@lexical/history 0.44.1-nightly.20260519.0 → 0.45.1-dev.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.
@@ -259,10 +259,17 @@ function clearHistory(historyState, onChange) {
259
259
  * NOT invoked when a candidate update is discarded without changing the
260
260
  * stacks. Useful for keeping derived values (e.g. signals) in sync with the
261
261
  * current `HistoryState`.
262
+ * @param maxDepth - The maximum number of entries the undo stack may hold.
263
+ * When the cap is exceeded a new history event has been pushed the oldest
264
+ * entries are dropped from the front of the stack until the stack length is
265
+ * `maxDepth`. Pass `null` (the default) to keep the stack unbounded — the
266
+ * historical behavior. May be a plain number or a `ReadonlySignal<number | null>`
267
+ * for reactive reconfiguration.
262
268
  * @returns The listeners cleanup callback function.
263
269
  */
264
- function registerHistory(editor, historyState, delay, dateNow = Date.now, onHistoryStateChange) {
270
+ function registerHistory(editor, historyState, delay, dateNow = Date.now, onHistoryStateChange, maxDepth = null) {
265
271
  const getMergeAction = createMergeActionGetter(editor, delay, dateNow);
272
+ const readMaxDepth = () => typeof maxDepth === 'number' || maxDepth === null ? maxDepth : maxDepth.peek();
266
273
  const notifyChange = () => {
267
274
  if (onHistoryStateChange) {
268
275
  onHistoryStateChange(historyState);
@@ -292,6 +299,14 @@ function registerHistory(editor, historyState, delay, dateNow = Date.now, onHist
292
299
  undoStack.push({
293
300
  ...current
294
301
  });
302
+ const cap = readMaxDepth();
303
+ if (cap !== null && undoStack.length > cap) {
304
+ // FIFO-evict the oldest entries so the stack stays at `cap`.
305
+ // Editing the array in place keeps the same `historyState.undoStack`
306
+ // reference that callers (e.g. SharedHistoryExtension) may hold on
307
+ // to.
308
+ undoStack.splice(0, undoStack.length - cap);
309
+ }
295
310
  editor.dispatchCommand(lexical.CAN_UNDO_COMMAND, true);
296
311
  }
297
312
  } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
@@ -359,6 +374,7 @@ const HistoryExtension = lexical.defineExtension({
359
374
  delay,
360
375
  createInitialHistoryState,
361
376
  disabled,
377
+ maxDepth,
362
378
  now
363
379
  }, state) => {
364
380
  // The init phase already created writable Signal<boolean> instances for
@@ -371,6 +387,7 @@ const HistoryExtension = lexical.defineExtension({
371
387
  delay,
372
388
  disabled,
373
389
  historyState: createInitialHistoryState(editor),
390
+ maxDepth,
374
391
  now
375
392
  }),
376
393
  ...state.getInitResult()
@@ -380,6 +397,7 @@ const HistoryExtension = lexical.defineExtension({
380
397
  createInitialHistoryState: createEmptyHistoryState,
381
398
  delay: 300,
382
399
  disabled: typeof window === 'undefined',
400
+ maxDepth: null,
383
401
  now: Date.now
384
402
  }),
385
403
  init: () => ({
@@ -406,7 +424,7 @@ const HistoryExtension = lexical.defineExtension({
406
424
  syncFromHistoryState(null);
407
425
  return undefined;
408
426
  }
409
- return registerHistory(editor, stores.historyState.value, stores.delay, () => stores.now.peek()(), syncFromHistoryState);
427
+ return registerHistory(editor, stores.historyState.value, stores.delay, () => stores.now.peek()(), syncFromHistoryState, stores.maxDepth);
410
428
  });
411
429
  }
412
430
  });
@@ -257,10 +257,17 @@ function clearHistory(historyState, onChange) {
257
257
  * NOT invoked when a candidate update is discarded without changing the
258
258
  * stacks. Useful for keeping derived values (e.g. signals) in sync with the
259
259
  * current `HistoryState`.
260
+ * @param maxDepth - The maximum number of entries the undo stack may hold.
261
+ * When the cap is exceeded a new history event has been pushed the oldest
262
+ * entries are dropped from the front of the stack until the stack length is
263
+ * `maxDepth`. Pass `null` (the default) to keep the stack unbounded — the
264
+ * historical behavior. May be a plain number or a `ReadonlySignal<number | null>`
265
+ * for reactive reconfiguration.
260
266
  * @returns The listeners cleanup callback function.
261
267
  */
262
- function registerHistory(editor, historyState, delay, dateNow = Date.now, onHistoryStateChange) {
268
+ function registerHistory(editor, historyState, delay, dateNow = Date.now, onHistoryStateChange, maxDepth = null) {
263
269
  const getMergeAction = createMergeActionGetter(editor, delay, dateNow);
270
+ const readMaxDepth = () => typeof maxDepth === 'number' || maxDepth === null ? maxDepth : maxDepth.peek();
264
271
  const notifyChange = () => {
265
272
  if (onHistoryStateChange) {
266
273
  onHistoryStateChange(historyState);
@@ -290,6 +297,14 @@ function registerHistory(editor, historyState, delay, dateNow = Date.now, onHist
290
297
  undoStack.push({
291
298
  ...current
292
299
  });
300
+ const cap = readMaxDepth();
301
+ if (cap !== null && undoStack.length > cap) {
302
+ // FIFO-evict the oldest entries so the stack stays at `cap`.
303
+ // Editing the array in place keeps the same `historyState.undoStack`
304
+ // reference that callers (e.g. SharedHistoryExtension) may hold on
305
+ // to.
306
+ undoStack.splice(0, undoStack.length - cap);
307
+ }
293
308
  editor.dispatchCommand(CAN_UNDO_COMMAND, true);
294
309
  }
295
310
  } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
@@ -357,6 +372,7 @@ const HistoryExtension = defineExtension({
357
372
  delay,
358
373
  createInitialHistoryState,
359
374
  disabled,
375
+ maxDepth,
360
376
  now
361
377
  }, state) => {
362
378
  // The init phase already created writable Signal<boolean> instances for
@@ -369,6 +385,7 @@ const HistoryExtension = defineExtension({
369
385
  delay,
370
386
  disabled,
371
387
  historyState: createInitialHistoryState(editor),
388
+ maxDepth,
372
389
  now
373
390
  }),
374
391
  ...state.getInitResult()
@@ -378,6 +395,7 @@ const HistoryExtension = defineExtension({
378
395
  createInitialHistoryState: createEmptyHistoryState,
379
396
  delay: 300,
380
397
  disabled: typeof window === 'undefined',
398
+ maxDepth: null,
381
399
  now: Date.now
382
400
  }),
383
401
  init: () => ({
@@ -404,7 +422,7 @@ const HistoryExtension = defineExtension({
404
422
  syncFromHistoryState(null);
405
423
  return undefined;
406
424
  }
407
- return registerHistory(editor, stores.historyState.value, stores.delay, () => stores.now.peek()(), syncFromHistoryState);
425
+ return registerHistory(editor, stores.historyState.value, stores.delay, () => stores.now.peek()(), syncFromHistoryState, stores.maxDepth);
408
426
  });
409
427
  }
410
428
  });
@@ -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("@lexical/extension"),t=require("@lexical/utils"),n=require("lexical");function o(e,t,o,r,i){if(null===e||0===o.size&&0===r.size&&!i)return 0;const a=t._selection,s=e._selection;if(i)return 1;if(!(n.$isRangeSelection(a)&&n.$isRangeSelection(s)&&s.isCollapsed()&&a.isCollapsed()))return 0;const l=function(e,t,o){const r=e._nodeMap,i=[];for(const e of t){const t=r.get(e);void 0!==t&&i.push(t)}for(const[e,t]of o){if(!t)continue;const o=r.get(e);void 0===o||n.$isRootNode(o)||i.push(o)}return i}(t,o,r);if(0===l.length)return 0;if(l.length>1){const o=t._nodeMap,r=o.get(a.anchor.key),i=o.get(s.anchor.key);return r&&i&&!e._nodeMap.has(r.__key)&&n.$isTextNode(r)&&1===r.__text.length&&1===a.anchor.offset?2:0}const d=l[0],u=e._nodeMap.get(d.__key);if(!n.$isTextNode(u)||!n.$isTextNode(d)||u.__mode!==d.__mode)return 0;const c=u.__text,_=d.__text;if(c===_)return 0;const f=a.anchor,p=s.anchor;if(f.key!==p.key||"text"!==f.type)return 0;const g=f.offset,h=p.offset,O=_.length-c.length;return 1===O&&h===g-1?2:-1===O&&h===g+1?3:-1===O&&h===g?4:0}function r(e,t,r){let i=r(),a=0,s=i,l=0,d=null;return(u,c,_,f,p,g)=>{const h=r();if(g.has(n.COMPOSITION_START_TAG)&&(s=i,l=a,d=u),g.has(n.HISTORIC_TAG))return a=0,i=h,2;g.has(n.COMPOSITION_END_TAG)&&d&&(i=s,a=l,u=d);const O=o(u,c,f,p,e.isComposing()),S=(()=>{const o=null===_||_.editor===e,r=g.has(n.HISTORY_PUSH_TAG);if(!r&&o&&g.has(n.HISTORY_MERGE_TAG))return 0;if(1===O)return 2;if(null===u)return 1;const s=c._selection;if(!(f.size>0||p.size>0))return null!==s?0:2;const l="number"==typeof t?t:t.peek();if(!1===r&&0!==O&&O===a&&h<i+l&&o)return 0;if(1===f.size){if(function(e,t,o){const r=t._nodeMap.get(e),i=o._nodeMap.get(e),a=t._selection,s=o._selection;return!(n.$isRangeSelection(a)&&n.$isRangeSelection(s)&&"element"===a.anchor.type&&"element"===a.focus.type&&"text"===s.anchor.type&&"text"===s.focus.type||!n.$isTextNode(r)||!n.$isTextNode(i)||r.__parent!==i.__parent)&&JSON.stringify(t.read(()=>r.exportJSON()))===JSON.stringify(o.read(()=>i.exportJSON()))}(Array.from(f)[0],u,c))return 0}return 1})();return i=h,a=O,S}}function i(e,t){e.undoStack=[],e.redoStack=[],e.current=null,t&&t(e)}function a(e,o,a,s=Date.now,l,d=null){const u=r(e,a,s),c=()=>{l&&l(o)};return c(),t.mergeRegister(e.registerCommand(n.UNDO_COMMAND,()=>(function(e,t,o){const r=t.redoStack,i=t.undoStack;if(0!==i.length){const a=t.current,s=i.pop();null!==a&&(r.push(a),e.dispatchCommand(n.CAN_REDO_COMMAND,!0)),0===i.length&&e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),t.current=s||null,o&&o(t),s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,o,l),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.REDO_COMMAND,()=>(function(e,t,o){const r=t.redoStack,i=t.undoStack;if(0!==r.length){const a=t.current;null!==a&&(i.push(a),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,o&&o(t),s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,o,l),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_EDITOR_COMMAND,()=>(i(o,l),!1),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_HISTORY_COMMAND,()=>(i(o,l),e.dispatchCommand(n.CAN_REDO_COMMAND,!1),e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),!0),n.COMMAND_PRIORITY_EDITOR),e.registerUpdateListener(({editorState:t,prevEditorState:r,dirtyLeaves:i,dirtyElements:a,tags:s})=>{const l=o.current,_=o.redoStack,f=o.undoStack,p=null===l?null:l.editorState;if(null!==l&&t===p)return;const g=u(r,t,l,i,a,s);if(1===g){if(0!==_.length&&(o.redoStack=[],e.dispatchCommand(n.CAN_REDO_COMMAND,!1)),null!==l){f.push({...l});const t="number"==typeof d||null===d?d:d.peek();null!==t&&f.length>t&&f.splice(0,f.length-t),e.dispatchCommand(n.CAN_UNDO_COMMAND,!0)}}else if(2===g)return;o.current={editor:e,editorState:t},c()}))}function s(){return{current:null,redoStack:[],undoStack:[]}}const l=n.defineExtension({build:(t,{delay:n,createInitialHistoryState:o,disabled:r,maxDepth:i,now:a},s)=>({...e.namedSignals({delay:n,disabled:r,historyState:o(t),maxDepth:i,now:a}),...s.getInitResult()}),config:n.safeCast({createInitialHistoryState:s,delay:300,disabled:"undefined"==typeof window,maxDepth:null,now:Date.now}),init:()=>({canRedo:e.signal(!1),canUndo:e.signal(!1)}),name:"@lexical/history/History",register:(t,n,o)=>{const{canUndo:r,canRedo:i}=o.getInitResult(),s=o.getOutput(),l=t=>e.batch(()=>{r.value=null!=t&&t.undoStack.length>0,i.value=null!=t&&t.redoStack.length>0});return e.effect(()=>{if(!s.disabled.value)return a(t,s.historyState.value,s.delay,()=>s.now.peek()(),l,s.maxDepth);l(null)})}});const d=n.defineExtension({build:(t,{disabled:n,parentEditor:o})=>e.namedSignals({disabled:n,parentEditor:o||t._parentEditor}),config:n.safeCast({disabled:!1,parentEditor:null}),dependencies:[n.configExtension(l,{disabled:!0})],name:"@lexical/history/SharedHistory",register:(t,n,o)=>e.effect(()=>{const{disabled:t,parentEditor:n}=o.getOutput();if(!t.value){const{output:t}=o.getDependency(l),r=function(t){return t?e.getPeerDependencyFromEditor(t,l.name):null}(n.value);if(!r)return;const i=r.output;e.batch(()=>{t.delay.value=i.delay.value,t.historyState.value=i.historyState.value,t.now.value=i.now.value,t.disabled.value=i.disabled.value})}})});exports.HistoryExtension=l,exports.SharedHistoryExtension=d,exports.createEmptyHistoryState=s,exports.registerHistory=a;
@@ -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{effect as t,signal as e,namedSignals as n,batch as o,getPeerDependencyFromEditor as r}from"@lexical/extension";import{mergeRegister as i}from"@lexical/utils";import{defineExtension as a,safeCast as l,configExtension as s,UNDO_COMMAND as u,COMMAND_PRIORITY_EDITOR as d,REDO_COMMAND as c,CLEAR_EDITOR_COMMAND as p,CLEAR_HISTORY_COMMAND as f,CAN_REDO_COMMAND as h,CAN_UNDO_COMMAND as m,COMPOSITION_START_TAG as g,HISTORIC_TAG as y,COMPOSITION_END_TAG as S,HISTORY_PUSH_TAG as _,HISTORY_MERGE_TAG as k,$isRangeSelection as x,$isTextNode as v,$isRootNode as b}from"lexical";function C(t,e,n,o,r){if(null===t||0===n.size&&0===o.size&&!r)return 0;const i=e._selection,a=t._selection;if(r)return 1;if(!(x(i)&&x(a)&&a.isCollapsed()&&i.isCollapsed()))return 0;const l=function(t,e,n){const o=t._nodeMap,r=[];for(const t of e){const e=o.get(t);void 0!==e&&r.push(e)}for(const[t,e]of n){if(!e)continue;const n=o.get(t);void 0===n||b(n)||r.push(n)}return r}(e,n,o);if(0===l.length)return 0;if(l.length>1){const n=e._nodeMap,o=n.get(i.anchor.key),r=n.get(a.anchor.key);return o&&r&&!t._nodeMap.has(o.__key)&&v(o)&&1===o.__text.length&&1===i.anchor.offset?2:0}const s=l[0],u=t._nodeMap.get(s.__key);if(!v(u)||!v(s)||u.__mode!==s.__mode)return 0;const d=u.__text,c=s.__text;if(d===c)return 0;const p=i.anchor,f=a.anchor;if(p.key!==f.key||"text"!==p.type)return 0;const h=p.offset,m=f.offset,g=c.length-d.length;return 1===g&&m===h-1?2:-1===g&&m===h+1?3:-1===g&&m===h?4:0}function w(t,e,n){let o=n(),r=0,i=o,a=0,l=null;return(s,u,d,c,p,f)=>{const h=n();if(f.has(g)&&(i=o,a=r,l=s),f.has(y))return r=0,o=h,2;f.has(S)&&l&&(o=i,r=a,s=l);const m=C(s,u,c,p,t.isComposing()),b=(()=>{const n=null===d||d.editor===t,i=f.has(_);if(!i&&n&&f.has(k))return 0;if(1===m)return 2;if(null===s)return 1;const a=u._selection;if(!(c.size>0||p.size>0))return null!==a?0:2;const l="number"==typeof e?e:e.peek();if(!1===i&&0!==m&&m===r&&h<o+l&&n)return 0;if(1===c.size){if(function(t,e,n){const o=e._nodeMap.get(t),r=n._nodeMap.get(t),i=e._selection,a=n._selection;return!(x(i)&&x(a)&&"element"===i.anchor.type&&"element"===i.focus.type&&"text"===a.anchor.type&&"text"===a.focus.type||!v(o)||!v(r)||o.__parent!==r.__parent)&&JSON.stringify(e.read(()=>o.exportJSON()))===JSON.stringify(n.read(()=>r.exportJSON()))}(Array.from(c)[0],s,u))return 0}return 1})();return o=h,r=m,b}}function E(t,e){t.undoStack=[],t.redoStack=[],t.current=null,e&&e(t)}function D(t,e,n,o=Date.now,r,a=null){const l=w(t,n,o),s=()=>{r&&r(e)};return s(),i(t.registerCommand(u,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==r.length){const i=e.current,a=r.pop();null!==i&&(o.push(i),t.dispatchCommand(h,!0)),0===r.length&&t.dispatchCommand(m,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:y})}}(t,e,r),!0),d),t.registerCommand(c,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==o.length){const i=e.current;null!==i&&(r.push(i),t.dispatchCommand(m,!0));const a=o.pop();0===o.length&&t.dispatchCommand(h,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:y})}}(t,e,r),!0),d),t.registerCommand(p,()=>(E(e,r),!1),d),t.registerCommand(f,()=>(E(e,r),t.dispatchCommand(h,!1),t.dispatchCommand(m,!1),!0),d),t.registerUpdateListener(({editorState:n,prevEditorState:o,dirtyLeaves:r,dirtyElements:i,tags:u})=>{const d=e.current,c=e.redoStack,p=e.undoStack,f=null===d?null:d.editorState;if(null!==d&&n===f)return;const g=l(o,n,d,r,i,u);if(1===g){if(0!==c.length&&(e.redoStack=[],t.dispatchCommand(h,!1)),null!==d){p.push({...d});const e="number"==typeof a||null===a?a:a.peek();null!==e&&p.length>e&&p.splice(0,p.length-e),t.dispatchCommand(m,!0)}}else if(2===g)return;e.current={editor:t,editorState:n},s()}))}function M(){return{current:null,redoStack:[],undoStack:[]}}const O=a({build:(t,{delay:e,createInitialHistoryState:o,disabled:r,maxDepth:i,now:a},l)=>({...n({delay:e,disabled:r,historyState:o(t),maxDepth:i,now:a}),...l.getInitResult()}),config:l({createInitialHistoryState:M,delay:300,disabled:"undefined"==typeof window,maxDepth:null,now:Date.now}),init:()=>({canRedo:e(!1),canUndo:e(!1)}),name:"@lexical/history/History",register:(e,n,r)=>{const{canUndo:i,canRedo:a}=r.getInitResult(),l=r.getOutput(),s=t=>o(()=>{i.value=null!=t&&t.undoStack.length>0,a.value=null!=t&&t.redoStack.length>0});return t(()=>{if(!l.disabled.value)return D(e,l.historyState.value,l.delay,()=>l.now.peek()(),s,l.maxDepth);s(null)})}});const z=a({build:(t,{disabled:e,parentEditor:o})=>n({disabled:e,parentEditor:o||t._parentEditor}),config:l({disabled:!1,parentEditor:null}),dependencies:[s(O,{disabled:!0})],name:"@lexical/history/SharedHistory",register:(e,n,i)=>t(()=>{const{disabled:t,parentEditor:e}=i.getOutput();if(!t.value){const{output:t}=i.getDependency(O),n=function(t){return t?r(t,O.name):null}(e.value);if(!n)return;const a=n.output;o(()=>{t.delay.value=a.delay.value,t.historyState.value=a.historyState.value,t.now.value=a.now.value,t.disabled.value=a.disabled.value})}})});export{O as HistoryExtension,z as SharedHistoryExtension,M as createEmptyHistoryState,D as registerHistory};
@@ -29,9 +29,15 @@ export type HistoryState = {
29
29
  * NOT invoked when a candidate update is discarded without changing the
30
30
  * stacks. Useful for keeping derived values (e.g. signals) in sync with the
31
31
  * current `HistoryState`.
32
+ * @param maxDepth - The maximum number of entries the undo stack may hold.
33
+ * When the cap is exceeded a new history event has been pushed the oldest
34
+ * entries are dropped from the front of the stack until the stack length is
35
+ * `maxDepth`. Pass `null` (the default) to keep the stack unbounded — the
36
+ * historical behavior. May be a plain number or a `ReadonlySignal<number | null>`
37
+ * for reactive reconfiguration.
32
38
  * @returns The listeners cleanup callback function.
33
39
  */
34
- export declare function registerHistory(editor: LexicalEditor, historyState: HistoryState, delay: number | ReadonlySignal<number>, dateNow?: () => number, onHistoryStateChange?: (state: HistoryState) => void): () => void;
40
+ export declare function registerHistory(editor: LexicalEditor, historyState: HistoryState, delay: number | ReadonlySignal<number>, dateNow?: () => number, onHistoryStateChange?: (state: HistoryState) => void, maxDepth?: number | null | ReadonlySignal<number | null>): () => void;
35
41
  /**
36
42
  * Creates an empty history state.
37
43
  * @returns - The empty history state, as an object.
@@ -55,6 +61,18 @@ export interface HistoryConfig {
55
61
  * The now() function, defaults to Date.now.
56
62
  */
57
63
  now: () => number;
64
+ /**
65
+ * The maximum number of entries the undo stack may hold. When the cap is
66
+ * exceeded the oldest entries are dropped (FIFO) so the stack stays at this
67
+ * length. Defaults to `null`, which keeps the stack unbounded — the
68
+ * historical behavior. Setting a finite cap is recommended for editors that
69
+ * may receive a very large number of distinct history events (long writing
70
+ * sessions, automated input, etc.) since each entry retains a full
71
+ * `EditorState` snapshot.
72
+ *
73
+ * For reference, ProseMirror's `history()` plugin defaults to `depth: 100`.
74
+ */
75
+ maxDepth: number | null;
58
76
  }
59
77
  /** Internal writable signals created during the init phase. */
60
78
  interface HistoryExtensionInit {
@@ -87,6 +105,12 @@ export interface HistoryExtensionOutput {
87
105
  disabled: Signal<boolean>;
88
106
  /** The active {@link HistoryState} instance. */
89
107
  historyState: Signal<HistoryState>;
108
+ /**
109
+ * Maximum number of entries the undo stack may hold. `null` disables the
110
+ * cap. Changes apply to the next history event — the current undo stack is
111
+ * not retroactively trimmed when the value is lowered.
112
+ */
113
+ maxDepth: Signal<number | null>;
90
114
  /** The clock function forwarded to {@link registerHistory}. */
91
115
  now: Signal<() => number>;
92
116
  }
package/package.json CHANGED
@@ -8,36 +8,50 @@
8
8
  "history"
9
9
  ],
10
10
  "license": "MIT",
11
- "version": "0.44.1-nightly.20260519.0",
12
- "main": "LexicalHistory.js",
13
- "types": "index.d.ts",
11
+ "version": "0.45.1-dev.0",
12
+ "main": "./dist/LexicalHistory.js",
13
+ "types": "./dist/index.d.ts",
14
14
  "dependencies": {
15
- "@lexical/extension": "0.44.1-nightly.20260519.0",
16
- "@lexical/utils": "0.44.1-nightly.20260519.0",
17
- "lexical": "0.44.1-nightly.20260519.0"
15
+ "@lexical/extension": "0.45.1-dev.0",
16
+ "@lexical/utils": "0.45.1-dev.0",
17
+ "lexical": "0.45.1-dev.0"
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
21
21
  "url": "git+https://github.com/facebook/lexical.git",
22
22
  "directory": "packages/lexical-history"
23
23
  },
24
- "module": "LexicalHistory.mjs",
24
+ "module": "./dist/LexicalHistory.mjs",
25
25
  "sideEffects": false,
26
26
  "exports": {
27
27
  ".": {
28
+ "source": "./src/index.ts",
28
29
  "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"
30
+ "types": "./dist/index.d.ts",
31
+ "development": "./dist/LexicalHistory.dev.mjs",
32
+ "production": "./dist/LexicalHistory.prod.mjs",
33
+ "node": "./dist/LexicalHistory.node.mjs",
34
+ "default": "./dist/LexicalHistory.mjs"
34
35
  },
35
36
  "require": {
36
- "types": "./index.d.ts",
37
- "development": "./LexicalHistory.dev.js",
38
- "production": "./LexicalHistory.prod.js",
39
- "default": "./LexicalHistory.js"
37
+ "types": "./dist/index.d.ts",
38
+ "development": "./dist/LexicalHistory.dev.js",
39
+ "production": "./dist/LexicalHistory.prod.js",
40
+ "default": "./dist/LexicalHistory.js"
40
41
  }
41
42
  }
42
- }
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "src",
47
+ "!src/__tests__",
48
+ "!src/__bench__",
49
+ "!src/__mocks__",
50
+ "!src/**/*.test.ts",
51
+ "!src/**/*.test.tsx",
52
+ "!src/**/*.bench.ts",
53
+ "!src/**/*.bench.tsx",
54
+ "README.md",
55
+ "LICENSE"
56
+ ]
43
57
  }
