@octostar/map-component 0.2.18 → 0.2.20

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 (32) hide show
  1. package/README.md +4 -1
  2. package/dist/index.cjs +807 -310
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.mjs +834 -336
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/styles.css +2 -0
  7. package/dist/types/components/layers-panel.d.ts +2 -2
  8. package/dist/types/components/layers-panel.d.ts.map +1 -1
  9. package/dist/types/components/map-editor-canvas.d.ts.map +1 -1
  10. package/dist/types/index.d.ts +4 -0
  11. package/dist/types/index.d.ts.map +1 -1
  12. package/dist/types/lib/feature-cap.d.ts +83 -0
  13. package/dist/types/lib/feature-cap.d.ts.map +1 -0
  14. package/dist/types/lib/geojson-serialize.d.ts +22 -8
  15. package/dist/types/lib/geojson-serialize.d.ts.map +1 -1
  16. package/dist/types/lib/ingest-pipeline.d.ts +12 -0
  17. package/dist/types/lib/ingest-pipeline.d.ts.map +1 -1
  18. package/dist/types/lib/ingest-progress.d.ts +5 -1
  19. package/dist/types/lib/ingest-progress.d.ts.map +1 -1
  20. package/dist/types/lib/layer-features.d.ts +25 -3
  21. package/dist/types/lib/layer-features.d.ts.map +1 -1
  22. package/dist/types/lib/map-editor-api.d.ts +40 -1
  23. package/dist/types/lib/map-editor-api.d.ts.map +1 -1
  24. package/dist/types/lib/temporal-ingest.d.ts +11 -1
  25. package/dist/types/lib/temporal-ingest.d.ts.map +1 -1
  26. package/dist/types/lib/trace-groups.d.ts +82 -0
  27. package/dist/types/lib/trace-groups.d.ts.map +1 -0
  28. package/dist/types/lib/trace-timeline.d.ts +75 -0
  29. package/dist/types/lib/trace-timeline.d.ts.map +1 -0
  30. package/dist/types/lib/yield-to-main.d.ts +2 -0
  31. package/dist/types/lib/yield-to-main.d.ts.map +1 -0
  32. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -3,6 +3,7 @@ import { useState, useEffect, useSyncExternalStore, useCallback, useMemo, create
3
3
  import maplibregl from "maplibre-gl";
4
4
  import MapboxDraw from "@mapbox/mapbox-gl-draw";
5
5
  import * as turf from "@turf/turf";
6
+ import { distance, point } from "@turf/turf";
6
7
  import * as THREE from "three";
7
8
  import proj4 from "proj4";
8
9
  import { Button, Modal, Input, App, message, Tooltip, Dropdown, Divider, Popover, Switch, Slider, Tag, Select, Segmented, Collapse, ColorPicker, Tabs, Card, Table, DatePicker } from "antd";
@@ -65,38 +66,85 @@ function hasAltitudeData(feature) {
65
66
  }
66
67
  return false;
67
68
  }
69
+ function yieldToMain() {
70
+ const scheduler = globalThis.scheduler;
71
+ if (typeof (scheduler == null ? void 0 : scheduler.yield) === "function") {
72
+ return scheduler.yield();
73
+ }
74
+ const channelCtor = globalThis.MessageChannel;
75
+ if (typeof channelCtor === "function") {
76
+ return new Promise((resolve) => {
77
+ const channel = new channelCtor();
78
+ channel.port1.onmessage = () => {
79
+ channel.port1.close();
80
+ resolve();
81
+ };
82
+ channel.port2.postMessage(void 0);
83
+ });
84
+ }
85
+ return new Promise((resolve) => setTimeout(resolve, 0));
86
+ }
68
87
  const PRETTY_EXPORT_MAX_FEATURES = 1e4;
69
88
  const TARGET_PART_CHARS = 8 * 1024 * 1024;
