@tmagic/editor 1.8.6 → 1.8.7

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.
@@ -4235,6 +4235,13 @@
4235
4235
  }
4236
4236
  };
4237
4237
  // packages/editor/src/utils/undo-redo.ts
4238
+ /** 各历史栈 index 0 的 initial 是撤销下限(见 utils/history.ts 的 undoFloor),裁剪时不能把它挤掉。 */
4239
+ var isInitialStep = (step) => step?.opType === "initial";
4240
+ /**
4241
+ * 容量按「真实步骤数」计算:index 0 的 initial 基线额外占一个位置,不挤掉真实记录。
4242
+ * 只要真实步骤没超限,最老一条的 oldSchema 仍指向加载时的 DSL,「回到初始」就是可达的。
4243
+ */
4244
+ var maxLength = (list, listMaxSize) => listMaxSize + (isInitialStep(list[0]) ? 1 : 0);
4238
4245
  var UndoRedo = class UndoRedo {
4239
4246
  /**
4240
4247
  * 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
@@ -4245,13 +4252,9 @@
4245
4252
  */
4246
4253
  static fromSerialized(data, options = {}) {
4247
4254
  const undoRedo = new UndoRedo(data.listMaxSize);
4255
+ undoRedo.initialReachable = data.initialReachable !== false;
4248
4256
  const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
4249
4257
  let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
4250
- const overflow = list.length - undoRedo.listMaxSize;
4251
- if (overflow > 0) {
4252
- list.splice(0, overflow);
4253
- cursor -= overflow;
4254
- }
4255
4258
  if (options.isSavedStep) {
4256
4259
  for (let i = list.length - 1; i >= 0; i--) if (options.isSavedStep(list[i])) {
4257
4260
  cursor = i + 1;
@@ -4265,7 +4268,9 @@
4265
4268
  elementList;
4266
4269
  listCursor;
4267
4270
  listMaxSize;
4268
- constructor(listMaxSize = 100) {
4271
+ /** 容量裁剪是否删掉过已应用的真实步骤(撤销链已断,「回到初始」不可达)。 */
4272
+ initialReachable = true;
4273
+ constructor(listMaxSize = 1e3) {
4269
4274
  const minListMaxSize = 2;
4270
4275
  this.elementList = [];
4271
4276
  this.listCursor = 0;
@@ -4279,16 +4284,55 @@
4279
4284
  return {
4280
4285
  elementList: this.elementList.map((item) => cloneDeep(item)),
4281
4286
  listCursor: this.listCursor,
4282
- listMaxSize: this.listMaxSize
4287
+ listMaxSize: this.listMaxSize,
4288
+ initialReachable: this.initialReachable
4283
4289
  };
4284
4290
  }
4285
4291
  pushElement(element) {
4286
4292
  this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
4287
4293
  this.listCursor += 1;
4288
- if (this.elementList.length > this.listMaxSize) {
4289
- this.elementList.shift();
4294
+ }
4295
+ /**
4296
+ * 把栈裁剪到容量上限(`listMaxSize` 条真实步骤,index 0 的 initial 基线额外占一个位置)。
4297
+ *
4298
+ * 只在保存后调用(见 historyService.markSaved):保存前不裁剪,避免用户还没落库就丢掉可撤销的历史。
4299
+ * **永不删除** initial 基线与「整体设置 root」产生的记录(`rootStep`);
4300
+ * 受保护记录本身占满容量时栈保持超限。
4301
+ *
4302
+ * 分两个阶段删除,保证撤销链与重做链各自连续:
4303
+ * 1. 先从最旧的记录开始删**已应用**区(游标之前)的可删记录,撤销链仍然连续;
4304
+ * 2. 已应用区删无可删仍超限时,溢出量落在重做区。重做链必须连续——后一条是按前一条的 DSL 打的补丁,
4305
+ * 只删掉开头几条会让留下的步骤叠在缺失的基线上,因此整段丢弃游标之后的步骤。
4306
+ * (不从重做区末尾往前删:重做区里可能有受保护的 `rootStep`,跳过它去删它前面的步骤同样会留空洞。)
4307
+ *
4308
+ * 「回到初始」是否仍可达,取决于被删的已应用步骤相对最早一条 `rootStep` 的位置:
4309
+ * - 位于其**之后**:撤销链完整——一直撤销会退到这条整页快照,再撤销它即回到加载时的 DSL,仍可达;
4310
+ * - 位于其**之前**(或栈内没有 `rootStep`):撤到底只能停在中途版本,标记为不可达。
4311
+ * 只删掉重做区记录时不影响可达性。
4312
+ */
4313
+ trim() {
4314
+ let overflow = this.elementList.length - maxLength(this.elementList, this.listMaxSize);
4315
+ if (overflow <= 0) return;
4316
+ let seenRootStep = false;
4317
+ let brokenChain = false;
4318
+ for (let index = 0; index < this.listCursor && overflow > 0;) {
4319
+ const step = this.elementList[index];
4320
+ if (isInitialStep(step)) {
4321
+ index += 1;
4322
+ continue;
4323
+ }
4324
+ if (step?.rootStep === true) {
4325
+ seenRootStep = true;
4326
+ index += 1;
4327
+ continue;
4328
+ }
4329
+ this.elementList.splice(index, 1);
4330
+ overflow -= 1;
4290
4331
  this.listCursor -= 1;
4332
+ if (!seenRootStep) brokenChain = true;
4291
4333
  }
4334
+ if (overflow > 0 && this.elementList.length > this.listCursor) this.elementList.length = this.listCursor;
4335
+ if (brokenChain) this.initialReachable = false;
4292
4336
  }
4293
4337
  canUndo() {
4294
4338
  return this.listCursor > 0;
@@ -4355,6 +4399,10 @@
4355
4399
  getLength() {
4356
4400
  return this.elementList.length;
4357
4401
  }
4402
+ /** 「回到初始」是否可达:容量裁剪删掉已应用的真实步骤后撤销链断开,返回 false。 */
4403
+ isInitialReachable() {
4404
+ return this.initialReachable;
4405
+ }
4358
4406
  };
4359
4407
  // packages/editor/src/utils/history.ts
4360
4408
  /**
@@ -4418,6 +4466,11 @@
4418
4466
  extra: payload.extra
4419
4467
  };
4420
4468
  };
4469
+ /**
4470
+ * 把栈当前游标所在的记录标记为「已保存」,随后把栈裁剪到容量上限(见 {@link UndoRedo.trim})。
4471
+ * 入栈与还原都不裁剪,只有保存后才收敛,避免用户在落库前丢掉可撤销的历史;
4472
+ * initial 基线与「整体设置 root」产生的记录(`rootStep`)不会被裁掉。
4473
+ */
4421
4474
  var markStackSaved = (undoRedo) => {
4422
4475
  if (!undoRedo) return;
4423
4476
  undoRedo.updateElements((element) => {
@@ -4426,6 +4479,7 @@
4426
4479
  undoRedo.updateCurrentElement((element) => {
4427
4480
  element.saved = true;
4428
4481
  });
4482
+ undoRedo.trim();
4429
4483
  };
4430
4484
  /**
4431
4485
  * 把单个历史栈(页面 / 代码块 / 数据源 / 扩展类型)的步骤列表按"目标"做相邻合并:
@@ -4537,20 +4591,33 @@
4537
4591
  *
4538
4592
  * 与 {@link serializeStacks} 相反:当传入 `parse`(parseDSL)时,把每条 step 中以字符串形式存储的 `diff`
4539
4593
  * 解析回真实对象(含函数);不含 `diff` 的元素(如通用栈)原样透传。
4594
+ *
4595
+ * 单个栈解析失败只丢弃该栈,其余栈照常还原:一条损坏的快照不应该让整份本地历史都不可用。
4596
+ * 结构性损坏(`elementList` 不是数组)同样按空栈处理,交给 {@link UndoRedo.fromSerialized} 兜底。
4597
+ * 全部栈都失败时抛出首个错误,避免调用方把「什么都没恢复」当成一次成功的还原。
4540
4598
  */
4541
4599
  var deserializeStacks = (stacks = {}, parse) => {
4542
4600
  const result = {};
4601
+ let firstError;
4602
+ let failedCount = 0;
4543
4603
  Object.entries(stacks).forEach(([id, serialized]) => {
4544
4604
  if (!serialized) return;
4545
- const elementList = parse ? serialized.elementList.map((step) => {
4546
- const { diff } = step;
4547
- return typeof diff === "string" ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
4548
- }) : serialized.elementList;
4549
- result[id] = UndoRedo.fromSerialized({
4550
- ...serialized,
4551
- elementList
4552
- }, { isSavedStep: (element) => element.saved === true });
4605
+ const source = Array.isArray(serialized.elementList) ? serialized.elementList : [];
4606
+ try {
4607
+ const elementList = parse ? source.map((step) => {
4608
+ const { diff } = step;
4609
+ return typeof diff === "string" ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
4610
+ }) : source;
4611
+ result[id] = UndoRedo.fromSerialized({
4612
+ ...serialized,
4613
+ elementList
4614
+ }, { isSavedStep: (element) => element.saved === true });
4615
+ } catch (error) {
4616
+ failedCount += 1;
4617
+ firstError ??= error;
4618
+ }
4553
4619
  });
4620
+ if (failedCount > 0 && Object.keys(result).length === 0) throw firstError;
4554
4621
  return result;
4555
4622
  };
4556
4623
  /**
@@ -6512,6 +6579,14 @@
6512
6579
  return parentNode;
6513
6580
  };
6514
6581
  // packages/editor/src/sdk/services/Editor.ts
6582
+ /**
6583
+ * 撤销 / 重做回放的内部标记键:不导出,也不出现在公开的 {@link HistoryOpOptions} 里。
6584
+ * 回放链路用它把 `isHistoryOp` 带进 `change` 事件;外部调用方即使传同名字符串字段也不会被读取,
6585
+ * 避免一次真实编辑被误标成历史回放,从而绕过业务侧的加锁 / 埋点 / 自动保存。
6586
+ */
6587
+ var HISTORY_OP = Symbol("isHistoryOp");
6588
+ /** 读取仅供编辑器内部使用的回放标记。 */
6589
+ var isReplay = (options) => options[HISTORY_OP] === true;
6515
6590
  /** 把插入下标收敛到 [0, length]:非整数取整,非法 / 越界(含未记录)一律追加到末尾 */
6516
6591
  var clampIndex = (index, length) => {
6517
6592
  const normalized = typeof index === "number" ? Math.trunc(index) : length;
@@ -6826,6 +6901,7 @@
6826
6901
  async add(addNode, parent, options = {}) {
6827
6902
  this.captureSelectionBeforeOp();
6828
6903
  const { doNotSelect = false, doNotSwitchPage = false, doNotPushHistory = false, historyDescription, historySource } = options;
6904
+ const isHistoryOp = isReplay(options);
6829
6905
  const stage = this.get("stage");
6830
6906
  const addNodes = [];
6831
6907
  if (!Array.isArray(addNode)) {
@@ -6903,7 +6979,8 @@
6903
6979
  page: this.getPageOfNode(node.id)
6904
6980
  })),
6905
6981
  historySource,
6906
- doNotPushHistory
6982
+ doNotPushHistory,
6983
+ isHistoryOp
6907
6984
  });
6908
6985
  const addedPages = newNodes.filter((node) => (0, _tmagic_utils.isPageOrFragment)(node));
6909
6986
  if (addedPages.length) this.ctx.history.notifyPageStructureChange({
@@ -6974,6 +7051,7 @@
6974
7051
  */
6975
7052
  async remove(nodeOrNodeList, options = {}) {
6976
7053
  const { doNotPushHistory = false, historyDescription, historySource } = options;
7054
+ const isHistoryOp = isReplay(options);
6977
7055
  this.captureSelectionBeforeOp();
6978
7056
  const nodes = Array.isArray(nodeOrNodeList) ? nodeOrNodeList : [nodeOrNodeList];
6979
7057
  const changeItems = nodes.map((node) => ({
@@ -7013,7 +7091,8 @@
7013
7091
  type: "remove",
7014
7092
  data: changeItems,
7015
7093
  historySource,
7016
- doNotPushHistory
7094
+ doNotPushHistory,
7095
+ isHistoryOp
7017
7096
  });
7018
7097
  const removedPages = nodes.filter((node) => (0, _tmagic_utils.isPageOrFragment)(node));
7019
7098
  if (removedPages.length) this.ctx.history.notifyPageStructureChange({
@@ -7077,6 +7156,7 @@
7077
7156
  async update(config, data = {}) {
7078
7157
  this.captureSelectionBeforeOp();
7079
7158
  const { doNotPushHistory = false, changeRecordList, changeRecords, historyDescription, historySource, invalidInfo } = data;
7159
+ const isHistoryOp = isReplay(data);
7080
7160
  const nodes = Array.isArray(config) ? config : [config];
7081
7161
  const commitInvalid = await this.runGuard(() => this.ctx.validator.guardUpdate(nodes, { replace: data.replace }));
7082
7162
  const updateData = await Promise.all(nodes.map((node, index) => {
@@ -7116,7 +7196,8 @@
7116
7196
  page: this.getPageOfNode(node.newNode.id)
7117
7197
  })),
7118
7198
  historySource,
7119
- doNotPushHistory
7199
+ doNotPushHistory,
7200
+ isHistoryOp
7120
7201
  });
7121
7202
  return Array.isArray(config) ? updateData.map((item) => item.newNode) : updateData[0].newNode;
7122
7203
  }
@@ -7244,7 +7325,9 @@
7244
7325
  * @param options 可选配置
7245
7326
  * @param options.doNotPushHistory 是否不写入历史记录(默认 false)
7246
7327
  */
7247
- async moveLayer(offset, { doNotPushHistory = false, historyDescription, historySource } = {}) {
7328
+ async moveLayer(offset, options = {}) {
7329
+ const { doNotPushHistory = false, historyDescription, historySource } = options;
7330
+ const isHistoryOp = isReplay(options);
7248
7331
  this.captureSelectionBeforeOp();
7249
7332
  const root = this.get("root");
7250
7333
  if (!root) throw new Error("root为空");
@@ -7291,7 +7374,8 @@
7291
7374
  }],
7292
7375
  offset,
7293
7376
  historySource,
7294
- doNotPushHistory
7377
+ doNotPushHistory,
7378
+ isHistoryOp
7295
7379
  });
7296
7380
  }
7297
7381
  /**
@@ -7364,7 +7448,9 @@
7364
7448
  } else this.selectionBeforeOp = null;
7365
7449
  return isBatch ? newConfigs : newConfigs[0];
7366
7450
  }
7367
- async dragTo(config, targetParent, targetIndex, { doNotPushHistory = false, historyDescription, historySource } = {}) {
7451
+ async dragTo(config, targetParent, targetIndex, options = {}) {
7452
+ const { doNotPushHistory = false, historyDescription, historySource } = options;
7453
+ const isHistoryOp = isReplay(options);
7368
7454
  this.captureSelectionBeforeOp();
7369
7455
  if (!targetParent || !Array.isArray(targetParent.items)) return;
7370
7456
  const configs = Array.isArray(config) ? config : [config];
@@ -7431,7 +7517,8 @@
7431
7517
  targetIndex,
7432
7518
  targetParent,
7433
7519
  historySource,
7434
- doNotPushHistory
7520
+ doNotPushHistory,
7521
+ isHistoryOp
7435
7522
  });
7436
7523
  }
7437
7524
  /**
@@ -7531,7 +7618,8 @@
7531
7618
  * @returns 反向后产生的新 step;目标不存在 / 未应用 / 反向失败时返回 null
7532
7619
  */
7533
7620
  async revertPageStep(index) {
7534
- const entry = this.ctx.history.getStepList("page", this.get("page")?.id)[index];
7621
+ const pageId = this.get("page")?.id;
7622
+ const entry = this.ctx.history.getStepList("page", pageId)[index];
7535
7623
  if (!entry?.applied) return null;
7536
7624
  const { step } = entry;
7537
7625
  if (step.opType === "initial") return null;
@@ -7541,10 +7629,10 @@
7541
7629
  if (!items.length || !items.every((item) => item.changeRecords?.length)) return null;
7542
7630
  }
7543
7631
  let revertedStep = null;
7544
- const captureRevert = (_pageId, s) => {
7545
- revertedStep = s;
7632
+ const captureRevert = (s, type, id) => {
7633
+ if (type === "page" && id === pageId && !revertedStep) revertedStep = s;
7546
7634
  };
7547
- this.ctx.history.once("change", captureRevert);
7635
+ this.ctx.history.on("change", captureRevert);
7548
7636
  const historyDescription = `回滚 #${index + 1}: ${describeStepForRevert(step)}`;
7549
7637
  const opts = {
7550
7638
  doNotSelect: true,
@@ -7854,9 +7942,11 @@
7854
7942
  /**
7855
7943
  * 构造一条页面级「set root」历史记录(不携带选区 / modifiedNodeIds 上下文)并落到该页面自己的栈。
7856
7944
  *
7857
- * 连续 set root 替换:若该页栈最新一条已是**同来源**的 set root 记录({@link StepValue.rootStep} 且 `source` 相同),
7858
- * 则用本次记录**替换**它而非新增,避免源码反复保存 / 外部重设 DSL 时堆积多条 root 记录;
7859
- * 来源不同则照常新增(initial 基线不是 rootStep,不在此列)。
7945
+ * 连续 set root 替换:若该页栈最新一条已是**同来源、同为整页 update**的 set root 记录
7946
+ * ({@link StepValue.rootStep} 且 `source` 相同),则用本次记录**替换**它而非新增,避免源码反复保存时堆积记录。
7947
+ * 替换时必须把 `oldSchema` 追溯到最早那一跳,并沿用原 uuid:否则只剩「上一版 → 本版」,
7948
+ * 撤销到基线时 DSL 会停在中途版本且无法继续回退,已发出的 historyId 也会失效。
7949
+ * 其余情况(来源不同 / 页面增删)照常新增,保留完整变更链条。
7860
7950
  */
7861
7951
  pushPageDiffStep(opType, page, diffItem, source) {
7862
7952
  const step = {
@@ -7876,8 +7966,19 @@
7876
7966
  };
7877
7967
  if (source) step.source = source;
7878
7968
  const top = this.ctx.history.getCurrentPageStep(page.id);
7879
- if (top?.rootStep && top.source === source) this.ctx.history.replaceCurrentStep("page", step, page.id);
7880
- else this.ctx.history.push("page", step, page.id);
7969
+ const earliestOldSchema = top?.diff?.[0]?.oldSchema;
7970
+ if (top?.rootStep && top.source === source && opType === "update" && top.opType === "update" && earliestOldSchema) {
7971
+ this.ctx.history.replaceCurrentStep("page", {
7972
+ ...step,
7973
+ uuid: top.uuid,
7974
+ diff: [{
7975
+ ...diffItem,
7976
+ oldSchema: earliestOldSchema
7977
+ }]
7978
+ }, page.id);
7979
+ return;
7980
+ }
7981
+ this.ctx.history.push("page", step, page.id);
7881
7982
  }
7882
7983
  pushOpHistory(opType, { diff, pageData, historyDescription, source }) {
7883
7984
  const step = {
@@ -7909,8 +8010,8 @@
7909
8010
  * 「重新插回节点」(撤销 remove / 重做 add)需按 step 记录的 parentId / index 精确还原,
7910
8011
  * 不走 this.add,由手工 splice + stage.add 完成后补发等价的 add / change 事件(见 emitHistoryInsertEvents)。
7911
8012
  *
7912
- * 注意:这些路径都会发出 add / remove / update / change 事件,业务侧若需要区分"用户操作"与"撤销重做触发",
7913
- * 请监听 `history-change` 事件配合判断。
8013
+ * 注意:这些路径都会发出 add / remove / update / change 事件,且 `change` 事件带 `isHistoryOp: true`,
8014
+ * 业务侧可据此跳过仅针对「用户主动编辑」的副作用(加锁 / 埋点 / 自动保存等)。
7914
8015
  *
7915
8016
  * @param step 操作记录
7916
8017
  * @param reverse true = 撤销,false = 重做
@@ -7924,6 +8025,7 @@
7924
8025
  doNotSelect: true,
7925
8026
  doNotSwitchPage: true,
7926
8027
  doNotPushHistory: true,
8028
+ [HISTORY_OP]: true,
7927
8029
  historySource: step.source
7928
8030
  };
7929
8031
  switch (step.opType) {
@@ -8007,10 +8109,7 @@
8007
8109
  }
8008
8110
  return cloneDeep(reverse ? oldNode : newNode);
8009
8111
  });
8010
- if (configs.length) await this.update(configs, {
8011
- doNotPushHistory: true,
8012
- historySource: step.source
8013
- });
8112
+ if (configs.length) await this.update(configs, commonOpts);
8014
8113
  break;
8015
8114
  }
8016
8115
  }
@@ -8048,7 +8147,8 @@
8048
8147
  page: this.getPageOfNode(node.id)
8049
8148
  })),
8050
8149
  historySource: source,
8051
- doNotPushHistory: true
8150
+ doNotPushHistory: true,
8151
+ isHistoryOp: true
8052
8152
  });
8053
8153
  }
