forked from johnnesky/beepbox
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Change.ts
118 lines (99 loc) · 2.52 KB
/
Change.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Copyright (c) 2012-2022 John Nesky and contributing authors, distributed under the MIT license, see accompanying the LICENSE.md file.
export class Change {
private _noop: boolean = true;
protected _didSomething(): void {
this._noop = false;
}
public isNoop(): boolean {
return this._noop;
}
public commit(): void {}
}
export class UndoableChange extends Change {
private _reversed: boolean;
private _doneForwards: boolean;
constructor(reversed: boolean) {
super();
this._reversed = reversed;
this._doneForwards = !reversed;
}
public undo(): void {
if (this._reversed) {
this._doForwards();
this._doneForwards = true;
} else {
this._doBackwards();
this._doneForwards = false;
}
}
public redo(): void {
if (this._reversed) {
this._doBackwards();
this._doneForwards = false;
} else {
this._doForwards();
this._doneForwards = true;
}
}
// isDoneForwards() returns whether or not the Change was most recently
// performed forwards or backwards. If the change created something, do not
// delete it in the change destructor unless the Change was performed
// backwards:
protected _isDoneForwards(): boolean {
return this._doneForwards;
}
protected _doForwards(): void {
throw new Error("Change.doForwards(): Override me.");
}
protected _doBackwards(): void {
throw new Error("Change.doBackwards(): Override me.");
}
}
export class ChangeGroup extends Change {
constructor() {
super();
}
public append(change: Change): void {
if (change.isNoop()) return;
this._didSomething();
}
}
export class ChangeSequence extends UndoableChange {
private _changes: UndoableChange[];
private _committed: boolean;
constructor(changes?: UndoableChange[]) {
super(false);
if (changes == undefined) {
this._changes = [];
} else {
this._changes = changes.concat();
}
this._committed = false;
}
public checkFirst(): UndoableChange | null {
if (this._changes.length > 0)
return this._changes[0];
return null;
}
public append(change: UndoableChange): void {
if (change.isNoop()) return;
this._changes[this._changes.length] = change;
this._didSomething();
}
protected _doForwards(): void {
for (let i: number = 0; i < this._changes.length; i++) {
this._changes[i].redo();
}
}
protected _doBackwards(): void {
for (let i: number = this._changes.length-1; i >= 0 ; i--) {
this._changes[i].undo();
}
}
public isCommitted(): boolean {
return this._committed;
}
public commit(): void {
this._committed = true;
}
}