From bf913734ea1ff2e129040f1b529a370b6724ecb7 Mon Sep 17 00:00:00 2001 From: fantasticit Date: Wed, 27 Apr 2022 21:35:17 +0800 Subject: [PATCH] tiptap: fix get editor element clientWidth --- packages/client/src/tiptap/utils/editor.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/client/src/tiptap/utils/editor.ts b/packages/client/src/tiptap/utils/editor.ts index 3e16d924..21b3c6aa 100644 --- a/packages/client/src/tiptap/utils/editor.ts +++ b/packages/client/src/tiptap/utils/editor.ts @@ -3,13 +3,26 @@ import { Editor } from '@tiptap/core'; const cache = new Map(); export function getEditorContainerDOMSize(editor: Editor): { width: number } { + const targetNode = editor.options.element as HTMLElement; + if (!cache.has('width')) { - cache.set('width', (editor.options.element as HTMLElement).offsetWidth); + cache.set('width', targetNode.clientWidth); } if (cache.has('width') && cache.get('width') <= 0) { - cache.set('width', (editor.options.element as HTMLElement).offsetWidth); + cache.set('width', targetNode.clientWidth); } + const config = { attributes: true, childList: true, subtree: true }; + const callback = function (mutationsList, observer) { + cache.set('width', targetNode.clientWidth); + }; + const observer = new MutationObserver(callback); + observer.observe(targetNode, config); + + editor.on('destroy', () => { + observer.disconnect(); + }); + return { width: cache.get('width') }; }