All files / is / mod.ts

100.00% Branches 9/9
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
x13
x14
x14
 
 
x20
x13
x15
x15
x13
x13
 
 
x13
x18
x18
x18
 
 
x18
x18
x22
x22
x18
x18
x18
 
 
x13
x14
x14
 
x54
x13
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 Directive

/** Default exports. */
export default _is