@octostar/map-component 0.1.38 → 0.2.0

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
@@ -5189,6 +5189,90 @@ function MapDropZone({ onDrop, children }) {
5189
5189
  }
5190
5190
  );
5191
5191
  }
5192
+ const DEFAULT_LIMIT = 50;
5193
+ const DEFAULT_COALESCE_MS = 600;
5194
+ class CommandHistory {
5195
+ constructor(limit = DEFAULT_LIMIT, coalesceMs = DEFAULT_COALESCE_MS, now = Date.now) {
5196
+ this.limit = limit;
5197
+ this.coalesceMs = coalesceMs;
5198
+ this.now = now;
5199
+ this.undoStack = [];
5200
+ this.redoStack = [];
5201
+ this.lastPush = null;
5202
+ }
5203
+ get canUndo() {
5204
+ return this.undoStack.length > 0;
5205
+ }
5206
+ get canRedo() {
5207
+ return this.redoStack.length > 0;
5208
+ }
5209
+ /** Push a new command. Clears the redo stack (a new action forks history). */
5210
+ push(command) {
5211
+ const at = this.now();
5212
+ const key = command.coalesceKey;
5213
+ const top = this.undoStack[this.undoStack.length - 1];
5214
+ if (key && top && this.lastPush && this.lastPush.key === key && at - this.lastPush.at < this.coalesceMs) {
5215
+ top.redo = command.redo;
5216
+ this.lastPush = { key, at };
5217
+ this.redoStack = [];
5218
+ return;
5219
+ }
5220
+ this.undoStack.push(command);
5221
+ if (this.undoStack.length > this.limit) this.undoStack.shift();
5222
+ this.redoStack = [];
5223
+ this.lastPush = key ? { key, at } : null;
5224
+ }
5225
+ /** Reverse the most recent command. Returns false if nothing to undo. */
5226
+ undo() {
5227
+ const command = this.undoStack.pop();
5228
+ if (!command) return false;
5229
+ this.lastPush = null;
5230
+ command.undo();
5231
+ this.redoStack.push(command);
5232
+ return true;
5233
+ }
5234
+ /** Re-apply the most recently undone command. Returns false if none. */
5235
+ redo() {
5236
+ const command = this.redoStack.pop();
5237
+ if (!command) return false;
5238
+ this.lastPush = null;
5239
+ command.redo();
5240
+ this.undoStack.push(command);
5241
+ return true;
5242
+ }
5243
+ clear() {
5244
+ this.undoStack = [];
5245
+ this.redoStack = [];
5246
+ this.lastPush = null;
5247
+ }
5248
+ }
5249
+ function useMapHistory(options) {
5250
+ const historyRef = react.useRef(null);
5251
+ if (historyRef.current === null) {
5252
+ historyRef.current = new CommandHistory(options == null ? void 0 : options.limit, options == null ? void 0 : options.coalesceMs);
5253
+ }
5254
+ const history = historyRef.current;
5255
+ const [, setTick] = react.useState(0);
5256
+ const rerender = react.useCallback(() => setTick((t) => t + 1), []);
5257
+ const push = react.useCallback(
5258
+ (command) => {
5259
+ history.push(command);
5260
+ rerender();
5261
+ },
5262
+ [history, rerender]
5263
+ );
5264
+ const undo = react.useCallback(() => {
5265
+ if (history.undo()) rerender();
5266
+ }, [history, rerender]);
5267
+ const redo = react.useCallback(() => {
5268
+ if (history.redo()) rerender();
5269
+ }, [history, rerender]);
5270
+ const clear = react.useCallback(() => {
5271
+ history.clear();
5272
+ rerender();
5273
+ }, [history, rerender]);
5274
+ return { push, undo, redo, clear, canUndo: history.canUndo, canRedo: history.canRedo };
5275
+ }
5192
5276
  const OTHER_BUCKET_KEY = "__other__";
5193
5277
  const OTHER_BUCKET_LABEL = "Other";
5194
5278
  const OTHER_BUCKET_COLOR = "#9ca3af";
@@ -5839,19 +5923,6 @@ const EXTERNAL_STYLE_URLS = {
5839
5923
  streets: "https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json",
5840
5924
  dark: "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json"
5841
5925
  };
5842
- function computeUndoRedoEvent(fromState, toState) {
5843
- const fromIds = new Set(fromState.features.map((f) => f.id));
5844
- const toIds = new Set(toState.features.map((f) => f.id));
5845
- const restoredFeatures = toState.features.filter((f) => !fromIds.has(f.id)).map((f) => {
5846
- var _a;
5847
- return {
5848
- feature: f,
5849
- layerId: ((_a = toState.layers.find((l) => l.featureIds.includes(f.id))) == null ? void 0 : _a.id) ?? null
5850
- };
5851
- });
5852
- const removedFeatureIds = fromState.features.filter((f) => !toIds.has(f.id)).map((f) => f.id);
5853
- return { restoredFeatures, removedFeatureIds };
5854
- }
5855
5926
  const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
