@lexical/history 0.13.0 → 0.14.0

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/LexicalHistory.js CHANGED
@@ -3,7 +3,9 @@
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
+ *
6
7
  */
7
- 'use strict'
8
- const LexicalHistory = process.env.NODE_ENV === 'development' ? require('./LexicalHistory.dev.js') : require('./LexicalHistory.prod.js')
9
- module.exports = LexicalHistory;
8
+
9
+ 'use strict';
10
+
11
+ module.exports = require('./dist/LexicalHistory.js');
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # `@lexical/history`
2
2
 
3
+ [![See API Documentation](https://lexical.dev/img/see-api-documentation.svg)](https://lexical.dev/docs/api/modules/lexical_history)
4
+
3
5
  This package contains history helpers for Lexical.
4
6
 
5
7
  ### Methods
package/package.json CHANGED
@@ -8,17 +8,19 @@
8
8
  "history"
9
9
  ],
10
10
  "license": "MIT",
11
- "version": "0.13.0",
11
+ "version": "0.14.0",
12
12
  "main": "LexicalHistory.js",
13
13
  "peerDependencies": {
14
- "lexical": "0.13.0"
14
+ "lexical": "0.14.0"
15
15
  },
16
16
  "dependencies": {
17
- "@lexical/utils": "0.13.0"
17
+ "@lexical/utils": "0.14.0"
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
21
21
  "url": "https://github.com/facebook/lexical",
22
22
  "directory": "packages/lexical-history"
23
- }
23
+ },
24
+ "module": "LexicalHistory.esm.js",
25
+ "sideEffects": false
24
26
  }
@@ -0,0 +1,323 @@
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
+ };
@@ -1,56 +1,119 @@
1
+ /** @module @lexical/history */
1
2
  /**
2
3
  * Copyright (c) Meta Platforms, Inc. and affiliates.
3
4
  *
4
5
  * This source code is licensed under the MIT license found in the
5
6
  * LICENSE file in the root directory of this source tree.
7
+ *
6
8
  */
7
- 'use strict';
8
9
 
9
- var utils = require('@lexical/utils');
10
- var lexical = require('lexical');
10
+ import type {EditorState, LexicalEditor, LexicalNode, NodeKey} from 'lexical';
11
11
 
12
- /** @module @lexical/history */
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;
13
27
  const HISTORY_MERGE = 0;
14
28
  const HISTORY_PUSH = 1;
15
29
  const DISCARD_HISTORY_CANDIDATE = 2;
30
+
31
+ type ChangeType = 0 | 1 | 2 | 3 | 4;
16
32
  const OTHER = 0;
17
33
  const COMPOSING_CHARACTER = 1;
18
34
  const INSERT_CHARACTER_AFTER_SELECTION = 2;
19
35
  const DELETE_CHARACTER_BEFORE_SELECTION = 3;
20
36
  const DELETE_CHARACTER_AFTER_SELECTION = 4;
21
- function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
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> {
22
55
  const nodeMap = editorState._nodeMap;
23
56
  const nodes = [];
57
+
24
58
  for (const dirtyLeafKey of dirtyLeaves) {
25
59
  const dirtyLeaf = nodeMap.get(dirtyLeafKey);
60
+
26
61
  if (dirtyLeaf !== undefined) {
27
62
  nodes.push(dirtyLeaf);
28
63
  }
29
64
  }
65
+
30
66
  for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
31
67
  if (!intentionallyMarkedAsDirty) {
32
68
  continue;
33
69
  }
70
+
34
71
  const dirtyElement = nodeMap.get(dirtyElementKey);
35
- if (dirtyElement !== undefined && !lexical.$isRootNode(dirtyElement)) {
72
+
73
+ if (dirtyElement !== undefined && !$isRootNode(dirtyElement)) {
36
74
  nodes.push(dirtyElement);
37
75
  }
38
76
  }
77
+
39
78
  return nodes;
40
79
  }
41
- function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
42
- if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing) {
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
+ ) {
43
92
  return OTHER;
44
93
  }
