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

pub const panic = z.env.panic;
pub const std_options: std.Options = .{
    .logFn = z.env.logFn,
};

pub const app: z.App(.{ .name = "Memora" }, .{
    .window = *z.Env.Object,
    .Object = *z.Env.Object,
}) = .init;

const js = struct {
    const window = app.globals.window;
    const Object = app.globals.Object;
};

fn run_wrapped() !void {
    var env: z.Env = .init(std.heap.wasm_allocator);
    defer env.deinit();

    _ = js.window.set(&env, "my_prop", 45);
    _ = js.window.delete(&env, "my_prop");

    const console = try app.globals.window.get(&env, "console").await(&env, .object);
    const location = try app.globals.window.get(&env, "location").await(&env, .object);

    const obj = app.globals.Object.new(&env);
    const hostname = try location.get(&env, "hostname").await(&env, .string);
    defer std.heap.wasm_allocator.free(hostname);

    const call = console.call(
        &env,
        .log,
        .{
            "hello, wasm!",
            try obj.await(&env),
            hostname,
        },
    );

    try call.await(&env, .undefined);

    _ = env.free(console);
}

fn run() callconv(.c) void {
    run_wrapped() catch |e| {
        var buffer: [1024]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buffer);

        writer.print("{}", .{e}) catch unreachable;

        z.env.console.log(writer.buffered());
    };
}

comptime {
    if (builtin.target.cpu.arch.isWasm()) {
        @export(&run, .{ .name = "run" });
    }
}