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
26 changes: 26 additions & 0 deletions REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,32 @@ ZigZag uses the Elm Architecture (Model-Update-View):
4. **update** - Handle messages and update state
5. **view** - Render your model to a string

### Fallible callbacks

`init`, `update` and `view` may each return an error union. Rendering allocates
on nearly every line, and without this each allocation needs its own fallback:

```zig
// Plain signature — every allocation needs a `catch`, and a failed one is
// silently rendered as text.
pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 {
const title = title_style.render(ctx.allocator, "Report") catch "Report";
const body = std.fmt.allocPrint(ctx.allocator, "{d} rows", .{self.rows}) catch "?";
return std.fmt.allocPrint(ctx.allocator, "{s}\n{s}", .{ title, body }) catch "Error";
}

// Error union — the runtime propagates the failure out of `tick()`.
pub fn view(self: *const Model, ctx: *const zz.Context) ![]const u8 {
const title = try title_style.render(ctx.allocator, "Report");
const body = try std.fmt.allocPrint(ctx.allocator, "{d} rows", .{self.rows});
return std.fmt.allocPrint(ctx.allocator, "{s}\n{s}", .{ title, body });
}
```

Both forms are supported; the runtime picks the right one at compile time, per
function. `SubProgram` mirrors its child, so a fallible child model gives a
`SubProgram` whose `view` is fallible too.

### Commands

Commands let you perform side effects:
Expand Down
30 changes: 16 additions & 14 deletions examples/counter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ const Model = struct {
return .none;
}

pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 {
// Returning an error union lets every allocation below use `try`, instead
// of each one needing its own `catch "..."` fallback.
pub fn view(self: *const Model, ctx: *const zz.Context) ![]const u8 {
// Title style
var title_style = zz.Style{};
title_style = title_style.bold(true);
Expand All @@ -62,40 +64,40 @@ const Model = struct {
box_style = box_style.paddingAll(1);
box_style = box_style.alignH(.center);

const title = title_style.render(ctx.allocator, "Counter Demo") catch "Counter Demo";
const counter = std.fmt.allocPrint(ctx.allocator, "{d}", .{self.count}) catch "?";
const styled_counter = counter_style.render(ctx.allocator, counter) catch counter;
const title = try title_style.render(ctx.allocator, "Counter Demo");
const counter = try std.fmt.allocPrint(ctx.allocator, "{d}", .{self.count});
const styled_counter = try counter_style.render(ctx.allocator, counter);

const content = std.fmt.allocPrint(
const content = try std.fmt.allocPrint(
ctx.allocator,
"{s}\n\nCount: {s}",
.{ title, styled_counter },
) catch "Error";
);

const boxed = box_style.render(ctx.allocator, content) catch content;
const boxed = try box_style.render(ctx.allocator, content);

var help_style = zz.Style{};
help_style = help_style.fg(zz.Color.gray(12));
help_style = help_style.inline_style(true);
const help = help_style.render(
const help = try help_style.render(
ctx.allocator,
"Up/+ Increment Down/- Decrement r Reset q Quit",
) catch "";
);

// Get max width for centering
const box_width = zz.measure.maxLineWidth(boxed);
const help_width = zz.measure.width(help);
const max_width = @max(box_width, help_width);

// Center elements
const centered_box = zz.place.place(ctx.allocator, max_width, zz.measure.height(boxed), .center, .top, boxed) catch boxed;
const centered_help = zz.place.place(ctx.allocator, max_width, 1, .center, .top, help) catch help;
const centered_box = try zz.place.place(ctx.allocator, max_width, zz.measure.height(boxed), .center, .top, boxed);
const centered_help = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, help);

const final_content = std.fmt.allocPrint(
const final_content = try std.fmt.allocPrint(
ctx.allocator,
"{s}\n\n{s}",
.{ centered_box, centered_help },
) catch "Error";
);

// Center in terminal
return zz.place.place(
Expand All @@ -105,7 +107,7 @@ const Model = struct {
.center,
.middle,
final_content,
) catch final_content;
);
}
};

Expand Down
67 changes: 35 additions & 32 deletions examples/hello_world.zig
Original file line number Diff line number Diff line change
Expand Up @@ -199,16 +199,19 @@ const Model = struct {
};
}