94
+
45
95
  const nextSelection = nextEditorState._selection;
46
96
  const prevSelection = prevEditorState._selection;
97
+
47
98
  if (isComposing) {
48
99
  return COMPOSING_CHARACTER;
49
100
  }
50
- if (!lexical.$isRangeSelection(nextSelection) || !lexical.$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
101
+
102
+ if (
103
+ !$isRangeSelection(nextSelection) ||
104
+ !$isRangeSelection(prevSelection) ||
105
+ !prevSelection.isCollapsed() ||
106
+ !nextSelection.isCollapsed()
107
+ ) {
51
108
  return OTHER;
52
109
  }
53
- const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
110
+
111
+ const dirtyNodes = getDirtyNodes(
112
+ nextEditorState,
113
+ dirtyLeavesSet,
114
+ dirtyElementsSet,
115
+ );
116
+
54
117
  if (dirtyNodes.length === 0) {
55
118
  return OTHER;
56
119
  }
@@ -61,58 +124,122 @@ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyEl
61
124
  const nextNodeMap = nextEditorState._nodeMap;
62
125
  const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
63
126
  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) {
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
+ ) {
65
136
  return INSERT_CHARACTER_AFTER_SELECTION;
66
137
  }
138
+
67
139
  return OTHER;
68
140
  }
141
+
69
142
  const nextDirtyNode = dirtyNodes[0];
143
+
70
144
  const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
71
- if (!lexical.$isTextNode(prevDirtyNode) || !lexical.$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
145
+
146
+ if (
147
+ !$isTextNode(prevDirtyNode) ||
148
+ !$isTextNode(nextDirtyNode) ||
149
+ prevDirtyNode.__mode !== nextDirtyNode.__mode
150
+ ) {
72
151
  return OTHER;
73
152
  }
153
+
74
154
  const prevText = prevDirtyNode.__text;
75
155
  const nextText = nextDirtyNode.__text;
156
+
76
157
  if (prevText === nextText) {
77
158
  return OTHER;
78
159
  }
160
+
79
161
  const nextAnchor = nextSelection.anchor;
80
162
  const prevAnchor = prevSelection.anchor;
163
+
81
164
  if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
82
165
  return OTHER;
83
166
  }
167
+
84
168
  const nextAnchorOffset = nextAnchor.offset;
85
169
  const prevAnchorOffset = prevAnchor.offset;
86
170
  const textDiff = nextText.length - prevText.length;
171
+
87
172
  if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
88
173
  return INSERT_CHARACTER_AFTER_SELECTION;
89
174
  }
175
+
90
176
  if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
91
177
  return DELETE_CHARACTER_BEFORE_SELECTION;
92
178
  }
179
+
93
180
  if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
94
181
  return DELETE_CHARACTER_AFTER_SELECTION;
95
182
  }
183
+
96
184
  return OTHER;
97
185
  }
98
- function isTextNodeUnchanged(key, prevEditorState, nextEditorState) {
186
+
187
+ function isTextNodeUnchanged(
188
+ key: NodeKey,
189
+ prevEditorState: EditorState,
190
+ nextEditorState: EditorState,
191
+ ): boolean {
99
192
  const prevNode = prevEditorState._nodeMap.get(key);
100
193
  const nextNode = nextEditorState._nodeMap.get(key);
194
+
101
195
  const prevSelection = prevEditorState._selection;
102
196
  const nextSelection = nextEditorState._selection;
103
197
  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';
198
+
199
+ 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';
106
205
  }
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;
206
+
207
+ 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
+ );
109
217
  }
110
218
  return false;
111
219
  }
