11import { Project , ProjectState , service } from "@/core/Project" ;
2+ import { Settings } from "@/core/service/Settings" ;
23import { deserialize , serialize } from "@graphif/serializer" ;
34import { Delta , diff , patch } from "jsondiffpatch" ;
45import _ from "lodash" ;
@@ -21,10 +22,6 @@ export class HistoryManager {
2122 * 历史记录列表数组上的一个指针
2223 */
2324 currentIndex = - 1 ;
24- /**
25- * 数组最大长度
26- */
27- historySize = 20 ;
2825 initialStage : Record < string , any > [ ] = [ ] ;
2926
3027 // 在软件启动时调用
@@ -43,16 +40,24 @@ export class HistoryManager {
4340 this . currentIndex ++ ;
4441 const prev = serialize ( this . get ( this . currentIndex - 1 ) ) ;
4542 const current = serialize ( this . project . stage ) ;
46- const patch = diff ( prev , current ) ;
47- if ( ! patch ) return ;
48- this . deltas . push ( patch ) ;
49- // if (this.deltas.length > this.historySize) {
50- // // 数组长度超过最大值时,合并第一个和第二个patch
51- // const second = this.get(1);
52- // const merged = diff(this.initialStage, second);
53- // this.deltas.splice(0, 2, merged);
54- // this.currentIndex--;
55- // }
43+ const patch_ = diff ( prev , current ) ;
44+ if ( ! patch_ ) return ;
45+ this . deltas . push ( patch_ ) ;
46+ if ( this . deltas . length > Settings . historySize ) {
47+ // 当历史记录超过限制时,需要删除最旧的记录
48+ // 但是不能简单删除,因为get方法依赖于从initialStage开始应用所有delta
49+ // 所以我们需要将第一个delta合并到initialStage中,然后删除这个delta
50+
51+ // 步骤1:将第一个delta合并到initialStage中
52+ const firstDelta = _ . cloneDeep ( this . deltas [ 0 ] ) ;
53+ this . initialStage = patch ( _ . cloneDeep ( this . initialStage ) , firstDelta ) as any ;
54+
55+ // 步骤2:删除最旧的记录(第一个delta)
56+ this . deltas . shift ( ) ;
57+
58+ // 步骤3:调整当前索引,因为删除了第一个元素,所有索引都向前移动了一位
59+ this . currentIndex -- ;
60+ }
5661 this . project . state = ProjectState . Unsaved ;
5762 }
5863
@@ -83,6 +88,11 @@ export class HistoryManager {
8388 }
8489
8590 get ( index : number ) {
91+ // 处理边界情况:如果索引为负数,直接返回初始状态
92+ if ( index < 0 ) {
93+ return deserialize ( _ . cloneDeep ( this . initialStage ) , this . project ) ;
94+ }
95+
8696 // 先获取从0到index(包含index)的所有patch
8797 const deltas = _ . cloneDeep ( this . deltas . slice ( 0 , index + 1 ) ) ;
8898 // 从initialStage开始应用patch,得到在index时刻的舞台序列化数据
0 commit comments