soma3/src/directives/teleport.ts
2024-10-19 10:26:39 -04:00

40 lines
1002 B
TypeScript

import { Block, Context } from "..";
import { nextTick } from "../util";
export function _teleport(el: Element, exp: string, ctx: Context) {
const anchor = new Comment(":teleport");
el.replaceWith(anchor);
const target = document.querySelector(exp);
if (!target) {
console.warn(`teleport target not found: ${exp}`);
return;
}
nextTick(() => {
target.appendChild(el);
const observer = new MutationObserver((mutationsList) => {
mutationsList.forEach((mutation) => {
mutation.removedNodes.forEach((removedNode) => {
if (removedNode.contains(anchor)) {
el.remove();
observer.disconnect();
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
// Walks the tree of this teleported element.
new Block({
element: el,
parentContext: ctx,
});
});
// Return the anchor so walk continues down the tree in the right order.
return anchor;
}