diff --git a/src/MystEditor.jsx b/src/MystEditor.jsx index de8a41c..9340d4c 100644 --- a/src/MystEditor.jsx +++ b/src/MystEditor.jsx @@ -209,32 +209,32 @@ export default ({ additionalStyles, id, ...params }, /** @type {HTMLElement} */ } window.myst_editor[editorId] = {}; - // cleanup function - window.myst_editor[editorId].remove = () => { - delete window.myst_editor[editorId]; - render(null, target.shadowRoot); - }; - const form = target.closest("form"); if (form) { form.addEventListener("formdata", (e) => e.formData.append(params.name, window.myst_editor[editorId].text)); } + const state = createMystState({ id: editorId, ...params }); + window.myst_editor[editorId].state = state; + + // cleanup function + function remove() { + state.cleanups.forEach((c) => c()); + delete window.myst_editor[editorId]; + render(null, target.shadowRoot); + } + window.myst_editor[editorId].remove = remove; // runs Preact cleanup logic when target is removed const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { if (Array.prototype.some.call(mutation.removedNodes, (n) => n == target)) { - delete window.myst_editor[editorId]; - render(null, target.shadowRoot); + remove(); observer.disconnect(); } } }); observer.observe(target.parentElement, { childList: true }); - const state = createMystState({ id: editorId, ...params }); - window.myst_editor[editorId].state = state; - render( diff --git a/src/mystState.js b/src/mystState.js index 502e03c..19d024c 100644 --- a/src/mystState.js +++ b/src/mystState.js @@ -158,7 +158,7 @@ export function createMystState(/** @type {typeof defaults} */ opts) { }); } const collab = signal(null); - effect(() => { + const collabCleanup = effect(() => { if (!signalOptions.collaboration.value.enabled) return; const client = new CollaborationClient(signalOptions.collaboration.value, { id: signalOptions.id.value, @@ -180,6 +180,7 @@ export function createMystState(/** @type {typeof defaults} */ opts) { }, userSettings: signal(userSettings), collab, + cleanups: [collabCleanup], }; }