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
2 changes: 2 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub fn build(b: *std.Build) void {
"menu_bar",
"checkbox_radio",
"dropdown",
"form",
"markdown",
"animation",
};
Expand Down Expand Up @@ -80,6 +81,7 @@ pub fn build(b: *std.Build) void {
"tests/menu_bar_tests.zig",
"tests/checkbox_radio_tests.zig",
"tests/dropdown_tests.zig",
"tests/form_tests.zig",
"tests/markdown_tests.zig",
"tests/animation_tests.zig",
};
Expand Down
89 changes: 89 additions & 0 deletions examples/form.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//! ZigZag Form Example
//! Demonstrates a form composing TextInput, Checkbox, and Confirm fields.

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

const Model = struct {
name_input: zz.TextInput,
email_input: zz.TextInput,
agree_checkbox: zz.Checkbox,
form: zz.Form(3),
status: []const u8,

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

pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) {
self.name_input = zz.TextInput.init(ctx.persistent_allocator);
self.name_input.placeholder = "Enter your name...";

self.email_input = zz.TextInput.init(ctx.persistent_allocator);
self.email_input.placeholder = "user@example.com";

self.agree_checkbox = zz.Checkbox.init("I agree to the terms and conditions");

self.form = zz.Form(3).init();
self.form.title = "Registration Form";
self.form.addField("Name", &self.name_input, .{ .required = true });
self.form.addField("Email", &self.email_input, .{ .required = true });
self.form.addField("Terms", &self.agree_checkbox, .{});
self.form.initFocus();

self.status = "Fill out the form and press Ctrl+Enter to submit";

return .none;
}

pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) {
switch (msg) {
.key => |k| {
if (k.key == .char) {
if (k.key.char == 'q' and k.modifiers.ctrl) return .quit;
}

_ = self.form.handleKey(k);

if (self.form.isSubmitted()) {
self.status = "Form submitted successfully!";
self.form.reset();
} else if (self.form.isCancelled()) {
return .quit;
}
},
}
return .none;
}

pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 {
const form_view = self.form.view(ctx.allocator) catch "error";

var status_style = zz.Style{};
status_style = status_style.fg(zz.Color.green());
status_style = status_style.bold(true);
status_style = status_style.inline_style(true);
const styled_status = status_style.render(ctx.allocator, self.status) catch self.status;

return std.fmt.allocPrint(
ctx.allocator,
"{s}\n\n{s}",
.{ form_view, styled_status },
) catch "Error";
}

pub fn deinit(self: *Model) void {
self.name_input.deinit();
self.email_input.deinit();
}
};

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();
}
267 changes: 267 additions & 0 deletions src/components/form.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
//! Form component.
//! Composes multiple input fields with focus management, labels, and validation.

const std = @import("std");
const keys = @import("../input/keys.zig");
const style_mod = @import("../style/style.zig");
const Color = @import("../style/color.zig").Color;
const border_mod = @import("../style/border.zig");
const focus_mod = @import("focus.zig");

