aboutsummaryrefslogtreecommitdiff
path: root/src/z/App/root.zig
blob: 326f3c0effd0d42aae057943c2626fb5c8303628 (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
const builtin = @import("builtin");
const std = @import("std");
const h = @import("html");

pub const Options = struct {
    name: []const u8,
    globals: []const Global,

    pub const Global = struct {
        name: []const u8,
        type: type,
    };
};

pub fn App(comptime options: Options) type {
    if (builtin.target.cpu.arch.isWasm()) {
        var names: [options.globals.len][]const u8 = undefined;
        var types: [options.globals.len]type = undefined;
        var attrs: [options.globals.len]std.builtin.Type.StructField.Attributes = undefined;

        for (options.globals, 0..) |field, index| {
            names[index] = field.name;
            types[index] = field.type;
            attrs[index] = .{};
        }

        const G = @Struct(.auto, null, &names, &types, &attrs);
        return struct {
            globals: G = g: {
                var gl: G = undefined;

                for (options.globals, 1..) |field, id| {
                    @field(gl, field.name) = @ptrFromInt(id);
                }

                break :g gl;
            },

            pub const init: @This() = .{};
        };
    } else {
        return struct {
            html: []const u8 = h.Element.native(.html, .{}, .children(&.{
                .native(.head, .{}, .children(&.{
                    .native(.title, .{}, .content(options.name)),
                    .native(.meta, .{
                        .name = "viewport",
                        .content = "width=device-width, initial-scale=1.0",
                    }, .void),
                })),
                .native(.body, .{}, .children(&.{
                    .native(.script, .{}, .content(@embedFile("object-store.js"))),
                    .native(.script, .{}, .content(reg: {
                        var register_code: []const u8 = "";

                        for (options.globals, 1..) |field, id| {
                            register_code = register_code ++ std.fmt.comptimePrint(
                                "ObjectStore.registerObject({}, {s});",
                                .{ id, field.name },
                            );
                        }

                        break :reg register_code;
                    })),
                    .native(.script, .{}, .content(@embedFile("main.js"))),
                })),
            })).toDocument(),

            pub const init: @This() = .{};
        };
    }
}