8054
8154
  /** 经由 reactivity 注入的 toRaw(默认是 Vue 的 toRaw) */
@@ -8195,8 +8295,9 @@
8195
8295
  * 注册一个扩展历史类型,使其可与内置 `page` / `codeBlock` / `dataSource` 一样走统一的
8196
8296
  * {@link push} / {@link undo} / {@link redo}(按 id 分栈、独立 undo/redo)。
8197
8297
  *
8298
+ * 扩展类型与内置类型一样统一派发 `change` 事件,无需(也不支持)单独指定事件名。
8299
+ *
8198
8300
  * @param stepType 自定义历史类型标识(勿与内置类型重名)
8199
- * @param options.event push/undo/redo 后派发的事件名,缺省为 `${stepType}-history-change`
8200
8301
  * @param options.name 历史面板中的展示名称(tab / 分组标题等),缺省回退到 stepType 本身
8201
8302
  */
8202
8303
  registerStepType(stepType, options = {}) {
@@ -8280,11 +8381,20 @@
8280
8381
  const first = this.state.steps[stepType]?.[id]?.getElementList()[0];
8281
8382
  return first?.opType === "initial" ? first : void 0;
8282
8383
  }
8384
+ /**
8385
+ * 目标栈「回到初始」是否可达:容量裁剪删掉已应用的真实步骤后撤销链断开,返回 false。
8386
+ * 与是否存在 {@link getMarker} 基线无关——没有基线的栈同样可能因裁剪回不到加载时的 DSL,
8387
+ * 历史面板的各 tab 统一用它判断初始行是否可高亮 / 可点击。
8388
+ */
8389
+ isInitialReachable(stepType, id) {
8390
+ if (!this.isValidStackId(id)) return true;
8391
+ return this.state.steps[stepType]?.[id]?.isInitialReachable() ?? true;
8392
+ }
8283
8393
  push(stepType, step, id) {
8284
8394
  if (!this.isValidStackId(id)) return null;
8285
8395
  this.fillStepMeta(step);
8286
8396
  getOrCreateStack(this.getStepBucket(stepType), id).pushElement(step);
8287
- this.emit("change", step, stepType, id);
8397
+ this.emitStepChange(step, stepType, id);
8288
8398
  return step;
8289
8399
  }
