@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.
@@ -1,5 +1,12 @@
1
1
  import { cloneDeep } from "lodash-es";
2
2
  // packages/editor/src/utils/undo-redo.ts
3
+ /** 各历史栈 index 0 的 initial 是撤销下限(见 utils/history.ts 的 undoFloor),裁剪时不能把它挤掉。 */
4
+ var isInitialStep = (step) => step?.opType === "initial";
5
+ /**
6
+ * 容量按「真实步骤数」计算:index 0 的 initial 基线额外占一个位置,不挤掉真实记录。
7
+ * 只要真实步骤没超限,最老一条的 oldSchema 仍指向加载时的 DSL,「回到初始」就是可达的。
8
+ */
9
+ var maxLength = (list, listMaxSize) => listMaxSize + (isInitialStep(list[0]) ? 1 : 0);
3
10
  var UndoRedo = class UndoRedo {
4
11
  /**
5
12
  * 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
@@ -10,13 +17,9 @@ var UndoRedo = class UndoRedo {
10
17
  */
11
18
  static fromSerialized(data, options = {}) {
12
19
  const undoRedo = new UndoRedo(data.listMaxSize);
20
+ undoRedo.initialReachable = data.initialReachable !== false;
13
21
  const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
14
22
  let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
15
- const overflow = list.length - undoRedo.listMaxSize;
16
- if (overflow > 0) {
17
- list.splice(0, overflow);
18
- cursor -= overflow;
19
- }
20
23
  if (options.isSavedStep) {
21
24
  for (let i = list.length - 1; i >= 0; i--) if (options.isSavedStep(list[i])) {
22
25
  cursor = i + 1;
@@ -30,7 +33,9 @@ var UndoRedo = class UndoRedo {
30
33
  elementList;
31
34
  listCursor;
32
35
  listMaxSize;
33
- constructor(listMaxSize = 100) {
36
+ /** 容量裁剪是否删掉过已应用的真实步骤(撤销链已断,「回到初始」不可达)。 */
37
+ initialReachable = true;
38
+ constructor(listMaxSize = 1e3) {
34
39
  const minListMaxSize = 2;
35
40
  this.elementList = [];
36
41
  this.listCursor = 0;
@@ -44,16 +49,55 @@ var UndoRedo = class UndoRedo {
44
49
  return {
45
50
  elementList: this.elementList.map((item) => cloneDeep(item)),
46
51
  listCursor: this.listCursor,
47
- listMaxSize: this.listMaxSize
52
+ listMaxSize: this.listMaxSize,
53
+ initialReachable: this.initialReachable
48
54
  };
49
55
  }
50
56
  pushElement(element) {
51
57
  this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
52
58
  this.listCursor += 1;
53
- if (this.elementList.length > this.listMaxSize) {
54
- this.elementList.shift();
59
+ }
60
+ /**
61
+ * 把栈裁剪到容量上限(`listMaxSize` 条真实步骤,index 0 的 initial 基线额外占一个位置)。
62
+ *
63
+ * 只在保存后调用(见 historyService.markSaved):保存前不裁剪,避免用户还没落库就丢掉可撤销的历史。
64
+ * **永不删除** initial 基线与「整体设置 root」产生的记录(`rootStep`);
65
+ * 受保护记录本身占满容量时栈保持超限。
66
+ *
67
+ * 分两个阶段删除,保证撤销链与重做链各自连续:
68
+ * 1. 先从最旧的记录开始删**已应用**区(游标之前)的可删记录,撤销链仍然连续;
69
+ * 2. 已应用区删无可删仍超限时,溢出量落在重做区。重做链必须连续——后一条是按前一条的 DSL 打的补丁,
70
+ * 只删掉开头几条会让留下的步骤叠在缺失的基线上,因此整段丢弃游标之后的步骤。
71
+ * (不从重做区末尾往前删:重做区里可能有受保护的 `rootStep`,跳过它去删它前面的步骤同样会留空洞。)
72
+ *
73
+ * 「回到初始」是否仍可达,取决于被删的已应用步骤相对最早一条 `rootStep` 的位置:
74
+ * - 位于其**之后**:撤销链完整——一直撤销会退到这条整页快照,再撤销它即回到加载时的 DSL,仍可达;
75
+ * - 位于其**之前**(或栈内没有 `rootStep`):撤到底只能停在中途版本,标记为不可达。
76
+ * 只删掉重做区记录时不影响可达性。
77
+ */
78
+ trim() {
79
+ let overflow = this.elementList.length - maxLength(this.elementList, this.listMaxSize);
80
+ if (overflow <= 0) return;
81
+ let seenRootStep = false;
82
+ let brokenChain = false;
83
+ for (let index = 0; index < this.listCursor && overflow > 0;) {
84
+ const step = this.elementList[index];
85
+ if (isInitialStep(step)) {
86
+ index += 1;
87
+ continue;
88
+ }
89
+ if (step?.rootStep === true) {
90
+ seenRootStep = true;
91
+ index += 1;
92
+ continue;
93
+ }
94
+ this.elementList.splice(index, 1);
95
+ overflow -= 1;
55
96
  this.listCursor -= 1;
97
+ if (!seenRootStep) brokenChain = true;
56
98
  }
99
+ if (overflow > 0 && this.elementList.length > this.listCursor) this.elementList.length = this.listCursor;
100
+ if (brokenChain) this.initialReachable = false;
57
101
  }
58
102
  canUndo() {
59
103
  return this.listCursor > 0;
@@ -120,5 +164,9 @@ var UndoRedo = class UndoRedo {
120
164
  getLength() {
121
165
  return this.elementList.length;
122
166
  }
167
+ /** 「回到初始」是否可达:容量裁剪删掉已应用的真实步骤后撤销链断开,返回 false。 */
168
+ isInitialReachable() {
169
+ return this.initialReachable;
170
+ }
123
171
  };
124
172
  export { UndoRedo };
@@ -4282,6 +4282,13 @@
4282
4282
  }
4283
4283
  };
4284
4284
  // packages/editor/src/utils/undo-redo.ts
4285
+ /** 各历史栈 index 0 的 initial 是撤销下限(见 utils/history.ts 的 undoFloor),裁剪时不能把它挤掉。 */
4286
+ var isInitialStep = (step) => step?.opType === "initial";
4287
+ /**
4288
+ * 容量按「真实步骤数」计算:index 0 的 initial 基线额外占一个位置,不挤掉真实记录。
4289
+ * 只要真实步骤没超限,最老一条的 oldSchema 仍指向加载时的 DSL,「回到初始」就是可达的。
4290
+ */
4291
+ var maxLength = (list, listMaxSize) => listMaxSize + (isInitialStep(list[0]) ? 1 : 0);
4285
4292
  var UndoRedo = class UndoRedo {
4286
4293
  /**
4287
4294
  * 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
@@ -4292,13 +4299,9 @@
4292
4299
  */
4293
4300
  static fromSerialized(data, options = {}) {
4294
4301
  const undoRedo = new UndoRedo(data.listMaxSize);
4302
+ undoRedo.initialReachable = data.initialReachable !== false;
4295
4303
  const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
4296
4304
  let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
4297
- const overflow = list.length - undoRedo.listMaxSize;
4298
- if (overflow > 0) {
4299
- list.splice(0, overflow);
4300
- cursor -= overflow;
4301
- }
4302
4305
  if (options.isSavedStep) {
4303
4306
  for (let i = list.length - 1; i >= 0; i--) if (options.isSavedStep(list[i])) {
4304
4307
  cursor = i + 1;
@@ -4312,7 +4315,9 @@
4312
4315
  elementList;
4313
4316
  listCursor;
4314
4317
  listMaxSize;
4315
- constructor(listMaxSize = 100) {
4318
+ /** 容量裁剪是否删掉过已应用的真实步骤(撤销链已断,「回到初始」不可达)。 */
4319
+ initialReachable = true;
4320
+ constructor(listMaxSize = 1e3) {
4316
4321
  const minListMaxSize = 2;
4317
4322
  this.elementList = [];
4318
4323
  this.listCursor = 0;
@@ -4326,16 +4331,55 @@
4326
4331
  return {
4327
4332
  elementList: this.elementList.map((item) => cloneDeep(item)),
4328
4333
  listCursor: this.listCursor,
4329
- listMaxSize: this.listMaxSize
4334
+ listMaxSize: this.listMaxSize,
4335
+ initialReachable: this.initialReachable
4330
4336
  };
4331
4337
  }
4332
4338
  pushElement(element) {
4333
4339
  this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
4334
4340
  this.listCursor += 1;
4335
- if (this.elementList.length > this.listMaxSize) {
4336
- this.elementList.shift();
4341
+ }
4342
+ /**
4343
+ * 把栈裁剪到容量上限(`listMaxSize` 条真实步骤,index 0 的 initial 基线额外占一个位置)。
4344
+ *
4345
+ * 只在保存后调用(见 historyService.markSaved):保存前不裁剪,避免用户还没落库就丢掉可撤销的历史。
4346
+ * **永不删除** initial 基线与「整体设置 root」产生的记录(`rootStep`);
4347
+ * 受保护记录本身占满容量时栈保持超限。
4348
+ *
4349
+ * 分两个阶段删除,保证撤销链与重做链各自连续:
4350
+ * 1. 先从最旧的记录开始删**已应用**区(游标之前)的可删记录,撤销链仍然连续;
4351
+ * 2. 已应用区删无可删仍超限时,溢出量落在重做区。重做链必须连续——后一条是按前一条的 DSL 打的补丁,
4352
+ * 只删掉开头几条会让留下的步骤叠在缺失的基线上,因此整段丢弃游标之后的步骤。
4353
+ * (不从重做区末尾往前删:重做区里可能有受保护的 `rootStep`,跳过它去删它前面的步骤同样会留空洞。)
4354
+ *
4355
+ * 「回到初始」是否仍可达,取决于被删的已应用步骤相对最早一条 `rootStep` 的位置:
4356
+ * - 位于其**之后**:撤销链完整——一直撤销会退到这条整页快照,再撤销它即回到加载时的 DSL,仍可达;
4357
+ * - 位于其**之前**(或栈内没有 `rootStep`):撤到底只能停在中途版本,标记为不可达。
4358
+ * 只删掉重做区记录时不影响可达性。
4359
+ */
4360
+ trim() {
4361
+ let overflow = this.elementList.length - maxLength(this.elementList, this.listMaxSize);
4362
+ if (overflow <= 0) return;
4363
+ let seenRootStep = false;
4364
+ let brokenChain = false;
4365
+ for (let index = 0; index < this.listCursor && overflow > 0;) {
4366
+ const step = this.elementList[index];
4367
+ if (isInitialStep(step)) {
4368
+ index += 1;
4369
+ continue;
4370
+ }
4371
+ if (step?.rootStep === true) {
4372
+ seenRootStep = true;
4373
+ index += 1;
4374
+ continue;
4375
+ }
4376
+ this.elementList.splice(index, 1);
4377
+ overflow -= 1;
4337
4378
  this.listCursor -= 1;
4379
+ if (!seenRootStep) brokenChain = true;
4338
4380
  }
4381
+ if (overflow > 0 && this.elementList.length > this.listCursor) this.elementList.length = this.listCursor;
4382
+ if (brokenChain) this.initialReachable = false;
4339
4383
  }
4340
4384
  canUndo() {
4341
4385
  return this.listCursor > 0;
@@ -4402,6 +4446,10 @@
4402
4446
  getLength() {
4403
4447
  return this.elementList.length;
4404
4448
  }
4449
+ /** 「回到初始」是否可达:容量裁剪删掉已应用的真实步骤后撤销链断开,返回 false。 */
4450
+ isInitialReachable() {
4451
+ return this.initialReachable;
4452
+ }
4405
4453
  };
4406
4454
  // packages/editor/src/utils/history.ts
4407
4455
  /**
@@ -4465,6 +4513,11 @@
4465
4513
  extra: payload.extra
4466
4514
  };
4467
4515
  };
4516
+ /**
4517
+ * 把栈当前游标所在的记录标记为「已保存」,随后把栈裁剪到容量上限(见 {@link UndoRedo.trim})。
4518
+ * 入栈与还原都不裁剪,只有保存后才收敛,避免用户在落库前丢掉可撤销的历史;
4519
+ * initial 基线与「整体设置 root」产生的记录(`rootStep`)不会被裁掉。
4520
+ */
4468
4521
  var markStackSaved = (undoRedo) => {
4469
4522
  if (!undoRedo) return;
4470
4523
  undoRedo.updateElements((element) => {
@@ -4473,6 +4526,7 @@
4473
4526
  undoRedo.updateCurrentElement((element) => {
4474
4527
  element.saved = true;
4475
4528
  });
4529
+ undoRedo.trim();
4476
4530
  };
4477
4531
  /**
4478
4532
  * 把单个历史栈(页面 / 代码块 / 数据源 / 扩展类型)的步骤列表按"目标"做相邻合并:
@@ -4584,20 +4638,33 @@
4584
4638
  *
4585
4639
  * 与 {@link serializeStacks} 相反:当传入 `parse`(parseDSL)时,把每条 step 中以字符串形式存储的 `diff`
4586
4640
  * 解析回真实对象(含函数);不含 `diff` 的元素(如通用栈)原样透传。
4641
+ *
4642
+ * 单个栈解析失败只丢弃该栈,其余栈照常还原:一条损坏的快照不应该让整份本地历史都不可用。
4643
+ * 结构性损坏(`elementList` 不是数组)同样按空栈处理,交给 {@link UndoRedo.fromSerialized} 兜底。
4644
+ * 全部栈都失败时抛出首个错误,避免调用方把「什么都没恢复」当成一次成功的还原。
4587
4645
  */
4588
4646
  var deserializeStacks = (stacks = {}, parse) => {
4589
4647
  const result = {};
4648
+ let firstError;
4649
+ let failedCount = 0;
4590
4650
  Object.entries(stacks).forEach(([id, serialized]) => {
4591
4651
  if (!serialized) return;
4592
- const elementList = parse ? serialized.elementList.map((step) => {
4593
- const { diff } = step;
4594
- return typeof diff === "string" ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
4595
- }) : serialized.elementList;
4596
- result[id] = UndoRedo.fromSerialized({
4597
- ...serialized,
4598
- elementList
4599
- }, { isSavedStep: (element) => element.saved === true });
4652
+ const source = Array.isArray(serialized.elementList) ? serialized.elementList : [];
4653
+ try {
4654
+ const elementList = parse ? source.map((step) => {
4655
+ const { diff } = step;
4656
+ return typeof diff === "string" ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
4657
+ }) : source;
4658
+ result[id] = UndoRedo.fromSerialized({
4659
+ ...serialized,
4660
+ elementList
4661
+ }, { isSavedStep: (element) => element.saved === true });
4662
+ } catch (error) {
4663
+ failedCount += 1;
4664
+ firstError ??= error;
4665
+ }
4600
4666
  });
4667
+ if (failedCount > 0 && Object.keys(result).length === 0) throw firstError;
4601
4668
  return result;
4602
4669
  };
4603
4670
  /**
@@ -6671,6 +6738,14 @@
6671
6738
  return parentNode;
6672
6739
  };
6673
6740
  // packages/editor/src/sdk/services/Editor.ts
6741
+ /**
6742
+ * 撤销 / 重做回放的内部标记键:不导出,也不出现在公开的 {@link HistoryOpOptions} 里。
6743
+ * 回放链路用它把 `isHistoryOp` 带进 `change` 事件;外部调用方即使传同名字符串字段也不会被读取,
6744
+ * 避免一次真实编辑被误标成历史回放,从而绕过业务侧的加锁 / 埋点 / 自动保存。
6745
+ */
6746
+ var HISTORY_OP = Symbol("isHistoryOp");
6747
+ /** 读取仅供编辑器内部使用的回放标记。 */
6748
+ var isReplay = (options) => options[HISTORY_OP] === true;
6674
6749
  /** 把插入下标收敛到 [0, length]:非整数取整,非法 / 越界(含未记录)一律追加到末尾 */
6675
6750
  var clampIndex = (index, length) => {
6676
6751
  const normalized = typeof index === "number" ? Math.trunc(index) : length;
@@ -6985,6 +7060,7 @@
6985
7060
  async add(addNode, parent, options = {}) {
6986
7061
  this.captureSelectionBeforeOp();
6987
7062
  const { doNotSelect = false, doNotSwitchPage = false, doNotPushHistory = false, historyDescription, historySource } = options;
7063
+ const isHistoryOp = isReplay(options);
6988
7064
  const stage = this.get("stage");
6989
7065
  const addNodes = [];
6990
7066
  if (!Array.isArray(addNode)) {
@@ -7062,7 +7138,8 @@
7062
7138
  page: this.getPageOfNode(node.id)
7063
7139
  })),
7064
7140
  historySource,
7065
- doNotPushHistory
7141
+ doNotPushHistory,
7142
+ isHistoryOp
7066
7143
  });
7067
7144
  const addedPages = newNodes.filter((node) => (0, _tmagic_utils.isPageOrFragment)(node));
7068
7145
  if (addedPages.length) this.ctx.history.notifyPageStructureChange({
@@ -7133,6 +7210,7 @@
7133
7210
  */
7134
7211
  async remove(nodeOrNodeList, options = {}) {
7135
7212
  const { doNotPushHistory = false, historyDescription, historySource } = options;
7213
+ const isHistoryOp = isReplay(options);
7136
7214
  this.captureSelectionBeforeOp();
7137
7215
  const nodes = Array.isArray(nodeOrNodeList) ? nodeOrNodeList : [nodeOrNodeList];
7138
7216
  const changeItems = nodes.map((node) => ({
@@ -7172,7 +7250,8 @@
7172
7250
  type: "remove",
7173
7251
  data: changeItems,
7174
7252
  historySource,
7175
- doNotPushHistory
7253
+ doNotPushHistory,
7254
+ isHistoryOp
7176
7255
  });
7177
7256
  const removedPages = nodes.filter((node) => (0, _tmagic_utils.isPageOrFragment)(node));
7178
7257
  if (removedPages.length) this.ctx.history.notifyPageStructureChange({
@@ -7236,6 +7315,7 @@
7236
7315
  async update(config, data = {}) {
7237
7316
  this.captureSelectionBeforeOp();
7238
7317
  const { doNotPushHistory = false, changeRecordList, changeRecords, historyDescription, historySource, invalidInfo } = data;
7318
+ const isHistoryOp = isReplay(data);
7239
7319
  const nodes = Array.isArray(config) ? config : [config];
7240
7320
  const commitInvalid = await this.runGuard(() => this.ctx.validator.guardUpdate(nodes, { replace: data.replace }));
7241
7321
  const updateData = await Promise.all(nodes.map((node, index) => {
@@ -7275,7 +7355,8 @@
7275
7355
  page: this.getPageOfNode(node.newNode.id)
7276
7356
  })),
7277
7357
  historySource,
7278
- doNotPushHistory
7358
+ doNotPushHistory,
7359
+ isHistoryOp
7279
7360
  });
7280
7361
  return Array.isArray(config) ? updateData.map((item) => item.newNode) : updateData[0].newNode;
7281
7362
  }
@@ -7403,7 +7484,9 @@
7403
7484
  * @param options 可选配置
7404
7485
  * @param options.doNotPushHistory 是否不写入历史记录(默认 false)
7405
7486
  */
7406
- async moveLayer(offset, { doNotPushHistory = false, historyDescription, historySource } = {}) {
7487
+ async moveLayer(offset, options = {}) {
7488
+ const { doNotPushHistory = false, historyDescription, historySource } = options;
7489
+ const isHistoryOp = isReplay(options);
7407
7490
  this.captureSelectionBeforeOp();
7408
7491
  const root = this.get("root");
7409
7492
  if (!root) throw new Error("root为空");
@@ -7450,7 +7533,8 @@
7450
7533
  }],
7451
7534
  offset,
7452
7535
  historySource,
7453
- doNotPushHistory
7536
+ doNotPushHistory,
7537
+ isHistoryOp
7454
7538
  });
7455
7539
  }
7456
7540
  /**
@@ -7523,7 +7607,9 @@
7523
7607
  } else this.selectionBeforeOp = null;
7524
7608
  return isBatch ? newConfigs : newConfigs[0];
7525
7609
  }
7526
- async dragTo(config, targetParent, targetIndex, { doNotPushHistory = false, historyDescription, historySource } = {}) {
7610
+ async dragTo(config, targetParent, targetIndex, options = {}) {
7611
+ const { doNotPushHistory = false, historyDescription, historySource } = options;
7612
+ const isHistoryOp = isReplay(options);
7527
7613
  this.captureSelectionBeforeOp();
7528
7614
  if (!targetParent || !Array.isArray(targetParent.items)) return;
7529
7615
  const configs = Array.isArray(config) ? config : [config];
@@ -7590,7 +7676,8 @@
7590
7676
  targetIndex,
7591
7677
  targetParent,
7592
7678
  historySource,
7593
- doNotPushHistory
7679
+ doNotPushHistory,
7680
+ isHistoryOp
7594
7681
  });
7595
7682
  }
7596
7683
  /**
@@ -7690,7 +7777,8 @@
7690
7777
  * @returns 反向后产生的新 step;目标不存在 / 未应用 / 反向失败时返回 null
7691
7778
  */
7692
7779
  async revertPageStep(index) {
7693
- const entry = this.ctx.history.getStepList("page", this.get("page")?.id)[index];
7780
+ const pageId = this.get("page")?.id;
7781
+ const entry = this.ctx.history.getStepList("page", pageId)[index];
7694
7782
  if (!entry?.applied) return null;
7695
7783
  const { step } = entry;
7696
7784
  if (step.opType === "initial") return null;
@@ -7700,10 +7788,10 @@
7700
7788
  if (!items.length || !items.every((item) => item.changeRecords?.length)) return null;
7701
7789
  }
7702
7790
  let revertedStep = null;
7703
- const captureRevert = (_pageId, s) => {
7704
- revertedStep = s;
7791
+ const captureRevert = (s, type, id) => {
7792
+ if (type === "page" && id === pageId && !revertedStep) revertedStep = s;
7705
7793
  };
7706
- this.ctx.history.once("change", captureRevert);
7794
+ this.ctx.history.on("change", captureRevert);
7707
7795
  const historyDescription = `回滚 #${index + 1}: ${describeStepForRevert(step)}`;
7708
7796
  const opts = {
7709
7797
  doNotSelect: true,
@@ -8013,9 +8101,11 @@
8013
8101
  /**
8014
8102
  * 构造一条页面级「set root」历史记录(不携带选区 / modifiedNodeIds 上下文)并落到该页面自己的栈。
8015
8103
  *
8016
- * 连续 set root 替换:若该页栈最新一条已是**同来源**的 set root 记录({@link StepValue.rootStep} 且 `source` 相同),
8017
- * 则用本次记录**替换**它而非新增,避免源码反复保存 / 外部重设 DSL 时堆积多条 root 记录;
8018
- * 来源不同则照常新增(initial 基线不是 rootStep,不在此列)。
8104
+ * 连续 set root 替换:若该页栈最新一条已是**同来源、同为整页 update**的 set root 记录
8105
+ * ({@link StepValue.rootStep} 且 `source` 相同),则用本次记录**替换**它而非新增,避免源码反复保存时堆积记录。
8106
+ * 替换时必须把 `oldSchema` 追溯到最早那一跳,并沿用原 uuid:否则只剩「上一版 → 本版」,
8107
+ * 撤销到基线时 DSL 会停在中途版本且无法继续回退,已发出的 historyId 也会失效。
8108
+ * 其余情况(来源不同 / 页面增删)照常新增,保留完整变更链条。
8019
8109
  */
8020
8110
  pushPageDiffStep(opType, page, diffItem, source) {
8021
8111
  const step = {
@@ -8035,8 +8125,19 @@
8035
8125
  };
8036
8126
  if (source) step.source = source;
8037
8127
  const top = this.ctx.history.getCurrentPageStep(page.id);
8038
- if (top?.rootStep && top.source === source) this.ctx.history.replaceCurrentStep("page", step, page.id);
8039
- else this.ctx.history.push("page", step, page.id);
8128
+ const earliestOldSchema = top?.diff?.[0]?.oldSchema;
8129
+ if (top?.rootStep && top.source === source && opType === "update" && top.opType === "update" && earliestOldSchema) {
8130
+ this.ctx.history.replaceCurrentStep("page", {
8131
+ ...step,
8132
+ uuid: top.uuid,
8133
+ diff: [{
8134
+ ...diffItem,
8135
+ oldSchema: earliestOldSchema
8136
+ }]
8137
+ }, page.id);
8138
+ return;
8139
+ }
8140
+ this.ctx.history.push("page", step, page.id);
8040
8141
  }
8041
8142
  pushOpHistory(opType, { diff, pageData, historyDescription, source }) {
8042
8143
  const step = {
@@ -8068,8 +8169,8 @@
8068
8169
  * 「重新插回节点」(撤销 remove / 重做 add)需按 step 记录的 parentId / index 精确还原,
8069
8170
  * 不走 this.add,由手工 splice + stage.add 完成后补发等价的 add / change 事件(见 emitHistoryInsertEvents)。
8070
8171
  *
8071
- * 注意:这些路径都会发出 add / remove / update / change 事件,业务侧若需要区分"用户操作"与"撤销重做触发",
8072
- * 请监听 `history-change` 事件配合判断。
8172
+ * 注意:这些路径都会发出 add / remove / update / change 事件,且 `change` 事件带 `isHistoryOp: true`,
8173
+ * 业务侧可据此跳过仅针对「用户主动编辑」的副作用(加锁 / 埋点 / 自动保存等)。
8073
8174
  *
8074
8175
  * @param step 操作记录
8075
8176
  * @param reverse true = 撤销,false = 重做
@@ -8083,6 +8184,7 @@
8083
8184
  doNotSelect: true,
8084
8185
  doNotSwitchPage: true,
8085
8186
  doNotPushHistory: true,
8187
+ [HISTORY_OP]: true,
8086
8188
  historySource: step.source
8087
8189
  };
8088
8190
  switch (step.opType) {
@@ -8166,10 +8268,7 @@
8166
8268
  }
8167
8269
  return cloneDeep(reverse ? oldNode : newNode);
8168
8270
  });
8169
- if (configs.length) await this.update(configs, {
8170
- doNotPushHistory: true,
8171
- historySource: step.source
8172
- });
8271
+ if (configs.length) await this.update(configs, commonOpts);
8173
8272
  break;
8174
8273
  }
8175
8274
  }
@@ -8207,7 +8306,8 @@
8207
8306
  page: this.getPageOfNode(node.id)
8208
8307
  })),
8209
8308
  historySource: source,
8210
- doNotPushHistory: true
8309
+ doNotPushHistory: true,
8310
+ isHistoryOp: true
8211
8311
  });
8212
8312
  }
8213
8313
  /** 经由 reactivity 注入的 toRaw(默认是 Vue 的 toRaw) */
@@ -8354,8 +8454,9 @@
8354
8454
  * 注册一个扩展历史类型,使其可与内置 `page` / `codeBlock` / `dataSource` 一样走统一的
8355
8455
  * {@link push} / {@link undo} / {@link redo}(按 id 分栈、独立 undo/redo)。
8356
8456
  *
8457
+ * 扩展类型与内置类型一样统一派发 `change` 事件,无需(也不支持)单独指定事件名。
8458
+ *
8357
8459
  * @param stepType 自定义历史类型标识(勿与内置类型重名)
8358
- * @param options.event push/undo/redo 后派发的事件名,缺省为 `${stepType}-history-change`
8359
8460
  * @param options.name 历史面板中的展示名称(tab / 分组标题等),缺省回退到 stepType 本身
8360
8461
  */
8361
8462
  registerStepType(stepType, options = {}) {
@@ -8439,11 +8540,20 @@
8439
8540
  const first = this.state.steps[stepType]?.[id]?.getElementList()[0];
8440
8541
  return first?.opType === "initial" ? first : void 0;
8441
8542
  }
8543
+ /**
8544
+ * 目标栈「回到初始」是否可达:容量裁剪删掉已应用的真实步骤后撤销链断开,返回 false。
8545
+ * 与是否存在 {@link getMarker} 基线无关——没有基线的栈同样可能因裁剪回不到加载时的 DSL,
8546
+ * 历史面板的各 tab 统一用它判断初始行是否可高亮 / 可点击。
8547
+ */
8548
+ isInitialReachable(stepType, id) {
8549
+ if (!this.isValidStackId(id)) return true;
8550
+ return this.state.steps[stepType]?.[id]?.isInitialReachable() ?? true;
8551
+ }
8442
8552
  push(stepType, step, id) {
8443
8553
  if (!this.isValidStackId(id)) return null;
8444
8554
  this.fillStepMeta(step);
8445
8555
  getOrCreateStack(this.getStepBucket(stepType), id).pushElement(step);
8446
- this.emit("change", step, stepType, id);
8556
+ this.emitStepChange(step, stepType, id);
8447
8557
  return step;
8448
8558
  }
8449
8559
  undo(stepType, id) {
@@ -8452,7 +8562,7 @@
8452
8562
  if (!undoRedo) return null;
8453
8563
  if (undoRedo.getCursor() <= undoFloor(undoRedo)) return null;
8454
8564
  const step = undoRedo.undo();
8455
- if (step) this.emit("change", step, stepType, id);
8565
+ if (step) this.emitStepChange(step, stepType, id, true);
8456
8566
  return step;
8457
8567
  }
8458
8568
  redo(stepType, id) {
@@ -8460,7 +8570,7 @@
8460
8570
  const undoRedo = this.state.steps[stepType]?.[id];
8461
8571
  if (!undoRedo) return null;
8462
8572
  const step = undoRedo.redo();
8463
- if (step) this.emit("change", step, stepType, id);
8573
+ if (step) this.emitStepChange(step, stepType, id, true);
8464
8574
  return step;
8465
8575
  }
8466
8576
  /**
@@ -8496,7 +8606,7 @@
8496
8606
  const undoRedo = getOrCreateStack(this.getStepBucket(stepType), id);
8497
8607
  this.fillStepMeta(state);
8498
8608
  if (!undoRedo.replaceCurrentElement(state)) return null;
8499
- this.emit("change", state, stepType, id);
8609
+ this.emitStepChange(state, stepType, id);
8500
8610
  return state;
8501
8611
  }
8502
8612
  destroy() {
@@ -8533,6 +8643,9 @@
8533
8643
  *
8534
8644
  * 同一栈内任意时刻最多只有一条记录为 `saved`;从 IndexedDB 恢复时游标会被定位到最近一条已保存记录之后。
8535
8645
  *
8646
+ * 标记后把对应栈裁剪到容量上限({@link markStackSaved} → {@link UndoRedo.trim}):入栈与还原都不裁剪,
8647
+ * 只有保存后才收敛,避免用户在落库前丢掉可撤销的历史;initial 基线与 set root 产生的记录不会被裁掉。
8648
+ *
8536
8649
  * @param stepType 历史类型
8537
8650
  * @param id 目标栈 id;缺省表示标记全部类型 / 全部栈
8538
8651
  */
@@ -8603,6 +8716,10 @@
8603
8716
  }
8604
8717
  /**
8605
8718
  * 用 {@link serialize} 导出的快照重建全部撤销/重做栈,会整体覆盖当前内存中的历史状态。
8719
+ *
8720
+ * 单个栈 / 单个类型的快照损坏只丢弃该部分,其余照常还原;
8721
+ * 快照里的栈全部还原失败时抛出首个错误,此时内存中的历史状态保持不变
8722
+ * (不会把「什么都没恢复」当成一次成功的还原)。
8606
8723
  */
8607
8724
  restore(snapshot) {
8608
8725
  const steps = {
@@ -8610,9 +8727,20 @@
8610
8727
  codeBlock: {},
8611
8728
  dataSource: {}
8612
8729
  };
8730
+ let firstError;
8731
+ let stackCount = 0;
8732
+ let restoredStackCount = 0;
8613
8733
  Object.entries(snapshot.steps).forEach(([stepType, bucket]) => {
8614
- steps[stepType] = deserializeStacks(convertExtraMaps(bucket, true), this.ctx.parseDSL);
8734
+ try {
8735
+ const restored = deserializeStacks(convertExtraMaps(bucket, true), this.ctx.parseDSL);
8736
+ steps[stepType] = restored;
8737
+ restoredStackCount += Object.keys(restored).length;
8738
+ } catch (error) {
8739
+ firstError ??= error;
8740
+ }
8741
+ stackCount += Object.keys(bucket ?? {}).length;
8615
8742
  });
8743
+ if (firstError && stackCount > 0 && restoredStackCount === 0) throw firstError;
8616
8744
  this.state.steps = steps;
8617
8745
  return snapshot;
8618
8746
  }
@@ -8708,6 +8836,16 @@
8708
8836
  return super.emit(eventName, ...args);
8709
8837
  }
8710
8838
  /**
8839
+ * 所有历史类型统一派发 `change`(签名 `(step, stepType, id, isHistoryOp)`);
8840
+ * 代码块 / 数据源额外派发文档约定的同构事件(签名 `(id, step, isHistoryOp)`)。
8841
+ * `isHistoryOp` 仅在 `undo` / `redo` 时为 true,供业务侧跳过历史回放触发的副作用。
8842
+ */
8843
+ emitStepChange(step, stepType, id, isHistoryOp = false) {
8844
+ this.emit("change", step, stepType, id, isHistoryOp);
8845
+ if (stepType === "codeBlock") this.emit("code-block-history-change", id, step, isHistoryOp);
8846
+ else if (stepType === "dataSource") this.emit("data-source-history-change", id, step, isHistoryOp);
8847
+ }
8848
+ /**
8711
8849
  * 取出指定历史类型的栈桶(`Record<id, UndoRedo>`);不存在时按需创建空桶,
8712
8850
  * 从而支持通过 {@link registerStepType} 或首次 push 动态扩展历史类型。
8713
8851
  */