@lexical/history 0.14.0 → 0.14.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,119 +1,54 @@
1
- /** @module @lexical/history */
2
1
  /**
3
2
  * Copyright (c) Meta Platforms, Inc. and affiliates.
4
3
  *
5
4
  * This source code is licensed under the MIT license found in the
6
5
  * LICENSE file in the root directory of this source tree.
7
- *
8
6
  */
7
+ import { mergeRegister } from '@lexical/utils';
8
+ import { UNDO_COMMAND, COMMAND_PRIORITY_EDITOR, REDO_COMMAND, CLEAR_EDITOR_COMMAND, CLEAR_HISTORY_COMMAND, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, $isRangeSelection, $isTextNode, $isRootNode } from 'lexical';
9
9
 
10
- import type {EditorState, LexicalEditor, LexicalNode, NodeKey} from 'lexical';
11
-
12
- import {mergeRegister} from '@lexical/utils';
13
- import {
14
- $isRangeSelection,
15
- $isRootNode,
16
- $isTextNode,
17
- CAN_REDO_COMMAND,
18
- CAN_UNDO_COMMAND,
19
- CLEAR_EDITOR_COMMAND,
20
- CLEAR_HISTORY_COMMAND,
21
- COMMAND_PRIORITY_EDITOR,
22
- REDO_COMMAND,
23
- UNDO_COMMAND,
24
- } from 'lexical';
25
-
26
- type MergeAction = 0 | 1 | 2;
10
+ /** @module @lexical/history */
27
11
  const HISTORY_MERGE = 0;
28
12
  const HISTORY_PUSH = 1;
29
13
  const DISCARD_HISTORY_CANDIDATE = 2;
30
-
31
- type ChangeType = 0 | 1 | 2 | 3 | 4;
32
14
  const OTHER = 0;
33
15
  const COMPOSING_CHARACTER = 1;
34
16
  const INSERT_CHARACTER_AFTER_SELECTION = 2;
35
17
  const DELETE_CHARACTER_BEFORE_SELECTION = 3;
36
18
  const DELETE_CHARACTER_AFTER_SELECTION = 4;
37
-
38
- export type HistoryStateEntry = {
39
- editor: LexicalEditor;
40
- editorState: EditorState;
41
- };
42
- export type HistoryState = {
43
- current: null | HistoryStateEntry;
44
- redoStack: Array<HistoryStateEntry>;
45
- undoStack: Array<HistoryStateEntry>;
46
- };
47
-
48
- type IntentionallyMarkedAsDirtyElement = boolean;
49
-
50
- function getDirtyNodes(
51
- editorState: EditorState,
52
- dirtyLeaves: Set<NodeKey>,
53
- dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
54
- ): Array<LexicalNode> {
19
+ function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
55
20
  const nodeMap = editorState._nodeMap;
56
21
  const nodes = [];
57
-
58
22
  for (const dirtyLeafKey of dirtyLeaves) {
59
23
  const dirtyLeaf = nodeMap.get(dirtyLeafKey);
60
-
61
24
  if (dirtyLeaf !== undefined) {
62
25
  nodes.push(dirtyLeaf);
63
26
  }
64
27
  }
65
-
66
28
  for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
67
29
  if (!intentionallyMarkedAsDirty) {
68
30
  continue;
69
31
  }
70
-
71
32
  const dirtyElement = nodeMap.get(dirtyElementKey);
72
-
73
33
  if (dirtyElement !== undefined && !$isRootNode(dirtyElement)) {
74
34
  nodes.push(dirtyElement);
75
35
  }
76
36
  }
77
-
78
37
  return nodes;
79
38
  }
80
-
81
- function getChangeType(
82
- prevEditorState: null | EditorState,
83
- nextEditorState: EditorState,
84
- dirtyLeavesSet: Set<NodeKey>,
85
- dirtyElementsSet: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
86
- isComposing: boolean,
87
- ): ChangeType {
88
- if (
89
- prevEditorState === null ||
90
- (dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing)
91
- ) {
39
+ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
40
+ if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing) {
92
41
  return OTHER;
93
42
  }
94
-
95
43
  const nextSelection = nextEditorState._selection;
96
44
  const prevSelection = prevEditorState._selection;
97
-
98
45
  if (isComposing) {
99
46
  return COMPOSING_CHARACTER;
100
47
  }
101
-
102
- if (
103
- !$isRangeSelection(nextSelection) ||
104
- !$isRangeSelection(prevSelection) ||
105
- !prevSelection.isCollapsed() ||
106
- !nextSelection.isCollapsed()
107
- ) {
48
+ if (!$isRangeSelection(nextSelection) || !$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
108
49
  return OTHER;
109
50
  }
110
-
111
- const dirtyNodes = getDirtyNodes(
112
- nextEditorState,
113
- dirtyLeavesSet,
114
- dirtyElementsSet,
115
- );
116
-
51
+ const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
117
52
  if (dirtyNodes.length === 0) {
118
53
  return OTHER;
119
54
  }
@@ -124,122 +59,58 @@ function getChangeType(
124
59
  const nextNodeMap = nextEditorState._nodeMap;
125
60
  const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
126
61
  const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
127
-
128
- if (
129
- nextAnchorNode &&
130
- prevAnchorNode &&
131
- !prevEditorState._nodeMap.has(nextAnchorNode.__key) &&
132
- $isTextNode(nextAnchorNode) &&
133
- nextAnchorNode.__text.length === 1 &&
134
- nextSelection.anchor.offset === 1
135
- ) {
62
+ if (nextAnchorNode && prevAnchorNode && !prevEditorState._nodeMap.has(nextAnchorNode.__key) && $isTextNode(nextAnchorNode) && nextAnchorNode.__text.length === 1 && nextSelection.anchor.offset === 1) {
136
63
  return INSERT_CHARACTER_AFTER_SELECTION;
137
64
  }
138
-
139
65
  return OTHER;
140
66
  }
141
-
142
67
  const nextDirtyNode = dirtyNodes[0];
143
-
144
68
  const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
145
-
146
- if (
147
- !$isTextNode(prevDirtyNode) ||
148
- !$isTextNode(nextDirtyNode) ||
149
- prevDirtyNode.__mode !== nextDirtyNode.__mode
150
- ) {
69
+ if (!$isTextNode(prevDirtyNode) || !$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
151
70
  return OTHER;
152
71
  }
153
-
154
72
  const prevText = prevDirtyNode.__text;
155
73
  const nextText = nextDirtyNode.__text;
156
-
157
74
  if (prevText === nextText) {
158
75
  return OTHER;
159
76
  }
160
-
161
77
  const nextAnchor = nextSelection.anchor;
162
78
  const prevAnchor = prevSelection.anchor;
163
-
164
79
  if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
165
80
  return OTHER;
166
81
  }
167
-
168
82
  const nextAnchorOffset = nextAnchor.offset;
169
83
  const prevAnchorOffset = prevAnchor.offset;
170
84
  const textDiff = nextText.length - prevText.length;
171
-
172
85
  if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
173
86
  return INSERT_CHARACTER_AFTER_SELECTION;
174
87
  }
175
-
176
88
  if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
177
89
  return DELETE_CHARACTER_BEFORE_SELECTION;
178
90
  }
179
-
180
91
  if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
181
92
  return DELETE_CHARACTER_AFTER_SELECTION;
182
93
  }