8290
8400
  undo(stepType, id) {
@@ -8293,7 +8403,7 @@
8293
8403
  if (!undoRedo) return null;
8294
8404
  if (undoRedo.getCursor() <= undoFloor(undoRedo)) return null;
8295
8405
  const step = undoRedo.undo();
8296
- if (step) this.emit("change", step, stepType, id);
8406
+ if (step) this.emitStepChange(step, stepType, id, true);
8297
8407
  return step;
8298
8408
  }
8299
8409
  redo(stepType, id) {
@@ -8301,7 +8411,7 @@
8301
8411
  const undoRedo = this.state.steps[stepType]?.[id];
8302
8412
  if (!undoRedo) return null;
8303
8413
  const step = undoRedo.redo();
8304
- if (step) this.emit("change", step, stepType, id);
8414
+ if (step) this.emitStepChange(step, stepType, id, true);
8305
8415
  return step;
8306
8416
  }
8307
8417
  /**
@@ -8337,7 +8447,7 @@
8337
8447
  const undoRedo = getOrCreateStack(this.getStepBucket(stepType), id);
8338
8448
  this.fillStepMeta(state);
8339
8449
  if (!undoRedo.replaceCurrentElement(state)) return null;
8340
- this.emit("change", state, stepType, id);
8450
+ this.emitStepChange(state, stepType, id);
8341
8451
  return state;
8342
8452
  }
8343
8453
  destroy() {
@@ -8374,6 +8484,9 @@
8374
8484
  *
8375
8485
  * 同一栈内任意时刻最多只有一条记录为 `saved`;从 IndexedDB 恢复时游标会被定位到最近一条已保存记录之后。
8376
8486
  *
8487
+ * 标记后把对应栈裁剪到容量上限({@link markStackSaved} → {@link UndoRedo.trim}):入栈与还原都不裁剪,
8488
+ * 只有保存后才收敛,避免用户在落库前丢掉可撤销的历史;initial 基线与 set root 产生的记录不会被裁掉。
8489
+ *
8377
8490
  * @param stepType 历史类型
8378
8491
  * @param id 目标栈 id;缺省表示标记全部类型 / 全部栈
8379
8492
  */
