diff --git a/src/editor/Editor.jsx b/src/editor/Editor.jsx index 6e6453a..c4a0e13 100644 --- a/src/editor/Editor.jsx +++ b/src/editor/Editor.jsx @@ -4,6 +4,7 @@ import { getWidget, DEFAULT_WIDGETS } from './widgets'; import { TrashIcon } from '../Icons'; import setPosition from './setPosition'; import i18n from '../i18n'; +import { debounce } from '../utils'; /** We need to compare bounds by value, not by object ref **/ const bounds = elem => { @@ -63,6 +64,14 @@ export default class Editor extends Component { componentDidMount() { this.removeObserver = this.initResizeObserver(); + + // This makes sure the editor is repositioned if the widgets change + const observer = new MutationObserver(debounce(() => { + this.removeObserver && this.removeObserver(); + this.removeObserver = this.initResizeObserver(); + })); + + observer.observe(this.element.current, { childList: true, subtree: true }); } componentWillUnmount() { diff --git a/src/utils/index.js b/src/utils/index.js index 22772a8..f8ca6c6 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -17,3 +17,16 @@ export const setLocale = (locale, opt_messages) => { I18n.init(null, opt_messages); } } + +/** See https://www.freecodecamp.org/news/javascript-debounce-example/ **/ +export const debounce = (fn, timeout = 10) => { + let timer; + + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => { fn.apply(this, args); }, timeout); + }; + +} + +export default debounce;