fn capsString(self: *const Model, allocator: std.mem.Allocator) []const u8 {
fn capsString(self: *const Model, allocator: std.mem.Allocator) ![]const u8 {
return std.fmt.allocPrint(allocator, "kitty={s} iterm2={s} sixel={s}", .{
if (self.caps.kitty_graphics) "yes" else "no",
if (self.caps.iterm2_inline_image) "yes" else "no",
if (self.caps.sixel) "yes" else "no",
}) catch "?";
});
}

/// Render the view
pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 {
/// Render the view.
///
/// The error union means every allocation here can just be `try`ed; a view
/// returning plain `[]const u8` has to end each one in `catch "..."`.
pub fn view(self: *const Model, ctx: *const zz.Context) ![]const u8 {
var title_style = zz.Style{};
title_style = title_style.bold(true);
title_style = title_style.fg(zz.Color.cyan);
Expand All @@ -227,33 +230,33 @@ const Model = struct {
image_hint_style = image_hint_style.fg(zz.Color.gray(16));
image_hint_style = image_hint_style.inline_style(true);

const title = title_style.render(ctx.allocator, "Hello, ZigZag!") catch "Hello, ZigZag!";
const subtitle = subtitle_style.render(ctx.allocator, "A TUI library for Zig") catch "";
const hint = hint_style.render(ctx.allocator, "Press 'q' to quit") catch "";
const title = try title_style.render(ctx.allocator, "Hello, ZigZag!");
const subtitle = try subtitle_style.render(ctx.allocator, "A TUI library for Zig");
const hint = try hint_style.render(ctx.allocator, "Press 'q' to quit");

const image_hint_text = if (self.image_supported)
"'i' draw 'c' cache 'z' z-index 'd' delete 'p' protocol"
else
"Inline image protocol not detected in this terminal";
const image_hint = image_hint_style.render(ctx.allocator, image_hint_text) catch image_hint_text;
const image_hint = try image_hint_style.render(ctx.allocator, image_hint_text);

const caps_text = self.capsString(ctx.allocator);
const caps_line = image_hint_style.render(ctx.allocator, caps_text) catch caps_text;
const caps_text = try self.capsString(ctx.allocator);
const caps_line = try image_hint_style.render(ctx.allocator, caps_text);

const protocol_text = std.fmt.allocPrint(ctx.allocator, "protocol: {s} z-index: {s} cached: {s}", .{
const protocol_text = try std.fmt.allocPrint(ctx.allocator, "protocol: {s} z-index: {s} cached: {s}", .{
self.protocolName(),
if (self.image_behind_text) "behind" else "normal",
if (self.image_cached) "yes" else "no",
}) catch "";
const protocol_line = image_hint_style.render(ctx.allocator, protocol_text) catch protocol_text;
});
const protocol_line = try image_hint_style.render(ctx.allocator, protocol_text);

const status_text = if (self.image_attempted and self.image_supported)
"Image command sent (check assets/cat.png path)"
else if (self.image_attempted and !self.image_supported)
"Image skipped: unsupported terminal protocol"
else
"";
const status = hint_style.render(ctx.allocator, status_text) catch status_text;
const status = try hint_style.render(ctx.allocator, status_text);

// Get max width for centering
const max_width = @max(
Expand All @@ -268,48 +271,48 @@ const Model = struct {
);

// Center each element
const centered_title = zz.place.place(ctx.allocator, max_width, 1, .center, .top, title) catch title;
const centered_subtitle = zz.place.place(ctx.allocator, max_width, 1, .center, .top, subtitle) catch subtitle;
const centered_hint = zz.place.place(ctx.allocator, max_width, 1, .center, .top, hint) catch hint;
const centered_image_hint = zz.place.place(ctx.allocator, max_width, 1, .center, .top, image_hint) catch image_hint;
const centered_caps = zz.place.place(ctx.allocator, max_width, 1, .center, .top, caps_line) catch caps_line;
const centered_protocol = zz.place.place(ctx.allocator, max_width, 1, .center, .top, protocol_line) catch protocol_line;
const centered_status = zz.place.place(ctx.allocator, max_width, 1, .center, .top, status) catch status;

const content = std.fmt.allocPrint(
const centered_title = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, title);
const centered_subtitle = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, subtitle);
const centered_hint = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, hint);
const centered_image_hint = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, image_hint);
const centered_caps = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, caps_line);
const centered_protocol = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, protocol_line);
const centered_status = try zz.place.place(ctx.allocator, max_width, 1, .center, .top, status);

