aboutsummaryrefslogtreecommitdiff
path: root/src/z/Component.zig
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2026-10-07 00:09:34 +0200
committerNathan Reiner <nathan@nathanreiner.xyz>2026-10-07 00:09:34 +0200
commit4e86e3e18e9b43e442a35361ac82b30dd6c0103a (patch)
treec37d84000608386147b910dd41df5743e947fd93 /src/z/Component.zig
parent12a02f161504b49a54243bed996df6b44e25b7b4 (diff)
wasm implement components
Diffstat (limited to 'src/z/Component.zig')
-rw-r--r--src/z/Component.zig96
1 files changed, 96 insertions, 0 deletions
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}
+ ),
+ ),
+ ),
+ },
+ ),
+ );
+}