diff options
Diffstat (limited to 'src')
94 files changed, 2391 insertions, 1684 deletions
diff --git a/src/app/components/gallery/index.css b/src/app/components/gallery/index.css new file mode 100644 index 0000000..35cab60 --- /dev/null +++ b/src/app/components/gallery/index.css @@ -0,0 +1,34 @@ +:host { + background: black; + --gallery-splits: 5; + display: flex; + flex-wrap: wrap; + overflow: auto; +} + +#control { + position: absolute; + bottom: 10px; + right: 70px; + width: 100px; + height: 50px; + background: var(--primary); + border-radius: 50px; + display: grid; + grid-template-columns: 1fr 1fr; + cursor: pointer; + user-select: none; + + div { + user-select: none; + color: var(--color); + width: 50px; + height: 50px; + text-align: center; + align-content: center; + } +} + +app-image { + width: calc(100% / var(--gallery-splits)); +} diff --git a/src/app/components/gallery/index.html b/src/app/components/gallery/index.html new file mode 100644 index 0000000..efa58a3 --- /dev/null +++ b/src/app/components/gallery/index.html @@ -0,0 +1,13 @@ +<div id="control"> + <div onclick="@zoomIn"> + <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus" viewBox="0 0 16 16"> + <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4"> + </path> + </svg> + </div> + <div onclick="@zoomOut"> + <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-dash" viewBox="0 0 16 16"> + <path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8"></path> + </svg> + </div> +</div> diff --git a/src/app/components/gallery/root.zig b/src/app/components/gallery/root.zig new file mode 100644 index 0000000..1eef707 --- /dev/null +++ b/src/app/components/gallery/root.zig @@ -0,0 +1,86 @@ +const std = @import("std"); +const gpa = std.heap.wasm_allocator; + +const zilch = @import("zilch"); +const Object = zilch.Object; +const components = @import("../root.zig"); +const Image = components.Image; + +const app = @import("root").app; + +pub const component: zilch.Component = .build(.{ + .name = "gallery", + .html = .parse(@embedFile("index.html")), + .css = @embedFile("index.css"), + .link = @This(), +}); + +const Self = @This(); + +element: *Object, +body: *Object, +pool: std.heap.MemoryPool(Image), +images: std.ArrayList(*Image), +style: *zilch.Object, +splits: usize, + +pub fn init(self: *Self, element: *Object) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + self.element = element; + self.style = blk: { + var style = self.element.get(&env, "style"); + break :blk try style.await(&env, *zilch.Object); + }; + self.pool = .empty; + self.images = .empty; + self.splits = 5; + + const number_of_boxes: u32 = 1000; + + { + var elements: []zilch.Env.Future(*Object) = try gpa.alloc(zilch.Env.Future(*Object), number_of_boxes); + defer gpa.free(elements); + for (0..number_of_boxes) |index| { + const image = try self.pool.create(gpa); + elements[index] = Image.component.new(image, &env); + try self.images.append(gpa, image); + } + + for (elements[0..], self.images.items) |*el, image| { + try image.init(try el.await(&env)); + var future = image.setUrl(&env, "image/1"); + future.ignore(&env); + } + } + + var body = self.element.get(&env, "shadowRoot"); + + for (self.images.items) |image| { + var append_call = Object.call(body, &env, "append", .{image.element}); + append_call.ignore(&env); + } + + self.body = try body.await(&env, *Object); +} + +pub fn zoomIn(self: *Self) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + self.splits = @max(1, self.splits - 1); + + var future = self.style.call(&env, "setProperty", .{ "--gallery-splits", self.splits }); + future.ignore(&env); +} + +pub fn zoomOut(self: *Self) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + self.splits = @min(10, self.splits + 1); + + var future = self.style.call(&env, "setProperty", .{ "--gallery-splits", self.splits }); + future.ignore(&env); +} diff --git a/src/app/components/icons/index.css b/src/app/components/icons/index.css new file mode 100644 index 0000000..81badfd --- /dev/null +++ b/src/app/components/icons/index.css @@ -0,0 +1,4 @@ +:host { + width: 16px; + height: 16px; +} diff --git a/src/app/components/icons/menu.svg b/src/app/components/icons/menu.svg new file mode 100644 index 0000000..df05f82 --- /dev/null +++ b/src/app/components/icons/menu.svg @@ -0,0 +1,3 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots-vertical" viewBox="0 0 16 16"> + <path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"></path> +</svg> diff --git a/src/app/components/icons/root.zig b/src/app/components/icons/root.zig new file mode 100644 index 0000000..0328472 --- /dev/null +++ b/src/app/components/icons/root.zig @@ -0,0 +1,17 @@ +const zilch = @import("zilch"); + +pub const icons: []const zilch.Component = &.{ + icon("menu"), + icon("upload"), + icon("settings"), +}; + +pub fn icon(name: []const u8) zilch.Component { + return .build(.{ + .namespace = "icon", + .name = name, + .html = .parse(@embedFile(name ++ ".svg")), + .css = @embedFile("index.css"), + .link = struct {}, + }); +} diff --git a/src/app/components/icons/settings.svg b/src/app/components/icons/settings.svg new file mode 100644 index 0000000..783f55f --- /dev/null +++ b/src/app/components/icons/settings.svg @@ -0,0 +1,4 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-gear" viewBox="0 0 16 16"> + <path d="M8 4.754a3.246 3.246 0 1 0 0 6.492 3.246 3.246 0 0 0 0-6.492M5.754 8a2.246 2.246 0 1 1 4.492 0 2.246 2.246 0 0 1-4.492 0"></path> + <path d="M9.796 1.343c-.527-1.79-3.065-1.79-3.592 0l-.094.319a.873.873 0 0 1-1.255.52l-.292-.16c-1.64-.892-3.433.902-2.54 2.541l.159.292a.873.873 0 0 1-.52 1.255l-.319.094c-1.79.527-1.79 3.065 0 3.592l.319.094a.873.873 0 0 1 .52 1.255l-.16.292c-.892 1.64.901 3.434 2.541 2.54l.292-.159a.873.873 0 0 1 1.255.52l.094.319c.527 1.79 3.065 1.79 3.592 0l.094-.319a.873.873 0 0 1 1.255-.52l.292.16c1.64.893 3.434-.902 2.54-2.541l-.159-.292a.873.873 0 0 1 .52-1.255l.319-.094c1.79-.527 1.79-3.065 0-3.592l-.319-.094a.873.873 0 0 1-.52-1.255l.16-.292c.893-1.64-.902-3.433-2.541-2.54l-.292.159a.873.873 0 0 1-1.255-.52zm-2.633.283c.246-.835 1.428-.835 1.674 0l.094.319a1.873 1.873 0 0 0 2.693 1.115l.291-.16c.764-.415 1.6.42 1.184 1.185l-.159.292a1.873 1.873 0 0 0 1.116 2.692l.318.094c.835.246.835 1.428 0 1.674l-.319.094a1.873 1.873 0 0 0-1.115 2.693l.16.291c.415.764-.42 1.6-1.185 1.184l-.291-.159a1.873 1.873 0 0 0-2.693 1.116l-.094.318c-.246.835-1.428.835-1.674 0l-.094-.319a1.873 1.873 0 0 0-2.692-1.115l-.292.16c-.764.415-1.6-.42-1.184-1.185l.159-.291A1.873 1.873 0 0 0 1.945 8.93l-.319-.094c-.835-.246-.835-1.428 0-1.674l.319-.094A1.873 1.873 0 0 0 3.06 4.377l-.16-.292c-.415-.764.42-1.6 1.185-1.184l.292.159a1.873 1.873 0 0 0 2.692-1.115z"></path> +</svg> diff --git a/src/app/components/icons/upload.svg b/src/app/components/icons/upload.svg new file mode 100644 index 0000000..5187f80 --- /dev/null +++ b/src/app/components/icons/upload.svg @@ -0,0 +1,4 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cloud-arrow-up" viewBox="0 0 16 16"> + <path fill-rule="evenodd" d="M7.646 5.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 6.707V10.5a.5.5 0 0 1-1 0V6.707L6.354 7.854a.5.5 0 1 1-.708-.708z"></path> + <path d="M4.406 3.342A5.53 5.53 0 0 1 8 2c2.69 0 4.923 2 5.166 4.579C14.758 6.804 16 8.137 16 9.773 16 11.569 14.502 13 12.687 13H3.781C1.708 13 0 11.366 0 9.318c0-1.763 1.266-3.223 2.942-3.593.143-.863.698-1.723 1.464-2.383m.653.757c-.757.653-1.153 1.44-1.153 2.056v.448l-.445.049C2.064 6.805 1 7.952 1 9.318 1 10.785 2.23 12 3.781 12h8.906C13.98 12 15 10.988 15 9.773c0-1.216-1.02-2.228-2.313-2.228h-.5v-.5C12.188 4.825 10.328 3 8 3a4.53 4.53 0 0 0-2.941 1.1z"></path> +</svg> diff --git a/src/app/components/image/index.css b/src/app/components/image/index.css new file mode 100644 index 0000000..d9a9ff5 --- /dev/null +++ b/src/app/components/image/index.css @@ -0,0 +1,26 @@ +.image { + width: 100%; + padding-bottom: 100%; + height: 0; + background: var(--image); + background-size: cover; + background-position: center; +} + +img { + content: var(--image); + width: 100%; + display: none; + visibility: hidden; +} + +@container style(--gallery-splits: 1) { + .image { + padding-bottom: 0px; + height: unset; + } + + img { + display: unset; + } +} diff --git a/src/app/components/image/index.html b/src/app/components/image/index.html new file mode 100644 index 0000000..2b135dc --- /dev/null +++ b/src/app/components/image/index.html @@ -0,0 +1,3 @@ +<div class="image"> + <img> +</div> diff --git a/src/app/components/image/root.zig b/src/app/components/image/root.zig new file mode 100644 index 0000000..1d46d30 --- /dev/null +++ b/src/app/components/image/root.zig @@ -0,0 +1,32 @@ +const std = @import("std"); +const zilch = @import("zilch"); + +pub const component: zilch.Component = .build(.{ + .name = "image", + .html = .parse(@embedFile("index.html")), + .css = @embedFile("index.css"), + .link = @This(), +}); + +const Self = @This(); + +element: *zilch.Object, +style: *zilch.Object, + +pub fn init(self: *Self, element: *zilch.Object) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + self.element = element; + self.style = blk: { + var style = self.element.get(&env, "style"); + break :blk try style.await(&env, *zilch.Object); + }; +} + +pub fn setUrl(self: *Self, env: *zilch.Env, url: []const u8) zilch.Env.Future(void) { + var buffer: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + writer.print("url({s})", .{url}) catch unreachable; + return .fromAny(self.style.call(env, "setProperty", .{"--image", writer.buffered()})); +} diff --git a/src/app/components/navbutton/index.css b/src/app/components/navbutton/index.css new file mode 100644 index 0000000..6909464 --- /dev/null +++ b/src/app/components/navbutton/index.css @@ -0,0 +1,63 @@ +:host { + position: absolute; + bottom: 10px; + right: 10px; + --items-count: 2; +} + +#button { + position: relative; + width: 50px; + height: 50px; + background: var(--secondary); + border-radius: 50px; + cursor: pointer; + color: var(--color); + transition: 0.2s ease height; + display: grid; + justify-content: center; + align-content: end; + overflow: hidden; +} + +#button.open { + height: calc(50px * (var(--items-count) + 1)); +} + +#menu { + width: 50px; + height: 50px; + background: red; + border-radius: 50px; + display: grid; + background: var(--primary); +} + +.icon { + margin: auto; + width: fit-content; + height: fit-content; + padding-top: 4px; +} + +.items { + height: calc(50px * var(--items-count)); + display: grid; + grid-template-rows: repeat(var(--items-count), auto); +} + +.item { + margin: auto; + width: 40px; + height: 40px; + border-radius: 40px; + display: grid; +} + +.item * { + margin: auto; +} + +.item:hover { + background: #5f5e9c; +} diff --git a/src/app/components/navbutton/index.html b/src/app/components/navbutton/index.html new file mode 100644 index 0000000..f2c9ff8 --- /dev/null +++ b/src/app/components/navbutton/index.html @@ -0,0 +1,12 @@ +<div id="button" onclick="@open"> + <div class="items"> + <div class="item"><icon-upload></icon-upload></div> + <div class="item"><icon-settings></icon-settings></div> + </div> + + <div id="menu"> + <div class="icon"> + <icon-menu></icon-menu> + </div> + </div> +</div> diff --git a/src/app/components/navbutton/root.zig b/src/app/components/navbutton/root.zig new file mode 100644 index 0000000..a512d1d --- /dev/null +++ b/src/app/components/navbutton/root.zig @@ -0,0 +1,58 @@ +const std = @import("std"); +const app = @import("root").app; +const zilch = @import("zilch"); +const Object = zilch.Object; +const Promise = zilch.Promise; + +const Self = @This(); + +pub const component: zilch.Component = .build(.{ + .name = "navbutton", + .html = .parse(@embedFile("index.html")), + .css = @embedFile("index.css"), + .link = @This(), +}); + +element: *zilch.Object, +shadow_root: *zilch.Object, +button: struct { + classList: *zilch.Object, +}, + +pub fn init(self: *Self, element: *Object) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + self.element = element; + + var shadow_root = self.element.get(&env, "shadowRoot"); + + var class_list = cls: { + var button = Object.call(shadow_root, &env, "getElementById", .{"button"}); + defer button.ignore(&env); + defer _ = Object.free(button, &env); + + break :cls Object.get(button, &env, "classList"); + }; + + self.button.classList = try class_list.await(&env, *Object); + + self.shadow_root = try shadow_root.await(&env, *Object); +} + +pub fn deinit(self: *Self) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + _ = self.element.free(&env); + _ = self.shadow_root.free(&env); + _ = self.button.classList.free(&env); +} + +pub fn open(self: *Self) !void { + var env: zilch.Env = .default; + defer env.deinit(); + + var toggle_call = self.button.classList.call(&env, "toggle", .{"open"}); + toggle_call.ignore(&env); +} diff --git a/src/app/components/root.zig b/src/app/components/root.zig new file mode 100644 index 0000000..999a052 --- /dev/null +++ b/src/app/components/root.zig @@ -0,0 +1,13 @@ +const zilch = @import("zilch"); + +const icons = @import("icons/root.zig").icons; + +pub const NavButton = @import("navbutton/root.zig"); +pub const Image = @import("image/root.zig"); +pub const Gallery = @import("gallery/root.zig"); + +pub const components = &[_]zilch.Component{ + NavButton.component, + Image.component, + Gallery.component, +} ++ icons; diff --git a/src/app/index.html b/src/app/index.html new file mode 100644 index 0000000..caf9703 --- /dev/null +++ b/src/app/index.html @@ -0,0 +1,2 @@ +<app-navbutton></app-navbutton> +<app-gallery></app-gallery> diff --git a/src/app/root.zig b/src/app/root.zig new file mode 100644 index 0000000..1a04b21 --- /dev/null +++ b/src/app/root.zig @@ -0,0 +1,31 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const zilch = @import("zilch"); + +pub const panic = zilch.panic; +pub const std_options: std.Options = .{ + .logFn = zilch.log.default, +}; + +const components = @import("components/root.zig").components; + +pub const app: zilch.App(.{ + .name = "Memora", + .favicon = "icon.png", + .functions = &(zilch.Object.functions ++ + zilch.Promise.functions ++ + zilch.Callable.functions ++ + zilch.Component.functions), + .globals = &.{ + zilch.Object.global(.window), + zilch.Object.global(.Object), + zilch.Callable.global(.fetch), + }, + .components = components, + .body = .parse(@embedFile("index.html")), + .theme = @embedFile("theme.css"), +}) = .init; + +comptime { + _ = app; +} diff --git a/src/app/theme.css b/src/app/theme.css new file mode 100644 index 0000000..1034db2 --- /dev/null +++ b/src/app/theme.css @@ -0,0 +1,19 @@ + +:root { + --color: #efefef; + --primary: #726eff; + --secondary: #39378a; +} + +body { + width: 100vw; + height: 100vh; + background: #202020; + margin: 0; + overflow: hidden; +} + +app-gallery { + width: 100%; + height: 100%; +} diff --git a/src/db/sqlite.zig b/src/db/sqlite.zig index 1d27dd5..57fe75c 100644 --- a/src/db/sqlite.zig +++ b/src/db/sqlite.zig @@ -283,7 +283,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, diff --git a/src/favicon.png b/src/favicon.png Binary files differnew file mode 100644 index 0000000..7ff5837 --- /dev/null +++ b/src/favicon.png diff --git a/src/html/Element.zig b/src/html/Element.zig deleted file mode 100644 index a9e5897..0000000 --- a/src/html/Element.zig +++ /dev/null @@ -1,103 +0,0 @@ -const Self = @This(); - -pub const Content = union(enum) { - elements: []const Self, - string: []const u8, - void: void, - - pub fn content(string: []const u8) @This() { - return .{ .string = string }; - } - - pub fn children(elements: []const Self) @This() { - return .{ .elements = elements }; - } -}; - -pub const Attribute = struct { - name: []const u8, - value: []const u8, -}; - -tag: []const u8, -attributes: []const Attribute, -content: Content, - -fn attributesFrom(attributes: anytype) []const Attribute { - const T = @TypeOf(attributes); - const info = @typeInfo(T); - - if (info != .@"struct") { - @compileError("struct needed"); - } - - const fields = info.@"struct".fields; - - var attrs: []const Attribute = &.{}; - - for (fields) |field| { - const name = field.name; - const value = @field(attributes, name); - - const next_attr: []const Attribute = &.{.{ .name = name, .value = value }}; - attrs = attrs ++ next_attr; - } - - return attrs; -} - -pub fn native(name: @EnumLiteral(), attrs: anytype, content: Content) Self { - return .{ - .tag = @tagName(name), - .attributes = attributesFrom(attrs), - .content = content, - }; -} - -pub fn transparent(content: Content) Self { - return .{ - .tag = "", - .attributes = &.{}, - .content = content, - }; -} - -pub fn toHtml(comptime self: Self) []const u8 { - var string: []const u8 = string: { - if (self.tag.len == 0) { - break :string ""; - } - - var string: []const u8 = "<" ++ self.tag; - - inline for (self.attributes) |attr| { - string = string ++ " " ++ attr.name ++ "='" ++ attr.value ++ "'"; - } - - string = string ++ ">"; - - break :string string; - }; - - switch (self.content) { - .void => {}, - .string => |s| { - string = string ++ s ++ "</" ++ self.tag ++ ">"; - }, - .elements => |els| { - for (els) |el| { - string = string ++ el.toHtml(); - } - - string = string ++ "</" ++ self.tag ++ ">"; - }, - } - - string = string ++ if (self.tag.len == 0) "" else "</" ++ self.tag ++ ">"; - - return string; -} - -pub fn toDocument(comptime self: Self) []const u8 { - return "<!DOCTYPE html>" ++ self.toHtml(); -} diff --git a/src/html/root.zig b/src/html/root.zig deleted file mode 100644 index 14a9b3c..0000000 --- a/src/html/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const std = @import("std"); - -pub const Element = @import("Element.zig"); - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/http/Response.zig b/src/http/Response.zig index 69bec65..62c53f5 100644 --- a/src/http/Response.zig +++ b/src/http/Response.zig @@ -18,10 +18,8 @@ pub const Message = union(enum) { return .{ .static = content }; } - pub fn file(io: std.Io, path: []const u8) !Message { - return .{ .streaming = try std.Io.Dir.cwd().openFile(io, path, .{ - .allow_directory = false, - }) }; + pub fn file(f: std.Io.File) Message { + return .{ .streaming = f }; } }; @@ -97,6 +95,7 @@ pub fn send( }); }, .streaming => |file| { + defer file.close(io); var write_buffer: [1024]u8 = undefined; var read_buffer: [1024]u8 = undefined; diff --git a/src/http/handler/root.zig b/src/http/handler/root.zig index 33fdb84..634888c 100644 --- a/src/http/handler/root.zig +++ b/src/http/handler/root.zig @@ -9,7 +9,6 @@ test "interface" { const C = Context(.{ "api", "images", .id, "metadata" }); const context: C = .{ .post = post, - .get = get, }; const Query = struct { @@ -25,10 +24,6 @@ test "interface" { return .ok(.string(request.params.id.as([]const u8))); } - - fn get(request: C.Request) Response { - return .ok(Response.Message.file(request.io, "./some/path.txt") catch return .with(.not_found, .void)); - } }; _ = M.context.interface(); 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/main.zig b/src/main.zig index 176d3b2..308d308 100644 --- a/src/main.zig +++ b/src/main.zig @@ -7,9 +7,38 @@ const std = @import("std"); const http = @import("http"); const api = @import("api"); -const web = @import("web/root.zig"); +const site = @import("site"); +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, site.app.html, "text/html").interface(), + http.handler.Static(.{"index.wasm"}, wasm, "application/wasm").interface(), + http.handler.Static(.{"icon.png"}, @embedFile("favicon.png"), "image/png").interface(), + images.ctx.interface(), +}) ++ api.interfaces); + +const images = struct { + const Ctx = http.handler.Context(.{ "image", .id }); + const ctx: Ctx = .{ + .get = get, + }; + + pub fn get(request: Ctx.Request) http.Response { + const id = request.params.id.as(usize) catch return .badRequest(.string("invalid id")); + + const storage = std.Io.Dir.cwd().openDir(request.io, "storage", .{}) catch return .with(.internal_server_error, .void); + defer storage.close(request.io); + + var allocating: std.Io.Writer.Allocating = .init(request.gpa); + defer allocating.deinit(); + + allocating.writer.print("{}.jpg", .{id}) catch return .with(.internal_server_error, .void); + + const file = storage.openFile(request.io, allocating.written(), .{}) catch return .badRequest(.string("invalid id")); + + return .ok(.file(file)); + } +}; pub fn main(init: std.process.Init) !void { try http.serve(init.gpa, routes, .{ diff --git a/src/root.zig b/src/root.zig index 0cd7c71..d09f37e 100644 --- a/src/root.zig +++ b/src/root.zig @@ -3,5 +3,5 @@ pub const db = @import("db"); pub const api = @import("api"); pub const html = @import("html"); -pub const z = @import("z"); +pub const zilch = @import("zilch"); pub const http = @import("http"); 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/navigation/index.css b/src/web/component/navigation/index.css deleted file mode 100644 index 836e3b5..0000000 --- a/src/web/component/navigation/index.css +++ /dev/null @@ -1,66 +0,0 @@ -#toggle { - --radius-open: 200px; - - position: absolute; - right: 10px; - bottom: 10px; - width: 45px; - height: 45px; - border-radius: 100%; - background: red; - z-index: 500; - cursor: pointer; - text-align: center; - align-content: center; - transition: - border-radius 0.1s ease, - right 0.1s ease, - bottom 0.1s ease, - width 0.1s ease, - height 0.1s ease; - - .bi { - baseline-shift: -2px; - } - - .items { - position: relative; - top: 0px; - left: 0px; - right: 0px; - bottom: 0px; - } - - .item { - display: none; - width: 45px; - height: 45px; - border-radius: 100%; - background: blue; - position: absolute; - right: calc(cos(18deg * var(--index)) * var(--radius-open)); - bottom: calc(sin(18deg * var(--index)) * var(--radius-open)); - font-size: calc(var(--index) * 1px); - } - - .item { - --index: sibling-index(); - } -} - -#toggle.open { - width: var(--radius-open); - height: var(--radius-open); - bottom: 0px; - right: 0px; - border-radius: 0px; - border-top-left-radius: 250px; - - .bi { - display: none; - } - - .item { - display: block; - } -} diff --git a/src/web/component/navigation/index.html b/src/web/component/navigation/index.html deleted file mode 100644 index b3b5ce0..0000000 --- a/src/web/component/navigation/index.html +++ /dev/null @@ -1,11 +0,0 @@ -<div id="toggle"> - <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots-vertical" viewBox="0 0 16 16"> - <path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/> - </svg> - <div class="items"> - <div class="item"></div> - <div class="item"></div> - <div class="item"></div> - <div class="item"></div> - </div> -</div> diff --git a/src/web/component/navigation/index.js b/src/web/component/navigation/index.js deleted file mode 100644 index 2c996a0..0000000 --- a/src/web/component/navigation/index.js +++ /dev/null @@ -1,11 +0,0 @@ - -const toggle = Z.by_id('toggle'); - -toggle.onclick = (event) => { - toggle.classList.toggle('open'); - event.stopPropagation(); -}; - -document.addEventListener('click', () => { - toggle.classList.remove('open'); -}); diff --git a/src/web/component/navigation/root.zig b/src/web/component/navigation/root.zig deleted file mode 100644 index 919cddb..0000000 --- a/src/web/component/navigation/root.zig +++ /dev/null @@ -1,8 +0,0 @@ -const z = @import("z"); - -pub const component: z.Component = .{ - .name = .navigation, - .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 ba2f565..0000000 --- a/src/web/component/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const z = @import("z"); - -pub const components: []const z.Component = &.{ - @import("image/root.zig").component, - @import("timeline/root.zig").component, - @import("navigation/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 bcdecae..0000000 --- a/src/web/index.css +++ /dev/null @@ -1,21 +0,0 @@ -html { - height: 100vh; - width: 100vw; - overflow: hidden; -} - -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 bcbb165..0000000 --- a/src/web/index.html +++ /dev/null @@ -1,4 +0,0 @@ -<z-component type="timeline" id="timeline"> -</z-component> -<z-component type="navigation" id="navigation"> -</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 d027dc8..0000000 --- a/src/web/root.zig +++ /dev/null @@ -1,26 +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/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/File.zig b/src/z/File.zig deleted file mode 100644 index cd19dba..0000000 --- a/src/z/File.zig +++ /dev/null @@ -1,17 +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/parser/js/grammar/identifier.zig b/src/z/parser/js/grammar/identifier.zig deleted file mode 100644 index ccc5268..0000000 --- a/src/z/parser/js/grammar/identifier.zig +++ /dev/null @@ -1,60 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Identifier = enum { - public, - private, - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - defer lexer.revert(); - - lexer.context.regex_possible = false; - - const token = tok: { - if (lexer.peekChar() == '#') { - const t = lexer.start(.{ .identifier = .private }); - lexer.skip() catch unreachable; - break :tok t; - } else { - break :tok lexer.start(.{ .identifier = .public }); - } - }; - - switch (try lexer.consume()) { - 'a'...'z', 'A'...'Z', '_' => {}, - else => return Lexer.Error.UnexpectedToken, - } - - while (lexer.peekChar()) |ch| { - switch (ch) { - 'a'...'z', 'A'...'Z', '0'...'9', '_' => {}, - else => break, - } - - try lexer.skip(); - } - - lexer.commit(token); - } - } -}; - -test "simple" { - { - comptime var lexer: Lexer = .init("some_literal9"); - try Identifier.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(13, lexer.tokens[0].slice.len); - } - - { - comptime var lexer: Lexer = .init("#some_literal9"); - try Identifier.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(14, lexer.tokens[0].slice.len); - } -} diff --git a/src/z/parser/js/grammar/keyword.zig b/src/z/parser/js/grammar/keyword.zig deleted file mode 100644 index 8e99b4a..0000000 --- a/src/z/parser/js/grammar/keyword.zig +++ /dev/null @@ -1,115 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Keyword = enum { - @"break", - case, - @"catch", - class, - @"const", - @"continue", - debugger, - default, - delete, - do, - @"else", - @"export", - extends, - finally, - @"for", - function, - @"if", - import, - in, - instanceof, - new, - @"return", - super, - @"switch", - this, - throw, - @"try", - typeof, - @"var", - void, - @"while", - with, - yield, - let, - static, - await, - async, - of, - from, - get, - set, - meta, - @"enum", - null, - true, - false, - - const Self = @This(); - - const keywordmap: std.StaticStringMap(Self) = .initComptime(kws: { - var keywords: []const struct { []const u8, Self } = &.{}; - - for (@typeInfo(Self).@"enum".fields) |field| { - const name: []const u8 = field.name; - const value: Self = @field(Self, field.name); - - keywords = keywords ++ .{ .{ name, value } }; - } - - break :kws keywords; - }); - - pub inline fn tokenize(lexer: *Lexer) Lexer.Error!void { - comptime { - @setEvalBranchQuota(10000); - errdefer lexer.revert(); - - lexer.context.regex_possible = true; - - const index = std.mem.findNone(u8, lexer.buffer, std.ascii.lowercase) orelse lexer.buffer.len; - - if (index == 0) return Lexer.Error.UnexpectedToken; - - if (keywordmap.get(lexer.buffer[0..index])) |tag| { - const token = lexer.start(.{ .keyword = tag }); - try lexer.skipTo(index); - lexer.commit(token); - } else { - return Lexer.Error.UnexpectedToken; - } - } - } -}; - -test "simple" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key); - try Keyword.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "ending" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "."); - try Keyword.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "subword" { - inline for (comptime Keyword.keywordmap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "a"); - try std.testing.expectError(Lexer.Error.UnexpectedToken, Keyword.tokenize(&lexer)); - } -} diff --git a/src/z/parser/js/grammar/literal.zig b/src/z/parser/js/grammar/literal.zig deleted file mode 100644 index 4316dee..0000000 --- a/src/z/parser/js/grammar/literal.zig +++ /dev/null @@ -1,192 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Literal = union(enum) { - // NOTE: currently only decimal literals are tokenized - numeric: void, - bigint: void, - string: void, - template: enum { - whole, - start, - middle, - end, - }, - regex: void, - - const digits = "_0123456789abcdef"; - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - errdefer lexer.revert(); - - var token = lexer.start(.{ .literal = undefined }); - - const regex_possible = lexer.context.regex_possible; - lexer.context.regex_possible = false; - - switch (try lexer.consume()) { - '0'...'9', '.' => |c| { - const base = if (c != '0') 10 else switch (lexer.peekChar() orelse 0) { - 'x' => 16, - 'o' => 8, - 'b' => 2, - else => 10, - }; - - if (base != 10) lexer.skip() catch unreachable; - - { - const index = std.mem.findNone( - u8, - lexer.buffer, - digits[0 .. base + 1], - ) orelse lexer.buffer.len; - try lexer.skipTo(index); - - - if (index == 0 and base != 10) return Lexer.Error.UnexpectedToken; - } - - if (base == 10 and lexer.peekChar() == '.') { - try lexer.skip(); - const index = std.mem.findNone( - u8, - lexer.buffer, - digits[0 .. base + 1], - ) orelse lexer.buffer.len; - try lexer.skipTo(index); - } - - if (lexer.peekChar() == 'n') { - lexer.skip() catch unreachable; - token.kind.literal = .bigint; - } else { - token.kind.literal = .numeric; - } - }, - '\'', '"' => |quote| { - token.kind.literal = .string; - while (true) { - switch (try lexer.consume()) { - quote => break, - '\\' => try lexer.skip(), - else => {}, - } - } - }, - '`' => { - token.kind.literal = .{ .template = undefined }; - - while (true) { - switch (try lexer.consume()) { - '`' => { - token.kind.literal.template = .whole; - break; - }, - '\\' => try lexer.skip(), - '$' => if (lexer.peekChar() == '{') { - lexer.skip() catch unreachable; - lexer.context.template_nesting += 1; - token.kind.literal.template = .start; - lexer.context.regex_possible = true; - break; - }, - else => {}, - } - } - }, - '}' => if (lexer.context.template_nesting > 0) { - lexer.context.template_nesting -= 1; - token.kind.literal = .{ .template = undefined }; - - while (true) { - switch (try lexer.consume()) { - '`' => { - token.kind.literal.template = .end; - break; - }, - '\\' => try lexer.skip(), - '$' => if (lexer.peekChar() == '{') { - lexer.skip() catch unreachable; - lexer.context.template_nesting += 1; - token.kind.literal.template = .middle; - lexer.context.regex_possible = true; - break; - }, - else => {}, - } - } - } else return Lexer.Error.UnexpectedToken, - '/' => if (regex_possible) { - token.kind.literal = .regex; - while (true) { - switch (try lexer.consume()) { - '/' => break, - '\\' => try lexer.skip(), - '\n' => return Lexer.Error.UnexpectedToken, - else => {}, - } - } - } else return Lexer.Error.UnexpectedToken, - else => return Lexer.Error.UnexpectedToken, - } - - lexer.commit(token); - } - } -}; - -test "numeric" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("1234", 4); - try Simple.run("1.234", 5); - try Simple.run("1_2_3_4", 7); - try Simple.run("0b101011", 8); - try Simple.run("0xabcf01", 8); - try Simple.run("0o731734", 8); - try Simple.run("0o731734n", 9); -} - -test "string" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("'hello'", 7); - try Simple.run("\"hello\"", 7); - try std.testing.expectError( - Lexer.Error.EndOfBuffer, - Simple.run("'hello", 0), - ); -} - -test "regex" { - const Simple = struct { - pub fn run(comptime buffer: []const u8, n: usize) !void { - comptime var lexer: Lexer = .init(buffer); - try Literal.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(n, lexer.tokens[0].slice.len); - } - }; - - try Simple.run("/hello/", 7); - try Simple.run("/some string\\/ here/", 20); -} diff --git a/src/z/parser/js/grammar/punctuator.zig b/src/z/parser/js/grammar/punctuator.zig deleted file mode 100644 index b085ce1..0000000 --- a/src/z/parser/js/grammar/punctuator.zig +++ /dev/null @@ -1,122 +0,0 @@ -const std = @import("std"); - -const root = @import("root.zig"); -const Lexer = root.Lexer; -const Token = root.Token; - -pub const Punctuator = enum { - @"+", - @"-", - @"*", - @"/", - @"%", - @"**", - @"++", - @"--", - @"=", - @"+=", - @"-=", - @"*=", - @"/=", - @"%=", - @"**=", - @"&=", - @"|=", - @"^=", - @"<<=", - @">>=", - @">>>=", - @"&&=", - @"||=", - @"??=", - @"==", - @"===", - @"!=", - @"!==", - @"<", - @"<=", - @">", - @">=", - @"&&", - @"||", - @"??", - @"&", - @"|", - @"^", - @"~", - @"<<", - @">>", - @">>>", - @"!", - @"?", - @":", - @";", - @",", - @".", - @"...", - @"=>", - @"(", - @")", - @"[", - @"]", - @"{", - @"}", - @"?.", - @"#", - @"@", - - const Self = @This(); - - const punctuatormap: std.StaticStringMap(Self) = .initComptime(kws: { - var punctuators: []const struct { []const u8, Self } = &.{}; - - for (@typeInfo(Self).@"enum".fields) |field| { - const name: []const u8 = field.name; - const value: Self = @field(Self, field.name); - - punctuators = punctuators ++ .{.{ name, value }}; - } - - break :kws punctuators; - }); - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - @setEvalBranchQuota(10_000); - defer lexer.revert(); - - lexer.context.regex_possible = true; - - if (punctuatormap.getLongestPrefix(lexer.buffer)) |pair| { - - if (std.mem.eql(u8, pair.key, "}") and lexer.context.template_nesting > 0) { - return Lexer.Error.UnexpectedToken; - } - - const token = lexer.start(.{ .punctuator = pair.value }); - try lexer.skipTo(pair.key.len); - lexer.commit(token); - } else { - return Lexer.Error.UnexpectedToken; - } - } - } -}; - -test "simple" { - inline for (comptime Punctuator.punctuatormap.keys()) |key| { - comptime var lexer: Lexer = .init(key); - try Punctuator.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} - -test "ending" { - inline for (comptime Punctuator.punctuatormap.keys()) |key| { - comptime var lexer: Lexer = .init(key ++ "a"); - try Punctuator.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(key.len, lexer.tokens[0].slice.len); - } -} diff --git a/src/z/parser/js/grammar/root.zig b/src/z/parser/js/grammar/root.zig deleted file mode 100644 index f732b7f..0000000 --- a/src/z/parser/js/grammar/root.zig +++ /dev/null @@ -1,66 +0,0 @@ -//! This is a Javascript parser and tokenizer. -//! It is and probably will never be complete, -//! since js is a very strange language and I want -//! to move forward and code on more interesting things -//! I started something called mujs (micro-js). It's a -//! subset of the javascript language. It does not support -//! the regex literal and currently also not template strings. -//! It is chosen like that to make parsing easier and also less -//! context-dependent. - -const std = @import("std"); - -const parser = @import("../../root.zig"); - -pub const Lexer = parser.Lexer(Grammar); -pub const Token = parser.Token(Grammar); - -pub const Whitespace = @import("whitespace.zig").Whitespace; -pub const Keyword = @import("keyword.zig").Keyword; -pub const Literal = @import("literal.zig").Literal; -pub const Punctuator = @import("punctuator.zig").Punctuator; -pub const Identifier = @import("identifier.zig").Identifier; - -pub const Grammar = union(enum) { - whitespace: Whitespace, - keyword: Keyword, - literal: Literal, - punctuator: Punctuator, - identifier: Identifier, - end_of_file: void, - - pub const Context = struct { - template_nesting: usize = 0, - regex_possible: bool = true, - }; - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - @setEvalBranchQuota(lexer.buffer.len * 1000); - comptime { - while (lexer.peekChar()) |_| { - Whitespace.tokenize(lexer) catch { - Keyword.tokenize(lexer) catch { - Literal.tokenize(lexer) catch { - Punctuator.tokenize(lexer) catch { - try Identifier.tokenize(lexer); - }; - }; - }; - }; - } - - lexer.commit(lexer.start(.end_of_file)); - } - } -}; - -test { - _ = std.testing.refAllDecls(@This()); -} - -test "z.js" { - comptime var lexer: Lexer = .init(@embedFile("../../../z.js")); - Grammar.tokenize(&lexer) catch |err| { - std.debug.print("error: {} at {s}", .{ err, lexer.buffer }); - }; -} diff --git a/src/z/parser/js/grammar/whitespace.zig b/src/z/parser/js/grammar/whitespace.zig deleted file mode 100644 index 08d031f..0000000 --- a/src/z/parser/js/grammar/whitespace.zig +++ /dev/null @@ -1,102 +0,0 @@ -const std = @import("std"); -const Lexer = @import("root.zig").Lexer; -const Token = @import("root.zig").Token; - -pub const Whitespace = enum { - space, - line_comment, - block_comment, - - pub inline fn tokenize(comptime lexer: *Lexer) Lexer.Error!void { - comptime { - errdefer lexer.revert(); - - var token = lexer.start(.{ .whitespace = undefined }); - - switch (try lexer.consume()) { - ' ', '\t', '\r', '\n' => { - token.kind.whitespace = .space; - - while (lexer.peekChar()) |ch| { - switch (ch) { - ' ', '\t', '\r', '\n' => try lexer.skip(), - else => break, - } - } - }, - '/' => { - switch (lexer.peekChar() orelse 0) { - '*' => { - token.kind.whitespace = .block_comment; - try lexer.skipUntil("*/"); - }, - '/' => { - token.kind.whitespace = .line_comment; - lexer.skipUntil("\n") catch lexer.skipToEnd(); - }, - else => return Lexer.Error.UnexpectedToken, - } - }, - else => return Lexer.Error.UnexpectedToken, - } - - lexer.commit(token); - } - } -}; - -test "space" { - { - comptime var lexer: Lexer = .init(" "); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(1, lexer.tokens[0].slice.len); - } - - { - comptime var lexer: Lexer = .init(" \t\t \n\r "); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqual(10, lexer.tokens[0].slice.len); - } -} - -test "line-comment" { - { - comptime var lexer: Lexer = .init("// some comment"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("// some comment", lexer.tokens[0].slice); - } - - { - comptime var lexer: Lexer = .init("// some comment\n"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("// some comment\n", lexer.tokens[0].slice); - } -} - -test "block-comment" { - { - comptime var lexer: Lexer = .init("/* some comment */"); - try Whitespace.tokenize(&lexer); - try std.testing.expectEqual(1, lexer.tokens.len); - try std.testing.expectEqualStrings("/* some comment */", lexer.tokens[0].slice); - } -} - -test "mixed" { - comptime var lexer: Lexer = .init( - \\ // some comment - \\/* other comment here */ // comment or so - \\ /* multi - \\ * line - \\ * comment - \\ */ - ); - inline while (Whitespace.tokenize(&lexer)) { - } else |_| {} - - try std.testing.expectEqual(7, lexer.tokens.len); -} diff --git a/src/z/parser/js/root.zig b/src/z/parser/js/root.zig deleted file mode 100644 index e604855..0000000 --- a/src/z/parser/js/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const std = @import("std"); - -pub const grammar = @import("./grammar/root.zig"); - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/z/parser/lexer.zig b/src/z/parser/lexer.zig deleted file mode 100644 index 5beefde..0000000 --- a/src/z/parser/lexer.zig +++ /dev/null @@ -1,127 +0,0 @@ -const std = @import("std"); - -pub fn Token(TokenKind: type) type { - return struct { - const Self = @This(); - - kind: TokenKind, - slice: []const u8, - - pub fn start(comptime lexer: *const Lexer(TokenKind), kind: TokenKind) Self { - return .{ - .kind = kind, - .slice = lexer.buffer, - }; - } - - pub inline fn stop(comptime self: Self, comptime lexer: *const Lexer(TokenKind)) Self { - comptime { - const length = self.slice.len - lexer.buffer.len; - return .{ - .kind = self.kind, - .slice = self.slice[0..length], - }; - } - } - - pub fn format(self: *const Self, writer: *std.Io.Writer) !void { - try writer.print("Token{}(\"{s}\")", .{self.kind, self.slice}); - } - }; -} - -pub fn Lexer(TokenKind: type) type { - return struct { - const Self = @This(); - - pub const Error = error{ - UnexpectedToken, - EndOfBuffer, - }; - - buffer: []const u8, - last_buffer: []const u8, - tokens: []const Token(TokenKind) = &.{}, - context: TokenKind.Context = .{}, - last_context: TokenKind.Context = .{}, - - pub fn init(buffer: []const u8) Self { - return .{ - .buffer = buffer, - .last_buffer = buffer, - }; - } - - pub inline fn peekChar(self: *Self) ?u8 { - return self.peekCharAt(0); - } - - pub inline fn peekCharAt(self: *Self, n: usize) ?u8 { - return if (n < self.buffer.len) self.buffer[n] else null; - } - - pub fn peekSlice(self: *Self, length: usize) ?[]const u8 { - return self.peekSliceAt(length, 0); - } - - pub fn peekSliceAt(self: *Self, length: usize, offset: usize) ?[]const u8 { - if (length + offset <= self.buffer.len) { - return self.buffer[offset .. offset + length]; - } - return null; - } - - pub fn consume(self: *Self) !u8 { - return (try self.consumeTo(1))[0]; - } - - pub fn consumeTo(self: *Self, n: usize) ![]const u8 { - if (n <= self.buffer.len) { - const slice = self.buffer[0..n]; - self.buffer = self.buffer[n..]; - return slice; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skip(self: *Self) !void { - return self.skipTo(1); - } - - pub fn skipTo(self: *Self, n: usize) Error!void { - if (n <= self.buffer.len) { - self.buffer = self.buffer[n..]; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skipUntil(self: *Self, literal: []const u8) Error!void { - if (std.mem.find(u8, self.buffer, literal)) |index| { - self.buffer = self.buffer[index + literal.len..]; - } else { - return Error.EndOfBuffer; - } - } - - pub fn skipToEnd(self: *Self) void { - self.buffer = self.buffer[self.buffer.len..]; - } - - pub fn start(self: *Self, kind: TokenKind) Token(TokenKind) { - return .start(self, kind); - } - - pub fn revert(self: *Self) void { - self.buffer = self.last_buffer; - self.context = self.last_context; - } - - pub fn commit(self: *Self, tok: Token(TokenKind)) void { - self.tokens = self.tokens ++ [_]Token(TokenKind){tok.stop(self)}; - self.last_buffer = self.buffer; - self.last_context = self.context; - } - }; -} diff --git a/src/z/parser/root.zig b/src/z/parser/root.zig deleted file mode 100644 index e0b67fb..0000000 --- a/src/z/parser/root.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const lexer = @import("lexer.zig"); -pub const Lexer = lexer.Lexer; -pub const Token = lexer.Token; - -pub const js = @import("js/root.zig"); - -pub fn Parser(TokenType: type) type { - return struct { - buffer: []const TokenType, - }; -} - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/z/rest.js b/src/z/rest.js deleted file mode 100644 index c14944d..0000000 --- a/src/z/rest.js +++ /dev/null @@ -1,20 +0,0 @@ - -const Rest = { - Request: class { - constructor(base) { - this.base = base; - } - - get(url) { return fetch(url); } - - post(url, body) { - return fetch( - url, - { - method: 'POST', - body: JSON.stringify(body), - } - ); - } - }, -}; diff --git a/src/z/root.zig b/src/z/root.zig deleted file mode 100644 index 1fa8d99..0000000 --- a/src/z/root.zig +++ /dev/null @@ -1,56 +0,0 @@ -const std = @import("std"); - -pub const Minifier = @import("Minifier.zig"); -pub const Component = @import("Component.zig"); -pub const File = @import("File.zig"); -pub const parser = @import("parser/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")), - script.load(@embedFile("rest.js")), - }; - - inline for (components) |c| { - const child: []const Element = &.{c.toElement()}; - children = children ++ child; - } - - 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; - - return element; -} - -test { - _ = std.testing.refAllDecls(@This()); -} diff --git a/src/z/z.js b/src/z/z.js deleted file mode 100644 index e279f42..0000000 --- a/src/z/z.js +++ /dev/null @@ -1,101 +0,0 @@ -class ZComponent extends HTMLElement { - static observedAttributes = [ 'type' ]; - - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - this.onconnected = () => {}; - this.ondisconnected = () => {}; - } - - build() { - 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)); - } - - attributeChangedCallback(name, previous, current) { - if (name == 'type') { - this.shadowRoot.innerHTML = ''; - this.build() - } - } - - connectedCallback() { - this.onconnected(); - } - - disconnectedCallback() { - this.ondisconnected(); - } -} - -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); diff --git a/src/zilch/AppBundle.zig b/src/zilch/AppBundle.zig new file mode 100644 index 0000000..c3e20cf --- /dev/null +++ b/src/zilch/AppBundle.zig @@ -0,0 +1,50 @@ +const std = @import("std"); + +pub const Options = struct { + root_source_file: std.Build.LazyPath, + target: std.Build.ResolvedTarget, +}; + +mod: *std.Build.Module, +wasm: struct { + mod: *std.Build.Module, + exe: *std.Build.Step.Compile, +}, + +pub fn init(b: *std.Build, options: Options, zilch_mod: *std.Build.Module) @This() { + const module = b.addModule("site", .{ + .root_source_file = options.root_source_file, + .target = options.target, + .imports = &.{ .{ .name = "zilch", .module = zilch_mod } }, + }); + + const wasm_module = b.createModule(.{ + .root_source_file = options.root_source_file, + .target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + }), + .imports = &.{ .{ .name = "zilch", .module = zilch_mod } }, + }); + + const exe = b.addExecutable(.{ + .name = "runtime", + .root_module = wasm_module, + }); + + exe.rdynamic = true; + exe.entry = .disabled; + exe.export_table = true; + + return .{ + .mod = module, + .wasm = .{ + .exe = exe, + .mod = wasm_module, + }, + }; +} + +pub fn getEmittedWasm(self: *const @This()) std.Build.LazyPath { + return self.wasm.exe.getEmittedBin(); +} diff --git a/src/zilch/Callable.zig b/src/zilch/Callable.zig new file mode 100644 index 0000000..d668953 --- /dev/null +++ b/src/zilch/Callable.zig @@ -0,0 +1,27 @@ +const mod = @import("root.zig"); +const Options = mod.Options; +const Env = mod.Env; +const AnyFuture = Env.AnyFuture; +const Function = Env.Function; + +const Self = @This(); + +pub inline fn call(self: anytype, env: *Env, args: anytype) AnyFuture { + return env.call(bindings.call, .{ self } ++ args); +} + +pub const bindings = struct { + pub const call: Function = .from( + \\function(target, ...args) { + \\ return target(...args); + \\} + ); +}; + +pub const functions = [_]Function{ + bindings.call, +}; + +pub fn global(tag: @EnumLiteral()) Options.Global { + return .{ .name = @tagName(tag), .type = *Self }; +} diff --git a/src/zilch/Component.zig b/src/zilch/Component.zig new file mode 100644 index 0000000..592b464 --- /dev/null +++ b/src/zilch/Component.zig @@ -0,0 +1,225 @@ +const std = @import("std"); +const Fragment = @import("root.zig").html.Fragment; +const Element = @import("root.zig").html.Element; +const Attribute = @import("root.zig").html.Attribute; +const Object = @import("Object.zig"); +const Env = @import("root.zig").Env; +const Function = Env.Function; +const Future = Env.Future; + +const Self = @This(); + +pub const Options = struct { + namespace: []const u8 = "app", + name: []const u8, + html: Fragment, + css: []const u8, + link: type, +}; + +namespace: []const u8, +name: []const u8, +html: Fragment, +css: []const u8, +link: type, +id: u32, + +pub fn build(comptime options: Options) Self { + return .{ + .namespace = options.namespace, + .name = options.name, + .html = options.html, + .css = options.css, + .link = options.link, + .id = std.hash.XxHash32.hash(4654, options.namespace ++ "-" ++ options.name), + }; +} + +fn handlerNeedsEvent(func: anytype) bool { + const T = @TypeOf(func); + return @typeInfo(T).@"fn".params.len == 2; +} + +fn wrapHandler(ret: anytype) void { + const T = @TypeOf(ret); + const ret_info = @typeInfo(T); + + if (ret_info == .error_union) { + ret catch |err| { + std.log.err("error: {}", .{err}); + }; + } +} + +fn exportFromHtml(self: *const Self, element: Element) void { + comptime { + switch (element) { + .tag => |tag| for (tag.attributes) |attr| { + if (attr.value.len > 0 and attr.value[0] == '@') { + const event_handler = @field(self.link, attr.value[1..]); + + const func = + if (handlerNeedsEvent(event_handler)) + struct { + pub fn func(obj: *self.link, event: *Object) callconv(.c) void { + wrapHandler(event_handler(obj, event)); + } + }.func + else + struct { + pub fn func(obj: *self.link) callconv(.c) void { + wrapHandler(event_handler(obj)); + } + }.func; + + @export( + &func, + .{ + .name = std.fmt.comptimePrint( + "export::{s}::{s}", + .{ self.name, attr.value[1..] }, + ), + }, + ); + } + + switch (tag.content) { + .children => |children| for (children) |child| { + self.exportFromHtml(child); + }, + else => {}, + } + }, + else => {}, + } + } +} + +pub fn exportLinks(self: *const Self) void { + const init = struct { + pub fn init(element: *Object) callconv(.c) ?*self.link { + const obj = std.heap.wasm_allocator.create(self.link) catch return null; + if (@hasDecl(self.link, "init")) { + wrapHandler(obj.init(element)); + } + return obj; + } + }.init; + + @export( + &init, + .{ + .name = std.fmt.comptimePrint( + "export::{s}::init", + .{self.name}, + ), + }, + ); + + for (self.html.elements) |element| { + comptime self.exportFromHtml(element); + } +} + +fn linkAttributes(self: *const Self, attributes: []const Attribute) []const Attribute { + var linked: []const Attribute = &.{}; + + for (attributes) |attr| { + if (attr.value.len > 0 and attr.value[0] == '@') { + const event_handler = @field(self.link, attr.value[1..]); + const attribute: Attribute = .{ + .name = attr.name, + .value = std.fmt.comptimePrint( + "wasm_handle_event(this, \"export::{s}::{s}\", event, {})", + .{ self.name, attr.value[1..], handlerNeedsEvent(event_handler) }, + ), + }; + linked = linked ++ .{attribute}; + } else { + linked = linked ++ .{attr}; + } + } + return linked; +} + +fn linkHtmlRecursive(self: *const Self, element: Element) Element { + comptime { + return switch (element) { + .tag => |el| .{ + .tag = .{ + .name = el.name, + .attributes = self.linkAttributes(el.attributes), + .content = switch (el.content) { + .children => |children| ch: { + var elements: []const Element = &.{}; + + for (children) |child| { + const e: []const Element = &.{self.linkHtmlRecursive(child)}; + elements = elements ++ e; + } + + break :ch .{ .children = elements }; + }, + .void => .void, + }, + }, + }, + .string => element, + }; + } +} + +pub fn toElement(self: *const Self) []const Element { + return &.{ + .node( + "template", + .{ .id = "@" ++ self.name }, + [_]Element{ + .node("style", .{}, &.{.text(self.css)}), + } ++ (html: { + var elements: []const Element = &.{}; + + for (self.html.elements) |element| { + elements = elements ++ .{self.linkHtmlRecursive(element)}; + } + + break :html elements; + }), + ), + .node( + "script", + .{}, + &.{.text( + std.fmt.comptimePrint( + @embedFile("component.template.js"), + .{ + self.namespace, + self.name, + self.name, + self.name, + }, + ), + )}, + ), + }; +} + +pub fn new(self: Self, obj: *self.link, env: *Env) Future(*Object) { + return .fromAny(env.call(bindings.new, .{ @as(usize, @intCast(self.id)), @intFromPtr(obj) })); +} + +const bindings = struct { + pub const new: Function = .from( + \\function(name_id, ptr) { + \\ const el = document.createElement(component_registry[name_id]); + \\ el[ZsPtr] = ptr; + \\ const id = ObjectStore.generateFreeId(); + \\ ObjectStore.registerObject(id, el); + \\ return el; + \\} + ); +}; + +pub const functions = [_]Function{ + bindings.new, +}; diff --git a/src/zilch/Env/Function.zig b/src/zilch/Env/Function.zig new file mode 100644 index 0000000..c37b1c7 --- /dev/null +++ b/src/zilch/Env/Function.zig @@ -0,0 +1,15 @@ +const std = @import("std"); + +const Self = @This(); + +content: []const u8, +id: u32, +await: bool, + +pub fn from(content: []const u8) Self { + return .{ + .content = content, + .id = std.hash.XxHash32.hash(4654, content), + .await = std.mem.startsWith(u8, content, "async ") or std.mem.startsWith(u8, content, "async("), + }; +} diff --git a/src/zilch/Env/call.zig b/src/zilch/Env/call.zig new file mode 100644 index 0000000..1681165 --- /dev/null +++ b/src/zilch/Env/call.zig @@ -0,0 +1,5 @@ + +pub const Call = extern struct { + kind: u32, + num_args: u8, +}; diff --git a/src/zilch/Env/future.zig b/src/zilch/Env/future.zig new file mode 100644 index 0000000..43f46c5 --- /dev/null +++ b/src/zilch/Env/future.zig @@ -0,0 +1,72 @@ +const std = @import("std"); +const Env = @import("root.zig"); +const z = @import("../root.zig"); + + +pub fn Future(Kind: type) type { + return struct { + const Self = @This(); + + future: AnyFuture, + + pub fn fromAny(future: AnyFuture) Self { + return .{ .future = future }; + } + + pub fn await(self: *Self, env: *Env) !Kind { + return self.future.await(env, Kind); + } + + pub fn ignore(self: *Self, env: *Env) void { + return self.future.ignore(env); + } + }; +} + +pub const AnyFuture = union(enum) { + const Self = @This(); + + ignored: void, + unresolved: struct { + id: usize, + value: *Env.Value, + }, + resolved: Env.Value, + err: anyerror, + + pub fn await(self: *Self, env: *Env, Kind: type) !Kind { + const result = try self.awaitAny(env); + return result.unwrap(Kind); + } + + pub fn awaitAny(self: *Self, env: *Env) !Env.Value { + defer self.* = undefined; + switch (self.*) { + .ignored => { + env.flush(); + return .from({}); + }, + .err => |err| return err, + .resolved => |result| return result, + .unresolved => |result| { + const value = result.value; + defer env.release(value); + + env.flush(); + + self.* = .{ .resolved = value.* }; + + return value.*; + } + } + } + + pub fn ignore(self: *Self, env: *Env) void { + defer self.* = .ignored; + + switch (self.*) { + .unresolved => env.ignore(self), + else => {}, + } + } +}; diff --git a/src/zilch/Env/js.zig b/src/zilch/Env/js.zig new file mode 100644 index 0000000..a653192 --- /dev/null +++ b/src/zilch/Env/js.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const Env = @import("root.zig"); + +pub extern "object_store" fn process( + [*]const u16, + [*]const Env.Value, + [*]*Env.Value, + length: usize, +) void; + +export fn valueAllocBuffer(value: *Env.Value, len: usize) [*]u8 { + const ptr: [*]u8 = @ptrCast(std.heap.wasm_allocator.alloc(u8, len) catch @panic("unable to allocate string")); + value.kind = .string; + value.value = .{ + .string = .{ + .ptr = ptr, + .len = len, + }, + }; + + return @constCast(value.value.string.ptr); +} diff --git a/src/zilch/Env/root.zig b/src/zilch/Env/root.zig new file mode 100644 index 0000000..d169b5f --- /dev/null +++ b/src/zilch/Env/root.zig @@ -0,0 +1,77 @@ +const std = @import("std"); + +const js = @import("js.zig"); +const Object = @import("../Object.zig"); + +pub const Call = @import("call.zig").Call; +pub const AnyFuture = @import("future.zig").AnyFuture; +pub const Future = @import("future.zig").Future; +pub const Value = @import("value.zig").Value; +pub const Function = @import("Function.zig"); + +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, + +const Self = @This(); + +pub const default: Self = .{ .gpa = std.heap.wasm_allocator }; + +pub fn call(self: *Self, function: Function, args: anytype) AnyFuture { + const id = self.calls.items.len; + + self.calls.append(self.gpa, .{ + .kind = function.id, + .num_args = args.len, + }) catch |err| return .{ .err = err }; + + inline for (args) |arg| { + self.values.append(self.gpa, .from(arg)) catch |err| return .{ .err = err }; + } + + const result = self.pool.create(self.gpa) catch |err| return .{ .err = err }; + errdefer self.pool.destroy(result); + self.results.append(self.gpa, result) catch |err| return .{ .err = err }; + return .{ + .unresolved = .{ + .id = id, + .value = 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.calls.clearRetainingCapacity(); + self.values.clearRetainingCapacity(); + self.results.clearRetainingCapacity(); +} + +pub fn release(self: *Self, value: *Value) void { + self.pool.destroy(value); +} + +pub fn ignore(self: *Self, future: *const AnyFuture) void { + if (self.results.items.len < future.unresolved.id and self.results.items[future.unresolved.id] == future.unresolved.value) { + self.pool.destroy(future.unresolved.value); + self.results.items[future.unresolved.id] = null; + } +} + +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/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig b/src/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig new file mode 100644 index 0000000..7ce2ce8 --- /dev/null +++ b/src/zilch/Env/value.sync-conflict-20261030-190805-2JYANE7.zig @@ -0,0 +1,185 @@ +const std = @import("std"); +const Object = @import("../Object.zig"); +const AnyFuture = @import("future.zig").AnyFuture; + +pub fn isString(comptime T: type) bool { + return comptime blk: { + const info = @typeInfo(T); + if (info != .pointer) break :blk false; + + const ptr = &info.pointer; + if (ptr.is_volatile or ptr.is_allowzero) break :blk false; + + if (ptr.size == .slice) { + break :blk ptr.child == u8; + } + + if (ptr.size == .one) { + const child = @typeInfo(ptr.child); + if (child == .array) { + const arr = &child.array; + break :blk arr.child == u8; + } + } + + break :blk false; + }; +} + +pub fn isObjectRef(comptime T: type) bool { + comptime { + const info = @typeInfo(T); + if (info != .pointer) return false; + + const ptr = &info.pointer; + return ptr.size == .one and @sizeOf(ptr.child) == 0; + } +} + +pub const Value = extern struct { + kind: Kind, + value: extern union { + object: *anyopaque, + string: extern struct { + ptr: [*]const u8, + len: usize, + }, + int: isize, + uint: usize, + float: f64, + undefined: void, + future: usize, + }, + + pub fn from(value: anytype) Value { + const T = @TypeOf(value); + + return switch (T) { + comptime_int => if (value >= 0) .{ + .kind = .uint, + .value = .{ .uint = value }, + } else .{ + .kind = .int, + .value = .{ .int = value }, + }, + usize => .{ + .kind = .uint, + .value = .{ .uint = value }, + }, + isize => .{ + .kind = .int, + .value = .{ .int = value }, + }, + f64, f32, f16 => .{ + .kind = .float, + .value = .{ .float = value }, + }, + void => .{ + .kind = .undefined, + .value = .{ .undefined = {} }, + }, + AnyFuture => .{ + .kind = .future, + .value = .{ .future = value.unresolved.id }, + }, + else => blk: { + if (comptime isString(T)) { + break :blk .{ + .kind = .string, + .value = .{ + .string = .{ + .ptr = @ptrCast(value), + .len = value.len, + }, + }, + }; + } else if (comptime isObjectRef(T)) { + break :blk .{ + .kind = .object, + .value = .{ .object = @ptrCast(value) }, + }; + } else if (@typeInfo(T) == .int) { + // TODO: weil kuscheln mit janina. + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub fn unwrap(self: *const Value, T: type) T { + if (Kind.fromType(T) != self.kind) { + std.log.err("unexpected {}, expected {}", .{ self.kind, T }); + @panic("type error"); + } + + return switch (T) { + comptime_int => self.value.int, + usize => self.value.uint, + isize => self.value.int, + f64, f32, f16 => self.value.float, + void => {}, + AnyFuture => @panic("unsupported return type"), + else => blk: { + if (comptime isString(T)) { + break :blk self.value.string.ptr[0..self.value.string.len]; + } else if (comptime isObjectRef(T)) { + break :blk @ptrCast(self.value.object); + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub const Kind = enum(u8) { + object = 0, + string = 1, + int = 2, + uint = 3, + float = 4, + undefined = 5, + future = 6, + + pub fn asType(comptime self: Kind) type { + return switch (self) { + .object => return *Object, + .string => return []const u8, + .int => return isize, + .uint => return usize, + .float => f64, + .undefined => return void, + .future => AnyFuture, + }; + } + + pub fn fromType(T: type) Kind { + return switch (T) { + comptime_int => .int, + usize => .uint, + isize => .int, + f64, f32, f16 => .float, + void => .undefined, + AnyFuture => .future, + else => blk: { + if (comptime isString(T)) { + break :blk .string; + } else if (comptime isObjectRef(T)) { + break :blk .object; + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + }; +}; diff --git a/src/zilch/Env/value.zig b/src/zilch/Env/value.zig new file mode 100644 index 0000000..ea54ff2 --- /dev/null +++ b/src/zilch/Env/value.zig @@ -0,0 +1,183 @@ +const std = @import("std"); +const Object = @import("../Object.zig"); +const AnyFuture = @import("future.zig").AnyFuture; + +pub fn isString(comptime T: type) bool { + return comptime blk: { + const info = @typeInfo(T); + if (info != .pointer) break :blk false; + + const ptr = &info.pointer; + if (ptr.is_volatile or ptr.is_allowzero) break :blk false; + + if (ptr.size == .slice) { + break :blk ptr.child == u8; + } + + if (ptr.size == .one) { + const child = @typeInfo(ptr.child); + if (child == .array) { + const arr = &child.array; + break :blk arr.child == u8; + } + } + + break :blk false; + }; +} + +pub fn isObjectRef(comptime T: type) bool { + comptime { + const info = @typeInfo(T); + if (info != .pointer) return false; + + const ptr = &info.pointer; + return ptr.size == .one and @sizeOf(ptr.child) == 0; + } +} + +pub const Value = extern struct { + kind: Kind, + value: extern union { + object: *anyopaque, + string: extern struct { + ptr: [*]const u8, + len: usize, + }, + int: isize, + uint: usize, + float: f64, + undefined: void, + future: usize, + }, + + pub fn from(value: anytype) Value { + const T = @TypeOf(value); + + return switch (T) { + comptime_int => if (value >= 0) .{ + .kind = .uint, + .value = .{ .uint = value }, + } else .{ + .kind = .int, + .value = .{ .int = value }, + }, + usize => .{ + .kind = .uint, + .value = .{ .uint = value }, + }, + isize => .{ + .kind = .int, + .value = .{ .int = value }, + }, + f64, f32, f16 => .{ + .kind = .float, + .value = .{ .float = value }, + }, + void => .{ + .kind = .undefined, + .value = .{ .undefined = {} }, + }, + AnyFuture => .{ + .kind = .future, + .value = .{ .future = value.unresolved.id }, + }, + else => blk: { + if (comptime isString(T)) { + break :blk .{ + .kind = .string, + .value = .{ + .string = .{ + .ptr = @ptrCast(value), + .len = value.len, + }, + }, + }; + } else if (comptime isObjectRef(T)) { + break :blk .{ + .kind = .object, + .value = .{ .object = @ptrCast(value) }, + }; + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub fn unwrap(self: *const Value, T: type) T { + if (Kind.fromType(T) != self.kind) { + std.log.err("unexpected {}, expected {}", .{ self.kind, T }); + @panic("type error"); + } + + return switch (T) { + comptime_int => self.value.int, + usize => self.value.uint, + isize => self.value.int, + f64, f32, f16 => self.value.float, + void => {}, + AnyFuture => @panic("unsupported return type"), + else => blk: { + if (comptime isString(T)) { + break :blk self.value.string.ptr[0..self.value.string.len]; + } else if (comptime isObjectRef(T)) { + break :blk @ptrCast(self.value.object); + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub const Kind = enum(u8) { + object = 0, + string = 1, + int = 2, + uint = 3, + float = 4, + undefined = 5, + future = 6, + + pub fn asType(comptime self: Kind) type { + return switch (self) { + .object => return *Object, + .string => return []const u8, + .int => return isize, + .uint => return usize, + .float => f64, + .undefined => return void, + .future => AnyFuture, + }; + } + + pub fn fromType(T: type) Kind { + return switch (T) { + comptime_int => .int, + usize => .uint, + isize => .int, + f64, f32, f16 => .float, + void => .undefined, + AnyFuture => .future, + else => blk: { + if (comptime isString(T)) { + break :blk .string; + } else if (comptime isObjectRef(T)) { + break :blk .object; + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + }; +}; diff --git a/src/zilch/Object.zig b/src/zilch/Object.zig new file mode 100644 index 0000000..1d30b8a --- /dev/null +++ b/src/zilch/Object.zig @@ -0,0 +1,85 @@ +const mod = @import("root.zig"); +const Options = mod.Options; +const Env = mod.Env; +const AnyFuture = Env.AnyFuture; +const Future = Env.Future; +const Function = Env.Function; + +const Self = @This(); + +pub inline fn get(self: anytype, env: *Env, key: anytype) AnyFuture { + return env.call(bindings.get, .{ self, key }); +} + +pub inline fn set(self: anytype, env: *Env, key: anytype, value: anytype) Future(void) { + return .fromAny(env.call(bindings.set, .{ self, key, value })); +} + +pub inline fn delete(self: anytype, env: *Env, key: anytype) Future(void) { + return .fromAny(env.call(bindings.delete, .{ self, key })); +} + +pub inline fn call(self: anytype, env: *Env, method: []const u8, args: anytype) AnyFuture { + return env.call(bindings.call, .{ self, method } ++ args); +} + +pub inline fn free(self: anytype, env: *Env) Future(void) { + return .fromAny(env.call(bindings.free, .{self})); +} + +pub inline fn new(self: anytype, env: *Env) Future(*Self) { + return .fromAny(env.call(bindings.new, .{self})); +} + +pub fn global(tag: @EnumLiteral()) Options.Global { + return .{ .name = @tagName(tag), .type = *Self }; +} + +pub const bindings = struct { + pub const get: Function = .from( + \\function(target, key) { + \\ return target[key]; + \\} + ); + + pub const set: Function = .from( + \\function(target, key, value) { + \\ target[key] = value; + \\} + ); + + pub const delete: Function = .from( + \\function(target, key) { + \\ delete target[key]; + \\} + ); + + pub const call: Function = .from( + \\function(target, method, ...args) { + \\ return target[method](...args); + \\} + ); + + pub const new: Function = .from( + \\function(target, ...args) { + \\ return new target(...args); + \\} + ); + + pub const free: Function = .from( + \\function(target) { + \\ const id = target[ZsId]; + \\ delete target[ZsId]; + \\ delete ObjectStore.store[id]; + \\} + ); +}; + +pub const functions = [_]Function{ + bindings.get, + bindings.set, + bindings.delete, + bindings.call, + bindings.new, + bindings.free, +}; diff --git a/src/zilch/Promise.zig b/src/zilch/Promise.zig new file mode 100644 index 0000000..7832b66 --- /dev/null +++ b/src/zilch/Promise.zig @@ -0,0 +1,62 @@ +const std = @import("std"); + +const mod = @import("root.zig"); +const Env = mod.Env; +const Future = Env.Future; +const Function = Env.Function; +const Object = mod.Object; +const Value = mod.Value; + +const Self = @This(); + +// NOTE: js runs only on one thread, so this is safe, +// else an allocation would be necessary! +var promise_value: Value = undefined; + +pub inline fn then(self: anytype, env: *Env, func: anytype, ud: *anyopaque) Future(void) { + const wrapper = struct { + fn wrapper(userdata: *anyopaque) callconv(.c) void { + const args = @typeInfo(@TypeOf(func)).@"fn".params; + + const value = promise_value.unwrap(args[1].type orelse void); + + func(@alignCast(@ptrCast(userdata)), value) catch |err| { + std.log.err("{}", .{err}); + @panic("error handling promise"); + }; + } + }.wrapper; + return .fromAny(env.call(bindings.then, .{ + self, + @intFromPtr(&wrapper), + @intFromPtr(&promise_value), + @intFromPtr(ud), + })); +} + +pub inline fn await(self: anytype, env: *Env, T: type) !T { + var future = env.call(bindings.await, .{ self }); + return future.await(env, T); +} + +pub const bindings = struct { + pub const then: Function = .from( + \\function(promise, func, ptr, ud) { + \\ promise.then((value) => { + \\ ObjectStore.writeValue(ptr, value); + \\ wasm.exports.__indirect_function_table.get(func)(ud); + \\ }) + \\} + ); + + pub const await: Function = .from( + \\async function(promise) { + \\ return promise; + \\} + ); +}; + +pub const functions = [_]Function{ + bindings.then, + bindings.await, +}; diff --git a/src/zilch/app/Options.zig b/src/zilch/app/Options.zig new file mode 100644 index 0000000..db1742d --- /dev/null +++ b/src/zilch/app/Options.zig @@ -0,0 +1,17 @@ +const mod = @import("../root.zig"); +const Fragment = mod.html.Fragment; +const Component = mod.Component; +const Env = mod.Env; + +name: []const u8, +favicon: []const u8, +functions: []const Env.Function, +globals: []const Global, +components: []const Component, +body: Fragment, +theme: []const u8, + +pub const Global = struct { + name: []const u8, + type: type, +}; diff --git a/src/zilch/app/event.js b/src/zilch/app/event.js new file mode 100644 index 0000000..9183bb5 --- /dev/null +++ b/src/zilch/app/event.js @@ -0,0 +1,16 @@ +async function wasm_handle_event(target, name, event, pass_event) { + await wasm_ready; + + const component = target.getRootNode().host; + + const handler = WebAssembly.promising(wasm.exports[name]) + + if (pass_event) { + const id = ObjectStore.generateFreeId(); + ObjectStore.registerObject(id, event); + handler(component[ZsPtr], id); + ObjectStore.free(event); + } else { + handler(component[ZsPtr]); + } +} diff --git a/src/zilch/app/load.js b/src/zilch/app/load.js new file mode 100644 index 0000000..ed3ab85 --- /dev/null +++ b/src/zilch/app/load.js @@ -0,0 +1,37 @@ +const imports = { + object_store: { + process: new WebAssembly.Suspending(ObjectStore.processWasm), + }, + console: { + log(buffer, length) { + console.log(ObjectStore.decodeString(buffer, length)) + }, + warn(buffer, length) { + console.warn(ObjectStore.decodeString(buffer, length)) + }, + err(buffer, length) { + console.error(ObjectStore.decodeString(buffer, length)) + }, + debug(buffer, length) { + console.debug(ObjectStore.decodeString(buffer, length)) + }, + }, +}; + +const wasm_ready = WebAssembly.instantiateStreaming(fetch("index.wasm"), imports).then( + ({ instance, module }) => { + const view = new DataView(instance.exports.memory.buffer); + const type_names = [ 'Call', 'Value', 'Ptr' ]; + const size_of = {}; + + for (const type of type_names) { + size_of[type] = view.getUint16(instance.exports[`type::size::${type}`], true); + } + + wasm = { + exports: instance.exports, + memory: instance.exports.memory, + size_of: size_of, + } + }, +); diff --git a/src/zilch/app/object-store.js b/src/zilch/app/object-store.js new file mode 100644 index 0000000..8a4715d --- /dev/null +++ b/src/zilch/app/object-store.js @@ -0,0 +1,185 @@ +class ObjectStore { + static types = Object.freeze({ + 0: "object", + 1: "string", + 2: "int", + 3: "uint", + 4: "float", + 5: "undefined", + 6: "future", + + "object": 0, + "string": 1, + "int": 2, + "uint": 3, + "float": 4, + "undefined": 5, + "future": 6, + }); + + static store = { 0: null }; + static methods = {}; + + static generateFreeId() { + let id = 0; + + while (id in ObjectStore.store) { + id = Math.floor(Math.random() * (2**32 - 1)) + } + + return id; + } + + static decodeString(base, len) { + const slice = new Uint8Array(wasm.memory.buffer, base, len); + return new TextDecoder().decode(slice); + } + + static decodeCall(view, offset) { + const method = ObjectStore.methods[view.getUint32(offset, true)] + + if (!method) throw "unknown method, cannot decode"; + + return { + method: method, + num_args: view.getUint8(offset + 4, true), + } + } + + static decodeValue(view, offset, results) { + 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 ObjectStore.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); + } + + if (kind === 'future') { + return results[view.getUint32(offset + 8, true)]; + } + } + + static registerObject(id, obj) { + ObjectStore.store[id] = obj; + Object.defineProperty(obj, ZsId, { + enumerable: false, + writable: false, + configurable: true, + value: id, + }) + } + + static writeValue(ptr, value) { + if (ptr === 0) return; + + const mem = new DataView(wasm.memory.buffer, ptr); + + if (typeof value === 'object' || typeof value === 'function') { + mem.setUint8(0, ObjectStore.types['object'], true); + let id = value == null ? 0 : value[ZsId]; + + if (id === undefined) { + id = ObjectStore.generateFreeId(); + ObjectStore.registerObject(id, value); + } + + mem.setUint32(8, id, true); + + return; + } + + if (typeof value === 'number' && Number.isInteger(value) && value >= 0) { + mem.setUint8(0, ObjectStore.types['uint'], true); + mem.setUint32(8, value, true) + return; + } + + if (typeof value === 'number' && Number.isInteger(value)) { + mem.setUint8(0, ObjectStore.types['int'], true); + mem.setInt32(8, value, true) + return; + } + + if (typeof value === 'number') { + mem.setUint8(0, ObjectStore.types['float'], true); + mem.setFloat64(8, value, true) + return; + } + + if (typeof value === 'string') { + const string_ptr = wasm.exports.valueAllocBuffer(ptr, value.length); + const encoder = new TextEncoder(); + const string = encoder.encode(value); + const memory = new Uint8Array(wasm.memory.buffer); + memory.set(string, string_ptr); + return; + } + + if (typeof value === 'undefined') { + mem.setUint8(0, ObjectStore.types['undefined'], true); + return; + } + } + + static async 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); + const results = []; + + for (let i = 0; i < length; ++i) { + const call = ObjectStore.decodeCall(calls_view, offset.call); + offset.call += wasm.size_of.Call; + + let args = new Array(call.num_args).fill().map(_ => { + const value = ObjectStore.decodeValue(values_view, offset.value, results); + offset.value += wasm.size_of.Value; + return value; + }); + + let result = call.method.fn(...args); + + if (call.method.await) { + result = await result; + } + + const result_ptr = results_view.getUint32(offset.result, true); + offset.result += wasm.size_of.Ptr; + + results.push(result); + + ObjectStore.writeValue(result_ptr, result); + } + } +} diff --git a/src/zilch/app/root.document.zig b/src/zilch/app/root.document.zig new file mode 100644 index 0000000..6191746 --- /dev/null +++ b/src/zilch/app/root.document.zig @@ -0,0 +1,87 @@ +const std = @import("std"); + +const mod = @import("../root.zig"); +const Element = mod.html.Element; +const Document = mod.html.Document; + +const Options = @import("Options.zig"); + +pub fn App(comptime options: Options) type { + const components: []const Element, const registry: []const u8 = (comp: { + var cs: []const Element = &.{}; + var registry: []const u8 = "const component_registry = {"; + + for (options.components) |component| { + cs = cs ++ component.toElement(); + registry = registry ++ std.fmt.comptimePrint("{}: '{s}-{s}',", .{ + component.id, + component.namespace, + component.name, + }); + } + + registry = registry ++ "};"; + + break :comp .{ cs, registry }; + }); + + const functions: []const u8 = func: { + var buf: []const u8 = "ObjectStore.methods = {"; + + for (options.functions) |function| { + buf = buf ++ std.fmt.comptimePrint("{}: {{await: {}, fn: {s}}},", .{ function.id, function.await, function.content }); + } + + buf = buf ++ "}"; + + break :func buf; + }; + + return struct { + const node: Document = .{ + .root = .node("html", .{}, &.{ + .node("head", .{}, &.{ + .node("title", .{}, &.{.text(options.name)}), + .void("link", .{ .rel = "icon", .href = options.favicon }), + .void("meta", .{ + .name = "viewport", + .content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0", + }), + .void("meta", .{ .charset = "utf8" }), + .node("style", .{}, &.{.text(options.theme)}), + .node("script", .{}, &.{.text(@embedFile("symbols.js"))}), + .node("script", .{}, &.{.text(@embedFile("object-store.js"))}), + .node("script", .{}, &.{.text(functions)}), + .node("script", .{}, &.{.text(@embedFile("event.js"))}), + .node("script", .{}, &.{.text(@embedFile("load.js"))}), + .node("script", .{}, &.{.text(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; + })}), + }), + .node( + "body", + .{}, + &[_]Element{ + .node("script", .{}, &.{.text(registry)}), + } ++ components ++ options.body.elements, + ), + }), + }; + + html: []const u8 = str: { + @setEvalBranchQuota(100_000); + break :str std.fmt.comptimePrint("{f}", .{node}); + }, + + pub const init: @This() = .{}; + }; +} diff --git a/src/zilch/app/root.wasm.zig b/src/zilch/app/root.wasm.zig new file mode 100644 index 0000000..ea04192 --- /dev/null +++ b/src/zilch/app/root.wasm.zig @@ -0,0 +1,36 @@ +const std = @import("std"); + +const Options = @import("Options.zig"); + +pub fn App(comptime options: Options) type { + 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() = .{}; + + comptime { + for (options.components) |component| { + component.exportLinks(); + } + } + }; +} diff --git a/src/zilch/app/root.zig b/src/zilch/app/root.zig new file mode 100644 index 0000000..b2a8863 --- /dev/null +++ b/src/zilch/app/root.zig @@ -0,0 +1,15 @@ +const builtin = @import("builtin"); +const std = @import("std"); + +const wasm = @import("root.wasm.zig"); +const document = @import("root.document.zig"); + +pub const Options = @import("Options.zig"); + +pub fn App(comptime options: Options) type { + if (builtin.target.cpu.arch.isWasm()) { + return wasm.App(options); + } else { + return document.App(options); + } +} diff --git a/src/zilch/app/symbols.js b/src/zilch/app/symbols.js new file mode 100644 index 0000000..c0870c5 --- /dev/null +++ b/src/zilch/app/symbols.js @@ -0,0 +1,2 @@ +const ZsId = Symbol("zilch::id"); +const ZsPtr = Symbol("zilch::ptr"); diff --git a/src/zilch/bridge/root.zig b/src/zilch/bridge/root.zig new file mode 100644 index 0000000..166aadc --- /dev/null +++ b/src/zilch/bridge/root.zig @@ -0,0 +1,40 @@ +const std = @import("std"); +const builtin = @import("builtin"); + +const mod = @import("../root.zig"); +const Env = mod.Env; +const Function = Env.Function; + +const wasm = @import("wasm.root.zig"); +const server = @import("server.root.zig"); + +pub fn Bridge(T: type) type { + if (builtin.target.cpu.arch.isWasm()) { + return wasm.Bridge(T); + } else { + return server.Bridge(T); + } +} + +pub const Context = struct { + gpa: std.mem.Allocator, + arena: std.mem.Allocator, + io: std.Io, +}; + +pub const bindings = struct { + pub const call: Function = .from( + \\async function(ptr, len, result_ptr, len_check) { + \\ const response = await fetch("/api", { + \\ method: "POST", + \\ body: new DateView(wasm.memory.buffer, ptr, len), + \\ }) + \\ const bytes = await response.bytes(); + \\ if (bytes.length != len_check) { + \\ throw "response has incorrect size"; + \\ } + \\ const memory = new Uint8Array(wasm.memory.buffer); + \\ memory.set(bytes, result_ptr); + \\} + ); +}; diff --git a/src/zilch/bridge/server.root.zig b/src/zilch/bridge/server.root.zig new file mode 100644 index 0000000..504286c --- /dev/null +++ b/src/zilch/bridge/server.root.zig @@ -0,0 +1,10 @@ +const std = @import("std"); +const http = @import("http"); + +pub fn Bridge(T: type) type { + _ = T; + return struct { + pub fn handle() void { + } + }; +} diff --git a/src/web/component/image/index.css b/src/zilch/bridge/wasm.root.zig index e69de29..e69de29 100644 --- a/src/web/component/image/index.css +++ b/src/zilch/bridge/wasm.root.zig diff --git a/src/zilch/component.template.js b/src/zilch/component.template.js new file mode 100644 index 0000000..553fe11 --- /dev/null +++ b/src/zilch/component.template.js @@ -0,0 +1,19 @@ +customElements.define("{s}-{s}", class extends HTMLElement {{ + constructor() {{ + super(); + this.attachShadow({{ mode: 'open' }}); + const template = document.getElementById("@{s}"); + const node = document.importNode(template.content, true); + this.shadowRoot.appendChild(node); + this[ZsPtr] = null; + }} + connectedCallback() {{ + if (this[ZsPtr] === null) {{ + wasm_ready.then(async () => {{ + const id = ObjectStore.generateFreeId(); + ObjectStore.registerObject(id, this); + this[ZsPtr] = await WebAssembly.promising(wasm.exports['export::{s}::init'])(id); + }}); + }} + }} +}}); diff --git a/src/zilch/html/Attribute.zig b/src/zilch/html/Attribute.zig new file mode 100644 index 0000000..1db49a0 --- /dev/null +++ b/src/zilch/html/Attribute.zig @@ -0,0 +1,45 @@ +const std = @import("std"); + +const Self = @This(); + +name: []const u8, +value: []const u8, + +pub fn from(attributes: anytype) []const Self { + const T = @TypeOf(attributes); + const info = @typeInfo(T); + + if (info != .@"struct") { + @compileError("struct needed"); + } + + const fields = info.@"struct".fields; + + var attrs: []const Self = &.{}; + + for (fields) |field| { + const name = field.name; + const value = @field(attributes, name); + + const next_attr: []const Self = &.{.{ .name = name, .value = value }}; + attrs = attrs ++ next_attr; + } + + return attrs; +} + +pub fn format(self: *const Self, writer: *std.Io.Writer) !void { + try writer.writeAll(self.name); + try writer.writeAll("=\""); + + var value: []const u8 = self.value; + + while (std.mem.findScalar(u8, value, '"')) |index| { + try writer.writeAll(value[0..index]); + try writer.writeAll("""); + value = value[index + 1..]; + } + + try writer.writeAll(value); + try writer.writeByte('"'); +} diff --git a/src/zilch/html/Document.zig b/src/zilch/html/Document.zig new file mode 100644 index 0000000..b1122e1 --- /dev/null +++ b/src/zilch/html/Document.zig @@ -0,0 +1,11 @@ +const std = @import("std"); + +const Element = @import("root.zig").Element; + +const Self = @This(); + +root: Element, + +pub fn format(self: Self, writer: *std.Io.Writer) !void { + try writer.print("<!DOCTYPE html>{f}", .{self.root}); +} diff --git a/src/zilch/html/Fragment.zig b/src/zilch/html/Fragment.zig new file mode 100644 index 0000000..d05ad4a --- /dev/null +++ b/src/zilch/html/Fragment.zig @@ -0,0 +1,15 @@ +const std = @import("std"); +const mod = @import("root.zig"); +const Element = mod.Element; + +const Self = @This(); + +elements: []const Element, + +pub fn format(self: *const Self, writer: *std.Io.Writer) !void { + for (self.elements) |element| { + try element.format(writer); + } +} + +pub const parse = mod.parser.fragment; diff --git a/src/zilch/html/Tag.zig b/src/zilch/html/Tag.zig new file mode 100644 index 0000000..90b5641 --- /dev/null +++ b/src/zilch/html/Tag.zig @@ -0,0 +1,53 @@ +const std = @import("std"); +const ctutils = @import("ctutils"); + +const mod = @import("root.zig"); +const Attribute = mod.Attribute; +const Element = mod.Element; + +const Self = @This(); + +pub const Content = union(enum) { + children: []const Element, + void: void, +}; + +name: []const u8, +attributes: []const Attribute, +content: Content, + +pub fn tag(name: []const u8, attributes: anytype, children: []const Element) Self { + return .{ + .name = name, + .attributes = Attribute.from(attributes), + .content = .{ .children = children }, + }; +} + +pub fn @"void"(name: []const u8, attributes: anytype) Self { + return .{ + .name = name, + .attributes = Attribute.from(attributes), + .content = .void, + }; +} + +pub fn format(self: *const Self, writer: *std.Io.Writer) !void { + try writer.writeByte('<'); + try writer.writeAll(self.name); + + for (self.attributes) |attribute| { + try writer.writeByte(' '); + try attribute.format(writer); + } + + try writer.writeByte('>'); + + switch (self.content) { + .children => |children| { + for (children) |child| try child.format(writer); + try writer.print("</{s}>", .{self.name}); + }, + .void => {}, + } +} diff --git a/src/zilch/html/element.zig b/src/zilch/html/element.zig new file mode 100644 index 0000000..739eb0b --- /dev/null +++ b/src/zilch/html/element.zig @@ -0,0 +1,30 @@ +const std = @import("std"); +const mod = @import("root.zig"); +const Attribute = mod.Attribute; +const Tag = mod.Tag; + +pub const Element = union(enum) { + const Self = @This(); + + tag: Tag, + string: []const u8, + + pub fn node(name: []const u8, attributes: anytype, children: []const Element) Self { + return .{ .tag = .tag(name, attributes, children) }; + } + + pub fn @"void"(name: []const u8, attribute: anytype) Self { + return .{ .tag = .void(name, attribute) }; + } + + pub fn text(content: []const u8) Self { + return .{ .string = content }; + } + + pub fn format(self: *const Self, writer: *std.Io.Writer) !void { + try switch (self.*) { + .string => |content| writer.writeAll(content), + .tag => |n| n.format(writer), + }; + } +}; diff --git a/src/zilch/html/parser.zig b/src/zilch/html/parser.zig new file mode 100644 index 0000000..186d712 --- /dev/null +++ b/src/zilch/html/parser.zig @@ -0,0 +1,174 @@ +const std = @import("std"); +const mod = @import("root.zig"); +const Element = mod.Element; +const Attribute = mod.Attribute; +const Tag = mod.Tag; +const Fragment = mod.Fragment; + +const tag_name: []const u8 = std.ascii.letters ++ .{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' }; +const void_elements: std.StaticStringMap(void) = .initComptime(.{ + .{"area"}, + .{"base"}, + .{"br"}, + .{"col"}, + .{"embed"}, + .{"hr"}, + .{"img"}, + .{"input"}, + .{"link"}, + .{"meta"}, + .{"param"}, + .{"source"}, + .{"track"}, + .{"wbr"}, +}); + +pub fn fragment(buffer: []const u8) Fragment { + @setEvalBranchQuota(buffer.len * 1000); + var elements: []const Element = &.{}; + var buf = buffer; + + while (buf.len > 0) { + const e, buf = element(buf); + elements = elements ++ .{e}; + } + + return .{ .elements = elements }; +} + +pub fn element(buffer: []const u8) struct { Element, []const u8 } { + if (buffer.len == 0) @panic("EOB, expected element"); + + switch (buffer[0]) { + '<' => { + const t, const b = tag(buffer); + return .{ .{ .tag = t }, b }; + }, + else => { + const t, const b = text(buffer); + return .{ .{ .string = t }, b }; + }, + } +} + +pub fn tag(buffer: []const u8) struct { Tag, []const u8 } { + if (buffer.len == 0) @panic("EOB, expected tag"); + + if (buffer[0] != '<') @panic("expected '<'"); + + var buf: []const u8 = buffer[1..]; + + const name = name: { + const index = std.mem.findNone(u8, buf, tag_name) orelse @panic("uncosed tag"); + defer buf = buf[index..]; + break :name buf[0..index]; + }; + + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + + var attributes: []const Attribute = &.{}; + + while (buf.len > 0 and buf[0] != '>') { + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + const attr, buf = attribute(buf); + attributes = attributes ++ .{attr}; + } + + if (buf.len == 0 or buf[0] != '>') @panic("expected tag-close"); + + buf = buf[1..]; + + if (void_elements.has(name)) { + return .{.{ + .name = name, + .attributes = attributes, + .content = .void, + }, buf}; + } + + var children: []const Element = &.{}; + + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + + const closing = std.fmt.comptimePrint("</{s}>", .{name}); + + while (buf.len > 0 and !std.mem.startsWith(u8, buf, closing)) { + const child, buf = element(buf); + children = children ++ .{child}; + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + } + + if (!std.mem.startsWith(u8, buf, closing)) @panic("expected closing-tag"); + + buf = buf[closing.len..]; + + return .{ + .{ + .name = name, + .attributes = attributes, + .content = .{ .children = children }, + }, + buf, + }; +} + +pub fn text(buffer: []const u8) struct { []const u8, []const u8 } { + const index = std.mem.findScalar(u8, buffer, '<') orelse buffer.len; + return .{ + std.mem.trim(u8, buffer[0..index], &std.ascii.whitespace), + buffer[index..], + }; +} + +pub fn attribute(buffer: []const u8) struct { Attribute, []const u8 } { + var buf = buffer; + + const name = name: { + const index = std.mem.findAny( + u8, + buf, + ">=\"'" ++ std.ascii.whitespace, + ) orelse @panic("EOB, expected attr-value"); + defer buf = buf[index..]; + break :name buf[0..index]; + }; + + if (name.len == 0) @panic("expected attr-name"); + + buf = std.mem.trimStart(u8, buf, &std.ascii.whitespace); + + if (buf.len == 0 or buf[0] == '>') { + return .{ .{ .name = name, .value = "" }, buf }; + } + + if (buf[0] != '=') @panic("expected attr-eql"); + + buf = std.mem.trimStart(u8, buf[1..], &std.ascii.whitespace); + + const delim = switch (buf[0]) { + '"' => "\"", + '\'' => "'", + else => std.ascii.whitespace ++ "=\"'<>`", + }; + + if (delim.len == 1) { + buf = buf[1..]; + } + + const value = value: { + const index = std.mem.findAny(u8, buf, delim) orelse if (delim.len == 1) + @panic("unclosed attr-value") + else + buf.len; + defer buf = buf[index + @intFromBool(delim.len == 1) ..]; + break :value buf[0..index]; + }; + + return .{ + .{ + .name = name, + .value = value, + }, + buf, + }; +} diff --git a/src/zilch/html/root.zig b/src/zilch/html/root.zig new file mode 100644 index 0000000..7bf91e8 --- /dev/null +++ b/src/zilch/html/root.zig @@ -0,0 +1,6 @@ +pub const Attribute = @import("Attribute.zig"); +pub const Tag = @import("Tag.zig"); +pub const Element = @import("element.zig").Element; +pub const Document = @import("Document.zig"); +pub const Fragment = @import("Fragment.zig"); +pub const parser = @import("parser.zig"); diff --git a/src/zilch/log/js.zig b/src/zilch/log/js.zig new file mode 100644 index 0000000..16f562c --- /dev/null +++ b/src/zilch/log/js.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/zilch/log/root.zig b/src/zilch/log/root.zig new file mode 100644 index 0000000..ac67298 --- /dev/null +++ b/src/zilch/log/root.zig @@ -0,0 +1,55 @@ +const std = @import("std"); + +pub const js = @import("js.zig"); + +pub fn Writer(func: fn ([]const u8) void, buffer: []u8) std.Io.Writer { + return .{ + .buffer = buffer, + .vtable = &.{ + .drain = &struct { + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + func(w.buffer[0..w.end]); + w.end = 0; + + var size: usize = 0; + + for (data[0..data.len - 1]) |s| { + func(s); + size += s.len; + } + + size += data[data.len - 1].len * splat; + for (0..splat) |_| { + func(data[data.len - 1]); + } + + return size; + } + }.drain, + } + }; +} + +pub fn default( + comptime level: std.log.Level, + comptime scope: @EnumLiteral(), + comptime format: []const u8, + args: anytype, +) void { + const func = switch (level) { + .err => js.err, + .warn => js.warn, + .info => js.log, + .debug => js.debug, + }; + var buffer: [1024]u8 = undefined; + var writer = Writer(func, &buffer); + + if (scope != .default) { + writer.print("[{s}]: ", .{@tagName(scope)}) catch unreachable; + } + writer.print(format, args) catch unreachable; + + writer.flush() catch unreachable; +} + diff --git a/src/zilch/panic.zig b/src/zilch/panic.zig new file mode 100644 index 0000000..7163c6d --- /dev/null +++ b/src/zilch/panic.zig @@ -0,0 +1,9 @@ +const log = @import("log/root.zig"); +const std = @import("std"); + +fn defaultPanic(msg: []const u8, _: ?usize) noreturn { + log.js.err(msg); + @trap(); +} + +pub const panic = std.debug.FullPanic(defaultPanic); diff --git a/src/zilch/root.zig b/src/zilch/root.zig new file mode 100644 index 0000000..bf0f1ad --- /dev/null +++ b/src/zilch/root.zig @@ -0,0 +1,34 @@ +const builtin = @import("builtin"); +const std = @import("std"); + +pub const Env = @import("Env/root.zig"); +pub const Call = Env.Call; +pub const AnyFuture = Env.AnyFuture; +pub const Future = Env.Future; +pub const Value = Env.Value; + +pub const log = @import("log/root.zig"); +pub const html = @import("html/root.zig"); + +pub const bridge = @import("bridge/root.zig"); + +pub const Object = @import("Object.zig"); +pub const Promise = @import("Promise.zig"); +pub const Callable = @import("Callable.zig"); + +pub const App = @import("app/root.zig").App; +pub const Options = @import("app/root.zig").Options; +pub const Component = @import("Component.zig"); + +pub const panic = @import("panic.zig").panic; + +const Ptr = struct { o: *anyopaque }; +comptime { + const export_sizes = .{ Call, Value, Ptr }; + + for (export_sizes) |T| { + const size: u16 = @sizeOf(T); + const name = @typeName(T)[if (std.mem.findScalarLast(u8, @typeName(T), '.')) |i| i + 1 else 0..]; + @export(&size, .{ .name = std.fmt.comptimePrint("type::size::{s}", .{name}) }); + } +} |