import Base # A DOM tree: elements with attributes and children, and text nodes. type Attr is Data: Attr{name: String, value: String} type Node is Data: Element{tag: String, attrs: +List, children: +List} # (TextNode, not Text: Bend 2.0.38 gave Base's Event a constructor Text, and # constructor names are one namespace with Base) TextNode{content: String, id: U32} def tag_of(n: Node) -> String: match n: case Element{tag, attrs, children}: tag case TextNode{content, tnid}: SNil{} def attrs_of(n: Node) -> List<&2, Attr>: match n: case Element{tag, attrs, children}: attrs case TextNode{content, tnid}: Nil{} def children_of(n: Node) -> List<&2, Node>: match n: case Element{tag, attrs, children}: children case TextNode{content, tnid}: Nil{} # A comment is kept as an element with this tag, its text in a "data" # attribute; it is not an element to anything that asks for elements, its # text is not text content, and nothing renders it. def comment_tag() -> String: "#comment" def is_comment(+tag: String) -> Bool: String.eq(tag, "#comment") def only_elements(xs: List<&2, Node>) -> List<&2, Node>: match xs: case Nil{}: Nil{} case Con{h, t}: match h: case Element{+tag, attrs, children}: +rest = only_elements(t) Bool.pick(List<&2, Node>, is_comment(tag), rest, Element{tag, attrs, children} <> rest) case TextNode{content, tnid}: only_elements(t) def element_children(n: Node) -> List<&2, Node>: only_elements(children_of(n)) def attr_go(xs: List<&2, Attr>, +name: String, acc: String) -> String: match xs: case Nil{}: acc case Con{a, t}: match a: case Attr{+n, v}: attr_go(t, name, Bool.pick(String, String.eq(n, name), v, acc)) # The value of attribute `name` (the first one wins in HTML), or "". def attr(n: Node, +name: String) -> String: match n: case Element{tag, attrs, children}: attr_go(List.reverse(&2, Attr, attrs), name, SNil{}) case TextNode{content, tnid}: SNil{} # A shadow root is kept as a child of its host with this tag; the host's # textContent, serialization and queries do not see into it. def is_shadow(+tag: String) -> Bool: String.eq(tag, "#shadow-root") # A