-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjs-undo-manager.es6
360 lines (290 loc) · 9.21 KB
/
js-undo-manager.es6
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*!
* JavaScript Undo Manager 1.0.0
* Simple JavaScript undo/redo command manager supporting transactions with no dependencies.
*
* Copyright: Alexey Grinko, 2017
* Git repository: https://github.com/agrinko/js-undo-manager.git
*
* @license MIT - https://opensource.org/licenses/MIT
*/
((global) => {
/////////// SOURCE CODE ///////////////
/**
* Default settings
*/
const DEFAULTS = {
limit: 100, // maximum commands stack size
debug: false, // whether to emit execution status in console
bindHotKeys: false, // whether to bind "undo" and "redo" commands to "Ctrl+Z", "Ctrl+Y" & "Ctrl+Shift+Z" hot keys
useTransactions: true // whether to initialize transactions manager
};
/**
* Main class
* @class JSUndoManager
*/
class JSUndoManager {
constructor(options) {
options = assign({}, DEFAULTS, options);
this.limit = options.limit;
this.options = options;
this.reset();
if (options.useTransactions) {
this.transaction = new TransactionManager(this);
}
if (options.bindHotKeys) {
this.bindHotKeys();
}
this.log(`Initialized with stack limit of ${this.limit} commands`);
}
/**
* Bind 'undo' and 'redo' actions to 'Ctrl+Z', 'Ctrl+Y' & 'Ctrl+Shift+Z' hot keys.
* It is a basic implementation for quick testing and should be replaced with custom event handlers
* for more flexible processing.
* @returns {JSUndoManager}
*/
bindHotKeys() {
this.log("Bound 'undo' and 'redo' actions to 'Ctrl+Z', 'Ctrl+Y' & 'Ctrl+Shift+Z' hot keys");
document.addEventListener("keydown", (e) => {
let Y = 89, Z = 90;
if (e.keyCode === Z && e.ctrlKey && !e.shiftKey) {
this.undo();
} else if (e.keyCode === Z && e.ctrlKey && e.shiftKey || e.keyCode === Y && e.ctrlKey) {
this.redo();
}
});
return this;
}
/**
* Remember executed command containing "redo" and "undo" functions
* @param {Object|Function} command - either an object with "redo" and "undo" functions or "redo" function itself
* @param {Function} [undo] - "undo" function, used if the first argument is also a function
* @returns {JSUndoManager}
*/
record(command) {
if (command && typeof command.redo === "function" && typeof command.undo === "function") {
this._record(command);
} else if (typeof arguments[0] === "function" && typeof arguments[1] === "function") {
this._record({
redo: arguments[0],
undo: arguments[1]
});
} else {
throw new TypeError("JSUndoManager.record(): unexpected arguments");
}
return this;
}
/**
* Execute function and record it with its opposite "undo" function
* @param {Object|Function} command - either an object with "redo" and "undo" functions or "redo" function itself
* @param {Function} [undo] - "undo" function, used if the first argument is also a function
* @returns {JSUndoManager}
*/
execute(command) {
let doFunction = command.redo || command;
this.record.apply(this, arguments);
this.log("Executing function...");
doFunction();
return this;
}
_record(command) {
if (this.transaction.isInProgress())
return this.transaction._record(command);
this.log("Recording command", command);
this._rebase();
this.stack.push(command);
this.sp++;
this._keepLimit();
}
//forget "future" commands if stack pointer is not at the end
_rebase() {
if (this.canRedo())
this.stack.length = this.sp + 1;
}
//sustain limited size of stack; cut extra commands starting with the latest ones
_keepLimit() {
if (this.stack.length <= this.limit)
return;
let exceedsBy = this.stack.length - this.limit;
this.log("Stack size reached its limit: ${this.limit} commands. Cutting off most old commands...");
if (exceedsBy === 1)
this.stack.shift(); //this is the most common case, so using "shift" will increase performance a bit
else
this.stack.splice(0, exceedsBy);
this.sp -= exceedsBy; //normalize stack pointer for the new stack length
}
/**
* Undo previous command if possible
* @returns {JSUndoManager}
*/
undo() {
if (!this.canUndo())
return this;
let command = this.stack[this.sp];
this.log("undo");
this.sp--;
command.undo();
return this;
}
/**
* Check whether undoing previous command is possible
* @returns {boolean}
*/
canUndo() {
return this.sp >= 0;
}
/**
* Redo the command which was previously undone
* @returns {JSUndoManager}
*/
redo() {
if (!this.canRedo())
return this;
let command = this.stack[this.sp + 1]; //execute next command after stack pointer
this.log("redo");
this.sp++;
command.redo();
return this;
}
/**
* Check whether redoing command is possible
* @returns {boolean}
*/
canRedo() {
return this.sp < this.stack.length - 1; //if stack pointer is not at the end
}
/**
* Change stack size limit initially defined in the constructor options
* @param {number} limit
*/
setLimit(limit) {
let redoable = this.stack.length - this.sp - 1;
if (limit < 1 || !(typeof limit === "number"))
throw new TypeError(`JSUndoManager.setLimit(): unexpected argument limit=${limit}. Should be a positive number`);
if (limit < redoable) {
console.warn(`JSUndoManager.setLimit(): cannot set stack limit (${limit}) less than the number of 'redoable' commands (${redoable})`);
} else {
this.limit = Math.floor(limit);
this._keepLimit();
}
return this;
}
/**
* Reset all commands from memory
*/
reset() {
this.log("reset");
this.stack = [];
this.sp = -1;
return this;
}
/**
* Check whether the commands stack is empty
* @returns {boolean}
*/
isEmpty() {
return !this.stack.length;
}
/**
* Check whether the commands stack size reaches its limit
* @returns {boolean}
*/
isFull() {
return this.stack.length === this.limit;
}
/**
* Get number of commands in memory stack
* @returns {Number}
*/
getSize() {
return this.stack.length;
}
log(msg, ...args) {
if (this.options.debug)
console.log(`Command Manager: ${msg}`, ...args);
}
}
/**
* Transaction manager helper.
* Allows working with transactions from JSUndoManager. Requires its instance as a constructor's parameter.
* @class TransactionManager
*/
class TransactionManager {
static _execForward(sequence) {
for (let i = 0; i < sequence.length; i++)
sequence[i].redo();
}
static _execBack(sequence) {
for (let i = sequence.length - 1; i >= 0; i--)
sequence[i].undo();
}
constructor(tracker) {
this.tracker = tracker;
this._reset();
tracker.log("TransactionManager is initialized");
}
begin() {
this.state = TransactionManager.IN_PROGRESS;
this.tracker.log("Begin transaction");
}
end() {
let seq = this.sequence;
this._reset();
if (seq.length > 0) {
this.tracker.record({
redo: TransactionManager._execForward.bind(null, seq),
undo: TransactionManager._execBack.bind(null, seq)
});
}
this.tracker.log("End transaction");
}
cancel() {
TransactionManager._execBack(this.sequence);
this._reset();
this.tracker.log("Cancel transaction");
}
isInProgress() {
return this.state === TransactionManager.IN_PROGRESS;
}
isPending() {
return this.state === TransactionManager.PENDING;
}
_record(command) {
this.sequence.push(command);
this.tracker.log("Recording command in transaction...", command);
}
_reset() {
this.state = TransactionManager.PENDING;
this.sequence = [];
}
}
TransactionManager.PENDING = 0;
TransactionManager.IN_PROGRESS = 1;
/////////// SOURCE CODE END ///////////////
// HELPER FUNCTIONS
/**
* Emulate ES6 Object.assign behaviour if native function is not defined
*/
let assign = Object.assign || function (target) {
for (let i = 1; i < arguments.length; i++ ) {
for (let key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
target[key] = arguments[i][key];
}
}
}
return target;
};
// EXPOSING THE COMPONENT
// AMD style
if (typeof define === "function" && define.amd) {
define(() => {
return JSUndoManager;
});
// CommonJS style
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = JSUndoManager;
// global definition
} else {
global.JSUndoManager = JSUndoManager;
}
})(window);