pub fn Form(comptime max_fields: usize) type {
return struct {
// Fields
fields: [max_fields]?Field,
field_count: usize,

// Focus
focus_group: focus_mod.FocusGroup(max_fields),

// State
submitted: bool,
cancelled: bool,

// Layout
label_width: u16,
spacing: u16,
show_required_marker: bool,

// Styling
label_style: style_mod.Style,
required_style: style_mod.Style,
error_style: style_mod.Style,
border_chars: border_mod.BorderChars,
border_fg: Color,
border_focus_fg: Color,
title: []const u8,
title_style: style_mod.Style,

const Self = @This();

pub const Field = struct {
label: []const u8,
required: bool,
error_msg: ?[]const u8,
// Type-erased component
ptr: *anyopaque,
view_fn: *const fn (*anyopaque, std.mem.Allocator) anyerror![]const u8,
handle_key_fn: *const fn (*anyopaque, keys.KeyEvent) void,
validate_fn: ?*const fn (*anyopaque) ?[]const u8,
};

pub fn init() Self {
return .{
.fields = [_]?Field{null} ** max_fields,
.field_count = 0,
.focus_group = .{},
.submitted = false,
.cancelled = false,
.label_width = 15,
.spacing = 1,
.show_required_marker = true,
.label_style = blk: {
var s = style_mod.Style{};
s = s.bold(true);
s = s.inline_style(true);
break :blk s;
},
.required_style = blk: {
var s = style_mod.Style{};
s = s.fg(Color.red());
s = s.inline_style(true);
break :blk s;
},
.error_style = blk: {
var s = style_mod.Style{};
s = s.fg(Color.red());
s = s.inline_style(true);
break :blk s;
},
.border_chars = border_mod.Border.rounded,
.border_fg = Color.gray(10),
.border_focus_fg = Color.cyan(),
.title = "",
.title_style = blk: {
var s = style_mod.Style{};
s = s.bold(true);
s = s.fg(Color.cyan());
s = s.inline_style(true);
break :blk s;
},
};
}

/// Add a focusable component as a form field.
pub fn addField(self: *Self, label: []const u8, component: anytype, options: struct {
required: bool = false,
validate_fn: ?*const fn (*anyopaque) ?[]const u8 = null,
}) void {
if (self.field_count >= max_fields) return;

const Ptr = @TypeOf(component);
const T = @typeInfo(Ptr).pointer.child;

self.fields[self.field_count] = .{
.label = label,
.required = options.required,
.error_msg = null,
.ptr = @ptrCast(component),
.view_fn = @ptrCast(&struct {
fn call(raw_ptr: *anyopaque, allocator: std.mem.Allocator) anyerror![]const u8 {
const ptr: *T = @ptrCast(@alignCast(raw_ptr));
return ptr.view(allocator);
}
}.call),
.handle_key_fn = @ptrCast(&struct {
fn call(raw_ptr: *anyopaque, key: keys.KeyEvent) void {
const ptr: *T = @ptrCast(@alignCast(raw_ptr));
ptr.handleKey(key);
}
}.call),
.validate_fn = options.validate_fn,
};

self.focus_group.add(component);
self.field_count += 1;
}

/// Initialize focus on first field.
pub fn initFocus(self: *Self) void {
self.focus_group.initFocus();
}

/// Check if form was submitted.
pub fn isSubmitted(self: *const Self) bool {
return self.submitted;
}

/// Check if form was cancelled.
pub fn isCancelled(self: *const Self) bool {
return self.cancelled;
}

/// Reset submission state.
pub fn reset(self: *Self) void {
self.submitted = false;
self.cancelled = false;
for (0..self.field_count) |i| {
if (self.fields[i]) |*field| {
field.error_msg = null;
}
}
}

/// Validate all fields. Returns true if all pass.
pub fn validate(self: *Self) bool {
var all_valid = true;
for (0..self.field_count) |i| {
if (self.fields[i]) |*field| {
if (field.validate_fn) |vfn| {
field.error_msg = vfn(field.ptr);
if (field.error_msg != null) all_valid = false;
}
}
}
return all_valid;
}

/// Get current focused field index.
pub fn focusedIndex(self: *const Self) usize {
return self.focus_group.focused();
}

/// Handle key events.
pub fn handleKey(self: *Self, key: keys.KeyEvent) bool {
// Ctrl+Enter to submit
if (key.modifiers.ctrl and key.key == .enter) {
if (self.validate()) {
self.submitted = true;
}
return true;
}

// Escape to cancel
if (key.key == .escape) {
self.cancelled = true;
return true;
}

// Tab/Shift+Tab for focus cycling
if (self.focus_group.handleKey(key)) {
return true;
}

// Forward to active field
const active = self.focus_group.focused();
if (active < self.field_count) {
if (self.fields[active]) |field| {
field.handle_key_fn(field.ptr, key);
return true;
}
}

return false;
}

/// Render the form.
pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 {
var result = std.array_list.Managed(u8).init(allocator);
const writer = result.writer();

// Title
if (self.title.len > 0) {
const styled_title = try self.title_style.render(allocator, self.title);
try writer.writeAll(styled_title);
try writer.writeByte('\n');
try writer.writeByte('\n');
}

// Fields
for (0..self.field_count) |i| {
const field = self.fields[i] orelse continue;

if (i > 0) {
for (0..self.spacing) |_| try writer.writeByte('\n');
}

// Label
const label_text = if (field.required and self.show_required_marker)
try std.fmt.allocPrint(allocator, "{s} *", .{field.label})
else
field.label;

const is_focused = self.focus_group.isFocused(i);
const lbl_style = if (is_focused) blk: {
var s = self.label_style;
s = s.fg(self.border_focus_fg);
break :blk s;
} else self.label_style;

const styled_label = try lbl_style.render(allocator, label_text);
try writer.writeAll(styled_label);
try writer.writeByte('\n');

// Component view
const component_view = field.view_fn(field.ptr, allocator) catch try allocator.dupe(u8, "render error");
try writer.writeAll(component_view);

// Error message
if (field.error_msg) |err_msg| {
try writer.writeByte('\n');
const styled_err = try self.error_style.render(allocator, err_msg);
try writer.writeAll(styled_err);
}
}

// Footer
try writer.writeAll("\n\n");
var hint_style = style_mod.Style{};
hint_style = hint_style.fg(Color.gray(12));
hint_style = hint_style.inline_style(true);
const hint = try hint_style.render(allocator, "Tab: next field | Ctrl+Enter: submit | Esc: cancel");
try writer.writeAll(hint);

return result.toOwnedSlice();
}
};
}
2 changes: 2 additions & 0 deletions src/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ pub const components = struct {
pub const CheckboxGroup = checkbox.CheckboxGroup;
pub const RadioGroup = @import("components/radio_group.zig").RadioGroup;
pub const Dropdown = @import("components/dropdown.zig").Dropdown;
pub const Form = @import("components/form.zig").Form;
pub const Markdown = @import("components/markdown.zig").Markdown;
};

Expand Down Expand Up @@ -174,6 +175,7 @@ pub const Checkbox = components.Checkbox;
pub const CheckboxGroup = components.CheckboxGroup;
pub const RadioGroup = components.RadioGroup;
pub const Dropdown = components.Dropdown;
pub const Form = components.Form;
pub const Markdown = components.Markdown;

// Focus management
Expand Down
Loading
Loading