@@ -8444,6 +8557,10 @@
8444
8557
  }
8445
8558
  /**
8446
8559
  * 用 {@link serialize} 导出的快照重建全部撤销/重做栈,会整体覆盖当前内存中的历史状态。
8560
+ *
8561
+ * 单个栈 / 单个类型的快照损坏只丢弃该部分,其余照常还原;
8562
+ * 快照里的栈全部还原失败时抛出首个错误,此时内存中的历史状态保持不变
8563
+ * (不会把「什么都没恢复」当成一次成功的还原)。
8447
8564
  */
8448
8565
  restore(snapshot) {
8449
8566
  const steps = {
@@ -8451,9 +8568,20 @@
8451
8568
  codeBlock: {},
8452
8569
  dataSource: {}
8453
8570
  };
8571
+ let firstError;
8572
+ let stackCount = 0;
8573
+ let restoredStackCount = 0;
8454
8574
  Object.entries(snapshot.steps).forEach(([stepType, bucket]) => {
8455
- steps[stepType] = deserializeStacks(convertExtraMaps(bucket, true), this.ctx.parseDSL);
8575
+ try {
8576
+ const restored = deserializeStacks(convertExtraMaps(bucket, true), this.ctx.parseDSL);
8577
+ steps[stepType] = restored;
8578
+ restoredStackCount += Object.keys(restored).length;
8579
+ } catch (error) {
8580
+ firstError ??= error;
8581
+ }
8582
+ stackCount += Object.keys(bucket ?? {}).length;
8456
8583
  });
8584
+ if (firstError && stackCount > 0 && restoredStackCount === 0) throw firstError;
8457
8585
  this.state.steps = steps;
8458
8586
  return snapshot;
8459
8587
  }
@@ -8549,6 +8677,16 @@
8549
8677
  return super.emit(eventName, ...args);
8550
8678
  }
8551
8679
  /**
8680
+ * 所有历史类型统一派发 `change`(签名 `(step, stepType, id, isHistoryOp)`);
8681
+ * 代码块 / 数据源额外派发文档约定的同构事件(签名 `(id, step, isHistoryOp)`)。
8682
+ * `isHistoryOp` 仅在 `undo` / `redo` 时为 true,供业务侧跳过历史回放触发的副作用。
8683
+ */
8684
+ emitStepChange(step, stepType, id, isHistoryOp = false) {
8685
+ this.emit("change", step, stepType, id, isHistoryOp);
8686
+ if (stepType === "codeBlock") this.emit("code-block-history-change", id, step, isHistoryOp);
8687
+ else if (stepType === "dataSource") this.emit("data-source-history-change", id, step, isHistoryOp);
8688
+ }
8689
+ /**
8552
8690
  * 取出指定历史类型的栈桶(`Record<id, UndoRedo>`);不存在时按需创建空桶,
8553
8691
  * 从而支持通过 {@link registerStepType} 或首次 push 动态扩展历史类型。
8554
8692
  */