diff --git a/build.zig b/build.zig index 6d0a104..6e5398c 100644 --- a/build.zig +++ b/build.zig @@ -31,6 +31,7 @@ pub fn build(b: *std.Build) void { "menu_bar", "checkbox_radio", "dropdown", + "toast", "context_menu", "form", "markdown", @@ -82,6 +83,7 @@ pub fn build(b: *std.Build) void { "tests/menu_bar_tests.zig", "tests/checkbox_radio_tests.zig", "tests/dropdown_tests.zig", + "tests/toast_tests.zig", "tests/context_menu_tests.zig", "tests/form_tests.zig", "tests/markdown_tests.zig", diff --git a/examples/toast.zig b/examples/toast.zig new file mode 100644 index 0000000..20a24ae --- /dev/null +++ b/examples/toast.zig @@ -0,0 +1,157 @@ +//! ZigZag Toast Example +//! Demonstrates the enhanced toast notification system with positioning and styles. + +const std = @import("std"); +const zz = @import("zigzag"); + +const Model = struct { + toast: zz.Toast, + msg_counter: usize, + last_elapsed: u64, + + pub const Msg = union(enum) { + key: zz.KeyEvent, + tick: zz.msg.Tick, + }; + + pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { + self.toast = zz.Toast.init(ctx.persistent_allocator); + self.toast.position = .top_right; + self.toast.show_countdown = true; + self.msg_counter = 0; + self.last_elapsed = 0; + + // Initial welcome toast + self.toast.push("Welcome to the Toast demo!", .info, 5000, 0) catch {}; + + return .{ .every = 100_000_000 }; + } + + pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) { + switch (msg) { + .tick => { + self.last_elapsed = ctx.elapsed; + self.toast.update(ctx.elapsed); + }, + .key => |k| { + switch (k.key) { + .char => |c| switch (c) { + 'q' => return .quit, + '1' => { + self.msg_counter += 1; + const text = std.fmt.allocPrint(ctx.persistent_allocator, "Info message #{d}", .{self.msg_counter}) catch "Info"; + self.toast.push(text, .info, 3000, ctx.elapsed) catch {}; + }, + '2' => { + self.msg_counter += 1; + const text = std.fmt.allocPrint(ctx.persistent_allocator, "Success #{d}!", .{self.msg_counter}) catch "Success"; + self.toast.push(text, .success, 3000, ctx.elapsed) catch {}; + }, + '3' => { + self.msg_counter += 1; + const text = std.fmt.allocPrint(ctx.persistent_allocator, "Warning #{d}", .{self.msg_counter}) catch "Warning"; + self.toast.push(text, .warning, 4000, ctx.elapsed) catch {}; + }, + '4' => { + self.msg_counter += 1; + const text = std.fmt.allocPrint(ctx.persistent_allocator, "Error #{d}!", .{self.msg_counter}) catch "Error"; + self.toast.push(text, .err, 5000, ctx.elapsed) catch {}; + }, + '5' => { + self.toast.pushPersistent("Persistent notification (press d to dismiss)", .info, ctx.elapsed) catch {}; + }, + 'd' => self.toast.dismiss(), + 'D' => self.toast.dismissAll(), + 'b' => self.toast.show_border = !self.toast.show_border, + 'i' => self.toast.show_icons = !self.toast.show_icons, + 'c' => self.toast.show_countdown = !self.toast.show_countdown, + 'p' => { + self.toast.position = switch (self.toast.position) { + .top_left => .top_center, + .top_center => .top_right, + .top_right => .bottom_right, + .bottom_right => .bottom_center, + .bottom_center => .bottom_left, + .bottom_left => .top_left, + }; + }, + 's' => { + self.toast.stack_order = if (self.toast.stack_order == .newest_first) .oldest_first else .newest_first; + }, + else => {}, + }, + .escape => return .quit, + else => {}, + } + }, + } + return .none; + } + + 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.magenta()); + title_style = title_style.inline_style(true); + const title = title_style.render(ctx.allocator, "Toast Notifications") catch "Toast"; + + const pos_name: []const u8 = switch (self.toast.position) { + .top_left => "top-left", + .top_center => "top-center", + .top_right => "top-right", + .bottom_left => "bottom-left", + .bottom_center => "bottom-center", + .bottom_right => "bottom-right", + }; + const order_name: []const u8 = if (self.toast.stack_order == .newest_first) "newest first" else "oldest first"; + + var info_style = zz.Style{}; + info_style = info_style.fg(zz.Color.cyan()); + info_style = info_style.inline_style(true); + const info = std.fmt.allocPrint( + ctx.allocator, + "Position: {s} | Order: {s} | Active: {d} | Borders: {s} | Icons: {s} | Countdown: {s}", + .{ + pos_name, + order_name, + self.toast.count(), + if (self.toast.show_border) "on" else "off", + if (self.toast.show_icons) "on" else "off", + if (self.toast.show_countdown) "on" else "off", + }, + ) catch "?"; + const styled_info = info_style.render(ctx.allocator, info) catch info; + + 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(ctx.allocator, + \\1: info 2: success 3: warning 4: error 5: persistent + \\d: dismiss D: dismiss all b: borders i: icons c: countdown + \\p: cycle position s: stack order q: quit + ) catch ""; + + // Render toast notifications + const toast_view = self.toast.viewPositioned(ctx.allocator, ctx.width, ctx.height -| 8, self.last_elapsed) catch ""; + + return std.fmt.allocPrint( + ctx.allocator, + "{s}\n{s}\n\n{s}\n\n{s}", + .{ title, styled_info, help, toast_view }, + ) catch "Error"; + } + + pub fn deinit(self: *Model) void { + self.toast.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(); +} diff --git a/src/components/toast.zig b/src/components/toast.zig new file mode 100644 index 0000000..08aff45 --- /dev/null +++ b/src/components/toast.zig @@ -0,0 +1,336 @@ +//! Enhanced Toast/Snackbar notification system. +//! Supports positioning, stacking, icons, borders, and auto-dismiss with countdown. + +const std = @import("std"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const border_mod = @import("../style/border.zig"); +const measure = @import("../layout/measure.zig"); + +pub const Level = enum { + info, + success, + warning, + err, +}; + +pub const Position = enum { + top_left, + top_center, + top_right, + bottom_left, + bottom_center, + bottom_right, +}; + +pub const StackOrder = enum { + newest_first, + oldest_first, +}; + +pub const ToastMessage = struct { + text: []const u8, + level: Level, + created_ns: u64, + duration_ms: u64, + dismissable: bool, +}; + +pub const Toast = struct { + allocator: std.mem.Allocator, + messages: std.array_list.Managed(ToastMessage), + + // Layout + max_visible: usize, + position: Position, + stack_order: StackOrder, + min_width: u16, + max_width: u16, + + // Visual + show_icons: bool, + show_border: bool, + show_countdown: bool, + border_chars: border_mod.BorderChars, + + // Icons per level + info_icon: []const u8, + success_icon: []const u8, + warning_icon: []const u8, + err_icon: []const u8, + + // Styling per level + info_style: style_mod.Style, + success_style: style_mod.Style, + warning_style: style_mod.Style, + err_style: style_mod.Style, + + info_border_fg: Color, + success_border_fg: Color, + warning_border_fg: Color, + err_border_fg: Color, + + pub fn init(allocator: std.mem.Allocator) Toast { + return .{ + .allocator = allocator, + .messages = std.array_list.Managed(ToastMessage).init(allocator), + .max_visible = 5, + .position = .top_right, + .stack_order = .newest_first, + .min_width = 20, + .max_width = 50, + .show_icons = true, + .show_border = true, + .show_countdown = false, + .border_chars = border_mod.Border.rounded, + .info_icon = "\u{2139} ", + .success_icon = "\u{2713} ", + .warning_icon = "\u{26a0} ", + .err_icon = "\u{2717} ", + .info_style = blk: { + var s = style_mod.Style{}; + s = s.fg(Color.cyan()); + s = s.inline_style(true); + break :blk s; + }, + .success_style = blk: { + var s = style_mod.Style{}; + s = s.fg(Color.green()); + s = s.inline_style(true); + break :blk s; + }, + .warning_style = blk: { + var s = style_mod.Style{}; + s = s.fg(Color.yellow()); + s = s.inline_style(true); + break :blk s; + }, + .err_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(Color.red()); + s = s.inline_style(true); + break :blk s; + }, + .info_border_fg = Color.cyan(), + .success_border_fg = Color.green(), + .warning_border_fg = Color.yellow(), + .err_border_fg = Color.red(), + }; + } + + pub fn deinit(self: *Toast) void { + self.messages.deinit(); + } + + /// Push a notification. + pub fn push(self: *Toast, text: []const u8, level: Level, duration_ms: u64, current_ns: u64) !void { + try self.messages.append(.{ + .text = text, + .level = level, + .created_ns = current_ns, + .duration_ms = duration_ms, + .dismissable = true, + }); + } + + /// Push a persistent notification (no auto-dismiss). + pub fn pushPersistent(self: *Toast, text: []const u8, level: Level, current_ns: u64) !void { + try self.messages.append(.{ + .text = text, + .level = level, + .created_ns = current_ns, + .duration_ms = 0, // 0 = no auto-dismiss + .dismissable = true, + }); + } + + /// Dismiss the most recent notification. + pub fn dismiss(self: *Toast) void { + if (self.messages.items.len > 0) { + _ = self.messages.pop(); + } + } + + /// Dismiss all notifications. + pub fn dismissAll(self: *Toast) void { + self.messages.clearRetainingCapacity(); + } + + /// Remove expired notifications. + pub fn update(self: *Toast, current_ns: u64) void { + var i: usize = 0; + while (i < self.messages.items.len) { + const msg = self.messages.items[i]; + if (msg.duration_ms == 0) { + // Persistent - don't auto-dismiss + i += 1; + continue; + } + const elapsed_ms = (current_ns -| msg.created_ns) / std.time.ns_per_ms; + if (elapsed_ms >= msg.duration_ms) { + _ = self.messages.orderedRemove(i); + } else { + i += 1; + } + } + } + + /// Check if there are any active notifications. + pub fn hasMessages(self: *const Toast) bool { + return self.messages.items.len > 0; + } + + /// Count of active messages. + pub fn count(self: *const Toast) usize { + return self.messages.items.len; + } + + /// Render notifications as a vertical stack. + pub fn view(self: *const Toast, allocator: std.mem.Allocator, current_ns: u64) ![]const u8 { + if (self.messages.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + var result = std.array_list.Managed(u8).init(allocator); + const writer = result.writer(); + + const visible_count = @min(self.messages.items.len, self.max_visible); + + // Determine which messages to show based on stack order + const total = self.messages.items.len; + var indices = std.array_list.Managed(usize).init(allocator); + + switch (self.stack_order) { + .newest_first => { + var i: usize = 0; + while (i < visible_count) : (i += 1) { + try indices.append(total - 1 - i); + } + }, + .oldest_first => { + const start = if (total > self.max_visible) total - self.max_visible else 0; + var i: usize = start; + while (i < start + visible_count) : (i += 1) { + try indices.append(i); + } + }, + } + + for (indices.items, 0..) |idx, render_idx| { + if (render_idx > 0) try writer.writeByte('\n'); + + const msg = self.messages.items[idx]; + const toast_str = try self.renderSingleToast(allocator, msg, current_ns); + try writer.writeAll(toast_str); + } + + // Show overflow indicator + if (total > self.max_visible) { + try writer.writeByte('\n'); + const overflow_text = try std.fmt.allocPrint(allocator, " +{d} more", .{total - self.max_visible}); + var dim_style = style_mod.Style{}; + dim_style = dim_style.fg(Color.gray(10)); + dim_style = dim_style.inline_style(true); + const styled = try dim_style.render(allocator, overflow_text); + try writer.writeAll(styled); + } + + return result.toOwnedSlice(); + } + + /// Render for positioned display within a terminal. + pub fn viewPositioned(self: *const Toast, allocator: std.mem.Allocator, term_width: usize, term_height: usize, current_ns: u64) ![]const u8 { + const toast_content = try self.view(allocator, current_ns); + if (toast_content.len == 0) return toast_content; + + const content_width = measure.maxLineWidth(toast_content); + const content_height = measure.height(toast_content); + + const place_mod = @import("../layout/place.zig"); + + const hpos: f32 = switch (self.position) { + .top_left, .bottom_left => 0.0, + .top_center, .bottom_center => 0.5, + .top_right, .bottom_right => 1.0, + }; + const vpos: f32 = switch (self.position) { + .top_left, .top_center, .top_right => 0.0, + .bottom_left, .bottom_center, .bottom_right => 1.0, + }; + + _ = content_width; + _ = content_height; + + return place_mod.placeFloat(allocator, term_width, term_height, hpos, vpos, toast_content); + } + + fn renderSingleToast(self: *const Toast, allocator: std.mem.Allocator, msg: ToastMessage, current_ns: u64) ![]const u8 { + const active_style = self.styleForLevel(msg.level); + + var line = std.array_list.Managed(u8).init(allocator); + const lw = line.writer(); + + // Icon + if (self.show_icons) { + const icon = switch (msg.level) { + .info => self.info_icon, + .success => self.success_icon, + .warning => self.warning_icon, + .err => self.err_icon, + }; + const styled_icon = try active_style.render(allocator, icon); + try lw.writeAll(styled_icon); + } + + // Text + const styled_text = try active_style.render(allocator, msg.text); + try lw.writeAll(styled_text); + + // Countdown + if (self.show_countdown and msg.duration_ms > 0) { + const elapsed_ms = (current_ns -| msg.created_ns) / std.time.ns_per_ms; + const remaining = if (elapsed_ms < msg.duration_ms) msg.duration_ms - elapsed_ms else 0; + const remaining_sec = remaining / 1000; + const countdown = try std.fmt.allocPrint(allocator, " ({d}s)", .{remaining_sec}); + var dim_style = style_mod.Style{}; + dim_style = dim_style.fg(Color.gray(10)); + dim_style = dim_style.inline_style(true); + const styled_cd = try dim_style.render(allocator, countdown); + try lw.writeAll(styled_cd); + } + + const line_content = try line.toOwnedSlice(); + + if (!self.show_border) { + return line_content; + } + + // Wrap in border + var box_style = style_mod.Style{}; + box_style = box_style.borderAll(self.border_chars); + box_style = box_style.borderForeground(self.borderColorForLevel(msg.level)); + box_style = box_style.paddingLeft(1).paddingRight(1); + box_style = box_style.inline_style(false); + + return box_style.render(allocator, line_content); + } + + fn styleForLevel(self: *const Toast, level: Level) style_mod.Style { + return switch (level) { + .info => self.info_style, + .success => self.success_style, + .warning => self.warning_style, + .err => self.err_style, + }; + } + + fn borderColorForLevel(self: *const Toast, level: Level) Color { + return switch (level) { + .info => self.info_border_fg, + .success => self.success_border_fg, + .warning => self.warning_border_fg, + .err => self.err_border_fg, + }; + } +}; diff --git a/src/root.zig b/src/root.zig index 5501551..f1d9e3b 100644 --- a/src/root.zig +++ b/src/root.zig @@ -145,6 +145,10 @@ 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 toast = @import("components/toast.zig"); + pub const Toast = toast.Toast; + pub const ToastPosition = toast.Position; + pub const ToastLevel = toast.Level; pub const ContextMenu = @import("components/context_menu.zig").ContextMenu; pub const Form = @import("components/form.zig").Form; pub const Markdown = @import("components/markdown.zig").Markdown; @@ -176,6 +180,9 @@ pub const Checkbox = components.Checkbox; pub const CheckboxGroup = components.CheckboxGroup; pub const RadioGroup = components.RadioGroup; pub const Dropdown = components.Dropdown; +pub const Toast = components.Toast; +pub const ToastPosition = components.ToastPosition; +pub const ToastLevel = components.ToastLevel; pub const ContextMenu = components.ContextMenu; pub const Form = components.Form; pub const Markdown = components.Markdown; diff --git a/tests/toast_tests.zig b/tests/toast_tests.zig new file mode 100644 index 0000000..8f1040a --- /dev/null +++ b/tests/toast_tests.zig @@ -0,0 +1,135 @@ +const std = @import("std"); +const testing = std.testing; +const zz = @import("zigzag"); + +test "Toast init defaults" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try testing.expect(!t.hasMessages()); + try testing.expectEqual(@as(usize, 0), t.count()); + try testing.expect(t.show_icons); + try testing.expect(t.show_border); + try testing.expectEqual(zz.ToastPosition.top_right, t.position); +} + +test "Toast push and count" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.push("Hello", .info, 3000, 0); + try testing.expectEqual(@as(usize, 1), t.count()); + try testing.expect(t.hasMessages()); + + try t.push("World", .success, 3000, 0); + try testing.expectEqual(@as(usize, 2), t.count()); +} + +test "Toast dismiss removes last" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.push("First", .info, 3000, 0); + try t.push("Second", .success, 3000, 0); + try testing.expectEqual(@as(usize, 2), t.count()); + + t.dismiss(); + try testing.expectEqual(@as(usize, 1), t.count()); + try testing.expectEqualStrings("First", t.messages.items[0].text); +} + +test "Toast dismissAll clears everything" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.push("A", .info, 3000, 0); + try t.push("B", .warning, 3000, 0); + try t.push("C", .err, 3000, 0); + + t.dismissAll(); + try testing.expectEqual(@as(usize, 0), t.count()); +} + +test "Toast update removes expired messages" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.push("Short", .info, 1000, 0); // 1 second + try t.push("Long", .success, 5000, 0); // 5 seconds + + // After 2 seconds, short should be gone + t.update(2_000_000_000); + try testing.expectEqual(@as(usize, 1), t.count()); + try testing.expectEqualStrings("Long", t.messages.items[0].text); +} + +test "Toast persistent messages survive update" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.pushPersistent("Sticky", .warning, 0); + try t.push("Timed", .info, 1000, 0); + + // After 2 seconds + t.update(2_000_000_000); + try testing.expectEqual(@as(usize, 1), t.count()); + try testing.expectEqualStrings("Sticky", t.messages.items[0].text); +} + +test "Toast view renders empty when no messages" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + const output = try t.view(testing.allocator, 0); + defer testing.allocator.free(output); + try testing.expectEqual(@as(usize, 0), output.len); +} + +test "Toast view renders messages" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + try t.push("Test message", .info, 3000, 0); + + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + + const output = try t.view(arena.allocator(), 0); + try testing.expect(output.len > 0); +} + +test "Toast max_visible limits display" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + t.max_visible = 2; + + try t.push("One", .info, 3000, 0); + try t.push("Two", .info, 3000, 0); + try t.push("Three", .info, 3000, 0); + + try testing.expectEqual(@as(usize, 3), t.count()); // all stored + + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + + const output = try t.view(arena.allocator(), 0); + try testing.expect(output.len > 0); + // Should contain overflow indicator + try testing.expect(std.mem.indexOf(u8, output, "+1 more") != null); +} + +test "Toast without borders" { + var t = zz.Toast.init(testing.allocator); + defer t.deinit(); + + t.show_border = false; + + try t.push("No border", .success, 3000, 0); + + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + + const output = try t.view(arena.allocator(), 0); + try testing.expect(output.len > 0); +}