112
- function createMergeActionGetter(editor, delay) {
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 {
113
232
  let prevChangeTime = Date.now();
114
233
  let prevChangeType = OTHER;
115
- return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
234
+
235
+ return (
236
+ prevEditorState,
237
+ nextEditorState,
238
+ currentHistoryEntry,
239
+ dirtyLeaves,
240
+ dirtyElements,
241
+ tags,
242
+ ) => {
116
243
  const changeTime = Date.now();
117
244
 
118
245
  // If applying changes from history stack there's no need
@@ -122,26 +249,48 @@ function createMergeActionGetter(editor, delay) {
122
249
  prevChangeTime = changeTime;
123
250
  return DISCARD_HISTORY_CANDIDATE;
124
251
  }
125
- const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
252
+
253
+ const changeType = getChangeType(
254
+ prevEditorState,
255
+ nextEditorState,
256
+ dirtyLeaves,
257
+ dirtyElements,
258
+ editor.isComposing(),
259
+ );
260
+
126
261
  const mergeAction = (() => {
127
- const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
262
+ const isSameEditor =
263
+ currentHistoryEntry === null || currentHistoryEntry.editor === editor;
128
264
  const shouldPushHistory = tags.has('history-push');
129
- const shouldMergeHistory = !shouldPushHistory && isSameEditor && tags.has('history-merge');
265
+ const shouldMergeHistory =
266
+ !shouldPushHistory && isSameEditor && tags.has('history-merge');
267
+
130
268
  if (shouldMergeHistory) {
131
269
  return HISTORY_MERGE;
132
270
  }
271
+
133
272
  if (prevEditorState === null) {
134
273
  return HISTORY_PUSH;
135
274
  }
275
+
136
276
  const selection = nextEditorState._selection;
137
277
  const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
278
+
138
279
  if (!hasDirtyNodes) {
139
280
  if (selection !== null) {
140
281
  return HISTORY_MERGE;
141
282
  }
283
+
142
284
  return DISCARD_HISTORY_CANDIDATE;
143
285
  }
144
- if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
286
+
287
+ if (
288
+ shouldPushHistory === false &&
289
+ changeType !== OTHER &&
290
+ changeType === prevChangeType &&
291
+ changeTime < prevChangeTime + delay &&
292
+ isSameEditor
293
+ ) {
145
294
  return HISTORY_MERGE;
146
295
  }
147
296
 
@@ -149,61 +298,80 @@ function createMergeActionGetter(editor, delay) {
149
298
  // due to some node transform reverting the change.
150
299
  if (dirtyLeaves.size === 1) {
151
300
  const dirtyLeafKey = Array.from(dirtyLeaves)[0];
152
- if (isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)) {
301
+ if (
302
+ isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)
303
+ ) {
153
304
  return HISTORY_MERGE;
154
305
  }
155
306
  }
307
+
156
308
  return HISTORY_PUSH;
157
309
  })();
310
+
158
311
  prevChangeTime = changeTime;
159
312
  prevChangeType = changeType;
313
+
160
314
  return mergeAction;
161
315
  };
162
316
  }
163
- function redo(editor, historyState) {
317
+
318
+ function redo(editor: LexicalEditor, historyState: HistoryState): void {
164
319
  const redoStack = historyState.redoStack;
165
320
  const undoStack = historyState.undoStack;
321
+
166
322
  if (redoStack.length !== 0) {
167
323
  const current = historyState.current;
324
+
168
325
  if (current !== null) {
169
326
  undoStack.push(current);
170
- editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
327
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
171
328
  }
329
+
172
330
  const historyStateEntry = redoStack.pop();
331
+
173
332
  if (redoStack.length === 0) {
174
- editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
333
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
175
334
  }
335
+
176
336
  historyState.current = historyStateEntry || null;
337
+
177
338
  if (historyStateEntry) {
178
339
  historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
179
- tag: 'historic'
340
+ tag: 'historic',
180
341
  });
181
342
  }
182
343
  }
183
344
  }