5856
5927
  className,
5857
5928
  enableDrawing = true,
@@ -5879,8 +5950,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
5879
5950
  onFeatureCreate,
5880
5951
  onFeatureUpdate,
5881
5952
  onFeatureDelete,
5882
- onUndo,
5883
- onRedo,
5884
5953
  onLayerChange,
5885
5954
  onActiveEditingLayerChange,
5886
5955
  onTimelineChange,
@@ -5971,8 +6040,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
5971
6040
  { id: "default", name: "Default Layer", visible: true, featureIds: [] }
5972
6041
  ]);
5973
6042
  const [activeEditingLayerId, setActiveEditingLayerId] = react.useState("default");
5974
- const [undoStack, setUndoStack] = react.useState([]);
5975
- const [redoStack, setRedoStack] = react.useState([]);
6043
+ const history = useMapHistory();
6044
+ const pendingCaptureRef = react.useRef(null);
6045
+ const preDragRef = react.useRef(null);
5976
6046
  const [isEditMode, setIsEditMode] = react.useState(false);
5977
6047
  const [currentMapStyle, setCurrentMapStyle] = react.useState(baseMapStyle);
5978
6048
  const [measureMode, setMeasureMode] = react.useState("none");
@@ -6182,16 +6252,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6182
6252
  });
6183
6253
  }
6184
6254
  }, [isMapLoaded, getFeatureById, onFeatureSelect]);
6185
- const saveStateForUndo = react.useCallback(() => {
6186
- if (!draw.current) return;
6187
- const currentState = {
6188
- features: draw.current.getAll().features,
6189
- layers: JSON.parse(JSON.stringify(layersRef.current)),
6190
- selectedIds: [...selectedFeatureIds]
6191
- };
6192
- setUndoStack((prev) => [...prev.slice(-49), currentState]);
6193
- setRedoStack([]);
6194
- }, [selectedFeatureIds]);
6195
6255
  const updateFeatureCount = react.useCallback(() => {
6196
6256
  const drawFeatureCount = draw.current ? draw.current.getAll().features.length : 0;
6197
6257
  let hiddenCount = 0;
@@ -6489,7 +6549,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6489
6549
  }
6490
6550
  });
6491
6551
  }
6492
- const isFeatureSelected = selectedIds.includes(featureId) ? 1 : 0;
6552
+ const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIds.includes(featureId) ? 1 : 0;
6493
6553
  let labelPriority = 100;
6494
6554
  if (isFeatureSelected) {
6495
6555
  labelPriority = 0;
@@ -6899,6 +6959,287 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6899
6959
  updateTimelineStore();
6900
6960
  }, 300);
6901
6961
  }, [updateTimelineStore]);
