@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.cjs CHANGED
@@ -86,38 +86,85 @@ function hasAltitudeData(feature) {
86
86
  }
87
87
  return false;
88
88
  }
89
+ function yieldToMain() {
90
+ const scheduler = globalThis.scheduler;
91
+ if (typeof (scheduler == null ? void 0 : scheduler.yield) === "function") {
92
+ return scheduler.yield();
93
+ }
94
+ const channelCtor = globalThis.MessageChannel;
95
+ if (typeof channelCtor === "function") {
96
+ return new Promise((resolve) => {
97
+ const channel = new channelCtor();
98
+ channel.port1.onmessage = () => {
99
+ channel.port1.close();
100
+ resolve();
101
+ };
102
+ channel.port2.postMessage(void 0);
103
+ });
104
+ }
105
+ return new Promise((resolve) => setTimeout(resolve, 0));
106
+ }
89
107
  const PRETTY_EXPORT_MAX_FEATURES = 1e4;
90
108
  const TARGET_PART_CHARS = 8 * 1024 * 1024;
91
- function featureCollectionBlobParts(collection, options) {
92
- const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
93
- if (collection.features.length <= prettyMax) {
94
- return [JSON.stringify(collection, null, 2)];
95
- }
96
- const targetChars = TARGET_PART_CHARS;
97
- const { features, ...rest } = collection;
98
- const head = JSON.stringify(rest);
109
+ function createBlobPartCoalescer(targetChars) {
99
110
  const parts = [];
100
111
  let pending = [];
101
112
  let pendingChars = 0;
102
- const push = (piece) => {
103
- pending.push(piece);
104
- pendingChars += piece.length;
105
- if (pendingChars >= targetChars) {
106
- parts.push(pending.join(""));
107
- pending = [];
108
- pendingChars = 0;
113
+ return {
114
+ push(piece) {
115
+ pending.push(piece);
116
+ pendingChars += piece.length;
117
+ if (pendingChars >= targetChars) {
118
+ parts.push(pending.join(""));
119
+ pending = [];
120
+ pendingChars = 0;
121
+ }
122
+ },
123
+ finish() {
124
+ if (pending.length > 0) parts.push(pending.join(""));
125
+ return parts;
109
126
  }
110
127
  };
111
- push(head.slice(0, -1));
112
- push(head.length > 2 ? ',"features":[' : '"features":[');
128
+ }
129
+ function pushCollectionHead(coalescer, rest) {
130
+ const head = JSON.stringify(rest);
131
+ coalescer.push(head.slice(0, -1));
132
+ coalescer.push(head.length > 2 ? ',"features":[' : '"features":[');
133
+ }
134
+ function serializeFeatureAt(feature, index) {
135
+ return index === 0 ? JSON.stringify(feature) : "," + JSON.stringify(feature);
136
+ }
137
+ const DEFAULT_SLICE_BUDGET_MS = 12;
138
+ async function featureCollectionBlobPartsAsync(collection, options) {
139
+ var _a, _b, _c;
140
+ const prettyMax = (options == null ? void 0 : options.prettyMaxFeatures) ?? PRETTY_EXPORT_MAX_FEATURES;
141
+ const mapFeature = options == null ? void 0 : options.mapFeature;
142
+ const total = collection.features.length;
143
+ if (total <= prettyMax) {
144
+ const mapped = mapFeature ? { ...collection, features: collection.features.map(mapFeature) } : collection;
145
+ (_a = options == null ? void 0 : options.onProgress) == null ? void 0 : _a.call(options, total, total);
146
+ return [JSON.stringify(mapped, null, 2)];
147
+ }
148
+ const { features, ...rest } = collection;
149
+ const coalescer = createBlobPartCoalescer((options == null ? void 0 : options.targetPartChars) ?? TARGET_PART_CHARS);
150
+ const yieldFn = (options == null ? void 0 : options.yieldFn) ?? yieldToMain;
151
+ const budget = (options == null ? void 0 : options.sliceBudgetMs) ?? DEFAULT_SLICE_BUDGET_MS;
152
+ pushCollectionHead(coalescer, rest);
153
+ let sliceStart = performance.now();
113
154
  for (let i = 0; i < features.length; i++) {
114
- push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
155
+ const feature = mapFeature ? mapFeature(features[i], i) : features[i];
156
+ coalescer.push(serializeFeatureAt(feature, i));
157
+ if (performance.now() - sliceStart >= budget) {
158
+ (_b = options == null ? void 0 : options.onProgress) == null ? void 0 : _b.call(options, i + 1, total);
159
+ await yieldFn();
160
+ sliceStart = performance.now();
161
+ }
115
162
  }
116
- push("]}");
117
- if (pending.length > 0) parts.push(pending.join(""));
118
- return parts;
163
+ coalescer.push("]}");
164
+ (_c = options == null ? void 0 : options.onProgress) == null ? void 0 : _c.call(options, total, total);
165
+ return coalescer.finish();
119
166
  }
120
- const ingestWorkerSource = '"use strict";(()=>{function p(e){let t=e.crs?.properties?.name,n=null;if(t){let r=t.match(/EPSG::?(\\d+)/i);r&&(n=`EPSG:${r[1]}`)}if(!n&&e.features.length>0){let r=w(e.features[0].geometry);if(r){let[s,a]=r;if(Math.abs(s)<=180&&Math.abs(a)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:n,needsReprojection:n!==null&&n!=="EPSG:4326"}}function w(e){if(!e)return null;switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":return e.coordinates[0];case"MultiLineString":case"Polygon":return e.coordinates[0]?.[0];case"MultiPolygon":return e.coordinates[0]?.[0]?.[0];default:return null}}function S(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(n=>n.length>=3&&n[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(n=>n.some(r=>r.length>=3&&r[2]!==0)):!1}function i(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function b(e){return!!(e.startDate||e.startdate||e.start_date||e.start_time||e.date||e.timestamp||e.flightDate||e.time||e.datetime||e.endDate||e.enddate||e.end_date||e.end_time)}function I(e){let t=i(e.startDate)||i(e.startdate)||i(e.start_date)||i(e.start_time)||i(e.date)||i(e.timestamp)||i(e.flightDate)||i(e.time)||i(e.datetime),n=i(e.endDate)||i(e.enddate)||i(e.end_date)||i(e.end_time);return t&&n&&n<t&&([t,n]=[n,t]),{startDate:t,endDate:n}}function h(e){return"kind"in e&&e.kind==="ack"}function J(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function D(e,t,n){switch(n.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${n.layerId}-f${t}`;case"uuid-fallback":return e.id?String(e.id):J()}}function C(e,t){if(Array.isArray(e)){if(typeof e[0]=="number"){let n=e[0],r=e[1];t[0]=Math.min(t[0],n),t[1]=Math.min(t[1],r),t[2]=Math.max(t[2],n),t[3]=Math.max(t[3],r);return}for(let n of e)C(n,t)}}function R(e,t){if(e){if(e.type==="GeometryCollection"){for(let n of e.geometries)R(n,t);return}C(e.coordinates,t)}}function M(e){let t=[1/0,1/0,-1/0,-1/0];for(let n of e)R(n.geometry,t);return t.every(n=>isFinite(n))?t:null}function x(e,t){let n;if(e.type==="text")try{n=JSON.parse(e.text)}catch(d){return{kind:"error",code:"parse-error",message:d instanceof Error?d.message:"Invalid file"}}else n=e.data;if(n&&n.type==="Feature"&&(n={type:"FeatureCollection",features:[n]}),!n||n.type!=="FeatureCollection"||!Array.isArray(n.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(t.emptyIsError&&n.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(n["octostar:map"])return{kind:"enriched",data:n};let{sourceCRS:r,needsReprojection:s}=p(n),a=!1,o=!1,u=[];n.features.forEach((d,G)=>{let m=D(d,G,t);!o&&S(d)&&(o=!0);let g=d.properties||{};if(!b(g)){u.push(t.idStrategy==="preserve"?d:{...d,id:m});return}let{startDate:y,endDate:k}=I(g);(y||k)&&(a=!0),u.push({...d,...m!==void 0&&{id:m},properties:{...g,startDate:y?.toISOString()||null,endDate:k?.toISOString()||null}})});let c=n.properties?.layerMetadata;return{kind:"features",features:u,featureCount:u.length,bbox:M(u),hasTemporal:a,hasAltitude:o,reprojected:!1,sourceCRS:r,...s&&{needsReprojection:s},...c&&{layerMetadata:c}}}var O=5e3;function P(e,t){let n=Number.isNaN(t)?O:Math.max(1,Math.floor(t)),r=[];for(let s=0;s<e.length;s+=n)r.push(e.slice(s,s+n));return r}function f(e){if(e===void 0)return!1;if(typeof e=="number")return Number.isFinite(e)&&!Object.is(e,-0);if(e===null||typeof e!="object")return!0;if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(!f(e[t]))return!1;return!0}for(let t in e)if(!f(e[t]))return!1;return!0}function A(e){for(let t=0;t<e.length;t++)if(!f(e[t]))return e;try{return JSON.stringify(e)}catch{return e}}function E(e){let{kind:t,features:n,...r}=e;return r}async function N(e,t,n,r){let s;try{s=x(t,n)}catch(a){r.post({kind:"result",id:e,ok:!1,error:a instanceof Error?a.message:String(a)});return}if(s.kind!=="features"){r.post({kind:"result",id:e,ok:!0,result:s});return}try{let a=r.encode??A,o=P(s.features,r.chunkSize??O);r.post({kind:"head",id:e,summary:E(s)});let u=o.length>0?a(o[0]):null;for(let c=0;c<o.length;c++){let d=r.waitAck(c);r.post({kind:"chunk",id:e,seq:c,payload:u}),u=c+1<o.length?a(o[c+1]):null,await d}r.post({kind:"done",id:e,chunkCount:o.length})}catch(a){r.post({kind:"error",id:e,message:a instanceof Error?a.message:String(a)})}}var F=e=>self.postMessage(e),l=new Map;self.onmessage=async e=>{let t=e.data;if(h(t)){let o=`${t.id}:${t.seq}`,u=l.get(o);l.delete(o),u?.();return}let{id:n,source:r,options:s,tuning:a}=t;try{let o=r.type==="blob"?{type:"text",text:await r.blob.text()}:r;await N(n,o,s,{post:F,waitAck:u=>new Promise(c=>{l.set(`${n}:${u}`,c)}),...a?.chunkSize!==void 0&&{chunkSize:a.chunkSize},...a?.featureArrayChunks&&{encode:u=>u}})}catch(o){F({kind:"result",id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}finally{l.forEach((o,u)=>{u.startsWith(`${n}:`)&&l.delete(u)})}};})();\n';
167
+ 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';
121
168
  proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
122
169
  proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
123
170
  proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
@@ -158,6 +205,73 @@ function reprojectGeometry(geometry, fromCRS) {
158
205
  coordinates: reprojectCoords(geomWithCoords.coordinates)
159
206
  };
160
207
  }
208
+ const DEFAULT_MAX_FEATURES_PER_LAYER = 2e5;
209
+ function resolveFeatureCap(value) {
210
+ if (value === void 0) return DEFAULT_MAX_FEATURES_PER_LAYER;
211
+ if (value === Infinity) return Infinity;
212
+ if (!Number.isFinite(value) || value < 1) {
213
+ console.warn(
214
+ `[map-editor] Ignoring maxFeaturesPerLayer=${String(value)} — expected a number >= 1 or Infinity. Falling back to ${DEFAULT_MAX_FEATURES_PER_LAYER}.`
215
+ );
216
+ return DEFAULT_MAX_FEATURES_PER_LAYER;
217
+ }
218
+ return Math.floor(value);
219
+ }
220
+ function capFeatures(features, options) {
221
+ const sourceCount = features.length;
222
+ const room = Math.max(0, options.max - (options.existing ?? 0));
223
+ if (sourceCount <= room) {
224
+ return { features, dropped: 0, sourceCount };
225
+ }
226
+ return {
227
+ features: features.slice(0, room),
228
+ dropped: sourceCount - room,
229
+ sourceCount
230
+ };
231
+ }
232
+ function truncationToCapInfo(truncation, rest) {
233
+ return {
234
+ ...rest,
235
+ dropped: truncation.droppedCount,
236
+ sourceCount: truncation.sourceFeatureCount,
237
+ max: truncation.maxFeatures
238
+ };
239
+ }
240
+ function formatCount(value) {
241
+ return value.toLocaleString("en-US");
242
+ }
243
+ function formatFeatureCapToast(info) {
244
+ const isRestore = info.source === "restore";
245
+ const variant = isRestore ? "destructive" : "default";
246
+ const withNote = (text) => isRestore ? `${text} Re-saving this map will persist only the loaded features.` : text;
247
+ const layerCount = info.layerCount ?? 1;
248
+ if (layerCount > 1) {
249
+ return {
250
+ title: "Feature limit reached",
251
+ description: withNote(
252
+ `${formatCount(layerCount)} layers were larger than the ${formatCount(info.max)}-feature limit; ${formatCount(info.dropped)} features in total were not loaded.`
253
+ ),
254
+ variant
255
+ };
256
+ }
257
+ const existing = info.existing ?? 0;
258
+ if (existing > 0) {
259
+ return {
260
+ title: "Feature limit reached",
261
+ description: withNote(
262
+ `"${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.`
263
+ ),
264
+ variant
265
+ };
266
+ }
267
+ return {
268
+ title: "Feature limit reached",
269
+ description: withNote(
270
+ `Only the first ${formatCount(info.kept)} of ${formatCount(info.sourceCount)} features were added to "${info.layerName}"; ${formatCount(info.dropped)} were skipped (per-layer limit).`
271
+ ),
272
+ variant
273
+ };
274
+ }
161
275
  function parseDate(value) {
162
276
  if (!value) return null;
163
277
  if (value instanceof Date) return value;
@@ -251,10 +365,11 @@ function runIngestPipeline(source, options) {
251
365
  return { kind: "enriched", data };
252
366
  }
253
367
  const { sourceCRS, needsReprojection } = detectSourceCRS(data);
368
+ const capped = capFeatures(data.features, { max: options.maxFeatures ?? Infinity });
254
369
  let hasTemporal = false;
255
370
  let hasAltitude = false;
256
371
  const features = [];
257
- data.features.forEach((f, index) => {
372
+ capped.features.forEach((f, index) => {
258
373
  const id = assignId(f, index, options);
259
374
  if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
260
375
  const props = f.properties || {};
@@ -289,7 +404,14 @@ function runIngestPipeline(source, options) {
289
404
  reprojected: false,
290
405
  sourceCRS,
291
406
  ...needsReprojection && { needsReprojection },
292
- ...layerMetadata && { layerMetadata }
407
+ ...layerMetadata && { layerMetadata },
408
+ ...capped.dropped > 0 && {
409
+ truncated: {
410
+ droppedCount: capped.dropped,
411
+ sourceFeatureCount: capped.sourceCount,
412
+ maxFeatures: options.maxFeatures
413
+ }
414
+ }
293
415
  };
294
416
  }
295
417
  function decodeChunkPayload(payload) {
@@ -609,9 +731,9 @@ function createIngestProgressStore() {
609
731
  listeners.forEach((listener) => listener());
610
732
  };
611
733
  return {
612
- begin(label) {
734
+ begin(label, options) {
613
735
  const id = nextId++;
614
- entries.set(id, { label, received: 0, total: null });
736
+ entries.set(id, { label, received: 0, total: null, ...(options == null ? void 0 : options.verb) && { verb: options.verb } });
615
737
  notify();
616
738
  return {
617
739
  setTotal(total) {
@@ -707,7 +829,8 @@ function IngestProgressOverlay({
707
829
  className: "rounded-md border bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-md",
708
830
  children: [
709
831
  /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
710
- "Importing ",
832
+ entry.verb ?? "Importing",
833
+ " ",
711
834
  entry.label,
712
835
  "…",
713
836
  entry.total !== null ? ` ${entry.received.toLocaleString()} / ${entry.total.toLocaleString()} features` : ""
@@ -1106,15 +1229,28 @@ function collectLayerFeatures(layer, sources) {
1106
1229
  if (readOnly) pushAll(features, readOnly);
1107
1230
  return features;
1108
1231
  }
1109
- function stripInternalProperties(features, keep) {
1110
- return features.map((f) => ({
1111
- ...f,
1232
+ function countLayerFeatures(layer, stores) {
1233
+ var _a;
1234
+ if (layer.readOnly) return ((_a = stores.readOnlyFeatures.get(layer.id)) == null ? void 0 : _a.length) ?? 0;
1235
+ const hidden = stores.hiddenFeatures.get(layer.id);
1236
+ if (!hidden || hidden.length === 0) return layer.featureIds.length;
1237
+ if (layer.featureIds.length === 0) return hidden.length;
1238
+ const ids = new Set(layer.featureIds);
1239
+ let count = layer.featureIds.length;
1240
+ for (const feature of hidden) {
1241
+ if (!ids.has(String(feature.id))) count++;
1242
+ }
1243
+ return count;
1244
+ }
1245
+ function stripInternalPropertiesFromFeature(feature, keep) {
1246
+ return {
1247
+ ...feature,
1112
1248
  properties: Object.fromEntries(
1113
- Object.entries(f.properties ?? {}).filter(
1249
+ Object.entries(feature.properties ?? {}).filter(
1114
1250
  ([key]) => !key.startsWith("_") || ((keep == null ? void 0 : keep.has(key)) ?? false)
1115
1251
  )
1116
1252
  )
1117
- }));
1253
+ };
1118
1254
  }
1119
1255
  const ToastContext = react.createContext(null);
1120
1256
  function useToast() {
@@ -2836,7 +2972,9 @@ function LayersPanel({
2836
2972
  key: "save-desktop",
2837
2973
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "w-[18px] h-[18px]" }),
2838
2974
  label: "Save GeoJSON to desktop",
2839
- onClick: () => onSaveLayerGeoJSON(layer.id)
2975
+ onClick: () => {
2976
+ void onSaveLayerGeoJSON(layer.id);
2977
+ }
2840
2978
  },
2841
2979
  ...onUpdateVisualConfig ? [
2842
2980
  { type: "divider" },
@@ -3517,7 +3655,9 @@ function LayersPanel({
3517
3655
  key: "save-geojson",
3518
3656
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "w-4 h-4" }),
3519
3657
  label: "Download Map",
3520
- onClick: onSaveAllGeoJSON
3658
+ onClick: () => {
3659
+ void onSaveAllGeoJSON();
3660
+ }
3521
3661
  },
3522
3662
  ...onWorkspaceSave ? [{
3523
3663
  key: "save-workspace",
@@ -6431,25 +6571,25 @@ function createSelectionPaintCache() {
6431
6571
  updatable: true
6432
6572
  };
6433
6573
  }
6434
- function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6435
- if (cache.presentIds.has(featureId)) {
6436
- cache.updatable = false;
6574
+ function recordPaintedFeature(cache2, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6575
+ if (cache2.presentIds.has(featureId)) {
6576
+ cache2.updatable = false;
6437
6577
  } else {
6438
- cache.presentIds.add(featureId);
6578
+ cache2.presentIds.add(featureId);
6439
6579
  }
6440
- cache.basePriorityById.set(featureId, basePriority);
6441
- if (isSelected) cache.appliedSelectedIds.add(featureId);
6580
+ cache2.basePriorityById.set(featureId, basePriority);
6581
+ if (isSelected) cache2.appliedSelectedIds.add(featureId);
6442
6582
  if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
6443
- cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6583
+ cache2.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6444
6584
  }
6445
6585
  if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
6446
- cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6586
+ cache2.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6447
6587
  }
6448
- if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
6588
+ if (isTimelineHidden) cache2.appliedHiddenIds.add(featureId);
6449
6589
  }
6450
- function applySelectionFastPath(cache, nextSelectedIds, source) {
6451
- if (!cache || !cache.updatable || !source) return false;
6452
- const diff = buildSelectionDiff(cache, nextSelectedIds);
6590
+ function applySelectionFastPath(cache2, nextSelectedIds, source) {
6591
+ if (!cache2 || !cache2.updatable || !source) return false;
6592
+ const diff = buildSelectionDiff(cache2, nextSelectedIds);
6453
6593
  if (diff) {
6454
6594
  try {
6455
6595
  source.updateData(diff);
@@ -6459,29 +6599,29 @@ function applySelectionFastPath(cache, nextSelectedIds, source) {
6459
6599
  }
6460
6600
  const applied = /* @__PURE__ */ new Set();
6461
6601
  nextSelectedIds.forEach((id) => {
6462
- if (cache.presentIds.has(id)) applied.add(id);
6602
+ if (cache2.presentIds.has(id)) applied.add(id);
6463
6603
  });
6464
- cache.appliedSelectedIds = applied;
6604
+ cache2.appliedSelectedIds = applied;
6465
6605
  return true;
6466
6606
  }
6467
6607
  function needsDrawSelectionUpdate(input) {
6468
6608
  return input.editableSelectionCount > 0 || input.drawSelectedCount > 0 || input.currentMode !== input.targetMode;
6469
6609
  }
6470
- function buildSelectionDiff(cache, nextSelectedIds) {
6610
+ function buildSelectionDiff(cache2, nextSelectedIds) {
6471
6611
  const update = [];
6472
- cache.appliedSelectedIds.forEach((id) => {
6473
- if (!nextSelectedIds.has(id) && cache.presentIds.has(id)) {
6612
+ cache2.appliedSelectedIds.forEach((id) => {
6613
+ if (!nextSelectedIds.has(id) && cache2.presentIds.has(id)) {
6474
6614
  update.push({
6475
6615
  id,
6476
6616
  addOrUpdateProperties: [
6477
6617
  { key: "isSelected", value: 0 },
6478
- { key: "_labelPriority", value: cache.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6618
+ { key: "_labelPriority", value: cache2.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6479
6619
  ]
6480
6620
  });
6481
6621
  }
6482
6622
  });
6483
6623
  nextSelectedIds.forEach((id) => {
6484
- if (!cache.appliedSelectedIds.has(id) && cache.presentIds.has(id)) {
6624
+ if (!cache2.appliedSelectedIds.has(id) && cache2.presentIds.has(id)) {
6485
6625
  update.push({
6486
6626
  id,
6487
6627
  addOrUpdateProperties: [
@@ -6493,13 +6633,13 @@ function buildSelectionDiff(cache, nextSelectedIds) {
6493
6633
  });
6494
6634
  return update.length > 0 ? { update } : null;
6495
6635
  }
6496
- function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6636
+ function buildTimelineVisibilityDiff(cache2, nextVisibleSet) {
6497
6637
  const update = [];
6498
6638
  const nextHiddenIds = /* @__PURE__ */ new Set();
6499
- cache.presentIds.forEach((id) => {
6639
+ cache2.presentIds.forEach((id) => {
6500
6640
  const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
6501
6641
  if (nextHidden) nextHiddenIds.add(id);
6502
- if (nextHidden === cache.appliedHiddenIds.has(id)) return;
6642
+ if (nextHidden === cache2.appliedHiddenIds.has(id)) return;
6503
6643
  if (nextHidden) {
6504
6644
  update.push({
6505
6645
  id,
@@ -6513,8 +6653,8 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6513
6653
  update.push({
6514
6654
  id,
6515
6655
  addOrUpdateProperties: [
6516
- { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6517
- { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6656
+ { key: "stroke-opacity", value: cache2.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6657
+ { key: "fill-opacity", value: cache2.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6518
6658
  { key: "isTimelineHidden", value: 0 }
6519
6659
  ]
6520
6660
  });
@@ -6522,10 +6662,10 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6522
6662
  });
6523
6663
  return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6524
6664
  }
6525
- function applyTimelineFastPath(cache, nextVisibleSet, source) {
6665
+ function applyTimelineFastPath(cache2, nextVisibleSet, source) {
6526
6666
  var _a;
6527
- if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6528
- const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6667
+ if (!cache2 || !cache2.updatable || !source) return { applied: false, toggled: 0 };
6668
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache2, nextVisibleSet);
6529
6669
  if (diff) {
6530
6670
  try {
6531
6671
  source.updateData(diff);
@@ -6533,9 +6673,204 @@ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6533
6673
  return { applied: false, toggled: 0 };
6534
6674
  }
6535
6675
  }
6536
- cache.appliedHiddenIds = nextHiddenIds;
6676
+ cache2.appliedHiddenIds = nextHiddenIds;
6537
6677
  return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6538
6678
  }
6679
+ const TRACE_DEFAULT_COLOR = "#3b82f6";
6680
+ const TRACE_UNGROUPED_KEY = "__all__";
6681
+ const cache = /* @__PURE__ */ new WeakMap();
6682
+ function getTraceGroups(features, groupByField) {
6683
+ const field = groupByField || null;
6684
+ let byField = cache.get(features);
6685
+ if (!byField) {
6686
+ byField = /* @__PURE__ */ new Map();
6687
+ cache.set(features, byField);
6688
+ }
6689
+ const fieldKey = field ?? "";
6690
+ let groups = byField.get(fieldKey);
6691
+ if (!groups) {
6692
+ groups = buildTraceGroups(features, field);
6693
+ byField.set(fieldKey, groups);
6694
+ }
6695
+ return groups;
6696
+ }
6697
+ function sortKey(time) {
6698
+ return Number.isNaN(time) ? -Infinity : time;
6699
+ }
6700
+ function compareStaged(a, b) {
6701
+ const ka = sortKey(a.time);
6702
+ const kb = sortKey(b.time);
6703
+ if (ka < kb) return -1;
6704
+ if (ka > kb) return 1;
6705
+ return 0;
6706
+ }
6707
+ function buildTraceGroups(features, field) {
6708
+ var _a;
6709
+ const staged = /* @__PURE__ */ new Map();
6710
+ for (const feature of features) {
6711
+ if (feature.id == null || feature.geometry.type !== "Point" || !((_a = feature.properties) == null ? void 0 : _a.startDate)) continue;
6712
+ const raw = field ? feature.properties[field] : void 0;
6713
+ const key = field && raw ? String(raw) : TRACE_UNGROUPED_KEY;
6714
+ let bucket = staged.get(key);
6715
+ if (!bucket) {
6716
+ bucket = [];
6717
+ staged.set(key, bucket);
6718
+ }
6719
+ bucket.push({ feature, time: new Date(feature.properties.startDate).getTime() });
6720
+ }
6721
+ const count = staged.size;
6722
+ const groups = [];
6723
+ staged.forEach((bucket, key) => {
6724
+ bucket.sort(compareStaged);
6725
+ groups.push({
6726
+ key,
6727
+ points: bucket.map((p) => p.feature),
6728
+ ids: bucket.map((p) => String(p.feature.id)),
6729
+ times: bucket.map((p) => p.time),
6730
+ color: traceGroupColor(key, groups.length, count),
6731
+ label: field && key !== TRACE_UNGROUPED_KEY ? key : null,
6732
+ pairStats: /* @__PURE__ */ new Map()
6733
+ });
6734
+ });
6735
+ return groups;
6736
+ }
6737
+ function traceGroupColor(key, index, count) {
6738
+ if (key === TRACE_UNGROUPED_KEY) return TRACE_DEFAULT_COLOR;
6739
+ return `hsl(${index * 360 / count % 360}, 70%, 50%)`;
6740
+ }
6741
+ function visibleTraceIndices(group, isVisible) {
6742
+ const indices = [];
6743
+ for (let i = 0; i < group.ids.length; i++) {
6744
+ if (isVisible(group.ids[i])) indices.push(i);
6745
+ }
6746
+ return indices;
6747
+ }
6748
+ function timelineVisibility(visibleSet) {
6749
+ return visibleSet === null ? () => true : (id) => visibleSet.has(id);
6750
+ }
6751
+ function traceSegmentStats(group, fromIndex, toIndex) {
6752
+ const key = `${fromIndex}:${toIndex}`;
6753
+ const cached = group.pairStats.get(key);
6754
+ if (cached) return cached;
6755
+ const from = group.points[fromIndex].geometry;
6756
+ const to = group.points[toIndex].geometry;
6757
+ const distanceKm = turf.distance(turf.point(from.coordinates), turf.point(to.coordinates), { units: "kilometers" });
6758
+ const durationMs = group.times[toIndex] - group.times[fromIndex];
6759
+ const durationHours = durationMs / (1e3 * 60 * 60);
6760
+ const avgSpeedKmh = durationHours > 0 ? distanceKm / durationHours : 0;
6761
+ const stats = {
6762
+ duration: formatDuration(durationMs),
6763
+ distance: distanceKm < 1 ? `${Math.round(distanceKm * 1e3)}m` : `${distanceKm.toFixed(2)}km`,
6764
+ avgSpeed: avgSpeedKmh < 1 ? `${(avgSpeedKmh * 1e3).toFixed(0)}m/h` : `${avgSpeedKmh.toFixed(1)}km/h`
6765
+ };
6766
+ group.pairStats.set(key, stats);
6767
+ return stats;
6768
+ }
6769
+ function formatDuration(durationMs) {
6770
+ if (durationMs < 6e4) return `${Math.round(durationMs / 1e3)}s`;
6771
+ if (durationMs < 36e5) return `${Math.round(durationMs / 6e4)}m`;
6772
+ if (durationMs < 864e5) {
6773
+ return `${Math.floor(durationMs / 36e5)}h ${Math.round(durationMs % 36e5 / 6e4)}m`;
6774
+ }
6775
+ return `${Math.floor(durationMs / 864e5)}d ${Math.round(durationMs % 864e5 / 36e5)}h`;
6776
+ }
6777
+ function traceSegmentId(groupIndex, fromIndex, toIndex) {
6778
+ return `${groupIndex}:${fromIndex}:${toIndex}`;
6779
+ }
6780
+ function traceSegmentFeature(group, groupIndex, fromIndex, toIndex) {
6781
+ var _a, _b;
6782
+ const from = group.points[fromIndex];
6783
+ const to = group.points[toIndex];
6784
+ return {
6785
+ type: "Feature",
6786
+ id: traceSegmentId(groupIndex, fromIndex, toIndex),
6787
+ properties: {
6788
+ group: group.key,
6789
+ color: group.color,
6790
+ ...traceSegmentStats(group, fromIndex, toIndex),
6791
+ fromName: ((_a = from.properties) == null ? void 0 : _a.name) || "",
6792
+ toName: ((_b = to.properties) == null ? void 0 : _b.name) || ""
6793
+ },
6794
+ geometry: {
6795
+ type: "LineString",
6796
+ coordinates: [from.geometry.coordinates, to.geometry.coordinates]
6797
+ }
6798
+ };
6799
+ }
6800
+ const TRACE_ENDPOINT_LABEL_PRIORITY = 5;
6801
+ const TRACE_POINT_RADIUS = 2;
6802
+ const TRACE_ENDPOINT_MIN_RADIUS = 8;
6803
+ function buildTraceTimelineDiff(trace, paint, nextVisibleSet) {
6804
+ const diff = { pointUpdates: [], segmentAdd: [], segmentRemove: [], basePriorities: [] };
6805
+ const paintedVisible = (id) => !paint.appliedHiddenIds.has(id);
6806
+ const nextVisible = timelineVisibility(nextVisibleSet);
6807
+ trace.groups.forEach((group, groupIndex) => {
6808
+ const prev = visibleTraceIndices(group, paintedVisible);
6809
+ const next = visibleTraceIndices(group, nextVisible);
6810
+ const prevEndpoint = prev.length > 0 ? prev[prev.length - 1] : -1;
6811
+ const nextEndpoint = next.length > 0 ? next[next.length - 1] : -1;
6812
+ if (prevEndpoint !== nextEndpoint) {
6813
+ if (prevEndpoint >= 0) pushEndpointUpdate(diff, trace, paint, group, group.ids[prevEndpoint], false);
6814
+ if (nextEndpoint >= 0) pushEndpointUpdate(diff, trace, paint, group, group.ids[nextEndpoint], true);
6815
+ }
6816
+ diffConsecutivePairs(
6817
+ prev,
6818
+ next,
6819
+ (from, to) => diff.segmentRemove.push(traceSegmentId(groupIndex, from, to)),
6820
+ (from, to) => diff.segmentAdd.push(traceSegmentFeature(group, groupIndex, from, to))
6821
+ );
6822
+ });
6823
+ return diff;
6824
+ }
6825
+ function pushEndpointUpdate(diff, trace, paint, group, id, isEndpoint) {
6826
+ const point = trace.pointPaint.get(id);
6827
+ if (!point) return;
6828
+ const labelled = isEndpoint && group.label !== null;
6829
+ const basePriority = labelled ? TRACE_ENDPOINT_LABEL_PRIORITY : point.basePriority;
6830
+ diff.pointUpdates.push({
6831
+ id,
6832
+ addOrUpdateProperties: [
6833
+ { key: "pointRadius", value: isEndpoint ? point.endpointRadius : TRACE_POINT_RADIUS },
6834
+ { key: "name", value: labelled ? group.label : point.name },
6835
+ { key: "isTraceLabel", value: labelled },
6836
+ { key: "_labelPriority", value: paint.appliedSelectedIds.has(id) ? 0 : basePriority }
6837
+ ]
6838
+ });
6839
+ diff.basePriorities.push([id, basePriority]);
6840
+ }
6841
+ function diffConsecutivePairs(prev, next, onRemove, onAdd) {
6842
+ let i = 0;
6843
+ let j = 0;
6844
+ while (i < prev.length - 1 || j < next.length - 1) {
6845
+ const prevFrom = i < prev.length - 1 ? prev[i] : Infinity;
6846
+ const nextFrom = j < next.length - 1 ? next[j] : Infinity;
6847
+ const prevTo = prev[i + 1];
6848
+ const nextTo = next[j + 1];
6849
+ if (prevFrom === nextFrom && prevTo === nextTo) {
6850
+ i++;
6851
+ j++;
6852
+ } else if (prevFrom < nextFrom || prevFrom === nextFrom && prevTo < nextTo) {
6853
+ onRemove(prevFrom, prevTo);
6854
+ i++;
6855
+ } else {
6856
+ onAdd(nextFrom, nextTo);
6857
+ j++;
6858
+ }
6859
+ }
6860
+ }
6861
+ function applyTraceTimelineDiff(diff, paint, pointSource, segmentSource) {
6862
+ try {
6863
+ if (diff.pointUpdates.length > 0) pointSource.updateData({ update: diff.pointUpdates });
6864
+ if (diff.segmentAdd.length > 0 || diff.segmentRemove.length > 0) {
6865
+ segmentSource.updateData({ add: diff.segmentAdd, remove: diff.segmentRemove });
6866
+ }
6867
+ } catch (error) {
6868
+ console.error("Trace timeline fast path failed; falling back to the full sync:", error);
6869
+ return false;
6870
+ }
6871
+ diff.basePriorities.forEach(([id, priority]) => paint.basePriorityById.set(id, priority));
6872
+ return true;
6873
+ }
6539
6874
  function deepClone(value) {
6540
6875
  try {
6541
6876
  return structuredClone(value);
@@ -6588,17 +6923,19 @@ function geometryEquals(a, b) {
6588
6923
  b.coordinates
6589
6924
  );
6590
6925
  }
6591
- function prepareFeaturesForLayer(input, caller) {
6926
+ function prepareFeaturesForLayer(input, caller, cap) {
6592
6927
  const logging = mapPerfLogEnabled();
6593
6928
  const started = logging ? performance.now() : 0;
6594
- const count = input.length;
6929
+ const capped = cap ? capFeatures(input, cap) : null;
6930
+ const source = capped ? capped.features : input;
6931
+ const count = source.length;
6595
6932
  const features = new Array(count);
6596
6933
  const featureIds = new Array(count);
6597
6934
  let hasTemporal = false;
6598
6935
  let temporalCount = 0;
6599
6936
  let reused = 0;
6600
6937
  for (let i = 0; i < count; i++) {
6601
- const f = input[i];
6938
+ const f = source[i];
6602
6939
  const props = f.properties || {};
6603
6940
  if (!hasAnyTemporalValue(props)) {
6604
6941
  if (typeof f.id === "string" && f.id) {
@@ -6633,10 +6970,17 @@ function prepareFeaturesForLayer(input, caller) {
6633
6970
  withTemporalKeys: temporalCount,
6634
6971
  hasTemporal,
6635
6972
  reused,
6636
- copied: count - reused
6973
+ copied: count - reused,
6974
+ ...capped && capped.dropped > 0 && { dropped: capped.dropped }
6637
6975
  });
6638
6976
  }
6639
- return { features, featureIds, hasTemporal };
6977
+ return {
6978
+ features,
6979
+ featureIds,
6980
+ hasTemporal,
6981
+ dropped: (capped == null ? void 0 : capped.dropped) ?? 0,
6982
+ sourceCount: (capped == null ? void 0 : capped.sourceCount) ?? count
6983
+ };
6640
6984
  }
6641
6985
  function scanTemporalFeatures(features, resolveLayerId, out) {
6642
6986
  let foundTemporal = false;
@@ -7567,6 +7911,7 @@ function extract3DFlightPaths(features) {
7567
7911
  });
7568
7912
  return paths;
7569
7913
  }
7914
+ const CAP_NOTICE_INTERVAL_MS = 5e3;
7570
7915
  const DEFAULT_LOCAL_GLYPHS_URL = "/fonts/{fontstack}/{range}.pbf";
7571
7916
  function basemapInsertAnchor(map) {
7572
7917
  if (map.getLayer("satellite-layer")) return "satellite-layer";
@@ -7690,6 +8035,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7690
8035
  enableProperties = true,
7691
8036
  autoOpenProperties = true,
7692
8037
  toastProvider,
8038
+ maxFeaturesPerLayer,
8039
+ onFeaturesTruncated,
7693
8040
  customGlobalMenuItems,
7694
8041
  extraLayerToolbarButtons,
7695
8042
  extraNewLayerButtons,
@@ -7797,6 +8144,31 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7797
8144
  const timelineStore = zustand.useStore(timelineStoreApi);
7798
8145
  const { toast: internalToast } = useToast();
7799
8146
  const toast = toastProvider ?? internalToast;
8147
+ const featureCap = react.useMemo(() => resolveFeatureCap(maxFeaturesPerLayer), [maxFeaturesPerLayer]);
8148
+ const featureCapRef = react.useRef(featureCap);
8149
+ featureCapRef.current = featureCap;
8150
+ const capNoticeRef = react.useRef(/* @__PURE__ */ new Map());
8151
+ const notifyFeatureCap = react.useCallback((info) => {
8152
+ if (onFeaturesTruncated) {
8153
+ onFeaturesTruncated(info);
8154
+ return;
8155
+ }
8156
+ if (info.source !== "restore") {
8157
+ const key = info.layerId ?? info.layerName;
8158
+ const now = Date.now();
8159
+ const last = capNoticeRef.current.get(key);
8160
+ if (last != null && now - last < CAP_NOTICE_INTERVAL_MS) return;
8161
+ capNoticeRef.current.set(key, now);
8162
+ }
8163
+ toast(formatFeatureCapToast(info));
8164
+ }, [onFeaturesTruncated, toast]);
8165
+ const countExisting = react.useCallback(
8166
+ (layer) => countLayerFeatures(layer, {
8167
+ hiddenFeatures: hiddenFeatures.current,
8168
+ readOnlyFeatures: readOnlyFeatures.current
8169
+ }),
8170
+ []
8171
+ );
7800
8172
  react.useEffect(() => {
7801
8173
  const handleError = (event) => {
7802
8174
  const msg = event.message || "";
@@ -7873,6 +8245,16 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7873
8245
  });
7874
8246
  return [...drawFeatures, ...readOnly];
7875
8247
  }, []);
8248
+ const traceSourceFeatures = react.useCallback((layer, featureById) => {
8249
+ const readOnly = readOnlyFeatures.current.get(layer.id);
8250
+ if (readOnly) return readOnly;
8251
+ const features = [];
8252
+ layer.featureIds.forEach((id) => {
8253
+ const f = featureById.get(id);
8254
+ if (f) features.push(f);
8255
+ });
8256
+ return features;
8257
+ }, []);
7876
8258
  const getSelectedFeatures = react.useCallback(() => {
7877
8259
  const drawSelected = draw.current ? draw.current.getSelected().features : [];
7878
8260
  const readOnlySelected = [];
@@ -8057,29 +8439,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8057
8439
  layers.forEach((layer) => {
8058
8440
  var _a;
8059
8441
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8060
- const layerFeatures = [];
8061
- layer.featureIds.forEach((id) => {
8062
- var _a2;
8063
- const f = featById.get(id);
8064
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8065
- layerFeatures.push(f);
8066
- });
8067
- if (layerFeatures.length < 1) return;
8068
- const groupByField = layer.traceConfig.groupByField;
8069
- const groups = /* @__PURE__ */ new Map();
8070
- layerFeatures.forEach((f) => {
8071
- var _a2;
8072
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8073
- if (!groups.has(key)) groups.set(key, []);
8074
- groups.get(key).push(f);
8075
- });
8076
- const groupKeys = Array.from(groups.keys());
8077
- groupKeys.forEach((key, index) => {
8078
- const color = key === "__all__" ? "#3b82f6" : `hsl(${index * 360 / groupKeys.length % 360}, 70%, 50%)`;
8079
- groups.get(key).forEach((f) => {
8080
- if (f.id) tracePointColors.set(String(f.id), color);
8081
- });
8082
- });
8442
+ for (const group of getTraceGroups(traceSourceFeatures(layer, featById), layer.traceConfig.groupByField)) {
8443
+ for (const id of group.ids) tracePointColors.set(id, group.color);
8444
+ }
8083
8445
  });
8084
8446
  const layerGradientRanges = /* @__PURE__ */ new Map();
8085
8447
  selectedFeatureIds.forEach((fid) => {
@@ -8113,7 +8475,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8113
8475
  colorMap.set(fid, color);
8114
8476
  });
8115
8477
  return colorMap;
8116
- }, [selectedFeatureIds, layers, getAllFeatures]);
8478
+ }, [selectedFeatureIds, layers, getAllFeatures, traceSourceFeatures]);
8117
8479
  const countVisibleFeatures = react.useCallback((threshold) => {
8118
8480
  const m = map.current;
8119
8481
  if (!m) return 0;
@@ -8132,6 +8494,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8132
8494
  }, []);
8133
8495
  const isSyncingRef = react.useRef(false);
8134
8496
  const selectionPaintCacheRef = react.useRef(null);
8497
+ const tracePaintCacheRef = react.useRef(null);
8135
8498
  const paintedArrowLinesRef = react.useRef([]);
8136
8499
  const renderArrowOverlays = react.useCallback((arrowLines) => {
8137
8500
  const mapInstance = map.current;
@@ -8301,60 +8664,29 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8301
8664
  const tracePointColors = /* @__PURE__ */ new Map();
8302
8665
  const lastTracePointLabels = /* @__PURE__ */ new Map();
8303
8666
  const tracePointIds = /* @__PURE__ */ new Set();
8667
+ const paintedTraceGroups = [];
8668
+ const traceSegments = [];
8669
+ const tracePointPaint = /* @__PURE__ */ new Map();
8670
+ const isTimelineVisibleId = timelineVisibility(visibleSet);
8304
8671
  currentLayers.forEach((layer) => {
8305
8672
  var _a;
8306
8673
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8307
- const layerFeatures = [];
8308
- layer.featureIds.forEach((id) => {
8309
- var _a2;
8310
- const f = featureById.get(id);
8311
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8312
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8313
- layerFeatures.push(f);
8314
- });
8315
- if (layerFeatures.length < 1) return;
8316
- const groupByField = layer.traceConfig.groupByField;
8317
- const groups = /* @__PURE__ */ new Map();
8318
- layerFeatures.forEach((f) => {
8319
- var _a2;
8320
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8321
- if (!groups.has(key)) groups.set(key, []);
8322
- groups.get(key).push(f);
8323
- });
8324
- const groupKeys = Array.from(groups.keys());
8325
- const groupColors = /* @__PURE__ */ new Map();
8326
- groupKeys.forEach((key, index) => {
8327
- if (key === "__all__") {
8328
- groupColors.set(key, "#3b82f6");
8329
- } else {
8330
- const hue = index * 360 / groupKeys.length % 360;
8331
- groupColors.set(key, `hsl(${hue}, 70%, 50%)`);
8674
+ const groups = getTraceGroups(traceSourceFeatures(layer, featureById), layer.traceConfig.groupByField);
8675
+ for (const group of groups) {
8676
+ const groupIndex = paintedTraceGroups.push(group) - 1;
8677
+ for (const id of group.ids) {
8678
+ tracePointIds.add(id);
8679
+ tracePointColors.set(id, group.color);
8332
8680
  }
8333
- });
8334
- groups.forEach((groupFeatures, groupKey) => {
8335
- const sorted = [...groupFeatures].sort((a, b) => {
8336
- var _a2, _b;
8337
- const dateA = new Date(((_a2 = a.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8338
- const dateB = new Date(((_b = b.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8339
- return dateA - dateB;
8340
- });
8341
- if (sorted.length > 0) {
8342
- const groupColor = groupColors.get(groupKey) || "#3b82f6";
8343
- sorted.forEach((point) => {
8344
- if (point.id) {
8345
- tracePointIds.add(String(point.id));
8346
- tracePointColors.set(String(point.id), groupColor);
8347
- }
8348
- });
8349
- const lastPoint = sorted[sorted.length - 1];
8350
- if (lastPoint.id) {
8351
- lastTracePointIds.add(String(lastPoint.id));
8352
- if (groupByField && groupKey !== "__all__") {
8353
- lastTracePointLabels.set(String(lastPoint.id), groupKey);
8354
- }
8355
- }
8681
+ const visible = visibleTraceIndices(group, isTimelineVisibleId);
8682
+ if (visible.length === 0) continue;
8683
+ const endpointId = group.ids[visible[visible.length - 1]];
8684
+ lastTracePointIds.add(endpointId);
8685
+ if (group.label !== null) lastTracePointLabels.set(endpointId, group.label);
8686
+ for (let k = 1; k < visible.length; k++) {
8687
+ traceSegments.push(traceSegmentFeature(group, groupIndex, visible[k - 1], visible[k]));
8356
8688
  }
8357
- });
8689
+ }
8358
8690
  });
8359
8691
  const paintCache = createSelectionPaintCache();
8360
8692
  const sourceData = {
@@ -8399,13 +8731,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8399
8731
  const isTracePoint = tracePointIds.has(featureId);
8400
8732
  const isLastTracePoint = lastTracePointIds.has(featureId);
8401
8733
  const traceLabel = lastTracePointLabels.get(featureId);
8734
+ let traceEndpointRadius = null;
8402
8735
  if (isTracePoint && f.geometry.type === "Point") {
8403
8736
  strokeColor = tracePointColors.get(featureId) || strokeColor;
8404
- if (isLastTracePoint) {
8405
- pointRadius = Math.max(pointRadius, 8);
8406
- } else {
8407
- pointRadius = 2;
8408
- }
8737
+ traceEndpointRadius = Math.max(pointRadius, TRACE_ENDPOINT_MIN_RADIUS);
8738
+ pointRadius = isLastTracePoint ? traceEndpointRadius : TRACE_POINT_RADIUS;
8409
8739
  }
8410
8740
  let labelText = ((_d = f.properties) == null ? void 0 : _d.name) || "";
8411
8741
  const labelConfig = visualConfig == null ? void 0 : visualConfig.label;
@@ -8419,6 +8749,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8419
8749
  labelText = fieldValue !== void 0 && fieldValue !== null ? String(fieldValue) : "";
8420
8750
  }
8421
8751
  }
8752
+ const nonTraceLabelText = labelText;
8422
8753
  if (traceLabel) {
8423
8754
  labelText = traceLabel;
8424
8755
  }
@@ -8450,11 +8781,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8450
8781
  });
8451
8782
  }
8452
8783
  const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIdSet.has(featureId) ? 1 : 0;
8453
- let basePriority = DEFAULT_LABEL_PRIORITY;
8454
- if (traceLabel) {
8455
- basePriority = 5;
8456
- } else if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
8457
- basePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
8784
+ let nonTracePriority = DEFAULT_LABEL_PRIORITY;
8785
+ if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
8786
+ nonTracePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
8458
8787
  } else {
8459
8788
  const idStr = String(featureId);
8460
8789
  let h = 0;
@@ -8462,9 +8791,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8462
8791
  h = (h << 5) - h + idStr.charCodeAt(i);
8463
8792
  h |= 0;
8464
8793
  }
8465
- basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8794
+ nonTracePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8466
8795
  }
8796
+ const basePriority = traceLabel ? TRACE_ENDPOINT_LABEL_PRIORITY : nonTracePriority;
8467
8797
  const labelPriority = isFeatureSelected ? 0 : basePriority;
8798
+ if (traceEndpointRadius !== null) {
8799
+ tracePointPaint.set(featureId, { name: nonTraceLabelText, endpointRadius: traceEndpointRadius, basePriority: nonTracePriority });
8800
+ }
8468
8801
  const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
8469
8802
  const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
8470
8803
  recordPaintedFeature(
@@ -8511,93 +8844,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8511
8844
  source.setData(sourceData);
8512
8845
  selectionPaintCacheRef.current = paintCache;
8513
8846
  const traceSource = map.current.getSource("trace-features");
8514
- if (traceSource) {
8515
- const traceSegments = [];
8516
- currentLayers.forEach((layer) => {
8517
- var _a;
8518
- if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8519
- const layerFeatures = [];
8520
- layer.featureIds.forEach((id) => {
8521
- var _a2;
8522
- const f = featureById.get(id);
8523
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8524
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8525
- layerFeatures.push(f);
8526
- });
8527
- if (layerFeatures.length < 2) return;
8528
- const groupByField = layer.traceConfig.groupByField;
8529
- const groups = /* @__PURE__ */ new Map();
8530
- layerFeatures.forEach((f) => {
8531
- var _a2;
8532
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8533
- if (!groups.has(key)) groups.set(key, []);
8534
- groups.get(key).push(f);
8535
- });
8536
- const groupKeys = Array.from(groups.keys());
8537
- const groupColors = /* @__PURE__ */ new Map();
8538
- groupKeys.forEach((key, index) => {
8539
- if (key === "__all__") {
8540
- groupColors.set(key, "#3b82f6");
8541
- } else {
8542
- const hue = index * 360 / groupKeys.length % 360;
8543
- groupColors.set(key, `hsl(${hue}, 70%, 50%)`);
8544
- }
8545
- });
8546
- groups.forEach((groupFeatures, groupKey) => {
8547
- var _a2, _b, _c, _d;
8548
- const sorted = [...groupFeatures].sort((a, b) => {
8549
- var _a3, _b2;
8550
- const dateA = new Date(((_a3 = a.properties) == null ? void 0 : _a3.startDate) || 0).getTime();
8551
- const dateB = new Date(((_b2 = b.properties) == null ? void 0 : _b2.startDate) || 0).getTime();
8552
- return dateA - dateB;
8553
- });
8554
- if (sorted.length < 2) return;
8555
- for (let i = 0; i < sorted.length - 1; i++) {
8556
- const from = sorted[i];
8557
- const to = sorted[i + 1];
8558
- const fromCoords = from.geometry.coordinates;
8559
- const toCoords = to.geometry.coordinates;
8560
- const fromPoint = turf__namespace.point(fromCoords);
8561
- const toPoint = turf__namespace.point(toCoords);
8562
- const distanceKm = turf__namespace.distance(fromPoint, toPoint, { units: "kilometers" });
8563
- const fromTime = new Date(((_a2 = from.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8564
- const toTime = new Date(((_b = to.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8565
- const durationMs = toTime - fromTime;
8566
- const durationHours = durationMs / (1e3 * 60 * 60);
8567
- const avgSpeedKmh = durationHours > 0 ? distanceKm / durationHours : 0;
8568
- let durationStr = "";
8569
- if (durationMs < 6e4) {
8570
- durationStr = `${Math.round(durationMs / 1e3)}s`;
8571
- } else if (durationMs < 36e5) {
8572
- durationStr = `${Math.round(durationMs / 6e4)}m`;
8573
- } else if (durationMs < 864e5) {
8574
- durationStr = `${Math.floor(durationMs / 36e5)}h ${Math.round(durationMs % 36e5 / 6e4)}m`;
8575
- } else {
8576
- durationStr = `${Math.floor(durationMs / 864e5)}d ${Math.round(durationMs % 864e5 / 36e5)}h`;
8577
- }
8578
- const distanceStr = distanceKm < 1 ? `${Math.round(distanceKm * 1e3)}m` : `${distanceKm.toFixed(2)}km`;
8579
- const speedStr = avgSpeedKmh < 1 ? `${(avgSpeedKmh * 1e3).toFixed(0)}m/h` : `${avgSpeedKmh.toFixed(1)}km/h`;
8580
- traceSegments.push({
8581
- type: "Feature",
8582
- properties: {
8583
- group: groupKey,
8584
- color: groupColors.get(groupKey) || "#3b82f6",
8585
- duration: durationStr,
8586
- distance: distanceStr,
8587
- avgSpeed: speedStr,
8588
- fromName: ((_c = from.properties) == null ? void 0 : _c.name) || "",
8589
- toName: ((_d = to.properties) == null ? void 0 : _d.name) || ""
8590
- },
8591
- geometry: {
8592
- type: "LineString",
8593
- coordinates: [fromCoords, toCoords]
8594
- }
8595
- });
8596
- }
8597
- });
8598
- });
8599
- traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8600
- }
8847
+ if (traceSource) traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8848
+ tracePaintCacheRef.current = traceSource && paintedTraceGroups.length > 0 ? { groups: paintedTraceGroups, pointPaint: tracePointPaint } : null;
8601
8849
  {
8602
8850
  let sawArrowFeature = false;
8603
8851
  const arrowLines = [];
@@ -10484,16 +10732,22 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10484
10732
  clusterConfig: options == null ? void 0 : options.clusterConfig,
10485
10733
  altitudeDisplayMode: options == null ? void 0 : options.altitudeDisplayMode
10486
10734
  };
10735
+ let addedFeatures = [];
10736
+ let capDropped = 0;
10487
10737
  if (geojson) {
10738
+ const max = featureCapRef.current;
10488
10739
  if (options == null ? void 0 : options.readOnly) {
10489
- const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
10740
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer", { max });
10490
10741
  readOnlyFeatures.current.set(layerId, prepared.features);
10491
10742
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10492
10743
  newLayer.featureIds = prepared.featureIds;
10744
+ addedFeatures = prepared.features;
10745
+ capDropped = prepared.dropped;
10493
10746
  } else if (draw.current) {
10747
+ const capped = capFeatures(geojson.features, { max });
10494
10748
  isApiAddingRef.current = true;
10495
10749
  try {
10496
- const addedIds = geojson.features.map((f) => {
10750
+ const addedIds = capped.features.map((f) => {
10497
10751
  const ids = draw.current.add(f);
10498
10752
  return ids[0];
10499
10753
  });
@@ -10501,8 +10755,21 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10501
10755
  } finally {
10502
10756
  isApiAddingRef.current = false;
10503
10757
  }
10758
+ addedFeatures = capped.features;
10759
+ capDropped = capped.dropped;
10504
10760
  }
10505
10761
  }
10762
+ if (capDropped > 0) {
10763
+ notifyFeatureCap({
10764
+ layerId,
10765
+ layerName: name,
10766
+ kept: addedFeatures.length,
10767
+ dropped: capDropped,
10768
+ sourceCount: (geojson == null ? void 0 : geojson.features.length) ?? 0,
10769
+ max: featureCapRef.current,
10770
+ source: "api"
10771
+ });
10772
+ }
10506
10773
  if (newLayer.visible === false && !(options == null ? void 0 : options.readOnly) && draw.current && newLayer.featureIds.length > 0) {
10507
10774
  const features = newLayer.featureIds.map((id) => draw.current.get(id)).filter(Boolean);
10508
10775
  hiddenFeatures.current.set(layerId, features);
@@ -10520,9 +10787,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10520
10787
  updateFeatureCount();
10521
10788
  scheduleTimelineUpdate();
10522
10789
  scheduleSync();
10523
- if (!(options == null ? void 0 : options.skipFit) && geojson && geojson.features.length > 0 && map.current) {
10790
+ if (!(options == null ? void 0 : options.skipFit) && addedFeatures.length > 0 && map.current) {
10524
10791
  try {
10525
- const bbox = turf__namespace.bbox(geojson);
10792
+ const bbox = turf__namespace.bbox({
10793
+ type: "FeatureCollection",
10794
+ features: addedFeatures
10795
+ });
10526
10796
  if (bbox.every((v) => isFinite(v))) {
10527
10797
  map.current.fitBounds(
10528
10798
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -10615,7 +10885,22 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10615
10885
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
10616
10886
  if (layer.readOnly) {
10617
10887
  const existing = readOnlyFeatures.current.get(layerId) || [];
10618
- const prepared = prepareFeaturesForLayer(features, "addFeatures");
10888
+ const prepared = prepareFeaturesForLayer(features, "addFeatures", {
10889
+ max: featureCapRef.current,
10890
+ existing: existing.length
10891
+ });
10892
+ if (prepared.dropped > 0) {
10893
+ notifyFeatureCap({
10894
+ layerId,
10895
+ layerName: layer.name,
10896
+ kept: prepared.features.length,
10897
+ dropped: prepared.dropped,
10898
+ sourceCount: prepared.sourceCount,
10899
+ max: featureCapRef.current,
10900
+ source: "api",
10901
+ existing: existing.length
10902
+ });
10903
+ }
10619
10904
  const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
10620
10905
  const combined = [...existing, ...prepared.features];
10621
10906
  readOnlyFeatures.current.set(layerId, combined);
@@ -10635,9 +10920,26 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10635
10920
  }
10636
10921
  if (!draw.current) return [];
10637
10922
  const addedIds = [];
10923
+ const existingInLayer = countExisting(layer);
10924
+ const cappedForDraw = capFeatures(features, {
10925
+ max: featureCapRef.current,
10926
+ existing: existingInLayer
10927
+ });
10928
+ if (cappedForDraw.dropped > 0) {
10929
+ notifyFeatureCap({
10930
+ layerId,
10931
+ layerName: layer.name,
10932
+ kept: cappedForDraw.features.length,
10933
+ dropped: cappedForDraw.dropped,
10934
+ sourceCount: cappedForDraw.sourceCount,
10935
+ max: featureCapRef.current,
10936
+ source: "api",
10937
+ existing: existingInLayer
10938
+ });
10939
+ }
10638
10940
  isApiAddingRef.current = true;
10639
10941
  try {
10640
- features.forEach((f) => {
10942
+ cappedForDraw.features.forEach((f) => {
10641
10943
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10642
10944
  const normalizedFeature = {
10643
10945
  ...f,
@@ -10746,12 +11048,29 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10746
11048
  return { type: "FeatureCollection", features: cleanedFeatures };
10747
11049
  },
10748
11050
  importGeoJSON: (layerId, geojson) => {
10749
- const layer = layers.find((l) => l.id === layerId);
11051
+ const layer = layersRef.current.find((l) => l.id === layerId);
10750
11052
  if (!layer || !draw.current || !isMapLoaded) return [];
10751
11053
  const addedIds = [];
11054
+ const existingInLayer = countExisting(layer);
11055
+ const capped = capFeatures(geojson.features, {
11056
+ max: featureCapRef.current,
11057
+ existing: existingInLayer
11058
+ });
11059
+ if (capped.dropped > 0) {
11060
+ notifyFeatureCap({
11061
+ layerId,
11062
+ layerName: layer.name,
11063
+ kept: capped.features.length,
11064
+ dropped: capped.dropped,
11065
+ sourceCount: capped.sourceCount,
11066
+ max: featureCapRef.current,
11067
+ source: "api",
11068
+ existing: existingInLayer
11069
+ });
11070
+ }
10752
11071
  isApiAddingRef.current = true;
10753
11072
  try {
10754
- geojson.features.forEach((f) => {
11073
+ capped.features.forEach((f) => {
10755
11074
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10756
11075
  const normalizedFeature = {
10757
11076
  ...f,
@@ -10855,9 +11174,20 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10855
11174
  updateReadOnlyLayer: (layerId, features) => {
10856
11175
  const layer = layersRef.current.find((l) => l.id === layerId);
10857
11176
  if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
10858
- const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
11177
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer", { max: featureCapRef.current });
11178
+ if (prepared.dropped > 0) {
11179
+ notifyFeatureCap({
11180
+ layerId,
11181
+ layerName: layer.name,
11182
+ kept: prepared.features.length,
11183
+ dropped: prepared.dropped,
11184
+ sourceCount: prepared.sourceCount,
11185
+ max: featureCapRef.current,
11186
+ source: "api"
11187
+ });
11188
+ }
10859
11189
  readOnlyFeatures.current.set(layerId, prepared.features);
10860
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
11190
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10861
11191
  if (prepared.hasTemporal) {
10862
11192
  scheduleTimelineUpdate();
10863
11193
  }
@@ -10873,9 +11203,20 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10873
11203
  },
10874
11204
  setLayerData: (name, geojson, options) => {
10875
11205
  if (!isMapLoadedRef.current) return "";
10876
- const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
11206
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData", { max: featureCapRef.current });
10877
11207
  const newFeatureIds = prepared.featureIds;
10878
11208
  const layerId = `managed-${name}`;
11209
+ if (prepared.dropped > 0) {
11210
+ notifyFeatureCap({
11211
+ layerId,
11212
+ layerName: name,
11213
+ kept: prepared.features.length,
11214
+ dropped: prepared.dropped,
11215
+ sourceCount: prepared.sourceCount,
11216
+ max: featureCapRef.current,
11217
+ source: "api"
11218
+ });
11219
+ }
10879
11220
  readOnlyFeatures.current.set(layerId, prepared.features);
10880
11221
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10881
11222
  const buildLayerObj = (existing) => {
@@ -10925,9 +11266,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10925
11266
  });
10926
11267
  updateFeatureCount();
10927
11268
  scheduleSync();
10928
- if ((options == null ? void 0 : options.fitPadding) != null && geojson.features.length > 0 && map.current) {
11269
+ if ((options == null ? void 0 : options.fitPadding) != null && prepared.features.length > 0 && map.current) {
10929
11270
  try {
10930
- const bbox = turf__namespace.bbox(geojson);
11271
+ const bbox = turf__namespace.bbox(
11272
+ prepared.dropped > 0 ? { type: "FeatureCollection", features: prepared.features } : geojson
11273
+ );
10931
11274
  if (bbox.every((v) => isFinite(v))) {
10932
11275
  map.current.fitBounds(
10933
11276
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -12502,23 +12845,26 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12502
12845
  const m = map.current;
12503
12846
  if (!m) return true;
12504
12847
  if (hasArrowFeaturesRef.current) return false;
12505
- if (layersRef.current.some((l) => {
12506
- var _a;
12507
- return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
12508
- })) return false;
12509
12848
  const source = m.getSource("custom-features");
12510
- const { applied, toggled } = applyTimelineFastPath(
12511
- selectionPaintCacheRef.current,
12512
- timelineVisibleIdsRef.current,
12513
- source
12514
- );
12515
- if (applied) {
12516
- const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
12517
- setVisibleFeatureCount(countVisibleFeatures(threshold));
12518
- setLabelsSuppressed(false);
12519
- mapPerfLog("timeline", "fast path applied", { toggled });
12520
- }
12521
- return applied;
12849
+ const paintCache = selectionPaintCacheRef.current;
12850
+ const nextVisible = timelineVisibleIdsRef.current;
12851
+ const trace = tracePaintCacheRef.current;
12852
+ const traceSource = trace ? m.getSource("trace-features") : void 0;
12853
+ if (trace && !traceSource) return false;
12854
+ const traceDiff = trace && paintCache ? buildTraceTimelineDiff(trace, paintCache, nextVisible) : null;
12855
+ const { applied, toggled } = applyTimelineFastPath(paintCache, nextVisible, source);
12856
+ if (!applied || !paintCache || !source) return false;
12857
+ if (traceDiff && (!traceSource || !applyTraceTimelineDiff(traceDiff, paintCache, source, traceSource))) return false;
12858
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
12859
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
12860
+ setLabelsSuppressed(false);
12861
+ mapPerfLog("timeline", "fast path applied", {
12862
+ toggled,
12863
+ endpointsMoved: (traceDiff == null ? void 0 : traceDiff.pointUpdates.length) ?? 0,
12864
+ segmentsAdded: (traceDiff == null ? void 0 : traceDiff.segmentAdd.length) ?? 0,
12865
+ segmentsRemoved: (traceDiff == null ? void 0 : traceDiff.segmentRemove.length) ?? 0
12866
+ });
12867
+ return true;
12522
12868
  }, [autoLabelConfig, countVisibleFeatures]);
12523
12869
  tryTimelineFastPathRef.current = tryTimelineFastPath;
12524
12870
  const collectSelectionFeatureGroups = react.useCallback(() => {
@@ -13242,9 +13588,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13242
13588
  source.setData({ type: "FeatureCollection", features });
13243
13589
  }
13244
13590
  }, [measurePoints, measureMode, isMapLoaded]);
13245
- const handleSaveLayerGeoJSON = react.useCallback((layerId) => {
13591
+ const [ingestProgressStore] = react.useState(createIngestProgressStore);
13592
+ const exportInFlightRef = react.useRef(false);
13593
+ const handleSaveLayerGeoJSON = react.useCallback(async (layerId) => {
13246
13594
  const layer = layers.find((l) => l.id === layerId);
13247
- if (!layer) return;
13595
+ if (!layer || exportInFlightRef.current) return;
13248
13596
  const features = collectLayerFeatures(layer, {
13249
13597
  getDrawFeature: (id) => {
13250
13598
  var _a;
@@ -13259,17 +13607,37 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13259
13607
  if (layer.traceConfig) layerMetadata.traceConfig = layer.traceConfig;
13260
13608
  if (layer.heatmapConfig) layerMetadata.heatmapConfig = layer.heatmapConfig;
13261
13609
  if (layer.visualConfig) layerMetadata.visualConfig = layer.visualConfig;
13262
- const cleanedFeatures = stripInternalProperties(features);
13263
13610
  const geojson = {
13264
13611
  type: "FeatureCollection",
13265
- features: cleanedFeatures,
13612
+ features,
13266
13613
  properties: {
13267
13614
  layerMetadata
13268
13615
  }
13269
13616
  };
13270
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
13271
- downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
13272
- }, [layers]);
13617
+ exportInFlightRef.current = true;
13618
+ const progress = ingestProgressStore.begin(layer.name, { verb: "Preparing download" });
13619
+ progress.setTotal(features.length);
13620
+ try {
13621
+ const parts = await featureCollectionBlobPartsAsync(geojson, {
13622
+ mapFeature: (f) => stripInternalPropertiesFromFeature(f),
13623
+ onProgress: (done) => progress.update(done)
13624
+ });
13625
+ downloadBlob(
13626
+ new Blob(parts, { type: "application/json" }),
13627
+ `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`
13628
+ );
13629
+ } catch (error) {
13630
+ console.error(`Failed to export layer "${layer.name}" as GeoJSON:`, error);
13631
+ toast({
13632
+ title: "Export failed",
13633
+ description: error instanceof Error ? error.message : "Could not prepare the download",
13634
+ variant: "destructive"
13635
+ });
13636
+ } finally {
13637
+ progress.end();
13638
+ exportInFlightRef.current = false;
13639
+ }
13640
+ }, [layers, ingestProgressStore, toast]);
13273
13641
  const handleLoadLayerGeoJSON = react.useCallback((layerId) => {
13274
13642
  const input = fileInputRef.current;
13275
13643
  if (!input) return;
@@ -13284,7 +13652,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13284
13652
  input.dataset.createNewLayer = "true";
13285
13653
  input.click();
13286
13654
  }, []);
13287
- const buildEnrichedGeoJSON = react.useCallback(() => {
13655
+ const buildEnrichedExport = react.useCallback(() => {
13288
13656
  const allFeatures = [];
13289
13657
  const layerStates = [];
13290
13658
  layers.forEach((layer, idx) => {
@@ -13309,7 +13677,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13309
13677
  const { id: _id, featureIds: _fids, hasAltitudeData: _alt, ...persistable } = layer;
13310
13678
  layerStates.push({ index: idx, ...persistable });
13311
13679
  });
13312
- const cleanedFeatures = stripInternalProperties(allFeatures, ENRICHED_EXPORT_KEEP_KEYS);
13680
+ const rawCount = allFeatures.length;
13313
13681
  let viewport;
13314
13682
  if (map.current && isMapLoaded) {
13315
13683
  const c = map.current.getCenter();
@@ -13325,17 +13693,42 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13325
13693
  ...hostState
13326
13694
  };
13327
13695
  return {
13328
- type: "FeatureCollection",
13329
- features: [...cleanedFeatures, ...extraFeatures],
13330
- "octostar:map": octostarMap
13696
+ collection: {
13697
+ type: "FeatureCollection",
13698
+ features: [...allFeatures, ...extraFeatures],
13699
+ "octostar:map": octostarMap
13700
+ },
13701
+ mapFeature: (feature, index) => index < rawCount ? stripInternalPropertiesFromFeature(feature, ENRICHED_EXPORT_KEEP_KEYS) : feature
13331
13702
  };
13332
13703
  }, [layers, isMapLoaded, getAdditionalSaveState]);
13333
- const handleSaveAllGeoJSON = react.useCallback(() => {
13334
- if (!draw.current) return;
13335
- const geojson = buildEnrichedGeoJSON();
13336
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
13337
- downloadBlob(blob, "map_export.geojson");
13338
- }, [buildEnrichedGeoJSON]);
13704
+ const buildEnrichedGeoJSON = react.useCallback(() => {
13705
+ const { collection, mapFeature } = buildEnrichedExport();
13706
+ return { ...collection, features: collection.features.map(mapFeature) };
13707
+ }, [buildEnrichedExport]);
13708
+ const handleSaveAllGeoJSON = react.useCallback(async () => {
13709
+ if (!draw.current || exportInFlightRef.current) return;
13710
+ const { collection, mapFeature } = buildEnrichedExport();
13711
+ exportInFlightRef.current = true;
13712
+ const progress = ingestProgressStore.begin("map_export.geojson", { verb: "Preparing download" });
13713
+ progress.setTotal(collection.features.length);
13714
+ try {
13715
+ const parts = await featureCollectionBlobPartsAsync(collection, {
13716
+ mapFeature,
13717
+ onProgress: (done) => progress.update(done)
13718
+ });
13719
+ downloadBlob(new Blob(parts, { type: "application/geo+json" }), "map_export.geojson");
13720
+ } catch (error) {
13721
+ console.error("Failed to export the map as GeoJSON:", error);
13722
+ toast({
13723
+ title: "Export failed",
13724
+ description: error instanceof Error ? error.message : "Could not prepare the download",
13725
+ variant: "destructive"
13726
+ });
13727
+ } finally {
13728
+ progress.end();
13729
+ exportInFlightRef.current = false;
13730
+ }
13731
+ }, [buildEnrichedExport, ingestProgressStore, toast]);
13339
13732
  const handleSearchAndAddToNewLayer = react.useCallback(async () => {
13340
13733
  if (!onSearchEngineRequest || !map.current || !draw.current) return;
13341
13734
  const mapInstance = map.current;
@@ -13368,10 +13761,17 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13368
13761
  });
13369
13762
  if (result && result.features && result.features.length > 0) {
13370
13763
  saveStateForUndo();
13764
+ const activeId = activeEditingLayerIdRef.current;
13765
+ const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13766
+ const existingInActive = activeLayer ? countExisting(activeLayer) : 0;
13767
+ const capped = capFeatures(result.features, {
13768
+ max: featureCapRef.current,
13769
+ existing: existingInActive
13770
+ });
13371
13771
  const addedIds = [];
13372
13772
  isApiAddingRef.current = true;
13373
13773
  try {
13374
- result.features.forEach((f) => {
13774
+ capped.features.forEach((f) => {
13375
13775
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
13376
13776
  const normalizedFeature = {
13377
13777
  ...f,
@@ -13387,17 +13787,19 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13387
13787
  } finally {
13388
13788
  isApiAddingRef.current = false;
13389
13789
  }
13390
- const activeId = activeEditingLayerIdRef.current;
13391
- const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13790
+ let targetLayerId;
13791
+ let targetLayerName;
13392
13792
  if (activeLayer) {
13393
13793
  activeLayer.featureIds = [...activeLayer.featureIds, ...addedIds];
13394
13794
  setLayers([...layersRef.current]);
13795
+ targetLayerId = activeLayer.id;
13796
+ targetLayerName = activeLayer.name;
13395
13797
  toast({
13396
13798
  title: "Features added",
13397
- description: `Added ${result.features.length} features to "${activeLayer.name}"`
13799
+ description: `Added ${addedIds.length} features to "${activeLayer.name}"`
13398
13800
  });
13399
13801
  } else {
13400
- const layerName = `${result.features.length} workspace features`;
13802
+ const layerName = `${addedIds.length} workspace features`;
13401
13803
  const newLayerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13402
13804
  const newLayer = {
13403
13805
  id: newLayerId,
@@ -13408,9 +13810,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13408
13810
  layersRef.current = [...layersRef.current, newLayer];
13409
13811
  setLayers(layersRef.current);
13410
13812
  setActiveEditingLayerId(newLayerId);
13813
+ targetLayerId = newLayerId;
13814
+ targetLayerName = layerName;
13411
13815
  toast({
13412
13816
  title: "Layer created",
13413
- description: `Added ${result.features.length} features to "${layerName}"`
13817
+ description: `Added ${addedIds.length} features to "${layerName}"`
13818
+ });
13819
+ }
13820
+ if (capped.dropped > 0) {
13821
+ notifyFeatureCap({
13822
+ layerId: targetLayerId,
13823
+ layerName: targetLayerName,
13824
+ kept: addedIds.length,
13825
+ dropped: capped.dropped,
13826
+ sourceCount: capped.sourceCount,
13827
+ max: featureCapRef.current,
13828
+ source: "search",
13829
+ existing: existingInActive
13414
13830
  });
13415
13831
  }
13416
13832
  updateFeatureCount();
@@ -13424,7 +13840,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13424
13840
  variant: "destructive"
13425
13841
  });
13426
13842
  }
13427
- }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
13843
+ }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast, notifyFeatureCap]);
13428
13844
  const restoreEnrichedGeoJSON = react.useCallback((enriched) => {
13429
13845
  var _a;
13430
13846
  const mapState = enriched["octostar:map"];
@@ -13447,9 +13863,22 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13447
13863
  });
13448
13864
  const sortedLayers = [...mapState.layers].sort((a, b) => a.index - b.index);
13449
13865
  const newLayers = [];
13866
+ let restoreDropped = 0;
13867
+ let restoreSourceCount = 0;
13868
+ let restoreKept = 0;
13869
+ let truncatedLayerCount = 0;
13870
+ let firstTruncatedLayer = "";
13450
13871
  for (const ls of sortedLayers) {
13451
13872
  if (((_a = ls.metadata) == null ? void 0 : _a.dataViewing) === true) continue;
13452
- const rawFeatures = featuresByIndex.get(ls.index) ?? [];
13873
+ const capped = capFeatures(featuresByIndex.get(ls.index) ?? [], { max: featureCapRef.current });
13874
+ const rawFeatures = capped.features;
13875
+ if (capped.dropped > 0) {
13876
+ restoreDropped += capped.dropped;
13877
+ restoreSourceCount += capped.sourceCount;
13878
+ restoreKept += rawFeatures.length;
13879
+ truncatedLayerCount += 1;
13880
+ if (!firstTruncatedLayer) firstTruncatedLayer = ls.name;
13881
+ }
13453
13882
  const normalized = rawFeatures.map((f) => {
13454
13883
  const cleanProps = Object.fromEntries(
13455
13884
  Object.entries(f.properties || {}).filter(([k]) => !k.startsWith("_"))
@@ -13511,7 +13940,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13511
13940
  title: "Map restored",
13512
13941
  description: `Restored ${newLayers.length} layers with ${totalFeatures} features`
13513
13942
  });
13514
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast]);
13943
+ if (restoreDropped > 0) {
13944
+ notifyFeatureCap({
13945
+ layerName: firstTruncatedLayer,
13946
+ kept: restoreKept,
13947
+ dropped: restoreDropped,
13948
+ sourceCount: restoreSourceCount,
13949
+ max: featureCapRef.current,
13950
+ source: "restore",
13951
+ layerCount: truncatedLayerCount
13952
+ });
13953
+ }
13954
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast, notifyFeatureCap]);
13515
13955
  restoreEnrichedGeoJSONRef.current = restoreEnrichedGeoJSON;
13516
13956
  const handleWorkspaceLoad = react.useCallback(async () => {
13517
13957
  if (!onWorkspaceLoad) return;
@@ -13524,12 +13964,24 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13524
13964
  }
13525
13965
  saveStateForUndo();
13526
13966
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13527
- const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
13967
+ const layerName = "Loaded from workspace";
13968
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad", { max: featureCapRef.current });
13969
+ if (prepared.dropped > 0) {
13970
+ notifyFeatureCap({
13971
+ layerId,
13972
+ layerName,
13973
+ kept: prepared.features.length,
13974
+ dropped: prepared.dropped,
13975
+ sourceCount: prepared.sourceCount,
13976
+ max: featureCapRef.current,
13977
+ source: "workspace"
13978
+ });
13979
+ }
13528
13980
  readOnlyFeatures.current.set(layerId, prepared.features);
13529
13981
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
13530
13982
  const newLayer = {
13531
13983
  id: layerId,
13532
- name: "Loaded from workspace",
13984
+ name: layerName,
13533
13985
  visible: true,
13534
13986
  featureIds: prepared.featureIds,
13535
13987
  readOnly: true
@@ -13627,20 +14079,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13627
14079
  duration: 1e3
13628
14080
  });
13629
14081
  }, [layers, toast]);
13630
- const [ingestProgressStore] = react.useState(createIngestProgressStore);
13631
14082
  const ingestWithProgress = react.useCallback(async (label, input, options) => {
13632
14083
  const progress = ingestProgressStore.begin(label);
13633
14084
  try {
13634
- return await getSharedIngestClient().ingest(input, options, {
13635
- onHead: (summary) => progress.setTotal(summary.featureCount),
13636
- onProgress: (received) => progress.update(received)
13637
- });
14085
+ return await getSharedIngestClient().ingest(
14086
+ input,
14087
+ { ...options, maxFeatures: featureCapRef.current },
14088
+ {
14089
+ onHead: (summary) => progress.setTotal(summary.featureCount),
14090
+ onProgress: (received) => progress.update(received)
14091
+ }
14092
+ );
13638
14093
  } finally {
13639
14094
  progress.end();
13640
14095
  }
13641
14096
  }, [ingestProgressStore]);
13642
14097
  const loadGeoJSONFile = react.useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
13643
- var _a;
14098
+ var _a, _b, _c;
13644
14099
  let result;
13645
14100
  try {
13646
14101
  result = await ingestWithProgress(file.name, file, {
@@ -13690,7 +14145,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13690
14145
  data: { type: "FeatureCollection", features: normalizedFeatures },
13691
14146
  file,
13692
14147
  reprojected,
13693
- sourceCRS: sourceCRS ?? void 0
14148
+ sourceCRS: sourceCRS ?? void 0,
14149
+ ...result.truncated && { truncated: result.truncated }
13694
14150
  }) === true) {
13695
14151
  return;
13696
14152
  }
@@ -13710,6 +14166,16 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13710
14166
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13711
14167
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
13712
14168
  newLayer.featureIds = addedIds;
14169
+ if (result.truncated) {
14170
+ notifyFeatureCap(
14171
+ truncationToCapInfo(result.truncated, {
14172
+ layerId,
14173
+ layerName: newLayer.name,
14174
+ kept: normalizedFeatures.length,
14175
+ source: "file"
14176
+ })
14177
+ );
14178
+ }
13713
14179
  setLayers((prev) => [...prev, newLayer]);
13714
14180
  updateFeatureCount();
13715
14181
  scheduleTimelineUpdate();
@@ -13753,6 +14219,25 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13753
14219
  return;
13754
14220
  }
13755
14221
  const targetId = targetLayer.id;
14222
+ const existingInTarget = countExisting(targetLayer);
14223
+ const appendCapped = capFeatures(normalizedFeatures, {
14224
+ max: featureCapRef.current,
14225
+ existing: existingInTarget
14226
+ });
14227
+ const appendFeatures = appendCapped.features;
14228
+ const totalDropped = (((_b = result.truncated) == null ? void 0 : _b.droppedCount) ?? 0) + appendCapped.dropped;
14229
+ if (totalDropped > 0) {
14230
+ notifyFeatureCap({
14231
+ layerId: targetId,
14232
+ layerName: targetLayer.name,
14233
+ kept: appendFeatures.length,
14234
+ dropped: totalDropped,
14235
+ sourceCount: ((_c = result.truncated) == null ? void 0 : _c.sourceFeatureCount) ?? appendCapped.sourceCount,
14236
+ max: featureCapRef.current,
14237
+ source: "file",
14238
+ existing: existingInTarget
14239
+ });
14240
+ }
13756
14241
  const withLayerMetadata = (l, addedIds) => ({
13757
14242
  ...l,
13758
14243
  featureIds: [...l.featureIds, ...addedIds],
@@ -13761,7 +14246,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13761
14246
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13762
14247
  });
13763
14248
  if (targetLayer.readOnly) {
13764
- const addedFeatures = normalizedFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
14249
+ const addedFeatures = appendFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
13765
14250
  const addedIds = addedFeatures.map((f) => String(f.id));
13766
14251
  const existing = readOnlyFeatures.current.get(targetId) || [];
13767
14252
  readOnlyFeatures.current.set(targetId, [...existing, ...addedFeatures]);
@@ -13775,7 +14260,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13775
14260
  const addedIds = [];
13776
14261
  isApiAddingRef.current = true;
13777
14262
  try {
13778
- normalizedFeatures.forEach((f) => {
14263
+ appendFeatures.forEach((f) => {
13779
14264
  const ids = draw.current.add(f);
13780
14265
  addedIds.push(ids[0]);
13781
14266
  });
@@ -13784,9 +14269,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13784
14269
  }
13785
14270
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13786
14271
  } else {
13787
- const addedIds = normalizedFeatures.map((f) => String(f.id));
14272
+ const addedIds = appendFeatures.map((f) => String(f.id));
13788
14273
  const existing = hiddenFeatures.current.get(targetId) || [];
13789
- hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
14274
+ hiddenFeatures.current.set(targetId, [...existing, ...appendFeatures]);
13790
14275
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13791
14276
  }
13792
14277
  updateFeatureCount();
@@ -13795,9 +14280,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13795
14280
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
13796
14281
  toast({
13797
14282
  title: "GeoJSON loaded",
13798
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
14283
+ description: `Added ${appendFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
13799
14284
  });
13800
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14285
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13801
14286
  const handleFileChange = react.useCallback((e) => {
13802
14287
  var _a;
13803
14288
  const file = (_a = e.target.files) == null ? void 0 : _a[0];
@@ -13859,6 +14344,16 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13859
14344
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13860
14345
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
13861
14346
  newLayer.featureIds = addedIds;
14347
+ if (result.truncated) {
14348
+ notifyFeatureCap(
14349
+ truncationToCapInfo(result.truncated, {
14350
+ layerId,
14351
+ layerName: newLayer.name,
14352
+ kept: normalizedFeatures.length,
14353
+ source: "drop"
14354
+ })
14355
+ );
14356
+ }
13862
14357
  const nextLayers = [...layersRef.current, newLayer];
13863
14358
  layersRef.current = nextLayers;
13864
14359
  setLayers(nextLayers);
@@ -13881,7 +14376,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13881
14376
  title: "Layer added",
13882
14377
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
13883
14378
  });
13884
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14379
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13885
14380
  const handleDropGeoJSON = react.useCallback((name, data) => {
13886
14381
  void ingestDroppedLayer(name, data);
13887
14382
  }, [ingestDroppedLayer]);
@@ -15871,6 +16366,7 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
15871
16366
  exports.ActionPanel = ActionPanel;
15872
16367
  exports.ClusterPieManager = ClusterPieManager;
15873
16368
  exports.ColorPickerPopover = ColorPickerPopover;
16369
+ exports.DEFAULT_MAX_FEATURES_PER_LAYER = DEFAULT_MAX_FEATURES_PER_LAYER;
15874
16370
  exports.DebugSidebar = DebugSidebar;
15875
16371
  exports.DrawingToolbar = DrawingToolbar;
15876
16372
  exports.INTERNAL_PROPERTY_KEYS = INTERNAL_PROPERTY_KEYS;
@@ -15889,6 +16385,7 @@ exports.Timebar = Timebar;
15889
16385
  exports.TimebarToggle = TimebarToggle;
15890
16386
  exports.cn = cn;
15891
16387
  exports.createClusterPieManager = createClusterPieManager;
16388
+ exports.featureCollectionBlobPartsAsync = featureCollectionBlobPartsAsync;
15892
16389
  exports.getIconEmoji = getIconEmoji;
15893
16390
  exports.isFeatureInRange = isFeatureInRange;
15894
16391
  exports.isInternalProperty = isInternalProperty;