aboutsummaryrefslogtreecommitdiff
path: root/src/z/Component.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/z/Component.zig')
-rw-r--r--src/z/Component.zig48
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;