|
| 1 | +import { ASTNode, CommentNode, parse, ParseOptions, stringify, TagNode, TextNode } from "html-parse-stringify"; |
| 2 | + |
| 3 | +// Test parse function |
| 4 | +const ast: ASTNode[] = parse("<div class=\"oh\"><p>hi</p></div>"); |
| 5 | + |
| 6 | +// Test parse with options |
| 7 | +const astWithOpts: ASTNode[] = parse("<div><my-component></my-component></div>", { |
| 8 | + components: { |
| 9 | + "my-component": true, |
| 10 | + }, |
| 11 | +}); |
| 12 | + |
| 13 | +// Test stringify function |
| 14 | +const htmlString: string = stringify(ast); |
| 15 | + |
| 16 | +// Test roundtrip |
| 17 | +const ast2: ASTNode[] = parse("<p>hello</p>"); |
| 18 | +const html2: string = stringify(ast2); |
| 19 | + |
| 20 | +// Test node type narrowing |
| 21 | +for (const node of ast) { |
| 22 | + if (node.type === "tag") { |
| 23 | + const tagNode: TagNode = node; |
| 24 | + const name: string = tagNode.name; |
| 25 | + const attrs: { [key: string]: string } = tagNode.attrs; |
| 26 | + const isVoid: boolean = tagNode.voidElement; |
| 27 | + const children: ASTNode[] = tagNode.children; |
| 28 | + } else if (node.type === "text") { |
| 29 | + const textNode: TextNode = node; |
| 30 | + const content: string = textNode.content; |
| 31 | + } else if (node.type === "comment") { |
| 32 | + const commentNode: CommentNode = node; |
| 33 | + const comment: string = commentNode.comment; |
| 34 | + } else if (node.type === "component") { |
| 35 | + const name: string = node.name; |
| 36 | + const attrs: { [key: string]: string } = node.attrs; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Test with complex HTML |
| 41 | +const complexAst = parse(` |
| 42 | + <div id="main" class="container"> |
| 43 | + <h1>Title</h1> |
| 44 | + <!-- A comment --> |
| 45 | + <p>Some <strong>bold</strong> text</p> |
| 46 | + <img src="image.jpg" /> |
| 47 | + </div> |
| 48 | +`); |
| 49 | + |
| 50 | +// Test roundtrip |
| 51 | +const original = "<div><p>test</p></div>"; |
| 52 | +const roundtrip: string = stringify(parse(original)); |
0 commit comments