All files / if / mod.ts

100.00% Branches 6/6
100.00% Lines 19/19
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
 
x10
 
 
 
 
 
 
 
 
 
x10
x10
x10
x10
x59
x59
 
x126
x67
x201
x67
 
x145
x430
x344
x86
x59
x59
x10
 
 
x10






























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

/**
 * `*if` directive.
 *
 * @internal `_directive.value` Force the directive to use specified value rather than the attribute value.
 * @internal `_directive.expression` Set the original expression for the directive if element is commented out.
 * @internal `_directive.directive` Set the original directive name for the directive if element is commented out.
 */
export const _if = {
  name: "*if",
  phase: Phase.TOGGLE,
  async execute(renderer, element, { attributes: [attribute], ...options }) {
    const result = Boolean(await renderer.evaluate(element, arguments[2]._directive?.value ?? attribute.value, options))
    switch (true) {
      // Switch comment to element if truthy
      case result && (renderer.isComment(element)) && (renderer.cache("*").has(element)): {
        const original = renderer.uncomment(element)
        return { element: original }
      }
      // Switch element to comment if falsy
      case (!result) && (renderer.isHtmlElement(element)): {
        const comment = renderer.comment(element, { expression: attribute.value, directive: _if.name, ...arguments[2]._directive })
        return { element: comment, final: true }
      }
    }
  },
} as Directive & { execute: NonNullable<Directive["execute"]> }

/** Default exports. */
export default _if