From 78264cf1177cfdade00bdaf08161ba799ade4370 Mon Sep 17 00:00:00 2001 From: Sunny Hirai Date: Tue, 28 May 2019 18:10:50 -0700 Subject: [PATCH] Hook debug-mutations into lifecycle events (#2841) --- .../src/plugins/debug/debug-mutations.js | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/slate-react/src/plugins/debug/debug-mutations.js b/packages/slate-react/src/plugins/debug/debug-mutations.js index aad6e0c0b..09bbba75b 100644 --- a/packages/slate-react/src/plugins/debug/debug-mutations.js +++ b/packages/slate-react/src/plugins/debug/debug-mutations.js @@ -60,10 +60,25 @@ function DebugMutationsPlugin({ editor }) { debug(`${array.length} Mutations`, ...array) }) - // `findDOMNode` does not exist until later so we use `setTimeout` - setTimeout(() => { + /** + * The previously observed DOM node + * + * @type {DOMNode} + */ + + let prevRootEl = null + + /** + * Start observing the DOM node for mutations if it isn't being observed + */ + + function start() { const rootEl = editor.findDOMNode([]) + if (rootEl === prevRootEl) return + + debug('start') + observer.observe(rootEl, { childList: true, characterData: true, @@ -71,7 +86,26 @@ function DebugMutationsPlugin({ editor }) { subtree: true, characterDataOldValue: true, }) - }) + + prevRootEl = rootEl + } + + /** + * Stop observing the DOM node for mutations + */ + + function stop() { + debug('stop') + + observer.disconnect() + prevRootEl = null + } + + return { + onComponentDidMount: start, + onComponentDidUpdate: start, + onComponentWillUnmount: stop, + } } export default DebugMutationsPlugin