@octostar/map-component 0.2.19 → 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.
package/dist/index.cjs CHANGED
@@ -164,7 +164,7 @@ async function featureCollectionBlobPartsAsync(collection, options) {
164
164
  (_c = options == null ? void 0 : options.onProgress) == null ? void 0 : _c.call(options, total, total);
165
165
  return coalescer.finish();
166
166
  }
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=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';
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';
168
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");
169
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");
170
170
  proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
@@ -229,6 +229,14 @@ function capFeatures(features, options) {
229
229
  sourceCount
230
230
  };
231
231
  }
232
+ function truncationToCapInfo(truncation, rest) {
233
+ return {
234
+ ...rest,
235
+ dropped: truncation.droppedCount,
236
+ sourceCount: truncation.sourceFeatureCount,
237
+ max: truncation.maxFeatures
238
+ };
239
+ }
232
240
  function formatCount(value) {
233
241
  return value.toLocaleString("en-US");
234
242
  }
@@ -246,6 +254,16 @@ function formatFeatureCapToast(info) {
246
254
  variant
247
255
  };
248
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
+ }
249
267
  return {
250
268
  title: "Feature limit reached",
251
269
  description: withNote(
@@ -2954,7 +2972,9 @@ function LayersPanel({
2954
2972
  key: "save-desktop",
2955
2973
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "w-[18px] h-[18px]" }),
2956
2974
  label: "Save GeoJSON to desktop",
2957
- onClick: () => onSaveLayerGeoJSON(layer.id)
2975
+ onClick: () => {
2976
+ void onSaveLayerGeoJSON(layer.id);
2977
+ }
2958
2978
  },
2959
2979
  ...onUpdateVisualConfig ? [
2960
2980
  { type: "divider" },
@@ -3635,7 +3655,9 @@ function LayersPanel({
3635
3655
  key: "save-geojson",
3636
3656
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "w-4 h-4" }),
3637
3657
  label: "Download Map",
3638
- onClick: onSaveAllGeoJSON
3658
+ onClick: () => {
3659
+ void onSaveAllGeoJSON();
3660
+ }
3639
3661
  },
3640
3662
  ...onWorkspaceSave ? [{
3641
3663
  key: "save-workspace",
@@ -6549,25 +6571,25 @@ function createSelectionPaintCache() {
6549
6571
  updatable: true
6550
6572
  };
6551
6573
  }
6552
- function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6553
- if (cache.presentIds.has(featureId)) {
6554
- cache.updatable = false;
6574
+ function recordPaintedFeature(cache2, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
6575
+ if (cache2.presentIds.has(featureId)) {
6576
+ cache2.updatable = false;
6555
6577
  } else {
6556
- cache.presentIds.add(featureId);
6578
+ cache2.presentIds.add(featureId);
6557
6579
  }
6558
- cache.basePriorityById.set(featureId, basePriority);
6559
- if (isSelected) cache.appliedSelectedIds.add(featureId);
6580
+ cache2.basePriorityById.set(featureId, basePriority);
6581
+ if (isSelected) cache2.appliedSelectedIds.add(featureId);
6560
6582
  if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
6561
- cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6583
+ cache2.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6562
6584
  }
6563
6585
  if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
6564
- cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6586
+ cache2.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6565
6587
  }
6566
- if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
6588
+ if (isTimelineHidden) cache2.appliedHiddenIds.add(featureId);
6567
6589
  }
6568
- function applySelectionFastPath(cache, nextSelectedIds, source) {
6569
- if (!cache || !cache.updatable || !source) return false;
6570
- 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);
6571
6593
  if (diff) {
6572
6594
  try {
6573
6595
  source.updateData(diff);
@@ -6577,29 +6599,29 @@ function applySelectionFastPath(cache, nextSelectedIds, source) {
6577
6599
  }
6578
6600
  const applied = /* @__PURE__ */ new Set();
6579
6601
  nextSelectedIds.forEach((id) => {
6580
- if (cache.presentIds.has(id)) applied.add(id);
6602
+ if (cache2.presentIds.has(id)) applied.add(id);
6581
6603
  });
6582
- cache.appliedSelectedIds = applied;
6604
+ cache2.appliedSelectedIds = applied;
6583
6605
  return true;
6584
6606
  }
6585
6607
  function needsDrawSelectionUpdate(input) {
6586
6608
  return input.editableSelectionCount > 0 || input.drawSelectedCount > 0 || input.currentMode !== input.targetMode;
6587
6609
  }
6588
- function buildSelectionDiff(cache, nextSelectedIds) {
6610
+ function buildSelectionDiff(cache2, nextSelectedIds) {
6589
6611
  const update = [];
6590
- cache.appliedSelectedIds.forEach((id) => {
6591
- if (!nextSelectedIds.has(id) && cache.presentIds.has(id)) {
6612
+ cache2.appliedSelectedIds.forEach((id) => {
6613
+ if (!nextSelectedIds.has(id) && cache2.presentIds.has(id)) {
6592
6614
  update.push({
6593
6615
  id,
6594
6616
  addOrUpdateProperties: [
6595
6617
  { key: "isSelected", value: 0 },
6596
- { key: "_labelPriority", value: cache.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6618
+ { key: "_labelPriority", value: cache2.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
6597
6619
  ]
6598
6620
  });
6599
6621
  }
6600
6622
  });
6601
6623
  nextSelectedIds.forEach((id) => {
6602
- if (!cache.appliedSelectedIds.has(id) && cache.presentIds.has(id)) {
6624
+ if (!cache2.appliedSelectedIds.has(id) && cache2.presentIds.has(id)) {
6603
6625
  update.push({
6604
6626
  id,
6605
6627
  addOrUpdateProperties: [
@@ -6611,13 +6633,13 @@ function buildSelectionDiff(cache, nextSelectedIds) {
6611
6633
  });
6612
6634
  return update.length > 0 ? { update } : null;
6613
6635
  }
6614
- function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6636
+ function buildTimelineVisibilityDiff(cache2, nextVisibleSet) {
6615
6637
  const update = [];
6616
6638
  const nextHiddenIds = /* @__PURE__ */ new Set();
6617
- cache.presentIds.forEach((id) => {
6639
+ cache2.presentIds.forEach((id) => {
6618
6640
  const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
6619
6641
  if (nextHidden) nextHiddenIds.add(id);
6620
- if (nextHidden === cache.appliedHiddenIds.has(id)) return;
6642
+ if (nextHidden === cache2.appliedHiddenIds.has(id)) return;
6621
6643
  if (nextHidden) {
6622
6644
  update.push({
6623
6645
  id,
@@ -6631,8 +6653,8 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6631
6653
  update.push({
6632
6654
  id,
6633
6655
  addOrUpdateProperties: [
6634
- { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6635
- { 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 },
6636
6658
  { key: "isTimelineHidden", value: 0 }
6637
6659
  ]
6638
6660
  });
@@ -6640,10 +6662,10 @@ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6640
6662
  });
6641
6663
  return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6642
6664
  }
6643
- function applyTimelineFastPath(cache, nextVisibleSet, source) {
6665
+ function applyTimelineFastPath(cache2, nextVisibleSet, source) {
6644
6666
  var _a;
6645
- if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6646
- const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6667
+ if (!cache2 || !cache2.updatable || !source) return { applied: false, toggled: 0 };
6668
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache2, nextVisibleSet);
6647
6669
  if (diff) {
6648
6670
  try {
6649
6671
  source.updateData(diff);
@@ -6651,9 +6673,204 @@ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6651
6673
  return { applied: false, toggled: 0 };
6652
6674
  }
6653
6675
  }
6654
- cache.appliedHiddenIds = nextHiddenIds;
6676
+ cache2.appliedHiddenIds = nextHiddenIds;
6655
6677
  return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6656
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
+ }
6657
6874
  function deepClone(value) {
6658
6875
  try {
6659
6876
  return structuredClone(value);
@@ -6710,15 +6927,15 @@ function prepareFeaturesForLayer(input, caller, cap) {
6710
6927
  const logging = mapPerfLogEnabled();
6711
6928
  const started = logging ? performance.now() : 0;
6712
6929
  const capped = cap ? capFeatures(input, cap) : null;
6713
- if (capped) input = capped.features;
6714
- const count = input.length;
6930
+ const source = capped ? capped.features : input;
6931
+ const count = source.length;
6715
6932
  const features = new Array(count);
6716
6933
  const featureIds = new Array(count);
6717
6934
  let hasTemporal = false;
6718
6935
  let temporalCount = 0;
6719
6936
  let reused = 0;
6720
6937
  for (let i = 0; i < count; i++) {
6721
- const f = input[i];
6938
+ const f = source[i];
6722
6939
  const props = f.properties || {};
6723
6940
  if (!hasAnyTemporalValue(props)) {
6724
6941
  if (typeof f.id === "string" && f.id) {
@@ -8028,6 +8245,16 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8028
8245
  });
8029
8246
  return [...drawFeatures, ...readOnly];
8030
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
+ }, []);
8031
8258
  const getSelectedFeatures = react.useCallback(() => {
8032
8259
  const drawSelected = draw.current ? draw.current.getSelected().features : [];
8033
8260
  const readOnlySelected = [];
@@ -8212,29 +8439,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8212
8439
  layers.forEach((layer) => {
8213
8440
  var _a;
8214
8441
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8215
- const layerFeatures = [];
8216
- layer.featureIds.forEach((id) => {
8217
- var _a2;
8218
- const f = featById.get(id);
8219
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8220
- layerFeatures.push(f);
8221
- });
8222
- if (layerFeatures.length < 1) return;
8223
- const groupByField = layer.traceConfig.groupByField;
8224
- const groups = /* @__PURE__ */ new Map();
8225
- layerFeatures.forEach((f) => {
8226
- var _a2;
8227
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8228
- if (!groups.has(key)) groups.set(key, []);
8229
- groups.get(key).push(f);
8230
- });
8231
- const groupKeys = Array.from(groups.keys());
8232
- groupKeys.forEach((key, index) => {
8233
- const color = key === "__all__" ? "#3b82f6" : `hsl(${index * 360 / groupKeys.length % 360}, 70%, 50%)`;
8234
- groups.get(key).forEach((f) => {
8235
- if (f.id) tracePointColors.set(String(f.id), color);
8236
- });
8237
- });
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
+ }
8238
8445
  });
8239
8446
  const layerGradientRanges = /* @__PURE__ */ new Map();
8240
8447
  selectedFeatureIds.forEach((fid) => {
@@ -8268,7 +8475,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8268
8475
  colorMap.set(fid, color);
8269
8476
  });
8270
8477
  return colorMap;
8271
- }, [selectedFeatureIds, layers, getAllFeatures]);
8478
+ }, [selectedFeatureIds, layers, getAllFeatures, traceSourceFeatures]);
8272
8479
  const countVisibleFeatures = react.useCallback((threshold) => {
8273
8480
  const m = map.current;
8274
8481
  if (!m) return 0;
@@ -8287,6 +8494,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8287
8494
  }, []);
8288
8495
  const isSyncingRef = react.useRef(false);
8289
8496
  const selectionPaintCacheRef = react.useRef(null);
8497
+ const tracePaintCacheRef = react.useRef(null);
8290
8498
  const paintedArrowLinesRef = react.useRef([]);
8291
8499
  const renderArrowOverlays = react.useCallback((arrowLines) => {
8292
8500
  const mapInstance = map.current;
@@ -8456,60 +8664,29 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8456
8664
  const tracePointColors = /* @__PURE__ */ new Map();
8457
8665
  const lastTracePointLabels = /* @__PURE__ */ new Map();
8458
8666
  const tracePointIds = /* @__PURE__ */ new Set();
8667
+ const paintedTraceGroups = [];
8668
+ const traceSegments = [];
8669
+ const tracePointPaint = /* @__PURE__ */ new Map();
8670
+ const isTimelineVisibleId = timelineVisibility(visibleSet);
8459
8671
  currentLayers.forEach((layer) => {
8460
8672
  var _a;
8461
8673
  if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8462
- const layerFeatures = [];
8463
- layer.featureIds.forEach((id) => {
8464
- var _a2;
8465
- const f = featureById.get(id);
8466
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8467
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8468
- layerFeatures.push(f);
8469
- });
8470
- if (layerFeatures.length < 1) return;
8471
- const groupByField = layer.traceConfig.groupByField;
8472
- const groups = /* @__PURE__ */ new Map();
8473
- layerFeatures.forEach((f) => {
8474
- var _a2;
8475
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8476
- if (!groups.has(key)) groups.set(key, []);
8477
- groups.get(key).push(f);
8478
- });
8479
- const groupKeys = Array.from(groups.keys());
8480
- const groupColors = /* @__PURE__ */ new Map();
8481
- groupKeys.forEach((key, index) => {
8482
- if (key === "__all__") {
8483
- groupColors.set(key, "#3b82f6");
8484
- } else {
8485
- const hue = index * 360 / groupKeys.length % 360;
8486
- 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);
8487
8680
  }
8488
- });
8489
- groups.forEach((groupFeatures, groupKey) => {
8490
- const sorted = [...groupFeatures].sort((a, b) => {
8491
- var _a2, _b;
8492
- const dateA = new Date(((_a2 = a.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8493
- const dateB = new Date(((_b = b.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8494
- return dateA - dateB;
8495
- });
8496
- if (sorted.length > 0) {
8497
- const groupColor = groupColors.get(groupKey) || "#3b82f6";
8498
- sorted.forEach((point) => {
8499
- if (point.id) {
8500
- tracePointIds.add(String(point.id));
8501
- tracePointColors.set(String(point.id), groupColor);
8502
- }
8503
- });
8504
- const lastPoint = sorted[sorted.length - 1];
8505
- if (lastPoint.id) {
8506
- lastTracePointIds.add(String(lastPoint.id));
8507
- if (groupByField && groupKey !== "__all__") {
8508
- lastTracePointLabels.set(String(lastPoint.id), groupKey);
8509
- }
8510
- }
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]));
8511
8688
  }
8512
- });
8689
+ }
8513
8690
  });
8514
8691
  const paintCache = createSelectionPaintCache();
8515
8692
  const sourceData = {
@@ -8554,13 +8731,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8554
8731
  const isTracePoint = tracePointIds.has(featureId);
8555
8732
  const isLastTracePoint = lastTracePointIds.has(featureId);
8556
8733
  const traceLabel = lastTracePointLabels.get(featureId);
8734
+ let traceEndpointRadius = null;
8557
8735
  if (isTracePoint && f.geometry.type === "Point") {
8558
8736
  strokeColor = tracePointColors.get(featureId) || strokeColor;
8559
- if (isLastTracePoint) {
8560
- pointRadius = Math.max(pointRadius, 8);
8561
- } else {
8562
- pointRadius = 2;
8563
- }
8737
+ traceEndpointRadius = Math.max(pointRadius, TRACE_ENDPOINT_MIN_RADIUS);
8738
+ pointRadius = isLastTracePoint ? traceEndpointRadius : TRACE_POINT_RADIUS;
8564
8739
  }
8565
8740
  let labelText = ((_d = f.properties) == null ? void 0 : _d.name) || "";
8566
8741
  const labelConfig = visualConfig == null ? void 0 : visualConfig.label;
@@ -8574,6 +8749,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8574
8749
  labelText = fieldValue !== void 0 && fieldValue !== null ? String(fieldValue) : "";
8575
8750
  }
8576
8751
  }
8752
+ const nonTraceLabelText = labelText;
8577
8753
  if (traceLabel) {
8578
8754
  labelText = traceLabel;
8579
8755
  }
@@ -8605,11 +8781,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8605
8781
  });
8606
8782
  }
8607
8783
  const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIdSet.has(featureId) ? 1 : 0;
8608
- let basePriority = DEFAULT_LABEL_PRIORITY;
8609
- if (traceLabel) {
8610
- basePriority = 5;
8611
- } else if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
8612
- 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;
8613
8787
  } else {
8614
8788
  const idStr = String(featureId);
8615
8789
  let h = 0;
@@ -8617,9 +8791,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8617
8791
  h = (h << 5) - h + idStr.charCodeAt(i);
8618
8792
  h |= 0;
8619
8793
  }
8620
- basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8794
+ nonTracePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
8621
8795
  }
8796
+ const basePriority = traceLabel ? TRACE_ENDPOINT_LABEL_PRIORITY : nonTracePriority;
8622
8797
  const labelPriority = isFeatureSelected ? 0 : basePriority;
8798
+ if (traceEndpointRadius !== null) {
8799
+ tracePointPaint.set(featureId, { name: nonTraceLabelText, endpointRadius: traceEndpointRadius, basePriority: nonTracePriority });
8800
+ }
8623
8801
  const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
8624
8802
  const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
8625
8803
  recordPaintedFeature(
@@ -8666,93 +8844,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8666
8844
  source.setData(sourceData);
8667
8845
  selectionPaintCacheRef.current = paintCache;
8668
8846
  const traceSource = map.current.getSource("trace-features");
8669
- if (traceSource) {
8670
- const traceSegments = [];
8671
- currentLayers.forEach((layer) => {
8672
- var _a;
8673
- if (!((_a = layer.traceConfig) == null ? void 0 : _a.enabled) || !layer.visible) return;
8674
- const layerFeatures = [];
8675
- layer.featureIds.forEach((id) => {
8676
- var _a2;
8677
- const f = featureById.get(id);
8678
- if (!f || f.geometry.type !== "Point" || !((_a2 = f.properties) == null ? void 0 : _a2.startDate)) return;
8679
- if (visibleSet && f.id && !visibleSet.has(String(f.id))) return;
8680
- layerFeatures.push(f);
8681
- });
8682
- if (layerFeatures.length < 2) return;
8683
- const groupByField = layer.traceConfig.groupByField;
8684
- const groups = /* @__PURE__ */ new Map();
8685
- layerFeatures.forEach((f) => {
8686
- var _a2;
8687
- const key = groupByField && ((_a2 = f.properties) == null ? void 0 : _a2[groupByField]) ? String(f.properties[groupByField]) : "__all__";
8688
- if (!groups.has(key)) groups.set(key, []);
8689
- groups.get(key).push(f);
8690
- });
8691
- const groupKeys = Array.from(groups.keys());
8692
- const groupColors = /* @__PURE__ */ new Map();
8693
- groupKeys.forEach((key, index) => {
8694
- if (key === "__all__") {
8695
- groupColors.set(key, "#3b82f6");
8696
- } else {
8697
- const hue = index * 360 / groupKeys.length % 360;
8698
- groupColors.set(key, `hsl(${hue}, 70%, 50%)`);
8699
- }
8700
- });
8701
- groups.forEach((groupFeatures, groupKey) => {
8702
- var _a2, _b, _c, _d;
8703
- const sorted = [...groupFeatures].sort((a, b) => {
8704
- var _a3, _b2;
8705
- const dateA = new Date(((_a3 = a.properties) == null ? void 0 : _a3.startDate) || 0).getTime();
8706
- const dateB = new Date(((_b2 = b.properties) == null ? void 0 : _b2.startDate) || 0).getTime();
8707
- return dateA - dateB;
8708
- });
8709
- if (sorted.length < 2) return;
8710
- for (let i = 0; i < sorted.length - 1; i++) {
8711
- const from = sorted[i];
8712
- const to = sorted[i + 1];
8713
- const fromCoords = from.geometry.coordinates;
8714
- const toCoords = to.geometry.coordinates;
8715
- const fromPoint = turf__namespace.point(fromCoords);
8716
- const toPoint = turf__namespace.point(toCoords);
8717
- const distanceKm = turf__namespace.distance(fromPoint, toPoint, { units: "kilometers" });
8718
- const fromTime = new Date(((_a2 = from.properties) == null ? void 0 : _a2.startDate) || 0).getTime();
8719
- const toTime = new Date(((_b = to.properties) == null ? void 0 : _b.startDate) || 0).getTime();
8720
- const durationMs = toTime - fromTime;
8721
- const durationHours = durationMs / (1e3 * 60 * 60);
8722
- const avgSpeedKmh = durationHours > 0 ? distanceKm / durationHours : 0;
8723
- let durationStr = "";
8724
- if (durationMs < 6e4) {
8725
- durationStr = `${Math.round(durationMs / 1e3)}s`;
8726
- } else if (durationMs < 36e5) {
8727
- durationStr = `${Math.round(durationMs / 6e4)}m`;
8728
- } else if (durationMs < 864e5) {
8729
- durationStr = `${Math.floor(durationMs / 36e5)}h ${Math.round(durationMs % 36e5 / 6e4)}m`;
8730
- } else {
8731
- durationStr = `${Math.floor(durationMs / 864e5)}d ${Math.round(durationMs % 864e5 / 36e5)}h`;
8732
- }
8733
- const distanceStr = distanceKm < 1 ? `${Math.round(distanceKm * 1e3)}m` : `${distanceKm.toFixed(2)}km`;
8734
- const speedStr = avgSpeedKmh < 1 ? `${(avgSpeedKmh * 1e3).toFixed(0)}m/h` : `${avgSpeedKmh.toFixed(1)}km/h`;
8735
- traceSegments.push({
8736
- type: "Feature",
8737
- properties: {
8738
- group: groupKey,
8739
- color: groupColors.get(groupKey) || "#3b82f6",
8740
- duration: durationStr,
8741
- distance: distanceStr,
8742
- avgSpeed: speedStr,
8743
- fromName: ((_c = from.properties) == null ? void 0 : _c.name) || "",
8744
- toName: ((_d = to.properties) == null ? void 0 : _d.name) || ""
8745
- },
8746
- geometry: {
8747
- type: "LineString",
8748
- coordinates: [fromCoords, toCoords]
8749
- }
8750
- });
8751
- }
8752
- });
8753
- });
8754
- traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8755
- }
8847
+ if (traceSource) traceSource.setData({ type: "FeatureCollection", features: traceSegments });
8848
+ tracePaintCacheRef.current = traceSource && paintedTraceGroups.length > 0 ? { groups: paintedTraceGroups, pointPaint: tracePointPaint } : null;
8756
8849
  {
8757
8850
  let sawArrowFeature = false;
8758
8851
  const arrowLines = [];
@@ -10639,7 +10732,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10639
10732
  clusterConfig: options == null ? void 0 : options.clusterConfig,
10640
10733
  altitudeDisplayMode: options == null ? void 0 : options.altitudeDisplayMode
10641
10734
  };
10642
- let addedFeatures = (geojson == null ? void 0 : geojson.features) ?? [];
10735
+ let addedFeatures = [];
10643
10736
  let capDropped = 0;
10644
10737
  if (geojson) {
10645
10738
  const max = featureCapRef.current;
@@ -10696,9 +10789,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10696
10789
  scheduleSync();
10697
10790
  if (!(options == null ? void 0 : options.skipFit) && addedFeatures.length > 0 && map.current) {
10698
10791
  try {
10699
- const bbox = turf__namespace.bbox(
10700
- capDropped > 0 ? { type: "FeatureCollection", features: addedFeatures } : geojson
10701
- );
10792
+ const bbox = turf__namespace.bbox({
10793
+ type: "FeatureCollection",
10794
+ features: addedFeatures
10795
+ });
10702
10796
  if (bbox.every((v) => isFinite(v))) {
10703
10797
  map.current.fitBounds(
10704
10798
  [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
@@ -10803,7 +10897,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10803
10897
  dropped: prepared.dropped,
10804
10898
  sourceCount: prepared.sourceCount,
10805
10899
  max: featureCapRef.current,
10806
- source: "api"
10900
+ source: "api",
10901
+ existing: existing.length
10807
10902
  });
10808
10903
  }
10809
10904
  const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
@@ -10825,9 +10920,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10825
10920
  }
10826
10921
  if (!draw.current) return [];
10827
10922
  const addedIds = [];
10923
+ const existingInLayer = countExisting(layer);
10828
10924
  const cappedForDraw = capFeatures(features, {
10829
10925
  max: featureCapRef.current,
10830
- existing: countExisting(layer)
10926
+ existing: existingInLayer
10831
10927
  });
10832
10928
  if (cappedForDraw.dropped > 0) {
10833
10929
  notifyFeatureCap({
@@ -10837,7 +10933,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10837
10933
  dropped: cappedForDraw.dropped,
10838
10934
  sourceCount: cappedForDraw.sourceCount,
10839
10935
  max: featureCapRef.current,
10840
- source: "api"
10936
+ source: "api",
10937
+ existing: existingInLayer
10841
10938
  });
10842
10939
  }
10843
10940
  isApiAddingRef.current = true;
@@ -10954,9 +11051,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10954
11051
  const layer = layersRef.current.find((l) => l.id === layerId);
10955
11052
  if (!layer || !draw.current || !isMapLoaded) return [];
10956
11053
  const addedIds = [];
11054
+ const existingInLayer = countExisting(layer);
10957
11055
  const capped = capFeatures(geojson.features, {
10958
11056
  max: featureCapRef.current,
10959
- existing: countExisting(layer)
11057
+ existing: existingInLayer
10960
11058
  });
10961
11059
  if (capped.dropped > 0) {
10962
11060
  notifyFeatureCap({
@@ -10966,7 +11064,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10966
11064
  dropped: capped.dropped,
10967
11065
  sourceCount: capped.sourceCount,
10968
11066
  max: featureCapRef.current,
10969
- source: "api"
11067
+ source: "api",
11068
+ existing: existingInLayer
10970
11069
  });
10971
11070
  }
10972
11071
  isApiAddingRef.current = true;
@@ -12746,23 +12845,26 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12746
12845
  const m = map.current;
12747
12846
  if (!m) return true;
12748
12847
  if (hasArrowFeaturesRef.current) return false;
12749
- if (layersRef.current.some((l) => {
12750
- var _a;
12751
- return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
12752
- })) return false;
12753
12848
  const source = m.getSource("custom-features");
12754
- const { applied, toggled } = applyTimelineFastPath(
12755
- selectionPaintCacheRef.current,
12756
- timelineVisibleIdsRef.current,
12757
- source
12758
- );
12759
- if (applied) {
12760
- const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
12761
- setVisibleFeatureCount(countVisibleFeatures(threshold));
12762
- setLabelsSuppressed(false);
12763
- mapPerfLog("timeline", "fast path applied", { toggled });
12764
- }
12765
- 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;
12766
12868
  }, [autoLabelConfig, countVisibleFeatures]);
12767
12869
  tryTimelineFastPathRef.current = tryTimelineFastPath;
12768
12870
  const collectSelectionFeatureGroups = react.useCallback(() => {
@@ -13524,11 +13626,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13524
13626
  new Blob(parts, { type: "application/json" }),
13525
13627
  `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`
13526
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
+ });
13527
13636
  } finally {
13528
13637
  progress.end();
13529
13638
  exportInFlightRef.current = false;
13530
13639
  }
13531
- }, [layers, ingestProgressStore]);
13640
+ }, [layers, ingestProgressStore, toast]);
13532
13641
  const handleLoadLayerGeoJSON = react.useCallback((layerId) => {
13533
13642
  const input = fileInputRef.current;
13534
13643
  if (!input) return;
@@ -13608,11 +13717,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13608
13717
  onProgress: (done) => progress.update(done)
13609
13718
  });
13610
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
+ });
13611
13727
  } finally {
13612
13728
  progress.end();
13613
13729
  exportInFlightRef.current = false;
13614
13730
  }
13615
- }, [buildEnrichedExport, ingestProgressStore]);
13731
+ }, [buildEnrichedExport, ingestProgressStore, toast]);
13616
13732
  const handleSearchAndAddToNewLayer = react.useCallback(async () => {
13617
13733
  if (!onSearchEngineRequest || !map.current || !draw.current) return;
13618
13734
  const mapInstance = map.current;
@@ -13647,9 +13763,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13647
13763
  saveStateForUndo();
13648
13764
  const activeId = activeEditingLayerIdRef.current;
13649
13765
  const activeLayer = activeId ? layersRef.current.find((l) => l.id === activeId && !l.readOnly) : null;
13766
+ const existingInActive = activeLayer ? countExisting(activeLayer) : 0;
13650
13767
  const capped = capFeatures(result.features, {
13651
13768
  max: featureCapRef.current,
13652
- existing: activeLayer ? countExisting(activeLayer) : 0
13769
+ existing: existingInActive
13653
13770
  });
13654
13771
  const addedIds = [];
13655
13772
  isApiAddingRef.current = true;
@@ -13708,7 +13825,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13708
13825
  dropped: capped.dropped,
13709
13826
  sourceCount: capped.sourceCount,
13710
13827
  max: featureCapRef.current,
13711
- source: "search"
13828
+ source: "search",
13829
+ existing: existingInActive
13712
13830
  });
13713
13831
  }
13714
13832
  updateFeatureCount();
@@ -14049,15 +14167,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
14049
14167
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
14050
14168
  newLayer.featureIds = addedIds;
14051
14169
  if (result.truncated) {
14052
- notifyFeatureCap({
14053
- layerId,
14054
- layerName: newLayer.name,
14055
- kept: normalizedFeatures.length,
14056
- dropped: result.truncated.droppedCount,
14057
- sourceCount: result.truncated.sourceFeatureCount,
14058
- max: result.truncated.maxFeatures,
14059
- source: "file"
14060
- });
14170
+ notifyFeatureCap(
14171
+ truncationToCapInfo(result.truncated, {
14172
+ layerId,
14173
+ layerName: newLayer.name,
14174
+ kept: normalizedFeatures.length,
14175
+ source: "file"
14176
+ })
14177
+ );
14061
14178
  }
14062
14179
  setLayers((prev) => [...prev, newLayer]);
14063
14180
  updateFeatureCount();
@@ -14102,9 +14219,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
14102
14219
  return;
14103
14220
  }
14104
14221
  const targetId = targetLayer.id;
14222
+ const existingInTarget = countExisting(targetLayer);
14105
14223
  const appendCapped = capFeatures(normalizedFeatures, {
14106
14224
  max: featureCapRef.current,
14107
- existing: countExisting(targetLayer)
14225
+ existing: existingInTarget
14108
14226
  });
14109
14227
  const appendFeatures = appendCapped.features;
14110
14228
  const totalDropped = (((_b = result.truncated) == null ? void 0 : _b.droppedCount) ?? 0) + appendCapped.dropped;
@@ -14116,7 +14234,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
14116
14234
  dropped: totalDropped,
14117
14235
  sourceCount: ((_c = result.truncated) == null ? void 0 : _c.sourceFeatureCount) ?? appendCapped.sourceCount,
14118
14236
  max: featureCapRef.current,
14119
- source: "file"
14237
+ source: "file",
14238
+ existing: existingInTarget
14120
14239
  });
14121
14240
  }
14122
14241
  const withLayerMetadata = (l, addedIds) => ({
@@ -14226,15 +14345,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
14226
14345
  layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
14227
14346
  newLayer.featureIds = addedIds;
14228
14347
  if (result.truncated) {
14229
- notifyFeatureCap({
14230
- layerId,
14231
- layerName: newLayer.name,
14232
- kept: normalizedFeatures.length,
14233
- dropped: result.truncated.droppedCount,
14234
- sourceCount: result.truncated.sourceFeatureCount,
14235
- max: result.truncated.maxFeatures,
14236
- source: "drop"
14237
- });
14348
+ notifyFeatureCap(
14349
+ truncationToCapInfo(result.truncated, {
14350
+ layerId,
14351
+ layerName: newLayer.name,
14352
+ kept: normalizedFeatures.length,
14353
+ source: "drop"
14354
+ })
14355
+ );
14238
14356
  }
14239
14357
  const nextLayers = [...layersRef.current, newLayer];
14240
14358
  layersRef.current = nextLayers;