@ekz/lexical-history 0.40.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.
@@ -0,0 +1,363 @@
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
+ 'use strict';
10
+
11
+ var lexicalExtension = require('@ekz/lexical-extension');
12
+ var lexicalUtils = require('@ekz/lexical-utils');
13
+ var lexical = require('@ekz/lexical');
14
+
15
+ /**
16
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
17
+ *
18
+ * This source code is licensed under the MIT license found in the
19
+ * LICENSE file in the root directory of this source tree.
20
+ *
21
+ */
22
+
23
+ const HISTORY_MERGE = 0;
24
+ const HISTORY_PUSH = 1;
25
+ const DISCARD_HISTORY_CANDIDATE = 2;
26
+ const OTHER = 0;
27
+ const COMPOSING_CHARACTER = 1;
28
+ const INSERT_CHARACTER_AFTER_SELECTION = 2;
29
+ const DELETE_CHARACTER_BEFORE_SELECTION = 3;
30
+ const DELETE_CHARACTER_AFTER_SELECTION = 4;
31
+ function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
32
+ const nodeMap = editorState._nodeMap;
33
+ const nodes = [];
34
+ for (const dirtyLeafKey of dirtyLeaves) {
35
+ const dirtyLeaf = nodeMap.get(dirtyLeafKey);
36
+ if (dirtyLeaf !== undefined) {
37
+ nodes.push(dirtyLeaf);
38
+ }
39
+ }
40
+ for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
41
+ if (!intentionallyMarkedAsDirty) {
42
+ continue;
43
+ }
44
+ const dirtyElement = nodeMap.get(dirtyElementKey);
45
+ if (dirtyElement !== undefined && !lexical.$isRootNode(dirtyElement)) {
46
+ nodes.push(dirtyElement);
47
+ }
48
+ }
49
+ return nodes;
50
+ }
51
+ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
52
+ if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing) {
53
+ return OTHER;
54
+ }
55
+ const nextSelection = nextEditorState._selection;
56
+ const prevSelection = prevEditorState._selection;
57
+ if (isComposing) {
58
+ return COMPOSING_CHARACTER;
59
+ }
60
+ if (!lexical.$isRangeSelection(nextSelection) || !lexical.$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
61
+ return OTHER;
62
+ }
63
+ const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
64
+ if (dirtyNodes.length === 0) {
65
+ return OTHER;
66
+ }
67
+
68
+ // Catching the case when inserting new text node into an element (e.g. first char in paragraph/list),
69
+ // or after existing node.
70
+ if (dirtyNodes.length > 1) {
71
+ const nextNodeMap = nextEditorState._nodeMap;
72
+ const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
73
+ const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
74
+ if (nextAnchorNode && prevAnchorNode && !prevEditorState._nodeMap.has(nextAnchorNode.__key) && lexical.$isTextNode(nextAnchorNode) && nextAnchorNode.__text.length === 1 && nextSelection.anchor.offset === 1) {
75
+ return INSERT_CHARACTER_AFTER_SELECTION;
76
+ }
77
+ return OTHER;
78
+ }
79
+ const nextDirtyNode = dirtyNodes[0];
80
+ const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
81
+ if (!lexical.$isTextNode(prevDirtyNode) || !lexical.$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
82
+ return OTHER;
83
+ }
84
+ const prevText = prevDirtyNode.__text;
85
+ const nextText = nextDirtyNode.__text;
86
+ if (prevText === nextText) {
87
+ return OTHER;
88
+ }
89
+ const nextAnchor = nextSelection.anchor;
90
+ const prevAnchor = prevSelection.anchor;
91
+ if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
92
+ return OTHER;
93
+ }
94
+ const nextAnchorOffset = nextAnchor.offset;
95
+ const prevAnchorOffset = prevAnchor.offset;
96
+ const textDiff = nextText.length - prevText.length;
97
+ if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
98
+ return INSERT_CHARACTER_AFTER_SELECTION;
99
+ }
100
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
101
+ return DELETE_CHARACTER_BEFORE_SELECTION;
102
+ }
103
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
104
+ return DELETE_CHARACTER_AFTER_SELECTION;
105
+ }
106
+ return OTHER;
107
+ }
108
+ function isTextNodeUnchanged(key, prevEditorState, nextEditorState) {
109
+ const prevNode = prevEditorState._nodeMap.get(key);
110
+ const nextNode = nextEditorState._nodeMap.get(key);
111
+ const prevSelection = prevEditorState._selection;
112
+ const nextSelection = nextEditorState._selection;
113
+ const isDeletingLine = lexical.$isRangeSelection(prevSelection) && lexical.$isRangeSelection(nextSelection) && prevSelection.anchor.type === 'element' && prevSelection.focus.type === 'element' && nextSelection.anchor.type === 'text' && nextSelection.focus.type === 'text';
114
+ if (!isDeletingLine && lexical.$isTextNode(prevNode) && lexical.$isTextNode(nextNode) && prevNode.__parent === nextNode.__parent) {
115
+ // This has the assumption that object key order won't change if the
116
+ // content did not change, which should normally be safe given
117
+ // the manner in which nodes and exportJSON are typically implemented.
118
+ return JSON.stringify(prevEditorState.read(() => prevNode.exportJSON())) === JSON.stringify(nextEditorState.read(() => nextNode.exportJSON()));
119
+ }
120
+ return false;
121
+ }
122
+ function createMergeActionGetter(editor, delayOrStore) {
123
+ let prevChangeTime = Date.now();
124
+ let prevChangeType = OTHER;
125
+ return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
126
+ const changeTime = Date.now();
127
+
128
+ // If applying changes from history stack there's no need
129
+ // to run history logic again, as history entries already calculated
130
+ if (tags.has(lexical.HISTORIC_TAG)) {
131
+ prevChangeType = OTHER;
132
+ prevChangeTime = changeTime;
133
+ return DISCARD_HISTORY_CANDIDATE;
134
+ }
135
+ const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
136
+ const mergeAction = (() => {
137
+ const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
138
+ const shouldPushHistory = tags.has(lexical.HISTORY_PUSH_TAG);
139
+ const shouldMergeHistory = !shouldPushHistory && isSameEditor && tags.has(lexical.HISTORY_MERGE_TAG);
140
+ if (shouldMergeHistory) {
141
+ return HISTORY_MERGE;
142
+ }
143
+ if (prevEditorState === null) {
144
+ return HISTORY_PUSH;
145
+ }
146
+ const selection = nextEditorState._selection;
147
+ const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
148
+ if (!hasDirtyNodes) {
149
+ if (selection !== null) {
150
+ return HISTORY_MERGE;
151
+ }
152
+ return DISCARD_HISTORY_CANDIDATE;
153
+ }
154
+ const delay = typeof delayOrStore === 'number' ? delayOrStore : delayOrStore.peek();
155
+ if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
156
+ return HISTORY_MERGE;
157
+ }
158
+
159
+ // A single node might have been marked as dirty, but not have changed
160
+ // due to some node transform reverting the change.
161
+ if (dirtyLeaves.size === 1) {
162
+ const dirtyLeafKey = Array.from(dirtyLeaves)[0];
163
+ if (isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)) {
164
+ return HISTORY_MERGE;
165
+ }
166
+ }
167
+ return HISTORY_PUSH;
168
+ })();
169
+ prevChangeTime = changeTime;
170
+ prevChangeType = changeType;
171
+ return mergeAction;
172
+ };
173
+ }
174
+ function redo(editor, historyState) {
175
+ const redoStack = historyState.redoStack;
176
+ const undoStack = historyState.undoStack;
177
+ if (redoStack.length !== 0) {
178
+ const current = historyState.current;
179
+ if (current !== null) {
180
+ undoStack.push(current);
181
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
182
+ }
183
+ const historyStateEntry = redoStack.pop();
184
+ if (redoStack.length === 0) {
185
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
186
+ }
187
+ historyState.current = historyStateEntry || null;
188
+ if (historyStateEntry) {
189
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
190
+ tag: lexical.HISTORIC_TAG
191
+ });
192
+ }
193
+ }
194
+ }
195
+ function undo(editor, historyState) {
196
+ const redoStack = historyState.redoStack;
197
+ const undoStack = historyState.undoStack;
198
+ const undoStackLength = undoStack.length;
199
+ if (undoStackLength !== 0) {
200
+ const current = historyState.current;
201
+ const historyStateEntry = undoStack.pop();
202
+ if (current !== null) {
203
+ redoStack.push(current);
204
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, true);
205
+ }
206
+ if (undoStack.length === 0) {
207
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
208
+ }
209
+ historyState.current = historyStateEntry || null;
210
+ if (historyStateEntry) {
211
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
212
+ tag: lexical.HISTORIC_TAG
213
+ });
214
+ }
215
+ }
216
+ }
217
+ function clearHistory(historyState) {
218
+ historyState.undoStack = [];
219
+ historyState.redoStack = [];
220
+ historyState.current = null;
221
+ }
222
+
223
+ /**
224
+ * Registers necessary listeners to manage undo/redo history stack and related editor commands.
225
+ * It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
226
+ * @param editor - The lexical editor.
227
+ * @param historyState - The history state, containing the current state and the undo/redo stack.
228
+ * @param delay - The time (in milliseconds) the editor should delay generating a new history stack,
229
+ * instead of merging the current changes with the current stack.
230
+ * @returns The listeners cleanup callback function.
231
+ */
232
+ function registerHistory(editor, historyState, delay) {
233
+ const getMergeAction = createMergeActionGetter(editor, delay);
234
+ const applyChange = ({
235
+ editorState,
236
+ prevEditorState,
237
+ dirtyLeaves,
238
+ dirtyElements,
239
+ tags
240
+ }) => {
241
+ const current = historyState.current;
242
+ const redoStack = historyState.redoStack;
243
+ const undoStack = historyState.undoStack;
244
+ const currentEditorState = current === null ? null : current.editorState;
245
+ if (current !== null && editorState === currentEditorState) {
246
+ return;
247
+ }
248
+ const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
249
+ if (mergeAction === HISTORY_PUSH) {
250
+ if (redoStack.length !== 0) {
251
+ historyState.redoStack = [];
252
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
253
+ }
254
+ if (current !== null) {
255
+ undoStack.push({
256
+ ...current
257
+ });
258
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
259
+ }
260
+ } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
261
+ return;
262
+ }
263
+
264
+ // Else we merge
265
+ historyState.current = {
266
+ editor,
267
+ editorState
268
+ };
269
+ };
270
+ const unregister = lexicalUtils.mergeRegister(editor.registerCommand(lexical.UNDO_COMMAND, () => {
271
+ undo(editor, historyState);
272
+ return true;
273
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.REDO_COMMAND, () => {
274
+ redo(editor, historyState);
275
+ return true;
276
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.CLEAR_EDITOR_COMMAND, () => {
277
+ clearHistory(historyState);
278
+ return false;
279
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.CLEAR_HISTORY_COMMAND, () => {
280
+ clearHistory(historyState);
281
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
282
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
283
+ return true;
284
+ }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerUpdateListener(applyChange));
285
+ return unregister;
286
+ }
287
+
288
+ /**
289
+ * Creates an empty history state.
290
+ * @returns - The empty history state, as an object.
291
+ */
292
+ function createEmptyHistoryState() {
293
+ return {
294
+ current: null,
295
+ redoStack: [],
296
+ undoStack: []
297
+ };
298
+ }
299
+ /**
300
+ * Registers necessary listeners to manage undo/redo history stack and related
301
+ * editor commands, via the \@lexical/history module.
302
+ */
303
+
304
+ const HistoryExtension = lexical.defineExtension({
305
+ build: (editor, {
306
+ delay,
307
+ createInitialHistoryState,
308
+ disabled
309
+ }) => lexicalExtension.namedSignals({
310
+ delay,
311
+ disabled,
312
+ historyState: createInitialHistoryState(editor)
313
+ }),
314
+ config: lexical.safeCast({
315
+ createInitialHistoryState: createEmptyHistoryState,
316
+ delay: 300,
317
+ disabled: typeof window === 'undefined'
318
+ }),
319
+ name: '@ekz/lexical-history/History',
320
+ register: (editor, config, state) => {
321
+ const stores = state.getOutput();
322
+ return lexicalExtension.effect(() => stores.disabled.value ? undefined : registerHistory(editor, stores.historyState.value, stores.delay));
323
+ }
324
+ });
325
+ function getHistoryPeer(editor) {
326
+ return editor ? lexicalExtension.getPeerDependencyFromEditor(editor, HistoryExtension.name) : null;
327
+ }
328
+
329
+ /**
330
+ * Registers necessary listeners to manage undo/redo history stack and related
331
+ * editor commands, via the \@lexical/history module, only if the parent editor
332
+ * has a history plugin implementation.
333
+ */
334
+ const SharedHistoryExtension = lexical.defineExtension({
335
+ dependencies: [lexical.configExtension(HistoryExtension, {
336
+ createInitialHistoryState: () => {
337
+ throw new Error('SharedHistory did not inherit parent history');
338
+ },
339
+ disabled: true
340
+ })],
341
+ name: '@ekz/lexical-history/SharedHistory',
342
+ register(editor, _config, state) {
343
+ const {
344
+ output
345
+ } = state.getDependency(HistoryExtension);
346
+ const parentPeer = getHistoryPeer(editor._parentEditor);
347
+ if (!parentPeer) {
348
+ return () => {};
349
+ }
350
+ const parentOutput = parentPeer.output;
351
+ return lexicalExtension.effect(() => lexicalExtension.batch(() => {
352
+ output.delay.value = parentOutput.delay.value;
353
+ output.historyState.value = parentOutput.historyState.value;
354
+ // Note that toggling the parent history will force this to be changed
355
+ output.disabled.value = parentOutput.disabled.value;
356
+ }));
357
+ }
358
+ });
359
+
360
+ exports.HistoryExtension = HistoryExtension;
361
+ exports.SharedHistoryExtension = SharedHistoryExtension;
362
+ exports.createEmptyHistoryState = createEmptyHistoryState;
363
+ exports.registerHistory = registerHistory;
@@ -0,0 +1,358 @@
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 { namedSignals, effect, batch, getPeerDependencyFromEditor } from '@ekz/lexical-extension';
10
+ import { mergeRegister } from '@ekz/lexical-utils';
11
+ import { defineExtension, safeCast, configExtension, UNDO_COMMAND, COMMAND_PRIORITY_EDITOR, REDO_COMMAND, CLEAR_EDITOR_COMMAND, CLEAR_HISTORY_COMMAND, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, HISTORIC_TAG, HISTORY_PUSH_TAG, HISTORY_MERGE_TAG, $isRangeSelection, $isTextNode, $isRootNode } from '@ekz/lexical';
12
+
13
+ /**
14
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
15
+ *
16
+ * This source code is licensed under the MIT license found in the
17
+ * LICENSE file in the root directory of this source tree.
18
+ *
19
+ */
20
+
21
+ const HISTORY_MERGE = 0;
22
+ const HISTORY_PUSH = 1;
23
+ const DISCARD_HISTORY_CANDIDATE = 2;
24
+ const OTHER = 0;
25
+ const COMPOSING_CHARACTER = 1;
26
+ const INSERT_CHARACTER_AFTER_SELECTION = 2;
27
+ const DELETE_CHARACTER_BEFORE_SELECTION = 3;
28
+ const DELETE_CHARACTER_AFTER_SELECTION = 4;
29
+ function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
30
+ const nodeMap = editorState._nodeMap;
31
+ const nodes = [];
32
+ for (const dirtyLeafKey of dirtyLeaves) {
33
+ const dirtyLeaf = nodeMap.get(dirtyLeafKey);
34
+ if (dirtyLeaf !== undefined) {
35
+ nodes.push(dirtyLeaf);
36
+ }
37
+ }
38
+ for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
39
+ if (!intentionallyMarkedAsDirty) {
40
+ continue;
41
+ }
42
+ const dirtyElement = nodeMap.get(dirtyElementKey);
43
+ if (dirtyElement !== undefined && !$isRootNode(dirtyElement)) {
44
+ nodes.push(dirtyElement);
45
+ }
46
+ }
47
+ return nodes;
48
+ }
49
+ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
50
+ if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing) {
51
+ return OTHER;
52
+ }
53
+ const nextSelection = nextEditorState._selection;
54
+ const prevSelection = prevEditorState._selection;
55
+ if (isComposing) {
56
+ return COMPOSING_CHARACTER;
57
+ }
58
+ if (!$isRangeSelection(nextSelection) || !$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
59
+ return OTHER;
60
+ }
61
+ const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
62
+ if (dirtyNodes.length === 0) {
63
+ return OTHER;
64
+ }
65
+
66
+ // Catching the case when inserting new text node into an element (e.g. first char in paragraph/list),
67
+ // or after existing node.
68
+ if (dirtyNodes.length > 1) {
69
+ const nextNodeMap = nextEditorState._nodeMap;
70
+ const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
71
+ const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
72
+ if (nextAnchorNode && prevAnchorNode && !prevEditorState._nodeMap.has(nextAnchorNode.__key) && $isTextNode(nextAnchorNode) && nextAnchorNode.__text.length === 1 && nextSelection.anchor.offset === 1) {
73
+ return INSERT_CHARACTER_AFTER_SELECTION;
74
+ }
75
+ return OTHER;
76
+ }
77
+ const nextDirtyNode = dirtyNodes[0];
78
+ const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
79
+ if (!$isTextNode(prevDirtyNode) || !$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
80
+ return OTHER;
81
+ }
82
+ const prevText = prevDirtyNode.__text;
83
+ const nextText = nextDirtyNode.__text;
84
+ if (prevText === nextText) {
85
+ return OTHER;
86
+ }
87
+ const nextAnchor = nextSelection.anchor;
88
+ const prevAnchor = prevSelection.anchor;
89
+ if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
90
+ return OTHER;
91
+ }
92
+ const nextAnchorOffset = nextAnchor.offset;
93
+ const prevAnchorOffset = prevAnchor.offset;
94
+ const textDiff = nextText.length - prevText.length;
95
+ if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
96
+ return INSERT_CHARACTER_AFTER_SELECTION;
97
+ }
98
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
99
+ return DELETE_CHARACTER_BEFORE_SELECTION;
100
+ }
101
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
102
+ return DELETE_CHARACTER_AFTER_SELECTION;
103
+ }
104
+ return OTHER;
105
+ }
106
+ function isTextNodeUnchanged(key, prevEditorState, nextEditorState) {
107
+ const prevNode = prevEditorState._nodeMap.get(key);
108
+ const nextNode = nextEditorState._nodeMap.get(key);
109
+ const prevSelection = prevEditorState._selection;
110
+ const nextSelection = nextEditorState._selection;
111
+ const isDeletingLine = $isRangeSelection(prevSelection) && $isRangeSelection(nextSelection) && prevSelection.anchor.type === 'element' && prevSelection.focus.type === 'element' && nextSelection.anchor.type === 'text' && nextSelection.focus.type === 'text';
112
+ if (!isDeletingLine && $isTextNode(prevNode) && $isTextNode(nextNode) && prevNode.__parent === nextNode.__parent) {
113
+ // This has the assumption that object key order won't change if the
114
+ // content did not change, which should normally be safe given
115
+ // the manner in which nodes and exportJSON are typically implemented.
116
+ return JSON.stringify(prevEditorState.read(() => prevNode.exportJSON())) === JSON.stringify(nextEditorState.read(() => nextNode.exportJSON()));
117
+ }
118
+ return false;
119
+ }
120
+ function createMergeActionGetter(editor, delayOrStore) {
121
+ let prevChangeTime = Date.now();
122
+ let prevChangeType = OTHER;
123
+ return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
124
+ const changeTime = Date.now();
125
+
126
+ // If applying changes from history stack there's no need
127
+ // to run history logic again, as history entries already calculated
128
+ if (tags.has(HISTORIC_TAG)) {
129
+ prevChangeType = OTHER;
130
+ prevChangeTime = changeTime;
131
+ return DISCARD_HISTORY_CANDIDATE;
132
+ }
133
+ const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
134
+ const mergeAction = (() => {
135
+ const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
136
+ const shouldPushHistory = tags.has(HISTORY_PUSH_TAG);
137
+ const shouldMergeHistory = !shouldPushHistory && isSameEditor && tags.has(HISTORY_MERGE_TAG);
138
+ if (shouldMergeHistory) {
139
+ return HISTORY_MERGE;
140
+ }
141
+ if (prevEditorState === null) {
142
+ return HISTORY_PUSH;
143
+ }
144
+ const selection = nextEditorState._selection;
145
+ const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
146
+ if (!hasDirtyNodes) {
147
+ if (selection !== null) {
148
+ return HISTORY_MERGE;
149
+ }
150
+ return DISCARD_HISTORY_CANDIDATE;
151
+ }
152
+ const delay = typeof delayOrStore === 'number' ? delayOrStore : delayOrStore.peek();
153
+ if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
154
+ return HISTORY_MERGE;
155
+ }
156
+
157
+ // A single node might have been marked as dirty, but not have changed
158
+ // due to some node transform reverting the change.
159
+ if (dirtyLeaves.size === 1) {
160
+ const dirtyLeafKey = Array.from(dirtyLeaves)[0];
161
+ if (isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)) {
162
+ return HISTORY_MERGE;
163
+ }
164
+ }
165
+ return HISTORY_PUSH;
166
+ })();
167
+ prevChangeTime = changeTime;
168
+ prevChangeType = changeType;
169
+ return mergeAction;
170
+ };
171
+ }
172
+ function redo(editor, historyState) {
173
+ const redoStack = historyState.redoStack;
174
+ const undoStack = historyState.undoStack;
175
+ if (redoStack.length !== 0) {
176
+ const current = historyState.current;
177
+ if (current !== null) {
178
+ undoStack.push(current);
179
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
180
+ }
181
+ const historyStateEntry = redoStack.pop();
182
+ if (redoStack.length === 0) {
183
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
184
+ }
185
+ historyState.current = historyStateEntry || null;
186
+ if (historyStateEntry) {
187
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
188
+ tag: HISTORIC_TAG
189
+ });
190
+ }
191
+ }
192
+ }
193
+ function undo(editor, historyState) {
194
+ const redoStack = historyState.redoStack;
195
+ const undoStack = historyState.undoStack;
196
+ const undoStackLength = undoStack.length;
197
+ if (undoStackLength !== 0) {
198
+ const current = historyState.current;
199
+ const historyStateEntry = undoStack.pop();
200
+ if (current !== null) {
201
+ redoStack.push(current);
202
+ editor.dispatchCommand(CAN_REDO_COMMAND, true);
203
+ }
204
+ if (undoStack.length === 0) {
205
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
206
+ }
207
+ historyState.current = historyStateEntry || null;
208
+ if (historyStateEntry) {
209
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
210
+ tag: HISTORIC_TAG
211
+ });
212
+ }
213
+ }
214
+ }
215
+ function clearHistory(historyState) {
216
+ historyState.undoStack = [];
217
+ historyState.redoStack = [];
218
+ historyState.current = null;
219
+ }
220
+
221
+ /**
222
+ * Registers necessary listeners to manage undo/redo history stack and related editor commands.
223
+ * It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
224
+ * @param editor - The lexical editor.
225
+ * @param historyState - The history state, containing the current state and the undo/redo stack.
226
+ * @param delay - The time (in milliseconds) the editor should delay generating a new history stack,
227
+ * instead of merging the current changes with the current stack.
228
+ * @returns The listeners cleanup callback function.
229
+ */
230
+ function registerHistory(editor, historyState, delay) {
231
+ const getMergeAction = createMergeActionGetter(editor, delay);
232
+ const applyChange = ({
233
+ editorState,
234
+ prevEditorState,
235
+ dirtyLeaves,
236
+ dirtyElements,
237
+ tags
238
+ }) => {
239
+ const current = historyState.current;
240
+ const redoStack = historyState.redoStack;
241
+ const undoStack = historyState.undoStack;
242
+ const currentEditorState = current === null ? null : current.editorState;
243
+ if (current !== null && editorState === currentEditorState) {
244
+ return;
245
+ }
246
+ const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
247
+ if (mergeAction === HISTORY_PUSH) {
248
+ if (redoStack.length !== 0) {
249
+ historyState.redoStack = [];
250
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
251
+ }
252
+ if (current !== null) {
253
+ undoStack.push({
254
+ ...current
255
+ });
256
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
257
+ }
258
+ } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
259
+ return;
260
+ }
261
+
262
+ // Else we merge
263
+ historyState.current = {
264
+ editor,
265
+ editorState
266
+ };
267
+ };
268
+ const unregister = mergeRegister(editor.registerCommand(UNDO_COMMAND, () => {
269
+ undo(editor, historyState);
270
+ return true;
271
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(REDO_COMMAND, () => {
272
+ redo(editor, historyState);
273
+ return true;
274
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(CLEAR_EDITOR_COMMAND, () => {
275
+ clearHistory(historyState);
276
+ return false;
277
+ }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(CLEAR_HISTORY_COMMAND, () => {
278
+ clearHistory(historyState);
279
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
280
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
281
+ return true;
282
+ }, COMMAND_PRIORITY_EDITOR), editor.registerUpdateListener(applyChange));
283
+ return unregister;
284
+ }
285
+
286
+ /**
287
+ * Creates an empty history state.
288
+ * @returns - The empty history state, as an object.
289
+ */
290
+ function createEmptyHistoryState() {
291
+ return {
292
+ current: null,
293
+ redoStack: [],
294
+ undoStack: []
295
+ };
296
+ }
297
+ /**
298
+ * Registers necessary listeners to manage undo/redo history stack and related
299
+ * editor commands, via the \@lexical/history module.
300
+ */
301
+
302
+ const HistoryExtension = defineExtension({
303
+ build: (editor, {
304
+ delay,
305
+ createInitialHistoryState,
306
+ disabled
307
+ }) => namedSignals({
308
+ delay,
309
+ disabled,
310
+ historyState: createInitialHistoryState(editor)
311
+ }),
312
+ config: safeCast({
313
+ createInitialHistoryState: createEmptyHistoryState,
314
+ delay: 300,
315
+ disabled: typeof window === 'undefined'
316
+ }),
317
+ name: '@ekz/lexical-history/History',
318
+ register: (editor, config, state) => {
319
+ const stores = state.getOutput();
320
+ return effect(() => stores.disabled.value ? undefined : registerHistory(editor, stores.historyState.value, stores.delay));
321
+ }
322
+ });
323
+ function getHistoryPeer(editor) {
324
+ return editor ? getPeerDependencyFromEditor(editor, HistoryExtension.name) : null;
325
+ }
326
+
327
+ /**
328
+ * Registers necessary listeners to manage undo/redo history stack and related
329
+ * editor commands, via the \@lexical/history module, only if the parent editor
330
+ * has a history plugin implementation.
331
+ */
332
+ const SharedHistoryExtension = defineExtension({
333
+ dependencies: [configExtension(HistoryExtension, {
334
+ createInitialHistoryState: () => {
335
+ throw new Error('SharedHistory did not inherit parent history');
336
+ },
337
+ disabled: true
338
+ })],
339
+ name: '@ekz/lexical-history/SharedHistory',
340
+ register(editor, _config, state) {
341
+ const {
342
+ output
343
+ } = state.getDependency(HistoryExtension);
344
+ const parentPeer = getHistoryPeer(editor._parentEditor);
345
+ if (!parentPeer) {
346
+ return () => {};
347
+ }
348
+ const parentOutput = parentPeer.output;
349
+ return effect(() => batch(() => {
350
+ output.delay.value = parentOutput.delay.value;
351
+ output.historyState.value = parentOutput.historyState.value;
352
+ // Note that toggling the parent history will force this to be changed
353
+ output.disabled.value = parentOutput.disabled.value;
354
+ }));
355
+ }
356
+ });
357
+
358
+ export { HistoryExtension, SharedHistoryExtension, createEmptyHistoryState, 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
+ */
8
+
9
+ 'use strict'
10
+ const EkzLexicalHistory = process.env.NODE_ENV !== 'production' ? require('./EkzLexicalHistory.dev.js') : require('./EkzLexicalHistory.prod.js');
11
+ module.exports = EkzLexicalHistory;
@@ -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
+ */
8
+
9
+ import * as modDev from './EkzLexicalHistory.dev.mjs';
10
+ import * as modProd from './EkzLexicalHistory.prod.mjs';
11
+ const mod = process.env.NODE_ENV !== 'production' ? modDev : modProd;
12
+ export const HistoryExtension = mod.HistoryExtension;
13
+ export const SharedHistoryExtension = mod.SharedHistoryExtension;
14
+ export const createEmptyHistoryState = mod.createEmptyHistoryState;
15
+ export const registerHistory = mod.registerHistory;
@@ -0,0 +1,13 @@
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
+ const mod = await (process.env.NODE_ENV !== 'production' ? import('./EkzLexicalHistory.dev.mjs') : import('./EkzLexicalHistory.prod.mjs'));
10
+ export const HistoryExtension = mod.HistoryExtension;
11
+ export const SharedHistoryExtension = mod.SharedHistoryExtension;
12
+ export const createEmptyHistoryState = mod.createEmptyHistoryState;
13
+ export const registerHistory = mod.registerHistory;
@@ -0,0 +1,9 @@
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
+ "use strict";var e=require("@ekz/lexical-extension"),t=require("@ekz/lexical-utils"),n=require("@ekz/lexical");function r(e,t,r,o,i){if(null===e||0===r.size&&0===o.size&&!i)return 0;const s=t._selection,a=e._selection;if(i)return 1;if(!(n.$isRangeSelection(s)&&n.$isRangeSelection(a)&&a.isCollapsed()&&s.isCollapsed()))return 0;const c=function(e,t,r){const o=e._nodeMap,i=[];for(const e of t){const t=o.get(e);void 0!==t&&i.push(t)}for(const[e,t]of r){if(!t)continue;const r=o.get(e);void 0===r||n.$isRootNode(r)||i.push(r)}return i}(t,r,o);if(0===c.length)return 0;if(c.length>1){const r=t._nodeMap,o=r.get(s.anchor.key),i=r.get(a.anchor.key);return o&&i&&!e._nodeMap.has(o.__key)&&n.$isTextNode(o)&&1===o.__text.length&&1===s.anchor.offset?2:0}const d=c[0],u=e._nodeMap.get(d.__key);if(!n.$isTextNode(u)||!n.$isTextNode(d)||u.__mode!==d.__mode)return 0;const l=u.__text,_=d.__text;if(l===_)return 0;const f=s.anchor,p=a.anchor;if(f.key!==p.key||"text"!==f.type)return 0;const h=f.offset,O=p.offset,S=_.length-l.length;return 1===S&&O===h-1?2:-1===S&&O===h+1?3:-1===S&&O===h?4:0}function o(e,t){let o=Date.now(),i=0;return(s,a,c,d,u,l)=>{const _=Date.now();if(l.has(n.HISTORIC_TAG))return i=0,o=_,2;const f=r(s,a,d,u,e.isComposing()),p=(()=>{const r=null===c||c.editor===e,p=l.has(n.HISTORY_PUSH_TAG);if(!p&&r&&l.has(n.HISTORY_MERGE_TAG))return 0;if(null===s)return 1;const h=a._selection;if(!(d.size>0||u.size>0))return null!==h?0:2;const O="number"==typeof t?t:t.peek();if(!1===p&&0!==f&&f===i&&_<o+O&&r)return 0;if(1===d.size){if(function(e,t,r){const o=t._nodeMap.get(e),i=r._nodeMap.get(e),s=t._selection,a=r._selection;return!(n.$isRangeSelection(s)&&n.$isRangeSelection(a)&&"element"===s.anchor.type&&"element"===s.focus.type&&"text"===a.anchor.type&&"text"===a.focus.type||!n.$isTextNode(o)||!n.$isTextNode(i)||o.__parent!==i.__parent)&&JSON.stringify(t.read(()=>o.exportJSON()))===JSON.stringify(r.read(()=>i.exportJSON()))}(Array.from(d)[0],s,a))return 0}return 1})();return o=_,i=f,p}}function i(e){e.undoStack=[],e.redoStack=[],e.current=null}function s(e,r,s){const a=o(e,s),c=t.mergeRegister(e.registerCommand(n.UNDO_COMMAND,()=>(function(e,t){const r=t.redoStack,o=t.undoStack;if(0!==o.length){const i=t.current,s=o.pop();null!==i&&(r.push(i),e.dispatchCommand(n.CAN_REDO_COMMAND,!0)),0===o.length&&e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),t.current=s||null,s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,r),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.REDO_COMMAND,()=>(function(e,t){const r=t.redoStack,o=t.undoStack;if(0!==r.length){const i=t.current;null!==i&&(o.push(i),e.dispatchCommand(n.CAN_UNDO_COMMAND,!0));const s=r.pop();0===r.length&&e.dispatchCommand(n.CAN_REDO_COMMAND,!1),t.current=s||null,s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,r),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_EDITOR_COMMAND,()=>(i(r),!1),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_HISTORY_COMMAND,()=>(i(r),e.dispatchCommand(n.CAN_REDO_COMMAND,!1),e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),!0),n.COMMAND_PRIORITY_EDITOR),e.registerUpdateListener(({editorState:t,prevEditorState:o,dirtyLeaves:i,dirtyElements:s,tags:c})=>{const d=r.current,u=r.redoStack,l=r.undoStack,_=null===d?null:d.editorState;if(null!==d&&t===_)return;const f=a(o,t,d,i,s,c);if(1===f)0!==u.length&&(r.redoStack=[],e.dispatchCommand(n.CAN_REDO_COMMAND,!1)),null!==d&&(l.push({...d}),e.dispatchCommand(n.CAN_UNDO_COMMAND,!0));else if(2===f)return;r.current={editor:e,editorState:t}}));return c}function a(){return{current:null,redoStack:[],undoStack:[]}}const c=n.defineExtension({build:(t,{delay:n,createInitialHistoryState:r,disabled:o})=>e.namedSignals({delay:n,disabled:o,historyState:r(t)}),config:n.safeCast({createInitialHistoryState:a,delay:300,disabled:"undefined"==typeof window}),name:"@ekz/lexical-history/History",register:(t,n,r)=>{const o=r.getOutput();return e.effect(()=>o.disabled.value?void 0:s(t,o.historyState.value,o.delay))}});const d=n.defineExtension({dependencies:[n.configExtension(c,{createInitialHistoryState:()=>{throw new Error("SharedHistory did not inherit parent history")},disabled:!0})],name:"@ekz/lexical-history/SharedHistory",register(t,n,r){const{output:o}=r.getDependency(c),i=function(t){return t?e.getPeerDependencyFromEditor(t,c.name):null}(t._parentEditor);if(!i)return()=>{};const s=i.output;return e.effect(()=>e.batch(()=>{o.delay.value=s.delay.value,o.historyState.value=s.historyState.value,o.disabled.value=s.disabled.value}))}});exports.HistoryExtension=c,exports.SharedHistoryExtension=d,exports.createEmptyHistoryState=a,exports.registerHistory=s;
@@ -0,0 +1,9 @@
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{namedSignals as t,effect as e,batch as n,getPeerDependencyFromEditor as r}from"@ekz/lexical-extension";import{mergeRegister as o}from"@ekz/lexical-utils";import{defineExtension as i,safeCast as a,configExtension as s,UNDO_COMMAND as c,COMMAND_PRIORITY_EDITOR as d,REDO_COMMAND as u,CLEAR_EDITOR_COMMAND as l,CLEAR_HISTORY_COMMAND as f,CAN_REDO_COMMAND as p,CAN_UNDO_COMMAND as h,HISTORIC_TAG as m,HISTORY_PUSH_TAG as y,HISTORY_MERGE_TAG as g,$isRangeSelection as S,$isTextNode as _,$isRootNode as k}from"@ekz/lexical";function x(t,e,n,r,o){if(null===t||0===n.size&&0===r.size&&!o)return 0;const i=e._selection,a=t._selection;if(o)return 1;if(!(S(i)&&S(a)&&a.isCollapsed()&&i.isCollapsed()))return 0;const s=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||k(n)||o.push(n)}return o}(e,n,r);if(0===s.length)return 0;if(s.length>1){const n=e._nodeMap,r=n.get(i.anchor.key),o=n.get(a.anchor.key);return r&&o&&!t._nodeMap.has(r.__key)&&_(r)&&1===r.__text.length&&1===i.anchor.offset?2:0}const c=s[0],d=t._nodeMap.get(c.__key);if(!_(d)||!_(c)||d.__mode!==c.__mode)return 0;const u=d.__text,l=c.__text;if(u===l)return 0;const f=i.anchor,p=a.anchor;if(f.key!==p.key||"text"!==f.type)return 0;const h=f.offset,m=p.offset,y=l.length-u.length;return 1===y&&m===h-1?2:-1===y&&m===h+1?3:-1===y&&m===h?4:0}function C(t,e){let n=Date.now(),r=0;return(o,i,a,s,c,d)=>{const u=Date.now();if(d.has(m))return r=0,n=u,2;const l=x(o,i,s,c,t.isComposing()),f=(()=>{const f=null===a||a.editor===t,p=d.has(y);if(!p&&f&&d.has(g))return 0;if(null===o)return 1;const h=i._selection;if(!(s.size>0||c.size>0))return null!==h?0:2;const m="number"==typeof e?e:e.peek();if(!1===p&&0!==l&&l===r&&u<n+m&&f)return 0;if(1===s.size){if(function(t,e,n){const r=e._nodeMap.get(t),o=n._nodeMap.get(t),i=e._selection,a=n._selection;return!(S(i)&&S(a)&&"element"===i.anchor.type&&"element"===i.focus.type&&"text"===a.anchor.type&&"text"===a.focus.type||!_(r)||!_(o)||r.__parent!==o.__parent)&&JSON.stringify(e.read(()=>r.exportJSON()))===JSON.stringify(n.read(()=>o.exportJSON()))}(Array.from(s)[0],o,i))return 0}return 1})();return n=u,r=l,f}}function v(t){t.undoStack=[],t.redoStack=[],t.current=null}function z(t,e,n){const r=C(t,n),i=o(t.registerCommand(c,()=>(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(p,!0)),0===r.length&&t.dispatchCommand(h,!1),e.current=i||null,i&&i.editor.setEditorState(i.editorState,{tag:m})}}(t,e),!0),d),t.registerCommand(u,()=>(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(h,!0));const i=n.pop();0===n.length&&t.dispatchCommand(p,!1),e.current=i||null,i&&i.editor.setEditorState(i.editorState,{tag:m})}}(t,e),!0),d),t.registerCommand(l,()=>(v(e),!1),d),t.registerCommand(f,()=>(v(e),t.dispatchCommand(p,!1),t.dispatchCommand(h,!1),!0),d),t.registerUpdateListener(({editorState:n,prevEditorState:o,dirtyLeaves:i,dirtyElements:a,tags:s})=>{const c=e.current,d=e.redoStack,u=e.undoStack,l=null===c?null:c.editorState;if(null!==c&&n===l)return;const f=r(o,n,c,i,a,s);if(1===f)0!==d.length&&(e.redoStack=[],t.dispatchCommand(p,!1)),null!==c&&(u.push({...c}),t.dispatchCommand(h,!0));else if(2===f)return;e.current={editor:t,editorState:n}}));return i}function b(){return{current:null,redoStack:[],undoStack:[]}}const w=i({build:(e,{delay:n,createInitialHistoryState:r,disabled:o})=>t({delay:n,disabled:o,historyState:r(e)}),config:a({createInitialHistoryState:b,delay:300,disabled:"undefined"==typeof window}),name:"@ekz/lexical-history/History",register:(t,n,r)=>{const o=r.getOutput();return e(()=>o.disabled.value?void 0:z(t,o.historyState.value,o.delay))}});const E=i({dependencies:[s(w,{createInitialHistoryState:()=>{throw new Error("SharedHistory did not inherit parent history")},disabled:!0})],name:"@ekz/lexical-history/SharedHistory",register(t,o,i){const{output:a}=i.getDependency(w),s=function(t){return t?r(t,w.name):null}(t._parentEditor);if(!s)return()=>{};const c=s.output;return e(()=>n(()=>{a.delay.value=c.delay.value,a.historyState.value=c.historyState.value,a.disabled.value=c.disabled.value}))}});export{w as HistoryExtension,E as SharedHistoryExtension,b as createEmptyHistoryState,z as registerHistory};
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.
@@ -0,0 +1,39 @@
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
+ * @flow strict
8
+ */
9
+ import type {LexicalExtension, ExtensionConfigBase, EditorState, BaseSelection, LexicalEditor} from '@ekz/lexical';
10
+ import type {NamedSignalsOutput} from '@ekz/lexical-extension';
11
+
12
+ export type HistoryStateEntry = {
13
+ editor: LexicalEditor,
14
+ editorState: EditorState,
15
+ undoSelection?: BaseSelection | null,
16
+ };
17
+ export type HistoryState = {
18
+ current: null | HistoryStateEntry,
19
+ redoStack: Array<HistoryStateEntry>,
20
+ undoStack: Array<HistoryStateEntry>,
21
+ };
22
+ declare export function registerHistory(
23
+ editor: LexicalEditor,
24
+ historyState: HistoryState,
25
+ delay: number,
26
+ ): () => void;
27
+ declare export function createEmptyHistoryState(): HistoryState;
28
+
29
+ export type HistoryConfig = {
30
+ delay: number;
31
+ createInitialHistoryState: (editor: LexicalEditor) => HistoryState;
32
+ disabled: boolean;
33
+ }
34
+ declare export var HistoryExtension: LexicalExtension<HistoryConfig, "@ekz/lexical-history/History", NamedSignalsOutput<{
35
+ delay: number;
36
+ disabled: boolean;
37
+ historyState: HistoryState;
38
+ }>, void>;
39
+ declare export var SharedHistoryExtension: LexicalExtension<ExtensionConfigBase, "@ekz/lexical-history/SharedHistory", void, void>;
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # `@lexical/history`
2
+
3
+ [![See API Documentation](https://lexical.dev/img/see-api-documentation.svg)](https://lexical.dev/docs/api/modules/lexical_history)
4
+
5
+ This package contains history helpers for Lexical.
6
+
7
+ ### Methods
8
+
9
+ #### `registerHistory`
10
+
11
+ Registers necessary listeners to manage undo/redo history stack and related editor commands. It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
12
+
13
+ ```js
14
+ function registerHistory(
15
+ editor: LexicalEditor,
16
+ externalHistoryState: HistoryState,
17
+ delay: number,
18
+ ): () => void
19
+ ```
20
+
21
+ ### Commands
22
+
23
+ History package handles `UNDO_COMMAND`, `REDO_COMMAND` and `CLEAR_HISTORY_COMMAND` commands. It also triggers `CAN_UNDO_COMMAND` and `CAN_REDO_COMMAND` commands when history state is changed. These commands could be used to work with history state:
24
+
25
+ ```jsx
26
+ import {UNDO_COMMAND, REDO_COMMAND} from '@ekz/lexical';
27
+
28
+ <Toolbar>
29
+ <Button onClick={() => editor.dispatchCommand(UNDO_COMMAND, undefined)}>Undo</Button>
30
+ <Button onClick={() => editor.dispatchCommand(REDO_COMMAND, undefined)}>Redo</Button>
31
+ </Toolbar>;
32
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,63 @@
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
+ import type { EditorState, LexicalEditor } from '@ekz/lexical';
9
+ import { ReadonlySignal } from '@ekz/lexical-extension';
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 | ReadonlySignal<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;
34
+ export interface HistoryConfig {
35
+ /**
36
+ * The time (in milliseconds) the editor should delay generating a new history stack,
37
+ * instead of merging the current changes with the current stack. The default is 300ms.
38
+ */
39
+ delay: number;
40
+ /**
41
+ * The initial history state, the default is {@link createEmptyHistoryState}.
42
+ */
43
+ createInitialHistoryState: (editor: LexicalEditor) => HistoryState;
44
+ /**
45
+ * Whether history is disabled or not
46
+ */
47
+ disabled: boolean;
48
+ }
49
+ /**
50
+ * Registers necessary listeners to manage undo/redo history stack and related
51
+ * editor commands, via the \@lexical/history module.
52
+ */
53
+ export declare const HistoryExtension: import("@ekz/lexical").LexicalExtension<HistoryConfig, "@ekz/lexical-history/History", import("@ekz/lexical-extension").NamedSignalsOutput<{
54
+ delay: number;
55
+ disabled: boolean;
56
+ historyState: HistoryState;
57
+ }>, unknown>;
58
+ /**
59
+ * Registers necessary listeners to manage undo/redo history stack and related
60
+ * editor commands, via the \@lexical/history module, only if the parent editor
61
+ * has a history plugin implementation.
62
+ */
63
+ export declare const SharedHistoryExtension: import("@ekz/lexical").LexicalExtension<import("@ekz/lexical").ExtensionConfigBase, "@ekz/lexical-history/SharedHistory", unknown, unknown>;
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ekz/lexical-history",
3
+ "description": "This package contains selection history helpers for Lexical.",
4
+ "keywords": [
5
+ "lexical",
6
+ "editor",
7
+ "rich-text",
8
+ "history"
9
+ ],
10
+ "license": "MIT",
11
+ "version": "0.40.0",
12
+ "main": "LexicalHistory.js",
13
+ "types": "index.d.ts",
14
+ "dependencies": {
15
+ "@ekz/lexical-extension": "0.40.0",
16
+ "@ekz/lexical-utils": "0.40.0",
17
+ "@ekz/lexical": "0.40.0"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/facebook/lexical.git",
22
+ "directory": "packages/lexical-history"
23
+ },
24
+ "module": "LexicalHistory.mjs",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./index.d.ts",
30
+ "development": "./LexicalHistory.dev.mjs",
31
+ "production": "./LexicalHistory.prod.mjs",
32
+ "node": "./LexicalHistory.node.mjs",
33
+ "default": "./LexicalHistory.mjs"
34
+ },
35
+ "require": {
36
+ "types": "./index.d.ts",
37
+ "development": "./LexicalHistory.dev.js",
38
+ "production": "./LexicalHistory.prod.js",
39
+ "default": "./LexicalHistory.js"
40
+ }
41
+ }
42
+ }
43
+ }