@lexical/history 0.1.17

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.
@@ -0,0 +1,31 @@
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 {
9
+ EditorState,
10
+ GridSelection,
11
+ LexicalEditor,
12
+ NodeSelection,
13
+ RangeSelection,
14
+ } from 'lexical';
15
+
16
+ export type HistoryStateEntry = {
17
+ editor: LexicalEditor;
18
+ editorState: EditorState;
19
+ undoSelection?: RangeSelection | NodeSelection | GridSelection | null;
20
+ };
21
+ export type HistoryState = {
22
+ current: null | HistoryStateEntry;
23
+ redoStack: Array<HistoryStateEntry>;
24
+ undoStack: Array<HistoryStateEntry>;
25
+ };
26
+ export function registerHistory(
27
+ editor: LexicalEditor,
28
+ historyState: HistoryState,
29
+ delay: number,
30
+ ): () => void;
31
+ export function createEmptyHistoryState(): HistoryState;
@@ -0,0 +1,315 @@
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
+ /**
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ *
18
+ *
19
+ */
20
+ const HISTORY_MERGE = 0;
21
+ const HISTORY_PUSH = 1;
22
+ const DISCARD_HISTORY_CANDIDATE = 2;
23
+ const OTHER = 0;
24
+ const COMPOSING_CHARACTER = 1;
25
+ const INSERT_CHARACTER_AFTER_SELECTION = 2;
26
+ const DELETE_CHARACTER_BEFORE_SELECTION = 3;
27
+ const DELETE_CHARACTER_AFTER_SELECTION = 4;
28
+ const EditorPriority = 0;
29
+
30
+ function getDirtyNodes(editorState, dirtyLeaves, dirtyElements) {
31
+ const nodeMap = editorState._nodeMap;
32
+ const nodes = [];
33
+
34
+ for (const dirtyLeafKey of dirtyLeaves) {
35
+ const dirtyLeaf = nodeMap.get(dirtyLeafKey);
36
+
37
+ if (dirtyLeaf !== undefined) {
38
+ nodes.push(dirtyLeaf);
39
+ }
40
+ }
41
+
42
+ for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
43
+ if (!intentionallyMarkedAsDirty) {
44
+ continue;
45
+ }
46
+
47
+ const dirtyElement = nodeMap.get(dirtyElementKey);
48
+
49
+ if (dirtyElement !== undefined && !lexical.$isRootNode(dirtyElement)) {
50
+ nodes.push(dirtyElement);
51
+ }
52
+ }
53
+
54
+ return nodes;
55
+ }
56
+
57
+ function getChangeType(prevEditorState, nextEditorState, dirtyLeavesSet, dirtyElementsSet, isComposing) {
58
+ if (prevEditorState === null || dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0) {
59
+ return OTHER;
60
+ }
61
+
62
+ const nextSelection = nextEditorState._selection;
63
+ const prevSelection = prevEditorState._selection;
64
+
65
+ if (isComposing) {
66
+ return COMPOSING_CHARACTER;
67
+ }
68
+
69
+ if (!lexical.$isRangeSelection(nextSelection) || !lexical.$isRangeSelection(prevSelection) || !prevSelection.isCollapsed() || !nextSelection.isCollapsed()) {
70
+ return OTHER;
71
+ }
72
+
73
+ const dirtyNodes = getDirtyNodes(nextEditorState, dirtyLeavesSet, dirtyElementsSet);
74
+
75
+ if (dirtyNodes.length === 0) {
76
+ return OTHER;
77
+ } // Catching the case when inserting new text node into an element (e.g. first char in paragraph/list),
78
+ // or after existing node.
79
+
80
+
81
+ if (dirtyNodes.length > 1) {
82
+ const nextNodeMap = nextEditorState._nodeMap;
83
+ const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
84
+ const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
85
+
86
+ if (nextAnchorNode && prevAnchorNode && !prevEditorState._nodeMap.has(nextAnchorNode.__key) && lexical.$isTextNode(nextAnchorNode) && nextAnchorNode.__text.length === 1 && nextSelection.anchor.offset === 1) {
87
+ return INSERT_CHARACTER_AFTER_SELECTION;
88
+ }
89
+
90
+ return OTHER;
91
+ }
92
+
93
+ const nextDirtyNode = dirtyNodes[0];
94
+
95
+ const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
96
+
97
+ if (!lexical.$isTextNode(prevDirtyNode) || !lexical.$isTextNode(nextDirtyNode) || prevDirtyNode.__mode !== nextDirtyNode.__mode) {
98
+ return OTHER;
99
+ }
100
+
101
+ const prevText = prevDirtyNode.__text;
102
+ const nextText = nextDirtyNode.__text;
103
+
104
+ if (prevText === nextText) {
105
+ return OTHER;
106
+ }
107
+
108
+ const nextAnchor = nextSelection.anchor;
109
+ const prevAnchor = prevSelection.anchor;
110
+
111
+ if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
112
+ return OTHER;
113
+ }
114
+
115
+ const nextAnchorOffset = nextAnchor.offset;
116
+ const prevAnchorOffset = prevAnchor.offset;
117
+ const textDiff = nextText.length - prevText.length;
118
+
119
+ if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
120
+ return INSERT_CHARACTER_AFTER_SELECTION;
121
+ }
122
+
123
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
124
+ return DELETE_CHARACTER_BEFORE_SELECTION;
125
+ }
126
+
127
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
128
+ return DELETE_CHARACTER_AFTER_SELECTION;
129
+ }
130
+
131
+ return OTHER;
132
+ }
133
+
134
+ function createMergeActionGetter(editor, delay) {
135
+ let prevChangeTime = Date.now();
136
+ let prevChangeType = OTHER;
137
+ return (prevEditorState, nextEditorState, currentHistoryEntry, dirtyLeaves, dirtyElements, tags) => {
138
+ const changeTime = Date.now(); // If applying changes from history stack there's no need
139
+ // to run history logic again, as history entries already calculated
140
+
141
+ if (tags.has('historic')) {
142
+ prevChangeType = OTHER;
143
+ prevChangeTime = changeTime;
144
+ return DISCARD_HISTORY_CANDIDATE;
145
+ }
146
+
147
+ const changeType = getChangeType(prevEditorState, nextEditorState, dirtyLeaves, dirtyElements, editor.isComposing());
148
+
149
+ const mergeAction = (() => {
150
+ const shouldPushHistory = tags.has('history-push');
151
+ const shouldMergeHistory = !shouldPushHistory && tags.has('history-merge');
152
+
153
+ if (shouldMergeHistory) {
154
+ return HISTORY_MERGE;
155
+ }
156
+
157
+ if (prevEditorState === null) {
158
+ return HISTORY_PUSH;
159
+ }
160
+
161
+ const selection = nextEditorState._selection;
162
+ const prevSelection = prevEditorState._selection;
163
+ const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
164
+
165
+ if (!hasDirtyNodes) {
166
+ if (prevSelection === null && selection !== null) {
167
+ return HISTORY_MERGE;
168
+ }
169
+
170
+ return DISCARD_HISTORY_CANDIDATE;
171
+ }
172
+
173
+ const isSameEditor = currentHistoryEntry === null || currentHistoryEntry.editor === editor;
174
+
175
+ if (shouldPushHistory === false && changeType !== OTHER && changeType === prevChangeType && changeTime < prevChangeTime + delay && isSameEditor) {
176
+ return HISTORY_MERGE;
177
+ }
178
+
179
+ return HISTORY_PUSH;
180
+ })();
181
+
182
+ prevChangeTime = changeTime;
183
+ prevChangeType = changeType;
184
+ return mergeAction;
185
+ };
186
+ }
187
+
188
+ function redo(editor, historyState) {
189
+ const redoStack = historyState.redoStack;
190
+ const undoStack = historyState.undoStack;
191
+
192
+ if (redoStack.length !== 0) {
193
+ const current = historyState.current;
194
+
195
+ if (current !== null) {
196
+ undoStack.push(current);
197
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
198
+ }
199
+
200
+ const historyStateEntry = redoStack.pop();
201
+
202
+ if (redoStack.length === 0) {
203
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, false);
204
+ }
205
+
206
+ historyState.current = historyStateEntry;
207
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
208
+ tag: 'historic'
209
+ });
210
+ }
211
+ }
212
+
213
+ function undo(editor, historyState) {
214
+ const redoStack = historyState.redoStack;
215
+ const undoStack = historyState.undoStack;
216
+ const undoStackLength = undoStack.length;
217
+
218
+ if (undoStackLength !== 0) {
219
+ const current = historyState.current;
220
+ const historyStateEntry = undoStack.pop();
221
+
222
+ if (current !== null) {
223
+ redoStack.push(current);
224
+ editor.dispatchCommand(lexical.CAN_REDO_COMMAND, true);
225
+ }
226
+
227
+ if (undoStack.length === 0) {
228
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, false);
229
+ }
230
+
231
+ historyState.current = historyStateEntry;
232
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState.clone(historyStateEntry.undoSelection), {
233
+ tag: 'historic'
234
+ });
235
+ }
236
+ }
237
+
238
+ function clearHistory(historyState) {
239
+ historyState.undoStack = [];
240
+ historyState.redoStack = [];
241
+ historyState.current = null;
242
+ }
243
+
244
+ function registerHistory(editor, historyState, delay) {
245
+ const getMergeAction = createMergeActionGetter(editor, delay);
246
+
247
+ const applyChange = ({
248
+ editorState,
249
+ prevEditorState,
250
+ dirtyLeaves,
251
+ dirtyElements,
252
+ tags
253
+ }) => {
254
+ const current = historyState.current;
255
+ const redoStack = historyState.redoStack;
256
+ const undoStack = historyState.undoStack;
257
+ const currentEditorState = current === null ? null : current.editorState;
258
+
259
+ if (current !== null && editorState === currentEditorState) {
260
+ return;
261
+ }
262
+
263
+ const mergeAction = getMergeAction(prevEditorState, editorState, current, dirtyLeaves, dirtyElements, tags);
264
+
265
+ if (mergeAction === HISTORY_PUSH) {
266
+ if (redoStack.length !== 0) {
267
+ historyState.redoStack = [];
268
+ }
269
+
270
+ if (current !== null) {
271
+ undoStack.push({ ...current,
272
+ undoSelection: prevEditorState.read(lexical.$getSelection)
273
+ });
274
+ editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
275
+ }
276
+ } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
277
+ return;
278
+ } // Else we merge
279
+
280
+
281
+ historyState.current = {
282
+ editor,
283
+ editorState
284
+ };
285
+ };
286
+
287
+ const unregisterCommandListener = utils.mergeRegister(editor.registerCommand(lexical.UNDO_COMMAND, () => {
288
+ undo(editor, historyState);
289
+ return true;
290
+ }, EditorPriority), editor.registerCommand(lexical.REDO_COMMAND, () => {
291
+ redo(editor, historyState);
292
+ return true;
293
+ }, EditorPriority), editor.registerCommand(lexical.CLEAR_EDITOR_COMMAND, () => {
294
+ clearHistory(historyState);
295
+ return false;
296
+ }, EditorPriority), editor.registerCommand(lexical.CLEAR_HISTORY_COMMAND, () => {
297
+ clearHistory(historyState);
298
+ return true;
299
+ }, EditorPriority), editor.registerUpdateListener(applyChange));
300
+ const unregisterUpdateListener = editor.registerUpdateListener(applyChange);
301
+ return () => {
302
+ unregisterCommandListener();
303
+ unregisterUpdateListener();
304
+ };
305
+ }
306
+ function createEmptyHistoryState() {
307
+ return {
308
+ current: null,
309
+ redoStack: [],
310
+ undoStack: []
311
+ };
312
+ }
313
+
314
+ exports.createEmptyHistoryState = createEmptyHistoryState;
315
+ exports.registerHistory = 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
+ '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,32 @@
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 {
10
+ EditorState,
11
+ GridSelection,
12
+ LexicalEditor,
13
+ NodeSelection,
14
+ RangeSelection,
15
+ } from 'lexical';
16
+
17
+ export type HistoryStateEntry = {
18
+ editor: LexicalEditor,
19
+ editorState: EditorState,
20
+ undoSelection?: RangeSelection | NodeSelection | GridSelection | null,
21
+ };
22
+ export type HistoryState = {
23
+ current: null | HistoryStateEntry,
24
+ redoStack: Array<HistoryStateEntry>,
25
+ undoStack: Array<HistoryStateEntry>,
26
+ };
27
+ declare export function registerHistory(
28
+ editor: LexicalEditor,
29
+ historyState: HistoryState,
30
+ delay: number,
31
+ ): () => void;
32
+ declare export function createEmptyHistoryState(): HistoryState;
@@ -0,0 +1,14 @@
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
+ var g=require("@lexical/utils"),u=require("lexical");
8
+ function v(b,a,k,h,m){if(null===b||0===k.size&&0===h.size)return 0;var e=a._selection,c=b._selection;if(m)return 1;if(!(u.$isRangeSelection(e)&&u.$isRangeSelection(c)&&c.isCollapsed()&&e.isCollapsed()))return 0;m=a._nodeMap;const d=[];for(const f of k)k=m.get(f),void 0!==k&&d.push(k);for(const [f,l]of h)l&&(h=m.get(f),void 0===h||u.$isRootNode(h)||d.push(h));if(0===d.length)return 0;if(1<d.length)return h=a._nodeMap,a=h.get(e.anchor.key),c=h.get(c.anchor.key),a&&c&&!b._nodeMap.has(a.__key)&&u.$isTextNode(a)&&
9
+ 1===a.__text.length&&1===e.anchor.offset?2:0;a=d[0];b=b._nodeMap.get(a.__key);if(!u.$isTextNode(b)||!u.$isTextNode(a)||b.__mode!==a.__mode)return 0;b=b.__text;a=a.__text;if(b===a)return 0;e=e.anchor;c=c.anchor;if(e.key!==c.key||"text"!==e.type)return 0;e=e.offset;c=c.offset;b=a.length-b.length;return 1===b&&c===e-1?2:-1===b&&c===e+1?3:-1===b&&c===e?4:0}
10
+ function w(b,a){let k=Date.now(),h=0;return(m,e,c,d,f,l)=>{const p=Date.now();if(l.has("historic"))return h=0,k=p,2;const n=v(m,e,d,f,b.isComposing()),t=(()=>{const r=l.has("history-push");if(!r&&l.has("history-merge"))return 0;if(null===m)return 1;var q=e._selection;const x=m._selection;if(!(0<d.size||0<f.size))return null===x&&null!==q?0:2;q=null===c||c.editor===b;return!1===r&&0!==n&&n===h&&p<k+a&&q?0:1})();k=p;h=n;return t}}
11
+ exports.createEmptyHistoryState=function(){return{current:null,redoStack:[],undoStack:[]}};
12
+ exports.registerHistory=function(b,a,k){const h=w(b,k);k=({editorState:c,prevEditorState:d,dirtyLeaves:f,dirtyElements:l,tags:p})=>{const n=a.current,t=a.redoStack,r=a.undoStack,q=null===n?null:n.editorState;if(null===n||c!==q){f=h(d,c,n,f,l,p);if(1===f)0!==t.length&&(a.redoStack=[]),null!==n&&(r.push({...n,undoSelection:d.read(u.$getSelection)}),b.dispatchCommand(u.CAN_UNDO_COMMAND,!0));else if(2===f)return;a.current={editor:b,editorState:c}}};const m=g.mergeRegister(b.registerCommand(u.UNDO_COMMAND,
13
+ ()=>{const c=a.redoStack,d=a.undoStack;if(0!==d.length){const f=a.current,l=d.pop();null!==f&&(c.push(f),b.dispatchCommand(u.CAN_REDO_COMMAND,!0));0===d.length&&b.dispatchCommand(u.CAN_UNDO_COMMAND,!1);a.current=l;l.editor.setEditorState(l.editorState.clone(l.undoSelection),{tag:"historic"})}return!0},0),b.registerCommand(u.REDO_COMMAND,()=>{const c=a.redoStack;var d=a.undoStack;if(0!==c.length){const f=a.current;null!==f&&(d.push(f),b.dispatchCommand(u.CAN_UNDO_COMMAND,!0));d=c.pop();0===c.length&&
14
+ b.dispatchCommand(u.CAN_REDO_COMMAND,!1);a.current=d;d.editor.setEditorState(d.editorState,{tag:"historic"})}return!0},0),b.registerCommand(u.CLEAR_EDITOR_COMMAND,()=>{a.undoStack=[];a.redoStack=[];a.current=null;return!1},0),b.registerCommand(u.CLEAR_HISTORY_COMMAND,()=>{a.undoStack=[];a.redoStack=[];a.current=null;return!0},0),b.registerUpdateListener(k)),e=b.registerUpdateListener(k);return()=>{m();e()}};
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # `@lexical/history`
2
+
3
+ This package contains history helpers for Lexical.
4
+
5
+ ### Methods
6
+
7
+ #### `registerHistory`
8
+
9
+ 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.
10
+
11
+ ```js
12
+ function registerHistory(
13
+ editor: LexicalEditor,
14
+ externalHistoryState: HistoryState,
15
+ delay: number,
16
+ ): () => void
17
+ ```
18
+
19
+ ### Commands
20
+
21
+ History package handles `undo`, `redo` and `clearHistory` commands. It also triggers `canUndo` and `canRedo` commands when history state is changed. These commands could be used to work with history state:
22
+
23
+ ```jsx
24
+ <Toolbar>
25
+ <Button onClick={() => editor.dispatchCommand('undo')}>Undo</Button>
26
+ <Button onClick={() => editor.dispatchCommand('redo')}>Redo</Button>
27
+ </Toolbar>
28
+ ```
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@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.1.17",
12
+ "main": "LexicalHistory.js",
13
+ "peerDependencies": {
14
+ "lexical": "0.1.17"
15
+ },
16
+ "dependencies": {
17
+ "@lexical/utils": "0.1.17"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/facebook/lexical",
22
+ "directory": "packages/lexical-history"
23
+ }
24
+ }