package/src/index.ts ADDED
@@ -0,0 +1,807 @@
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 type {EditorState, LexicalEditor, LexicalNode, NodeKey} from 'lexical';
10
+
11
+ import {
12
+ batch,
13
+ effect,
14
+ getPeerDependencyFromEditor,
15
+ namedSignals,
16
+ ReadonlySignal,
17
+ Signal,
18
+ signal,
19
+ } from '@lexical/extension';
20
+ import {mergeRegister} from '@lexical/utils';
21
+ import {
22
+ $isRangeSelection,
23
+ $isRootNode,
24
+ $isTextNode,
25
+ CAN_REDO_COMMAND,
26
+ CAN_UNDO_COMMAND,
27
+ CLEAR_EDITOR_COMMAND,
28
+ CLEAR_HISTORY_COMMAND,
29
+ COMMAND_PRIORITY_EDITOR,
30
+ COMPOSITION_END_TAG,
31
+ COMPOSITION_START_TAG,
32
+ configExtension,
33
+ defineExtension,
34
+ HISTORIC_TAG,
35
+ HISTORY_MERGE_TAG,
36
+ HISTORY_PUSH_TAG,
37
+ REDO_COMMAND,
38
+ safeCast,
39
+ UNDO_COMMAND,
40
+ } from 'lexical';
41
+
42
+ type MergeAction = 0 | 1 | 2;
43
+ const HISTORY_MERGE = 0;
44
+ const HISTORY_PUSH = 1;
45
+ const DISCARD_HISTORY_CANDIDATE = 2;
46
+
47
+ type ChangeType = 0 | 1 | 2 | 3 | 4;
48
+ const OTHER = 0;
49
+ const COMPOSING_CHARACTER = 1;
50
+ const INSERT_CHARACTER_AFTER_SELECTION = 2;
51
+ const DELETE_CHARACTER_BEFORE_SELECTION = 3;
52
+ const DELETE_CHARACTER_AFTER_SELECTION = 4;
53
+
54
+ export type HistoryStateEntry = {
55
+ editor: LexicalEditor;
56
+ editorState: EditorState;
57
+ };
58
+ export type HistoryState = {
59
+ current: null | HistoryStateEntry;
60
+ redoStack: Array<HistoryStateEntry>;
61
+ undoStack: Array<HistoryStateEntry>;
62
+ };
63
+
64
+ type IntentionallyMarkedAsDirtyElement = boolean;
65
+
66
+ function getDirtyNodes(
67
+ editorState: EditorState,
68
+ dirtyLeaves: Set<NodeKey>,
69
+ dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
70
+ ): Array<LexicalNode> {
71
+ const nodeMap = editorState._nodeMap;
72
+ const nodes = [];
73
+
74
+ for (const dirtyLeafKey of dirtyLeaves) {
75
+ const dirtyLeaf = nodeMap.get(dirtyLeafKey);
76
+
77
+ if (dirtyLeaf !== undefined) {
78
+ nodes.push(dirtyLeaf);
79
+ }
80
+ }
81
+
82
+ for (const [dirtyElementKey, intentionallyMarkedAsDirty] of dirtyElements) {
83
+ if (!intentionallyMarkedAsDirty) {
84
+ continue;
85
+ }
86
+
87
+ const dirtyElement = nodeMap.get(dirtyElementKey);
88
+
89
+ if (dirtyElement !== undefined && !$isRootNode(dirtyElement)) {
90
+ nodes.push(dirtyElement);
91
+ }
92
+ }
93
+
94
+ return nodes;
95
+ }
96
+
97
+ function getChangeType(
98
+ prevEditorState: null | EditorState,
99
+ nextEditorState: EditorState,
100
+ dirtyLeavesSet: Set<NodeKey>,
101
+ dirtyElementsSet: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
102
+ isComposing: boolean,
103
+ ): ChangeType {
104
+ if (
105
+ prevEditorState === null ||
106
+ (dirtyLeavesSet.size === 0 && dirtyElementsSet.size === 0 && !isComposing)
107
+ ) {
108
+ return OTHER;
109
+ }
110
+
111
+ const nextSelection = nextEditorState._selection;
112
+ const prevSelection = prevEditorState._selection;
113
+
114
+ if (isComposing) {
115
+ return COMPOSING_CHARACTER;
116
+ }
117
+
118
+ if (
119
+ !$isRangeSelection(nextSelection) ||
120
+ !$isRangeSelection(prevSelection) ||
121
+ !prevSelection.isCollapsed() ||
122
+ !nextSelection.isCollapsed()
123
+ ) {
124
+ return OTHER;
125
+ }
126
+
127
+ const dirtyNodes = getDirtyNodes(
128
+ nextEditorState,
129
+ dirtyLeavesSet,
130
+ dirtyElementsSet,
131
+ );
132
+
133
+ if (dirtyNodes.length === 0) {
134
+ return OTHER;
135
+ }
136
+
137
+ // Catching the case when inserting new text node into an element (e.g. first char in paragraph/list),
138
+ // or after existing node.
139
+ if (dirtyNodes.length > 1) {
140
+ const nextNodeMap = nextEditorState._nodeMap;
141
+ const nextAnchorNode = nextNodeMap.get(nextSelection.anchor.key);
142
+ const prevAnchorNode = nextNodeMap.get(prevSelection.anchor.key);
143
+
144
+ if (
145
+ nextAnchorNode &&
146
+ prevAnchorNode &&
147
+ !prevEditorState._nodeMap.has(nextAnchorNode.__key) &&
148
+ $isTextNode(nextAnchorNode) &&
149
+ nextAnchorNode.__text.length === 1 &&
150
+ nextSelection.anchor.offset === 1
151
+ ) {
152
+ return INSERT_CHARACTER_AFTER_SELECTION;
153
+ }
154
+
155
+ return OTHER;
156
+ }
157
+
158
+ const nextDirtyNode = dirtyNodes[0];
159
+
160
+ const prevDirtyNode = prevEditorState._nodeMap.get(nextDirtyNode.__key);
161
+
162
+ if (
163
+ !$isTextNode(prevDirtyNode) ||
164
+ !$isTextNode(nextDirtyNode) ||
165
+ prevDirtyNode.__mode !== nextDirtyNode.__mode
166
+ ) {
167
+ return OTHER;
168
+ }
169
+
170
+ const prevText = prevDirtyNode.__text;
171
+ const nextText = nextDirtyNode.__text;
172
+
173
+ if (prevText === nextText) {
174
+ return OTHER;
175
+ }
176
+
177
+ const nextAnchor = nextSelection.anchor;
178
+ const prevAnchor = prevSelection.anchor;
179
+
180
+ if (nextAnchor.key !== prevAnchor.key || nextAnchor.type !== 'text') {
181
+ return OTHER;
182
+ }
183
+
184
+ const nextAnchorOffset = nextAnchor.offset;
185
+ const prevAnchorOffset = prevAnchor.offset;
186
+ const textDiff = nextText.length - prevText.length;
187
+
188
+ if (textDiff === 1 && prevAnchorOffset === nextAnchorOffset - 1) {
189
+ return INSERT_CHARACTER_AFTER_SELECTION;
190
+ }
191
+
192
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset + 1) {
193
+ return DELETE_CHARACTER_BEFORE_SELECTION;
194
+ }
195
+
196
+ if (textDiff === -1 && prevAnchorOffset === nextAnchorOffset) {
197
+ return DELETE_CHARACTER_AFTER_SELECTION;
198
+ }
199
+
200
+ return OTHER;
201
+ }
202
+
203
+ function isTextNodeUnchanged(
204
+ key: NodeKey,
205
+ prevEditorState: EditorState,
206
+ nextEditorState: EditorState,
207
+ ): boolean {
208
+ const prevNode = prevEditorState._nodeMap.get(key);
209
+ const nextNode = nextEditorState._nodeMap.get(key);
210
+
211
+ const prevSelection = prevEditorState._selection;
212
+ const nextSelection = nextEditorState._selection;
213
+ const isDeletingLine =
214
+ $isRangeSelection(prevSelection) &&
215
+ $isRangeSelection(nextSelection) &&
216
+ prevSelection.anchor.type === 'element' &&
217
+ prevSelection.focus.type === 'element' &&
218
+ nextSelection.anchor.type === 'text' &&
219
+ nextSelection.focus.type === 'text';
220
+
221
+ if (
222
+ !isDeletingLine &&
223
+ $isTextNode(prevNode) &&
224
+ $isTextNode(nextNode) &&
225
+ prevNode.__parent === nextNode.__parent
226
+ ) {
227
+ // This has the assumption that object key order won't change if the
228
+ // content did not change, which should normally be safe given
229
+ // the manner in which nodes and exportJSON are typically implemented.
230
+ return (
231
+ JSON.stringify(prevEditorState.read(() => prevNode.exportJSON())) ===
232
+ JSON.stringify(nextEditorState.read(() => nextNode.exportJSON()))
233
+ );
234
+ }
235
+ return false;
236
+ }
237
+
238
+ function createMergeActionGetter(
239
+ editor: LexicalEditor,
240
+ delayOrStore: number | ReadonlySignal<number>,
241
+ dateNow: () => number,
242
+ ): (
243
+ prevEditorState: null | EditorState,
244
+ nextEditorState: EditorState,
245
+ currentHistoryEntry: null | HistoryStateEntry,
246
+ dirtyLeaves: Set<NodeKey>,
247
+ dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
248
+ tags: Set<string>,
249
+ ) => MergeAction {
250
+ let prevChangeTime = dateNow();
251
+ let prevChangeType = OTHER;
252
+ let compositionStartTime = prevChangeTime;
253
+ let compositionStartChangeType = OTHER;
254
+ let compositionStartState: EditorState | null = null;
255
+
256
+ return (
257
+ prevEditorState,
258
+ nextEditorState,
259
+ currentHistoryEntry,
260
+ dirtyLeaves,
261
+ dirtyElements,
262
+ tags,
263
+ ) => {
264
+ const changeTime = dateNow();
265
+
266
+ if (tags.has(COMPOSITION_START_TAG)) {
267
+ compositionStartTime = prevChangeTime;
268
+ compositionStartChangeType = prevChangeType;
269
+ compositionStartState = prevEditorState;
270
+ }
271
+
272
+ // If applying changes from history stack there's no need
273
+ // to run history logic again, as history entries already calculated
274
+ if (tags.has(HISTORIC_TAG)) {
275
+ prevChangeType = OTHER;
276
+ prevChangeTime = changeTime;
277
+ return DISCARD_HISTORY_CANDIDATE;
278
+ }
279
+
280
+ const isCompositionEnd = tags.has(COMPOSITION_END_TAG);
281
+ if (isCompositionEnd && compositionStartState) {
282
+ prevChangeTime = compositionStartTime;
283
+ prevChangeType = compositionStartChangeType;
284
+ prevEditorState = compositionStartState;
285
+ }
286
+
287
+ const changeType = getChangeType(
288
+ prevEditorState,
289
+ nextEditorState,
290
+ dirtyLeaves,
291
+ dirtyElements,
292
+ editor.isComposing(),
293
+ );
294
+
295
+ const mergeAction = (() => {
296
+ const isSameEditor =
297
+ currentHistoryEntry === null || currentHistoryEntry.editor === editor;
298
+ const shouldPushHistory = tags.has(HISTORY_PUSH_TAG);
299
+ const shouldMergeHistory =
300
+ !shouldPushHistory && isSameEditor && tags.has(HISTORY_MERGE_TAG);
301
+
302
+ if (shouldMergeHistory) {
303
+ return HISTORY_MERGE;
304
+ }
305
+
306
+ if (changeType === COMPOSING_CHARACTER) {
307
+ return DISCARD_HISTORY_CANDIDATE;
308
+ }
309
+
310
+ if (prevEditorState === null) {
311
+ return HISTORY_PUSH;
312
+ }
313
+
314
+ const selection = nextEditorState._selection;
315
+ const hasDirtyNodes = dirtyLeaves.size > 0 || dirtyElements.size > 0;
316
+
317
+ if (!hasDirtyNodes) {
318
+ if (selection !== null) {
319
+ return HISTORY_MERGE;
320
+ }
321
+
322
+ return DISCARD_HISTORY_CANDIDATE;
323
+ }
324
+
325
+ const delay =
326
+ typeof delayOrStore === 'number' ? delayOrStore : delayOrStore.peek();
327
+ if (
328
+ shouldPushHistory === false &&
329
+ changeType !== OTHER &&
330
+ changeType === prevChangeType &&
331
+ changeTime < prevChangeTime + delay &&
332
+ isSameEditor
333
+ ) {
334
+ return HISTORY_MERGE;
335
+ }
336
+
337
+ // A single node might have been marked as dirty, but not have changed
338
+ // due to some node transform reverting the change.
339
+ if (dirtyLeaves.size === 1) {
340
+ const dirtyLeafKey = Array.from(dirtyLeaves)[0];
341
+ if (
342
+ isTextNodeUnchanged(dirtyLeafKey, prevEditorState, nextEditorState)
343
+ ) {
344
+ return HISTORY_MERGE;
345
+ }
346
+ }
347
+
348
+ return HISTORY_PUSH;
349
+ })();
350
+
351
+ prevChangeTime = changeTime;
352
+ prevChangeType = changeType;
353
+
354
+ return mergeAction;
355
+ };
356
+ }
357
+
358
+ function redo(
359
+ editor: LexicalEditor,
360
+ historyState: HistoryState,
361
+ onChange?: (state: HistoryState) => void,
362
+ ): void {
363
+ const redoStack = historyState.redoStack;
364
+ const undoStack = historyState.undoStack;
365
+
366
+ if (redoStack.length !== 0) {
367
+ const current = historyState.current;
368
+
369
+ if (current !== null) {
370
+ undoStack.push(current);
371
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
372
+ }
373
+
374
+ const historyStateEntry = redoStack.pop();
375
+
376
+ if (redoStack.length === 0) {
377
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
378
+ }
379
+
380
+ historyState.current = historyStateEntry || null;
381
+
382
+ if (onChange) {
383
+ onChange(historyState);
384
+ }
385
+
386
+ if (historyStateEntry) {
387
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
388
+ tag: HISTORIC_TAG,
389
+ });
390
+ }
391
+ }
392
+ }
393
+
394
+ function undo(
395
+ editor: LexicalEditor,
396
+ historyState: HistoryState,
397
+ onChange?: (state: HistoryState) => void,
398
+ ): void {
399
+ const redoStack = historyState.redoStack;
400
+ const undoStack = historyState.undoStack;
401
+ const undoStackLength = undoStack.length;
402
+
403
+ if (undoStackLength !== 0) {
404
+ const current = historyState.current;
405
+ const historyStateEntry = undoStack.pop();
406
+
407
+ if (current !== null) {
408
+ redoStack.push(current);
409
+ editor.dispatchCommand(CAN_REDO_COMMAND, true);
410
+ }
411
+
412
+ if (undoStack.length === 0) {
413
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
414
+ }
415
+
416
+ historyState.current = historyStateEntry || null;
417
+
418
+ if (onChange) {
419
+ onChange(historyState);
420
+ }
421
+
422
+ if (historyStateEntry) {
423
+ historyStateEntry.editor.setEditorState(historyStateEntry.editorState, {
424
+ tag: HISTORIC_TAG,
425
+ });
426
+ }
427
+ }
428
+ }
429
+
430
+ function clearHistory(
431
+ historyState: HistoryState,
432
+ onChange?: (state: HistoryState) => void,
433
+ ): void {
434
+ historyState.undoStack = [];
435
+ historyState.redoStack = [];
436
+ historyState.current = null;
437
+ if (onChange) {
438
+ onChange(historyState);
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Registers necessary listeners to manage undo/redo history stack and related editor commands.
444
+ * It returns `unregister` callback that cleans up all listeners and should be called on editor unmount.
445
+ * @param editor - The lexical editor.
446
+ * @param historyState - The history state, containing the current state and the undo/redo stack.
447
+ * @param delay - The time (in milliseconds) the editor should delay generating a new history stack,
448
+ * instead of merging the current changes with the current stack.
449
+ * @param dateNow - The clock function used for delay-based merging.
450
+ * @param onHistoryStateChange - Optional callback invoked once on registration
451
+ * and again any time `historyState` is mutated (push, pop, clear, etc.). It is
452
+ * NOT invoked when a candidate update is discarded without changing the
453
+ * stacks. Useful for keeping derived values (e.g. signals) in sync with the
454
+ * current `HistoryState`.
455
+ * @param maxDepth - The maximum number of entries the undo stack may hold.
456
+ * When the cap is exceeded a new history event has been pushed the oldest
457
+ * entries are dropped from the front of the stack until the stack length is
458
+ * `maxDepth`. Pass `null` (the default) to keep the stack unbounded — the
459
+ * historical behavior. May be a plain number or a `ReadonlySignal<number | null>`
460
+ * for reactive reconfiguration.
461
+ * @returns The listeners cleanup callback function.
462
+ */
463
+ export function registerHistory(
464
+ editor: LexicalEditor,
465
+ historyState: HistoryState,
466
+ delay: number | ReadonlySignal<number>,
467
+ dateNow: () => number = Date.now,
468
+ onHistoryStateChange?: (state: HistoryState) => void,
469
+ maxDepth: number | null | ReadonlySignal<number | null> = null,
470
+ ): () => void {
471
+ const getMergeAction = createMergeActionGetter(editor, delay, dateNow);
472
+ const readMaxDepth = (): number | null =>
473
+ typeof maxDepth === 'number' || maxDepth === null
474
+ ? maxDepth
475
+ : maxDepth.peek();
476
+
477
+ const notifyChange = () => {
478
+ if (onHistoryStateChange) {
479
+ onHistoryStateChange(historyState);
480
+ }
481
+ };
482
+
483
+ const applyChange = ({
484
+ editorState,
485
+ prevEditorState,
486
+ dirtyLeaves,
487
+ dirtyElements,
488
+ tags,
489
+ }: {
490
+ editorState: EditorState;
491
+ prevEditorState: EditorState;
492
+ dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>;
493
+ dirtyLeaves: Set<NodeKey>;
494
+ tags: Set<string>;
495
+ }): void => {
496
+ const current = historyState.current;
497
+ const redoStack = historyState.redoStack;
498
+ const undoStack = historyState.undoStack;
499
+ const currentEditorState = current === null ? null : current.editorState;
500
+
501
+ if (current !== null && editorState === currentEditorState) {
502
+ return;
503
+ }
504
+
505
+ const mergeAction = getMergeAction(
506
+ prevEditorState,
507
+ editorState,
508
+ current,
509
+ dirtyLeaves,
510
+ dirtyElements,
511
+ tags,
512
+ );
513
+
514
+ if (mergeAction === HISTORY_PUSH) {
515
+ if (redoStack.length !== 0) {
516
+ historyState.redoStack = [];
517
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
518
+ }
519
+
520
+ if (current !== null) {
521
+ undoStack.push({
522
+ ...current,
523
+ });
524
+ const cap = readMaxDepth();
525
+ if (cap !== null && undoStack.length > cap) {
526
+ // FIFO-evict the oldest entries so the stack stays at `cap`.
527
+ // Editing the array in place keeps the same `historyState.undoStack`
528
+ // reference that callers (e.g. SharedHistoryExtension) may hold on
529
+ // to.
530
+ undoStack.splice(0, undoStack.length - cap);
531
+ }
532
+ editor.dispatchCommand(CAN_UNDO_COMMAND, true);
533
+ }
534
+ } else if (mergeAction === DISCARD_HISTORY_CANDIDATE) {
535
+ return;
536
+ }
537
+
538
+ // Else we merge
539
+ historyState.current = {
540
+ editor,
541
+ editorState,
542
+ };
543
+ notifyChange();
544
+ };
545
+
546
+ // Allow consumers (e.g. HistoryExtension) to read pre-populated stacks
547
+ // immediately, without waiting for the first edit.
548
+ notifyChange();
549
+
550
+ return mergeRegister(
551
+ editor.registerCommand(
552
+ UNDO_COMMAND,
553
+ () => {
554
+ undo(editor, historyState, onHistoryStateChange);
555
+ return true;
556
+ },
557
+ COMMAND_PRIORITY_EDITOR,
558
+ ),
559
+ editor.registerCommand(
560
+ REDO_COMMAND,
561
+ () => {
562
+ redo(editor, historyState, onHistoryStateChange);
563
+ return true;
564
+ },
565
+ COMMAND_PRIORITY_EDITOR,
566
+ ),
567
+ editor.registerCommand(
568
+ CLEAR_EDITOR_COMMAND,
569
+ () => {
570
+ clearHistory(historyState, onHistoryStateChange);
571
+ return false;
572
+ },
573
+ COMMAND_PRIORITY_EDITOR,
574
+ ),
575
+ editor.registerCommand(
576
+ CLEAR_HISTORY_COMMAND,
577
+ () => {
578
+ clearHistory(historyState, onHistoryStateChange);
579
+ editor.dispatchCommand(CAN_REDO_COMMAND, false);
580
+ editor.dispatchCommand(CAN_UNDO_COMMAND, false);
581
+ return true;
582
+ },
583
+ COMMAND_PRIORITY_EDITOR,
584
+ ),
585
+ editor.registerUpdateListener(applyChange),
586
+ );
587
+ }
588
+
589
+ /**
590
+ * Creates an empty history state.
591
+ * @returns - The empty history state, as an object.
592
+ */
593
+ export function createEmptyHistoryState(): HistoryState {
594
+ return {
595
+ current: null,
596
+ redoStack: [],
597
+ undoStack: [],
598
+ };
599
+ }
600
+
601
+ export interface HistoryConfig {
602
+ /**
603
+ * The time (in milliseconds) the editor should delay generating a new history stack,
604
+ * instead of merging the current changes with the current stack. The default is 300ms.
605
+ */
606
+ delay: number;
607
+ /**
608
+ * The initial history state, the default is {@link createEmptyHistoryState}.
609
+ */
610
+ createInitialHistoryState: (editor: LexicalEditor) => HistoryState;
611
+ /**
612
+ * Whether history is disabled or not
613
+ */
614
+ disabled: boolean;
615
+ /**
616
+ * The now() function, defaults to Date.now.
617
+ */
618
+ now: () => number;
619
+ /**
620
+ * The maximum number of entries the undo stack may hold. When the cap is
621
+ * exceeded the oldest entries are dropped (FIFO) so the stack stays at this
622
+ * length. Defaults to `null`, which keeps the stack unbounded — the
623
+ * historical behavior. Setting a finite cap is recommended for editors that
624
+ * may receive a very large number of distinct history events (long writing
625
+ * sessions, automated input, etc.) since each entry retains a full
626
+ * `EditorState` snapshot.
627
+ *
628
+ * For reference, ProseMirror's `history()` plugin defaults to `depth: 100`.
629
+ */
630
+ maxDepth: number | null;
631
+ }
632
+
633
+ /** Internal writable signals created during the init phase. */
634
+ interface HistoryExtensionInit {
635
+ canRedo: Signal<boolean>;
636
+ canUndo: Signal<boolean>;
637
+ }
638
+
639
+ /**
640
+ * The output signals exposed by {@link HistoryExtension}.
641
+ *
642
+ * Config-derived signals (`delay`, `disabled`, `historyState`, `now`) are
643
+ * writable so that peer extensions such as {@link SharedHistoryExtension} can
644
+ * redirect them at runtime. The `canUndo` / `canRedo` signals are
645
+ * **readonly** for consumers — they are derived from the current
646
+ * {@link HistoryState} and kept in sync automatically.
647
+ */
648
+ export interface HistoryExtensionOutput {
649
+ /**
650
+ * `true` when there is at least one entry in the redo stack, i.e. the
651
+ * editor can perform a redo.
652
+ */
653
+ canRedo: ReadonlySignal<boolean>;
654
+ /**
655
+ * `true` when there is at least one entry in the undo stack, i.e. the
656
+ * editor can perform an undo.
657
+ */
658
+ canUndo: ReadonlySignal<boolean>;
659
+ /** The merge-delay in milliseconds forwarded to {@link registerHistory}. */
660
+ delay: Signal<number>;
661
+ /** When `true` the history listener is not registered. */
662
+ disabled: Signal<boolean>;
663
+ /** The active {@link HistoryState} instance. */
664
+ historyState: Signal<HistoryState>;
665
+ /**
666
+ * Maximum number of entries the undo stack may hold. `null` disables the
667
+ * cap. Changes apply to the next history event — the current undo stack is
668
+ * not retroactively trimmed when the value is lowered.
669
+ */
670
+ maxDepth: Signal<number | null>;
671
+ /** The clock function forwarded to {@link registerHistory}. */
672
+ now: Signal<() => number>;
673
+ }
674
+
675
+ /**
676
+ * Registers necessary listeners to manage undo/redo history stack and related
677
+ * editor commands, via the \@lexical/history module.
678
+ */
679
+ export const HistoryExtension = defineExtension({
680
+ build: (
681
+ editor,
682
+ {delay, createInitialHistoryState, disabled, maxDepth, now},
683
+ state,
684
+ ): HistoryExtensionOutput => {
685
+ // The init phase already created writable Signal<boolean> instances for
686
+ // canUndo/canRedo. Signal<T> extends ReadonlySignal<T>, so exposing them
687
+ // through the HistoryExtensionOutput type (which declares them as
688
+ // ReadonlySignal<boolean>) is sufficient to prevent consumers from
689
+ // mutating them — no computed() wrapper required.
690
+ return {
691
+ ...namedSignals({
692
+ delay,
693
+ disabled,
694
+ historyState: createInitialHistoryState(editor),
695
+ maxDepth,
696
+ now,
697
+ }),
698
+ ...state.getInitResult(),
699
+ };
700
+ },
701
+ config: safeCast<HistoryConfig>({
702
+ createInitialHistoryState: createEmptyHistoryState,
703
+ delay: 300,
704
+ disabled: typeof window === 'undefined',
705
+ maxDepth: null,
706
+ now: Date.now,
707
+ }),
708
+ init: (): HistoryExtensionInit => ({
709
+ canRedo: signal(false),
710
+ canUndo: signal(false),
711
+ }),
712
+ name: '@lexical/history/History',
713
+ register: (editor, config, state) => {
714
+ const {canUndo, canRedo} = state.getInitResult();
715
+ const stores = state.getOutput();
716
+ // Single update path: passing `null` resets both signals (used for the
717
+ // disabled state); passing a HistoryState derives them from its stacks
718
+ // (used by registerHistory on init and after every mutation). The batch
719
+ // ensures subscribers to both signals are only notified once per change.
720
+ const syncFromHistoryState = (historyState: HistoryState | null) =>
721
+ batch(() => {
722
+ canUndo.value =
723
+ historyState != null && historyState.undoStack.length > 0;
724
+ canRedo.value =
725
+ historyState != null && historyState.redoStack.length > 0;
726
+ });
727
+ return effect(() => {
728
+ if (stores.disabled.value) {
729
+ syncFromHistoryState(null);
730
+ return undefined;
731
+ }
732
+ return registerHistory(
733
+ editor,
734
+ stores.historyState.value,
735
+ stores.delay,
736
+ () => stores.now.peek()(),
737
+ syncFromHistoryState,
738
+ stores.maxDepth,
739
+ );
740
+ });
741
+ },
742
+ });
743
+
744
+ function getHistoryPeer(editor: LexicalEditor | null | undefined) {
745
+ return editor
746
+ ? getPeerDependencyFromEditor<typeof HistoryExtension>(
747
+ editor,
748
+ HistoryExtension.name,
749
+ )
750
+ : null;
751
+ }
752
+
753
+ export interface SharedHistoryConfig {
754
+ /**
755
+ * Whether shared history is disabled or not
756
+ */
757
+ disabled: boolean;
758
+ /**
759
+ * The parentEditor to use, by default it is derived from
760
+ * `config.parentEditor` which can be provided by
761
+ * NestedEditorExtension
762
+ */
763
+ parentEditor: LexicalEditor | null;
764
+ }
765
+
766
+ /**
767
+ * Registers necessary listeners to manage undo/redo history stack and related
768
+ * editor commands, via the \@lexical/history module, only if the parent editor
769
+ * has a history plugin implementation.
770
+ */
771
+ export const SharedHistoryExtension = defineExtension({
772
+ build: (editor, {disabled, parentEditor}) =>
773
+ namedSignals({
774
+ disabled,
775
+ parentEditor: parentEditor || editor._parentEditor,
776
+ }),
777
+ config: safeCast<SharedHistoryConfig>({
778
+ disabled: false,
779
+ parentEditor: null,
780
+ }),
781
+ dependencies: [
782
+ configExtension(HistoryExtension, {
783
+ disabled: true,
784
+ }),
785
+ ],
786
+ name: '@lexical/history/SharedHistory',
787
+ register(editor, _config, state) {
788
+ return effect(() => {
789
+ const {disabled, parentEditor} = state.getOutput();
790
+ if (!disabled.value) {
791
+ const {output} = state.getDependency(HistoryExtension);
792
+ const parentPeer = getHistoryPeer(parentEditor.value);
793
+ if (!parentPeer) {
794
+ return;
795
+ }
796
+ const parentOutput = parentPeer.output;
797
+ batch(() => {
798
+ output.delay.value = parentOutput.delay.value;
799
+ output.historyState.value = parentOutput.historyState.value;
800
+ output.now.value = parentOutput.now.value;
801
+ // Note that toggling the parent history will force this to be changed
802
+ output.disabled.value = parentOutput.disabled.value;
803
+ });
804
+ }
805
+ });
806
+ },
807
+ });
@@ -1,9 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
-
9
- "use strict";var e=require("@lexical/extension"),t=require("@lexical/utils"),n=require("lexical");function o(e,t,o,r,i){if(null===e||0===o.size&&0===r.size&&!i)return 0;const a=t._selection,s=e._selection;if(i)return 1;if(!(n.$isRangeSelection(a)&&n.$isRangeSelection(s)&&s.isCollapsed()&&a.isCollapsed()))return 0;const l=function(e,t,o){const r=e._nodeMap,i=[];for(const e of t){const t=r.get(e);void 0!==t&&i.push(t)}for(const[e,t]of o){if(!t)continue;const o=r.get(e);void 0===o||n.$isRootNode(o)||i.push(o)}return i}(t,o,r);if(0===l.length)return 0;if(l.length>1){const o=t._nodeMap,r=o.get(a.anchor.key),i=o.get(s.anchor.key);return r&&i&&!e._nodeMap.has(r.__key)&&n.$isTextNode(r)&&1===r.__text.length&&1===a.anchor.offset?2:0}const d=l[0],u=e._nodeMap.get(d.__key);if(!n.$isTextNode(u)||!n.$isTextNode(d)||u.__mode!==d.__mode)return 0;const c=u.__text,_=d.__text;if(c===_)return 0;const f=a.anchor,p=s.anchor;if(f.key!==p.key||"text"!==f.type)return 0;const O=f.offset,g=p.offset,S=_.length-c.length;return 1===S&&g===O-1?2:-1===S&&g===O+1?3:-1===S&&g===O?4:0}function r(e,t,r){let i=r(),a=0,s=i,l=0,d=null;return(u,c,_,f,p,O)=>{const g=r();if(O.has(n.COMPOSITION_START_TAG)&&(s=i,l=a,d=u),O.has(n.HISTORIC_TAG))return a=0,i=g,2;O.has(n.COMPOSITION_END_TAG)&&d&&(i=s,a=l,u=d);const S=o(u,c,f,p,e.isComposing()),h=(()=>{const o=null===_||_.editor===e,r=O.has(n.HISTORY_PUSH_TAG);if(!r&&o&&O.has(n.HISTORY_MERGE_TAG))return 0;if(1===S)return 2;if(null===u)return 1;const s=c._selection;if(!(f.size>0||p.size>0))return null!==s?0:2;const l="number"==typeof t?t:t.peek();if(!1===r&&0!==S&&S===a&&g<i+l&&o)return 0;if(1===f.size){if(function(e,t,o){const r=t._nodeMap.get(e),i=o._nodeMap.get(e),a=t._selection,s=o._selection;return!(n.$isRangeSelection(a)&&n.$isRangeSelection(s)&&"element"===a.anchor.type&&"element"===a.focus.type&&"text"===s.anchor.type&&"text"===s.focus.type||!n.$isTextNode(r)||!n.$isTextNode(i)||r.__parent!==i.__parent)&&JSON.stringify(t.read(()=>r.exportJSON()))===JSON.stringify(o.read(()=>i.exportJSON()))}(Array.from(f)[0],u,c))return 0}return 1})();return i=g,a=S,h}}function i(e,t){e.undoStack=[],e.redoStack=[],e.current=null,t&&t(e)}function a(e,o,a,s=Date.now,l){const d=r(e,a,s),u=()=>{l&&l(o)};return u(),t.mergeRegister(e.registerCommand(n.UNDO_COMMAND,()=>(function(e,t,o){const r=t.redoStack,i=t.undoStack;if(0!==i.length){const a=t.current,s=i.pop();null!==a&&(r.push(a),e.dispatchCommand(n.CAN_REDO_COMMAND,!0)),0===i.length&&e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),t.current=s||null,o&&o(t),s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,o,l),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.REDO_COMMAND,()=>(function(e,t,o){const r=t.redoStack,i=t.undoStack;if(0!==r.length){const a=t.current;null!==a&&(i.push(a),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,o&&o(t),s&&s.editor.setEditorState(s.editorState,{tag:n.HISTORIC_TAG})}}(e,o,l),!0),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_EDITOR_COMMAND,()=>(i(o,l),!1),n.COMMAND_PRIORITY_EDITOR),e.registerCommand(n.CLEAR_HISTORY_COMMAND,()=>(i(o,l),e.dispatchCommand(n.CAN_REDO_COMMAND,!1),e.dispatchCommand(n.CAN_UNDO_COMMAND,!1),!0),n.COMMAND_PRIORITY_EDITOR),e.registerUpdateListener(({editorState:t,prevEditorState:r,dirtyLeaves:i,dirtyElements:a,tags:s})=>{const l=o.current,c=o.redoStack,_=o.undoStack,f=null===l?null:l.editorState;if(null!==l&&t===f)return;const p=d(r,t,l,i,a,s);if(1===p)0!==c.length&&(o.redoStack=[],e.dispatchCommand(n.CAN_REDO_COMMAND,!1)),null!==l&&(_.push({...l}),e.dispatchCommand(n.CAN_UNDO_COMMAND,!0));else if(2===p)return;o.current={editor:e,editorState:t},u()}))}function s(){return{current:null,redoStack:[],undoStack:[]}}const l=n.defineExtension({build:(t,{delay:n,createInitialHistoryState:o,disabled:r,now:i},a)=>({...e.namedSignals({delay:n,disabled:r,historyState:o(t),now:i}),...a.getInitResult()}),config:n.safeCast({createInitialHistoryState:s,delay:300,disabled:"undefined"==typeof window,now:Date.now}),init:()=>({canRedo:e.signal(!1),canUndo:e.signal(!1)}),name:"@lexical/history/History",register:(t,n,o)=>{const{canUndo:r,canRedo:i}=o.getInitResult(),s=o.getOutput(),l=t=>e.batch(()=>{r.value=null!=t&&t.undoStack.length>0,i.value=null!=t&&t.redoStack.length>0});return e.effect(()=>{if(!s.disabled.value)return a(t,s.historyState.value,s.delay,()=>s.now.peek()(),l);l(null)})}});const d=n.defineExtension({build:(t,{disabled:n,parentEditor:o})=>e.namedSignals({disabled:n,parentEditor:o||t._parentEditor}),config:n.safeCast({disabled:!1,parentEditor:null}),dependencies:[n.configExtension(l,{disabled:!0})],name:"@lexical/history/SharedHistory",register:(t,n,o)=>e.effect(()=>{const{disabled:t,parentEditor:n}=o.getOutput();if(!t.value){const{output:t}=o.getDependency(l),r=function(t){return t?e.getPeerDependencyFromEditor(t,l.name):null}(n.value);if(!r)return;const i=r.output;e.batch(()=>{t.delay.value=i.delay.value,t.historyState.value=i.historyState.value,t.now.value=i.now.value,t.disabled.value=i.disabled.value})}})});exports.HistoryExtension=l,exports.SharedHistoryExtension=d,exports.createEmptyHistoryState=s,exports.registerHistory=a;
@@ -1,9 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
-
9
- import{effect as t,signal as e,namedSignals as n,batch as o,getPeerDependencyFromEditor as r}from"@lexical/extension";import{mergeRegister as i}from"@lexical/utils";import{defineExtension as a,safeCast as l,configExtension as s,UNDO_COMMAND as u,COMMAND_PRIORITY_EDITOR as d,REDO_COMMAND as c,CLEAR_EDITOR_COMMAND as f,CLEAR_HISTORY_COMMAND as p,CAN_REDO_COMMAND as h,CAN_UNDO_COMMAND as m,COMPOSITION_START_TAG as g,HISTORIC_TAG as y,COMPOSITION_END_TAG as S,HISTORY_PUSH_TAG as _,HISTORY_MERGE_TAG as k,$isRangeSelection as v,$isTextNode as x,$isRootNode as C}from"lexical";function b(t,e,n,o,r){if(null===t||0===n.size&&0===o.size&&!r)return 0;const i=e._selection,a=t._selection;if(r)return 1;if(!(v(i)&&v(a)&&a.isCollapsed()&&i.isCollapsed()))return 0;const l=function(t,e,n){const o=t._nodeMap,r=[];for(const t of e){const e=o.get(t);void 0!==e&&r.push(e)}for(const[t,e]of n){if(!e)continue;const n=o.get(t);void 0===n||C(n)||r.push(n)}return r}(e,n,o);if(0===l.length)return 0;if(l.length>1){const n=e._nodeMap,o=n.get(i.anchor.key),r=n.get(a.anchor.key);return o&&r&&!t._nodeMap.has(o.__key)&&x(o)&&1===o.__text.length&&1===i.anchor.offset?2:0}const s=l[0],u=t._nodeMap.get(s.__key);if(!x(u)||!x(s)||u.__mode!==s.__mode)return 0;const d=u.__text,c=s.__text;if(d===c)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,g=c.length-d.length;return 1===g&&m===h-1?2:-1===g&&m===h+1?3:-1===g&&m===h?4:0}function w(t,e,n){let o=n(),r=0,i=o,a=0,l=null;return(s,u,d,c,f,p)=>{const h=n();if(p.has(g)&&(i=o,a=r,l=s),p.has(y))return r=0,o=h,2;p.has(S)&&l&&(o=i,r=a,s=l);const m=b(s,u,c,f,t.isComposing()),C=(()=>{const n=null===d||d.editor===t,i=p.has(_);if(!i&&n&&p.has(k))return 0;if(1===m)return 2;if(null===s)return 1;const a=u._selection;if(!(c.size>0||f.size>0))return null!==a?0:2;const l="number"==typeof e?e:e.peek();if(!1===i&&0!==m&&m===r&&h<o+l&&n)return 0;if(1===c.size){if(function(t,e,n){const o=e._nodeMap.get(t),r=n._nodeMap.get(t),i=e._selection,a=n._selection;return!(v(i)&&v(a)&&"element"===i.anchor.type&&"element"===i.focus.type&&"text"===a.anchor.type&&"text"===a.focus.type||!x(o)||!x(r)||o.__parent!==r.__parent)&&JSON.stringify(e.read(()=>o.exportJSON()))===JSON.stringify(n.read(()=>r.exportJSON()))}(Array.from(c)[0],s,u))return 0}return 1})();return o=h,r=m,C}}function E(t,e){t.undoStack=[],t.redoStack=[],t.current=null,e&&e(t)}function M(t,e,n,o=Date.now,r){const a=w(t,n,o),l=()=>{r&&r(e)};return l(),i(t.registerCommand(u,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==r.length){const i=e.current,a=r.pop();null!==i&&(o.push(i),t.dispatchCommand(h,!0)),0===r.length&&t.dispatchCommand(m,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:y})}}(t,e,r),!0),d),t.registerCommand(c,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==o.length){const i=e.current;null!==i&&(r.push(i),t.dispatchCommand(m,!0));const a=o.pop();0===o.length&&t.dispatchCommand(h,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:y})}}(t,e,r),!0),d),t.registerCommand(f,()=>(E(e,r),!1),d),t.registerCommand(p,()=>(E(e,r),t.dispatchCommand(h,!1),t.dispatchCommand(m,!1),!0),d),t.registerUpdateListener(({editorState:n,prevEditorState:o,dirtyLeaves:r,dirtyElements:i,tags:s})=>{const u=e.current,d=e.redoStack,c=e.undoStack,f=null===u?null:u.editorState;if(null!==u&&n===f)return;const p=a(o,n,u,r,i,s);if(1===p)0!==d.length&&(e.redoStack=[],t.dispatchCommand(h,!1)),null!==u&&(c.push({...u}),t.dispatchCommand(m,!0));else if(2===p)return;e.current={editor:t,editorState:n},l()}))}function O(){return{current:null,redoStack:[],undoStack:[]}}const z=a({build:(t,{delay:e,createInitialHistoryState:o,disabled:r,now:i},a)=>({...n({delay:e,disabled:r,historyState:o(t),now:i}),...a.getInitResult()}),config:l({createInitialHistoryState:O,delay:300,disabled:"undefined"==typeof window,now:Date.now}),init:()=>({canRedo:e(!1),canUndo:e(!1)}),name:"@lexical/history/History",register:(e,n,r)=>{const{canUndo:i,canRedo:a}=r.getInitResult(),l=r.getOutput(),s=t=>o(()=>{i.value=null!=t&&t.undoStack.length>0,a.value=null!=t&&t.redoStack.length>0});return t(()=>{if(!l.disabled.value)return M(e,l.historyState.value,l.delay,()=>l.now.peek()(),s);s(null)})}});const H=a({build:(t,{disabled:e,parentEditor:o})=>n({disabled:e,parentEditor:o||t._parentEditor}),config:l({disabled:!1,parentEditor:null}),dependencies:[s(z,{disabled:!0})],name:"@lexical/history/SharedHistory",register:(e,n,i)=>t(()=>{const{disabled:t,parentEditor:e}=i.getOutput();if(!t.value){const{output:t}=i.getDependency(z),n=function(t){return t?r(t,z.name):null}(e.value);if(!n)return;const a=n.output;o(()=>{t.delay.value=a.delay.value,t.historyState.value=a.historyState.value,t.now.value=a.now.value,t.disabled.value=a.disabled.value})}})});export{z as HistoryExtension,H as SharedHistoryExtension,O as createEmptyHistoryState,M as registerHistory};
File without changes
File without changes