184
- function undo(editor, historyState) {
345
+
346
+ function undo(editor: LexicalEditor, historyState: HistoryState): void {
185
347
  const redoStack = historyState.redoStack;
186
348
  const undoStack = historyState.undoStack;
187
349
  const undoStackLength = undoStack.length;
350
+
188
351
  if (undoStackLength !== 0) {
189
352
  const current = historyState.current;
190
353
  const historyStateEntry = undoStack.pop();
354
+
191
355
  if (current !== null) {
192
356
  redoStack.push(current);
193
- editor.dispatchCommand(lexical.CAN_REDO_COMMAND, true);
357
+ editor.dispatchCommand(CAN_REDO_COMMAND, true);
194
358
  }
359
+
195
360
  if (undoStack.length === 0) {
196
- editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
361
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
197
362
  }
363
+
198
364
  historyState.current = historyStateEntry || null;
365
+
199
366
  if (historyStateEntry) {
200
367
  historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
201
- tag: 'historic'
368
+ tag: 'historic',
202
369
  });
203
370
  }
204
371
  }
205
372
  }
206
- function clearHistory(historyState) {
373
+
374
+ function clearHistory(historyState: HistoryState) {
207
375
  historyState.undoStack = [];
208
376
  historyState.redoStack = [];
209
377
  historyState.current = null;
@@ -218,33 +386,55 @@ function clearHistory(historyState) {
218
386
  * instead of merging the current changes with the current stack.
219
387
  * @returns The listeners cleanup callback function.
220
388
  */
221
- function registerHistory(editor, historyState, delay) {
389
+ export function registerHistory(
390
+ editor: LexicalEditor,
391
+ historyState: HistoryState,
392
+ delay: number,
393
+ ): () => void {
222
394
  const getMergeAction = createMergeActionGetter(editor, delay);
395
+
223
396
  const applyChange = ({
224
397
  editorState,
225
398
  prevEditorState,
226
399
  dirtyLeaves,
227
400
  dirtyElements,
228
- tags
229
- }) => {
401
+ tags,
402
+ }: {
403
+ editorState: EditorState;
404
+ prevEditorState: EditorState;
405
+ dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>;
406
+ dirtyLeaves: Set<NodeKey>;
407
+ tags: Set<string>;
408
+ }): void => {
230
409
  const current = historyState.current;
231
410
  const redoStack = historyState.redoStack;
232
411
  const undoStack = historyState.undoStack;
233
412
  const currentEditorState = current === null ? null : current.editorState;
413
+
234
414
  if (current !== null && editorState === currentEditorState) {
235
415
  return;
236
416
  }
237
- const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
417
+
418
+ const mergeAction = getMergeAction(
419
+ prevEditorState,
420
+ editorState,
421
+ current,
422
+ dirtyLeaves,
423
+ dirtyElements,
424
+ tags,
425
+ );
426
+
238
427
  if (mergeAction === HISTORY_PUSH) {
239
428
  if (redoStack.length !== 0) {
240
429
  historyState.redoStack = [];
241
- editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
430
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
242
431
  }
432
+
243
433
  if (current !== null) {
244
434
  undoStack.push({
245
- ...current
435
+ ...current,
246
436
  });
247
- editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
437
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
248
438
  }
249
439
  } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
250
440
  return;
@@ -253,25 +443,50 @@ function registerHistory(editor, historyState, delay) {
253
443
  // Else we merge
254
444
  historyState.current = {
255
445
  editor,
256
- editorState
446
+ editorState,
257
447
  };
258
448
  };
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));
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
+
274
488
  const unregisterUpdateListener = editor.registerUpdateListener(applyChange);
489
+
275
490
  return () => {
276
491
  unregisterCommandListener();
277
492
  unregisterUpdateListener();
@@ -282,13 +497,10 @@ function registerHistory(editor, historyState, delay) {
282
497
  * Creates an empty history state.
283
498
  * @returns - The empty history state, as an object.
284
499
  */
285
- function createEmptyHistoryState() {
500
+ export function createEmptyHistoryState(): HistoryState {
286
501
  return {
287
502
  current: null,
288
503
  redoStack: [],
289
- undoStack: []
504
+ undoStack: [],
290
505
  };
291
506
  }
292
-
293
- exports.createEmptyHistoryState = createEmptyHistoryState;
294
- exports.registerHistory = registerHistory;
package/LICENSE DELETED
@@ -1,21 +0,0 @@
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,15 +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
- '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 DELETED
@@ -1,33 +0,0 @@
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;