aboutsummaryrefslogtreecommitdiff
path: root/src/dom/Element.zig
blob: 3aa49864b136d3380126b14d4cc04ffe47e5b79a (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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
const std = @import("std");
const Allocator = std.mem.Allocator;
const eql = std.mem.eql;
const html = @import("html.zig");

pub const Kind = enum {
    void,
    content,
    literal,
};

const Self = @This();

kind: Kind,
alloc: Allocator,
tag: ?[]const u8 = null,
attributes: std.StringArrayHashMap([]const u8),
class_list: std.BufSet,
content: std.ArrayList(Self) = .empty,
literal: ?[]const u8 = null,

/// Init a new Element with the given kind.
/// The tag will never be escaped.
pub fn init(alloc: Allocator, knd: Kind, tag: []const u8) Self {
    return .{
        .kind = knd,
        .alloc = alloc,
        .tag = tag,
        .attributes = .init(alloc),
        .class_list = .init(alloc),
    };
}

/// Init a new literal element.
/// The literal content will never be escaped, see initLitEscaped if you want to escape it.
/// The literal content must be free'd by the allocator (use Allocator.dupe if you want to use a const string).
pub fn initLit(alloc: Allocator, literal: []const u8) Self {
    return .{
        .kind = .literal,
        .alloc = alloc,
        .literal = literal,
        .attributes = .init(alloc),
        .class_list = .init(alloc),
    };
}

/// Init a new literal element that is escaped.
/// The literal content will be escaped, see initLit if you don't want this behavior.
pub fn initLitEscaped(alloc: Allocator, literal: []const u8) !Self {
    return .initLit(alloc, try html.escape(alloc, literal));
}

pub fn deinit(self: *Self) void {
    self.attributes.deinit();
    self.class_list.deinit();
    for (self.content.items) |it| {
        var v = it;
        v.deinit();
    }
    self.content.deinit(self.alloc);
    if (self.literal) |it| self.alloc.free(it);
}

pub fn render(self: *Self, alloc: Allocator) ![]const u8 {
    const attr = try self.renderAttribute(alloc);
    defer if (attr) |it| alloc.free(it);
    var acc = try std.ArrayList(u8).initCapacity(alloc, 2);
    errdefer acc.deinit(alloc);
    if (self.tag) |tag| {
        try acc.append(alloc, '<');
        try acc.appendSlice(alloc, tag);
        if (attr) |it| try acc.appendSlice(alloc, it);
        try acc.append(alloc, '>');
    }
    switch (self.kind) {
        .void => return acc.toOwnedSlice(alloc),
        .content => {
            for (self.content.items) |it| {
                var v = it;
                const sub = try v.render(alloc);
                defer alloc.free(sub);
                try acc.appendSlice(alloc, sub);
            }
        },
        .literal => try acc.appendSlice(alloc, self.literal.?),
    }
    if (self.tag) |tag| {
        try acc.appendSlice(alloc, "</");
        try acc.appendSlice(alloc, tag);
        try acc.append(alloc, '>');
    }
    return acc.toOwnedSlice(alloc);
}

fn renderAttribute(self: *Self, alloc: Allocator) !?[]const u8 {
    const class = try self.renderClass(alloc);
    defer if (class) |it| alloc.free(it);
    if (class) |it| try self.setAttribute("class", it);
    var iter = self.attributes.iterator();
    if (iter.len == 0) return null;
    var acc = try std.ArrayList(u8).initCapacity(alloc, 2);
    errdefer acc.deinit(alloc);
    try acc.append(alloc, ' ');
    var i: usize = 0;
    while (iter.next()) |it| : (i += 1) {
        try acc.appendSlice(alloc, it.key_ptr.*);
        try acc.appendSlice(alloc, "=\"");
        const escape = try html.escape(alloc, it.value_ptr.*);
        defer alloc.free(escape);
        try acc.appendSlice(alloc, escape);
        try acc.append(alloc, '"');
        if (i < iter.len - 1) try acc.append(alloc, ' ');
    }
    return try acc.toOwnedSlice(alloc);
}

fn renderClass(self: *const Self, alloc: Allocator) !?[]const u8 {
    var iter = self.class_list.iterator();
    if (iter.len == 0) return null;
    const n = self.class_list.count();
    var acc = try std.ArrayList(u8).initCapacity(alloc, 2);
    errdefer acc.deinit(alloc);
    var i: usize = 0;
    while (iter.next()) |it| : (i += 1) {
        try acc.appendSlice(alloc, it.*);
        if (i < n - 1) try acc.append(alloc, ' ');
    }
    return try acc.toOwnedSlice(alloc);
}

pub fn setAttribute(self: *Self, k: []const u8, v: []const u8) !void {
    try self.attributes.put(k, v);
}

pub fn removeAttribute(self: *Self, k: []const u8) void {
    _ = self.attributes.orderedRemove(k);
}

pub fn hasAttribute(self: *Self, k: []const u8) bool {
    return self.attributes.contains(k);
}

pub fn appendClass(self: *Self, v: []const u8) !void {
    try self.class_list.insert(v);
}

pub fn hasClass(self: *Self, v: []const u8) bool {
    return self.class_list.contains(v);
}

pub fn removeClass(self: *Self, v: []const u8) void {
    self.class_list.remove(v);
}

pub fn appendContent(self: *Self, content: Self) !void {
    return self.content.append(self.alloc, content);
}

pub fn initImg(alloc: Allocator, src: []const u8, alt: []const u8) !Self {
    var el = init(alloc, .void, "img");
    try el.setAttribute("src", src);
    try el.setAttribute("alt", alt);
    return el;
}

pub fn initContent(alloc: Allocator, tag: []const u8, content: []Self) !Self {
    var el = init(alloc, .content, tag);
    for (content) |it| try el.appendContent(it);
    return el;
}

/// Init a paragraph tag with an automatically escaped content.
pub fn initParagraph(alloc: Allocator, content: []const u8) !Self {
    var el = init(alloc, .content, "p");
    try el.appendContent(initLitEscaped(alloc, content));
    return el;
}

fn doTest(alloc: Allocator, el: *Self, exp: []const u8) !void {
    const got = try el.render(alloc);
    defer alloc.free(got);
    std.testing.expect(eql(u8, got, exp)) catch |err| {
        std.debug.print("{s}\n", .{got});
        return err;
    };
}

test "void element" {
    var arena = std.heap.DebugAllocator(.{}).init;
    defer _ = arena.deinit();
    const alloc = arena.allocator();

    var br = init(alloc, .void, "br");
    defer br.deinit();

    try doTest(alloc, &br, "<br>");

    var img = init(alloc, .void, "img");
    defer img.deinit();
    try img.setAttribute("src", "foo");
    try img.setAttribute("alt", "bar");

    try doTest(alloc, &img, "<img src=\"foo\" alt=\"bar\">");

    var img2 = try initImg(alloc, "foo", "bar");
    defer img2.deinit();
    try doTest(alloc, &img2, "<img src=\"foo\" alt=\"bar\">");
}

test "content element" {
    var arena = std.heap.DebugAllocator(.{}).init;
    defer _ = arena.deinit();
    const alloc = arena.allocator();

    var p = init(alloc, .content, "p");
    defer p.deinit();

    var content = initLit(alloc, try alloc.dupe(u8, "hello world"));
    try p.appendContent(content);

    try doTest(alloc, &content, "hello world");
    try doTest(alloc, &p, "<p>hello world</p>");

    var p_managed = try initParagraph(alloc, "hello world");
    defer p_managed.deinit();

    try doTest(alloc, &p_managed, "<p>hello world</p>");

    var div = init(alloc, .content, "div");
    defer div.deinit();
    try div.appendClass("foo-bar");
    try div.appendContent(try initParagraph(alloc, "hello world"));
    try div.appendContent(try initImg(alloc, "example.org", "example"));

    try doTest(alloc, &div, "<div class=\"foo-bar\"><p>hello world</p><img src=\"example.org\" alt=\"example\"></div>");
}