Move elements inserted into decorated component no matter the position

This commit is contained in:
Henrik Giesel 2021-08-06 19:02:39 +02:00
parent 8ddb0bc6ed
commit ea01183bfd

View file

@ -6,34 +6,59 @@ import { nodeIsElement } from "lib/dom";
import Mathjax_svelte from "./Mathjax.svelte"; import Mathjax_svelte from "./Mathjax.svelte";
function moveNodesInsertedBeforeEndToAfterEnd(element: Element): () => void { function moveNodeOutOfElement(
const allowedChildNodes = element.childNodes.length; element: Element,
node: Node,
const observer = new MutationObserver(() => { placement: "beforebegin" | "afterend"
for (const node of [...element.childNodes].slice(allowedChildNodes)) { ): Node {
element.removeChild(node); element.removeChild(node);
let referenceNode: Node; let referenceNode: Node;
if (nodeIsElement(node)) { if (nodeIsElement(node)) {
referenceNode = element.insertAdjacentElement("afterend", node)!; referenceNode = element.insertAdjacentElement(placement, node)!;
} else { } else {
element.insertAdjacentText("afterend", (node as Text).wholeText); element.insertAdjacentText(placement, (node as Text).wholeText);
referenceNode = element.nextSibling!; referenceNode =
placement === "beforebegin"
? element.previousSibling!
: element.nextSibling!;
} }
if (!referenceNode) { return referenceNode;
continue;
} }
function placeCaretAfter(node: Node): void {
const range = document.createRange(); const range = document.createRange();
range.setStartAfter(referenceNode); range.setStartAfter(node);
range.collapse(false); range.collapse(false);
const selection = document.getSelection()!; const selection = document.getSelection()!;
selection.removeAllRanges(); selection.removeAllRanges();
selection.addRange(range); selection.addRange(range);
} }
function moveNodesInsertedOutside(element: Element, allowedChild: Node): () => void {
const observer = new MutationObserver(() => {
const childNodes = [...element.childNodes];
const allowedIndex = childNodes.findIndex((child) => child === allowedChild);
const beforeChildren = childNodes.slice(0, allowedIndex);
const afterChildren = childNodes.slice(allowedIndex + 1);
let lastNode: Node | null = null;
for (const node of beforeChildren) {
lastNode = moveNodeOutOfElement(element, node, "beforebegin");
}
for (const node of afterChildren) {
lastNode = moveNodeOutOfElement(element, node, "afterend");
}
if (lastNode) {
placeCaretAfter(lastNode);
}
}); });
observer.observe(element, { characterData: true, subtree: true }); observer.observe(element, { characterData: true, subtree: true });
@ -92,7 +117,8 @@ export const Mathjax: DecoratedElementConstructor = class Mathjax
connectedCallback(): void { connectedCallback(): void {
this.decorate(); this.decorate();
this.disconnect = moveNodesInsertedBeforeEndToAfterEnd(this); // TODO text is assigned white-space: normal
this.disconnect = moveNodesInsertedOutside(this, this.children[0]);
} }
disconnectedCallback(): void { disconnectedCallback(): void {