All files / is / mod.ts

100.00% Branches 18/18
100.00% Functions 1/1
100.00% Lines 32/32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
x5
 
 
 
x5
x5
x5
x5
x8
x1
x1
 
 
x7
x8
x2
x2
x8
x8
 
 
x8
x5
x5
x5
 
 
x5
x5
x4
x4
x5
x5
x5
 
 
x8
x1
x1
 
x5
x8
x5
 
 
x5












































// Imports
import { type Directive, Phase } from "@mizu/internal/engine"
export type * from "@mizu/internal/engine"

/** `*is` directive. */
export const _is = {
  name: "*is",
  phase: Phase.MORPHING,
  async execute(renderer, element, { attributes: [attribute], ...options }) {
    if (!renderer.isHtmlElement(element)) {
      return
    }

    // Check whether element needs to be morphed
    const tagname = `${await renderer.evaluate(element, attribute.value, options)}`.toLocaleUpperCase()
    if (tagname === element.tagName) {
      return
    }
    const original = renderer.cache("*").get(element) ?? element
    let morphed = original

    // Create morphed element if tagname doesn't match and keep track of original element
    if (tagname !== original.tagName) {
      morphed = renderer.createElement(tagname)
      renderer.cache("*").set(morphed, original)
    }

    // Replace element with morphed element while keeping same children and cloning attributes
    if (element !== morphed) {
      for (const child of Array.from(element.childNodes) as HTMLElement[]) {
        morphed.appendChild(child)
      }
      Array.from(element.attributes).forEach((attribute) => morphed.attributes.setNamedItem(attribute.cloneNode(true) as Attr))
      element.replaceWith(morphed)
    }

    // Clean up previous element if it isn't original element
    if (element !== original) {
      renderer.cache("*").delete(element)
    }

    return { element: morphed }
  },
} as const satisfies Directive

/** Default exports. */
export default _is