diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-08 19:26:47 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-08 19:26:47 +0200 |
| commit | 3d0d5d88458112e5cc276f650e02609dc85c5b87 (patch) | |
| tree | 7b0a48f7f7ef0af82360aa356b88a83b7dcfd699 /src/z/Component.zig | |
| parent | 0260f392c19db7911496172c7d43d1178c6215cb (diff) | |
juicy event handler
Diffstat (limited to 'src/z/Component.zig')
| -rw-r--r-- | src/z/Component.zig | 48 |
1 files changed, 41 insertions, 7 deletions
diff --git a/src/z/Component.zig b/src/z/Component.zig index deab261..122975f 100644 --- a/src/z/Component.zig +++ b/src/z/Component.zig @@ -11,16 +11,49 @@ html: Fragment, css: []const u8, link: type, +fn handlerNeedsEvent(func: anytype) bool { + const T = @TypeOf(func); + return @typeInfo(T).@"fn".params.len == 2; +} + +fn handlerNeedsErrorHandling(func: anytype) bool { + const T = @TypeOf(func); + const ret_info = @typeInfo(@typeInfo(T).@"fn".return_type orelse void); + return ret_info == .error_union; +} + 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 func = struct { - pub fn func(obj: *self.link) callconv(.c) void { - @field(self.link, attr.value[1..])(obj); - } - }.func; + 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 { + if (comptime handlerNeedsErrorHandling(event_handler)) { + event_handler(obj, event) catch |err| { + std.log.err("error: {}", .{err}); + }; + } else { + event_handler(obj, event); + } + } + }.func + else + struct { + pub fn func(obj: *self.link) callconv(.c) void { + if (comptime handlerNeedsErrorHandling(event_handler)) { + event_handler(obj) catch |err| { + std.log.err("error: {}", .{err}); + }; + } else { + event_handler(obj); + } + } + }.func; @export( &func, @@ -74,11 +107,12 @@ fn linkAttributes(self: *const Self, attributes: []const Attribute) []const Attr for (attributes) |*attr| { if (attr.value.len > 0 and attr.value[0] == '@') { + const event_handler = @field(self.link, attr.value[1..]); const attribute: []const Attribute = &.{.{ .name = attr.name, .value = std.fmt.comptimePrint( - "wasm.exports[\"export::{s}::{s}\"](this[\"@ptr\"])", - .{ self.name, attr.value[1..] }, + "wasm_handle_event(\"export::{s}::{s}\", event, {})", + .{ self.name, attr.value[1..], handlerNeedsEvent(event_handler) }, ), }}; linked = linked ++ attribute; |