-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
UndoManager.ts
428 lines (360 loc) · 11.9 KB
/
UndoManager.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { Event } from '@ephox/dom-globals';
import GetBookmark from '../bookmark/GetBookmark';
import Levels, { UndoLevel } from '../undo/Levels';
import Tools from './util/Tools';
import Editor from './Editor';
/**
* This class handles the undo/redo history levels for the editor. Since the built-in undo/redo has major drawbacks a custom one was needed.
*
* @class tinymce.UndoManager
*/
interface UndoManager {
data: UndoLevel[];
typing: boolean;
add: (level?: UndoLevel, event?: Event) => UndoLevel;
beforeChange: () => void;
undo: () => UndoLevel;
redo: () => UndoLevel;
clear: () => void;
reset: () => void;
hasUndo: () => boolean;
hasRedo: () => boolean;
transact: (callback: () => void) => UndoLevel;
ignore: (callback: () => void) => void;
extra: (callback1: () => void, callback2: () => void) => void;
}
const UndoManager = function (editor: Editor): UndoManager {
let self: UndoManager = this, index = 0, data = [], beforeBookmark, isFirstTypedCharacter, locks = 0;
const isUnlocked = function () {
return locks === 0;
};
const setTyping = function (typing) {
if (isUnlocked()) {
self.typing = typing;
}
};
const setDirty = function (state) {
editor.setDirty(state);
};
const addNonTypingUndoLevel = function (e?) {
setTyping(false);
self.add({} as UndoLevel, e);
};
const endTyping = function () {
if (self.typing) {
setTyping(false);
self.add();
}
};
// Add initial undo level when the editor is initialized
editor.on('init', function () {
self.add();
});
// Get position before an execCommand is processed
editor.on('BeforeExecCommand', function (e) {
const cmd = e.command;
if (cmd !== 'Undo' && cmd !== 'Redo' && cmd !== 'mceRepaint') {
endTyping();
self.beforeChange();
}
});
// Add undo level after an execCommand call was made
editor.on('ExecCommand', function (e) {
const cmd = e.command;
if (cmd !== 'Undo' && cmd !== 'Redo' && cmd !== 'mceRepaint') {
addNonTypingUndoLevel(e);
}
});
editor.on('ObjectResizeStart cut', function () {
self.beforeChange();
});
editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
editor.on('dragend', addNonTypingUndoLevel);
editor.on('keyup', function (e) {
const keyCode = e.keyCode;
// If key is prevented then don't add undo level
// This would happen on keyboard shortcuts for example
if (e.isDefaultPrevented()) {
return;
}
if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode === 45 || e.ctrlKey) {
addNonTypingUndoLevel();
editor.nodeChanged();
}
if (keyCode === 46 || keyCode === 8) {
editor.nodeChanged();
}
// Fire a TypingUndo/Change event on the first character entered
if (isFirstTypedCharacter && self.typing && Levels.isEq(Levels.createFromEditor(editor), data[0]) === false) {
if (editor.isDirty() === false) {
setDirty(true);
editor.fire('change', { level: data[0], lastLevel: null });
}
editor.fire('TypingUndo');
isFirstTypedCharacter = false;
editor.nodeChanged();
}
});
editor.on('keydown', function (e) {
const keyCode = e.keyCode;
// If key is prevented then don't add undo level
// This would happen on keyboard shortcuts for example
if (e.isDefaultPrevented()) {
return;
}
// Is character position keys left,right,up,down,home,end,pgdown,pgup,enter
if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode === 45) {
if (self.typing) {
addNonTypingUndoLevel(e);
}
return;
}
// If key isn't Ctrl+Alt/AltGr
const modKey = (e.ctrlKey && !e.altKey) || e.metaKey;
if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !self.typing && !modKey) {
self.beforeChange();
setTyping(true);
self.add({} as UndoLevel, e);
isFirstTypedCharacter = true;
}
});
editor.on('mousedown', function (e) {
if (self.typing) {
addNonTypingUndoLevel(e);
}
});
// Special inputType, currently only Chrome implements this: https://www.w3.org/TR/input-events-2/#x5.1.2-attributes
const isInsertReplacementText = (event) => event.inputType === 'insertReplacementText';
// Safari just shows inputType `insertText` but with data set to null so we can use that
const isInsertTextDataNull = (event) => event.inputType === 'insertText' && event.data === null;
// For detecting when user has replaced text using the browser built-in spell checker
editor.on('input', (e) => {
if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e))) {
addNonTypingUndoLevel(e);
}
});
// Add keyboard shortcuts for undo/redo keys
editor.addShortcut('meta+z', '', 'Undo');
editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
editor.on('AddUndo Undo Redo ClearUndos', function (e) {
if (!e.isDefaultPrevented()) {
editor.nodeChanged();
}
});
/*eslint consistent-this:0 */
self = {
// Explode for debugging reasons
data,
/**
* State if the user is currently typing or not. This will add a typing operation into one undo
* level instead of one new level for each keystroke.
*
* @field {Boolean} typing
*/
typing: false,
/**
* Stores away a bookmark to be used when performing an undo action so that the selection is before
* the change has been made.
*
* @method beforeChange
*/
beforeChange () {
if (isUnlocked()) {
beforeBookmark = GetBookmark.getUndoBookmark(editor.selection);
}
},
/**
* Adds a new undo level/snapshot to the undo list.
*
* @method add
* @param {Object} level Optional undo level object to add.
* @param {DOMEvent} event Optional event responsible for the creation of the undo level.
* @return {Object} Undo level that got added or null it a level wasn't needed.
*/
add (level?: UndoLevel, event?: Event): UndoLevel {
let i;
const settings = editor.settings;
let lastLevel, currentLevel;
currentLevel = Levels.createFromEditor(editor);
level = level || {} as UndoLevel;
level = Tools.extend(level, currentLevel);
if (isUnlocked() === false || editor.removed) {
return null;
}
lastLevel = data[index];
if (editor.fire('BeforeAddUndo', { level, lastLevel, originalEvent: event }).isDefaultPrevented()) {
return null;
}
// Add undo level if needed
if (lastLevel && Levels.isEq(lastLevel, level)) {
return null;
}
// Set before bookmark on previous level
if (data[index]) {
data[index].beforeBookmark = beforeBookmark;
}
// Time to compress
if (settings.custom_undo_redo_levels) {
if (data.length > settings.custom_undo_redo_levels) {
for (i = 0; i < data.length - 1; i++) {
data[i] = data[i + 1];
}
data.length--;
index = data.length;
}
}
// Get a non intrusive normalized bookmark
level.bookmark = GetBookmark.getUndoBookmark(editor.selection);
// Crop array if needed
if (index < data.length - 1) {
data.length = index + 1;
}
data.push(level);
index = data.length - 1;
const args = { level, lastLevel, originalEvent: event };
editor.fire('AddUndo', args);
if (index > 0) {
setDirty(true);
editor.fire('change', args);
}
return level;
},
/**
* Undoes the last action.
*
* @method undo
* @return {Object} Undo level or null if no undo was performed.
*/
undo (): UndoLevel {
let level: UndoLevel;
if (self.typing) {
self.add();
self.typing = false;
setTyping(false);
}
if (index > 0) {
level = data[--index];
Levels.applyToEditor(editor, level, true);
setDirty(true);
editor.fire('Undo', { level });
}
return level;
},
/**
* Redoes the last action.
*
* @method redo
* @return {Object} Redo level or null if no redo was performed.
*/
redo (): UndoLevel {
let level: UndoLevel;
if (index < data.length - 1) {
level = data[++index];
Levels.applyToEditor(editor, level, false);
setDirty(true);
editor.fire('Redo', { level });
}
return level;
},
/**
* Removes all undo levels.
*
* @method clear
*/
clear () {
data = [];
index = 0;
self.typing = false;
self.data = data;
editor.fire('ClearUndos');
},
/**
* Resets the undo manager levels by clearing all levels and then adding an initial level.
*
* @method reset
*/
reset () {
self.clear();
self.add();
},
/**
* Returns true/false if the undo manager has any undo levels.
*
* @method hasUndo
* @return {Boolean} true/false if the undo manager has any undo levels.
*/
hasUndo () {
// Has undo levels or typing and content isn't the same as the initial level
return index > 0 || (self.typing && data[0] && !Levels.isEq(Levels.createFromEditor(editor), data[0]));
},
/**
* Returns true/false if the undo manager has any redo levels.
*
* @method hasRedo
* @return {Boolean} true/false if the undo manager has any redo levels.
*/
hasRedo () {
return index < data.length - 1 && !self.typing;
},
/**
* Executes the specified mutator function as an undo transaction. The selection
* before the modification will be stored to the undo stack and if the DOM changes
* it will add a new undo level. Any logic within the translation that adds undo levels will
* be ignored. So a translation can include calls to execCommand or editor.insertContent.
*
* @method transact
* @param {function} callback Function that gets executed and has dom manipulation logic in it.
* @return {Object} Undo level that got added or null it a level wasn't needed.
*/
transact (callback: () => void): UndoLevel {
endTyping();
self.beforeChange();
self.ignore(callback);
return self.add();
},
/**
* Executes the specified mutator function as an undo transaction. But without adding an undo level.
* Any logic within the translation that adds undo levels will be ignored. So a translation can
* include calls to execCommand or editor.insertContent.
*
* @method ignore
* @param {function} callback Function that gets executed and has dom manipulation logic in it.
*/
ignore (callback: () => void) {
try {
locks++;
callback();
} finally {
locks--;
}
},
/**
* Adds an extra "hidden" undo level by first applying the first mutation and store that to the undo stack
* then roll back that change and do the second mutation on top of the stack. This will produce an extra
* undo level that the user doesn't see until they undo.
*
* @method extra
* @param {function} callback1 Function that does mutation but gets stored as a "hidden" extra undo level.
* @param {function} callback2 Function that does mutation but gets displayed to the user.
*/
extra (callback1: () => void, callback2: () => void) {
let lastLevel, bookmark;
if (self.transact(callback1)) {
bookmark = data[index].bookmark;
lastLevel = data[index - 1];
Levels.applyToEditor(editor, lastLevel, true);
if (self.transact(callback2)) {
data[index - 1].beforeBookmark = bookmark;
}
}
}
};
return self;
};
export default UndoManager;