6962
+ const collectHistoryFeatures = react.useCallback(
6963
+ (overrides) => {
6964
+ var _a;
6965
+ const featureToLayer = /* @__PURE__ */ new Map();
6966
+ for (const l of layersRef.current) {
6967
+ if (((_a = l.metadata) == null ? void 0 : _a.dataViewing) === true) continue;
6968
+ for (const fid of l.featureIds) featureToLayer.set(fid, l.id);
6969
+ }
6970
+ const result = /* @__PURE__ */ new Map();
6971
+ if (draw.current) {
6972
+ for (const f of draw.current.getAll().features) {
6973
+ if (f.id == null) continue;
6974
+ const id = String(f.id);
6975
+ result.set(id, {
6976
+ feature: f,
6977
+ layerId: featureToLayer.get(id) ?? activeEditingLayerIdRef.current,
6978
+ store: "draw"
6979
+ });
6980
+ }
6981
+ }
6982
+ readOnlyFeatures.current.forEach((features, layerId) => {
6983
+ var _a2;
6984
+ const layer = layersRef.current.find((l) => l.id === layerId);
6985
+ if (((_a2 = layer == null ? void 0 : layer.metadata) == null ? void 0 : _a2.dataViewing) === true) return;
6986
+ for (const f of features) {
6987
+ if (f.id == null) continue;
6988
+ result.set(String(f.id), { feature: f, layerId, store: "readOnly" });
6989
+ }
6990
+ });
6991
+ hiddenFeatures.current.forEach((features, layerId) => {
6992
+ for (const f of features) {
6993
+ if (f.id == null) continue;
6994
+ result.set(String(f.id), { feature: f, layerId, store: "hidden" });
6995
+ }
6996
+ });
6997
+ if (overrides == null ? void 0 : overrides.excludeDrawIds) {
6998
+ overrides.excludeDrawIds.forEach((id) => result.delete(id));
6999
+ }
7000
+ if (overrides == null ? void 0 : overrides.addDrawFeatures) {
7001
+ for (const f of overrides.addDrawFeatures) {
7002
+ if (f.id == null) continue;
7003
+ const id = String(f.id);
7004
+ const layerId = featureToLayer.get(id) ?? activeEditingLayerIdRef.current;
7005
+ const layer = layersRef.current.find((l) => l.id === layerId);
7006
+ result.set(id, { feature: f, layerId, store: (layer == null ? void 0 : layer.readOnly) ? "readOnly" : "draw" });
7007
+ }
7008
+ }
7009
+ return result;
7010
+ },
7011
+ []
7012
+ );
7013
+ const collectHistoryLayers = react.useCallback(() => {
7014
+ var _a;
7015
+ const result = /* @__PURE__ */ new Map();
7016
+ for (const l of layersRef.current) {
7017
+ if (((_a = l.metadata) == null ? void 0 : _a.dataViewing) === true) continue;
7018
+ result.set(l.id, { ...l, featureIds: [...l.featureIds] });
7019
+ }
7020
+ return result;
7021
+ }, []);
7022
+ const cleanupOrphanLayerSources = react.useCallback((liveLayerIds) => {
7023
+ clusterPieManagers.current.forEach((mgr, layerId) => {
7024
+ if (!liveLayerIds.has(layerId)) {
7025
+ try {
7026
+ mgr.destroy();
7027
+ } catch {
7028
+ }
7029
+ clusterPieManagers.current.delete(layerId);
7030
+ }
7031
+ });
7032
+ const m = map.current;
7033
+ if (!m) return;
7034
+ let style;
7035
+ try {
7036
+ style = m.getStyle();
7037
+ } catch {
7038
+ return;
7039
+ }
7040
+ const layerPrefixes = ["heatmap-layer-", "cluster-count-", "clusters-", "unclustered-point-"];
7041
+ const sourcePrefixes = ["heatmap-source-", "cluster-source-"];
7042
+ ((style == null ? void 0 : style.layers) ?? []).forEach((sl) => {
7043
+ const prefix = layerPrefixes.find((p) => sl.id.startsWith(p));
7044
+ if (!prefix) return;
7045
+ const id = sl.id.slice(prefix.length);
7046
+ if (!liveLayerIds.has(id) && m.getLayer(sl.id)) {
7047
+ try {
7048
+ m.removeLayer(sl.id);
7049
+ } catch {
7050
+ }
7051
+ }
7052
+ });
7053
+ Object.keys((style == null ? void 0 : style.sources) ?? {}).forEach((sid) => {
7054
+ const prefix = sourcePrefixes.find((p) => sid.startsWith(p));
7055
+ if (!prefix) return;
7056
+ const id = sid.slice(prefix.length);
7057
+ if (!liveLayerIds.has(id) && m.getSource(sid)) {
7058
+ try {
7059
+ m.removeSource(sid);
7060
+ } catch {
7061
+ }
7062
+ }
7063
+ });
7064
+ }, []);
7065
+ react.useEffect(() => {
7066
+ if (!isMapLoaded) return;
7067
+ cleanupOrphanLayerSources(new Set(layers.map((l) => l.id)));
7068
+ }, [layers, isMapLoaded, cleanupOrphanLayerSources]);
7069
+ const applyHistoryState = react.useCallback(
7070
+ (featureIds, layerIds, targetFeatures, targetLayers) => {
7071
+ isApiAddingRef.current = true;
7072
+ isSelectingReadOnlyRef.current = true;
7073
+ try {
7074
+ featureIds.forEach((id) => {
7075
+ var _a;
7076
+ try {
7077
+ (_a = draw.current) == null ? void 0 : _a.delete(id);
7078
+ } catch {
7079
+ }
7080
+ });
7081
+ readOnlyFeatures.current.forEach((features, layerId) => {
7082
+ const filtered = features.filter((f) => !featureIds.has(String(f.id)));
7083
+ if (filtered.length !== features.length) readOnlyFeatures.current.set(layerId, filtered);
7084
+ });
7085
+ hiddenFeatures.current.forEach((features, layerId) => {
7086
+ const filtered = features.filter((f) => !featureIds.has(String(f.id)));
7087
+ if (filtered.length !== features.length) hiddenFeatures.current.set(layerId, filtered);
7088
+ });
7089
+ const readOnlyAdds = /* @__PURE__ */ new Map();
7090
+ const hiddenAdds = /* @__PURE__ */ new Map();
7091
+ featureIds.forEach((id) => {
7092
+ var _a;
7093
+ const entry = targetFeatures.get(id);
7094
+ if (!entry) return;
7095
+ if (entry.store === "draw") {
7096
+ try {
7097
+ (_a = draw.current) == null ? void 0 : _a.add(entry.feature);
7098
+ } catch {
7099
+ }
7100
+ } else if (entry.store === "readOnly") {
7101
+ const list = readOnlyAdds.get(entry.layerId) ?? [];
7102
+ list.push(entry.feature);
7103
+ readOnlyAdds.set(entry.layerId, list);
7104
+ } else {
7105
+ const list = hiddenAdds.get(entry.layerId) ?? [];
7106
+ list.push(entry.feature);
7107
+ hiddenAdds.set(entry.layerId, list);
7108
+ }
7109
+ });
7110
+ readOnlyAdds.forEach((features, layerId) => {
7111
+ readOnlyFeatures.current.set(layerId, [...readOnlyFeatures.current.get(layerId) ?? [], ...features]);
7112
+ });
7113
+ hiddenAdds.forEach((features, layerId) => {
7114
+ hiddenFeatures.current.set(layerId, [...hiddenFeatures.current.get(layerId) ?? [], ...features]);
7115
+ });
7116
+ const next = layersRef.current.slice();
7117
+ layerIds.forEach((id) => {
7118
+ const target = targetLayers.get(id);
7119
+ const idx = next.findIndex((l) => l.id === id);
7120
+ if (target && idx === -1) next.push(target);
7121
+ else if (target && idx !== -1) next[idx] = target;
7122
+ else if (!target && idx !== -1) {
7123
+ next.splice(idx, 1);
7124
+ readOnlyFeatures.current.delete(id);
7125
+ hiddenFeatures.current.delete(id);
7126
+ layerTemporalCacheRef.current.delete(id);
7127
+ }
7128
+ });
7129
+ layersRef.current = next;
7130
+ setLayers(next);
7131
+ } finally {
7132
+ isApiAddingRef.current = false;
7133
+ }
7134
+ cleanupOrphanLayerSources(new Set(layersRef.current.map((l) => l.id)));
7135
+ layerTemporalCacheRef.current.clear();
7136
+ updateFeatureCount();
7137
+ scheduleTimelineUpdate();
7138
+ syncFeaturesToCustomLayers();
7139
+ queueMicrotask(() => {
7140
+ isSelectingReadOnlyRef.current = false;
7141
+ });
7142
+ },
7143
+ [cleanupOrphanLayerSources, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers]
7144
+ );
7145
+ const buildDiffCommand = react.useCallback(
7146
+ (label, coalesceKey, before, after, beforeLayers, afterLayers, beforeSelectedIds, afterSelectedIds) => {
7147
+ const featureIds = /* @__PURE__ */ new Set();
7148
+ before.forEach((_v, k) => featureIds.add(k));
7149
+ after.forEach((_v, k) => featureIds.add(k));
7150
+ const layerIds = /* @__PURE__ */ new Set();
7151
+ beforeLayers.forEach((_v, k) => layerIds.add(k));
7152
+ afterLayers.forEach((_v, k) => layerIds.add(k));
7153
+ const featuresChanged = Array.from(featureIds).some((id) => {
7154
+ const b = before.get(id);
7155
+ const a = after.get(id);
7156
+ if (!b || !a || b.layerId !== a.layerId) return true;
7157
+ if (JSON.stringify(b.feature.geometry) !== JSON.stringify(a.feature.geometry)) return true;
7158
+ return JSON.stringify(b.feature.properties ?? {}) !== JSON.stringify(a.feature.properties ?? {});
7159
+ });
7160
+ const layersChanged = featuresChanged || Array.from(layerIds).some((id) => {
7161
+ const b = beforeLayers.get(id);
7162
+ const a = afterLayers.get(id);
7163
+ return !b || !a || JSON.stringify(b) !== JSON.stringify(a);
7164
+ });
7165
+ if (!featuresChanged && !layersChanged) return null;
7166
+ const pick = (src, keys) => {
7167
+ const out = /* @__PURE__ */ new Map();
7168
+ keys.forEach((k) => {
7169
+ const v = src.get(k);
7170
+ if (v !== void 0) out.set(k, v);
7171
+ });
7172
+ return out;
7173
+ };
7174
+ const beforeF = pick(before, featureIds);
7175
+ const afterF = pick(after, featureIds);
7176
+ const beforeL = pick(beforeLayers, layerIds);
7177
+ const afterL = pick(afterLayers, layerIds);
7178
+ return {
7179
+ label,
7180
+ coalesceKey,
7181
+ undo: () => {
7182
+ applyHistoryState(featureIds, layerIds, beforeF, beforeL);
7183
+ applySelectionState(beforeSelectedIds, { focusProperties: false });
7184
+ },
7185
+ redo: () => {
7186
+ applyHistoryState(featureIds, layerIds, afterF, afterL);
7187
+ applySelectionState(afterSelectedIds, { focusProperties: false });
7188
+ }
7189
+ };
7190
+ },
7191
+ [applyHistoryState, applySelectionState]
7192
+ );
7193
+ const finalizeCapture = react.useCallback(() => {
7194
+ const pending = pendingCaptureRef.current;
7195
+ pendingCaptureRef.current = null;
7196
+ if (!pending) return;
7197
+ const after = collectHistoryFeatures();
7198
+ const afterLayers = collectHistoryLayers();
7199
+ const command = buildDiffCommand(
7200
+ pending.label,
7201
+ pending.coalesceKey,
7202
+ pending.before,
7203
+ after,
7204
+ pending.beforeLayers,
7205
+ afterLayers,
7206
+ pending.beforeSelectedIds,
7207
+ [...selectedFeatureIdsRef.current]
7208
+ );
7209
+ if (command) {
7210
+ history.push(command);
7211
+ }
7212
+ }, [collectHistoryFeatures, collectHistoryLayers, buildDiffCommand, history]);
7213
+ const saveStateForUndo = react.useCallback(
7214
+ (label = "edit", options) => {
7215
+ if (isApiAddingRef.current) return;
7216
+ if (pendingCaptureRef.current) return;
7217
+ pendingCaptureRef.current = {
7218
+ label,
7219
+ coalesceKey: options == null ? void 0 : options.coalesceKey,
7220
+ before: collectHistoryFeatures({
7221
+ excludeDrawIds: options == null ? void 0 : options.excludeDrawIds,
7222
+ addDrawFeatures: options == null ? void 0 : options.addDrawFeatures
7223
+ }),
7224
+ beforeLayers: collectHistoryLayers(),
7225
+ beforeSelectedIds: [...selectedFeatureIdsRef.current]
7226
+ };
7227
+ requestAnimationFrame(finalizeCapture);
7228
+ },
7229
+ [collectHistoryFeatures, collectHistoryLayers, finalizeCapture]
7230
+ );
7231
+ const recordMoveFromPreDrag = react.useCallback(() => {
7232
+ const pre = preDragRef.current;
7233
+ preDragRef.current = null;
7234
+ if (!pre || isApiAddingRef.current || pendingCaptureRef.current) return;
7235
+ pendingCaptureRef.current = {
7236
+ label: "move feature",
7237
+ before: pre.features,
7238
+ beforeLayers: pre.layers,
7239
+ beforeSelectedIds: pre.selectedIds
7240
+ };
7241
+ requestAnimationFrame(finalizeCapture);
7242
+ }, [finalizeCapture]);
6902
7243
  react.useEffect(() => {
6903
7244
  if (!mapContainer.current || map.current) return;
6904
7245
  try {
@@ -7827,6 +8168,15 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7827
8168
  }
7828
8169
  });