183
-
184
94
  return OTHER;
185
95
  }
186
-
187
- function isTextNodeUnchanged(
188
- key: NodeKey,
189
- prevEditorState: EditorState,
190
- nextEditorState: EditorState,
191
- ): boolean {
96
+ function isTextNodeUnchanged(key, prevEditorState, nextEditorState) {
192
97
  const prevNode = prevEditorState._nodeMap.get(key);
193
98
  const nextNode = nextEditorState._nodeMap.get(key);
194
-
195
99
  const prevSelection = prevEditorState._selection;
196
100
  const nextSelection = nextEditorState._selection;
197
101
  let isDeletingLine = false;
198
-
199
102
  if ($isRangeSelection(prevSelection) && $isRangeSelection(nextSelection)) {
200
- isDeletingLine =
201
- prevSelection.anchor.type === 'element' &&
202
- prevSelection.focus.type === 'element' &&
203
- nextSelection.anchor.type === 'text' &&
204
- nextSelection.focus.type === 'text';
103
+ isDeletingLine = prevSelection.anchor.type === 'element' && prevSelection.focus.type === 'element' && nextSelection.anchor.type === 'text' && nextSelection.focus.type === 'text';
205
104
  }
206
-
207
105
  if (!isDeletingLine && $isTextNode(prevNode) && $isTextNode(nextNode)) {
208
- return (
209
- prevNode.__type === nextNode.__type &&
210
- prevNode.__text === nextNode.__text &&
211
- prevNode.__mode === nextNode.__mode &&
212
- prevNode.__detail === nextNode.__detail &&
213
- prevNode.__style === nextNode.__style &&
214
- prevNode.__format === nextNode.__format &&
215
- prevNode.__parent === nextNode.__parent
216
- );
106
+ return prevNode.__type === nextNode.__type && prevNode.__text === nextNode.__text && prevNode.__mode === nextNode.__mode && prevNode.__detail === nextNode.__detail && prevNode.__style === nextNode.__style && prevNode.__format === nextNode.__format && prevNode.__parent === nextNode.__parent;
217
107
  }
218
108
  return false;
219
109
  }
220
-
221
- function createMergeActionGetter(
222
- editor: LexicalEditor,
223
- delay: number,
224
- ): (
225
- prevEditorState: null | EditorState,
226
- nextEditorState: EditorState,
227
- currentHistoryEntry: null | HistoryStateEntry,
228
- dirtyLeaves: Set<NodeKey>,
229
- dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
230
- tags: Set<string>,
231
- ) => MergeAction {
110
+ function createMergeActionGetter(editor, delay) {
232
111
  let prevChangeTime = Date.now();
233
112
  let prevChangeType = OTHER;
234
-
235
- return (
236
- prevEditorState,
237
- nextEditorState,
238
- currentHistoryEntry,
239
- dirtyLeaves,
240
- dirtyElements,
241
- tags,
242
- ) => {
113
+ return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
243
114
  const changeTime = Date.now();
244
115
 
245
116
  // If applying changes from history stack there's no need
@@ -249,48 +120,26 @@ function createMergeActionGetter(
249
120
  prevChangeTime = changeTime;
250
121
  return DISCARD_HISTORY_CANDIDATE;
251
122
  }
252
-
253
- const changeType = getChangeType(
254
- prevEditorState,
255
- nextEditorState,
256
- dirtyLeaves,
257
- dirtyElements,
258
- editor.isComposing(),
259
- );
260
-
123
+ const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
261
124
  const mergeAction = (() => {
262
- const isSameEditor =
263
- currentHistoryEntry === null || currentHistoryEntry.editor === editor;
125
+ const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
264
126
  const shouldPushHistory = tags.has('history-push');
265
- const shouldMergeHistory =
266
- !shouldPushHistory && isSameEditor && tags.has('history-merge');
267
-
127
+ const shouldMergeHistory = !shouldPushHistory && isSameEditor && tags.has('history-merge');
268
128
  if (shouldMergeHistory) {
269
129
  return HISTORY_MERGE;
270
130
  }
271
-
272
131
  if (prevEditorState === null) {
273
132
  return HISTORY_PUSH;
274
133
  }
275
-
276
134
  const selection = nextEditorState._selection;
277
135
  const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
278
-
279
136
  if (!hasDirtyNodes) {
280
137
  if (selection !== null) {
281
138
  return HISTORY_MERGE;
282
139
  }
283
-
284
140
  return DISCARD_HISTORY_CANDIDATE;
285
141
  }
286
-
287
- if (
288
- shouldPushHistory === false &&
289
- changeType !== OTHER &&
290
- changeType === prevChangeType &&
291
- changeTime < prevChangeTime + delay &&
292
- isSameEditor
293
- ) {
142
+ if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
294
143
  return HISTORY_MERGE;
295
144
  }
296
145
 
@@ -298,80 +147,61 @@ function createMergeActionGetter(
298
147
  // due to some node transform reverting the change.
299
148
  if (dirtyLeaves.size === 1) {
300
149
  const dirtyLeafKey = Array.from(dirtyLeaves)[0];
301
- if (
302
- isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)
303
- ) {
150
+ if (isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)) {
304
151
  return HISTORY_MERGE;
305
152
  }
306
153
  }
307
-
308
154
  return HISTORY_PUSH;
309
155
  })();
310
-
311
156
  prevChangeTime = changeTime;
312
157
  prevChangeType = changeType;
313
-
314
158
  return mergeAction;
315
159
  };
316
160
  }
317
-
318
- function redo(editor: LexicalEditor, historyState: HistoryState): void {
161
+ function redo(editor, historyState) {
319
162
  const redoStack = historyState.redoStack;
320
163
  const undoStack = historyState.undoStack;
321
-
322
164
  if (redoStack.length !== 0) {
323
165
  const current = historyState.current;
324
-
325
166
  if (current !== null) {
326
167
  undoStack.push(current);
327
168
  editor.dispatchCommand(CAN_UNDO_COMMAND, true);
328
169
  }
329
-
330
170
  const historyStateEntry = redoStack.pop();
331
-
332
171
  if (redoStack.length === 0) {
333
172
  editor.dispatchCommand(CAN_REDO_COMMAND, false);
334
173
  }
335
-
336
174
  historyState.current = historyStateEntry || null;
337
-
338
175
  if (historyStateEntry) {
339
176
  historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
340
- tag: 'historic',
177
+ tag: 'historic'
341
178
  });
342
179
  }
343
180
  }
344
181
  }
345
-
346
- function undo(editor: LexicalEditor, historyState: HistoryState): void {
182
+ function undo(editor, historyState) {
347
183
  const redoStack = historyState.redoStack;
348
184
  const undoStack = historyState.undoStack;
349
185
  const undoStackLength = undoStack.length;
350
-
351
186
  if (undoStackLength !== 0) {
352
187
  const current = historyState.current;
353
188
  const historyStateEntry = undoStack.pop();
354
-
355
189
  if (current !== null) {
356
190
  redoStack.push(current);
357
191
  editor.dispatchCommand(CAN_REDO_COMMAND, true);
358
192
  }
359
-
360
193
  if (undoStack.length === 0) {
361
194
  editor.dispatchCommand(CAN_UNDO_COMMAND, false);
362
195
  }
363
-
364
196
  historyState.current = historyStateEntry || null;
365
-
366
197
  if (historyStateEntry) {
367
198
  historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
368
- tag: 'historic',
199
+ tag: 'historic'
369
200
  });
370
201
  }
371
202
  }
372
203
  }
