From bce557cc2dc767628bed6aac87301a1be7c5431b Mon Sep 17 00:00:00 2001 From: rxliuli Date: Tue, 4 Nov 2025 05:03:50 +0800 Subject: init commit --- src/utils/portal.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/utils/portal.ts (limited to 'src/utils/portal.ts') diff --git a/src/utils/portal.ts b/src/utils/portal.ts new file mode 100644 index 0000000..0c61ed0 --- /dev/null +++ b/src/utils/portal.ts @@ -0,0 +1,34 @@ +/** + * Svelte action to move an element to a different part of the DOM (as specified by the `targetId` + * provided), effectively creating a "portal." + * + * @param {HTMLElement} node - The element to be moved (provided by Svelte's `use:action` syntax). + * @param {string} targetId - The ID of the target element where `node` should be moved. + * @returns {{ destroy(): void } | void} - An object with a `destroy` method to remove `node` from the target when unmounted. + * + * @example + * ```svelte + *
+ * This content will be moved to the element with ID "target-container". + *
+ * ``` + */ +export default function portal(node: HTMLElement, targetId: string) { + if (typeof document === 'undefined') { + return; + } + + let targetElement: HTMLElement | null = document.getElementById(targetId); + + if (!targetElement) { + return; + } + + targetElement.appendChild(node); + + return { + destroy() { + targetElement.removeChild(node); + }, + }; +} -- cgit v1.2.3