aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/api/hello-body.zig4
-rw-r--r--src/api/hello-json.zig4
-rw-r--r--src/api/hello-param.zig6
-rw-r--r--src/api/root.zig2
-rw-r--r--src/app/root.zig13
-rw-r--r--src/db/sqlite.zig82
-rw-r--r--src/db/sqlite_new.zig32
-rw-r--r--src/html/Element.zig5
-rw-r--r--src/http/Response.zig51
-rw-r--r--src/http/handler/static.zig6
-rw-r--r--src/http/serve.zig21
-rw-r--r--src/main.zig16
-rw-r--r--src/web/component/image/index.css0
-rw-r--r--src/web/component/image/index.html2
-rw-r--r--src/web/component/image/index.js1
-rw-r--r--src/web/component/image/root.zig8
-rw-r--r--src/web/component/root.zig6
-rw-r--r--src/web/component/timeline/index.css18
-rw-r--r--src/web/component/timeline/index.html2
-rw-r--r--src/web/component/timeline/index.js96
-rw-r--r--src/web/component/timeline/root.zig8
-rw-r--r--src/web/index.css20
-rw-r--r--src/web/index.html2
-rw-r--r--src/web/index.js0
-rw-r--r--src/web/pinch.js82
-rw-r--r--src/web/root.zig27
-rw-r--r--src/z/AppBundle.zig35
-rw-r--r--src/z/Component.zig18
-rw-r--r--src/z/Env/Future.zig29
-rw-r--r--src/z/Env/call.zig15
-rw-r--r--src/z/Env/js.zig9
-rw-r--r--src/z/Env/root.zig64
-rw-r--r--src/z/Env/value.zig36
-rw-r--r--src/z/File.zig18
-rw-r--r--src/z/Minifier.zig168
-rw-r--r--src/z/app/main.js245
-rw-r--r--src/z/app/root.zig20
-rw-r--r--src/z/env/console.zig24
-rw-r--r--src/z/env/root.zig2
-rw-r--r--src/z/root.zig59
-rw-r--r--src/z/z.js82
41 files changed, 647 insertions, 691 deletions
diff --git a/src/api/hello-body.zig b/src/api/hello-body.zig
index 2e5a09e..43afb87 100644
--- a/src/api/hello-body.zig
+++ b/src/api/hello-body.zig
@@ -12,9 +12,9 @@ const Body = struct {
};
fn post(request: Ctx.Request) Response {
- const body = request.json(Body) catch return .bad_request(.void);
+ const body = request.json(Body) catch return .badRequest(.void);
- return .ok_or_error(.json(request.arena, .{
+ return .okOrError(.json(request.arena, .{
.value = body.value,
}));
}
diff --git a/src/api/hello-json.zig b/src/api/hello-json.zig
index 7c96c29..12f1e72 100644
--- a/src/api/hello-json.zig
+++ b/src/api/hello-json.zig
@@ -2,13 +2,13 @@ const http = @import("http");
const Context = http.handler.Context;
const Response = http.Response;
-const Ctx = Context(.{ "hello-json" });
+const Ctx = Context(.{"hello-json"});
pub const ctx: Ctx = .{
.get = get,
};
fn get(request: Ctx.Request) Response {
- return .ok_or_error(.json(request.arena, .{
+ return .okOrError(.json(request.arena, .{
.value = 42,
.message = "Hello, Json!",
}));
diff --git a/src/api/hello-param.zig b/src/api/hello-param.zig
index ba798af..b67212b 100644
--- a/src/api/hello-param.zig
+++ b/src/api/hello-param.zig
@@ -8,7 +8,9 @@ pub const ctx: Ctx = .{
};
fn get(request: Ctx.Request) Response {
- const value = request.params.value.as(usize) catch return .bad_request(.string("parameter needs to be an int"));
+ const value = request.params.value.as(usize) catch return .badRequest(.string("parameter needs to be an int"));
- return .ok_or_error(.json(request.arena, .{ .value = value, }));
+ return .okOrError(.json(request.arena, .{
+ .value = value,
+ }));
}
diff --git a/src/api/root.zig b/src/api/root.zig
index 7570a76..2a54b91 100644
--- a/src/api/root.zig
+++ b/src/api/root.zig
@@ -16,7 +16,7 @@ pub const interfaces: []const Interface = ifs: {
var ifs: []const Interface = &.{};
for (modules) |module| {
- const interface: []const Interface = &.{ module.ctx.interface() };
+ const interface: []const Interface = &.{module.ctx.interface()};
ifs = ifs ++ interface;
}
diff --git a/src/app/root.zig b/src/app/root.zig
new file mode 100644
index 0000000..13d26b8
--- /dev/null
+++ b/src/app/root.zig
@@ -0,0 +1,13 @@
+const std = @import("std");
+pub const z = @import("z");
+
+export fn run() void {
+ var env: z.Env = .init(std.heap.wasm_allocator);
+ defer env.deinit();
+
+ var ref = env.getProp(1, "console") catch unreachable;
+ var buffer: [255]u8 = undefined;
+ var writer: std.Io.Writer = .fixed(&buffer);
+ writer.print("hello, wasm: {}", .{ref.await(&env, .object)}) catch unreachable;
+ z.env.console.log(writer.buffered());
+}
diff --git a/src/db/sqlite.zig b/src/db/sqlite.zig
index 55cb60a..0ef1b20 100644
--- a/src/db/sqlite.zig
+++ b/src/db/sqlite.zig
@@ -8,7 +8,7 @@ const Writer = std.Io.Writer;
pub fn Database(comptime T: type) type {
const tables = switch (@typeInfo(T)) {
.@"struct" => |s| s.fields,
- else => @compileError("Database schema must be of type `struct`"),
+ else => @compileError("Database schema must be of type `struct`"),
};
// NOTE: `std.math.log2_int_ceil(@TypeOf(tables.len), tables.len)` panics
@@ -16,14 +16,14 @@ pub fn Database(comptime T: type) type {
// a (useless) schema that does not define any tables.
const TagIntTables = @Int(.unsigned, @bitSizeOf(@TypeOf(tables.len)) - @clz(tables.len));
- var table_names : [tables.len][]const u8 = undefined;
- var table_types : [tables.len]type = undefined;
+ var table_names: [tables.len][]const u8 = undefined;
+ var table_types: [tables.len]type = undefined;
var table_values: [tables.len]TagIntTables = undefined;
inline for (&table_names, &table_types, &table_values, tables, 0..) |*table_name, *table_type, *table_value, table, table_index| {
const columns = switch (@typeInfo(table.type)) {
.@"struct" => |s| s.fields,
- else => @compileError("Table `" ++ table.name ++ "` must be of type `struct`"),
+ else => @compileError("Table `" ++ table.name ++ "` must be of type `struct`"),
};
// NOTE: A table must have at least one column; see
@@ -32,8 +32,8 @@ pub fn Database(comptime T: type) type {
const TagIntColumns = @Int(.unsigned, std.math.log2_int_ceil(@TypeOf(columns.len), columns.len));
- var column_names : [columns.len][]const u8 = undefined;
- var column_types : [columns.len]type = undefined;
+ var column_names: [columns.len][]const u8 = undefined;
+ var column_types: [columns.len]type = undefined;
var column_values: [columns.len]TagIntColumns = undefined;
inline for (&column_names, &column_types, &column_values, columns, 0..) |*column_name, *column_type, *column_value, column, column_index| {
@@ -49,15 +49,15 @@ pub fn Database(comptime T: type) type {
}
const TagColumns = @Enum(TagIntColumns, .exhaustive, &column_names, &column_values);
- const Columns = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
+ const Columns = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
- table_name.* = table.name;
- table_type.* = Columns;
+ table_name.* = table.name;
+ table_type.* = Columns;
table_value.* = table_index;
}
const TagTables = @Enum(TagIntTables, .exhaustive, &table_names, &table_values);
- const Tables = @Union(.auto, TagTables, &table_names, &table_types, &@splat(.{}));
+ const Tables = @Union(.auto, TagTables, &table_names, &table_types, &@splat(.{}));
return struct {
handle: *sqlite.sqlite3,
@@ -87,14 +87,14 @@ pub fn Database(comptime T: type) type {
};
const Schema = Tables;
- const Self = @This();
+ const Self = @This();
// Source: https://sqlite.org/c3ref/open.html
pub fn init(kind: Kind) Error!Self {
const name = switch (kind) {
.temp_in_memory => ":memory:",
- .temp_on_disk => "",
- .path => |path| path,
+ .temp_on_disk => "",
+ .path => |path| path,
};
var handle: ?*sqlite.sqlite3 = null;
@@ -179,7 +179,6 @@ fn Typename(comptime affinity: Affinity) type {
return struct {
type : type = T,
affinity: Affinity = affinity,
-
default_value: ?T = null,
is_not_null : bool = false,
is_unique : bool = false,
@@ -610,7 +609,6 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
}
};
}
-
/// SQLite result codes.
///
/// Primary result codes define a broad category of results, whereas extended
@@ -829,7 +827,7 @@ test {
};
};
- var db: Database(Schema) = try .init(.temp_in_memory);
+ var db: Database(Schema) = try .init(.temp_in_memory);
defer assert(db.deinit() == .ok);
const query = try db.select(.contacts, &.{ .first_name , .last_name, .age })
@@ -847,30 +845,30 @@ test {
}
// test {
- // NOTE: we don't use `union(enum)` here as if a column has a default value,
- // an integer tag type is needed explicitely, which, from a usability
- // standpoint, is not great; we can calulate this value in `Schema.from`.
- //
- // CREATE TABLE contacts (
- // contact_id INTEGER PRIMARY KEY,
- // first_name TEXT NOT NULL DEFAULT "Hans",
- // last_name TEXT NOT NULL DEFAULT "Mustermann",
- // nickname TEXT,
- // email TEXT NOT NULL UNIQUE,
- // phone TEXT NOT NULL UNIQUE
- // );
- // const S = struct {
- // contacts: struct {
- // contact_id: PrimaryKey(Integer, .{}),
- // first_name: VarChar(255, .{}) = "Hans",
- // last_name: VarChar(255, .{}) = "Mustermann",
- // nickname: ?VarChar(255, .{}),
- // email: VarChar(255, .{.unique}),
- // phone: VarChar(255, .{.unique}),
- // },
- // };
- //
- // // NOTE: init connects to DB and creates tables if not already present
- // var db: Database(Schema(S)) = try .init(.temp_in_memory);
- // db.deinit();
+// NOTE: we don't use `union(enum)` here as if a column has a default value,
+// an integer tag type is needed explicitely, which, from a usability
+// standpoint, is not great; we can calulate this value in `Schema.from`.
+//
+// CREATE TABLE contacts (
+// contact_id INTEGER PRIMARY KEY,
+// first_name TEXT NOT NULL DEFAULT "Hans",
+// last_name TEXT NOT NULL DEFAULT "Mustermann",
+// nickname TEXT,
+// email TEXT NOT NULL UNIQUE,
+// phone TEXT NOT NULL UNIQUE
+// );
+// const S = struct {
+// contacts: struct {
+// contact_id: PrimaryKey(Integer, .{}),
+// first_name: VarChar(255, .{}) = "Hans",
+// last_name: VarChar(255, .{}) = "Mustermann",
+// nickname: ?VarChar(255, .{}),
+// email: VarChar(255, .{.unique}),
+// phone: VarChar(255, .{.unique}),
+// },
+// };
+//
+// // NOTE: init connects to DB and creates tables if not already present
+// var db: Database(Schema(S)) = try .init(.temp_in_memory);
+// db.deinit();
// }
diff --git a/src/db/sqlite_new.zig b/src/db/sqlite_new.zig
index 46706b8..36eaf61 100644
--- a/src/db/sqlite_new.zig
+++ b/src/db/sqlite_new.zig
@@ -25,7 +25,7 @@ pub fn Database(comptime T: type) type {
// TODO: make functions out of `table` and `columns`: Table(Schema), []const Column(Schema, table) for readability?
pub fn select(self: *Self, comptime table: std.meta.Tag(Schema), comptime columns: []const std.meta.Tag(@FieldType(Schema, @tagName(table)))) Select(Schema, table, columns) {
_ = self;
- std.debug.print("{any}\n", .{ columns });
+ std.debug.print("{any}\n", .{columns});
return .{
// .handle = self.handle,
};
@@ -152,17 +152,17 @@ fn Unique(comptime T: type) type {
const Type = T.Type;
// TODO: `contains(expected, str)` function
const string = if (std.mem.count(u8, T.string, "UNIQUE") > 0)
- @compileError(std.fmt.comptimePrint("Type `{s}` is already unique", .{ @typeName(T) }))
+ @compileError(std.fmt.comptimePrint("Type `{s}` is already unique", .{@typeName(T)}))
else
- std.fmt.comptimePrint("UNIQUE {s}", .{ T.string });
+ std.fmt.comptimePrint("UNIQUE {s}", .{T.string});
};
}
fn Default(comptime T: type, comptime value: T.Type) type {
return struct {
const Type = T.type;
- const string = if(std.mem.count(u8, T.string, "DEFAULT") > 0)
- @compileError(std.fmt.comptimePrint("Type `{s}` already has a default value", .{ @typeName(T) }))
+ const string = if (std.mem.count(u8, T.string, "DEFAULT") > 0)
+ @compileError(std.fmt.comptimePrint("Type `{s}` already has a default value", .{@typeName(T)}))
else
std.fmt.comptimePrint("{s} DEFAULT {}", .{ T.string, value });
};
@@ -202,12 +202,12 @@ fn Test(comptime Schema: type, comptime table: std.meta.Tag(Schema), comptime co
fn Eql(comptime column: std.meta.Tag(ColumnUnion), value: @FieldType(ColumnUnion, @tagName(column))) type {
return struct {
- const fmt: []const u8 = std.fmt.comptimePrint("{s} = ", .{ @tagName(column) });
- const args: @Tuple(&.{ @TypeOf(value) }) = .{ value };
+ const fmt: []const u8 = std.fmt.comptimePrint("{s} = ", .{@tagName(column)});
+ const args: @Tuple(&.{@TypeOf(value)}) = .{value};
};
}
// fn And() type {
- // todo: concat fmt slices and args tuples
+ // todo: concat fmt slices and args tuples
// }
string: Node,
@@ -236,10 +236,10 @@ test "schema" {
const Schema = struct {
contacts: Contacts,
// contacts: struct {
- // contact_id: Integer = .constrain(.primary_key),
- // age: Integer = .unconstrained,
- // contact_id: Integer(usize) = .constrain(.{ .primary_key = true }),
- // first_name: Default(VarChar(255), "Hans"),
+ // contact_id: Integer = .constrain(.primary_key),
+ // age: Integer = .unconstrained,
+ // contact_id: Integer(usize) = .constrain(.{ .primary_key = true }),
+ // first_name: Default(VarChar(255), "Hans"),
// },
};
@@ -254,10 +254,10 @@ test "schema" {
const t: Test(@TypeOf(db).Schema, .contacts, &.{ .id, .first_name }) = .eql(.id, 42);
// const t: Test(@TypeOf(db).Schema, .contacts, &.{ .id, .first_name }) = .op_and(.eql(.id, 42), .eql(.first_name, "name"));
- std.debug.print("test output: {s}{}\n", switch (t.string) { .eql => |eq| .{ eq.fmt, eq.args } });
+ std.debug.print("test output: {s}{}\n", switch (t.string) {
+ .eql => |eq| .{ eq.fmt, eq.args },
+ });
const Int = Default(Unique(Integer(usize)), 42);
- std.debug.print("default unique integer with default 42: {s}\n", .{ Int.string });
-
-
+ std.debug.print("default unique integer with default 42: {s}\n", .{Int.string});
}
diff --git a/src/html/Element.zig b/src/html/Element.zig
index 8ecf31e..a9e5897 100644
--- a/src/html/Element.zig
+++ b/src/html/Element.zig
@@ -39,7 +39,7 @@ fn attributesFrom(attributes: anytype) []const Attribute {
const name = field.name;
const value = @field(attributes, name);
- const next_attr: []const Attribute = &.{ .{ .name = name, .value = value } };
+ const next_attr: []const Attribute = &.{.{ .name = name, .value = value }};
attrs = attrs ++ next_attr;
}
@@ -79,7 +79,6 @@ pub fn toHtml(comptime self: Self) []const u8 {
break :string string;
};
-
switch (self.content) {
.void => {},
.string => |s| {
@@ -91,7 +90,7 @@ pub fn toHtml(comptime self: Self) []const u8 {
}
string = string ++ "</" ++ self.tag ++ ">";
- }
+ },
}
string = string ++ if (self.tag.len == 0) "" else "</" ++ self.tag ++ ">";
diff --git a/src/http/Response.zig b/src/http/Response.zig
index d54792b..69bec65 100644
--- a/src/http/Response.zig
+++ b/src/http/Response.zig
@@ -27,34 +27,74 @@ pub const Message = union(enum) {
status: std.http.Status,
message: Message,
+headers: []const std.http.Header = &.{},
pub fn with(status: std.http.Status, message: Message) @This() {
return .{ .status = status, .message = message };
}
+pub fn withHeaders(
+ status: std.http.Status,
+ message: Message,
+ headers: []const std.http.Header,
+) @This() {
+ return .{
+ .status = status,
+ .message = message,
+ .headers = headers,
+ };
+}
+
pub fn ok(message: Message) @This() {
return with(.ok, message);
}
-pub fn ok_or_error(message: anyerror!Message) @This() {
- return ok(message catch return with(.internal_server_error, .void));
+pub fn okOr(message: anyerror!Message, err: @This()) @This() {
+ return ok(message catch return err);
}
-pub fn bad_request(message: Message) @This() {
+pub fn okOrError(message: anyerror!Message) @This() {
+ return okOr(message, .with(.internal_server_error, .void));
+}
+
+pub fn badRequest(message: Message) @This() {
return with(.bad_request, message);
}
+pub const SendOptions = struct {
+ headers: []const std.http.Header,
+};
+
pub fn send(
self: *const @This(),
io: std.Io,
+ arena: std.mem.Allocator,
request: *std.http.Server.Request,
+ options: SendOptions,
) !void {
+ const headers = hdrs: {
+ if (options.headers.len == 0) {
+ break :hdrs self.headers;
+ }
+
+ const h = try arena.alloc(std.http.Header, options.headers.len + self.headers.len);
+ @memcpy(h[0..options.headers.len], options.headers);
+ @memcpy(h[options.headers.len..], self.headers);
+ break :hdrs h;
+ };
+
switch (self.message) {
.void => {
- try request.respond("", .{ .status = self.status });
+ try request.respond("", .{
+ .status = self.status,
+ .extra_headers = headers,
+ });
},
.static => |content| {
- try request.respond(content, .{ .status = self.status });
+ try request.respond(content, .{
+ .status = self.status,
+ .extra_headers = headers,
+ });
},
.streaming => |file| {
var write_buffer: [1024]u8 = undefined;
@@ -63,6 +103,7 @@ pub fn send(
var body_writer = try request.respondStreaming(&write_buffer, .{
.respond_options = .{
.status = self.status,
+ .extra_headers = headers,
.transfer_encoding = .chunked,
},
});
diff --git a/src/http/handler/static.zig b/src/http/handler/static.zig
index d53f213..df307b7 100644
--- a/src/http/handler/static.zig
+++ b/src/http/handler/static.zig
@@ -2,10 +2,12 @@ const Interface = @import("Interface.zig");
const Context = @import("context.zig").Context;
const Response = @import("../Response.zig");
-pub fn Static(route: anytype, content: []const u8) Context(route) {
+pub fn Static(route: anytype, content: []const u8, mime: []const u8) Context(route) {
const get = struct {
fn get(_: Context(route).Request) Response {
- return .ok(.string(content));
+ return .withHeaders(.ok, .string(content), &.{
+ .{ .name = "Content-Type", .value = mime },
+ });
}
}.get;
diff --git a/src/http/serve.zig b/src/http/serve.zig
index 587f4a3..036eecd 100644
--- a/src/http/serve.zig
+++ b/src/http/serve.zig
@@ -1,20 +1,30 @@
const std = @import("std");
+const Response = @import("Response.zig");
const RouteSet = @import("RouteSet.zig");
+pub const Options = struct {
+ address: std.Io.net.IpAddress,
+ headers: []const std.http.Header = &.{},
+};
+
pub fn serve(
gpa: std.mem.Allocator,
comptime routes: RouteSet,
- address: std.Io.net.IpAddress,
+ options: Options,
) !void {
var threaded: std.Io.Threaded = .init(gpa, .{});
var group: std.Io.Group = .init;
const io = threaded.io();
- var server = try address.listen(io, .{ .reuse_address = true });
+ var server = try options.address.listen(io, .{ .reuse_address = true });
+
+ const send_options: Response.SendOptions = .{
+ .headers = options.headers,
+ };
while (true) {
const stream = try server.accept(io);
- group.async(io, handle, .{ io, gpa, stream, &routes });
+ group.async(io, handle, .{ io, gpa, stream, &routes, send_options });
}
}
@@ -23,6 +33,7 @@ pub fn handle(
gpa: std.mem.Allocator,
stream: std.Io.net.Stream,
routes: *const RouteSet,
+ send_options: Response.SendOptions,
) void {
var read_buffer: [1024 * 8]u8 = undefined;
var write_buffer: [1024 * 8]u8 = undefined;
@@ -44,8 +55,8 @@ pub fn handle(
std.debug.print("{s} {s}\n", .{ @tagName(request.head.method), request.head.target });
if (routes.getInterface(request.head.target)) |interface| {
- const message = interface.handle(gpa, arena.allocator(), io, &request);
- message.send(io, &request) catch return;
+ const response = interface.handle(gpa, arena.allocator(), io, &request);
+ response.send(io, arena.allocator(), &request, send_options) catch return;
} else {
request.respond("", .{ .status = .not_found }) catch return;
}
diff --git a/src/main.zig b/src/main.zig
index bf1b09f..bb8b34d 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -7,14 +7,16 @@ const std = @import("std");
const http = @import("http");
const api = @import("api");
-const web = @import("web/root.zig");
+const z = @import("z");
+const wasm = @embedFile("wasm");
-const routes: http.RouteSet = .init(api.interfaces ++ web.interfaces);
+const routes: http.RouteSet = .init(&([_]http.handler.Interface{
+ http.handler.Static(.index, z.app.create(.{ .name = "Memora" }), "text/html").interface(),
+ http.handler.Static(.{"index.wasm"}, wasm, "application/wasm").interface(),
+}) ++ api.interfaces);
pub fn main(init: std.process.Init) !void {
- try http.serve(
- init.gpa,
- routes,
- try .parseLiteral("0.0.0.0:8080"),
- );
+ try http.serve(init.gpa, routes, .{
+ .address = try .parseLiteral("0.0.0.0:8080"),
+ });
}
diff --git a/src/web/component/image/index.css b/src/web/component/image/index.css
deleted file mode 100644
index e69de29..0000000
--- a/src/web/component/image/index.css
+++ /dev/null
diff --git a/src/web/component/image/index.html b/src/web/component/image/index.html
deleted file mode 100644
index 918c5df..0000000
--- a/src/web/component/image/index.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<div id="image">
-</div>
diff --git a/src/web/component/image/index.js b/src/web/component/image/index.js
deleted file mode 100644
index d88023d..0000000
--- a/src/web/component/image/index.js
+++ /dev/null
@@ -1 +0,0 @@
-console.log(Z.by_selector('div'));
diff --git a/src/web/component/image/root.zig b/src/web/component/image/root.zig
deleted file mode 100644
index 7c8ec77..0000000
--- a/src/web/component/image/root.zig
+++ /dev/null
@@ -1,8 +0,0 @@
-const z = @import("z");
-
-pub const component: z.Component = .{
- .name = .image,
- .body = @embedFile("index.html"),
- .style = @embedFile("index.css"),
- .script = @embedFile("index.js"),
-};
diff --git a/src/web/component/root.zig b/src/web/component/root.zig
deleted file mode 100644
index 226f3f7..0000000
--- a/src/web/component/root.zig
+++ /dev/null
@@ -1,6 +0,0 @@
-const z = @import("z");
-
-pub const components: []const z.Component = &.{
- @import("image/root.zig").component,
- @import("timeline/root.zig").component,
-};
diff --git a/src/web/component/timeline/index.css b/src/web/component/timeline/index.css
deleted file mode 100644
index 6d58f59..0000000
--- a/src/web/component/timeline/index.css
+++ /dev/null
@@ -1,18 +0,0 @@
-#container {
- width: 100%;
- display: inline-grid;
- gap: 0px;
- overflow-y: auto;
-}
-
-.image {
- text-align: center;
- align-content: center;
- font-weight: bold;
- font-size: 0.5em;
- overflow: hidden;
-}
-
-#container.tiling .image {
- aspect-ratio: 1 / 1 !important;
-}
diff --git a/src/web/component/timeline/index.html b/src/web/component/timeline/index.html
deleted file mode 100644
index 41d4617..0000000
--- a/src/web/component/timeline/index.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<div id="container">
-</div>
diff --git a/src/web/component/timeline/index.js b/src/web/component/timeline/index.js
deleted file mode 100644
index 81322c6..0000000
--- a/src/web/component/timeline/index.js
+++ /dev/null
@@ -1,96 +0,0 @@
-const container = Z.by_id('container');
-
-function getRandomColor() {
- var letters = '0123456789ABCDEF';
- var color = '#';
- for (var i = 0; i < 6; i++) {
- color += letters[Math.floor(Math.random() * 16)];
- }
- return color;
-}
-
-for (let i = 0; i < 10000; ++i) {
- container.appendChild(Z.native('div', {
- innerText: i,
- className: 'image',
- style: {
- background: getRandomColor(),
- aspectRatio: '1 / ' + (Math.random() + 0.5),
- },
- }));
-}
-
-const zoom = new (class {
- constructor() {
- this.committed = 5;
- container.style.gridTemplateColumns = `repeat(5, 1fr)`;
- container.classList.toggle('tiling', this.committed != 1);
- this.por = { x: 0, y: 0 };
- this.eor = null;
- this.y_offset = 0;
- this.distance = 0;
- }
-
- update(distance, point) {
- const scale = distance / this.distance;
- const x = point.x - this.por.x;
- container.style.transform = `translate(${x}px, 0px) scale(${scale})`;
- }
-
- set reference({ point, distance }) {
- const rect = container.getClientRects()[0];
-
- this.por = { x: point.x, y: point.y - rect.y };
- container.style.transformOrigin = `${this.por.x}px ${this.por.y}px`;
- this.eor = Z.document.shadowRoot.elementFromPoint(point.x, point.y);
-
- const box_rect = this.eor.getBoundingClientRect();
- this.y_offset = box_rect.y;
-
- this.distance = distance;
- }
-
- commit(distance) {
- const scale = distance / this.distance;
- this.committed = Math.round(Math.min(Math.max(this.committed / scale, 1), 20));
- container.style.gridTemplateColumns = `repeat(${this.committed}, 1fr)`;
- container.classList.toggle('tiling', this.committed != 1);
- container.style.transform = 'scale(1)';
-
- const rect = this.eor.getBoundingClientRect();
-
- Z.document.scrollBy({
- top: rect.y - this.y_offset,
- behavior: 'instant',
- });
- }
-
- increase_line_by(n) {
- this.committed = Math.min(Math.max(this.committed + n, 1), 20);
- container.style.gridTemplateColumns = `repeat(${this.committed}, 1fr)`;
- container.classList.toggle('tiling', this.committed != 1);
- container.style.transform = 'scale(1)';
- }
-});
-
-Z.document.onwheel = (event) => {
- if (!event.ctrlKey) {
- return;
- }
- event.preventDefault();
- zoom.increase_line_by(event.wheelDeltaY / 120);
-};
-
-const pinch = new Pinch(Z.document);
-
-pinch.onstart = (event) => {
- zoom.reference = event;
-};
-
-pinch.onpinch = (event) => {
- zoom.update(event.distance, event.point);
-};
-
-pinch.onfinish = (event) => {
- zoom.commit(event.distance);
-};
diff --git a/src/web/component/timeline/root.zig b/src/web/component/timeline/root.zig
deleted file mode 100644
index 9faa40e..0000000
--- a/src/web/component/timeline/root.zig
+++ /dev/null
@@ -1,8 +0,0 @@
-const z = @import("z");
-
-pub const component: z.Component = .{
- .name = .timeline,
- .body = @embedFile("index.html"),
- .style = @embedFile("index.css"),
- .script = @embedFile("index.js"),
-};
diff --git a/src/web/index.css b/src/web/index.css
deleted file mode 100644
index 6b1927f..0000000
--- a/src/web/index.css
+++ /dev/null
@@ -1,20 +0,0 @@
-html {
- height: 100vh;
- width: 100vw;
-}
-
-body {
- padding: 0;
- margin: 0;
- width: 100vw;
- height: 100vh;
- overflow: hidden;
- touch-action: pan-y;
-}
-
-#timeline {
- display: block;
- height: 100vh;
- overflow-y: auto;
- background: gray;
-}
diff --git a/src/web/index.html b/src/web/index.html
deleted file mode 100644
index d2bc6fe..0000000
--- a/src/web/index.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<z-component type="timeline" id="timeline">
-</z-component>
diff --git a/src/web/index.js b/src/web/index.js
deleted file mode 100644
index e69de29..0000000
--- a/src/web/index.js
+++ /dev/null
diff --git a/src/web/pinch.js b/src/web/pinch.js
deleted file mode 100644
index bb06b0d..0000000
--- a/src/web/pinch.js
+++ /dev/null
@@ -1,82 +0,0 @@
-class Pinch {
- constructor(element) {
- this.event_cache = [];
- this.onpinch = () => {};
- this.onfinish = () => {};
- this.onstart = () => {};
-
- element.onpointerdown = (e) => this.pointer_down_handler(e);
- element.onpointermove = (e) => this.pointer_move_handler(e);
- element.onpointerup = (e) => this.pointer_up_handler(e);
- element.onpointercancel = (e) => this.pointer_up_handler(e);
- element.onpointerout = (e) => this.pointer_up_handler(e);
- element.onpointerleave = (e) => this.pointer_up_handler(e);
- }
-
- pointer_down_handler(event) {
- this.event_cache.push(event);
-
- if (this.event_cache.length === 2) {
- const diff = Math.hypot(
- this.event_cache[0].clientX - this.event_cache[1].clientX,
- this.event_cache[0].clientY - this.event_cache[1].clientY,
- );
-
- const point = {
- x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2,
- y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2,
- };
-
- this.onstart({ point, distance: diff });
- }
- }
-
- pointer_move_handler(event) {
- const index = this.event_cache.findIndex(
- (cached) => cached.pointerId == event.pointerId,
- );
- this.event_cache[index] = event;
-
- if (this.event_cache.length === 2) {
- const diff = Math.hypot(
- this.event_cache[0].clientX - this.event_cache[1].clientX,
- this.event_cache[0].clientY - this.event_cache[1].clientY,
- );
-
- const point = {
- x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2,
- y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2,
- };
-
- this.onpinch({ distance: diff, point });
- }
- }
-
- pointer_up_handler(event) {
- let cleanup = false;
- const ev = {};
-
- if (this.event_cache.length === 2) {
- ev['distance'] = Math.hypot(
- this.event_cache[0].clientX - this.event_cache[1].clientX,
- this.event_cache[0].clientY - this.event_cache[1].clientY,
- );
-
- ev['point'] = {
- x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2,
- y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2,
- };
-
- cleanup = true;
- }
-
- const index = this.event_cache.findIndex(
- (cached) => cached.pointerId === event.pointerId,
- );
- this.event_cache.splice(index, 1);
-
- if (cleanup) {
- this.onfinish(ev);
- }
- }
-}
diff --git a/src/web/root.zig b/src/web/root.zig
deleted file mode 100644
index c9c1b08..0000000
--- a/src/web/root.zig
+++ /dev/null
@@ -1,27 +0,0 @@
-const z = @import("z");
-const html = @import("html");
-const http = @import("http");
-const Static = http.handler.Static;
-
-const components = @import("component/root.zig").components;
-
-const document: html.Element = .native(.html, .{}, .children(&.{
- .native(.head, .{}, .children(&.{
- .native(.title, .{}, .content("Memora")),
- .native(.meta, .{
- .name = "viewport",
- .content = "width=device-width, initial-scale=1.0",
- }, .void),
- z.script.load(@embedFile("pinch.js")),
- z.style.load(@embedFile("index.css")),
- z.env(components),
- })),
- .native(.body, .{}, .children(&.{
- z.html.load(@embedFile("index.html")),
- })),
-}));
-
-pub const interfaces: []const http.handler.Interface = &.{
- Static(.index, document.toDocument()).interface(),
-};
-
diff --git a/src/z/AppBundle.zig b/src/z/AppBundle.zig
new file mode 100644
index 0000000..3fec9fb
--- /dev/null
+++ b/src/z/AppBundle.zig
@@ -0,0 +1,35 @@
+const std = @import("std");
+
+pub const Options = struct {
+ root_source_file: std.Build.LazyPath,
+};
+
+mod: *std.Build.Module,
+wasm: *std.Build.Step.Compile,
+
+pub fn init(b: *std.Build, options: Options) @This() {
+ const module = b.createModule(.{
+ .root_source_file = options.root_source_file,
+ .target = b.resolveTargetQuery(.{
+ .cpu_arch = .wasm32,
+ .os_tag = .freestanding,
+ }),
+ });
+
+ const exe = b.addExecutable(.{
+ .name = "runtime",
+ .root_module = module,
+ });
+
+ exe.rdynamic = true;
+ exe.entry = .disabled;
+
+ return .{
+ .wasm = exe,
+ .mod = module,
+ };
+}
+
+pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath {
+ return self.wasm.getEmittedBin();
+}
diff --git a/src/z/Component.zig b/src/z/Component.zig
deleted file mode 100644
index a6a4923..0000000
--- a/src/z/Component.zig
+++ /dev/null
@@ -1,18 +0,0 @@
-const std = @import("std");
-const html = @import("html");
-const z = @import("root.zig");
-
-name: @EnumLiteral(),
-body: []const u8,
-style: []const u8,
-script: []const u8,
-
-pub fn toElement(comptime self: @This()) html.Element {
- return .transparent(.children(&.{
- .native(.template, .{ .id = "@" ++ @tagName(self.name) }, .children(&.{
- z.style.load(self.style),
- z.body.load(self.body),
- })),
- z.script.load("Zenv.constructors['component__" ++ @tagName(self.name) ++ "'] = async (Z) => {" ++ self.script ++ "}"),
- }));
-}
diff --git a/src/z/Env/Future.zig b/src/z/Env/Future.zig
new file mode 100644
index 0000000..17266b9
--- /dev/null
+++ b/src/z/Env/Future.zig
@@ -0,0 +1,29 @@
+const std = @import("std");
+const Env = @import("root.zig");
+
+const Self = @This();
+
+result: *Env.Value,
+
+pub fn await(self: *Self, env: *Env, comptime kind: Env.Value.Kind) kind.asType() {
+ const result = self.awaitAny(env);
+ std.debug.assert(kind == result.kind);
+
+ return switch (kind) {
+ .uninit => @panic("uninitialized result"),
+ .string => result.value.string.ptr[0..result.value.string.len],
+ else => @field(result.value, @tagName(kind)),
+ };
+}
+
+pub fn awaitAny(self: *Self, env: *Env) Env.Value {
+ defer env.pool.destroy(self.result);
+
+ if (self.result.kind != .uninit) {
+ return self.result.*;
+ }
+
+ env.flush();
+
+ return self.result.*;
+}
diff --git a/src/z/Env/call.zig b/src/z/Env/call.zig
new file mode 100644
index 0000000..bf64392
--- /dev/null
+++ b/src/z/Env/call.zig
@@ -0,0 +1,15 @@
+
+pub const Call = extern struct {
+ kind: Kind,
+ num_args: u8,
+
+ const Kind = enum(u8) {
+ free = 0,
+ get_prop = 1,
+ set_prop = 2,
+ del_prop = 3,
+ call_method = 4,
+ call = 5,
+ };
+};
+
diff --git a/src/z/Env/js.zig b/src/z/Env/js.zig
new file mode 100644
index 0000000..b35f6ed
--- /dev/null
+++ b/src/z/Env/js.zig
@@ -0,0 +1,9 @@
+const std = @import("std");
+const Env = @import("root.zig");
+
+pub extern "object_store" fn process(
+ [*]const Env.Call,
+ [*]const Env.Value,
+ [*]*Env.Value,
+ length: usize,
+) void;
diff --git a/src/z/Env/root.zig b/src/z/Env/root.zig
new file mode 100644
index 0000000..7b31e84
--- /dev/null
+++ b/src/z/Env/root.zig
@@ -0,0 +1,64 @@
+const std = @import("std");
+
+const mod = @import("../root.zig");
+const js = @import("js.zig");
+
+const Self = @This();
+pub const Call = @import("call.zig").Call;
+pub const Future = @import("Future.zig");
+pub const Value = @import("value.zig").Value;
+
+calls: std.ArrayList(Call) = .empty,
+values: std.ArrayList(Value) = .empty,
+pool: std.heap.MemoryPool(Value) = .empty,
+results: std.ArrayList(*Value) = .empty,
+gpa: std.mem.Allocator,
+
+pub fn init(gpa: std.mem.Allocator) Self {
+ return .{ .gpa = gpa };
+}
+
+pub fn getProp(self: *Self, id: u32, key: []const u8) !Future {
+ try self.calls.append(self.gpa, .{
+ .kind = .get_prop,
+ .num_args = 2,
+ });
+ try self.values.append(self.gpa, .{
+ .kind = .object,
+ .value = .{ .object = id },
+ });
+ try self.values.append(self.gpa, .{
+ .kind = .string,
+ .value = .{
+ .string = .{
+ .ptr = @ptrCast(key),
+ .len = key.len,
+ },
+ },
+ });
+ const result = try self.pool.create(self.gpa);
+ result.kind = .uninit;
+ try self.results.append(self.gpa, result);
+ return .{ .result = result };
+}
+
+pub fn flush(self: *Self) void {
+ js.process(
+ @ptrCast(self.calls.items),
+ @ptrCast(self.values.items),
+ @ptrCast(self.results.items),
+ self.results.items.len,
+ );
+ self.results.clearRetainingCapacity();
+}
+
+pub fn deinit(self: *Self) void {
+ self.flush();
+
+ self.calls.deinit(self.gpa);
+ self.values.deinit(self.gpa);
+ self.pool.deinit(self.gpa);
+ self.results.deinit(self.gpa);
+
+ self.* = undefined;
+}
diff --git a/src/z/Env/value.zig b/src/z/Env/value.zig
new file mode 100644
index 0000000..4630a76
--- /dev/null
+++ b/src/z/Env/value.zig
@@ -0,0 +1,36 @@
+pub const Value = extern struct {
+ kind: Kind,
+ value: extern union {
+ object: u32,
+ string: extern struct {
+ ptr: [*]const u8,
+ len: usize,
+ },
+ int: isize,
+ uint: usize,
+ float: f64,
+ undefined: void,
+ },
+
+ pub const Kind = enum(u8) {
+ uninit = 0,
+ object = 1,
+ string = 2,
+ int = 3,
+ uint = 4,
+ float = 5,
+ undefined = 6,
+
+ pub fn asType(comptime self: Kind) type {
+ return switch (self) {
+ .object => return u32,
+ .string => return []const u8,
+ .int => return isize,
+ .uint => return usize,
+ .float => f64,
+ .undefined => return void,
+ .uninit => @compileError("uninit has no associated type."),
+ };
+ }
+ };
+};
diff --git a/src/z/File.zig b/src/z/File.zig
deleted file mode 100644
index cd7094f..0000000
--- a/src/z/File.zig
+++ /dev/null
@@ -1,18 +0,0 @@
-const Minifier = @import("Minifier.zig");
-const Element = @import("html").Element;
-
-tag: ?@EnumLiteral(),
-minifier: Minifier,
-
-pub fn load(comptime self: @This(), comptime content: []const u8) Element {
- if (self.tag) |tag| {
- return .native(
- tag,
- .{},
- .content(comptime self.minifier.minify(content)),
- );
- } else {
- return .transparent(.content(comptime self.minifier.minify(content)));
- }
-}
-
diff --git a/src/z/Minifier.zig b/src/z/Minifier.zig
deleted file mode 100644
index 65dd9fb..0000000
--- a/src/z/Minifier.zig
+++ /dev/null
@@ -1,168 +0,0 @@
-const std = @import("std");
-
-/// A string contained in quotes will not be changed in any form.
-quotes: []const u8,
-
-/// This character is used to escape in strings.
-escape: ?u8,
-
-/// A delimiter does not need any padding around it.
-delimiters: []const u8,
-
-/// Kinds of comments, will be removed in the output.
-comments: []const struct { []const u8, []const u8 },
-
-pub const html: @This() = .{
- .quotes = "\"'",
- .escape = null,
- .delimiters = "<>",
- .comments = &.{.{ "<!--", "-->" }},
-};
-
-pub const js: @This() = .{
- .quotes = "\"'`",
- .escape = '\\',
- .delimiters = "+-*,.:;[](){}=&|^",
- .comments = &.{ .{ "//", "\n" }, .{ "/*", "*/" } },
-};
-
-pub const css: @This() = .{
- .quotes = "\"'",
- .escape = '\\',
- .delimiters = ":;{}",
- .comments = &.{.{ "/*", "*/" }},
-};
-
-fn skip(comptime source: *[]const u8, comptime len: usize) void {
- source.* = (source.*)[len..];
-}
-
-fn push(
- comptime source: *[]const u8,
- comptime target: *[]const u8,
- comptime len: usize,
-) void {
- target.* = target.* ++ (source.*)[0..len];
- skip(source, len);
-}
-
-pub fn minify(
- comptime self: *const @This(),
- comptime c: []const u8,
-) []const u8 {
- @setEvalBranchQuota(c.len * 100);
- var content = std.mem.trimStart(u8, c, &std.ascii.whitespace);
- var block: []const u8 = "";
-
- while (content.len > 0) {
- const had_comment: bool = cmt: {
- inline for (self.comments) |comment| {
- const start, const end = comment;
-
- if (std.mem.startsWith(u8, content, start)) {
- skip(&content, start.len);
- skip(&content, if (std.mem.indexOf(u8, content, end)) |l| l + end.len else content.len);
- break :cmt true;
- }
- }
- break :cmt false;
- };
-
- if (had_comment) {} else if (std.mem.indexOfScalar(u8, self.quotes, content[0])) |_| {
- const quote = content[0];
- push(&content, &block, 1);
- while (content.len > 0) {
- if (content[0] == self.escape) {
- push(&content, &block, 2);
- } else if (content[0] == quote) {
- push(&content, &block, 1);
- break;
- }
- push(&content, &block, 1);
- }
- } else {
- push(&content, &block, 1);
- }
-
- const was_trimmed = content.len > 0 and std.ascii.isWhitespace(content[0]);
- content = std.mem.trimStart(u8, content, &std.ascii.whitespace);
- if (was_trimmed and
- block.len > 0 and
- content.len > 0 and
- std.mem.indexOfScalar(u8, self.delimiters, block[block.len - 1]) == null and
- std.mem.indexOfScalar(u8, self.delimiters, content[0]) == null)
- {
- block = block ++ " ";
- }
- }
-
- return block;
-}
-
-test "html" {
- const buffer: []const u8 =
- \\<html>
- \\ <head>
- \\ <title>Some Title</title>
- \\ </head>
- \\ <body>
- \\ <z-component type="something here" tag="1 2 3"> 123 </z-component>
- \\ <!-- some comment here -->
- \\ Hello World!
- \\ </body>
- \\</html>
- ;
-
- try std.testing.expectEqualStrings(
- "<html><head><title>Some Title</title></head><body><z-component type=\"something here\" tag=\"1 2 3\">123</z-component>Hello World!</body></html>",
- comptime html.minify(buffer),
- );
-}
-
-test "css" {
- const buffer: []const u8 =
- \\body {
- \\ background: #fff;
- \\ color: red;
- \\}
- \\
- \\#content:first {
- \\ user-select: none;
- \\ /* comment */
- \\ content: ' ';
- \\ padding: 5px 5px;
- \\}
- ;
-
- try std.testing.expectEqualStrings(
- "body{background:#fff;color:red;}#content:first{user-select:none;content:' ';padding:5px 5px;}",
- comptime css.minify(buffer),
- );
-}
-
-test "js" {
- const buffer: []const u8 =
- \\class extends HTMLElement {
- \\ // comment here
- \\ constructor() {
- \\ super();
- \\ this.attachShadow({ mode: 'open' });
- \\ }
- \\
- \\ /*
- \\ * Mulitline
- \\ */
- \\ connectedCallback() {
- \\ const type = this.getAttribute('type');
- \\ const template = document.getElementById(`--${type}`);
- \\ const node = document.importNode(template.content, true);
- \\ this.shadowRoot.appendChild(node);
- \\ }
- \\}
- ;
-
- try std.testing.expectEqualStrings(
- "class extends HTMLElement{constructor(){super();this.attachShadow({mode:'open'});}connectedCallback(){const type=this.getAttribute('type');const template=document.getElementById(`--${type}`);const node=document.importNode(template.content,true);this.shadowRoot.appendChild(node);}}",
- comptime js.minify(buffer),
- );
-}
diff --git a/src/z/app/main.js b/src/z/app/main.js
new file mode 100644
index 0000000..bad4422
--- /dev/null
+++ b/src/z/app/main.js
@@ -0,0 +1,245 @@
+function decodeString(base, length) {
+ const slice = new Uint8Array(wasm.memory.buffer, base, length);
+ return new TextDecoder().decode(slice);
+}
+
+class ObjectStore {
+ static id_name = "+-store-id";
+
+ static types = Object.freeze({
+ 0: "uninit",
+ 1: "object",
+ 2: "string",
+ 3: "int",
+ 4: "uint",
+ 5: "float",
+ 6: "undefined",
+
+ "uninit": 0,
+ "object": 1,
+ "string": 2,
+ "int": 3,
+ "uint": 4,
+ "float": 5,
+ "undefined": 6,
+ });
+
+ static methods = Object.freeze({
+ 0: 'free',
+ 1: 'getProp',
+ 2: 'setProp',
+ 3: 'delProp',
+ 4: 'callMethod',
+ 5: 'call',
+ });
+
+ static store = { 0: null, 1: window };
+
+ static generateFreeId() {
+ let id = 0;
+
+ while (id in ObjectStore.store) {
+ id = Math.floor(Math.random() * (2**32 - 1))
+ }
+
+ return id;
+ }
+
+ static free(id) {
+ delete ObjectStore.store[id][ObjectStore.id_name];
+ delete ObjectStore.store[id];
+ }
+
+ static getProp(target, key) {
+ return target[key];
+ }
+
+ static setProp(target, key, value) {
+ target[key] = value;
+ }
+
+ static delProp(target, key) {
+ delete target[key];
+ }
+
+ static callMethod(target, method, ...args) {
+ return target[method](...args);
+ }
+
+ static call(target, args) {
+ return target(args);
+ }
+
+ static decodeValue(view, offset) {
+ if (ObjectStore.types[kind] === 'string') {
+ const ptr = view.getUint32((offset * 4) * 2, true);
+ const len = view.getUint32((offset * 4) * 2 + 4, true);
+ return decodeString(ptr, len);
+ }
+ }
+
+ static decodeCall(view, offset) {
+ const kind = ObjectStore.methods[view.getUint8(offset, true)]
+
+ if (!kind) throw "unknown method, cannot decode";
+
+ return {
+ kind: kind,
+ num_args: view.getUint8(offset + 1, true),
+ }
+ }
+
+ static decodeValue(view, offset) {
+ const kind = ObjectStore.types[view.getUint8(offset, true)];
+
+ if (!kind) throw "unknown type, cannot decode";
+
+ if (kind === 'string') {
+ const ptr = view.getUint32(offset + 8, true)
+ const len = view.getUint32(offset + 12, true)
+ return decodeString(ptr, len);
+ }
+
+ if (kind === 'int') {
+ return view.getInt32(offset + 8, true);
+ }
+
+ if (kind === 'uint') {
+ return view.getUint32(offset + 8, true);
+ }
+
+ if (kind === 'object') {
+ const id = view.getUint32(offset + 8, true);
+ return ObjectStore.store[id];
+ }
+
+ if (kind === 'float') {
+ return view.getFloat64(offset + 8, true);
+ }
+ }
+
+ static writeValue(ptr, value) {
+ const mem = new DataView(wasm.memory.buffer, ptr);
+
+ if (typeof value === 'object') {
+ mem.setUint8(0, ObjectStore.types['object'], true);
+ let id = value == null ? 0 : value[ObjectStore.id_name];
+
+ if (id === undefined) {
+ id = ObjectStore.generateFreeId();
+ ObjectStore.store[id] = value;
+ value[ObjectStore.id_name] = id;
+ }
+
+ mem.setUint32(8, id, true);
+
+ return;
+ }
+
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
+ // uint
+ throw "unimplemented";
+ return;
+ }
+
+ if (typeof value === 'number' && Number.isInteger(value)) {
+ // int
+ throw "unimplemented";
+ return;
+ }
+
+ if (typeof value === 'number') {
+ // float
+ throw "unimplemented";
+ return;
+ }
+
+ if (typeof value === 'string') {
+ // string
+ throw "unimplemented";
+ return;
+ }
+
+ if (typeof value === 'undefined') {
+ // undefined
+ throw "unimplemented";
+ return;
+ }
+ }
+
+ static processWasm(
+ calls_base,
+ values_base,
+ result_base,
+ length,
+ ) {
+ const offset = {
+ call: 0,
+ value: 0,
+ result: 0,
+ }
+
+ const calls_view = new DataView(wasm.memory.buffer, calls_base);
+ const values_view = new DataView(wasm.memory.buffer, values_base);
+ const results_view = new DataView(wasm.memory.buffer, result_base);
+
+ for (let i = 0; i < length; ++i) {
+ const method = ObjectStore.decodeCall(calls_view, offset.call);
+ offset.call += 2;
+
+ let args = new Array(method.num_args).fill().map(_ => {
+ const value = ObjectStore.decodeValue(values_view, offset.value);
+ offset.value += 16;
+ return value;
+ });
+
+ const result = ObjectStore[method.kind](...args);
+ const result_ptr = results_view.getUint32(offset.result, true);
+ offset.result += 4;
+
+ ObjectStore.writeValue(result_ptr, result);
+ }
+ }
+}
+
+const imports = {
+ object_store: {
+ process: ObjectStore.processWasm,
+ },
+ console: {
+ log(buffer, length) {
+ console.log(decodeString(buffer, length))
+ },
+ warn(buffer, length) {
+ console.warn(decodeString(buffer, length))
+ },
+ error(buffer, length) {
+ console.error(decodeString(buffer, length))
+ },
+ debug(buffer, length) {
+ console.debug(decodeString(buffer, length))
+ },
+ }
+}
+
+WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then(
+ ({ instance, module }) => {
+ const is64 = new Uint8Array(
+ instance.exports.memory.buffer,
+ instance.exports.bit_length,
+ 1,
+ )[0] == 8
+
+ window.wasm = {
+ exports: instance.exports,
+ memory: instance.exports.memory,
+ is64: is64,
+ UsizeArray: is64 ? BigUint64Array : Uint32Array,
+ IsizeArray: is64 ? BigInt64Array : Int32Array,
+ }
+
+ window[ObjectStore.id_name] = 1;
+
+ wasm.exports.run();
+ },
+);
diff --git a/src/z/app/root.zig b/src/z/app/root.zig
new file mode 100644
index 0000000..03760c4
--- /dev/null
+++ b/src/z/app/root.zig
@@ -0,0 +1,20 @@
+const html = @import("html");
+
+pub const Options = struct {
+ name: []const u8
+};
+
+pub fn create(options: Options) []const u8 {
+ return html.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("main.js"))),
+ })),
+ })).toDocument();
+}
diff --git a/src/z/env/console.zig b/src/z/env/console.zig
new file mode 100644
index 0000000..16f562c
--- /dev/null
+++ b/src/z/env/console.zig
@@ -0,0 +1,24 @@
+
+const js = struct {
+ extern "console" fn log(buffer: [*]const u8, len: usize) void;
+ extern "console" fn warn(buffer: [*]const u8, len: usize) void;
+ extern "console" fn err(buffer: [*]const u8, len: usize) void;
+ extern "console" fn debug(buffer: [*]const u8, len: usize) void;
+};
+
+
+pub fn log(buffer: []const u8) void {
+ js.log(@ptrCast(buffer), buffer.len);
+}
+
+pub fn warn(buffer: []const u8) void {
+ js.warn(@ptrCast(buffer), buffer.len);
+}
+
+pub fn err(buffer: []const u8) void {
+ js.err(@ptrCast(buffer), buffer.len);
+}
+
+pub fn debug(buffer: []const u8) void {
+ js.debug(@ptrCast(buffer), buffer.len);
+}
diff --git a/src/z/env/root.zig b/src/z/env/root.zig
new file mode 100644
index 0000000..9e49181
--- /dev/null
+++ b/src/z/env/root.zig
@@ -0,0 +1,2 @@
+
+pub const console = @import("console.zig");
diff --git a/src/z/root.zig b/src/z/root.zig
index 26bbffc..6ca6302 100644
--- a/src/z/root.zig
+++ b/src/z/root.zig
@@ -1,52 +1,19 @@
-const std = @import("std");
+const builtin = @import("builtin");
-pub const Minifier = @import("Minifier.zig");
-pub const Component = @import("Component.zig");
-pub const File = @import("File.zig");
+const wasm = wasm_struct: {
+ if (builtin.target.cpu.arch.isWasm()) {
+ break :wasm_struct struct {
+ pub const env = @import("env/root.zig");
+ pub const Env = @import("Env/root.zig");
-const Element = @import("html").Element;
-
-pub const script: File = .{
- .tag = .script,
- .minifier = .js,
-};
-pub const style: File = .{
- .tag = .style,
- .minifier = .css,
-};
-pub const body: File = .{
- .tag = .body,
- .minifier = .html,
-};
-
-pub const html: File = .{
- .tag = null,
- .minifier = .html,
-};
-
-pub fn env(comptime components: []const Component) Element {
- var children: []const Element = &.{script.load(@embedFile("z.js"))};
-
- inline for (components) |c| {
- const child: []const Element = &.{c.toElement()};
- children = children ++ child;
+ export const bit_length: u8 = @sizeOf(usize);
+ };
}
- return .transparent(.children(children));
-}
-
-pub fn component(kind: @EnumLiteral(), attrs: anytype, content: Element.Content) Element {
- var element: Element = .native(.@"z-component", attrs, content);
-
- const type_attr: []const Element.Attribute = &.{.{
- .name = "type",
- .value = @tagName(kind),
- }};
- element.attributes = type_attr ++ element.attributes;
+ break :wasm_struct struct {};
+};
- return element;
-}
+pub const env = wasm.env;
+pub const Env = wasm.Env;
-test {
- _ = std.testing.refAllDecls(@This());
-}
+pub const app = @import("app/root.zig");
diff --git a/src/z/z.js b/src/z/z.js
deleted file mode 100644
index ba07b9e..0000000
--- a/src/z/z.js
+++ /dev/null
@@ -1,82 +0,0 @@
-class ZComponent extends HTMLElement {
- constructor() {
- super();
- this.attachShadow({ mode: 'open' });
- }
-
- connectedCallback() {
- const type = this.getAttribute('type');
-
- if (type == null) {
- throw `component without any type given.`;
- }
-
- const template = document.getElementById(`@${type}`);
-
- if (template == null) {
- throw `component '${type}' does not exist.`;
- }
-
- const node = document.importNode(template.content, true);
- this.shadowRoot.appendChild(node);
-
- Zenv.constructors[`component__${type}`](new Zenv(this));
- }
-}
-
-class Zenv {
- static constructors = {};
-
- constructor(doc) {
- this.document = doc;
- }
-
- component(type, slots) {
- const element = document.createElement('z-component');
- element.setAttribute('type', type);
-
- for (const name in slots) {
- const slot = slots[name];
- slot.setAttribute('slot', name);
- element.appendChild(slot);
- }
-
- return element;
- }
-
- populate_attributes(obj, attrs) {
- for (const attr in attrs) {
- if (typeof(obj[attr]) == 'object' && typeof(attrs[attr]) == 'object') {
- this.populate_attributes(obj[attr], attrs[attr]);
- } else {
- obj[attr] = attrs[attr];
- }
- }
- }
-
- native(name, options) {
- const element = document.createElement(name);
- this.populate_attributes(element, options);
- return element;
- }
-
- by_id(id) {
- return this.document.shadowRoot.getElementById(id);
- }
-
- by_selector(query) {
- return this.document.shadowRoot.querySelector(query);
- }
-
- by_selector_all(query) {
- return this.document.shadowRoot.querySelectorAll(query);
- }
-
- get body() {
- return this.document.shadowRoot;
- }
-}
-
-Z = new Zenv(document.body);
-
-customElements.define("z-component", ZComponent);