From 4e86e3e18e9b43e442a35361ac82b30dd6c0103a Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Wed, 7 Oct 2026 00:09:34 +0200 Subject: wasm implement components --- src/z/Component.zig | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/z/Component.zig (limited to 'src/z/Component.zig') diff --git a/src/z/Component.zig b/src/z/Component.zig new file mode 100644 index 0000000..2bc293e --- /dev/null +++ b/src/z/Component.zig @@ -0,0 +1,96 @@ +const std = @import("std"); +const Element = @import("html.zig").Element; + +const Self = @This(); + +name: []const u8, +html: Element, +css: []const u8, +link: type, + +fn exportFromHtml(self: *const Self, element: Element) void { + comptime { + for (element.attributes) |attr| { + if (attr.value.len > 0 and attr.value[0] == '@') { + const func = struct { + pub fn func() callconv(.c) void { + @field(self.link, attr.value[1..])(); + } + }.func; + + @export( + &func, + .{ + .name = std.fmt.comptimePrint( + "export::{s}::{s}", + .{ self.name, attr.value[1..] }, + ), + }, + ); + } + } + } +} + +pub fn exportLinks(self: *const Self) void { + comptime self.exportFromHtml(self.html); +} + +fn linkHtmlRecursive(self: *const Self, element: Element) Element { + comptime { + return .{ + .tag = element.tag, + .attributes = attrs: { + var attributes: []const Element.Attribute = &.{}; + + for (element.attributes) |*attr| { + if (attr.value.len > 0 and attr.value[0] == '@') { + const attribute: []const Element.Attribute = &.{.{ + .name = attr.name, + .value = std.fmt.comptimePrint( + "wasm.exports[\"export::{s}::{s}\"]()", + .{ self.name, attr.value[1..] }, + ), + }}; + attributes = attributes ++ attribute; + } + } + break :attrs attributes; + }, + .content = element.content, + }; + } +} + +pub fn toElement(self: *const Self) Element { + return .transparent( + .children( + &.{ + .native( + .template, + .{ .id = "@" ++ self.name }, + .children(&.{self.linkHtmlRecursive(self.html)}), + ), + .native( + .script, + .{}, + .content( + std.fmt.comptimePrint( + \\customElements.define("app-{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); + \\ }} + \\}}) + , + .{self.name, self.name} + ), + ), + ), + }, + ), + ); +} -- cgit v1.2.3-70-g09d2