aboutsummaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 66a762e047f8d50b5ba5925356ab2165429c0ebc (plain)
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
const std = @import("std");
const c = @import("c.zig");

const example = @embedFile("example.html");

pub fn main() !void {
    var html_tree: c.HtmlTree = undefined;
    if(c.html_parse_to_tree(&html_tree, example.ptr, example.len) != 0)
        return error.FailedToParseHtml;
    defer c.html_tree_deinit(&html_tree);
    html_node_print(&html_tree.root_node);

    const html = html_tree.root_node.first_child;
    const body = html.*.node.first_child;
    const div = c.html_node_find_child(&body.*.node, "div", "class", "cool") orelse error.UnableToFindHtmlNode;
    std.debug.print("div {any}\n", .{div});
}

fn html_attributes_print(attr: [*c]c.HtmlAttribute) void {
    var a = attr;
    while(a != null) {
        std.debug.print("{s}=\"{s}\" ", .{html_string_view_to_slice(a.*.key), html_string_view_to_slice(a.*.value)});
        a = a.*.next;
    }
}

fn html_node_child_print(node_child: [*c]c.HtmlNodeChild) void {
    var node = node_child;
    while(node != null) {
        html_node_print(&node.*.node);
        node = node.*.next;
    }
}

fn html_node_print(node: [*c]c.HtmlNode) void {
    const n: *c.HtmlNode = @ptrCast(node);
    switch(n.node_type) {
        c.HTML_NODE_NODE => {
            std.debug.print("\n<{s} ", .{html_string_view_to_slice(n.name_or_value)});
            html_attributes_print(n.first_attr);
            std.debug.print(">", .{});
            html_node_child_print(n.first_child);
            std.debug.print("</{s}>\n", .{html_string_view_to_slice(n.name_or_value)});
        },
        c.HTML_NODE_TEXT => {
            std.debug.print("{s}", .{html_string_view_to_slice(n.name_or_value)});
        },
        c.HTML_NODE_JS => {
            std.debug.print("{s}", .{html_string_view_to_slice(n.name_or_value)});
        },
        else => {},
    }
}

fn html_string_view_to_slice(view: c.HtmlStringView) []const u8 {
    if(view.size == 0) {
        return "";
    } else {
        return view.data[0..view.size];
    }
}