/ src / utils / portal.ts
portal.ts
 1  /**
 2   * Svelte action to move an element to a different part of the DOM (as specified by the `targetId`
 3   * provided), effectively creating a "portal."
 4   *
 5   * @param {HTMLElement} node - The element to be moved (provided by Svelte's `use:action` syntax).
 6   * @param {string} targetId - The ID of the target element where `node` should be moved.
 7   * @returns {{ destroy(): void } | void} - An object with a `destroy` method to remove `node` from the target when unmounted.
 8   *
 9   * @example
10   * ```svelte
11   * <div use:portal={'target-container'}>
12   *   This content will be moved to the element with ID "target-container".
13   * </div>
14   * ```
15   */
16  export default function portal(node: HTMLElement, targetId: string) {
17      if (typeof document === 'undefined') {
18          return;
19      }
20  
21      let targetElement: HTMLElement | null = document.getElementById(targetId);
22  
23      if (!targetElement) {
24          return;
25      }
26  
27      targetElement.appendChild(node);
28  
29      return {
30          destroy() {
31              targetElement.removeChild(node);
32          },
33      };
34  }