7829
8170
  const processedFeatureIds = /* @__PURE__ */ new Set();
8171
+ mapInstance.on("mousedown", () => {
8172
+ if (draw.current && draw.current.getSelectedIds().length > 0) {
8173
+ preDragRef.current = {
8174
+ features: collectHistoryFeatures(),
8175
+ layers: collectHistoryLayers(),
8176
+ selectedIds: [...selectedFeatureIdsRef.current]
8177
+ };
8178
+ }
8179
+ });
7830
8180
  mapInstance.on("draw.create", (e) => {
7831
8181
  justCreatedFeatureRef.current = true;
7832
8182
  setTimeout(() => {
@@ -7916,7 +8266,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7916
8266
  }
7917
8267
  updateFeatureCount();
7918
8268
  scheduleTimelineUpdate();
7919
- saveStateForUndo();
8269
+ saveStateForUndo("draw feature", {
8270
+ excludeDrawIds: new Set(newFeatures.map((f) => String(f.id)))
8271
+ });
7920
8272
  syncRef.current();
7921
8273
  setTimeout(() => {
7922
8274
  setActiveMode("simple_select");
@@ -7973,7 +8325,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7973
8325
  syncRef.current();
7974
8326
  if (e.action === "change_coordinates" && !hasRevertedFeatures) {
7975
8327
  scheduleTimelineUpdate();
7976
- saveStateForUndo();
8328
+ recordMoveFromPreDrag();
7977
8329
  }
7978
8330
  });
7979
8331
  mapInstance.on("draw.delete", (e) => {
@@ -7989,7 +8341,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7989
8341
  });
7990
8342
  updateFeatureCount();
7991
8343
  scheduleTimelineUpdate();
7992
- saveStateForUndo();
8344
+ saveStateForUndo("delete feature", { addDrawFeatures: e.features });
7993
8345
  syncRef.current();
7994
8346
  onFeatureDelete == null ? void 0 : onFeatureDelete(deletedIds);
7995
8347
  });
@@ -8029,6 +8381,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8029
8381
  });
