Skip to content

Commit

Permalink
Add $onUpdate, tests
Browse files Browse the repository at this point in the history
  • Loading branch information
landisdesign committed Oct 27, 2024
1 parent 173a3de commit 8301547
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/lexical/src/LexicalUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,19 @@ export function $addUpdateTag(tag: string): void {
editor._updateTags.add(tag);
}

/**
* Add a function to run after the current update. This will run after any
* `onUpdate` function already supplied to `editor.update()`, as well as any
* functions added with previous calls to `$onUpdate`.
*
* @param updateFn The function to run after the current update.
*/
export function $onUpdate(updateFn: () => void): void {
errorOnReadOnly();
const editor = getActiveEditor();
editor._deferred.push(updateFn);
}

export function $maybeMoveChildrenSelectionToParent(
parentNode: LexicalNode,
): BaseSelection | null {
Expand Down
38 changes: 38 additions & 0 deletions packages/lexical/src/__tests__/unit/LexicalUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from 'lexical';

import {
$onUpdate,
emptyFunction,
generateRandomKey,
getCachedTypeToNodeMap,
Expand Down Expand Up @@ -242,6 +243,43 @@ describe('LexicalUtils tests', () => {
});
});

describe('$onUpdate', () => {
test('added fn runs after update, original onUpdate, and prior calls to $onUpdate', () => {
const {editor} = testEnv;
const runs: string[] = [];

editor.update(
() => {
$getRoot().append(
$createParagraphNode().append($createTextNode('foo')),
);
$onUpdate(() => {
runs.push('second');
});
$onUpdate(() => {
runs.push('third');
});
},
{
onUpdate: () => {
runs.push('first');
},
},
);

// Flush pending updates
editor.read(() => {});

expect(runs).toEqual(['first', 'second', 'third']);
});

test('adding fn throws outside update', () => {
expect(() => {
$onUpdate(() => {});
}).toThrow();
});
});

test('getCachedTypeToNodeMap', async () => {
const {editor} = testEnv;
const paragraphKeys: string[] = [];
Expand Down
1 change: 1 addition & 0 deletions packages/lexical/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ export {
$isRootOrShadowRoot,
$isTokenOrSegmented,
$nodesOfType,
$onUpdate,
$selectAll,
$setCompositionKey,
$setSelection,
Expand Down

0 comments on commit 8301547

Please sign in to comment.