WHATWG HTML5 spec-compliant parser for MoonBit
Dependencies
///|
test "basic parsing" {
let doc = @html5.parse(
"<html><head><title>Hello</title></head><body><p>World</p></body></html>",
)
@debug.assert_eq(
doc.dump(),
(
#|<html>
#| <head>
#| <title>
#| "Hello"
#| <body>
#| <p>
#| "World"
),
)
}///|
test "error recovery - unclosed tags" {
let doc = @html5.parse("<p>First<p>Second<p>Third")
@debug.assert_eq(
doc.dump(),
(
#|<html>
#| <head>
#| <body>
#| <p>
#| "First"
#| <p>
#| "Second"
#| <p>
#| "Third"
),
)
}///|
test "error recovery - misnested tags" {
let doc = @html5.parse("<b><i>Bold and Italic</b> Just Italic</i>")
@debug.assert_eq(
doc.dump(),
(
#|<html>
#| <head>
#| <body>
#| <b>
#| <i>
#| "Bold and Italic"
#| <i>
#| " Just Italic"
),
)
}///|
test "serialize to html" {
let doc = @html5.parse("<div class=\"container\"><span>Hello</span></div>")
assert_true(
doc.to_html()
is "<html><head></head><body><div class=\"container\"><span>Hello</span></div></body></html>",
)
}///|
test "parse with errors" {
let (doc, errors) = @html5.parse_with_errors("<p>Test</p attr>")
assert_true((errors.length() > 0) is true)
@debug.assert_eq(
doc.dump(),
(
#|<html>
#| <head>
#| <body>
#| <p>
#| "Test"
),
)
}///|
test "tokenization" {
let (tokens, _errors) = @html5.tokenize("<div>Hello</div>")
assert_true(
tokens[0] is @html5.StartTag(name="div", attrs=[], self_closing=false),
)
assert_true(tokens[1] is @html5.Character('H'))
assert_true(tokens[2] is @html5.Character('e'))
}///|
test "dom access" {
let doc = @html5.parse("<div id=\"main\"><p class=\"text\">Content</p></div>")
// Get body element
let body_id = doc.body_element
let children = doc.get_children(body_id)
// Get the div
let div_id = children[0]
assert_true(doc.get_tag_name(div_id) is Some("div"))
assert_true(doc.get_attribute(div_id, "id") is Some("main"))
// Get the p element
let p_id = doc.get_children(div_id)[0]
assert_true(doc.get_attribute(p_id, "class") is Some("text"))
assert_true(doc.get_text_content(p_id) is "Content")
}///|
test "character references" {
let doc = @html5.parse("<p>& < > © © ©</p>")
let p_id = doc.get_children(doc.body_element)[0]
assert_true(doc.get_text_content(p_id) is "& < > \u{00A9} \u{00A9} \u{00A9}")
}///|
test "svg support" {
let doc = @html5.parse(
"<div><svg><circle cx=\"50\" cy=\"50\" r=\"40\"/></svg></div>",
)
@debug.assert_eq(
doc.dump(),
(
#|<html>
#| <head>
#| <body>
#| <div>
#| <svg svg>
#| <svg circle>
#| cx="50"
#| cy="50"
#| r="40"
),
)
}WHATWG HTML5 spec-compliant parser for MoonBit
Dependencies