8030
8382
  mapInstance.on("click", (e) => {
8031
8383
  var _a;
8384
+ if (!enableSelectionRef.current) return;
8032
8385
  if (e.originalEvent.button !== 0) return;
8033
8386
  if (contextMenuFiredRef.current) return;
8034
8387
  if (Date.now() - shiftSelectionRef.current.completedAt < 300) return;
@@ -8305,6 +8658,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8305
8658
  listLayers: () => [...layersRef.current],
8306
8659
  addLayer: (name, geojson, options) => {
8307
8660
  if (!isMapLoadedRef.current) return "";
8661
+ if (options == null ? void 0 : options.recordHistory) saveStateForUndo(`add layer "${name}"`);
8308
8662
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8309
8663
  const newLayer = {
8310
8664
  id: layerId,
@@ -8397,9 +8751,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8397
8751
  }
8398
8752
  return newLayer.id;
8399
8753
  },
8400
- removeLayer: (layerId) => {
8754
+ removeLayer: (layerId, options) => {
8401
8755
  const layer = layersRef.current.find((l) => l.id === layerId);
8402
8756
  if (!layer || !isMapLoadedRef.current) return false;
8757
+ if (options == null ? void 0 : options.recordHistory) saveStateForUndo(`remove layer "${layer.name}"`);
8403
8758
  if (draw.current && !layer.readOnly) {
8404
8759
  layer.featureIds.forEach((id) => {
8405
8760
  try {
@@ -8476,10 +8831,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8476
8831
  syncRef.current();
8477
8832
  });
8478
8833
  },
8479
- addFeatures: (layerId, features) => {
8834
+ addFeatures: (layerId, features, options) => {
8480
8835
  var _a;
8481
8836
  const layer = layersRef.current.find((l) => l.id === layerId);
8482
8837
  if (!layer || !isMapLoadedRef.current) return [];
8838
+ if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
8483
8839
  if (layer.readOnly) {
8484
8840
  const existing = readOnlyFeatures.current.get(layerId) || [];
8485
8841
  let layerHasTemporal = ((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false;
@@ -8549,8 +8905,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8549
8905
  syncFeaturesToCustomLayers();
8550
8906
  return addedIds;
8551
8907
  },
8552
- removeFeatures: (featureIds) => {
8908
+ removeFeatures: (featureIds, options) => {
8553
8909
  if (!isMapLoaded) return;
8910
+ if (options == null ? void 0 : options.recordHistory) saveStateForUndo("remove features");
8554
8911
  const idSet = new Set(featureIds);
8555
8912
  if (draw.current) {
8556
8913
  featureIds.forEach((id) => {
@@ -8926,6 +9283,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8926
9283
  end: ts.rangeEnd
8927
9284
  };
8928
9285
  },
9286
+ // --- Undo / redo (also driven by the toolbar buttons + Ctrl/Cmd+Z) ---
9287
+ undo: () => history.undo(),
9288
+ redo: () => history.redo(),
9289
+ canUndo: () => history.canUndo,
9290
+ canRedo: () => history.canRedo,
9291
+ clearHistory: () => history.clear(),
9292
+ pushHistory: (command) => history.push(command),
8929
9293
  getMapUnsavedCount: () => {
8930
9294
  if (!draw.current) return 0;
8931
9295
  const allFeatures = draw.current.getAll().features;
@@ -8949,7 +9313,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8949
9313
  var _a;
8950
9314
  (_a = restoreEnrichedGeoJSONRef.current) == null ? void 0 : _a.call(restoreEnrichedGeoJSONRef, enriched);
8951
9315
  }
8952
- }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode]);
9316
+ }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode, saveStateForUndo, history]);
8953
9317
  const handleModeChange = react.useCallback((mode) => {
8954
9318
  if (!draw.current || !isMapLoaded) return;
8955
9319
  if (!hasVisibleLayers && mode !== "simple_select" && mode !== "view_select") {
@@ -8985,60 +9349,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8985
9349
  setActiveMode(mode);
8986
9350
  draw.current.changeMode(mode);
8987
9351
  }, [isMapLoaded, hasVisibleLayers, toast]);
8988
- const handleUndo = react.useCallback(() => {
8989
- if (undoStack.length === 0 || !draw.current) return;
8990
- const currentState = {
8991
- features: draw.current.getAll().features,
8992
- layers: JSON.parse(JSON.stringify(layers)),
8993
- selectedIds: [...selectedFeatureIds]
8994
- };
8995
- const prevState = undoStack[undoStack.length - 1];
8996
- isSelectingReadOnlyRef.current = true;
8997
- draw.current.deleteAll();
8998
- isApiAddingRef.current = true;
8999
- try {
9000
- prevState.features.forEach((f) => draw.current.add(f));
9001
- } finally {
9002
- isApiAddingRef.current = false;
9003
- }
9004
- setLayers(prevState.layers);
9005
- applySelectionState(prevState.selectedIds, { focusProperties: false });
9006
- setUndoStack((prev) => prev.slice(0, -1));
9007
- setRedoStack((prev) => [...prev, currentState]);
9008
- updateFeatureCount();
9009
- layerTemporalCacheRef.current.clear();
9010
- scheduleTimelineUpdate();
9011
- syncFeaturesToCustomLayers();
9012
- layersRef.current = prevState.layers;
9013
- onUndo == null ? void 0 : onUndo(computeUndoRedoEvent(currentState, prevState));
9014
- }, [undoStack, layers, selectedFeatureIds, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, applySelectionState, onUndo]);
9015
- const handleRedo = react.useCallback(() => {
9016
- if (redoStack.length === 0 || !draw.current) return;
9017
- const currentState = {
9018
- features: draw.current.getAll().features,
9019
- layers: JSON.parse(JSON.stringify(layers)),
9020
- selectedIds: [...selectedFeatureIds]
9021
- };
9022
- const nextState = redoStack[redoStack.length - 1];
9023
- isSelectingReadOnlyRef.current = true;
9024
- draw.current.deleteAll();
9025
- isApiAddingRef.current = true;
9026
- try {
9027
- nextState.features.forEach((f) => draw.current.add(f));
9028
- } finally {
9029
- isApiAddingRef.current = false;
9030
- }
9031
- setLayers(nextState.layers);
9032
- applySelectionState(nextState.selectedIds, { focusProperties: false });
9033
- setRedoStack((prev) => prev.slice(0, -1));
9034
- setUndoStack((prev) => [...prev, currentState]);
9035
- updateFeatureCount();
9036
- layerTemporalCacheRef.current.clear();
9037
- scheduleTimelineUpdate();
9038
- syncFeaturesToCustomLayers();
9039
- layersRef.current = nextState.layers;
9040
- onRedo == null ? void 0 : onRedo(computeUndoRedoEvent(currentState, nextState));
9041
- }, [redoStack, layers, selectedFeatureIds, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, applySelectionState, onRedo]);
9042
9352
  const handleClear = react.useCallback(() => {
9043
9353
  if (!draw.current) return;
9044
9354
  const activeLayer = layersRef.current.find((l) => l.id === activeEditingLayerId);
@@ -9181,12 +9491,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9181
9491
  const isCtrlOrCmd = e.ctrlKey || e.metaKey;
9182
9492
  if (isCtrlOrCmd && key === "z" && !e.shiftKey) {
9183
9493
  e.preventDefault();
9184
- handleUndo();
9494
+ history.undo();
9185
9495
  return;
9186
9496
  }
9187
9497
  if (isCtrlOrCmd && (key === "y" || key === "z" && e.shiftKey)) {
9188
9498
  e.preventDefault();
9189
- handleRedo();
9499
+ history.redo();
9190
9500
  return;
9191
9501
  }
9192
9502
  if (key === "e" && !isCtrlOrCmd && !e.altKey) {
@@ -9238,7 +9548,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9238
9548
  };
9239
9549
  container.addEventListener("keydown", handleKeyDown);
9240
9550
  return () => container.removeEventListener("keydown", handleKeyDown);
9241
- }, [isMapLoaded, enableKeyboardShortcuts, isEditMode, activeMode, handleToggleEditMode, handleUndo, handleRedo, handleModeChange, selectedFeatureIds, handleDeleteSelected, canDeleteSelected, hiddenDrawingTools]);
9551
+ }, [isMapLoaded, enableKeyboardShortcuts, isEditMode, activeMode, handleToggleEditMode, history, handleModeChange, selectedFeatureIds, handleDeleteSelected, canDeleteSelected, hiddenDrawingTools]);
9242
9552
  const createPointAtCoords = react.useCallback((lng, lat) => {
9243
9553
  if (!draw.current || !isMapLoaded) return;
9244
9554
  if (!isEditModeRef.current) {
@@ -10022,30 +10332,35 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10022
10332
  }, [loadBasemapStyle, setBasemapVisibility, moveLabelsBeforeBasemapSymbols]);
10023
10333
  handleMapStyleChangeRef.current = handleMapStyleChange;
10024
10334
  const handleUpdateTraceConfig = react.useCallback((layerId, config) => {
10335
+ saveStateForUndo("trace config", { coalesceKey: `traceConfig:${layerId}` });
10025
10336
  setLayers((prev) => prev.map(
10026
10337
  (l) => l.id === layerId ? { ...l, traceConfig: config } : l
10027
10338
  ));
10028
- }, []);
10339
+ }, [saveStateForUndo]);
10029
10340
  const handleUpdateHeatmapConfig = react.useCallback((layerId, config) => {
10341
+ saveStateForUndo("heatmap config", { coalesceKey: `heatmapConfig:${layerId}` });
10030
10342
  setLayers((prev) => prev.map(
10031
10343
  (l) => l.id === layerId ? { ...l, heatmapConfig: config } : l
10032
10344
  ));
10033
- }, []);
10345
+ }, [saveStateForUndo]);
10034
10346
  const handleUpdateClusterConfig = react.useCallback((layerId, config) => {
10347
+ saveStateForUndo("cluster config", { coalesceKey: `clusterConfig:${layerId}` });
10035
10348
  setLayers((prev) => prev.map(
10036
10349
  (l) => l.id === layerId ? { ...l, clusterConfig: config } : l
10037
10350
  ));
10038
- }, []);
10351
+ }, [saveStateForUndo]);
10039
10352
  const handleUpdateVisualConfig = react.useCallback((layerId, config) => {
10353
+ saveStateForUndo("style config", { coalesceKey: `visualConfig:${layerId}` });
10040
10354
  setLayers((prev) => prev.map(
10041
10355
  (l) => l.id === layerId ? { ...l, visualConfig: config } : l
10042
10356
  ));
10043
- }, []);
10357
+ }, [saveStateForUndo]);
10044
10358
  const handleUpdateAltitudeDisplayMode = react.useCallback((layerId, mode) => {
10359
+ saveStateForUndo("altitude mode", { coalesceKey: `altitude:${layerId}` });
10045
10360
  setLayers((prev) => prev.map(
10046
10361
  (l) => l.id === layerId ? { ...l, altitudeDisplayMode: mode } : l
10047
10362
  ));
10048
- }, []);
10363
+ }, [saveStateForUndo]);
10049
10364
  const handleUpdateAutoLabelConfig = react.useCallback((config) => {
10050
10365
  setAutoLabelConfig(config);
10051
10366
  }, []);
