all files / src/hyperscript/ VNode.ts

100% Statements 30/30
100% Branches 4/4
100% Functions 6/6
100% Lines 28/28
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87        957×   957× 957× 957× 957× 957× 957× 957× 957×                 591×                       305×                                                                      
import { VNode, VNodeProps, VNodeEvents } from '../types'
 
export const SVG_NAMESPACE = `http://www.w3.org/2000/svg`
 
const defaultTextNodeData: VNodeProps<Element> = {}
 
export class MostlyVNode<T extends Node> implements VNode<T> {
  public parent: MostlyVNode<Element> | undefined = undefined
 
  constructor(
    public tagName: string | undefined,
    public props: VNodeProps<Element>,
    public children: Array<VNode> | undefined,
    public element: T | undefined,
    public text: string | undefined,
    public key: string | number | undefined,
    public scope: string | undefined,
    public namespace: string | undefined
  ) {}
 
  public static create<N extends Node>(
    tagName: string | undefined,
    props: VNodeProps<Element>,
    children: Array<VNode> | undefined,
    text: string | undefined
  )
  {
    return new MostlyVNode(
      tagName,
      props,
      children,
      undefined,
      text,
      props.key,
      props.scope,
      undefined
    )
  }
 
  public static createText(text: string): MostlyVNode<Text> {
    return new MostlyVNode<Text>(
      undefined,
      defaultTextNodeData,
      undefined,
      undefined,
      text,
      undefined,
      undefined,
      undefined
    )
  }
 
  public static createSvg(
    tagName: string | undefined,
    props: VNodeProps<SVGElement, VNodeEvents<SVGElement, SVGElementEventMap>>,
    children: Array<VNode> | undefined,
    text: string | undefined
  )
  {
    return new MostlyVNode<SVGElement>(
      tagName,
      props as any,
      children,
      undefined,
      text,
      props.key,
      props.scope,
      SVG_NAMESPACE
    )
  }
}
 
export function addSvgNamespace(vNode: MostlyVNode<Node>): void {
  vNode.namespace = SVG_NAMESPACE
 
  if (Array.isArray(vNode.children)) {
    const children = vNode.children
    const childCount = children.length
 
    for (let i = 0; i < childCount; ++i) {
      const child = children[i]
 
      if (child.tagName !== 'foreignObject') addSvgNamespace(child as MostlyVNode<Node>)
    }
  }
}