373
-
374
- function clearHistory(historyState: HistoryState) {
204
+ function clearHistory(historyState) {
375
205
  historyState.undoStack = [];
376
206
  historyState.redoStack = [];
377
207
  historyState.current = null;
@@ -386,53 +216,31 @@ function clearHistory(historyState: HistoryState) {
386
216
  * instead of merging the current changes with the current stack.
387
217
  * @returns The listeners cleanup callback function.
388
218
  */
389
- export function registerHistory(
390
- editor: LexicalEditor,
391
- historyState: HistoryState,
392
- delay: number,
393
- ): () => void {
219
+ function registerHistory(editor, historyState, delay) {
394
220
  const getMergeAction = createMergeActionGetter(editor, delay);
395
-
396
221
  const applyChange = ({
397
222
  editorState,
398
223
  prevEditorState,
399
224
  dirtyLeaves,
400
225
  dirtyElements,
401
- tags,
402
- }: {
403
- editorState: EditorState;
404
- prevEditorState: EditorState;
405
- dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>;
406
- dirtyLeaves: Set<NodeKey>;
407
- tags: Set<string>;
408
- }): void => {
226
+ tags
227
+ }) => {
409
228
  const current = historyState.current;
410
229
  const redoStack = historyState.redoStack;
411
230
  const undoStack = historyState.undoStack;
412
231
  const currentEditorState = current === null ? null : current.editorState;
413
-
414
232
  if (current !== null && editorState === currentEditorState) {
415
233
  return;
416
234
  }
417
-
418
- const mergeAction = getMergeAction(
419
- prevEditorState,
420
- editorState,
421
- current,
422
- dirtyLeaves,
423
- dirtyElements,
424
- tags,
425
- );
426
-
235
+ const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
427
236
  if (mergeAction === HISTORY_PUSH) {
428
237
  if (redoStack.length !== 0) {
429
238
  historyState.redoStack = [];
430
239
  editor.dispatchCommand(CAN_REDO_COMMAND, false);
431
240
  }
432
-
433
241
  if (current !== null) {
434
242
  undoStack.push({
435
- ...current,
243
+ ...current
436
244
  });
437
245
  editor.dispatchCommand(CAN_UNDO_COMMAND, true);
438
246
  }
@@ -443,50 +251,25 @@ export function registerHistory(
443
251
  // Else we merge
444
252
  historyState.current = {
445
253
  editor,
446
- editorState,
254
+ editorState
447
255
  };
448
256
  };
449
-
450
- const unregisterCommandListener = mergeRegister(
451
- editor.registerCommand(
452
- UNDO_COMMAND,
453
- () => {
454
- undo(editor, historyState);
455
- return true;
456
- },
457
- COMMAND_PRIORITY_EDITOR,
458
- ),
459
- editor.registerCommand(
460
- REDO_COMMAND,
461
- () => {
462
- redo(editor, historyState);
463
- return true;
464
- },
465
- COMMAND_PRIORITY_EDITOR,
466
- ),
467
- editor.registerCommand(
468
- CLEAR_EDITOR_COMMAND,
469
- () => {
470
- clearHistory(historyState);
471
- return false;
472
- },
473
- COMMAND_PRIORITY_EDITOR,
474
- ),
475
- editor.registerCommand(
476
- CLEAR_HISTORY_COMMAND,
477
- () => {
478
- clearHistory(historyState);
479
- editor.dispatchCommand(CAN_REDO_COMMAND, false);
480
- editor.dispatchCommand(CAN_UNDO_COMMAND, false);
481
- return true;
482
- },
483
- COMMAND_PRIORITY_EDITOR,
484
- ),
485
- editor.registerUpdateListener(applyChange),
486
- );
487
-
257
+ const unregisterCommandListener = mergeRegister(editor.registerCommand(UNDO_COMMAND, () => {
258
+ undo(editor, historyState);
259
+ return true;
260
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(REDO_COMMAND, () => {
261
+ redo(editor, historyState);
262
+ return true;
263
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(CLEAR_EDITOR_COMMAND, () => {
264
+ clearHistory(historyState);
265
+ return false;
266
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(CLEAR_HISTORY_COMMAND, () => {
267
+ clearHistory(historyState);
268
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
269
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
270
+ return true;
271
+ }, COMMAND_PRIORITY_EDITOR), editor.registerUpdateListener(applyChange));
488
272
  const unregisterUpdateListener = editor.registerUpdateListener(applyChange);
489
-
490
273
  return () => {
491
274
  unregisterCommandListener();
492
275
  unregisterUpdateListener();
@@ -497,10 +280,12 @@ export function registerHistory(
497
280
  * Creates an empty history state.
498
281
  * @returns - The empty history state, as an object.
499
282
  */
500
- export function createEmptyHistoryState(): HistoryState {
283
+ function createEmptyHistoryState() {
501
284
  return {
502
285
  current: null,
503
286
  redoStack: [],
504
- undoStack: [],
287
+ undoStack: []
505
288
  };
506
289
  }
290
+
291
+ export { createEmptyHistoryState, registerHistory };
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict';
8
+
9
+ var utils = require('@lexical/utils');
10
+ var lexical = require('lexical');
11
+
12
+ /** @module @lexical/history */
13
+ const HISTORY_MERGE = 0;
14
+ const HISTORY_PUSH = 1;
15
+ const DISCARD_HISTORY_CANDIDATE = 2;
16
+ const OTHER = 0;
17
+ const COMPOSING_CHARACTER = 1;
18
+ const INSERT_CHARACTER_AFTER_SELECTION = 2;
19
+ const DELETE_CHARACTER_BEFORE_SELECTION = 3;
20
+ const DELETE_CHARACTER_AFTER_SELECTION = 4;
21
+ function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
22
+ const nodeMap = editorState._nodeMap;
23
+ const nodes = [];
24
+ for (const dirtyLeafKey of dirtyLeaves) {
25
+ const dirtyLeaf = nodeMap.get(dirtyLeafKey);
26
+ if (dirtyLeaf !== undefined) {
27
+ nodes.push(dirtyLeaf);
28
+ }
29
+ }
30
+ for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
31
+ if (!intentionallyMarkedAsDirty) {
32
+ continue;
33
+ }
34
+ const dirtyElement = nodeMap.get(dirtyElementKey);
35
+ if (dirtyElement !== undefined && !lexical.$isRootNode(dirtyElement)) {
36
+ nodes.push(dirtyElement);
37
+ }
38
+ }
39
+ return nodes;
40
+ }
41
+ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
42
+ if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing) {
43
+ return OTHER;
44
+ }
45
+ const nextSelection = nextEditorState._selection;
46
+ const prevSelection = prevEditorState._selection;
47
+ if (isComposing) {
48
+ return COMPOSING_CHARACTER;
49
+ }
50
+ if (!lexical.$isRangeSelection(nextSelection) || !lexical.$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
51
+ return OTHER;
52
+ }
53
+ const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
54
+ if (dirtyNodes.length === 0) {
55
+ return OTHER;
56
+ }
57
+
58
+ // Catching the case when inserting new text node into an element (e.g. first char in paragraph/list),
59
+ // or after existing node.
60
+ if (dirtyNodes.length > 1) {
61
+ const nextNodeMap = nextEditorState._nodeMap;
62
+ const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
63
+ const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
64
+ if (nextAnchorNode && prevAnchorNode && !prevEditorState._nodeMap.has(nextAnchorNode.__key) && lexical.$isTextNode(nextAnchorNode) && nextAnchorNode.__text.length === 1 && nextSelection.anchor.offset === 1) {
65
+ return INSERT_CHARACTER_AFTER_SELECTION;
66
+ }
67
+ return OTHER;
68
+ }
69
+ const nextDirtyNode = dirtyNodes[0];
70
+ const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
71
+ if (!lexical.$isTextNode(prevDirtyNode) || !lexical.$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
72
+ return OTHER;
73
+ }
74
+ const prevText = prevDirtyNode.__text;
75
+ const nextText = nextDirtyNode.__text;
76
+ if (prevText === nextText) {
77
+ return OTHER;
78
+ }
79
+ const nextAnchor = nextSelection.anchor;
80
+ const prevAnchor = prevSelection.anchor;
81
+ if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
82
+ return OTHER;
83
+ }
84
+ const nextAnchorOffset = nextAnchor.offset;
85
+ const prevAnchorOffset = prevAnchor.offset;
86
+ const textDiff = nextText.length - prevText.length;
87
+ if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
88
+ return INSERT_CHARACTER_AFTER_SELECTION;
89
+ }
90
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
91
+ return DELETE_CHARACTER_BEFORE_SELECTION;
92
+ }
93
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
94
+ return DELETE_CHARACTER_AFTER_SELECTION;
95
+ }
96
+ return OTHER;
97
+ }
98
+ function isTextNodeUnchanged(key, prevEditorState, nextEditorState) {
99
+ const prevNode = prevEditorState._nodeMap.get(key);
100
+ const nextNode = nextEditorState._nodeMap.get(key);
101
+ const prevSelection = prevEditorState._selection;
102
+ const nextSelection = nextEditorState._selection;
103
+ let isDeletingLine = false;
104
+ if (lexical.$isRangeSelection(prevSelection) && lexical.$isRangeSelection(nextSelection)) {
105
+ isDeletingLine = prevSelection.anchor.type === 'element' && prevSelection.focus.type === 'element' && nextSelection.anchor.type === 'text' && nextSelection.focus.type === 'text';
106
+ }
107
+ if (!isDeletingLine && lexical.$isTextNode(prevNode) && lexical.$isTextNode(nextNode)) {
108
+ return prevNode.__type === nextNode.__type && prevNode.__text === nextNode.__text && prevNode.__mode === nextNode.__mode && prevNode.__detail === nextNode.__detail && prevNode.__style === nextNode.__style && prevNode.__format === nextNode.__format && prevNode.__parent === nextNode.__parent;
109
+ }
110
+ return false;
111
+ }
112
+ function createMergeActionGetter(editor, delay) {
113
+ let prevChangeTime = Date.now();
114
+ let prevChangeType = OTHER;
115
+ return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
116
+ const changeTime = Date.now();
117
+
118
+ // If applying changes from history stack there's no need
119
+ // to run history logic again, as history entries already calculated
120
+ if (tags.has('historic')) {
121
+ prevChangeType = OTHER;
122
+ prevChangeTime = changeTime;
123
+ return DISCARD_HISTORY_CANDIDATE;
124
+ }
125
+ const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
126
+ const mergeAction = (() => {
127
+ const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
128
+ const shouldPushHistory = tags.has('history-push');
129
+ const shouldMergeHistory = !shouldPushHistory && isSameEditor && tags.has('history-merge');
130
+ if (shouldMergeHistory) {
131
+ return HISTORY_MERGE;
132
+ }
133
+ if (prevEditorState === null) {
134
+ return HISTORY_PUSH;
135
+ }
136
+ const selection = nextEditorState._selection;
137
+ const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
138
+ if (!hasDirtyNodes) {
139
+ if (selection !== null) {
140
+ return HISTORY_MERGE;
141
+ }
142
+ return DISCARD_HISTORY_CANDIDATE;
143
+ }
144
+ if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
145
+ return HISTORY_MERGE;
146
+ }
147
+
148
+ // A single node might have been marked as dirty, but not have changed
149
+ // due to some node transform reverting the change.
150
+ if (dirtyLeaves.size === 1) {
151
+ const dirtyLeafKey = Array.from(dirtyLeaves)[0];
152
+ if (isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)) {
153
+ return HISTORY_MERGE;
154
+ }
155
+ }
156
+ return HISTORY_PUSH;
157
+ })();
158
+ prevChangeTime = changeTime;
159
+ prevChangeType = changeType;
160
+ return mergeAction;
161
+ };
162
+ }
163
+ function redo(editor, historyState) {
164
+ const redoStack = historyState.redoStack;
165
+ const undoStack = historyState.undoStack;
166
+ if (redoStack.length !== 0) {
167
+ const current = historyState.current;
168
+ if (current !== null) {
169
+ undoStack.push(current);
170
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
171
+ }
172
+ const historyStateEntry = redoStack.pop();
173
+ if (redoStack.length === 0) {
174
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
175
+ }
176
+ historyState.current = historyStateEntry || null;
177
+ if (historyStateEntry) {
178
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
179
+ tag: 'historic'
180
+ });
181
+ }
182
+ }
183
+ }
184
+ function undo(editor, historyState) {
185
+ const redoStack = historyState.redoStack;
186
+ const undoStack = historyState.undoStack;
187
+ const undoStackLength = undoStack.length;
188
+ if (undoStackLength !== 0) {
189
+ const current = historyState.current;
190
+ const historyStateEntry = undoStack.pop();
191
+ if (current !== null) {
192
+ redoStack.push(current);
193
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, true);
194
+ }
195
+ if (undoStack.length === 0) {
196
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
197
+ }
198
+ historyState.current = historyStateEntry || null;
199
+ if (historyStateEntry) {
200
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
201
+ tag: 'historic'
202
+ });
203
+ }
204
+ }
205
+ }
206
+ function clearHistory(historyState) {
207
+ historyState.undoStack = [];
208
+ historyState.redoStack = [];
209
+ historyState.current = null;
210
+ }
211
+
212
+ /**
213
+ * Registers necessary listeners to manage undo/redo history stack and related editor commands.
214
+ * It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
215
+ * @param editor - The lexical editor.
216
+ * @param historyState - The history state, containing the current state and the undo/redo stack.
217
+ * @param delay - The time (in milliseconds) the editor should delay generating a new history stack,
218
+ * instead of merging the current changes with the current stack.
219
+ * @returns The listeners cleanup callback function.
220
+ */
221
+ function registerHistory(editor, historyState, delay) {
222
+ const getMergeAction = createMergeActionGetter(editor, delay);
223
+ const applyChange = ({
224
+ editorState,
225
+ prevEditorState,
226
+ dirtyLeaves,
227
+ dirtyElements,
228
+ tags
229
+ }) => {
230
+ const current = historyState.current;
231
+ const redoStack = historyState.redoStack;
232
+ const undoStack = historyState.undoStack;
233
+ const currentEditorState = current === null ? null : current.editorState;
234
+ if (current !== null && editorState === currentEditorState) {
235
+ return;
236
+ }
237
+ const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
238
+ if (mergeAction === HISTORY_PUSH) {
239
+ if (redoStack.length !== 0) {
240
+ historyState.redoStack = [];
241
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
242
+ }
243
+ if (current !== null) {
244
+ undoStack.push({
245
+ ...current
246
+ });
247
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
248
+ }
249
+ } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
250
+ return;
251
+ }
252
+
253
+ // Else we merge
254
+ historyState.current = {
255
+ editor,
256
+ editorState
257
+ };
258
+ };
259
+ const unregisterCommandListener = utils.mergeRegister(editor.registerCommand(lexical.UNDO_COMMAND, () => {
260
+ undo(editor, historyState);
261
+ return true;
262
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.REDO_COMMAND, () => {
263
+ redo(editor, historyState);
264
+ return true;
265
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.CLEAR_EDITOR_COMMAND, () => {
266
+ clearHistory(historyState);
267
+ return false;
268
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.CLEAR_HISTORY_COMMAND, () => {
269
+ clearHistory(historyState);
270
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
271
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
272
+ return true;
273
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerUpdateListener(applyChange));
274
+ const unregisterUpdateListener = editor.registerUpdateListener(applyChange);
275
+ return () => {
276
+ unregisterCommandListener();
277
+ unregisterUpdateListener();
278
+ };
279
+ }
280
+
281
+ /**
282
+ * Creates an empty history state.
283
+ * @returns - The empty history state, as an object.
284
+ */
285
+ function createEmptyHistoryState() {
286
+ return {
287
+ current: null,
288
+ redoStack: [],
289
+ undoStack: []
290
+ };
291
+ }
292
+
293
+ exports.createEmptyHistoryState = createEmptyHistoryState;
294
+ exports.registerHistory = registerHistory;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import * as modDev from './LexicalHistory.dev.esm.js';
8
+ import * as modProd from './LexicalHistory.prod.esm.js';
9
+ const mod = process.env.NODE_ENV === 'development' ? modDev : modProd;
10
+ export const createEmptyHistoryState = mod.createEmptyHistoryState;
11
+ export const registerHistory = mod.registerHistory;
package/LexicalHistory.js CHANGED
@@ -3,9 +3,7 @@
3
3
  *
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
- *
7
6
  */
8
-
9
- 'use strict';
10
-
11
- module.exports = require('./dist/LexicalHistory.js');
7
+ 'use strict'
8
+ const LexicalHistory = process.env.NODE_ENV === 'development' ? require('./LexicalHistory.dev.js') : require('./LexicalHistory.prod.js');
9
+ module.exports = LexicalHistory;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import{mergeRegister as t}from"@lexical/utils";import{UNDO_COMMAND as e,COMMAND_PRIORITY_EDITOR as n,REDO_COMMAND as r,CLEAR_EDITOR_COMMAND as o,CLEAR_HISTORY_COMMAND as i,CAN_REDO_COMMAND as s,CAN_UNDO_COMMAND as c,$isRangeSelection as a,$isTextNode as u,$isRootNode as d}from"lexical";const l=0,_=1,f=2,p=0,h=1,m=2,g=3,y=4;function S(t,e,n,r,o){if(null===t||0===n.size&&0===r.size&&!o)return p;const i=e._selection,s=t._selection;if(o)return h;if(!(a(i)&&a(s)&&s.isCollapsed()&&i.isCollapsed()))return p;const c=function(t,e,n){const r=t._nodeMap,o=[];for(const t of e){const e=r.get(t);void 0!==e&&o.push(e)}for(const[t,e]of n){if(!e)continue;const n=r.get(t);void 0===n||d(n)||o.push(n)}return o}(e,n,r);if(0===c.length)return p;if(c.length>1){const n=e._nodeMap,r=n.get(i.anchor.key),o=n.get(s.anchor.key);return r&&o&&!t._nodeMap.has(r.__key)&&u(r)&&1===r.__text.length&&1===i.anchor.offset?m:p}const l=c[0],_=t._nodeMap.get(l.__key);if(!u(_)||!u(l)||_.__mode!==l.__mode)return p;const f=_.__text,S=l.__text;if(f===S)return p;const k=i.anchor,C=s.anchor;if(k.key!==C.key||"text"!==k.type)return p;const x=k.offset,M=C.offset,z=S.length-f.length;return 1===z&&M===x-1?m:-1===z&&M===x+1?g:-1===z&&M===x?y:p}function k(t,e){let n=Date.now(),r=p;return(o,i,s,c,d,h)=>{const m=Date.now();if(h.has("historic"))return r=p,n=m,f;const g=S(o,i,c,d,t.isComposing()),y=(()=>{const y=null===s||s.editor===t,S=h.has("history-push");if(!S&&y&&h.has("history-merge"))return l;if(null===o)return _;const k=i._selection;if(!(c.size>0||d.size>0))return null!==k?l:f;if(!1===S&&g!==p&&g===r&&m<n+e&&y)return l;if(1===c.size){if(function(t,e,n){const r=e._nodeMap.get(t),o=n._nodeMap.get(t),i=e._selection,s=n._selection;let c=!1;return a(i)&&a(s)&&(c="element"===i.anchor.type&&"element"===i.focus.type&&"text"===s.anchor.type&&"text"===s.focus.type),!(c||!u(r)||!u(o))&&r.__type===o.__type&&r.__text===o.__text&&r.__mode===o.__mode&&r.__detail===o.__detail&&r.__style===o.__style&&r.__format===o.__format&&r.__parent===o.__parent}(Array.from(c)[0],o,i))return l}return _})();return n=m,r=g,y}}function C(t){t.undoStack=[],t.redoStack=[],t.current=null}function x(a,u,d){const l=k(a,d),p=({editorState:t,prevEditorState:e,dirtyLeaves:n,dirtyElements:r,tags:o})=>{const i=u.current,d=u.redoStack,p=u.undoStack,h=null===i?null:i.editorState;if(null!==i&&t===h)return;const m=l(e,t,i,n,r,o);if(m===_)0!==d.length&&(u.redoStack=[],a.dispatchCommand(s,!1)),null!==i&&(p.push({...i}),a.dispatchCommand(c,!0));else if(m===f)return;u.current={editor:a,editorState:t}},h=t(a.registerCommand(e,(()=>(function(t,e){const n=e.redoStack,r=e.undoStack;if(0!==r.length){const o=e.current,i=r.pop();null!==o&&(n.push(o),t.dispatchCommand(s,!0)),0===r.length&&t.dispatchCommand(c,!1),e.current=i||null,i&&i.editor.setEditorState(i.editorState,{tag:"historic"})}}(a,u),!0)),n),a.registerCommand(r,(()=>(function(t,e){const n=e.redoStack,r=e.undoStack;if(0!==n.length){const o=e.current;null!==o&&(r.push(o),t.dispatchCommand(c,!0));const i=n.pop();0===n.length&&t.dispatchCommand(s,!1),e.current=i||null,i&&i.editor.setEditorState(i.editorState,{tag:"historic"})}}(a,u),!0)),n),a.registerCommand(o,(()=>(C(u),!1)),n),a.registerCommand(i,(()=>(C(u),a.dispatchCommand(s,!1),a.dispatchCommand(c,!1),!0)),n),a.registerUpdateListener(p)),m=a.registerUpdateListener(p);return()=>{h(),m()}}function M(){return{current:null,redoStack:[],undoStack:[]}}export{M as createEmptyHistoryState,x as registerHistory};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict';var c=require("@lexical/utils"),x=require("lexical");
8
+ function y(b,a,l,h,n){if(null===b||0===l.size&&0===h.size&&!n)return 0;var f=a._selection,d=b._selection;if(n)return 1;if(!(x.$isRangeSelection(f)&&x.$isRangeSelection(d)&&d.isCollapsed()&&f.isCollapsed()))return 0;n=a._nodeMap;let e=[];for(let m of l)l=n.get(m),void 0!==l&&e.push(l);for(let [m,p]of h)p&&(h=n.get(m),void 0===h||x.$isRootNode(h)||e.push(h));if(0===e.length)return 0;if(1<e.length)return h=a._nodeMap,a=h.get(f.anchor.key),d=h.get(d.anchor.key),a&&d&&!b._nodeMap.has(a.__key)&&x.$isTextNode(a)&&
9
+ 1===a.__text.length&&1===f.anchor.offset?2:0;a=e[0];b=b._nodeMap.get(a.__key);if(!x.$isTextNode(b)||!x.$isTextNode(a)||b.__mode!==a.__mode)return 0;b=b.__text;a=a.__text;if(b===a)return 0;f=f.anchor;d=d.anchor;if(f.key!==d.key||"text"!==f.type)return 0;f=f.offset;d=d.offset;b=a.length-b.length;return 1===b&&d===f-1?2:-1===b&&d===f+1?3:-1===b&&d===f?4:0}
10
+ function z(b,a){let l=Date.now(),h=0;return(n,f,d,e,m,p)=>{let r=Date.now();if(p.has("historic"))return h=0,l=r,2;let q=y(n,f,e,m,b.isComposing()),v=(()=>{var k=null===d||d.editor===b,g=p.has("history-push");if(!g&&k&&p.has("history-merge"))return 0;if(null===n)return 1;var t=f._selection;if(!(0<e.size||0<m.size))return null!==t?0:2;if(!1===g&&0!==q&&q===h&&r<l+a&&k)return 0;if(1===e.size){{g=Array.from(e)[0];k=n._nodeMap.get(g);g=f._nodeMap.get(g);t=n._selection;let u=f._selection,w=!1;x.$isRangeSelection(t)&&
11
+ x.$isRangeSelection(u)&&(w="element"===t.anchor.type&&"element"===t.focus.type&&"text"===u.anchor.type&&"text"===u.focus.type);k=!w&&x.$isTextNode(k)&&x.$isTextNode(g)?k.__type===g.__type&&k.__text===g.__text&&k.__mode===g.__mode&&k.__detail===g.__detail&&k.__style===g.__style&&k.__format===g.__format&&k.__parent===g.__parent:!1}if(k)return 0}return 1})();l=r;h=q;return v}}exports.createEmptyHistoryState=function(){return{current:null,redoStack:[],undoStack:[]}};
12
+ exports.registerHistory=function(b,a,l){let h=z(b,l);l=({editorState:d,prevEditorState:e,dirtyLeaves:m,dirtyElements:p,tags:r})=>{const q=a.current,v=a.redoStack,k=a.undoStack,g=null===q?null:q.editorState;if(null===q||d!==g){e=h(e,d,q,m,p,r);if(1===e)0!==v.length&&(a.redoStack=[],b.dispatchCommand(x.CAN_REDO_COMMAND,!1)),null!==q&&(k.push({...q}),b.dispatchCommand(x.CAN_UNDO_COMMAND,!0));else if(2===e)return;a.current={editor:b,editorState:d}}};let n=c.mergeRegister(b.registerCommand(x.UNDO_COMMAND,
13
+ ()=>{let d=a.redoStack,e=a.undoStack;if(0!==e.length){let m=a.current,p=e.pop();null!==m&&(d.push(m),b.dispatchCommand(x.CAN_REDO_COMMAND,!0));0===e.length&&b.dispatchCommand(x.CAN_UNDO_COMMAND,!1);a.current=p||null;p&&p.editor.setEditorState(p.editorState,{tag:"historic"})}return!0},x.COMMAND_PRIORITY_EDITOR),b.registerCommand(x.REDO_COMMAND,()=>{let d=a.redoStack;var e=a.undoStack;if(0!==d.length){let m=a.current;null!==m&&(e.push(m),b.dispatchCommand(x.CAN_UNDO_COMMAND,!0));e=d.pop();0===d.length&&
14
+ b.dispatchCommand(x.CAN_REDO_COMMAND,!1);a.current=e||null;e&&e.editor.setEditorState(e.editorState,{tag:"historic"})}return!0},x.COMMAND_PRIORITY_EDITOR),b.registerCommand(x.CLEAR_EDITOR_COMMAND,()=>{a.undoStack=[];a.redoStack=[];a.current=null;return!1},x.COMMAND_PRIORITY_EDITOR),b.registerCommand(x.CLEAR_HISTORY_COMMAND,()=>{a.undoStack=[];a.redoStack=[];a.current=null;b.dispatchCommand(x.CAN_REDO_COMMAND,!1);b.dispatchCommand(x.CAN_UNDO_COMMAND,!1);return!0},x.COMMAND_PRIORITY_EDITOR),b.registerUpdateListener(l)),
15
+ f=b.registerUpdateListener(l);return()=>{n();f()}}
package/index.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /** @module @lexical/history */
2
+ /**
3
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ *
8
+ */
9
+ import type { EditorState, LexicalEditor } from 'lexical';
10
+ export type HistoryStateEntry = {
11
+ editor: LexicalEditor;
12
+ editorState: EditorState;
13
+ };
14
+ export type HistoryState = {
15
+ current: null | HistoryStateEntry;
16
+ redoStack: Array<HistoryStateEntry>;
17
+ undoStack: Array<HistoryStateEntry>;
18
+ };
19
+ /**
20
+ * Registers necessary listeners to manage undo/redo history stack and related editor commands.
21
+ * It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
22
+ * @param editor - The lexical editor.
23
+ * @param historyState - The history state, containing the current state and the undo/redo stack.
24
+ * @param delay - The time (in milliseconds) the editor should delay generating a new history stack,
25
+ * instead of merging the current changes with the current stack.
26
+ * @returns The listeners cleanup callback function.
27
+ */
28
+ export declare function registerHistory(editor: LexicalEditor, historyState: HistoryState, delay: number): () => void;
29
+ /**
30
+ * Creates an empty history state.
31
+ * @returns - The empty history state, as an object.
32
+ */
33
+ export declare function createEmptyHistoryState(): HistoryState;
package/package.json CHANGED
@@ -8,13 +8,13 @@
8
8
  "history"
9
9
  ],
10
10
  "license": "MIT",
11
- "version": "0.14.0",
11
+ "version": "0.14.2",
12
12
  "main": "LexicalHistory.js",
13
13
  "peerDependencies": {
14
- "lexical": "0.14.0"
14
+ "lexical": "0.14.2"
15
15
  },
16
16
  "dependencies": {
17
- "@lexical/utils": "0.14.0"
17
+ "@lexical/utils": "0.14.2"
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
@@ -1,323 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
-
9
- import {createEmptyHistoryState, registerHistory} from '@lexical/history';
10
- import {useLexicalComposerContext} from '@lexical/react/src/LexicalComposerContext';
11
- import {ContentEditable} from '@lexical/react/src/LexicalContentEditable';
12
- import LexicalErrorBoundary from '@lexical/react/src/LexicalErrorBoundary';
13
- import {HistoryPlugin} from '@lexical/react/src/LexicalHistoryPlugin';
14
- import {RichTextPlugin} from '@lexical/react/src/LexicalRichTextPlugin';
15
- import {$createQuoteNode} from '@lexical/rich-text/src';
16
- import {$setBlocksType} from '@lexical/selection/src';
17
- import {
18
- $createNodeSelection,
19
- $createRangeSelection,
20
- $isNodeSelection,
21
- CAN_REDO_COMMAND,
22
- CAN_UNDO_COMMAND,
23
- CLEAR_HISTORY_COMMAND,
24
- COMMAND_PRIORITY_CRITICAL,
25
- LexicalEditor,
26
- REDO_COMMAND,
27
- SerializedElementNode,
28
- SerializedTextNode,
29
- UNDO_COMMAND,
30
- } from 'lexical/src';
31
- import {createTestEditor, TestComposer} from 'lexical/src/__tests__/utils';
32
- import {$getRoot, $setSelection} from 'lexical/src/LexicalUtils';
33
- import {$createParagraphNode} from 'lexical/src/nodes/LexicalParagraphNode';
34
- import {$createTextNode} from 'lexical/src/nodes/LexicalTextNode';
35
- import React from 'react';
36
- import {createRoot} from 'react-dom/client';
37
- import * as ReactTestUtils from 'react-dom/test-utils';
38
-
39
- describe('LexicalHistory tests', () => {
40
- let container: HTMLDivElement | null = null;
41
- let reactRoot;
42
-
43
- beforeEach(() => {
44
- container = document.createElement('div');
45
- reactRoot = createRoot(container);
46
- document.body.appendChild(container);
47
- });
48
-
49
- afterEach(() => {
50
- if (container !== null) {
51
- document.body.removeChild(container);
52
- }
53
- container = null;
54
-
55
- jest.restoreAllMocks();
56
- });
57
-
58
- // Shared instance across tests
59
- let editor: LexicalEditor;
60
-
61
- function Test(): JSX.Element {
62
- function TestPlugin() {
63
- // Plugin used just to get our hands on the Editor object
64
- [editor] = useLexicalComposerContext();
65
- return null;
66
- }
67
-
68
- return (
69
- <TestComposer>
70
- <RichTextPlugin
71
- contentEditable={<ContentEditable />}
72
- placeholder={
73
- <div className="editor-placeholder">Enter some text...</div>
74
- }
75
- ErrorBoundary={LexicalErrorBoundary}
76
- />
77
- <TestPlugin />
78
- <HistoryPlugin />
79
- </TestComposer>
80
- );
81
- }
82
-
83
- test('LexicalHistory after clearing', async () => {
84
- let canRedo = true;
85
- let canUndo = true;
86
-
87
- ReactTestUtils.act(() => {
88
- reactRoot.render(<Test key="smth" />);
89
- });
90
-
91
- editor.registerCommand<boolean>(
92
- CAN_REDO_COMMAND,
93
- (payload) => {
94
- canRedo = payload;
95
- return false;
96
- },
97
- COMMAND_PRIORITY_CRITICAL,
98
- );
99
-
100
- editor.registerCommand<boolean>(
101
- CAN_UNDO_COMMAND,
102
- (payload) => {
103
- canUndo = payload;
104
- return false;
105
- },
106
- COMMAND_PRIORITY_CRITICAL,
107
- );
108
-
109
- await Promise.resolve().then();
110
-
111
- await ReactTestUtils.act(async () => {
112
- editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined);
113
- });
114
-
115
- expect(canRedo).toBe(false);
116
- expect(canUndo).toBe(false);
117
- });
118
-
119
- test('LexicalHistory.Redo after Quote Node', async () => {
120
- ReactTestUtils.act(() => {
121
- reactRoot.render(<Test key="smth" />);
122
- });
123
-
124
- // Wait for update to complete
125
- await Promise.resolve().then();
126
-
127
- await ReactTestUtils.act(async () => {
128
- await editor.update(() => {
129
- const root = $getRoot();
130
- const paragraph1 = createParagraphNode('AAA');
131
- const paragraph2 = createParagraphNode('BBB');
132
-
133
- // The editor has one child that is an empty
134
- // paragraph Node.
135
- root.getChildAtIndex(0)?.replace(paragraph1);
136
- root.append(paragraph2);
137
- });
138
- });
139
-
140
- const initialJSONState = editor.getEditorState().toJSON();
141
-
142
- await ReactTestUtils.act(async () => {
143
- await editor.update(() => {
144
- const root = $getRoot();
145
- const selection = $createRangeSelection();
146
-
147
- const firstTextNode = root.getAllTextNodes()[0];
148
- selection.anchor.set(firstTextNode.getKey(), 0, 'text');
149
- selection.focus.set(firstTextNode.getKey(), 3, 'text');
150
-
151
- $setSelection(selection);
152
- $setBlocksType(selection, () => $createQuoteNode());
153
- });
154
- });
155
-
156
- const afterQuoteInsertionJSONState = editor.getEditorState().toJSON();
157
- expect(afterQuoteInsertionJSONState.root.children.length).toBe(2);
158
- expect(afterQuoteInsertionJSONState.root.children[0].type).toBe('quote');
159
-
160
- expect(
161
- (afterQuoteInsertionJSONState.root.children as SerializedElementNode[])[0]
162
- .children.length,
163
- ).toBe(1);
164
- expect(
165
- (afterQuoteInsertionJSONState.root.children as SerializedElementNode[])[0]
166
- .children[0].type,
167
- ).toBe('text');
168
- expect(
169
- (
170
- (
171
- afterQuoteInsertionJSONState.root.children as SerializedElementNode[]
172
- )[0].children[0] as SerializedTextNode
173
- ).text,
174
- ).toBe('AAA');
175
-
176
- await ReactTestUtils.act(async () => {
177
- await editor.update(() => {
178
- editor.dispatchCommand(UNDO_COMMAND, undefined);
179
- });
180
- });
181
-
182
- expect(JSON.stringify(initialJSONState)).toBe(
183
- JSON.stringify(editor.getEditorState().toJSON()),
184
- );
185
- });
186
-
187
- test('LexicalHistory in sequence: change, undo, redo, undo, change', async () => {
188
- let canRedo = false;
189
- let canUndo = false;
190
-
191
- ReactTestUtils.act(() => {
192
- reactRoot.render(<Test key="smth" />);
193
- });
194
-
195
- editor.registerCommand<boolean>(
196
- CAN_REDO_COMMAND,
197
- (payload) => {
198
- canRedo = payload;
199
- return false;
200
- },
201
- COMMAND_PRIORITY_CRITICAL,
202
- );
203
-
204
- editor.registerCommand<boolean>(
205
- CAN_UNDO_COMMAND,
206
- (payload) => {
207
- canUndo = payload;
208
- return false;
209
- },
210
- COMMAND_PRIORITY_CRITICAL,
211
- );
212
-
213
- // focus (needs the focus to initialize)
214
- await ReactTestUtils.act(async () => {
215
- editor.focus();
216
- });
217
-
218
- expect(canRedo).toBe(false);
219
- expect(canUndo).toBe(false);
220
-
221
- // change
222
- await ReactTestUtils.act(async () => {
223
- await editor.update(() => {
224
- const root = $getRoot();
225
- const paragraph = createParagraphNode('foo');
226
- root.append(paragraph);
227
- });
228
- });
229
- expect(canRedo).toBe(false);
230
- expect(canUndo).toBe(true);
231
-
232
- // undo
233
- await ReactTestUtils.act(async () => {
234
- await editor.update(() => {
235
- editor.dispatchCommand(UNDO_COMMAND, undefined);
236
- });
237
- });
238
- expect(canRedo).toBe(true);
239
- expect(canUndo).toBe(false);
240
-
241
- // redo
242
- await ReactTestUtils.act(async () => {
243
- await editor.update(() => {
244
- editor.dispatchCommand(REDO_COMMAND, undefined);
245
- });
246
- });
247
- expect(canRedo).toBe(false);
248
- expect(canUndo).toBe(true);
249
-
250
- // undo
251
- await ReactTestUtils.act(async () => {
252
- await editor.update(() => {
253
- editor.dispatchCommand(UNDO_COMMAND, undefined);
254
- });
255
- });
256
- expect(canRedo).toBe(true);
257
- expect(canUndo).toBe(false);
258
-
259
- // change
260
- await ReactTestUtils.act(async () => {
261
- await editor.update(() => {
262
- const root = $getRoot();
263
- const paragraph = createParagraphNode('foo');
264
- root.append(paragraph);
265
- });
266
- });
267
-
268
- expect(canRedo).toBe(false);
269
- expect(canUndo).toBe(true);
270
- });
271
-
272
- test('undoStack selection points to the same editor', async () => {
273
- const editor_ = createTestEditor({namespace: 'parent'});
274
- const sharedHistory = createEmptyHistoryState();
275
- registerHistory(editor_, sharedHistory, 1000);
276
- await editor_.update(() => {
277
- const root = $getRoot();
278
- const paragraph = $createParagraphNode();
279
- root.append(paragraph);
280
- });
281
- await editor_.update(() => {
282
- const root = $getRoot();
283
- const paragraph = $createParagraphNode();
284
- root.append(paragraph);
285
- const nodeSelection = $createNodeSelection();
286
- nodeSelection.add(paragraph.getKey());
287
- $setSelection(nodeSelection);
288
- });
289
- const nestedEditor = createTestEditor({namespace: 'nested'});
290
- await nestedEditor.update(
291
- () => {
292
- const root = $getRoot();
293
- const paragraph = $createParagraphNode();
294
- root.append(paragraph);
295
- paragraph.selectEnd();
296
- },
297
- {
298
- tag: 'history-merge',
299
- },
300
- );
301
- nestedEditor._parentEditor = editor_;
302
- registerHistory(nestedEditor, sharedHistory, 1000);
303
-
304
- await nestedEditor.update(() => {
305
- const root = $getRoot();
306
- const paragraph = $createParagraphNode();
307
- root.append(paragraph);
308
- paragraph.selectEnd();
309
- });
310
-
311
- expect(sharedHistory.undoStack.length).toBe(2);
312
- await editor_.dispatchCommand(UNDO_COMMAND, undefined);
313
- expect($isNodeSelection(editor_.getEditorState()._selection)).toBe(true);
314
- });
315
- });
316
-
317
- const createParagraphNode = (text: string) => {
318
- const paragraph = $createParagraphNode();
319
- const textNode = $createTextNode(text);
320
-
321
- paragraph.append(textNode);
322
- return paragraph;
323
- };