@octostar/map-component 0.2.18 → 0.2.19

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.
package/dist/index.mjs CHANGED
@@ -65,38 +65,85 @@ function hasAltitudeData(feature) {
65
65
  }
66
66
  return false;
67
67
  }
68
+ function yieldToMain() {
69
+ const scheduler = globalThis.scheduler;
70
+ if (typeof (scheduler == null ? void 0 : scheduler.yield) === "function") {
71
+ return scheduler.yield();
72
+ }
73
+ const channelCtor = globalThis.MessageChannel;
74
+ if (typeof channelCtor === "function") {
75
+ return new Promise((resolve) => {
76
+ const channel = new channelCtor();
77
+ channel.port1.onmessage = () => {
78
+ channel.port1.close();
79
+ resolve();
80
+ };
81
+ channel.port2.postMessage(void 0);
82
+ });
83
+ }
84
+ return new Promise((resolve) => setTimeout(resolve, 0));
85
+ }
68
86
  const PRETTY_EXPORT_MAX_FEATURES = 1e4;
69
87
  const TARGET_PART_CHARS = 8 * 1024 * 1024;
70
- function featureCollectionBlobParts(collection, options) {
71
- const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
72
- if (collection.features.length <= prettyMax) {
73
- return [JSON.stringify(collection, null, 2)];
74
- }
75
- const targetChars = TARGET_PART_CHARS;
76
- const { features, ...rest } = collection;
77
- const head = JSON.stringify(rest);
88
+ function createBlobPartCoalescer(targetChars) {
78
89
  const parts = [];
79
90
  let pending = [];
80
91
  let pendingChars = 0;
81
- const push = (piece) => {
82
- pending.push(piece);
83
- pendingChars += piece.length;
84
- if (pendingChars >= targetChars) {
85
- parts.push(pending.join(""));
86
- pending = [];
87
- pendingChars = 0;
92
+ return {
93
+ push(piece) {
94
+ pending.push(piece);
95
+ pendingChars += piece.length;
96
+ if (pendingChars >= targetChars) {
97
+ parts.push(pending.join(""));
98
+ pending = [];
99
+ pendingChars = 0;
100
+ }
101
+ },
102
+ finish() {
103
+ if (pending.length > 0) parts.push(pending.join(""));
104
+ return parts;
88
105
  }
89
106
  };
90
- push(head.slice(0, -1));
91
- push(head.length > 2 ? ',"features":[' : '"features":[');
107
+ }
108
+ function pushCollectionHead(coalescer, rest) {
109
+ const head = JSON.stringify(rest);
110
+ coalescer.push(head.slice(0, -1));
111
+ coalescer.push(head.length > 2 ? ',"features":[' : '"features":[');
112
+ }
113
+ function serializeFeatureAt(feature, index) {
114
+ return index === 0 ? JSON.stringify(feature) : "," + JSON.stringify(feature);
115
+ }
116
+ const DEFAULT_SLICE_BUDGET_MS = 12;
117
+ async function featureCollectionBlobPartsAsync(collection, options) {
118
+ var _a, _b, _c;
119
+ const prettyMax = (options == null ? void 0 : options.prettyMaxFeatures) ?? PRETTY_EXPORT_MAX_FEATURES;
120
+ const mapFeature = options == null ? void 0 : options.mapFeature;
121
+ const total = collection.features.length;
122
+ if (total <= prettyMax) {
123
+ const mapped = mapFeature ? { ...collection, features: collection.features.map(mapFeature) } : collection;
124
+ (_a = options == null ? void 0 : options.onProgress) == null ? void 0 : _a.call(options, total, total);
125
+ return [JSON.stringify(mapped, null, 2)];
126
+ }
127
+ const { features, ...rest } = collection;
128
+ const coalescer = createBlobPartCoalescer((options == null ? void 0 : options.targetPartChars) ?? TARGET_PART_CHARS);
129
+ const yieldFn = (options == null ? void 0 : options.yieldFn) ?? yieldToMain;
130
+ const budget = (options == null ? void 0 : options.sliceBudgetMs) ?? DEFAULT_SLICE_BUDGET_MS;
131
+ pushCollectionHead(coalescer, rest);
132
+ let sliceStart = performance.now();
92
133
  for (let i = 0; i < features.length; i++) {
93
- push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
134
+ const feature = mapFeature ? mapFeature(features[i], i) : features[i];
135
+ coalescer.push(serializeFeatureAt(feature, i));
136
+ if (performance.now() - sliceStart >= budget) {
137
+ (_b = options == null ? void 0 : options.onProgress) == null ? void 0 : _b.call(options, i + 1, total);
138
+ await yieldFn();
139
+ sliceStart = performance.now();
140
+ }
94
141
  }
95
- push("]}");
96
- if (pending.length > 0) parts.push(pending.join(""));
97
- return parts;
142
+ coalescer.push("]}");
143
+ (_c = options == null ? void 0 : options.onProgress) == null ? void 0 : _c.call(options, total, total);
144
+ return coalescer.finish();
98
145
  }
99
- const ingestWorkerSource = '"use strict";(()=>{function p(e){let t=e.crs?.properties?.name,n=null;if(t){let r=t.match(/EPSG::?(\\d+)/i);r&&(n=`EPSG:${r[1]}`)}if(!n&&e.features.length>0){let r=w(e.features[0].geometry);if(r){let[s,a]=r;if(Math.abs(s)<=180&&Math.abs(a)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:n,needsReprojection:n!==null&&n!=="EPSG:4326"}}function w(e){if(!e)return null;switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":return e.coordinates[0];case"MultiLineString":case"Polygon":return e.coordinates[0]?.[0];case"MultiPolygon":return e.coordinates[0]?.[0]?.[0];default:return null}}function S(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(n=>n.length>=3&&n[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(n=>n.some(r=>r.length>=3&&r[2]!==0)):!1}function i(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function b(e){return!!(e.startDate||e.startdate||e.start_date||e.start_time||e.date||e.timestamp||e.flightDate||e.time||e.datetime||e.endDate||e.enddate||e.end_date||e.end_time)}function I(e){let t=i(e.startDate)||i(e.startdate)||i(e.start_date)||i(e.start_time)||i(e.date)||i(e.timestamp)||i(e.flightDate)||i(e.time)||i(e.datetime),n=i(e.endDate)||i(e.enddate)||i(e.end_date)||i(e.end_time);return t&&n&&n<t&&([t,n]=[n,t]),{startDate:t,endDate:n}}function h(e){return"kind"in e&&e.kind==="ack"}function J(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function D(e,t,n){switch(n.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${n.layerId}-f${t}`;case"uuid-fallback":return e.id?String(e.id):J()}}function C(e,t){if(Array.isArray(e)){if(typeof e[0]=="number"){let n=e[0],r=e[1];t[0]=Math.min(t[0],n),t[1]=Math.min(t[1],r),t[2]=Math.max(t[2],n),t[3]=Math.max(t[3],r);return}for(let n of e)C(n,t)}}function R(e,t){if(e){if(e.type==="GeometryCollection"){for(let n of e.geometries)R(n,t);return}C(e.coordinates,t)}}function M(e){let t=[1/0,1/0,-1/0,-1/0];for(let n of e)R(n.geometry,t);return t.every(n=>isFinite(n))?t:null}function x(e,t){let n;if(e.type==="text")try{n=JSON.parse(e.text)}catch(d){return{kind:"error",code:"parse-error",message:d instanceof Error?d.message:"Invalid file"}}else n=e.data;if(n&&n.type==="Feature"&&(n={type:"FeatureCollection",features:[n]}),!n||n.type!=="FeatureCollection"||!Array.isArray(n.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(t.emptyIsError&&n.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(n["octostar:map"])return{kind:"enriched",data:n};let{sourceCRS:r,needsReprojection:s}=p(n),a=!1,o=!1,u=[];n.features.forEach((d,G)=>{let m=D(d,G,t);!o&&S(d)&&(o=!0);let g=d.properties||{};if(!b(g)){u.push(t.idStrategy==="preserve"?d:{...d,id:m});return}let{startDate:y,endDate:k}=I(g);(y||k)&&(a=!0),u.push({...d,...m!==void 0&&{id:m},properties:{...g,startDate:y?.toISOString()||null,endDate:k?.toISOString()||null}})});let c=n.properties?.layerMetadata;return{kind:"features",features:u,featureCount:u.length,bbox:M(u),hasTemporal:a,hasAltitude:o,reprojected:!1,sourceCRS:r,...s&&{needsReprojection:s},...c&&{layerMetadata:c}}}var O=5e3;function P(e,t){let n=Number.isNaN(t)?O:Math.max(1,Math.floor(t)),r=[];for(let s=0;s<e.length;s+=n)r.push(e.slice(s,s+n));return r}function f(e){if(e===void 0)return!1;if(typeof e=="number")return Number.isFinite(e)&&!Object.is(e,-0);if(e===null||typeof e!="object")return!0;if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(!f(e[t]))return!1;return!0}for(let t in e)if(!f(e[t]))return!1;return!0}function A(e){for(let t=0;t<e.length;t++)if(!f(e[t]))return e;try{return JSON.stringify(e)}catch{return e}}function E(e){let{kind:t,features:n,...r}=e;return r}async function N(e,t,n,r){let s;try{s=x(t,n)}catch(a){r.post({kind:"result",id:e,ok:!1,error:a instanceof Error?a.message:String(a)});return}if(s.kind!=="features"){r.post({kind:"result",id:e,ok:!0,result:s});return}try{let a=r.encode??A,o=P(s.features,r.chunkSize??O);r.post({kind:"head",id:e,summary:E(s)});let u=o.length>0?a(o[0]):null;for(let c=0;c<o.length;c++){let d=r.waitAck(c);r.post({kind:"chunk",id:e,seq:c,payload:u}),u=c+1<o.length?a(o[c+1]):null,await d}r.post({kind:"done",id:e,chunkCount:o.length})}catch(a){r.post({kind:"error",id:e,message:a instanceof Error?a.message:String(a)})}}var F=e=>self.postMessage(e),l=new Map;self.onmessage=async e=>{let t=e.data;if(h(t)){let o=`${t.id}:${t.seq}`,u=l.get(o);l.delete(o),u?.();return}let{id:n,source:r,options:s,tuning:a}=t;try{let o=r.type==="blob"?{type:"text",text:await r.blob.text()}:r;await N(n,o,s,{post:F,waitAck:u=>new Promise(c=>{l.set(`${n}:${u}`,c)}),...a?.chunkSize!==void 0&&{chunkSize:a.chunkSize},...a?.featureArrayChunks&&{encode:u=>u}})}catch(o){F({kind:"result",id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}finally{l.forEach((o,u)=>{u.startsWith(`${n}:`)&&l.delete(u)})}};})();\n';
146
+ 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=G(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 G(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 c(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=c(e.startDate)||c(e.startdate)||c(e.start_date)||c(e.start_time)||c(e.date)||c(e.timestamp)||c(e.flightDate)||c(e.time)||c(e.datetime),n=c(e.endDate)||c(e.enddate)||c(e.end_date)||c(e.end_time);return t&&n&&n<t&&([t,n]=[n,t]),{startDate:t,endDate:n}}function C(e){return"kind"in e&&e.kind==="ack"}function T(){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):T()}}function x(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)x(n,t)}}function R(e,t){if(e){if(e.type==="GeometryCollection"){for(let n of e.geometries)R(n,t);return}x(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(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}=S(n),a=b(n.features,{max:t.maxFeatures??1/0}),o=!1,u=!1,i=[];a.features.forEach((d,w)=>{let f=_(d,w,t);!u&&I(d)&&(u=!0);let g=d.properties||{};if(!h(g)){i.push(t.idStrategy==="preserve"?d:{...d,id:f});return}let{startDate:y,endDate:k}=F(g);(y||k)&&(o=!0),i.push({...d,...f!==void 0&&{id:f},properties:{...g,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 p(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(!p(e[t]))return!1;return!0}for(let t in e)if(!p(e[t]))return!1;return!0}function P(e){for(let t=0;t<e.length;t++)if(!p(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 A(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 E=e=>self.postMessage(e),l=new Map;self.onmessage=async e=>{let t=e.data;if(C(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 A(n,o,s,{post:E,waitAck:u=>new Promise(i=>{l.set(`${n}:${u}`,i)}),...a?.chunkSize!==void 0&&{chunkSize:a.chunkSize},...a?.featureArrayChunks&&{encode:u=>u}})}catch(o){E({kind:"result",id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}finally{l.forEach((o,u)=>{u.startsWith(`${n}:`)&&l.delete(u)})}};})();\n';
100
147
  proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
101
148
  proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
102
149
  proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
@@ -137,6 +184,55 @@ function reprojectGeometry(geometry, fromCRS) {
137
184
  coordinates: reprojectCoords(geomWithCoords.coordinates)
138
185
  };
139
186
  }
187
+ const DEFAULT_MAX_FEATURES_PER_LAYER = 2e5;
188
+ function resolveFeatureCap(value) {
189
+ if (value === void 0) return DEFAULT_MAX_FEATURES_PER_LAYER;
190
+ if (value === Infinity) return Infinity;
191
+ if (!Number.isFinite(value) || value < 1) {
192
+ console.warn(
193
+ `[map-editor] Ignoring maxFeaturesPerLayer=${String(value)} — expected a number >= 1 or Infinity. Falling back to ${DEFAULT_MAX_FEATURES_PER_LAYER}.`
194
+ );
195
+ return DEFAULT_MAX_FEATURES_PER_LAYER;
196
+ }
197
+ return Math.floor(value);
198
+ }
199
+ function capFeatures(features, options) {
200
+ const sourceCount = features.length;
201
+ const room = Math.max(0, options.max - (options.existing ?? 0));
202
+ if (sourceCount <= room) {
203
+ return { features, dropped: 0, sourceCount };
204
+ }
205
+ return {
206
+ features: features.slice(0, room),
207
+ dropped: sourceCount - room,
208
+ sourceCount
209
+ };
210
+ }
211
+ function formatCount(value) {
212
+ return value.toLocaleString("en-US");
213
+ }
214
+ function formatFeatureCapToast(info) {
215
+ const isRestore = info.source === "restore";
216
+ const variant = isRestore ? "destructive" : "default";
217
+ const withNote = (text) => isRestore ? `${text} Re-saving this map will persist only the loaded features.` : text;
218
+ const layerCount = info.layerCount ?? 1;
219
+ if (layerCount > 1) {
220
+ return {
221
+ title: "Feature limit reached",
222
+ description: withNote(
223
+ `${formatCount(layerCount)} layers were larger than the ${formatCount(info.max)}-feature limit; ${formatCount(info.dropped)} features in total were not loaded.`
224
+ ),
225
+ variant
226
+ };
227
+ }
228
+ return {
229
+ title: "Feature limit reached",
230
+ description: withNote(
231
+ `Only the first ${formatCount(info.kept)} of ${formatCount(info.sourceCount)} features were added to "${info.layerName}"; ${formatCount(info.dropped)} were skipped (per-layer limit).`
232
+ ),
233
+ variant
234
+ };
235
+ }
140
236
  function parseDate(value) {
141
237
  if (!value) return null;
142
238
  if (value instanceof Date) return value;
@@ -230,10 +326,11 @@ function runIngestPipeline(source, options) {
230
326
  return { kind: "enriched", data };
231
327
  }
232
328
  const { sourceCRS, needsReprojection } = detectSourceCRS(data);
329
+ const capped = capFeatures(data.features, { max: options.maxFeatures ?? Infinity });
233
330
  let hasTemporal = false;
234
331
  let hasAltitude = false;
235
332
  const features = [];
236
- data.features.forEach((f, index) => {
333
+ capped.features.forEach((f, index) => {
237
334
  const id = assignId(f, index, options);
238
335
  if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
239
336
  const props = f.properties || {};
@@ -268,7 +365,14 @@ function runIngestPipeline(source, options) {
268
365
  reprojected: false,
269
366
  sourceCRS,
270
367
  ...needsReprojection && { needsReprojection },
271
- ...layerMetadata && { layerMetadata }
368
+ ...layerMetadata && { layerMetadata },
369
+ ...capped.dropped > 0 && {
370
+ truncated: {
371
+ droppedCount: capped.dropped,
372
+ sourceFeatureCount: capped.sourceCount,
373
+ maxFeatures: options.maxFeatures
374
+ }
375
+ }
272
376
  };
273
377
  }
274
378
  function decodeChunkPayload(payload) {
@@ -588,9 +692,9 @@ function createIngestProgressStore() {
588
692
  listeners.forEach((listener) => listener());
589
693
  };
590
694
  return {
591
- begin(label) {
695
+ begin(label, options) {
592
696
  const id = nextId++;
593
- entries.set(id, { label, received: 0, total: null });
697
+ entries.set(id, { label, received: 0, total: null, ...(options == null ? void 0 : options.verb) && { verb: options.verb } });
594
698
  notify();
595
699
  return {
596
700
  setTotal(total) {
@@ -686,7 +790,8 @@ function IngestProgressOverlay({
686
790
  className: "rounded-md border bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-md",
687
791
  children: [
688
792
  /* @__PURE__ */ jsxs("span", { children: [
689
- "Importing ",
793
+ entry.verb ?? "Importing",
794
+ " ",
690
795
  entry.label,
691
796
  "…",
692
797
  entry.total !== null ? ` ${entry.received.toLocaleString()} / ${entry.total.toLocaleString()} features` : ""
@@ -1085,15 +1190,28 @@ function collectLayerFeatures(layer, sources) {
1085
1190
  if (readOnly) pushAll(features, readOnly);
1086
1191
  return features;
1087
1192
  }
1088
- function stripInternalProperties(features, keep) {
1089
- return features.map((f) => ({
1090
- ...f,
1193
+ function countLayerFeatures(layer, stores) {
1194
+ var _a;
1195
+ if (layer.readOnly) return ((_a = stores.readOnlyFeatures.get(layer.id)) == null ? void 0 : _a.length) ?? 0;
1196
+ const hidden = stores.hiddenFeatures.get(layer.id);
1197
+ if (!hidden || hidden.length === 0) return layer.featureIds.length;
1198
+ if (layer.featureIds.length === 0) return hidden.length;
1199
+ const ids = new Set(layer.featureIds);
1200
+ let count = layer.featureIds.length;
1201
+ for (const feature of hidden) {
1202
+ if (!ids.has(String(feature.id))) count++;
1203
+ }
1204
+ return count;
1205
+ }
1206
+ function stripInternalPropertiesFromFeature(feature, keep) {
1207
+ return {
1208
+ ...feature,
1091
1209
  properties: Object.fromEntries(
1092
- Object.entries(f.properties ?? {}).filter(
1210
+ Object.entries(feature.properties ?? {}).filter(
1093
1211
  ([key]) => !key.startsWith("_") || ((keep == null ? void 0 : keep.has(key)) ?? false)
1094
1212
  )
1095
1213
  )
1096
- }));
1214
+ };
1097
1215
  }
1098
1216
  const ToastContext = createContext(null);
1099
1217
  function useToast() {
@@ -6567,9 +6685,11 @@ function geometryEquals(a, b) {
6567
6685
  b.coordinates
6568
6686
  );
6569
6687
  }
6570
- function prepareFeaturesForLayer(input, caller) {
6688
+ function prepareFeaturesForLayer(input, caller, cap) {
6571
6689
  const logging = mapPerfLogEnabled();
6572
6690
  const started = logging ? performance.now() : 0;
6691
+ const capped = cap ? capFeatures(input, cap) : null;
6692
+ if (capped) input = capped.features;
6573
6693
  const count = input.length;
6574
6694
  const features = new Array(count);
6575
6695
  const featureIds = new Array(count);
@@ -6612,10 +6732,17 @@ function prepareFeaturesForLayer(input, caller) {
6612
6732
  withTemporalKeys: temporalCount,
6613
6733
  hasTemporal,
6614
6734
  reused,
6615
- copied: count - reused
6735
+ copied: count - reused,
6736
+ ...capped && capped.dropped > 0 && { dropped: capped.dropped }
6616
6737
  });
6617
6738
  }
6618
- return { features, featureIds, hasTemporal };
6739
+ return {
6740
+ features,
6741
+ featureIds,
6742
+ hasTemporal,
6743
+ dropped: (capped == null ? void 0 : capped.dropped) ?? 0,
6744
+ sourceCount: (capped == null ? void 0 : capped.sourceCount) ?? count
6745
+ };
6619
6746
  }
6620
6747
  function scanTemporalFeatures(features, resolveLayerId, out) {
6621
6748
  let foundTemporal = false;
@@ -7546,6 +7673,7 @@ function extract3DFlightPaths(features) {
7546
7673
  });
7547
7674
  return paths;
7548
7675
  }
7676
+ const CAP_NOTICE_INTERVAL_MS = 5e3;
7549
7677
  const DEFAULT_LOCAL_GLYPHS_URL = "/fonts/{fontstack}/{range}.pbf";
7550
7678
  function basemapInsertAnchor(map) {
7551
7679
  if (map.getLayer("satellite-layer")) return "satellite-layer";
@@ -7669,6 +7797,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7669
7797
  enableProperties = true,
7670
7798
  autoOpenProperties = true,
7671
7799
  toastProvider,
7800
+ maxFeaturesPerLayer,
7801
+ onFeaturesTruncated,
7672
7802
  customGlobalMenuItems,
7673
7803
  extraLayerToolbarButtons,
7674
7804
  extraNewLayerButtons,
@@ -7776,6 +7906,31 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7776
7906
  const timelineStore = useStore(timelineStoreApi);
7777
7907
  const { toast: internalToast } = useToast();
7778
7908
  const toast = toastProvider ?? internalToast;
7909
+ const featureCap = useMemo(() => resolveFeatureCap(maxFeaturesPerLayer), [maxFeaturesPerLayer]);
7910
+ const featureCapRef = useRef(featureCap);
7911
+ featureCapRef.current = featureCap;
7912
+ const capNoticeRef = useRef(/* @__PURE__ */ new Map());
7913
+ const notifyFeatureCap = useCallback((info) => {
7914
+ if (onFeaturesTruncated) {
7915
+ onFeaturesTruncated(info);
7916
+ return;
7917
+ }
7918
+ if (info.source !== "restore") {
7919
+ const key = info.layerId ?? info.layerName;
7920
+ const now = Date.now();
7921
+ const last = capNoticeRef.current.get(key);
7922
+ if (last != null && now - last < CAP_NOTICE_INTERVAL_MS) return;
7923
+ capNoticeRef.current.set(key, now);
7924
+ }
7925
+ toast(formatFeatureCapToast(info));
7926
+ }, [onFeaturesTruncated, toast]);
7927
+ const countExisting = useCallback(
7928
+ (layer) => countLayerFeatures(layer, {
7929
+ hiddenFeatures: hiddenFeatures.current,
7930
+ readOnlyFeatures: readOnlyFeatures.current
7931
+ }),
7932
+ []
7933
+ );
7779
7934
  useEffect(() => {
7780
7935
  const handleError = (event) => {
7781
7936
  const msg = event.message || "";
@@ -10463,16 +10618,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10463
10618
  clusterConfig: options == null ? void 0 : options.clusterConfig,
10464
10619
  altitudeDisplayMode: options == null ? void 0 : options.altitudeDisplayMode
10465
10620
  };
10621
+ let addedFeatures = (geojson == null ? void 0 : geojson.features) ?? [];
10622
+ let capDropped = 0;
10466
10623
  if (geojson) {
10624
+ const max = featureCapRef.current;
10467
10625
  if (options == null ? void 0 : options.readOnly) {
10468
- const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
10626
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer", { max });
10469
10627
  readOnlyFeatures.current.set(layerId, prepared.features);
10470
10628
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10471
10629
  newLayer.featureIds = prepared.featureIds;
10630
+ addedFeatures = prepared.features;
10631
+ capDropped = prepared.dropped;
10472
10632
  } else if (draw.current) {
10633
+ const capped = capFeatures(geojson.features, { max });
10473
10634
  isApiAddingRef.current = true;
10474
10635
  try {
10475
- const addedIds = geojson.features.map((f) => {
10636
+ const addedIds = capped.features.map((f) => {
10476
10637
  const ids = draw.current.add(f);
10477
10638
  return ids[0];
10478
10639
  });
@@ -10480,8 +10641,21 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10480
10641
  } finally {
10481
10642
  isApiAddingRef.current = false;
10482
10643
  }
10644
+ addedFeatures = capped.features;
10645
+ capDropped = capped.dropped;
10483
10646
  }
10484
10647
  }
10648
+ if (capDropped > 0) {
10649
+ notifyFeatureCap({
10650
+ layerId,
10651
+ layerName: name,
10652
+ kept: addedFeatures.length,
10653
+ dropped: capDropped,
10654
+ sourceCount: (geojson == null ? void 0 : geojson.features.length) ?? 0,
10655
+ max: featureCapRef.current,
10656
+ source: "api"
10657
+ });
10658
+ }
10485
10659
  if (newLayer.visible === false && !(options == null ? void 0 : options.readOnly) && draw.current && newLayer.featureIds.length > 0) {
10486
10660
  const features = newLayer.featureIds.map((id) => draw.current.get(id)).filter(Boolean);
10487
10661
  hiddenFeatures.current.set(layerId, features);
@@ -10499,9 +10673,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10499
10673
  updateFeatureCount();
10500
10674
  scheduleTimelineUpdate();
10501
10675
  scheduleSync();
10502
- if (!(options == null ? void 0 : options.skipFit) && geojson && geojson.features.length > 0 && map.current) {
10676
+ if (!(options == null ? void 0 : options.skipFit) && addedFeatures.length > 0 && map.current) {
10503
10677
  try {
10504
- const bbox = turf.bbox(geojson);
10678
+ const bbox = turf.bbox(
10679
+ capDropped > 0 ? { type: "FeatureCollection", features: addedFeatures } : geojson
10680
+ );
10505
10681
  if (bbox.every((v) => isFinite(v))) {
10506
10682
  map.current.fitBounds(
10507
10683
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -10594,7 +10770,21 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10594
10770
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
10595
10771
  if (layer.readOnly) {
10596
10772
  const existing = readOnlyFeatures.current.get(layerId) || [];
10597
- const prepared = prepareFeaturesForLayer(features, "addFeatures");
10773
+ const prepared = prepareFeaturesForLayer(features, "addFeatures", {
10774
+ max: featureCapRef.current,
10775
+ existing: existing.length
10776
+ });
10777
+ if (prepared.dropped > 0) {
10778
+ notifyFeatureCap({
10779
+ layerId,
10780
+ layerName: layer.name,
10781
+ kept: prepared.features.length,
10782
+ dropped: prepared.dropped,
10783
+ sourceCount: prepared.sourceCount,
10784
+ max: featureCapRef.current,
10785
+ source: "api"
10786
+ });
10787
+ }
10598
10788
  const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
10599
10789
  const combined = [...existing, ...prepared.features];
10600
10790
  readOnlyFeatures.current.set(layerId, combined);
@@ -10614,9 +10804,24 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10614
10804
  }
10615
10805
  if (!draw.current) return [];
10616
10806
  const addedIds = [];
10807
+ const cappedForDraw = capFeatures(features, {
10808
+ max: featureCapRef.current,
10809
+ existing: countExisting(layer)
10810
+ });
10811
+ if (cappedForDraw.dropped > 0) {
10812
+ notifyFeatureCap({
10813
+ layerId,
10814
+ layerName: layer.name,
10815
+ kept: cappedForDraw.features.length,
10816
+ dropped: cappedForDraw.dropped,
10817
+ sourceCount: cappedForDraw.sourceCount,
10818
+ max: featureCapRef.current,
10819
+ source: "api"
10820
+ });
10821
+ }
10617
10822
  isApiAddingRef.current = true;
10618
10823
  try {
10619
- features.forEach((f) => {
10824
+ cappedForDraw.features.forEach((f) => {
10620
10825
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10621
10826
  const normalizedFeature = {
10622
10827
  ...f,
@@ -10725,12 +10930,27 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10725
10930
  return { type: "FeatureCollection", features: cleanedFeatures };
10726
10931
  },
10727
10932
  importGeoJSON: (layerId, geojson) => {
10728
- const layer = layers.find((l) => l.id === layerId);
10933
+ const layer = layersRef.current.find((l) => l.id === layerId);
10729
10934
  if (!layer || !draw.current || !isMapLoaded) return [];
10730
10935
  const addedIds = [];
10936
+ const capped = capFeatures(geojson.features, {
10937
+ max: featureCapRef.current,
10938
+ existing: countExisting(layer)
10939
+ });
10940
+ if (capped.dropped > 0) {
10941
+ notifyFeatureCap({
10942
+ layerId,
10943
+ layerName: layer.name,
10944
+ kept: capped.features.length,
10945
+ dropped: capped.dropped,
10946
+ sourceCount: capped.sourceCount,
10947
+ max: featureCapRef.current,
10948
+ source: "api"
10949
+ });
10950
+ }
10731
10951
  isApiAddingRef.current = true;
10732
10952
  try {
10733
- geojson.features.forEach((f) => {
10953
+ capped.features.forEach((f) => {
10734
10954
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
10735
10955
  const normalizedFeature = {
10736
10956
  ...f,
@@ -10834,9 +11054,20 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10834
11054
  updateReadOnlyLayer: (layerId, features) => {
10835
11055
  const layer = layersRef.current.find((l) => l.id === layerId);
10836
11056
  if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
10837
- const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
11057
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer", { max: featureCapRef.current });
11058
+ if (prepared.dropped > 0) {
11059
+ notifyFeatureCap({
11060
+ layerId,
11061
+ layerName: layer.name,
11062
+ kept: prepared.features.length,
11063
+ dropped: prepared.dropped,
11064
+ sourceCount: prepared.sourceCount,
11065
+ max: featureCapRef.current,
11066
+ source: "api"
11067
+ });
11068
+ }
10838
11069
  readOnlyFeatures.current.set(layerId, prepared.features);
10839
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
11070
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10840
11071
  if (prepared.hasTemporal) {
10841
11072
  scheduleTimelineUpdate();
10842
11073
  }
@@ -10852,9 +11083,20 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10852
11083
  },
10853
11084
  setLayerData: (name, geojson, options) => {
10854
11085
  if (!isMapLoadedRef.current) return "";
10855
- const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
11086
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData", { max: featureCapRef.current });
10856
11087
  const newFeatureIds = prepared.featureIds;
10857
11088
  const layerId = `managed-${name}`;
11089
+ if (prepared.dropped > 0) {
11090
+ notifyFeatureCap({
11091
+ layerId,
11092
+ layerName: name,
11093
+ kept: prepared.features.length,
11094
+ dropped: prepared.dropped,
11095
+ sourceCount: prepared.sourceCount,
11096
+ max: featureCapRef.current,
11097
+ source: "api"
11098
+ });
11099
+ }
10858
11100
  readOnlyFeatures.current.set(layerId, prepared.features);
10859
11101
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
10860
11102
  const buildLayerObj = (existing) => {
@@ -10904,9 +11146,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10904
11146
  });
10905
11147
  updateFeatureCount();
10906
11148
  scheduleSync();
10907
- if ((options == null ? void 0 : options.fitPadding) != null && geojson.features.length > 0 && map.current) {
11149
+ if ((options == null ? void 0 : options.fitPadding) != null && prepared.features.length > 0 && map.current) {
10908
11150
  try {
10909
- const bbox = turf.bbox(geojson);
11151
+ const bbox = turf.bbox(
11152
+ prepared.dropped > 0 ? { type: "FeatureCollection", features: prepared.features } : geojson
11153
+ );
10910
11154
  if (bbox.every((v) => isFinite(v))) {
10911
11155
  map.current.fitBounds(
10912
11156
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -13221,9 +13465,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13221
13465
  source.setData({ type: "FeatureCollection", features });
13222
13466
  }
13223
13467
  }, [measurePoints, measureMode, isMapLoaded]);
13224
- const handleSaveLayerGeoJSON = useCallback((layerId) => {
13468
+ const [ingestProgressStore] = useState(createIngestProgressStore);
13469
+ const exportInFlightRef = useRef(false);
13470
+ const handleSaveLayerGeoJSON = useCallback(async (layerId) => {
13225
13471
  const layer = layers.find((l) => l.id === layerId);
13226
- if (!layer) return;
13472
+ if (!layer || exportInFlightRef.current) return;
13227
13473
  const features = collectLayerFeatures(layer, {
13228
13474
  getDrawFeature: (id) => {
13229
13475
  var _a;
@@ -13238,17 +13484,30 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13238
13484
  if (layer.traceConfig) layerMetadata.traceConfig = layer.traceConfig;
13239
13485
  if (layer.heatmapConfig) layerMetadata.heatmapConfig = layer.heatmapConfig;
13240
13486
  if (layer.visualConfig) layerMetadata.visualConfig = layer.visualConfig;
13241
- const cleanedFeatures = stripInternalProperties(features);
13242
13487
  const geojson = {
13243
13488
  type: "FeatureCollection",
13244
- features: cleanedFeatures,
13489
+ features,
13245
13490
  properties: {
13246
13491
  layerMetadata
13247
13492
  }
13248
13493
  };
13249
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
13250
- downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
13251
- }, [layers]);
13494
+ exportInFlightRef.current = true;
13495
+ const progress = ingestProgressStore.begin(layer.name, { verb: "Preparing download" });
13496
+ progress.setTotal(features.length);
13497
+ try {
13498
+ const parts = await featureCollectionBlobPartsAsync(geojson, {
13499
+ mapFeature: (f) => stripInternalPropertiesFromFeature(f),
13500
+ onProgress: (done) => progress.update(done)
13501
+ });
13502
+ downloadBlob(
13503
+ new Blob(parts, { type: "application/json" }),
13504
+ `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`
13505
+ );
13506
+ } finally {
13507
+ progress.end();
13508
+ exportInFlightRef.current = false;
13509
+ }
13510
+ }, [layers, ingestProgressStore]);
13252
13511
  const handleLoadLayerGeoJSON = useCallback((layerId) => {
13253
13512
  const input = fileInputRef.current;
13254
13513
  if (!input) return;
@@ -13263,7 +13522,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13263
13522
  input.dataset.createNewLayer = "true";
13264
13523
  input.click();
13265
13524
  }, []);
13266
- const buildEnrichedGeoJSON = useCallback(() => {
13525
+ const buildEnrichedExport = useCallback(() => {
13267
13526
  const allFeatures = [];
13268
13527
  const layerStates = [];
13269
13528
  layers.forEach((layer, idx) => {
@@ -13288,7 +13547,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13288
13547
  const { id: _id, featureIds: _fids, hasAltitudeData: _alt, ...persistable } = layer;
13289
13548
  layerStates.push({ index: idx, ...persistable });
13290
13549
  });
13291
- const cleanedFeatures = stripInternalProperties(allFeatures, ENRICHED_EXPORT_KEEP_KEYS);
13550
+ const rawCount = allFeatures.length;
13292
13551
  let viewport;
13293
13552
  if (map.current && isMapLoaded) {
13294
13553
  const c = map.current.getCenter();
@@ -13304,17 +13563,35 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13304
13563
  ...hostState
13305
13564
  };
13306
13565
  return {
13307
- type: "FeatureCollection",
13308
- features: [...cleanedFeatures, ...extraFeatures],
13309
- "octostar:map": octostarMap
13566
+ collection: {
13567
+ type: "FeatureCollection",
13568
+ features: [...allFeatures, ...extraFeatures],
13569
+ "octostar:map": octostarMap
13570
+ },
13571
+ mapFeature: (feature, index) => index < rawCount ? stripInternalPropertiesFromFeature(feature, ENRICHED_EXPORT_KEEP_KEYS) : feature
13310
13572
  };
13311
13573
  }, [layers, isMapLoaded, getAdditionalSaveState]);
13312
- const handleSaveAllGeoJSON = useCallback(() => {
13313
- if (!draw.current) return;
13314
- const geojson = buildEnrichedGeoJSON();
13315
- const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
13316
- downloadBlob(blob, "map_export.geojson");
13317
- }, [buildEnrichedGeoJSON]);
13574
+ const buildEnrichedGeoJSON = useCallback(() => {
13575
+ const { collection, mapFeature } = buildEnrichedExport();
13576
+ return { ...collection, features: collection.features.map(mapFeature) };
13577
+ }, [buildEnrichedExport]);
13578
+ const handleSaveAllGeoJSON = useCallback(async () => {
13579
+ if (!draw.current || exportInFlightRef.current) return;
13580
+ const { collection, mapFeature } = buildEnrichedExport();
13581
+ exportInFlightRef.current = true;
13582
+ const progress = ingestProgressStore.begin("map_export.geojson", { verb: "Preparing download" });
13583
+ progress.setTotal(collection.features.length);
13584
+ try {
13585
+ const parts = await featureCollectionBlobPartsAsync(collection, {
13586
+ mapFeature,
13587
+ onProgress: (done) => progress.update(done)
13588
+ });
13589
+ downloadBlob(new Blob(parts, { type: "application/geo+json" }), "map_export.geojson");
13590
+ } finally {
13591
+ progress.end();
13592
+ exportInFlightRef.current = false;
13593
+ }
13594
+ }, [buildEnrichedExport, ingestProgressStore]);
13318
13595
  const handleSearchAndAddToNewLayer = useCallback(async () => {
13319
13596
  if (!onSearchEngineRequest || !map.current || !draw.current) return;
13320
13597
  const mapInstance = map.current;
@@ -13347,10 +13624,16 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13347
13624
  });
13348
13625
  if (result && result.features && result.features.length > 0) {
13349
13626
  saveStateForUndo();
13627
+ const activeId = activeEditingLayerIdRef.current;
13628
+ const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13629
+ const capped = capFeatures(result.features, {
13630
+ max: featureCapRef.current,
13631
+ existing: activeLayer ? countExisting(activeLayer) : 0
13632
+ });
13350
13633
  const addedIds = [];
13351
13634
  isApiAddingRef.current = true;
13352
13635
  try {
13353
- result.features.forEach((f) => {
13636
+ capped.features.forEach((f) => {
13354
13637
  const { startDate, endDate } = normalizeTemporalProperties(f.properties || {});
13355
13638
  const normalizedFeature = {
13356
13639
  ...f,
@@ -13366,17 +13649,19 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13366
13649
  } finally {
13367
13650
  isApiAddingRef.current = false;
13368
13651
  }
13369
- const activeId = activeEditingLayerIdRef.current;
13370
- const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13652
+ let targetLayerId;
13653
+ let targetLayerName;
13371
13654
  if (activeLayer) {
13372
13655
  activeLayer.featureIds = [...activeLayer.featureIds, ...addedIds];
13373
13656
  setLayers([...layersRef.current]);
13657
+ targetLayerId = activeLayer.id;
13658
+ targetLayerName = activeLayer.name;
13374
13659
  toast({
13375
13660
  title: "Features added",
13376
- description: `Added ${result.features.length} features to "${activeLayer.name}"`
13661
+ description: `Added ${addedIds.length} features to "${activeLayer.name}"`
13377
13662
  });
13378
13663
  } else {
13379
- const layerName = `${result.features.length} workspace features`;
13664
+ const layerName = `${addedIds.length} workspace features`;
13380
13665
  const newLayerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13381
13666
  const newLayer = {
13382
13667
  id: newLayerId,
@@ -13387,9 +13672,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13387
13672
  layersRef.current = [...layersRef.current, newLayer];
13388
13673
  setLayers(layersRef.current);
13389
13674
  setActiveEditingLayerId(newLayerId);
13675
+ targetLayerId = newLayerId;
13676
+ targetLayerName = layerName;
13390
13677
  toast({
13391
13678
  title: "Layer created",
13392
- description: `Added ${result.features.length} features to "${layerName}"`
13679
+ description: `Added ${addedIds.length} features to "${layerName}"`
13680
+ });
13681
+ }
13682
+ if (capped.dropped > 0) {
13683
+ notifyFeatureCap({
13684
+ layerId: targetLayerId,
13685
+ layerName: targetLayerName,
13686
+ kept: addedIds.length,
13687
+ dropped: capped.dropped,
13688
+ sourceCount: capped.sourceCount,
13689
+ max: featureCapRef.current,
13690
+ source: "search"
13393
13691
  });
13394
13692
  }
13395
13693
  updateFeatureCount();
@@ -13403,7 +13701,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13403
13701
  variant: "destructive"
13404
13702
  });
13405
13703
  }
13406
- }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
13704
+ }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast, notifyFeatureCap]);
13407
13705
  const restoreEnrichedGeoJSON = useCallback((enriched) => {
13408
13706
  var _a;
13409
13707
  const mapState = enriched["octostar:map"];
@@ -13426,9 +13724,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13426
13724
  });
13427
13725
  const sortedLayers = [...mapState.layers].sort((a, b) => a.index - b.index);
13428
13726
  const newLayers = [];
13727
+ let restoreDropped = 0;
13728
+ let restoreSourceCount = 0;
13729
+ let restoreKept = 0;
13730
+ let truncatedLayerCount = 0;
13731
+ let firstTruncatedLayer = "";
13429
13732
  for (const ls of sortedLayers) {
13430
13733
  if (((_a = ls.metadata) == null ? void 0 : _a.dataViewing) === true) continue;
13431
- const rawFeatures = featuresByIndex.get(ls.index) ?? [];
13734
+ const capped = capFeatures(featuresByIndex.get(ls.index) ?? [], { max: featureCapRef.current });
13735
+ const rawFeatures = capped.features;
13736
+ if (capped.dropped > 0) {
13737
+ restoreDropped += capped.dropped;
13738
+ restoreSourceCount += capped.sourceCount;
13739
+ restoreKept += rawFeatures.length;
13740
+ truncatedLayerCount += 1;
13741
+ if (!firstTruncatedLayer) firstTruncatedLayer = ls.name;
13742
+ }
13432
13743
  const normalized = rawFeatures.map((f) => {
13433
13744
  const cleanProps = Object.fromEntries(
13434
13745
  Object.entries(f.properties || {}).filter(([k]) => !k.startsWith("_"))
@@ -13490,7 +13801,18 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13490
13801
  title: "Map restored",
13491
13802
  description: `Restored ${newLayers.length} layers with ${totalFeatures} features`
13492
13803
  });
13493
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast]);
13804
+ if (restoreDropped > 0) {
13805
+ notifyFeatureCap({
13806
+ layerName: firstTruncatedLayer,
13807
+ kept: restoreKept,
13808
+ dropped: restoreDropped,
13809
+ sourceCount: restoreSourceCount,
13810
+ max: featureCapRef.current,
13811
+ source: "restore",
13812
+ layerCount: truncatedLayerCount
13813
+ });
13814
+ }
13815
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast, notifyFeatureCap]);
13494
13816
  restoreEnrichedGeoJSONRef.current = restoreEnrichedGeoJSON;
13495
13817
  const handleWorkspaceLoad = useCallback(async () => {
13496
13818
  if (!onWorkspaceLoad) return;
@@ -13503,12 +13825,24 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13503
13825
  }
13504
13826
  saveStateForUndo();
13505
13827
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13506
- const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
13828
+ const layerName = "Loaded from workspace";
13829
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad", { max: featureCapRef.current });
13830
+ if (prepared.dropped > 0) {
13831
+ notifyFeatureCap({
13832
+ layerId,
13833
+ layerName,
13834
+ kept: prepared.features.length,
13835
+ dropped: prepared.dropped,
13836
+ sourceCount: prepared.sourceCount,
13837
+ max: featureCapRef.current,
13838
+ source: "workspace"
13839
+ });
13840
+ }
13507
13841
  readOnlyFeatures.current.set(layerId, prepared.features);
13508
13842
  layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
13509
13843
  const newLayer = {
13510
13844
  id: layerId,
13511
- name: "Loaded from workspace",
13845
+ name: layerName,
13512
13846
  visible: true,
13513
13847
  featureIds: prepared.featureIds,
13514
13848
  readOnly: true
@@ -13606,20 +13940,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13606
13940
  duration: 1e3
13607
13941
  });
13608
13942
  }, [layers, toast]);
13609
- const [ingestProgressStore] = useState(createIngestProgressStore);
13610
13943
  const ingestWithProgress = useCallback(async (label, input, options) => {
13611
13944
  const progress = ingestProgressStore.begin(label);
13612
13945
  try {
13613
- return await getSharedIngestClient().ingest(input, options, {
13614
- onHead: (summary) => progress.setTotal(summary.featureCount),
13615
- onProgress: (received) => progress.update(received)
13616
- });
13946
+ return await getSharedIngestClient().ingest(
13947
+ input,
13948
+ { ...options, maxFeatures: featureCapRef.current },
13949
+ {
13950
+ onHead: (summary) => progress.setTotal(summary.featureCount),
13951
+ onProgress: (received) => progress.update(received)
13952
+ }
13953
+ );
13617
13954
  } finally {
13618
13955
  progress.end();
13619
13956
  }
13620
13957
  }, [ingestProgressStore]);
13621
13958
  const loadGeoJSONFile = useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
13622
- var _a;
13959
+ var _a, _b, _c;
13623
13960
  let result;
13624
13961
  try {
13625
13962
  result = await ingestWithProgress(file.name, file, {
@@ -13669,7 +14006,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13669
14006
  data: { type: "FeatureCollection", features: normalizedFeatures },
13670
14007
  file,
13671
14008
  reprojected,
13672
- sourceCRS: sourceCRS ?? void 0
14009
+ sourceCRS: sourceCRS ?? void 0,
14010
+ ...result.truncated && { truncated: result.truncated }
13673
14011
  }) === true) {
13674
14012
  return;
13675
14013
  }
@@ -13689,6 +14027,17 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13689
14027
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13690
14028
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
13691
14029
  newLayer.featureIds = addedIds;
14030
+ if (result.truncated) {
14031
+ notifyFeatureCap({
14032
+ layerId,
14033
+ layerName: newLayer.name,
14034
+ kept: normalizedFeatures.length,
14035
+ dropped: result.truncated.droppedCount,
14036
+ sourceCount: result.truncated.sourceFeatureCount,
14037
+ max: result.truncated.maxFeatures,
14038
+ source: "file"
14039
+ });
14040
+ }
13692
14041
  setLayers((prev) => [...prev, newLayer]);
13693
14042
  updateFeatureCount();
13694
14043
  scheduleTimelineUpdate();
@@ -13732,6 +14081,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13732
14081
  return;
13733
14082
  }
13734
14083
  const targetId = targetLayer.id;
14084
+ const appendCapped = capFeatures(normalizedFeatures, {
14085
+ max: featureCapRef.current,
14086
+ existing: countExisting(targetLayer)
14087
+ });
14088
+ const appendFeatures = appendCapped.features;
14089
+ const totalDropped = (((_b = result.truncated) == null ? void 0 : _b.droppedCount) ?? 0) + appendCapped.dropped;
14090
+ if (totalDropped > 0) {
14091
+ notifyFeatureCap({
14092
+ layerId: targetId,
14093
+ layerName: targetLayer.name,
14094
+ kept: appendFeatures.length,
14095
+ dropped: totalDropped,
14096
+ sourceCount: ((_c = result.truncated) == null ? void 0 : _c.sourceFeatureCount) ?? appendCapped.sourceCount,
14097
+ max: featureCapRef.current,
14098
+ source: "file"
14099
+ });
14100
+ }
13735
14101
  const withLayerMetadata = (l, addedIds) => ({
13736
14102
  ...l,
13737
14103
  featureIds: [...l.featureIds, ...addedIds],
@@ -13740,7 +14106,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13740
14106
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13741
14107
  });
13742
14108
  if (targetLayer.readOnly) {
13743
- const addedFeatures = normalizedFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
14109
+ const addedFeatures = appendFeatures.map((f) => ({ ...f, id: crypto.randomUUID() }));
13744
14110
  const addedIds = addedFeatures.map((f) => String(f.id));
13745
14111
  const existing = readOnlyFeatures.current.get(targetId) || [];
13746
14112
  readOnlyFeatures.current.set(targetId, [...existing, ...addedFeatures]);
@@ -13754,7 +14120,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13754
14120
  const addedIds = [];
13755
14121
  isApiAddingRef.current = true;
13756
14122
  try {
13757
- normalizedFeatures.forEach((f) => {
14123
+ appendFeatures.forEach((f) => {
13758
14124
  const ids = draw.current.add(f);
13759
14125
  addedIds.push(ids[0]);
13760
14126
  });
@@ -13763,9 +14129,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13763
14129
  }
13764
14130
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13765
14131
  } else {
13766
- const addedIds = normalizedFeatures.map((f) => String(f.id));
14132
+ const addedIds = appendFeatures.map((f) => String(f.id));
13767
14133
  const existing = hiddenFeatures.current.get(targetId) || [];
13768
- hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
14134
+ hiddenFeatures.current.set(targetId, [...existing, ...appendFeatures]);
13769
14135
  setLayers((prev) => prev.map((l) => l.id === targetId ? withLayerMetadata(l, addedIds) : l));
13770
14136
  }
13771
14137
  updateFeatureCount();
@@ -13774,9 +14140,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13774
14140
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
13775
14141
  toast({
13776
14142
  title: "GeoJSON loaded",
13777
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
14143
+ description: `Added ${appendFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
13778
14144
  });
13779
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14145
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13780
14146
  const handleFileChange = useCallback((e) => {
13781
14147
  var _a;
13782
14148
  const file = (_a = e.target.files) == null ? void 0 : _a[0];
@@ -13838,6 +14204,17 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13838
14204
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
13839
14205
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
13840
14206
  newLayer.featureIds = addedIds;
14207
+ if (result.truncated) {
14208
+ notifyFeatureCap({
14209
+ layerId,
14210
+ layerName: newLayer.name,
14211
+ kept: normalizedFeatures.length,
14212
+ dropped: result.truncated.droppedCount,
14213
+ sourceCount: result.truncated.sourceFeatureCount,
14214
+ max: result.truncated.maxFeatures,
14215
+ source: "drop"
14216
+ });
14217
+ }
13841
14218
  const nextLayers = [...layersRef.current, newLayer];
13842
14219
  layersRef.current = nextLayers;
13843
14220
  setLayers(nextLayers);
@@ -13860,7 +14237,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13860
14237
  title: "Layer added",
13861
14238
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
13862
14239
  });
13863
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
14240
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress, notifyFeatureCap]);
13864
14241
  const handleDropGeoJSON = useCallback((name, data) => {
13865
14242
  void ingestDroppedLayer(name, data);
13866
14243
  }, [ingestDroppedLayer]);
@@ -15851,6 +16228,7 @@ export {
15851
16228
  ActionPanel,
15852
16229
  ClusterPieManager,
15853
16230
  ColorPickerPopover,
16231
+ DEFAULT_MAX_FEATURES_PER_LAYER,
15854
16232
  DebugSidebar,
15855
16233
  DrawingToolbar,
15856
16234
  INTERNAL_PROPERTY_KEYS,
@@ -15869,6 +16247,7 @@ export {
15869
16247
  TimebarToggle,
15870
16248
  cn,
15871
16249
  createClusterPieManager,
16250
+ featureCollectionBlobPartsAsync,
15872
16251
  getIconEmoji,
15873
16252
  isFeatureInRange,
15874
16253
  isInternalProperty,