70
- function featureCollectionBlobParts(collection, options) {
71
- const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
72
- if (collection.features.length <= prettyMax) {
73
- return [JSON.stringify(collection, null, 2)];
74
- }
75
- const targetChars = TARGET_PART_CHARS;
76
- const { features, ...rest } = collection;
77
- const head = JSON.stringify(rest);
89
+ function createBlobPartCoalescer(targetChars) {
78
90
  const parts = [];
79
91
  let pending = [];
80
92
  let pendingChars = 0;
81
- const push = (piece) => {
82
- pending.push(piece);
83
- pendingChars += piece.length;
84
- if (pendingChars >= targetChars) {
85
- parts.push(pending.join(""));
86
- pending = [];
87
- pendingChars = 0;
93
+ return {
94
+ push(piece) {
95
+ pending.push(piece);
96
+ pendingChars += piece.length;
97
+ if (pendingChars >= targetChars) {
98
+ parts.push(pending.join(""));
99
+ pending = [];
100
+ pendingChars = 0;
101
+ }
102
+ },
103
+ finish() {
104
+ if (pending.length > 0) parts.push(pending.join(""));
105
+ return parts;
88
106
  }
89
107
  };
90
- push(head.slice(0, -1));
91
- push(head.length > 2 ? ',"features":[' : '"features":[');
108
+ }
109
+ function pushCollectionHead(coalescer, rest) {
110
+ const head = JSON.stringify(rest);
111
+ coalescer.push(head.slice(0, -1));
112
+ coalescer.push(head.length > 2 ? ',"features":[' : '"features":[');
113
+ }
114
+ function serializeFeatureAt(feature, index) {
115
+ return index === 0 ? JSON.stringify(feature) : "," + JSON.stringify(feature);
116
+ }
117
+ const DEFAULT_SLICE_BUDGET_MS = 12;
118
+ async function featureCollectionBlobPartsAsync(collection, options) {
119
+ var _a, _b, _c;
120
+ const prettyMax = (options == null ? void 0 : options.prettyMaxFeatures) ?? PRETTY_EXPORT_MAX_FEATURES;
121
+ const mapFeature = options == null ? void 0 : options.mapFeature;
122
+ const total = collection.features.length;
123
+ if (total <= prettyMax) {
124
+ const mapped = mapFeature ? { ...collection, features: collection.features.map(mapFeature) } : collection;
125
+ (_a = options == null ? void 0 : options.onProgress) == null ? void 0 : _a.call(options, total, total);
126
+ return [JSON.stringify(mapped, null, 2)];
127
+ }
128
+ const { features, ...rest } = collection;
129
+ const coalescer = createBlobPartCoalescer((options == null ? void 0 : options.targetPartChars) ?? TARGET_PART_CHARS);
130
+ const yieldFn = (options == null ? void 0 : options.yieldFn) ?? yieldToMain;
131
+ const budget = (options == null ? void 0 : options.sliceBudgetMs) ?? DEFAULT_SLICE_BUDGET_MS;
132
+ pushCollectionHead(coalescer, rest);
133
+ let sliceStart = performance.now();
92
134
  for (let i = 0; i < features.length; i++) {
93
- push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
135
+ const feature = mapFeature ? mapFeature(features[i], i) : features[i];
136
+ coalescer.push(serializeFeatureAt(feature, i));
137
+ if (performance.now() - sliceStart >= budget) {
138
+ (_b = options == null ? void 0 : options.onProgress) == null ? void 0 : _b.call(options, i + 1, total);
139
+ await yieldFn();
140
+ sliceStart = performance.now();
141
+ }
94
142
  }
95
- push("]}");
96
- if (pending.length > 0) parts.push(pending.join(""));
97
- return parts;
143
+ coalescer.push("]}");
144
+ (_c = options == null ? void 0 : options.onProgress) == null ? void 0 : _c.call(options, total, total);
145
+ return coalescer.finish();
98
146
  }
99
- 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';
147
+ const ingestWorkerSource = '"use strict";(()=>{function b(e,t){let n=e.length,r=Math.max(0,t.max-(t.existing??0));return n<=r?{features:e,dropped:0,sourceCount:n}:{features:e.slice(0,r),dropped:n-r,sourceCount:n}}function S(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=T(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 T(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 I(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 d(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 h(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 F(e){let t=d(e.startDate)||d(e.startdate)||d(e.start_date)||d(e.start_time)||d(e.date)||d(e.timestamp)||d(e.flightDate)||d(e.time)||d(e.datetime),n=d(e.endDate)||d(e.enddate)||d(e.end_date)||d(e.end_time);return t&&n&&n<t&&([t,n]=[n,t]),{startDate:t,endDate:n}}function x(e){return"kind"in e&&e.kind==="ack"}function G(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function _(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):G()}}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 D(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 O(e,t){let n;if(e.type==="text")try{n=JSON.parse(e.text)}catch(c){return{kind:"error",code:"parse-error",message:c instanceof Error?c.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}=S(n),a=b(n.features,{max:t.maxFeatures??1/0}),o=!1,u=!1,i=[];a.features.forEach((c,E)=>{let p=_(c,E,t);!u&&I(c)&&(u=!0);let f=c.properties||{};if(!h(f)){i.push(t.idStrategy==="preserve"?c:{...c,id:p});return}let{startDate:y,endDate:k}=F(f);(y||k)&&(o=!0),i.push({...c,...p!==void 0&&{id:p},properties:{...f,startDate:y?.toISOString()||null,endDate:k?.toISOString()||null}})});let m=n.properties?.layerMetadata;return{kind:"features",features:i,featureCount:i.length,bbox:D(i),hasTemporal:o,hasAltitude:u,reprojected:!1,sourceCRS:r,...s&&{needsReprojection:s},...m&&{layerMetadata:m},...a.dropped>0&&{truncated:{droppedCount:a.dropped,sourceFeatureCount:a.sourceCount,maxFeatures:t.maxFeatures}}}}var N=5e3;function M(e,t){let n=Number.isNaN(t)?N: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 g(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(!g(e[t]))return!1;return!0}for(let t in e)if(!g(e[t]))return!1;return!0}function P(e){for(let t=0;t<e.length;t++)if(!g(e[t]))return e;try{return JSON.stringify(e)}catch{return e}}function J(e){let{kind:t,features:n,...r}=e;return r}async function w(e,t,n,r){let s;try{s=O(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??P,o=M(s.features,r.chunkSize??N);r.post({kind:"head",id:e,summary:J(s)});let u=o.length>0?a(o[0]):null;for(let i=0;i<o.length;i++){let m=r.waitAck(i);r.post({kind:"chunk",id:e,seq:i,payload:u}),u=i+1<o.length?a(o[i+1]):null,await m}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 A=e=>self.postMessage(e),l=new Map;self.onmessage=async e=>{let t=e.data;if(x(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 w(n,o,s,{post:A,waitAck:u=>new Promise(i=>{l.set(`${n}:${u}`,i)}),...a?.chunkSize!==void 0&&{chunkSize:a.chunkSize},...a?.featureArrayChunks&&{encode:u=>u}})}catch(o){A({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';
100
148
  proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
101
149
  proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
102
150
  proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
@@ -137,6 +185,73 @@ function reprojectGeometry(geometry, fromCRS) {
137
185
  coordinates: reprojectCoords(geomWithCoords.coordinates)
138
186
  };
139
187
  }
188
+ const DEFAULT_MAX_FEATURES_PER_LAYER = 2e5;
189
+ function resolveFeatureCap(value) {
190
+ if (value === void 0) return DEFAULT_MAX_FEATURES_PER_LAYER;
191
+ if (value === Infinity) return Infinity;
192
+ if (!Number.isFinite(value) || value < 1) {
193
+ console.warn(
194
+ `[map-editor] Ignoring maxFeaturesPerLayer=${String(value)} — expected a number >= 1 or Infinity. Falling back to ${DEFAULT_MAX_FEATURES_PER_LAYER}.`
195
+ );
196
+ return DEFAULT_MAX_FEATURES_PER_LAYER;
197
+ }
198
+ return Math.floor(value);
199
+ }
200
+ function capFeatures(features, options) {
201
+ const sourceCount = features.length;
202
+ const room = Math.max(0, options.max - (options.existing ?? 0));
203
+ if (sourceCount <= room) {
204
+ return { features, dropped: 0, sourceCount };
205
+ }
206
+ return {
207
+ features: features.slice(0, room),
208
+ dropped: sourceCount - room,
209
+ sourceCount
210
+ };
211
+ }
212
+ function truncationToCapInfo(truncation, rest) {
213
+ return {
214
+ ...rest,
215
+ dropped: truncation.droppedCount,
216
+ sourceCount: truncation.sourceFeatureCount,
217
+ max: truncation.maxFeatures
218
+ };
219
+ }
220
+ function formatCount(value) {
221
+ return value.toLocaleString("en-US");
222
+ }
223
+ function formatFeatureCapToast(info) {
224
+ const isRestore = info.source === "restore";
225
+ const variant = isRestore ? "destructive" : "default";
226
+ const withNote = (text) => isRestore ? `${text} Re-saving this map will persist only the loaded features.` : text;
227
+ const layerCount = info.layerCount ?? 1;
228
+ if (layerCount > 1) {
229
+ return {
230
+ title: "Feature limit reached",
231
+ description: withNote(
232
+ `${formatCount(layerCount)} layers were larger than the ${formatCount(info.max)}-feature limit; ${formatCount(info.dropped)} features in total were not loaded.`
233
+ ),
234
+ variant
235
+ };
236
+ }
237
+ const existing = info.existing ?? 0;
238
+ if (existing > 0) {
239
+ return {
240
+ title: "Feature limit reached",
241
+ description: withNote(
242
+ `"${info.layerName}" already held ${formatCount(existing)} of its ${formatCount(info.max)}-feature limit, so only ${formatCount(info.kept)} more were added; ${formatCount(info.dropped)} were skipped.`
243
+ ),
244
+ variant
245
+ };
246
+ }
247
+ return {
248
+ title: "Feature limit reached",
249
+ description: withNote(
250
+ `Only the first ${formatCount(info.kept)} of ${formatCount(info.sourceCount)} features were added to "${info.layerName}"; ${formatCount(info.dropped)} were skipped (per-layer limit).`
251
+ ),
252
+ variant
253
+ };
254
+ }
140
255
  function parseDate(value) {
141
256
  if (!value) return null;
142
257
  if (value instanceof Date) return value;
@@ -230,10 +345,11 @@ function runIngestPipeline(source, options) {
230
345
  return { kind: "enriched", data };
231
346
  }
232
347
  const { sourceCRS, needsReprojection } = detectSourceCRS(data);
348
+ const capped = capFeatures(data.features, { max: options.maxFeatures ?? Infinity });
233
349
  let hasTemporal = false;
234
350
  let hasAltitude = false;
235
351
  const features = [];
236
- data.features.forEach((f, index) => {
352
+ capped.features.forEach((f, index) => {
237
353
  const id = assignId(f, index, options);
238
354
  if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
239
355
  const props = f.properties || {};
@@ -268,7 +384,14 @@ function runIngestPipeline(source, options) {
268
384
  reprojected: false,
269
385
  sourceCRS,
270
386
  ...needsReprojection && { needsReprojection },
271
- ...layerMetadata && { layerMetadata }
387
+ ...layerMetadata && { layerMetadata },
388
+ ...capped.dropped > 0 && {
389
+ truncated: {
390
+ droppedCount: capped.dropped,
391
+ sourceFeatureCount: capped.sourceCount,
392
+ maxFeatures: options.maxFeatures
393
+ }
394
+ }
272
395
  };
273
396
  }
274
397
  function decodeChunkPayload(payload) {
@@ -588,9 +711,9 @@ function createIngestProgressStore() {
588
711
  listeners.forEach((listener) => listener());
589
712
  };
590
713
  return {
591
- begin(label) {
714
+ begin(label, options) {
592
715
  const id = nextId++;
593
- entries.set(id, { label, received: 0, total: null });
716
+ entries.set(id, { label, received: 0, total: null, ...(options == null ? void 0 : options.verb) && { verb: options.verb } });
594
717
  notify();
595
718
  return {
596
719
  setTotal(total) {
@@ -686,7 +809,8 @@ function IngestProgressOverlay({
686
809
  className: "rounded-md border bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-md",
687
810
  children: [
688
811
  /* @__PURE__ */ jsxs("span", { children: [
689
- "Importing ",
812
+ entry.verb ?? "Importing",
813
+ " ",
690
814
  entry.label,
691
815
  "…",
692
816
  entry.total !== null ? ` ${entry.received.toLocaleString()} / ${entry.total.toLocaleString()} features` : ""
@@ -1085,15 +1209,28 @@ function collectLayerFeatures(layer, sources) {
1085
1209
  if (readOnly) pushAll(features, readOnly);
1086
1210
  return features;
1087
1211
  }
1088
- function stripInternalProperties(features, keep) {
1089
- return features.map((f) => ({
1090
- ...f,
1212
+ function countLayerFeatures(layer, stores) {
1213
+ var _a;
1214
+ if (layer.readOnly) return ((_a = stores.readOnlyFeatures.get(layer.id)) == null ? void 0 : _a.length) ?? 0;
1215
+ const hidden = stores.hiddenFeatures.get(layer.id);
1216
+ if (!hidden || hidden.length === 0) return layer.featureIds.length;
1217
+ if (layer.featureIds.length === 0) return hidden.length;
1218
+ const ids = new Set(layer.featureIds);
1219
+ let count = layer.featureIds.length;
1220
+ for (const feature of hidden) {
1221
+ if (!ids.has(String(feature.id))) count++;
1222
+ }
1223
+ return count;
1224
+ }
1225
+ function stripInternalPropertiesFromFeature(feature, keep) {
1226
+ return {
1227
+ ...feature,
1091
1228
  properties: Object.fromEntries(
1092
- Object.entries(f.properties ?? {}).filter(
1229
+ Object.entries(feature.properties ?? {}).filter(
1093
1230
  ([key]) => !key.startsWith("_") || ((keep == null ? void 0 : keep.has(key)) ?? false)
1094
1231
  )
1095
1232
  )
1096
- }));
1233
+ };
1097
1234
  }
1098
1235
  const ToastContext = createContext(null);
1099
1236
  function useToast() {
@@ -2815,7 +2952,9 @@ function LayersPanel({
2815
2952
  key: "save-desktop",
2816
2953
  icon: /* @__PURE__ */ jsx(Download, { className: "w-[18px] h-[18px]" }),
2817
2954
  label: "Save GeoJSON to desktop",
2818
- onClick: () => onSaveLayerGeoJSON(layer.id)
2955
+ onClick: () => {
2956
+ void onSaveLayerGeoJSON(layer.id);
2957
+ }
2819
2958
  },
2820
2959
  ...onUpdateVisualConfig ? [
2821
2960
  { type: "divider" },
@@ -3496,7 +3635,9 @@ function LayersPanel({
3496
3635
  key: "save-geojson",
3497
3636
  icon: /* @__PURE__ */ jsx(Download, { className: "w-4 h-4" }),
3498
3637
  label: "Download Map",
3499
- onClick: onSaveAllGeoJSON
3638
+ onClick: () => {
3639
+ void onSaveAllGeoJSON();
3640
+ }
3500
3641
  },
3501
3642
  ...onWorkspaceSave ? [{
3502
3643
  key: "save-workspace",
@@ -6410,25 +6551,25 @@ function createSelectionPaintCache() {
6410
6551
  updatable: true
6411
6552
  };
6412
6553
  }
6413
- function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6414
- if (cache.presentIds.has(featureId)) {
6415
- cache.updatable = false;
6554
+ function recordPaintedFeature(cache2, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6555
+ if (cache2.presentIds.has(featureId)) {
6556
+ cache2.updatable = false;
6416
6557
  } else {
6417
- cache.presentIds.add(featureId);
6558
+ cache2.presentIds.add(featureId);
6418
6559
  }
6419
- cache.basePriorityById.set(featureId, basePriority);
6420
- if (isSelected) cache.appliedSelectedIds.add(featureId);
6560
+ cache2.basePriorityById.set(featureId, basePriority);
6561
+ if (isSelected) cache2.appliedSelectedIds.add(featureId);
6421
6562
  if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
6422
- cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6563
+ cache2.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6423
6564
  }
6424
6565
  if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
6425
- cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6566
+ cache2.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6426
6567
  }
6427
- if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
6568
+ if (isTimelineHidden) cache2.appliedHiddenIds.add(featureId);
6428
6569
  }
6429
- function applySelectionFastPath(cache, nextSelectedIds, source) {
6430
- if (!cache || !cache.updatable || !source) return false;
6431
- const diff = buildSelectionDiff(cache, nextSelectedIds);
6570
+ function applySelectionFastPath(cache2, nextSelectedIds, source) {
6571
+ if (!cache2 || !cache2.updatable || !source) return false;
6572
+ const diff = buildSelectionDiff(cache2, nextSelectedIds);
6432
6573
  if (diff) {
6433
6574
  try {
6434
6575
  source.updateData(diff);
@@ -6438,29 +6579,29 @@ function applySelectionFastPath(cache, nextSelectedIds, source) {
6438
6579
  }
6439
6580
  const applied = /* @__PURE__ */ new Set();
6440
6581
  nextSelectedIds.forEach((id) => {
6441
- if (cache.presentIds.has(id)) applied.add(id);
6582
+ if (cache2.presentIds.has(id)) applied.add(id);
6442
6583
  });
6443
- cache.appliedSelectedIds = applied;
6584
+ cache2.appliedSelectedIds = applied;
6444
6585
  return true;
6445
6586
  }
6446
6587
  function needsDrawSelectionUpdate(input) {
6447
6588
  return input.editableSelectionCount > 0 || input.drawSelectedCount > 0 || input.currentMode !== input.targetMode;
6448
6589
  }
6449
- function buildSelectionDiff(cache, nextSelectedIds) {
6590
+ function buildSelectionDiff(cache2, nextSelectedIds) {
6450
6591
  const update = [];
6451
- cache.appliedSelectedIds.forEach((id) => {
6452
- if (!nextSelectedIds.has(id) && cache.presentIds.has(id)) {
6592
+ cache2.appliedSelectedIds.forEach((id) => {
6593
+ if (!nextSelectedIds.has(id) && cache2.presentIds.has(id)) {
6453
6594
  update.push({
6454
6595
  id,
6455
6596
  addOrUpdateProperties: [
6456
6597
  { key: "isSelected", value: 0 },
6457
- { key: "_labelPriority", value: cache.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6598
+ { key: "_labelPriority", value: cache2.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6458
6599
  ]
6459
6600
  });
6460
6601
  }
6461
6602
  });
6462
6603
  nextSelectedIds.forEach((id) => {
6463
- if (!cache.appliedSelectedIds.has(id) && cache.presentIds.has(id)) {
6604
+ if (!cache2.appliedSelectedIds.has(id) && cache2.presentIds.has(id)) {
6464
6605
  update.push({
6465
6606
  id,
6466
6607
  addOrUpdateProperties: [
@@ -6472,13 +6613,13 @@ function buildSelectionDiff(cache, nextSelectedIds) {
6472
6613
  });
6473
6614
  return update.length > 0 ? { update } : null;
6474
6615
  }
6475
- function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6616
+ function buildTimelineVisibilityDiff(cache2, nextVisibleSet) {
6476
6617
  const update = [];
6477
6618
  const nextHiddenIds = /* @__PURE__ */ new Set();
6478
- cache.presentIds.forEach((id) => {
6619
+ cache2.presentIds.forEach((id) => {
6479
6620
  const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
6480
6621
  if (nextHidden) nextHiddenIds.add(id);
6481
- if (nextHidden === cache.appliedHiddenIds.has(id)) return;
6622
+ if (nextHidden === cache2.appliedHiddenIds.has(id)) return;
6482
6623
  if (nextHidden) {
6483
6624
  update.push({
6484
6625
  id,
@@ -6492,8 +6633,8 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6492
6633
  update.push({
6493
6634
  id,
6494
6635
  addOrUpdateProperties: [
6495
- { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6496
- { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6636
+ { key: "stroke-opacity", value: cache2.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6637
+ { key: "fill-opacity", value: cache2.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6497
6638
  { key: "isTimelineHidden", value: 0 }
6498
6639
  ]
6499
6640
  });
@@ -6501,10 +6642,10 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6501
6642
  });
6502
6643
  return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6503
6644
  }
6504
- function applyTimelineFastPath(cache, nextVisibleSet, source) {
6645
+ function applyTimelineFastPath(cache2, nextVisibleSet, source) {
6505
6646
  var _a;
6506
- if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6507
- const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6647
+ if (!cache2 || !cache2.updatable || !source) return { applied: false, toggled: 0 };
6648
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache2, nextVisibleSet);
6508
6649
  if (diff) {
6509
6650
  try {
6510
6651
  source.updateData(diff);
@@ -6512,9 +6653,204 @@ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6512
6653
  return { applied: false, toggled: 0 };
6513
6654
  }
6514
6655
  }
6515
- cache.appliedHiddenIds = nextHiddenIds;
6656
+ cache2.appliedHiddenIds = nextHiddenIds;
6516
6657
  return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6517
6658
  }
6659
+ const TRACE_DEFAULT_COLOR = "#3b82f6";
6660
+ const TRACE_UNGROUPED_KEY = "__all__";
6661
+ const cache = /* @__PURE__ */ new WeakMap();
6662
+ function getTraceGroups(features, groupByField) {
6663
+ const field = groupByField || null;
6664
+ let byField = cache.get(features);
6665
+ if (!byField) {
6666
+ byField = /* @__PURE__ */ new Map();
6667
+ cache.set(features, byField);
6668
+ }
6669
+ const fieldKey = field ?? "";
6670
+ let groups = byField.get(fieldKey);
6671
+ if (!groups) {
6672
+ groups = buildTraceGroups(features, field);
6673
+ byField.set(fieldKey, groups);
6674
+ }
6675
+ return groups;
6676
+ }
6677
+ function sortKey(time) {
6678
+ return Number.isNaN(time) ? -Infinity : time;
6679
+ }
6680
+ function compareStaged(a, b) {
6681
+ const ka = sortKey(a.time);
6682
+ const kb = sortKey(b.time);
6683
+ if (ka < kb) return -1;
6684
+ if (ka > kb) return 1;
6685
+ return 0;
6686
+ }
6687
+ function buildTraceGroups(features, field) {
6688
+ var _a;
6689
+ const staged = /* @__PURE__ */ new Map();
6690
+ for (const feature of features) {
6691
+ if (feature.id == null || feature.geometry.type !== "Point" || !((_a = feature.properties) == null ? void 0 : _a.startDate)) continue;
6692
+ const raw = field ? feature.properties[field] : void 0;
6693
+ const key = field && raw ? String(raw) : TRACE_UNGROUPED_KEY;
6694
+ let bucket = staged.get(key);
6695
+ if (!bucket) {
6696
+ bucket = [];
6697
+ staged.set(key, bucket);
6698
+ }
6699
+ bucket.push({ feature, time: new Date(feature.properties.startDate).getTime() });
6700
+ }
6701
+ const count = staged.size;
6702
+ const groups = [];
6703
+ staged.forEach((bucket, key) => {
6704
+ bucket.sort(compareStaged);
6705
+ groups.push({
6706
+ key,
6707
+ points: bucket.map((p) => p.feature),
6708
+ ids: bucket.map((p) => String(p.feature.id)),
6709
+ times: bucket.map((p) => p.time),
6710
+ color: traceGroupColor(key, groups.length, count),
6711
+ label: field && key !== TRACE_UNGROUPED_KEY ? key : null,
6712
+ pairStats: /* @__PURE__ */ new Map()
6713
+ });
6714
+ });
6715
+ return groups;
6716
+ }
6717
+ function traceGroupColor(key, index, count) {
6718
+ if (key === TRACE_UNGROUPED_KEY) return TRACE_DEFAULT_COLOR;
6719
+ return `hsl(${index * 360 / count % 360}, 70%, 50%)`;
6720
+ }
6721
+ function visibleTraceIndices(group, isVisible) {
6722
+ const indices = [];
6723
+ for (let i = 0; i < group.ids.length; i++) {
6724
+ if (isVisible(group.ids[i])) indices.push(i);
6725
+ }
6726
+ return indices;
6727
+ }
6728
+ function timelineVisibility(visibleSet) {
6729
+ return visibleSet === null ? () => true : (id) => visibleSet.has(id);
6730
+ }
6731
+ function traceSegmentStats(group, fromIndex, toIndex) {
6732
+ const key = `${fromIndex}:${toIndex}`;
6733
+ const cached = group.pairStats.get(key);
6734
+ if (cached) return cached;
6735
+ const from = group.points[fromIndex].geometry;
6736
+ const to = group.points[toIndex].geometry;
6737
+ const distanceKm = distance(point(from.coordinates), point(to.coordinates), { units: "kilometers" });
6738
+ const durationMs = group.times[toIndex] - group.times[fromIndex];
6739
+ const durationHours = durationMs / (1e3 * 60 * 60);
6740
+ const avgSpeedKmh = durationHours > 0 ? distanceKm / durationHours : 0;
6741
+ const stats = {
6742
+ duration: formatDuration(durationMs),
6743
+ distance: distanceKm < 1 ? `${Math.round(distanceKm * 1e3)}m` : `${distanceKm.toFixed(2)}km`,
6744
+ avgSpeed: avgSpeedKmh < 1 ? `${(avgSpeedKmh * 1e3).toFixed(0)}m/h` : `${avgSpeedKmh.toFixed(1)}km/h`
6745
+ };
6746
+ group.pairStats.set(key, stats);
6747
+ return stats;
6748
+ }
6749
+ function formatDuration(durationMs) {
6750
+ if (durationMs < 6e4) return `${Math.round(durationMs / 1e3)}s`;
6751
+ if (durationMs < 36e5) return `${Math.round(durationMs / 6e4)}m`;
6752
+ if (durationMs < 864e5) {
6753
+ return `${Math.floor(durationMs / 36e5)}h ${Math.round(durationMs % 36e5 / 6e4)}m`;
6754
+ }
6755
+ return `${Math.floor(durationMs / 864e5)}d ${Math.round(durationMs % 864e5 / 36e5)}h`;
6756
+ }
6757
+ function traceSegmentId(groupIndex, fromIndex, toIndex) {
6758
+ return `${groupIndex}:${fromIndex}:${toIndex}`;
6759
+ }
6760
+ function traceSegmentFeature(group, groupIndex, fromIndex, toIndex) {
6761
+ var _a, _b;
6762
+ const from = group.points[fromIndex];
6763
+ const to = group.points[toIndex];
6764
+ return {
6765
+ type: "Feature",
6766
+ id: traceSegmentId(groupIndex, fromIndex, toIndex),
6767
+ properties: {
6768
+ group: group.key,
6769
+ color: group.color,
6770
+ ...traceSegmentStats(group, fromIndex, toIndex),
6771
+ fromName: ((_a = from.properties) == null ? void 0 : _a.name) || "",
6772
+ toName: ((_b = to.properties) == null ? void 0 : _b.name) || ""
6773
+ },
6774
+ geometry: {
6775
+ type: "LineString",
6776
+ coordinates: [from.geometry.coordinates, to.geometry.coordinates]
6777
+ }
6778
+ };
6779
+ }
6780
+ const TRACE_ENDPOINT_LABEL_PRIORITY = 5;
6781
+ const TRACE_POINT_RADIUS = 2;
6782
+ const TRACE_ENDPOINT_MIN_RADIUS = 8;
6783
+ function buildTraceTimelineDiff(trace, paint, nextVisibleSet) {
6784
+ const diff = { pointUpdates: [], segmentAdd: [], segmentRemove: [], basePriorities: [] };
6785
+ const paintedVisible = (id) => !paint.appliedHiddenIds.has(id);
6786
+ const nextVisible = timelineVisibility(nextVisibleSet);
6787
+ trace.groups.forEach((group, groupIndex) => {
6788
+ const prev = visibleTraceIndices(group, paintedVisible);
6789
+ const next = visibleTraceIndices(group, nextVisible);
6790
+ const prevEndpoint = prev.length > 0 ? prev[prev.length - 1] : -1;
6791
+ const nextEndpoint = next.length > 0 ? next[next.length - 1] : -1;
6792
+ if (prevEndpoint !== nextEndpoint) {
6793
+ if (prevEndpoint >= 0) pushEndpointUpdate(diff, trace, paint, group, group.ids[prevEndpoint], false);
6794
+ if (nextEndpoint >= 0) pushEndpointUpdate(diff, trace, paint, group, group.ids[nextEndpoint], true);
6795
+ }
6796
+ diffConsecutivePairs(
6797
+ prev,
6798
+ next,
6799
+ (from, to) => diff.segmentRemove.push(traceSegmentId(groupIndex, from, to)),
6800
+ (from, to) => diff.segmentAdd.push(traceSegmentFeature(group, groupIndex, from, to))
6801
+ );
6802
+ });
6803
+ return diff;
6804
+ }
6805
+ function pushEndpointUpdate(diff, trace, paint, group, id, isEndpoint) {
6806
+ const point2 = trace.pointPaint.get(id);
6807
+ if (!point2) return;
6808
+ const labelled = isEndpoint && group.label !== null;
6809
+ const basePriority = labelled ? TRACE_ENDPOINT_LABEL_PRIORITY : point2.basePriority;
6810
+ diff.pointUpdates.push({
6811
+ id,
6812
+ addOrUpdateProperties: [
6813
+ { key: "pointRadius", value: isEndpoint ? point2.endpointRadius : TRACE_POINT_RADIUS },
6814
+ { key: "name", value: labelled ? group.label : point2.name },
6815
+ { key: "isTraceLabel", value: labelled },
6816
+ { key: "_labelPriority", value: paint.appliedSelectedIds.has(id) ? 0 : basePriority }
6817
+ ]
6818
+ });
6819
+ diff.basePriorities.push([id, basePriority]);
6820
+ }
6821
+ function diffConsecutivePairs(prev, next, onRemove, onAdd) {
6822
+ let i = 0;
6823
+ let j = 0;
6824
+ while (i < prev.length - 1 || j < next.length - 1) {
6825
+ const prevFrom = i < prev.length - 1 ? prev[i] : Infinity;
6826
+ const nextFrom = j < next.length - 1 ? next[j] : Infinity;
6827
+ const prevTo = prev[i + 1];
6828
+ const nextTo = next[j + 1];
6829
+ if (prevFrom === nextFrom && prevTo === nextTo) {
6830
+ i++;
6831
+ j++;
6832
+ } else if (prevFrom < nextFrom || prevFrom === nextFrom && prevTo < nextTo) {
6833
+ onRemove(prevFrom, prevTo);
6834
+ i++;
6835
+ } else {
6836
+ onAdd(nextFrom, nextTo);
6837
+ j++;
6838
+ }
6839
+ }
6840
+ }
6841
+ function applyTraceTimelineDiff(diff, paint, pointSource, segmentSource) {
6842
+ try {
6843
+ if (diff.pointUpdates.length > 0) pointSource.updateData({ update: diff.pointUpdates });
6844
+ if (diff.segmentAdd.length > 0 || diff.segmentRemove.length > 0) {
6845
+ segmentSource.updateData({ add: diff.segmentAdd, remove: diff.segmentRemove });
6846
+ }
6847
+ } catch (error) {
6848
+ console.error("Trace timeline fast path failed; falling back to the full sync:", error);
6849
+ return false;
6850
+ }
6851
+ diff.basePriorities.forEach(([id, priority]) => paint.basePriorityById.set(id, priority));
6852
+ return true;
6853
+ }
6518
6854
  function deepClone(value) {
6519
6855
  try {
6520
6856
  return structuredClone(value);
@@ -6567,17 +6903,19 @@ function geometryEquals(a, b) {
6567
6903
  b.coordinates
6568
6904
  );
6569
6905
  }
6570
- function prepareFeaturesForLayer(input, caller) {
6906
+ function prepareFeaturesForLayer(input, caller, cap) {
6571
6907
  const logging = mapPerfLogEnabled();
6572
6908
  const started = logging ? performance.now() : 0;
6573
- const count = input.length;
6909
+ const capped = cap ? capFeatures(input, cap) : null;
6910
+ const source = capped ? capped.features : input;
6911
+ const count = source.length;
6574
6912
  const features = new Array(count);
6575
6913
  const featureIds = new Array(count);
6576
6914
  let hasTemporal = false;
6577
6915
  let temporalCount = 0;
6578
6916
  let reused = 0;
6579
6917
  for (let i = 0; i < count; i++) {
6580
- const f = input[i];
6918
+ const f = source[i];
6581
6919
  const props = f.properties || {};
6582
6920
  if (!hasAnyTemporalValue(props)) {
6583
6921
  if (typeof f.id === "string" && f.id) {
@@ -6612,10 +6950,17 @@ function prepareFeaturesForLayer(input, caller) {
6612
6950
  withTemporalKeys: temporalCount,
6613
6951
  hasTemporal,
6614
6952
  reused,
6615
- copied: count - reused
6953
+ copied: count - reused,
6954
+ ...capped && capped.dropped > 0 && { dropped: capped.dropped }
6616
6955
  });
6617
6956
  }
6618
- return { features, featureIds, hasTemporal };
6957
+ return {
6958
+ features,
6959
+ featureIds,
6960
+ hasTemporal,
6961
+ dropped: (capped == null ? void 0 : capped.dropped) ?? 0,
6962
+ sourceCount: (capped == null ? void 0 : capped.sourceCount) ?? count
6963
+ };
6619
6964
  }
6620
6965
  function scanTemporalFeatures(features, resolveLayerId, out) {
6621
6966
  let foundTemporal = false;
@@ -7546,6 +7891,7 @@ function extract3DFlightPaths(features) {
7546
7891
  });
7547
7892
  return paths;
7548
7893
  }
7894
+ const CAP_NOTICE_INTERVAL_MS = 5e3;
7549
7895
  const DEFAULT_LOCAL_GLYPHS_URL = "/fonts/{fontstack}/{range}.pbf";
7550
7896
  function basemapInsertAnchor(map) {
7551
7897
  if (map.getLayer("satellite-layer")) return "satellite-layer";
@@ -7669,6 +8015,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7669
8015
  enableProperties = true,
7670
8016
  autoOpenProperties = true,
7671
8017
  toastProvider,
8018
+ maxFeaturesPerLayer,
8019
+ onFeaturesTruncated,
7672
8020
  customGlobalMenuItems,
7673
8021
  extraLayerToolbarButtons,
7674
8022
  extraNewLayerButtons,
@@ -7776,6 +8124,31 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7776
8124
  const timelineStore = useStore(timelineStoreApi);
7777
8125
  const { toast: internalToast } = useToast();
7778
8126
  const toast = toastProvider ?? internalToast;
8127
+ const featureCap = useMemo(() => resolveFeatureCap(maxFeaturesPerLayer), [maxFeaturesPerLayer]);
8128
+ const featureCapRef = useRef(featureCap);
8129
+ featureCapRef.current = featureCap;
8130
+ const capNoticeRef = useRef(/* @__PURE__ */ new Map());
8131
+ const notifyFeatureCap = useCallback((info) => {
8132
+ if (onFeaturesTruncated) {
8133
+ onFeaturesTruncated(info);
8134
+ return;
8135
+ }
8136
+ if (info.source !== "restore") {
8137
+ const key = info.layerId ?? info.layerName;
8138
+ const now = Date.now();
8139
+ const last = capNoticeRef.current.get(key);
8140
+ if (last != null && now - last < CAP_NOTICE_INTERVAL_MS) return;
8141
+ capNoticeRef.current.set(key, now);
8142
+ }
8143
+ toast(formatFeatureCapToast(info));
8144
+ }, [onFeaturesTruncated, toast]);
8145
+ const countExisting = useCallback(
8146
+ (layer) => countLayerFeatures(layer, {
8147
+ hiddenFeatures: hiddenFeatures.current,
8148
+ readOnlyFeatures: readOnlyFeatures.current
8149
+ }),
8150
+ []
8151
+ );
7779
8152
  useEffect(() => {
7780
8153
  const handleError = (event) => {
7781
8154
  const msg = event.message || "";
@@ -7852,6 +8225,16 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7852
8225
  });
7853
8226
  return [...drawFeatures, ...readOnly];
7854
8227
  }, []);
8228
+ const traceSourceFeatures = useCallback((layer, featureById) => {
8229
+ const readOnly = readOnlyFeatures.current.get(layer.id);
8230
+ if (readOnly) return readOnly;
8231
+ const features = [];
8232
+ layer.featureIds.forEach((id) => {
8233
+ const f = featureById.get(id);
8234
+ if (f) features.push(f);
8235
+ });
8236
+ return features;
8237
+ }, []);
7855
8238
  const getSelectedFeatures = useCallback(() => {
7856
8239
  const drawSelected = draw.current ? draw.current.getSelected().features : [];
7857
8240
  const readOnlySelected = [];
@@ -8036,29 +8419,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8036
8419
  layers.forEach((layer) => {
8037
8420
  var _a;
8038
8421
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8039
- const layerFeatures = [];
8040
- layer.featureIds.forEach((id) => {
8041
- var _a2;
8042
- const f = featById.get(id);
8043
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8044
- layerFeatures.push(f);
8045
- });
8046
- if (layerFeatures.length < 1) return;
8047
- const groupByField = layer.traceConfig.groupByField;
8048
- const groups = /* @__PURE__ */ new Map();
8049
- layerFeatures.forEach((f) => {
8050
- var _a2;
8051
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8052
- if (!groups.has(key)) groups.set(key, []);
8053
- groups.get(key).push(f);
8054
- });
8055
- const groupKeys = Array.from(groups.keys());
8056
- groupKeys.forEach((key, index) => {
8057
- const color = key === "__all__" ? "#3b82f6" : `hsl(${index * 360 / groupKeys.length % 360}, 70%, 50%)`;
8058
- groups.get(key).forEach((f) => {
8059
- if (f.id) tracePointColors.set(String(f.id), color);
8060
- });
8061
- });
8422
+ for (const group of getTraceGroups(traceSourceFeatures(layer, featById), layer.traceConfig.groupByField)) {
8423
+ for (const id of group.ids) tracePointColors.set(id, group.color);
8424
+ }
8062
8425
  });
8063
8426
  const layerGradientRanges = /* @__PURE__ */ new Map();
8064
8427
  selectedFeatureIds.forEach((fid) => {
@@ -8092,7 +8455,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8092
8455
  colorMap.set(fid, color);
8093
8456
  });
8094
8457
  return colorMap;
8095
- }, [selectedFeatureIds, layers, getAllFeatures]);
8458
+ }, [selectedFeatureIds, layers, getAllFeatures, traceSourceFeatures]);
8096
8459
  const countVisibleFeatures = useCallback((threshold) => {
8097
8460
  const m = map.current;
8098
8461
  if (!m) return 0;
@@ -8111,6 +8474,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8111
8474
  }, []);
8112
8475
  const isSyncingRef = useRef(false);
8113
8476
  const selectionPaintCacheRef = useRef(null);
8477
+ const tracePaintCacheRef = useRef(null);
8114
8478
  const paintedArrowLinesRef = useRef([]);
8115
8479
  const renderArrowOverlays = useCallback((arrowLines) => {
8116
8480
  const mapInstance = map.current;
@@ -8280,60 +8644,29 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8280
8644
  const tracePointColors = /* @__PURE__ */ new Map();
8281
8645
  const lastTracePointLabels = /* @__PURE__ */ new Map();
8282
8646
  const tracePointIds = /* @__PURE__ */ new Set();
8647
+ const paintedTraceGroups = [];
8648
+ const traceSegments = [];
8649
+ const tracePointPaint = /* @__PURE__ */ new Map();
8650
+ const isTimelineVisibleId = timelineVisibility(visibleSet);
8283
8651
  currentLayers.forEach((layer) => {
8284
8652
  var _a;
8285
8653
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8286
- const layerFeatures = [];
8287
- layer.featureIds.forEach((id) => {
8288
- var _a2;
8289
- const f = featureById.get(id);
8290
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8291
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8292
- layerFeatures.push(f);
8293
- });
8294
- if (layerFeatures.length < 1) return;
8295
- const groupByField = layer.traceConfig.groupByField;
8296
- const groups = /* @__PURE__ */ new Map();
8297
- layerFeatures.forEach((f) => {
8298
- var _a2;
8299
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8300
- if (!groups.has(key)) groups.set(key, []);
8301
- groups.get(key).push(f);
8302
- });
8303
- const groupKeys = Array.from(groups.keys());
8304
- const groupColors = /* @__PURE__ */ new Map();
8305
- groupKeys.forEach((key, index) => {
8306
- if (key === "__all__") {
8307
- groupColors.set(key, "#3b82f6");
8308
- } else {
8309
- const hue = index * 360 / groupKeys.length % 360;
8310
- groupColors.set(key, `hsl(${hue}, 70%, 50%)`);
8654
+ const groups = getTraceGroups(traceSourceFeatures(layer, featureById), layer.traceConfig.groupByField);
8655
+ for (const group of groups) {
8656
+ const groupIndex = paintedTraceGroups.push(group) - 1;
8657
+ for (const id of group.ids) {
8658
+ tracePointIds.add(id);
8659
+ tracePointColors.set(id, group.color);
8660
+ }
8661
+ const visible = visibleTraceIndices(group, isTimelineVisibleId);
8662
+ if (visible.length === 0) continue;
8663
+ const endpointId = group.ids[visible[visible.length - 1]];
8664
+ lastTracePointIds.add(endpointId);
8665
+ if (group.label !== null) lastTracePointLabels.set(endpointId, group.label);
8666
+ for (let k = 1; k < visible.length; k++) {
8667
+ traceSegments.push(traceSegmentFeature(group, groupIndex, visible[k - 1], visible[k]));
8311
8668
  }
8312
- });
8313
- groups.forEach((groupFeatures, groupKey) => {
8314
- const sorted = [...groupFeatures].sort((a, b) => {
8315
- var _a2, _b;
8316
- const dateA = new Date(((_a2 = a.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8317
- const dateB = new Date(((_b = b.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8318
- return dateA - dateB;
8319
- });
8320
- if (sorted.length > 0) {
8321
- const groupColor = groupColors.get(groupKey) || "#3b82f6";
8322
- sorted.forEach((point) => {
8323
- if (point.id) {
8324
- tracePointIds.add(String(point.id));
8325
- tracePointColors.set(String(point.id), groupColor);
8326
- }
8327
- });
8328
- const lastPoint = sorted[sorted.length - 1];
8329
- if (lastPoint.id) {
8330
- lastTracePointIds.add(String(lastPoint.id));
8331
- if (groupByField && groupKey !== "__all__") {
8332
- lastTracePointLabels.set(String(lastPoint.id), groupKey);
8333
- }
8334
- }
8335
- }
8336
- });
8669
+ }
8337
8670
  });
8338
8671
  const paintCache = createSelectionPaintCache();
8339
8672
  const sourceData = {
@@ -8378,13 +8711,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8378
8711
  const isTracePoint = tracePointIds.has(featureId);
8379
8712
  const isLastTracePoint = lastTracePointIds.has(featureId);
8380
8713
  const traceLabel = lastTracePointLabels.get(featureId);
8714
+ let traceEndpointRadius = null;
8381
8715
  if (isTracePoint && f.geometry.type === "Point") {
8382
8716
  strokeColor = tracePointColors.get(featureId) || strokeColor;
8383
- if (isLastTracePoint) {
8384
- pointRadius = Math.max(pointRadius, 8);
8385
- } else {
8386
- pointRadius = 2;
8387
- }
8717
+ traceEndpointRadius = Math.max(pointRadius, TRACE_ENDPOINT_MIN_RADIUS);
8718
+ pointRadius = isLastTracePoint ? traceEndpointRadius : TRACE_POINT_RADIUS;
8388
8719
  }
8389
8720
  let labelText = ((_d = f.properties) == null ? void 0 : _d.name) || "";
8390
8721
  const labelConfig = visualConfig == null ? void 0 : visualConfig.label;
@@ -8398,6 +8729,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8398
8729
  labelText = fieldValue !== void 0 && fieldValue !== null ? String(fieldValue) : "";
8399
8730
  }
8400
8731
  }
8732
+ const nonTraceLabelText = labelText;
8401
8733
  if (traceLabel) {
8402
8734
  labelText = traceLabel;
8403
8735
  }
@@ -8429,11 +8761,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8429
8761
  });
8430
8762
  }
8431
8763
  const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIdSet.has(featureId) ? 1 : 0;
8432
- let basePriority = DEFAULT_LABEL_PRIORITY;
8433
- if (traceLabel) {
8434
- basePriority = 5;
8435
- } else if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
8436
- basePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
8764
+ let nonTracePriority = DEFAULT_LABEL_PRIORITY;
8765
+ if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
8766
+ nonTracePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
8437
8767
  } else {
8438
8768
  const idStr = String(featureId);
8439
8769
  let h = 0;
@@ -8441,9 +8771,13 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8441
8771
  h = (h << 5) - h + idStr.charCodeAt(i);
8442
8772
  h |= 0;
8443
8773
  }
8444
- basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8774
+ nonTracePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8445
8775
  }
8776
+ const basePriority = traceLabel ? TRACE_ENDPOINT_LABEL_PRIORITY : nonTracePriority;
8446
8777
  const labelPriority = isFeatureSelected ? 0 : basePriority;
8778
+ if (traceEndpointRadius !== null) {
8779
+ tracePointPaint.set(featureId, { name: nonTraceLabelText, endpointRadius: traceEndpointRadius, basePriority: nonTracePriority });
8780
+ }
8447
8781
  const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
8448
8782
  const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
8449
8783
  recordPaintedFeature(
@@ -8490,93 +8824,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8490
8824
  source.setData(sourceData);
8491
8825
  selectionPaintCacheRef.current = paintCache;
8492
8826
  const traceSource = map.current.getSource("trace-features");
8493
- if (traceSource) {
8494
- const traceSegments = [];
8495
- currentLayers.forEach((layer) => {
8496
- var _a;
8497
- if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8498
- const layerFeatures = [];
8499
- layer.featureIds.forEach((id) => {
8500
- var _a2;
8501
- const f = featureById.get(id);
8502
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8503
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8504
- layerFeatures.push(f);
8505
- });
8506
- if (layerFeatures.length < 2) return;
8507
- const groupByField = layer.traceConfig.groupByField;
8508
- const groups = /* @__PURE__ */ new Map();
8509
- layerFeatures.forEach((f) => {
8510
- var _a2;
8511
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8512
- if (!groups.has(key)) groups.set(key, []);
8513
- groups.get(key).push(f);
8514
- });
8515
- const groupKeys = Array.from(groups.keys());
8516
- const groupColors = /* @__PURE__ */ new Map();
8517
- groupKeys.forEach((key, index) => {
8518
- if (key === "__all__") {
8519
- groupColors.set(key, "#3b82f6");
8520
- } else {
8521
- const hue = index * 360 / groupKeys.length % 360;
8522
- groupColors.set(key, `hsl(${hue}, 70%, 50%)`);
8523
- }
8524
- });
8525
- groups.forEach((groupFeatures, groupKey) => {
8526
- var _a2, _b, _c, _d;
8527
- const sorted = [...groupFeatures].sort((a, b) => {
8528
- var _a3, _b2;
8529
- const dateA = new Date(((_a3 = a.properties) == null ? void 0 : _a3.startDate) || 0).getTime();
8530
- const dateB = new Date(((_b2 = b.properties) == null ? void 0 : _b2.startDate) || 0).getTime();
8531
- return dateA - dateB;
8532
- });
8533
- if (sorted.length < 2) return;
8534
- for (let i = 0; i < sorted.length - 1; i++) {
8535
- const from = sorted[i];
8536
- const to = sorted[i + 1];
8537
- const fromCoords = from.geometry.coordinates;
8538
- const toCoords = to.geometry.coordinates;
8539
- const fromPoint = turf.point(fromCoords);
8540
- const toPoint = turf.point(toCoords);
8541
- const distanceKm = turf.distance(fromPoint, toPoint, { units: "kilometers" });
8542
- const fromTime = new Date(((_a2 = from.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8543
- const toTime = new Date(((_b = to.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8544
- const durationMs = toTime - fromTime;
8545
- const durationHours = durationMs / (1e3 * 60 * 60);
8546
- const avgSpeedKmh = durationHours > 0 ? distanceKm / durationHours : 0;
8547
- let durationStr = "";
8548
- if (durationMs < 6e4) {
8549
- durationStr = `${Math.round(durationMs / 1e3)}s`;
8550
- } else if (durationMs < 36e5) {
8551
- durationStr = `${Math.round(durationMs / 6e4)}m`;
8552
- } else if (durationMs < 864e5) {
8553
- durationStr = `${Math.floor(durationMs / 36e5)}h ${Math.round(durationMs % 36e5 / 6e4)}m`;
8554
- } else {
8555
- durationStr = `${Math.floor(durationMs / 864e5)}d ${Math.round(durationMs % 864e5 / 36e5)}h`;
8556
- }
8557
- const distanceStr = distanceKm < 1 ? `${Math.round(distanceKm * 1e3)}m` : `${distanceKm.toFixed(2)}km`;
8558
- const speedStr = avgSpeedKmh < 1 ? `${(avgSpeedKmh * 1e3).toFixed(0)}m/h` : `${avgSpeedKmh.toFixed(1)}km/h`;
8559
- traceSegments.push({
8560
- type: "Feature",
8561
- properties: {
8562
- group: groupKey,
8563
- color: groupColors.get(groupKey) || "#3b82f6",
8564
- duration: durationStr,
8565
- distance: distanceStr,
8566
- avgSpeed: speedStr,
8567
- fromName: ((_c = from.properties) == null ? void 0 : _c.name) || "",
8568
- toName: ((_d = to.properties) == null ? void 0 : _d.name) || ""
8569
- },
8570
- geometry: {
8571
- type: "LineString",
8572
- coordinates: [fromCoords, toCoords]
8573
- }
8574
- });
8575
- }
8576
- });
8577
- });
8578
- traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8579
- }
8827
+ if (traceSource) traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8828
+ tracePaintCacheRef.current = traceSource && paintedTraceGroups.length > 0 ? { groups: paintedTraceGroups, pointPaint: tracePointPaint } : null;
8580
8829
  {
8581
8830
  let sawArrowFeature = false;
8582
8831
  const arrowLines = [];
@@ -9399,11 +9648,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9399
9648
  let lastHoveredFeatureKey = null;
9400
9649
  const positionTooltip = () => {
9401
9650
  if (!tooltipLngLat || tooltipEl2.style.display === "none") return;
9402
- const point = mapInstance.project(tooltipLngLat);
9651
+ const point2 = mapInstance.project(tooltipLngLat);
9403
9652
  const container = mapInstance.getContainer();
9404
9653
  const rect = container.getBoundingClientRect();
9405
- const ax = rect.left + point.x;
9406
- const ay = rect.top + point.y;
9654
+ const ax = rect.left + point2.x;
9655
+ const ay = rect.top + point2.y;
9407
9656
  const vw = window.innerWidth;
9408
9657
  const vh = window.innerHeight;
9409
9658
  tooltipEl2.style.maxWidth = Math.min(480, vw - 24) + "px";
@@ -9724,7 +9973,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9724
9973
  if (e.features && e.features.length > 0) {
9725
9974
  const props = e.features[0].properties || {};
9726
9975
  const duration = props.duration || "";
9727
- const distance = props.distance || "";
9976
+ const distance2 = props.distance || "";
9728
9977
  const avgSpeed = props.avgSpeed || "";
9729
9978
  const group = props.group !== "__all__" ? props.group : null;
9730
9979
  const fromName = props.fromName || "";
@@ -9735,7 +9984,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9735
9984
  }
9736
9985
  html += '<div class="space-y-0.5">';
9737
9986
  html += `<div><span class="text-muted-foreground">Duration:</span> <span class="font-medium">${duration}</span></div>`;
9738
- html += `<div><span class="text-muted-foreground">Distance:</span> <span class="font-medium">${distance}</span></div>`;
9987
+ html += `<div><span class="text-muted-foreground">Distance:</span> <span class="font-medium">${distance2}</span></div>`;
9739
9988
  html += `<div><span class="text-muted-foreground">Avg Speed:</span> <span class="font-medium">${avgSpeed}</span></div>`;
9740
9989
  html += "</div>";
9741
9990
  if (group) {
@@ -10463,16 +10712,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10463
10712
  clusterConfig: options == null ? void 0 : options.clusterConfig,
10464
10713
  altitudeDisplayMode: options == null ? void 0 : options.altitudeDisplayMode
10465
10714
  };
10715
+ let addedFeatures = [];
10716
+ let capDropped = 0;
10466
10717
  if (geojson) {
10718
+ const max = featureCapRef.current;
10467
10719
  if (options == null ? void 0 : options.readOnly) {
10468
- const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
10720
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer", { max });
10469
10721
  readOnlyFeatures.current.set(layerId, prepared.features);
10470
10722
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10471
10723
  newLayer.featureIds = prepared.featureIds;
10724
+ addedFeatures = prepared.features;
10725
+ capDropped = prepared.dropped;
10472
10726
  } else if (draw.current) {
10727
+ const capped = capFeatures(geojson.features, { max });
10473
10728
  isApiAddingRef.current = true;
10474
10729
  try {
10475
- const addedIds = geojson.features.map((f) => {
10730
+ const addedIds = capped.features.map((f) => {
10476
10731
  const ids = draw.current.add(f);
10477
10732
  return ids[0];
10478
10733
  });
@@ -10480,8 +10735,21 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10480
10735
  } finally {
10481
10736
  isApiAddingRef.current = false;
10482
10737
  }
10738
+ addedFeatures = capped.features;
10739
+ capDropped = capped.dropped;
10483
10740
  }
10484
10741
  }
10742
+ if (capDropped > 0) {
10743
+ notifyFeatureCap({
10744
+ layerId,
10745
+ layerName: name,
10746
+ kept: addedFeatures.length,
10747
+ dropped: capDropped,
10748
+ sourceCount: (geojson == null ? void 0 : geojson.features.length) ?? 0,
10749
+ max: featureCapRef.current,
10750
+ source: "api"
10751
+ });
10752
+ }
10485
10753
  if (newLayer.visible === false && !(options == null ? void 0 : options.readOnly) && draw.current && newLayer.featureIds.length > 0) {
10486
10754
  const features = newLayer.featureIds.map((id) => draw.current.get(id)).filter(Boolean);
10487
10755
  hiddenFeatures.current.set(layerId, features);
@@ -10499,9 +10767,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10499
10767
  updateFeatureCount();
10500
10768
  scheduleTimelineUpdate();
10501
10769
  scheduleSync();
10502
- if (!(options == null ? void 0 : options.skipFit) && geojson && geojson.features.length > 0 && map.current) {
10770
+ if (!(options == null ? void 0 : options.skipFit) && addedFeatures.length > 0 && map.current) {
10503
10771
  try {
10504
- const bbox = turf.bbox(geojson);
10772
+ const bbox = turf.bbox({
10773
+ type: "FeatureCollection",
10774
+ features: addedFeatures
10775
+ });
10505
10776
  if (bbox.every((v) => isFinite(v))) {
10506
10777
  map.current.fitBounds(
10507
10778
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -10594,7 +10865,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10594
10865
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
10595
10866
  if (layer.readOnly) {
10596
10867
  const existing = readOnlyFeatures.current.get(layerId) || [];
10597
- const prepared = prepareFeaturesForLayer(features, "addFeatures");
10868
+ const prepared = prepareFeaturesForLayer(features, "addFeatures", {
10869
+ max: featureCapRef.current,
10870
+ existing: existing.length
10871
+ });
10872
+ if (prepared.dropped > 0) {
10873
+ notifyFeatureCap({
10874
+ layerId,
10875
+ layerName: layer.name,
10876
+ kept: prepared.features.length,
10877
+ dropped: prepared.dropped,
10878
+ sourceCount: prepared.sourceCount,
10879
+ max: featureCapRef.current,
10880
+ source: "api",
10881
+ existing: existing.length
10882
+ });
10883
+ }
10598
10884
  const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
10599
10885
  const combined = [...existing, ...prepared.features];
10600
10886
  readOnlyFeatures.current.set(layerId, combined);
@@ -10614,9 +10900,26 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10614
10900
  }
10615
10901
  if (!draw.current) return [];
10616
10902
  const addedIds = [];
10903
+ const existingInLayer = countExisting(layer);
10904
+ const cappedForDraw = capFeatures(features, {
10905
+ max: featureCapRef.current,
10906
+ existing: existingInLayer
10907
+ });
10908
+ if (cappedForDraw.dropped > 0) {
10909
+ notifyFeatureCap({
10910
+ layerId,
10911
+ layerName: layer.name,
10912
+ kept: cappedForDraw.features.length,
10913
+ dropped: cappedForDraw.dropped,
10914
+ sourceCount: cappedForDraw.sourceCount,
10915
+ max: featureCapRef.current,
10916
+ source: "api",
10917
+ existing: existingInLayer
10918
+ });
10919
+ }
10617
10920
  isApiAddingRef.current = true;
10618
10921
  try {
10619
- features.forEach((f) => {
10922
+ cappedForDraw.features.forEach((f) => {
10620
10923
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10621
10924
  const normalizedFeature = {
10622
10925
  ...f,
@@ -10725,12 +11028,29 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10725
11028
  return { type: "FeatureCollection", features: cleanedFeatures };
10726
11029
  },
10727
11030
  importGeoJSON: (layerId, geojson) => {
10728
- const layer = layers.find((l) => l.id === layerId);
11031
+ const layer = layersRef.current.find((l) => l.id === layerId);
10729
11032
  if (!layer || !draw.current || !isMapLoaded) return [];
10730
11033
  const addedIds = [];
11034
+ const existingInLayer = countExisting(layer);
11035
+ const capped = capFeatures(geojson.features, {
11036
+ max: featureCapRef.current,
11037
+ existing: existingInLayer
11038
+ });
11039
+ if (capped.dropped > 0) {
11040
+ notifyFeatureCap({
11041
+ layerId,
11042
+ layerName: layer.name,
11043
+ kept: capped.features.length,
11044
+ dropped: capped.dropped,
11045
+ sourceCount: capped.sourceCount,
11046
+ max: featureCapRef.current,
11047
+ source: "api",
11048
+ existing: existingInLayer
11049
+ });
11050
+ }
10731
11051
  isApiAddingRef.current = true;
10732
11052
  try {
10733
- geojson.features.forEach((f) => {
11053
+ capped.features.forEach((f) => {
10734
11054
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10735
11055
  const normalizedFeature = {
10736
11056
  ...f,
@@ -10834,9 +11154,20 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10834
11154
  updateReadOnlyLayer: (layerId, features) => {
10835
11155
  const layer = layersRef.current.find((l) => l.id === layerId);
10836
11156
  if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
10837
- const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
11157
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer", { max: featureCapRef.current });
11158
+ if (prepared.dropped > 0) {
11159
+ notifyFeatureCap({
11160
+ layerId,
11161
+ layerName: layer.name,
11162
+ kept: prepared.features.length,
11163
+ dropped: prepared.dropped,
11164
+ sourceCount: prepared.sourceCount,
11165
+ max: featureCapRef.current,
11166
+ source: "api"
11167
+ });
11168
+ }
10838
11169
  readOnlyFeatures.current.set(layerId, prepared.features);
10839
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
11170
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10840
11171
  if (prepared.hasTemporal) {
10841
11172
  scheduleTimelineUpdate();
10842
11173
  }
@@ -10852,9 +11183,20 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10852
11183
  },
10853
11184
  setLayerData: (name, geojson, options) => {
10854
11185
  if (!isMapLoadedRef.current) return "";
10855
- const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
11186
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData", { max: featureCapRef.current });
10856
11187
  const newFeatureIds = prepared.featureIds;
10857
11188
  const layerId = `managed-${name}`;
11189
+ if (prepared.dropped > 0) {
11190
+ notifyFeatureCap({
11191
+ layerId,
11192
+ layerName: name,
11193
+ kept: prepared.features.length,
11194
+ dropped: prepared.dropped,
11195
+ sourceCount: prepared.sourceCount,
11196
+ max: featureCapRef.current,
11197
+ source: "api"
11198
+ });
11199
+ }
10858
11200
  readOnlyFeatures.current.set(layerId, prepared.features);
10859
11201
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10860
11202
  const buildLayerObj = (existing) => {
@@ -10904,9 +11246,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10904
11246
  });
10905
11247
  updateFeatureCount();
10906
11248
  scheduleSync();
10907
- if ((options == null ? void 0 : options.fitPadding) != null && geojson.features.length > 0 && map.current) {
11249
+ if ((options == null ? void 0 : options.fitPadding) != null && prepared.features.length > 0 && map.current) {
10908
11250
  try {
10909
- const bbox = turf.bbox(geojson);
11251
+ const bbox = turf.bbox(
11252
+ prepared.dropped > 0 ? { type: "FeatureCollection", features: prepared.features } : geojson
11253
+ );
10910
11254
  if (bbox.every((v) => isFinite(v))) {
10911
11255
  map.current.fitBounds(
10912
11256
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -11288,8 +11632,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11288
11632
  }, 0);
11289
11633
  if (!map.current) return;
11290
11634
  const mapInstance = map.current;
11291
- const point = [e.offsetX, e.offsetY];
11292
- const clickedFeatures = mapInstance.queryRenderedFeatures(point, {
11635
+ const point2 = [e.offsetX, e.offsetY];
11636
+ const clickedFeatures = mapInstance.queryRenderedFeatures(point2, {
11293
11637
  layers: ["custom-point", "custom-line", "custom-polygon-fill"]
11294
11638
  });
11295
11639
  let features = [];
@@ -12481,23 +12825,26 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12481
12825
  const m = map.current;
12482
12826
  if (!m) return true;
12483
12827
  if (hasArrowFeaturesRef.current) return false;
12484
- if (layersRef.current.some((l) => {
12485
- var _a;
12486
- return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
12487
- })) return false;
12488
12828
  const source = m.getSource("custom-features");
12489
- const { applied, toggled } = applyTimelineFastPath(
12490
- selectionPaintCacheRef.current,
12491
- timelineVisibleIdsRef.current,
12492
- source
12493
- );
12494
- if (applied) {
12495
- const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
12496
- setVisibleFeatureCount(countVisibleFeatures(threshold));
12497
- setLabelsSuppressed(false);
12498
- mapPerfLog("timeline", "fast path applied", { toggled });
12499
- }
12500
- return applied;
12829
+ const paintCache = selectionPaintCacheRef.current;
12830
+ const nextVisible = timelineVisibleIdsRef.current;
12831
+ const trace = tracePaintCacheRef.current;
12832
+ const traceSource = trace ? m.getSource("trace-features") : void 0;
12833
+ if (trace && !traceSource) return false;
12834
+ const traceDiff = trace && paintCache ? buildTraceTimelineDiff(trace, paintCache, nextVisible) : null;
12835
+ const { applied, toggled } = applyTimelineFastPath(paintCache, nextVisible, source);
12836
+ if (!applied || !paintCache || !source) return false;
12837
+ if (traceDiff && (!traceSource || !applyTraceTimelineDiff(traceDiff, paintCache, source, traceSource))) return false;
12838
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
12839
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
12840
+ setLabelsSuppressed(false);
12841
+ mapPerfLog("timeline", "fast path applied", {
12842
+ toggled,
12843
+ endpointsMoved: (traceDiff == null ? void 0 : traceDiff.pointUpdates.length) ?? 0,
12844
+ segmentsAdded: (traceDiff == null ? void 0 : traceDiff.segmentAdd.length) ?? 0,
12845
+ segmentsRemoved: (traceDiff == null ? void 0 : traceDiff.segmentRemove.length) ?? 0
12846
+ });
12847
+ return true;
12501
12848
  }, [autoLabelConfig, countVisibleFeatures]);
12502
12849
  tryTimelineFastPathRef.current = tryTimelineFastPath;
12503
12850
  const collectSelectionFeatureGroups = useCallback(() => {
@@ -13113,11 +13460,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13113
13460
  const updated = [...prev, newPoint];
13114
13461
  if (measureMode === "distance" && updated.length >= 2) {
13115
13462
  const line = turf.lineString(updated);
13116
- const distance = turf.length(line, { units: "kilometers" });
13117
- if (distance < 1) {
13118
- setMeasureResult(`${(distance * 1e3).toFixed(1)} m`);
13463
+ const distance2 = turf.length(line, { units: "kilometers" });
13464
+ if (distance2 < 1) {
13465
+ setMeasureResult(`${(distance2 * 1e3).toFixed(1)} m`);
13119
13466
  } else {
13120
- setMeasureResult(`${distance.toFixed(2)} km`);
13467
+ setMeasureResult(`${distance2.toFixed(2)} km`);
13121
13468
  }
13122
13469
  } else if (measureMode === "area" && updated.length >= 3) {
13123
13470
  const closed = [...updated, updated[0]];
@@ -13221,9 +13568,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13221
13568
  source.setData({ type: "FeatureCollection", features });
13222
13569
  }
13223
13570
  }, [measurePoints, measureMode, isMapLoaded]);
13224
- const handleSaveLayerGeoJSON = useCallback((layerId) => {
13571
+ const [ingestProgressStore] = useState(createIngestProgressStore);
13572
+ const exportInFlightRef = useRef(false);
13573
+ const handleSaveLayerGeoJSON = useCallback(async (layerId) => {
13225
13574
  const layer = layers.find((l) => l.id === layerId);
13226
- if (!layer) return;
13575
+ if (!layer || exportInFlightRef.current) return;
13227
13576
  const features = collectLayerFeatures(layer, {
13228
13577
  getDrawFeature: (id) => {
13229
13578
  var _a;
@@ -13238,17 +13587,37 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13238
13587
  if (layer.traceConfig) layerMetadata.traceConfig = layer.traceConfig;
13239
13588
  if (layer.heatmapConfig) layerMetadata.heatmapConfig = layer.heatmapConfig;
13240
13589
  if (layer.visualConfig) layerMetadata.visualConfig = layer.visualConfig;
13241
- const cleanedFeatures = stripInternalProperties(features);
13242
13590
  const geojson = {
13243
13591
  type: "FeatureCollection",
13244
- features: cleanedFeatures,
13592
+ features,
13245
13593
  properties: {
13246
13594
  layerMetadata
13247
13595
  }
13248
13596
  };
13249
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
13250
- downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
13251
- }, [layers]);
13597
+ exportInFlightRef.current = true;
13598
+ const progress = ingestProgressStore.begin(layer.name, { verb: "Preparing download" });
13599
+ progress.setTotal(features.length);
13600
+ try {
13601
+ const parts = await featureCollectionBlobPartsAsync(geojson, {
13602
+ mapFeature: (f) => stripInternalPropertiesFromFeature(f),
13603
+ onProgress: (done) => progress.update(done)
13604
+ });
13605
+ downloadBlob(
13606
+ new Blob(parts, { type: "application/json" }),
13607
+ `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`
13608
+ );
13609
+ } catch (error) {
13610
+ console.error(`Failed to export layer "${layer.name}" as GeoJSON:`, error);
13611
+ toast({
13612
+ title: "Export failed",
13613
+ description: error instanceof Error ? error.message : "Could not prepare the download",
13614
+ variant: "destructive"
13615
+ });
13616
+ } finally {
13617
+ progress.end();
13618
+ exportInFlightRef.current = false;
13619
+ }
13620
+ }, [layers, ingestProgressStore, toast]);
13252
13621
  const handleLoadLayerGeoJSON = useCallback((layerId) => {
13253
13622
  const input = fileInputRef.current;
13254
13623
  if (!input) return;
@@ -13263,7 +13632,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13263
13632
  input.dataset.createNewLayer = "true";
13264
13633
  input.click();
13265
13634
  }, []);
13266
- const buildEnrichedGeoJSON = useCallback(() => {
13635
+ const buildEnrichedExport = useCallback(() => {
13267
13636
  const allFeatures = [];
13268
13637
  const layerStates = [];
13269
13638
  layers.forEach((layer, idx) => {
@@ -13288,7 +13657,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13288
13657
  const { id: _id, featureIds: _fids, hasAltitudeData: _alt, ...persistable } = layer;
13289
13658
  layerStates.push({ index: idx, ...persistable });
13290
13659
  });
13291
- const cleanedFeatures = stripInternalProperties(allFeatures, ENRICHED_EXPORT_KEEP_KEYS);
13660
+ const rawCount = allFeatures.length;
13292
13661
  let viewport;
13293
13662
  if (map.current && isMapLoaded) {
13294
13663
  const c = map.current.getCenter();
@@ -13304,17 +13673,42 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13304
13673
  ...hostState
13305
13674
  };
13306
13675
  return {
13307
- type: "FeatureCollection",
13308
- features: [...cleanedFeatures, ...extraFeatures],
13309
- "octostar:map": octostarMap
13676
+ collection: {
13677
+ type: "FeatureCollection",
13678
+ features: [...allFeatures, ...extraFeatures],
13679
+ "octostar:map": octostarMap
13680
+ },
13681
+ mapFeature: (feature, index) => index < rawCount ? stripInternalPropertiesFromFeature(feature, ENRICHED_EXPORT_KEEP_KEYS) : feature
13310
13682
  };
13311
13683
  }, [layers, isMapLoaded, getAdditionalSaveState]);
13312
- const handleSaveAllGeoJSON = useCallback(() => {
13313
- if (!draw.current) return;
13314
- const geojson = buildEnrichedGeoJSON();
13315
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
13316
- downloadBlob(blob, "map_export.geojson");
13317
- }, [buildEnrichedGeoJSON]);
13684
+ const buildEnrichedGeoJSON = useCallback(() => {
13685
+ const { collection, mapFeature } = buildEnrichedExport();
13686
+ return { ...collection, features: collection.features.map(mapFeature) };
13687
+ }, [buildEnrichedExport]);
13688
+ const handleSaveAllGeoJSON = useCallback(async () => {
13689
+ if (!draw.current || exportInFlightRef.current) return;
13690
+ const { collection, mapFeature } = buildEnrichedExport();
13691
+ exportInFlightRef.current = true;
13692
+ const progress = ingestProgressStore.begin("map_export.geojson", { verb: "Preparing download" });
13693
+ progress.setTotal(collection.features.length);
13694
+ try {
13695
+ const parts = await featureCollectionBlobPartsAsync(collection, {
13696
+ mapFeature,
13697
+ onProgress: (done) => progress.update(done)
13698
+ });
13699
+ downloadBlob(new Blob(parts, { type: "application/geo+json" }), "map_export.geojson");
13700
+ } catch (error) {
13701
+ console.error("Failed to export the map as GeoJSON:", error);
13702
+ toast({
13703
+ title: "Export failed",
13704
+ description: error instanceof Error ? error.message : "Could not prepare the download",
13705
+ variant: "destructive"
13706
+ });
13707
+ } finally {
13708
+ progress.end();
13709
+ exportInFlightRef.current = false;
13710
+ }
13711
+ }, [buildEnrichedExport, ingestProgressStore, toast]);
13318
13712
  const handleSearchAndAddToNewLayer = useCallback(async () => {
13319
13713
  if (!onSearchEngineRequest || !map.current || !draw.current) return;
13320
13714
  const mapInstance = map.current;
@@ -13347,10 +13741,17 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13347
13741
  });
13348
13742
  if (result && result.features && result.features.length > 0) {
13349
13743
  saveStateForUndo();
13744
+ const activeId = activeEditingLayerIdRef.current;
13745
+ const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13746
+ const existingInActive = activeLayer ? countExisting(activeLayer) : 0;
13747
+ const capped = capFeatures(result.features, {
13748
+ max: featureCapRef.current,
13749
+ existing: existingInActive
13750
+ });
13350
13751
  const addedIds = [];
13351
13752
  isApiAddingRef.current = true;
13352
13753
  try {
13353
- result.features.forEach((f) => {
13754
+ capped.features.forEach((f) => {
13354
13755
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
13355
13756
  const normalizedFeature = {
13356
13757
  ...f,
@@ -13366,17 +13767,19 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13366
13767
  } finally {
13367
13768
  isApiAddingRef.current = false;
13368
13769
  }
13369
- const activeId = activeEditingLayerIdRef.current;
13370
- const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13770
+ let targetLayerId;
13771
+ let targetLayerName;
13371
13772
  if (activeLayer) {
13372
13773
  activeLayer.featureIds = [...activeLayer.featureIds, ...addedIds];
13373
13774
  setLayers([...layersRef.current]);
13775
+ targetLayerId = activeLayer.id;
13776
+ targetLayerName = activeLayer.name;
13374
13777
  toast({
13375
13778
  title: "Features added",
13376
- description: `Added ${result.features.length} features to "${activeLayer.name}"`
13779
+ description: `Added ${addedIds.length} features to "${activeLayer.name}"`
13377
13780
  });
13378
13781
  } else {
13379
- const layerName = `${result.features.length} workspace features`;
13782
+ const layerName = `${addedIds.length} workspace features`;
13380
13783
  const newLayerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13381
13784
  const newLayer = {
13382
13785
  id: newLayerId,
@@ -13387,9 +13790,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13387
13790
  layersRef.current = [...layersRef.current, newLayer];
13388
13791
  setLayers(layersRef.current);
13389
13792
  setActiveEditingLayerId(newLayerId);
13793
+ targetLayerId = newLayerId;
13794
+ targetLayerName = layerName;
13390
13795
  toast({
13391
13796
  title: "Layer created",
13392
- description: `Added ${result.features.length} features to "${layerName}"`
13797
+ description: `Added ${addedIds.length} features to "${layerName}"`
13798
+ });
13799
+ }
13800
+ if (capped.dropped > 0) {
13801
+ notifyFeatureCap({
13802
+ layerId: targetLayerId,
13803
+ layerName: targetLayerName,
13804
+ kept: addedIds.length,
13805
+ dropped: capped.dropped,
13806
+ sourceCount: capped.sourceCount,
13807
+ max: featureCapRef.current,
13808
+ source: "search",
13809
+ existing: existingInActive
13393
13810
  });
13394
13811
  }
13395
13812
  updateFeatureCount();
@@ -13403,7 +13820,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13403
13820
  variant: "destructive"
13404
13821
  });
13405
13822
  }
13406
- }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
13823
+ }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast, notifyFeatureCap]);
13407
13824
  const restoreEnrichedGeoJSON = useCallback((enriched) => {
13408
13825
  var _a;
13409
13826
  const mapState = enriched["octostar:map"];
@@ -13426,9 +13843,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13426
13843
  });
13427
13844
  const sortedLayers = [...mapState.layers].sort((a, b) => a.index - b.index);
13428
13845
  const newLayers = [];
13846
+ let restoreDropped = 0;
13847
+ let restoreSourceCount = 0;
13848
+ let restoreKept = 0;
13849
+ let truncatedLayerCount = 0;
13850
+ let firstTruncatedLayer = "";
13429
13851
  for (const ls of sortedLayers) {
13430
13852
  if (((_a = ls.metadata) == null ? void 0 : _a.dataViewing) === true) continue;
13431
- const rawFeatures = featuresByIndex.get(ls.index) ?? [];
13853
+ const capped = capFeatures(featuresByIndex.get(ls.index) ?? [], { max: featureCapRef.current });
13854
+ const rawFeatures = capped.features;
13855
+ if (capped.dropped > 0) {
13856
+ restoreDropped += capped.dropped;
13857
+ restoreSourceCount += capped.sourceCount;
13858
+ restoreKept += rawFeatures.length;
13859
+ truncatedLayerCount += 1;
13860
+ if (!firstTruncatedLayer) firstTruncatedLayer = ls.name;
13861
+ }
13432
13862
  const normalized = rawFeatures.map((f) => {
13433
13863
  const cleanProps = Object.fromEntries(
13434
13864
  Object.entries(f.properties || {}).filter(([k]) => !k.startsWith("_"))
@@ -13490,7 +13920,18 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13490
13920
  title: "Map restored",
13491
13921
  description: `Restored ${newLayers.length} layers with ${totalFeatures} features`
13492
13922
  });
13493
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast]);
13923
+ if (restoreDropped > 0) {
13924
+ notifyFeatureCap({
13925
+ layerName: firstTruncatedLayer,
13926
+ kept: restoreKept,
13927
+ dropped: restoreDropped,
13928
+ sourceCount: restoreSourceCount,
13929
+ max: featureCapRef.current,
13930
+ source: "restore",
13931
+ layerCount: truncatedLayerCount
13932
+ });
13933
+ }
13934
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast, notifyFeatureCap]);
13494
13935
  restoreEnrichedGeoJSONRef.current = restoreEnrichedGeoJSON;
13495
13936
  const handleWorkspaceLoad = useCallback(async () => {
13496
13937
  if (!onWorkspaceLoad) return;
@@ -13503,12 +13944,24 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13503
13944
  }
13504
13945
  saveStateForUndo();
13505
13946
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13506
- const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
13947
+ const layerName = "Loaded from workspace";
13948
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad", { max: featureCapRef.current });
13949
+ if (prepared.dropped > 0) {
13950
+ notifyFeatureCap({
13951
+ layerId,
13952
+ layerName,
13953
+ kept: prepared.features.length,
13954
+ dropped: prepared.dropped,
13955
+ sourceCount: prepared.sourceCount,
13956
+ max: featureCapRef.current,
13957
+ source: "workspace"
13958
+ });
13959
+ }
13507
13960
  readOnlyFeatures.current.set(layerId, prepared.features);
13508
13961
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
13509
13962
  const newLayer = {
13510
13963
  id: layerId,
13511
- name: "Loaded from workspace",
13964
+ name: layerName,
13512
13965
  visible: true,
13513
13966
  featureIds: prepared.featureIds,
13514
13967
  readOnly: true
@@ -13606,20 +14059,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13606
14059
  duration: 1e3
13607
14060
  });
13608
14061
  }, [layers, toast]);
13609
- const [ingestProgressStore] = useState(createIngestProgressStore);
13610
14062
  const ingestWithProgress = useCallback(async (label, input, options) => {
13611
14063
  const progress = ingestProgressStore.begin(label);
13612
14064
  try {
13613
- return await getSharedIngestClient().ingest(input, options, {
13614
- onHead: (summary) => progress.setTotal(summary.featureCount),
13615
- onProgress: (received) => progress.update(received)
13616
- });
14065
+ return await getSharedIngestClient().ingest(
14066
+ input,
14067
+ { ...options, maxFeatures: featureCapRef.current },
14068
+ {
14069
+ onHead: (summary) => progress.setTotal(summary.featureCount),
14070
+ onProgress: (received) => progress.update(received)
14071
+ }
14072
+ );
13617
14073
  } finally {
13618
14074
  progress.end();
13619
14075
  }
13620
14076
  }, [ingestProgressStore]);
13621
14077
  const loadGeoJSONFile = useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
13622
- var _a;
14078
+ var _a, _b, _c;
13623
14079
  let result;
13624
14080
  try {
13625
14081
  result = await ingestWithProgress(file.name, file, {
@@ -13669,7 +14125,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13669
14125
  data: { type: "FeatureCollection", features: normalizedFeatures },
13670
14126
  file,
13671
14127
  reprojected,
13672
- sourceCRS: sourceCRS ?? void 0
14128
+ sourceCRS: sourceCRS ?? void 0,
14129
+ ...result.truncated && { truncated: result.truncated }
13673
14130
  }) === true) {
13674
14131
  return;
13675
14132
  }
@@ -13689,6 +14146,16 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13689
14146
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13690
14147
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
13691
14148
  newLayer.featureIds = addedIds;
14149
+ if (result.truncated) {
14150
+ notifyFeatureCap(
14151
+ truncationToCapInfo(result.truncated, {
14152
+ layerId,
14153
+ layerName: newLayer.name,
14154
+ kept: normalizedFeatures.length,
14155
+ source: "file"
14156
+ })
14157
+ );
14158
+ }
13692
14159
  setLayers((prev) => [...prev, newLayer]);
13693
14160
  updateFeatureCount();
13694
14161
  scheduleTimelineUpdate();
@@ -13732,6 +14199,25 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13732
14199
  return;
13733
14200
  }
13734
14201
  const targetId = targetLayer.id;
14202
+ const existingInTarget = countExisting(targetLayer);
14203
+ const appendCapped = capFeatures(normalizedFeatures, {
14204
+ max: featureCapRef.current,
14205
+ existing: existingInTarget
14206
+ });
14207
+ const appendFeatures = appendCapped.features;
14208
+ const totalDropped = (((_b = result.truncated) == null ? void 0 : _b.droppedCount) ?? 0) + appendCapped.dropped;
14209
+ if (totalDropped > 0) {
14210
+ notifyFeatureCap({
14211
+ layerId: targetId,
14212
+ layerName: targetLayer.name,
14213
+ kept: appendFeatures.length,
14214
+ dropped: totalDropped,
14215
+ sourceCount: ((_c = result.truncated) == null ? void 0 : _c.sourceFeatureCount) ?? appendCapped.sourceCount,
14216
+ max: featureCapRef.current,
14217
+ source: "file",
14218
+ existing: existingInTarget
14219
+ });
14220
+ }
13735
14221
  const withLayerMetadata = (l, addedIds) => ({
13736
14222
  ...l,
13737
14223
  featureIds: [...l.featureIds, ...addedIds],
@@ -13740,7 +14226,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13740
14226
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13741
14227
  });
13742
14228
  if (targetLayer.readOnly) {
13743
- const addedFeatures = normalizedFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
14229
+ const addedFeatures = appendFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
13744
14230
  const addedIds = addedFeatures.map((f) => String(f.id));
13745
14231
  const existing = readOnlyFeatures.current.get(targetId) || [];
13746
14232
  readOnlyFeatures.current.set(targetId, [...existing, ...addedFeatures]);
@@ -13754,7 +14240,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13754
14240
  const addedIds = [];
13755
14241
  isApiAddingRef.current = true;
13756
14242
  try {
13757
- normalizedFeatures.forEach((f) => {
14243
+ appendFeatures.forEach((f) => {
13758
14244
  const ids = draw.current.add(f);
13759
14245
  addedIds.push(ids[0]);
13760
14246
  });
@@ -13763,9 +14249,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13763
14249
  }
13764
14250
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13765
14251
  } else {
13766
- const addedIds = normalizedFeatures.map((f) => String(f.id));
14252
+ const addedIds = appendFeatures.map((f) => String(f.id));
13767
14253
  const existing = hiddenFeatures.current.get(targetId) || [];
13768
- hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
14254
+ hiddenFeatures.current.set(targetId, [...existing, ...appendFeatures]);
13769
14255
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13770
14256
  }
13771
14257
  updateFeatureCount();
@@ -13774,9 +14260,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13774
14260
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
13775
14261
  toast({
13776
14262
  title: "GeoJSON loaded",
13777
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
14263
+ description: `Added ${appendFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
13778
14264
  });
13779
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14265
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13780
14266
  const handleFileChange = useCallback((e) => {
13781
14267
  var _a;
13782
14268
  const file = (_a = e.target.files) == null ? void 0 : _a[0];
@@ -13838,6 +14324,16 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13838
14324
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13839
14325
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
13840
14326
  newLayer.featureIds = addedIds;
14327
+ if (result.truncated) {
14328
+ notifyFeatureCap(
14329
+ truncationToCapInfo(result.truncated, {
14330
+ layerId,
14331
+ layerName: newLayer.name,
14332
+ kept: normalizedFeatures.length,
14333
+ source: "drop"
14334
+ })
14335
+ );
14336
+ }
13841
14337
  const nextLayers = [...layersRef.current, newLayer];
13842
14338
  layersRef.current = nextLayers;
13843
14339
  setLayers(nextLayers);
@@ -13860,7 +14356,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13860
14356
  title: "Layer added",
13861
14357
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
13862
14358
  });
13863
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14359
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13864
14360
  const handleDropGeoJSON = useCallback((name, data) => {
13865
14361
  void ingestDroppedLayer(name, data);
13866
14362
  }, [ingestDroppedLayer]);
@@ -14382,8 +14878,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
14382
14878
  "polygon",
14383
14879
  {
14384
14880
  points: selectionPoints.map(([lng, lat]) => {
14385
- const point = map.current.project([lng, lat]);
14386
- return `${point.x},${point.y}`;
14881
+ const point2 = map.current.project([lng, lat]);
14882
+ return `${point2.x},${point2.y}`;
14387
14883
  }).join(" "),
14388
14884
  fill: "rgba(59, 130, 246, 0.15)",
14389
14885
  stroke: "rgb(59, 130, 246)",
@@ -14442,12 +14938,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
14442
14938
  }
14443
14939
  ),
14444
14940
  selectionPoints.map(([lng, lat], i) => {
14445
- const point = map.current.project([lng, lat]);
14941
+ const point2 = map.current.project([lng, lat]);
14446
14942
  return /* @__PURE__ */ jsx(
14447
14943
  "circle",
14448
14944
  {
14449
- cx: point.x,
14450
- cy: point.y,
14945
+ cx: point2.x,
14946
+ cy: point2.y,
14451
14947
  r: "5",
14452
14948
  fill: "rgb(59, 130, 246)",
14453
14949
  stroke: "white",
@@ -14479,8 +14975,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
14479
14975
  "polygon",
14480
14976
  {
14481
14977
  points: selectionPoints.map(([lng, lat]) => {
14482
- const point = map.current.project([lng, lat]);
14483
- return `${point.x},${point.y}`;
14978
+ const point2 = map.current.project([lng, lat]);
14979
+ return `${point2.x},${point2.y}`;
14484
14980
  }).join(" "),
14485
14981
  fill: "rgba(59, 130, 246, 0.15)",
14486
14982
  stroke: "rgb(59, 130, 246)",
@@ -14500,8 +14996,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
14500
14996
  "polygon",
14501
14997
  {
14502
14998
  points: circleDrawPreview.map(([lng, lat]) => {
14503
- const point = map.current.project([lng, lat]);
14504
- return `${point.x},${point.y}`;
14999
+ const point2 = map.current.project([lng, lat]);
15000
+ return `${point2.x},${point2.y}`;
14505
15001
  }).join(" "),
14506
15002
  fill: "rgba(34, 197, 94, 0.15)",
14507
15003
  stroke: "rgb(34, 197, 94)",
@@ -14533,8 +15029,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
14533
15029
  "polygon",
14534
15030
  {
14535
15031
  points: rectangleDrawPreview.map(([lng, lat]) => {
14536
- const point = map.current.project([lng, lat]);
14537
- return `${point.x},${point.y}`;
15032
+ const point2 = map.current.project([lng, lat]);
15033
+ return `${point2.x},${point2.y}`;
14538
15034
  }).join(" "),
14539
15035
  fill: "rgba(34, 197, 94, 0.15)",
14540
15036
  stroke: "rgb(34, 197, 94)",
@@ -15267,9 +15763,9 @@ function generateNYCPoints(count) {
15267
15763
  };
15268
15764
  const features = Array.from({ length: count }, (_, i) => {
15269
15765
  const angle = Math.random() * Math.PI * 2;
15270
- const distance = Math.random() * Math.random() * spread;
15271
- const lng = nycCenter.lng + Math.cos(angle) * distance;
15272
- const lat = nycCenter.lat + Math.sin(angle) * distance * 0.7;
15766
+ const distance2 = Math.random() * Math.random() * spread;
15767
+ const lng = nycCenter.lng + Math.cos(angle) * distance2;
15768
+ const lat = nycCenter.lat + Math.sin(angle) * distance2 * 0.7;
15273
15769
  const type = getRandomType();
15274
15770
  const maxOccupancy = getMaxOccupancy(type);
15275
15771
  return {
@@ -15851,6 +16347,7 @@ export {
15851
16347
  ActionPanel,
15852
16348
  ClusterPieManager,
15853
16349
  ColorPickerPopover,
16350
+ DEFAULT_MAX_FEATURES_PER_LAYER,
15854
16351
  DebugSidebar,
15855
16352
  DrawingToolbar,
15856
16353
  INTERNAL_PROPERTY_KEYS,
@@ -15869,6 +16366,7 @@ export {
15869
16366
  TimebarToggle,
15870
16367
  cn,
15871
16368
  createClusterPieManager,
16369
+ featureCollectionBlobPartsAsync,
15872
16370
  getIconEmoji,
15873
16371
  isFeatureInRange,
15874
16372
  isInternalProperty,