@@ -10430,6 +10745,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10430
10745
  react.useEffect(() => {
10431
10746
  selectedFeatureIdsRef.current = selectedFeatureIds;
10432
10747
  }, [selectedFeatureIds]);
10748
+ const enableSelectionRef = react.useRef(enableSelection);
10749
+ react.useEffect(() => {
10750
+ enableSelectionRef.current = enableSelection;
10751
+ }, [enableSelection]);
10752
+ const enableDrawingRef = react.useRef(enableDrawing);
10753
+ react.useEffect(() => {
10754
+ enableDrawingRef.current = enableDrawing;
10755
+ }, [enableDrawing]);
10433
10756
  react.useEffect(() => {
10434
10757
  if (!map.current || !isMapLoaded) {
10435
10758
  return;
@@ -10928,6 +11251,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10928
11251
  },
10929
11252
  geometry: circle.geometry
10930
11253
  };
11254
+ saveStateForUndo("draw circle");
10931
11255
  drawInstance.add(circleFeature);
10932
11256
  const currentActiveEditingLayerId = activeEditingLayerIdRef.current;
10933
11257
  setLayers((prev) => {
@@ -10943,12 +11267,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10943
11267
  syncFeaturesToCustomLayers();
10944
11268
  const newCount = drawInstance.getAll().features.length;
10945
11269
  setFeatureCount(newCount);
10946
- setUndoStack((prev) => [...prev, {
10947
- features: drawInstance.getAll().features,
10948
- selectedIds: [featureId],
10949
- layers: layersRef.current
10950
- }]);
10951
- setRedoStack([]);
10952
11270
  drawInstance.changeMode("simple_select", { featureIds: [featureId] });
10953
11271
  setActiveMode("simple_select");
10954
11272
  setSelectedFeatureIds([featureId]);
@@ -11055,6 +11373,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11055
11373
  coordinates: [rectCoords]
11056
11374
  }
11057
11375
  };
11376
+ saveStateForUndo("draw rectangle");
11058
11377
  drawInstance.add(rectFeature);
11059
11378
  const currentActiveEditingLayerId = activeEditingLayerIdRef.current;
11060
11379
  setLayers((prev) => {
@@ -11070,12 +11389,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11070
11389
  syncFeaturesToCustomLayers();
11071
11390
  const newCount = drawInstance.getAll().features.length;
11072
11391
  setFeatureCount(newCount);
11073
- setUndoStack((prev) => [...prev, {
11074
- features: drawInstance.getAll().features,
11075
- selectedIds: [featureId],
11076
- layers: layersRef.current
11077
- }]);
11078
- setRedoStack([]);
11079
11392
  justCreatedRectangleRef.current = true;
11080
11393
  drawInstance.changeMode("simple_select", { featureIds: [featureId] });
11081
11394
  setActiveMode("simple_select");
@@ -12512,13 +12825,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12512
12825
  onModeChange: handleModeChange,
12513
12826
  onClear: handleClear,
12514
12827
  onDeleteSelected: handleDeleteSelected,
12515
- onUndo: handleUndo,
12516
- onRedo: handleRedo,
12828
+ onUndo: history.undo,
12829
+ onRedo: history.redo,
12517
12830
  featureCount,
12518
12831
  selectedCount: selectedFeatureIds.length,
12519
12832
  canDeleteSelected,
12520
- canUndo: undoStack.length > 0,
12521
- canRedo: redoStack.length > 0,
12833
+ canUndo: history.canUndo,
12834
+ canRedo: history.canRedo,
12835
+ showUndoRedo: true,
12522
12836
  disabled: !isMapLoaded,
12523
12837
  isEditMode,
12524
12838
  onToggleEditMode: handleToggleEditMode,