const content = try std.fmt.allocPrint(
ctx.allocator,
"{s}\n\n{s}\n\n{s}\n{s}\n{s}\n{s}\n{s}",
.{ centered_title, centered_subtitle, centered_hint, centered_image_hint, centered_caps, centered_protocol, centered_status },
) catch "Error rendering view";
);

if (self.image_supported and self.image_visible) {
const image_size = if (self.image_size_cells > 0) self.image_size_cells else self.pickImageSize(ctx);
const slot_height = @as(usize, image_size) + image_gap_lines;
const container_width = @max(max_width, @as(usize, image_size));
const text_height = zz.measure.height(content);

const centered_text = zz.place.place(
const centered_text = try zz.place.place(
ctx.allocator,
container_width,
text_height,
.center,
.top,
content,
) catch content;
);

const image_slot = zz.place.place(
const image_slot = try zz.place.place(
ctx.allocator,
container_width,
slot_height,
.left,
.top,
"",
) catch "";
);

const container = zz.joinVertical(
const container = try zz.joinVertical(
ctx.allocator,
&.{ centered_text, image_slot },
) catch centered_text;
);

return zz.place.place(
ctx.allocator,
Expand All @@ -318,7 +321,7 @@ const Model = struct {
.center,
.middle,
container,
) catch container;
);
}

return zz.place.place(
Expand All @@ -328,7 +331,7 @@ const Model = struct {
.center,
.middle,
content,
) catch content;
);
}
};

Expand Down
84 changes: 84 additions & 0 deletions src/core/model.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! The Model contract, and the comptime helpers that let it be flexible.
//!
//! A model supplies three functions:
//!
//! pub fn init(self: *Model, ctx: *Context) Cmd(Msg)
//! pub fn update(self: *Model, msg: Msg, ctx: *Context) Cmd(Msg)
//! pub fn view(self: *const Model, ctx: *const Context) []const u8
//!
//! Each of them may return an error union instead (`!Cmd(Msg)`, `![]const u8`).
//! Views allocate on nearly every line, so without that every one of them ends
//! up littered with `catch "Error"`, which turns an allocation failure into a
//! rendering artefact.

const std = @import("std");

/// Whether a function returns an error union. Accepts a function type or a
/// pointer to one.
pub fn returnsError(comptime Func: type) bool {
const return_type = returnType(Func) orelse return false;
return @typeInfo(return_type) == .error_union;
}

/// The result type a wrapper should use to mirror `Func`'s fallibility:
/// `Payload` when `Func` cannot fail, `E!Payload` when it can.
pub fn Result(comptime Func: type, comptime Payload: type) type {
const return_type = returnType(Func) orelse return Payload;
return switch (@typeInfo(return_type)) {
.error_union => |eu| eu.error_set!Payload,
else => Payload,
};
}

fn returnType(comptime Func: type) ?type {
return switch (@typeInfo(Func)) {
.@"fn" => |f| f.return_type,
.pointer => |p| @typeInfo(p.child).@"fn".return_type,
else => null,
};
}

/// Fail at compile time with a readable message when a type is missing part of
/// the Model contract.
pub fn validate(comptime Model: type, comptime role: []const u8) void {
comptime {
for ([_][]const u8{ "Msg", "init", "update", "view" }) |name| {
if (!@hasDecl(Model, name)) {
@compileError(role ++ " '" ++ @typeName(Model) ++ "' is missing '" ++
name ++ "'. A model needs a 'Msg' type plus 'init', 'update' and 'view'.");
}
}
}
}

test "returnsError distinguishes fallible signatures" {
const S = struct {
fn plain() u8 {
return 0;
}
fn fallible() !u8 {
return 0;
}
};

try std.testing.expect(!returnsError(@TypeOf(S.plain)));
try std.testing.expect(returnsError(@TypeOf(S.fallible)));
try std.testing.expect(returnsError(@TypeOf(&S.fallible)));
}

test "Result mirrors fallibility" {
const S = struct {
fn plain() u8 {
return 0;
}
fn fallible() error{Boom}!u8 {
return 0;
}
};

try std.testing.expectEqual([]const u8, Result(@TypeOf(S.plain), []const u8));
try std.testing.expectEqual(
error{Boom}![]const u8,
Result(@TypeOf(S.fallible), []const u8),
);
}
Loading
Loading