Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub fn build(b: *std.Build) void {
"mouse",
"accessibility",
"wasm_app",
"sub_program",
"layers",
"virtual_list",
"calendar",
Expand Down
142 changes: 142 additions & 0 deletions examples/sub_program.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//! ZigZag Sub-Program Example
//! Demonstrates embedding independent sub-programs inside a parent.

const std = @import("std");
const zz = @import("zigzag");

// Child model: a simple counter
const Counter = struct {
count: i32 = 0,
label: []const u8 = "Counter",

pub const Msg = union(enum) {
key: zz.KeyEvent,
};

pub fn init(self: *Counter, _: *zz.Context) zz.Cmd(Msg) {
self.count = 0;
return .none;
}

pub fn update(self: *Counter, msg: Msg, _: *zz.Context) zz.Cmd(Msg) {
switch (msg) {
.key => |k| switch (k.key) {
.up => self.count += 1,
.down => self.count -= 1,
.char => |c| if (c == 'r') {
self.count = 0;
},
else => {},
},
}
return .none;
}

pub fn view(self: *const Counter, ctx: *const zz.Context) []const u8 {
const alloc = ctx.allocator;
return std.fmt.allocPrint(alloc, "{s}: {d}", .{ self.label, self.count }) catch "?";
}
};

// Parent model with two sub-programs
const Model = struct {
counter_a: zz.SubProgram(Counter, Msg),
counter_b: zz.SubProgram(Counter, Msg),
active: u8,

pub const Msg = union(enum) {
key: zz.KeyEvent,
};

pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) {
self.active = 0;
self.counter_a = .{};
self.counter_a.model.label = "Counter A";
_ = self.counter_a.init(ctx);
self.counter_b = .{};
self.counter_b.model.label = "Counter B";
_ = self.counter_b.init(ctx);
return .none;
}

pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) {
switch (msg) {
.key => |k| {
switch (k.key) {
.char => |c| switch (c) {
'q' => return .quit,
else => {},
},
.escape => return .quit,
.tab => {
self.active = (self.active + 1) % 2;
return .none;
},
else => {},
}

// Forward to active sub-program
if (self.active == 0) {
return self.counter_a.update(.{ .key = k }, ctx);
} else {
return self.counter_b.update(.{ .key = k }, ctx);
}
},
}
}

pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 {
const alloc = ctx.allocator;

var title_s = zz.Style{};
title_s = title_s.bold(true);
title_s = title_s.fg(zz.Color.cyan());
title_s = title_s.inline_style(true);

// Sub-program views
var box_a = zz.Style{};
box_a = box_a.borderAll(zz.Border.rounded);
box_a = box_a.borderForeground(if (self.active == 0) zz.Color.green() else zz.Color.gray(8));
box_a = box_a.paddingAll(1);
box_a = box_a.width(30);

var box_b = zz.Style{};
box_b = box_b.borderAll(zz.Border.rounded);
box_b = box_b.borderForeground(if (self.active == 1) zz.Color.green() else zz.Color.gray(8));
box_b = box_b.paddingAll(1);
box_b = box_b.width(30);

const view_a = box_a.render(alloc, self.counter_a.view(ctx)) catch "";
const view_b = box_b.render(alloc, self.counter_b.view(ctx)) catch "";

const panels = zz.join.horizontal(alloc, .top, &.{ view_a, view_b }) catch "";

var help_s = zz.Style{};
help_s = help_s.fg(zz.Color.gray(10));
help_s = help_s.inline_style(true);

const active_label = if (self.active == 0) "A" else "B";

const content = std.fmt.allocPrint(alloc,
"{s}\n\nActive: {s}\n\n{s}\n\n{s}",
.{
title_s.render(alloc, "Sub-Program Demo") catch "Sub-Program",
active_label,
panels,
help_s.render(alloc, "Tab: switch Up/Down: count r: reset q: quit") catch "",
},
) catch "Error";

return zz.place.place(alloc, ctx.width, ctx.height, .center, .middle, content) catch content;
}
};

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();

