Skip to content

Commit

Permalink
Fix udecode#2230: Stop accidental infinite recursion (udecode#2233)
Browse files Browse the repository at this point in the history
* Add check for `then` being replaced

* adjust white space

* Change to be a limit of the number of times then can be replaced.

* Create .changeset/nasty-cougars-hear.md

---------

Co-authored-by: Ziad Beyens <ziad.beyens@gmail.com>
  • Loading branch information
fimion and zbeyens authored Feb 27, 2023
1 parent 75893f4 commit 8c15238
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/nasty-cougars-hear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@udecode/plate-core": patch
---

Fixes #2230: infinite recursion when using plugin field `then`
5 changes: 5 additions & 0 deletions packages/core/src/types/plugin/PlatePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ export type PlatePlugin<
plugin: WithPlatePlugin<P, V, E>
) => Partial<PlatePlugin<P, V, E>> | void;

/**
* For internal use. Tracks if then has been replaced for recursive calls.
*/
_thenReplaced?: number;

/**
* Hook called when the editor is initialized.
*/
Expand Down
26 changes: 17 additions & 9 deletions packages/core/src/utils/plate/overridePluginsByKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,23 @@ export const overridePluginsByKey = <
const { then } = plugin;

if (then) {
// override plugin.then
plugin.then = (editor, p) => {
const pluginThen = { key: plugin.key, ...then(editor, p) };

return defaultsDeep(
overridePluginsByKey(pluginThen as any, overrideByKey),
pluginThen
);
};
if(typeof plugin._thenReplaced === 'undefined') {
plugin._thenReplaced = 0;
}
// Limit the number of times that `then` can be replaced.
// otherwise we will accidentally create a stack overflow.
// There is probably a better solution for this.
if((plugin._thenReplaced as number) < 3) {
// override plugin.then
plugin.then = (editor, p) => {
const pluginThen = { key: plugin.key, ...then(editor, p) };
return defaultsDeep(
overridePluginsByKey(pluginThen as any, overrideByKey),
pluginThen
);
};
(plugin._thenReplaced as number)++;
}
} else if (overrideByKey[plugin.key]?.then) {
// TODO: recursvie
plugin.then = overrideByKey[plugin.key].then as any;
Expand Down

0 comments on commit 8c15238

Please sign in to comment.