Check for id when inserting dynamic elements

* I'm not sure it behaved, if there were multiple elements
  inserted by different add-ons into the same container
This commit is contained in:
Henrik Giesel 2021-05-07 16:50:17 +02:00
parent cf38cb334e
commit 8b0c6ba5df
2 changed files with 16 additions and 9 deletions

View File

@ -382,7 +382,7 @@ class Browser(QMainWindow):
editor._links["preview"] = lambda _editor: self.onTogglePreview() editor._links["preview"] = lambda _editor: self.onTogglePreview()
editor.web.eval( editor.web.eval(
"$editorToolbar.then(({ notetypeButtons }) => notetypeButtons.appendButton({ component: editorToolbar.PreviewButton }));" "$editorToolbar.then(({ notetypeButtons }) => notetypeButtons.appendButton({ component: editorToolbar.PreviewButton, id: 'preview' }));"
) )
gui_hooks.editor_did_init.append(add_preview_button) gui_hooks.editor_did_init.append(add_preview_button)

View File

@ -8,7 +8,7 @@ import { find } from "./identifier";
export interface SvelteComponent { export interface SvelteComponent {
component: SvelteComponentTyped; component: SvelteComponentTyped;
id: string | undefined; id: string;
props: Record<string, unknown> | undefined; props: Record<string, unknown> | undefined;
} }
@ -32,6 +32,10 @@ export interface DynamicRegistrationAPI<T> {
) => void; ) => void;
} }
export function nodeIsElement(node: Node): node is Element {
return node.nodeType === Node.ELEMENT_NODE;
}
export function makeInterface<T>(makeRegistration: () => T): RegistrationAPI<T> { export function makeInterface<T>(makeRegistration: () => T): RegistrationAPI<T> {
const registrations: T[] = []; const registrations: T[] = [];
const items = writable(registrations); const items = writable(registrations);
@ -60,18 +64,21 @@ export function makeInterface<T>(makeRegistration: () => T): RegistrationAPI<T>
observer: MutationObserver observer: MutationObserver
): void => { ): void => {
for (const mutation of mutations) { for (const mutation of mutations) {
const addedNode = mutation.addedNodes[0]; for (const addedNode of mutation.addedNodes) {
if (
nodeIsElement(addedNode) &&
(!component.id || addedNode.id === component.id)
) {
const index = add(addedNode, elementRef);
if (addedNode.nodeType === Node.ELEMENT_NODE) { if (index >= 0) {
const index = add(addedNode as Element, elementRef); registerComponent(index, registration);
}
if (index >= 0) { return observer.disconnect();
registerComponent(index, registration);
} }
} }
} }
observer.disconnect();
}; };
const observer = new MutationObserver(callback); const observer = new MutationObserver(callback);