robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinfragment: handle nonempty elements without children8188f2c

push-srxvuswpkqxx
6.0 KiB231 linesraw
1const std = @import("std");
2
3const zlua = @import("zlua");
4const Lua = zlua.Lua;
5const fern = @import("fern");
6
7const display = @import("lua/lua_display.zig");
8const str = @import("lua/lua_str.zig");
9const maivi = @import("root.zig");
10
11// void elements
12// https://developer.mozilla.org/en-US/docs/Glossary/Void_element
13const VOID_ELEMENTS = [_][]const u8{
14    "area",
15    "base",
16    "br",
17    "col",
18    "embed",
19    "hr",
20    "img",
21    "input",
22    "link",
23    "meta",
24    "source",
25    "wbr",
26};
27
28const ElementConfig = struct {
29    close: bool = true,
30    empty: bool = false,
31    raw: bool = false,
32
33    pub fn default(ntype: ?[]const u8) @This() {
34        const name = ntype orelse return .{};
35
36        for (VOID_ELEMENTS) |n| if (std.mem.eql(u8, name, n)) return .{
37            .close = false,
38        };
39
40        return .{};
41    }
42};
43
44pub const Error = error{
45    ExpectedTable,
46    ExpectedString,
47} || error{
48    LuaTableMissingValue,
49    LuaValueNotATable,
50    LuaRuntime,
51    LuaMsgHandler,
52    UnexpectedStackSize,
53} || std.Io.Writer.Error || std.mem.Allocator.Error;
54fn elem(l: *Lua, w: *std.Io.Writer) Error!void {
55    const stack_size_on_entry = l.getTop();
56
57    if (!l.isTable(-1)) return error.ExpectedTable;
58
59    const name: ?[]u8 = blk: {
60        const ltype_type = l.getField(-1, "type");
61        defer l.pop(1);
62        if (ltype_type == .nil) break :blk null;
63        if (ltype_type != .string) return error.ExpectedString;
64
65        l.pushValue(-1);
66        defer l.pop(1);
67        const namez = try l.toString(-1);
68        break :blk try maivi.allocator.dupe(u8, namez);
69    };
70    defer if (name) |m| maivi.allocator.free(m);
71
72    const config: ElementConfig = blk: {
73        l.getMetatable(-1) catch break :blk null;
74        defer l.pop(1);
75
76        const ltype_config = l.getField(-1, "config");
77        defer l.pop(1);
78        if (ltype_config == .nil) break :blk null;
79        if (ltype_config != .table) return error.ExpectedTable;
80        break :blk try l.toStruct(ElementConfig, null, false, -1);
81    } orelse .default(name);
82
83    if (name) |n| {
84        try w.writeByte('<');
85        try w.writeAll(n);
86    }
87
88    // props
89    props: {
90        const ltype_props = l.getField(-1, "props");
91        defer l.pop(1);
92        if (ltype_props == .nil) break :props;
93        if (ltype_props != .table) return error.ExpectedTable;
94
95        try writeProps(l, w);
96    }
97
98    {
99        const nchildren: usize = nchildren: {
100            const ltype_children = l.getField(-1, "children");
101            if (ltype_children == .nil) break :nchildren 0;
102            if (ltype_children != .table) return error.ExpectedTable;
103            break :nchildren l.lenRaw(-1);
104        };
105        // -1 => children; -2 => elem
106        defer l.pop(1); // pops "children"
107
108        if (config.empty and nchildren == 0) {
109            if (name != null) try w.writeAll(" />");
110
111            try w.flush();
112            return;
113        }
114
115        if (name != null) try w.writeByte('>');
116
117        // children
118        if (nchildren > 0)
119            try writeChildren(l, w, config);
120    }
121
122    // close
123    if (config.close) if (name) |n| {
124        try w.writeAll("</");
125        try w.writeAll(n);
126        try w.writeByte('>');
127    };
128
129    if (l.getTop() != stack_size_on_entry) return error.UnexpectedStackSize;
130
131    try w.flush();
132}
133
134fn writeProps(l: *Lua, w: *std.Io.Writer) !void {
135    var arena: std.heap.ArenaAllocator = .init(maivi.allocator);
136    defer arena.deinit();
137    var allocator = arena.allocator();
138
139    l.pushValue(-1);
140    defer l.pop(1);
141
142    l.pushNil();
143    // stack now contains: -1 => nil; -2 => table
144
145    while (l.next(-2)) {
146        // stack now contains: -1 => value; -2 => key; -3 => table
147
148        try w.writeByte(' ');
149
150        const k = k: {
151            l.pushValue(-2);
152            defer l.pop(1);
153
154            const kz = try l.toString(-1);
155            break :k try allocator.dupe(u8, kz);
156        };
157
158        // uses -1 => value
159        _ = try display.attr(l);
160        // stack now contains: -1 => value (parsed); -2 => value; -3 => key; -4 => table
161
162        // uses -1 => value (parsed)
163        _ = try str.escape(l);
164        // stack now contains: -1 => value (escaped); -2 => value (parsed); -3 => value; -4 => key; -5 => table
165
166        const vz = try l.toString(-1);
167        const v = try allocator.dupe(u8, vz);
168
169        try w.writeAll(k);
170        try w.writeByte('=');
171        try w.writeByte('"');
172        try w.writeAll(v);
173        try w.writeByte('"');
174
175        // pop value + parsed + escaped, leaving original key
176        l.pop(3);
177        // stack now contains: -1 => key; -2 => table
178    }
179}
180
181fn writeChildren(l: *Lua, w: *std.Io.Writer, config: ElementConfig) !void {
182    var arena: std.heap.ArenaAllocator = .init(maivi.allocator);
183    defer arena.deinit();
184    var allocator = arena.allocator();
185
186    l.pushValue(-1);
187    defer l.pop(1);
188
189    l.pushNil();
190    // stack now contains: -1 => nil; -2 => table
191
192    while (l.next(-2)) {
193        // stack now contains: -1 => value; -2 => key; -3 => table
194
195        if (l.isFunction(-1)) {
196            try maivi.lua.pcall(l, .{ .results = 1 });
197        }
198
199        if (!l.isTable(-1)) {
200            // uses -1 => value
201            _ = try display.elem(l);
202            // stack now contains: -1 => value (parsed); -2 => value; -3 => key; -4 => table
203
204            if (!config.raw) {
205                // uses -1 => value (parsed)
206                _ = try str.escape(l);
207                // stack now contains: -1 => value (escaped); -2 => value (parsed); -3 => value; -4 => key; -5 => table
208            }
209
210            const vz = try l.toString(-1);
211            const v = try allocator.dupe(u8, vz);
212
213            if (!config.raw)
214                l.pop(1); // pop escaped
215            l.pop(1); // pop parsed
216
217            try w.writeAll(v);
218        } else {
219            // uses -1 => value
220            try elem(l, w);
221        }
222
223        // pop value, leaving original key
224        l.pop(1);
225        // stack now contains: -1 => key; -2 => table
226    }
227}
228
229pub fn render(l: *Lua, w: *std.Io.Writer) !void {
230    try elem(l, w);
231}