diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-26 09:23:55 +0100 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-26 09:23:55 +0100 |
| commit | 91d9b6992ac0ebee13704a3faefa8fd41a00075e (patch) | |
| tree | ea0a30cc0cfb2232d3e60c845c20a67b6cdf0b99 /src/zilch/Component.zig | |
| parent | 65300a13dcd11037218bf8ba61efd8ca19e5920e (diff) | |
zilch: dynamic element creation
Diffstat (limited to 'src/zilch/Component.zig')
| -rw-r--r-- | src/zilch/Component.zig | 71 |
1 files changed, 50 insertions, 21 deletions
diff --git a/src/zilch/Component.zig b/src/zilch/Component.zig index 35fafbe..592b464 100644 --- a/src/zilch/Component.zig +++ b/src/zilch/Component.zig @@ -3,14 +3,37 @@ 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(); -namespace: []const u8 = "app", +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); @@ -93,25 +116,6 @@ pub fn exportLinks(self: *const Self) void { }, ); - const deinit = struct { - pub fn deinit(obj: *self.link) callconv(.c) void { - if (@hasDecl(self.link, "deinit")) { - wrapHandler(obj.deinit()); - } - std.heap.wasm_allocator.destroy(obj); - } - }.deinit; - - @export( - &deinit, - .{ - .name = std.fmt.comptimePrint( - "export::{s}::deinit", - .{self.name}, - ), - }, - ); - for (self.html.elements) |element| { comptime self.exportFromHtml(element); } @@ -188,9 +192,34 @@ pub fn toElement(self: *const Self) []const Element { &.{.text( std.fmt.comptimePrint( @embedFile("component.template.js"), - .{ self.namespace, self.name, self.name, self.name, self.name }, + .{ + 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, +}; |