var program = try zz.Program(Model).init(gpa.allocator());
defer program.deinit();

try program.run();
}
87 changes: 87 additions & 0 deletions src/core/sub_program.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Sub-program support for embedding child models inside a parent.
//! Allows composing independent Model-Update-View units with message routing.

const std = @import("std");
const Context = @import("context.zig").Context;
const command = @import("command.zig");

/// A wrapper that embeds a child Model inside a parent, with message mapping.
///
/// - `ChildModel` must have `Msg`, `init`, `update`, `view` like a top-level model.
/// - `ParentMsg` is the parent's message type.
/// - The child's `.quit` command is converted to an optional parent message via `quit_msg`.
pub fn SubProgram(comptime ChildModel: type, comptime ParentMsg: type) type {
comptime {
if (!@hasDecl(ChildModel, "Msg")) @compileError("ChildModel must have a 'Msg' type");
if (!@hasDecl(ChildModel, "init")) @compileError("ChildModel must have an 'init' function");
if (!@hasDecl(ChildModel, "update")) @compileError("ChildModel must have an 'update' function");
if (!@hasDecl(ChildModel, "view")) @compileError("ChildModel must have a 'view' function");
}

const ChildMsg = ChildModel.Msg;
const ChildCmd = command.Cmd(ChildMsg);
const ParentCmd = command.Cmd(ParentMsg);

return struct {
model: ChildModel = undefined,
initialized: bool = false,
/// Optional message to send to parent when child issues .quit.
quit_msg: ?ParentMsg = null,

const Self = @This();

/// Initialize the child model.
pub fn init(self: *Self, ctx: *Context) ParentCmd {
const child_cmd = self.model.init(ctx);
self.initialized = true;
return self.translateCmd(child_cmd);
}

/// Forward a child message to the child's update, returning a parent command.
pub fn update(self: *Self, child_msg: ChildMsg, ctx: *Context) ParentCmd {
if (!self.initialized) return .none;
const child_cmd = self.model.update(child_msg, ctx);
return self.translateCmd(child_cmd);
}

/// Render the child model.
pub fn view(self: *const Self, ctx: *const Context) []const u8 {
if (!self.initialized) return "";
return self.model.view(ctx);
}

/// Translate a child command into a parent command.
fn translateCmd(self: *const Self, cmd: ChildCmd) ParentCmd {
return switch (cmd) {
.none => .none,
.quit => if (self.quit_msg) |m| .{ .msg = m } else .none,
.tick => |ns| .{ .tick = ns },
.every => |ns| .{ .every = ns },
.msg => |child_msg| blk: {
// Child-internal messages: re-dispatch is not possible at parent level,
// so we drop them. The parent should call sub.update() with child messages.
_ = child_msg;
break :blk .none;
},
.perform => .none, // Can't translate perform functions across types
.suspend_process => .suspend_process,
.enable_mouse => .enable_mouse,
.disable_mouse => .disable_mouse,
.show_cursor => .show_cursor,
.hide_cursor => .hide_cursor,
.enter_alt_screen => .enter_alt_screen,
.exit_alt_screen => .exit_alt_screen,
.set_title => |t| .{ .set_title = t },
.println => |l| .{ .println = l },
.batch => .none, // Complex: would need recursive translation
.sequence => .none,
.image_file => |img| .{ .image_file = img },
.kitty_image_file => |img| .{ .kitty_image_file = img },
.image_data => |img| .{ .image_data = img },
.cache_image => |c| .{ .cache_image = c },
.place_cached_image => |p| .{ .place_cached_image = p },
.delete_image => |d| .{ .delete_image = d },
};
}
};
}
1 change: 1 addition & 0 deletions src/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub const program = @import("core/program.zig");
pub const Program = program.Program;
pub const Cmd = program.Cmd;
pub const command = @import("core/command.zig");
pub const SubProgram = @import("core/sub_program.zig").SubProgram;
pub const Context = @import("core/context.zig").Context;
pub const Options = @import("core/context.zig").Options;
pub const msg = @import("core/message.zig");
Expand Down
Loading