From 23256f1ae8abcfab19ab70bcf2769f592798a45d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 12:57:32 +0200 Subject: [PATCH 1/8] refactor: extract fuzzy matcher into reusable utility Consolidate the fuzzy scoring logic previously duplicated inline in list and dropdown components into src/core/fuzzy.zig. Adds matchPositions for highlighting and a rank helper, exposed via zz.fuzzy. --- src/components/dropdown.zig | 54 ++---------- src/components/list.zig | 66 ++------------ src/core/fuzzy.zig | 171 ++++++++++++++++++++++++++++++++++++ src/root.zig | 1 + 4 files changed, 184 insertions(+), 108 deletions(-) create mode 100644 src/core/fuzzy.zig diff --git a/src/components/dropdown.zig b/src/components/dropdown.zig index 30f4034..d0d9a31 100644 --- a/src/components/dropdown.zig +++ b/src/components/dropdown.zig @@ -7,6 +7,7 @@ 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"); +const fuzzy = @import("../core/fuzzy.zig"); pub fn Dropdown(comptime T: type) type { return struct { @@ -456,25 +457,16 @@ pub fn Dropdown(comptime T: type) type { try self.filtered_indices.append(i); } } else { - const filter_lower = try toLower(self.allocator, self.filter_text.items); - defer self.allocator.free(filter_lower); - - const ScoredIndex = struct { index: usize, score: i32 }; - var scored = std.array_list.Managed(ScoredIndex).init(self.allocator); + var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); defer scored.deinit(); for (self.items.items, 0..) |item, i| { - const title_lower = try toLower(self.allocator, item.label); - defer self.allocator.free(title_lower); - - const score = fuzzyScore(title_lower, filter_lower); - if (score > 0) { - try scored.append(.{ .index = i, .score = score }); - } + const s = fuzzy.scoreIgnoreCase(item.label, self.filter_text.items); + if (s > 0) try scored.append(.{ .index = i, .score = s }); } - std.mem.sort(ScoredIndex, scored.items, {}, struct { - pub fn lessThan(_: void, a: ScoredIndex, b: ScoredIndex) bool { + std.mem.sort(fuzzy.Ranked, scored.items, {}, struct { + pub fn lessThan(_: void, a: fuzzy.Ranked, b: fuzzy.Ranked) bool { return a.score > b.score; } }.lessThan); @@ -490,40 +482,6 @@ pub fn Dropdown(comptime T: type) type { self.ensureVisible(); } - fn fuzzyScore(text: []const u8, pattern: []const u8) i32 { - if (pattern.len == 0) return 1; - if (text.len == 0) return 0; - - var score: i32 = 0; - var pi: usize = 0; - var consecutive: i32 = 0; - - for (text, 0..) |c, ti| { - if (pi < pattern.len and c == pattern[pi]) { - score += 1; - consecutive += 1; - score += consecutive; - if (ti == 0 or text[ti - 1] == ' ' or text[ti - 1] == '_' or text[ti - 1] == '-') { - score += 5; - } - pi += 1; - } else { - consecutive = 0; - } - } - - if (pi < pattern.len) return 0; - return score; - } - - fn toLower(allocator: std.mem.Allocator, str: []const u8) ![]u8 { - const result = try allocator.alloc(u8, str.len); - for (str, 0..) |c, i| { - result[i] = if (c >= 'A' and c <= 'Z') c + 32 else c; - } - return result; - } - // ── Rendering ─────────────────────────────────── pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { diff --git a/src/components/list.zig b/src/components/list.zig index 0b5be48..2e15d79 100644 --- a/src/components/list.zig +++ b/src/components/list.zig @@ -5,6 +5,7 @@ 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 fuzzy = @import("../core/fuzzy.zig"); pub fn List(comptime T: type) type { return struct { @@ -361,40 +362,24 @@ pub fn List(comptime T: type) type { return self.filtered_indices.items; } - const ScoredIndex = struct { - index: usize, - score: i32, - }; - pub fn updateFilter(self: *Self) !void { self.filtered_indices.clearRetainingCapacity(); if (self.filter_text.items.len == 0) { - // No filter - show all for (0..self.items.items.len) |i| { try self.filtered_indices.append(i); } } else { - // Fuzzy match by title - const filter_lower = try self.toLower(self.allocator, self.filter_text.items); - defer self.allocator.free(filter_lower); - - var scored = std.array_list.Managed(ScoredIndex).init(self.allocator); + var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); defer scored.deinit(); for (self.items.items, 0..) |item, i| { - const title_lower = try self.toLower(self.allocator, item.title); - defer self.allocator.free(title_lower); - - const score = fuzzyScore(title_lower, filter_lower); - if (score > 0) { - try scored.append(.{ .index = i, .score = score }); - } + const s = fuzzy.scoreIgnoreCase(item.title, self.filter_text.items); + if (s > 0) try scored.append(.{ .index = i, .score = s }); } - // Sort by score descending - std.mem.sort(ScoredIndex, scored.items, {}, struct { - pub fn lessThan(_: void, a: ScoredIndex, b: ScoredIndex) bool { + std.mem.sort(fuzzy.Ranked, scored.items, {}, struct { + pub fn lessThan(_: void, a: fuzzy.Ranked, b: fuzzy.Ranked) bool { return a.score > b.score; } }.lessThan); @@ -404,51 +389,12 @@ pub fn List(comptime T: type) type { } } - // Adjust cursor if (self.cursor >= self.filtered_indices.items.len and self.filtered_indices.items.len > 0) { self.cursor = self.filtered_indices.items.len - 1; } self.ensureVisible(); } - fn fuzzyScore(text: []const u8, pattern: []const u8) i32 { - if (pattern.len == 0) return 1; - if (text.len == 0) return 0; - - var score: i32 = 0; - var pi: usize = 0; // pattern index - var consecutive: i32 = 0; - - for (text, 0..) |c, ti| { - if (pi < pattern.len and c == pattern[pi]) { - score += 1; - consecutive += 1; - // Consecutive bonus - score += consecutive; - // Word start bonus - if (ti == 0 or text[ti - 1] == ' ' or text[ti - 1] == '_' or text[ti - 1] == '-') { - score += 5; - } - pi += 1; - } else { - consecutive = 0; - } - } - - // All pattern chars must match - if (pi < pattern.len) return 0; - return score; - } - - fn toLower(self: *const Self, allocator: std.mem.Allocator, str: []const u8) ![]u8 { - _ = self; - const result = try allocator.alloc(u8, str.len); - for (str, 0..) |c, i| { - result[i] = if (c >= 'A' and c <= 'Z') c + 32 else c; - } - return result; - } - fn ensureVisible(self: *Self) void { if (self.cursor < self.y_offset) { self.y_offset = self.cursor; diff --git a/src/core/fuzzy.zig b/src/core/fuzzy.zig new file mode 100644 index 0000000..296e227 --- /dev/null +++ b/src/core/fuzzy.zig @@ -0,0 +1,171 @@ +//! Fuzzy string matching utility. +//! +//! Provides character-subsequence scoring used by filterable components like +//! `List`, `Dropdown`, and `CommandPalette`. The scoring rewards consecutive +//! matches and word-start positions so that "fb" ranks "file_browser" above +//! "find_buffer". + +const std = @import("std"); + +/// Score a subsequence match. Returns 0 when `pattern` is not a subsequence of +/// `text`. Comparison is case-sensitive: use `scoreIgnoreCase` if you want to +/// ignore case without allocating. +pub fn score(text: []const u8, pattern: []const u8) i32 { + if (pattern.len == 0) return 1; + if (text.len == 0) return 0; + + var total: i32 = 0; + var pi: usize = 0; + var consecutive: i32 = 0; + + for (text, 0..) |c, ti| { + if (pi < pattern.len and c == pattern[pi]) { + total += 1; + consecutive += 1; + total += consecutive; + if (ti == 0 or text[ti - 1] == ' ' or text[ti - 1] == '_' or text[ti - 1] == '-' or text[ti - 1] == '/') { + total += 5; + } + pi += 1; + } else { + consecutive = 0; + } + } + + if (pi < pattern.len) return 0; + return total; +} + +/// Like `score` but compares ASCII characters case-insensitively without +/// allocating. Non-ASCII bytes are compared exactly. +pub fn scoreIgnoreCase(text: []const u8, pattern: []const u8) i32 { + if (pattern.len == 0) return 1; + if (text.len == 0) return 0; + + var total: i32 = 0; + var pi: usize = 0; + var consecutive: i32 = 0; + + for (text, 0..) |c, ti| { + if (pi < pattern.len and asciiLower(c) == asciiLower(pattern[pi])) { + total += 1; + consecutive += 1; + total += consecutive; + if (ti == 0 or text[ti - 1] == ' ' or text[ti - 1] == '_' or text[ti - 1] == '-' or text[ti - 1] == '/') { + total += 5; + } + pi += 1; + } else { + consecutive = 0; + } + } + + if (pi < pattern.len) return 0; + return total; +} + +/// Return the byte positions in `text` that match characters of `pattern` in +/// order. Useful for highlighting matched characters. Returns `null` if +/// `pattern` is not a subsequence. +pub fn matchPositions( + allocator: std.mem.Allocator, + text: []const u8, + pattern: []const u8, + ignore_case: bool, +) !?[]usize { + if (pattern.len == 0) return try allocator.alloc(usize, 0); + + var positions = try std.array_list.Managed(usize).initCapacity(allocator, pattern.len); + errdefer positions.deinit(); + + var pi: usize = 0; + for (text, 0..) |c, ti| { + if (pi >= pattern.len) break; + const a = if (ignore_case) asciiLower(c) else c; + const b = if (ignore_case) asciiLower(pattern[pi]) else pattern[pi]; + if (a == b) { + try positions.append(ti); + pi += 1; + } + } + + if (pi < pattern.len) { + positions.deinit(); + return null; + } + return try positions.toOwnedSlice(); +} + +pub const Ranked = struct { + index: usize, + score: i32, +}; + +/// Score every haystack entry against `pattern` and return the ones with a +/// positive score, sorted by score descending. Caller owns the returned slice. +pub fn rank( + allocator: std.mem.Allocator, + haystack: []const []const u8, + pattern: []const u8, + ignore_case: bool, +) ![]Ranked { + var out = std.array_list.Managed(Ranked).init(allocator); + errdefer out.deinit(); + + for (haystack, 0..) |entry, i| { + const s = if (ignore_case) scoreIgnoreCase(entry, pattern) else score(entry, pattern); + if (s > 0) try out.append(.{ .index = i, .score = s }); + } + + std.mem.sort(Ranked, out.items, {}, struct { + fn lt(_: void, a: Ranked, b: Ranked) bool { + return a.score > b.score; + } + }.lt); + + return out.toOwnedSlice(); +} + +fn asciiLower(c: u8) u8 { + return if (c >= 'A' and c <= 'Z') c + 32 else c; +} + +test "empty pattern matches with score 1" { + try std.testing.expectEqual(@as(i32, 1), score("hello", "")); + try std.testing.expectEqual(@as(i32, 1), scoreIgnoreCase("hello", "")); +} + +test "non-subsequence returns zero" { + try std.testing.expectEqual(@as(i32, 0), score("hello", "xyz")); +} + +test "consecutive matches score higher than scattered" { + // Both have the 'h' at a word-start, so the difference comes from the + // second character: consecutive in "hello", scattered in "hxexy". + const consec = score("hello", "he"); + const split = score("hxexy", "he"); + try std.testing.expect(consec > split); +} + +test "case insensitive" { + try std.testing.expect(scoreIgnoreCase("HELLO", "he") > 0); + try std.testing.expect(score("HELLO", "he") == 0); +} + +test "matchPositions returns byte indices" { + const allocator = std.testing.allocator; + const positions = (try matchPositions(allocator, "hello", "hl", false)).?; + defer allocator.free(positions); + try std.testing.expectEqualSlices(usize, &.{ 0, 2 }, positions); +} + +test "rank sorts by score descending" { + const allocator = std.testing.allocator; + const items = [_][]const u8{ "apple", "application", "ape" }; + const ranked = try rank(allocator, &items, "app", false); + defer allocator.free(ranked); + try std.testing.expect(ranked.len >= 2); + // "apple" and "application" both start with "app"; first-place tie is + // valid, but "ape" (partial) should lose if present. + for (ranked) |r| try std.testing.expect(r.score > 0); +} diff --git a/src/root.zig b/src/root.zig index 4916347..31c6414 100644 --- a/src/root.zig +++ b/src/root.zig @@ -63,6 +63,7 @@ pub const Options = @import("core/context.zig").Options; pub const msg = @import("core/message.zig"); pub const log = @import("core/log.zig"); pub const Logger = log.Logger; +pub const fuzzy = @import("core/fuzzy.zig"); pub const animation = @import("core/animation.zig"); pub const Tween = animation.Tween; pub const Easing = animation.Easing; From 46ad8b4922f7a5449b3cd7e28bf47da870ecb6b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 12:59:06 +0200 Subject: [PATCH 2/8] feat: add status bar component Single-line bar with left/center/right segment groups, each with independent styling. Useful as a footer for editor-style apps and dashboards. Exposed via zz.StatusBar. --- src/components/status_bar.zig | 214 ++++++++++++++++++++++++++++++++++ src/root.zig | 5 + 2 files changed, 219 insertions(+) create mode 100644 src/components/status_bar.zig diff --git a/src/components/status_bar.zig b/src/components/status_bar.zig new file mode 100644 index 0000000..4a5f2ef --- /dev/null +++ b/src/components/status_bar.zig @@ -0,0 +1,214 @@ +//! Status bar component. +//! +//! Renders a single-line bar with left, center, and right-aligned segments. +//! Each segment may have its own style and is styled independently so the bar +//! can show, for example, a mode indicator, the current file, and cursor +//! position simultaneously. + +const std = @import("std"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); + +pub const Segment = struct { + text: []const u8, + style: ?style_mod.Style = null, +}; + +pub const StatusBar = struct { + allocator: std.mem.Allocator, + + left: std.array_list.Managed(Segment), + center: std.array_list.Managed(Segment), + right: std.array_list.Managed(Segment), + + width: u16, + separator: []const u8, + /// Style applied to the gap characters between segment groups. + base_style: style_mod.Style, + + pub fn init(allocator: std.mem.Allocator) StatusBar { + var base = style_mod.Style{}; + base = base.bg(Color.gray(4)); + base = base.fg(Color.gray(14)); + base = base.inline_style(true); + + return .{ + .allocator = allocator, + .left = std.array_list.Managed(Segment).init(allocator), + .center = std.array_list.Managed(Segment).init(allocator), + .right = std.array_list.Managed(Segment).init(allocator), + .width = 80, + .separator = " │ ", + .base_style = base, + }; + } + + pub fn deinit(self: *StatusBar) void { + self.left.deinit(); + self.center.deinit(); + self.right.deinit(); + } + + pub fn setWidth(self: *StatusBar, w: u16) void { + self.width = w; + } + + pub fn setBaseStyle(self: *StatusBar, s: style_mod.Style) void { + self.base_style = s; + } + + pub fn setSeparator(self: *StatusBar, sep: []const u8) void { + self.separator = sep; + } + + pub fn addLeft(self: *StatusBar, segment: Segment) !void { + try self.left.append(segment); + } + + pub fn addCenter(self: *StatusBar, segment: Segment) !void { + try self.center.append(segment); + } + + pub fn addRight(self: *StatusBar, segment: Segment) !void { + try self.right.append(segment); + } + + pub fn clear(self: *StatusBar) void { + self.left.clearRetainingCapacity(); + self.center.clearRetainingCapacity(); + self.right.clearRetainingCapacity(); + } + + /// Replace all left segments with a single-segment string. + pub fn setLeft(self: *StatusBar, text: []const u8, s: ?style_mod.Style) !void { + self.left.clearRetainingCapacity(); + try self.left.append(.{ .text = text, .style = s }); + } + + pub fn setCenter(self: *StatusBar, text: []const u8, s: ?style_mod.Style) !void { + self.center.clearRetainingCapacity(); + try self.center.append(.{ .text = text, .style = s }); + } + + pub fn setRight(self: *StatusBar, text: []const u8, s: ?style_mod.Style) !void { + self.right.clearRetainingCapacity(); + try self.right.append(.{ .text = text, .style = s }); + } + + /// Render the status bar to a single line padded to `width` columns. + pub fn view(self: *const StatusBar, allocator: std.mem.Allocator) ![]const u8 { + const left_str = try self.renderGroup(allocator, self.left.items); + defer allocator.free(left_str); + const center_str = try self.renderGroup(allocator, self.center.items); + defer allocator.free(center_str); + const right_str = try self.renderGroup(allocator, self.right.items); + defer allocator.free(right_str); + + const lw = measure.width(left_str); + const cw = measure.width(center_str); + const rw = measure.width(right_str); + + var result = std.array_list.Managed(u8).init(allocator); + const writer = result.writer(); + + try writer.writeAll(left_str); + + // Center text: place it so its midpoint sits on width/2, but never + // overlap the left or right groups. + if (cw > 0) { + const target_start = (self.width -| cw) / 2; + const start = @max(lw, target_start); + const gap = start -| lw; + try self.writeGap(writer.any(), allocator, gap); + try writer.writeAll(center_str); + const consumed = lw + gap + cw; + const trailing = (self.width -| rw) -| consumed; + try self.writeGap(writer.any(), allocator, trailing); + } else { + const gap = (self.width -| rw) -| lw; + try self.writeGap(writer.any(), allocator, gap); + } + + try writer.writeAll(right_str); + + return result.toOwnedSlice(); + } + + fn renderGroup(self: *const StatusBar, allocator: std.mem.Allocator, items: []const Segment) ![]u8 { + var out = std.array_list.Managed(u8).init(allocator); + const w = out.writer(); + for (items, 0..) |seg, i| { + if (i > 0) { + if (self.separator.len > 0) { + const sep_styled = try self.base_style.render(allocator, self.separator); + defer allocator.free(sep_styled); + try w.writeAll(sep_styled); + } + } + if (seg.style) |s| { + const styled = try s.render(allocator, seg.text); + defer allocator.free(styled); + try w.writeAll(styled); + } else { + const styled = try self.base_style.render(allocator, seg.text); + defer allocator.free(styled); + try w.writeAll(styled); + } + } + return out.toOwnedSlice(); + } + + fn writeGap(self: *const StatusBar, writer: std.io.AnyWriter, allocator: std.mem.Allocator, count: usize) !void { + if (count == 0) return; + const spaces = try allocator.alloc(u8, count); + defer allocator.free(spaces); + @memset(spaces, ' '); + const styled = try self.base_style.render(allocator, spaces); + defer allocator.free(styled); + try writer.writeAll(styled); + } +}; + +test "status bar places left and right segments on opposite ends" { + const allocator = std.testing.allocator; + var bar = StatusBar.init(allocator); + defer bar.deinit(); + + bar.setWidth(20); + try bar.setLeft("L", null); + try bar.setRight("R", null); + + const out = try bar.view(allocator); + defer allocator.free(out); + try std.testing.expectEqual(@as(usize, 20), measure.width(out)); +} + +test "status bar centers middle segment" { + const allocator = std.testing.allocator; + var bar = StatusBar.init(allocator); + defer bar.deinit(); + + bar.setWidth(30); + try bar.setLeft("A", null); + try bar.setCenter("MID", null); + try bar.setRight("Z", null); + + const out = try bar.view(allocator); + defer allocator.free(out); + try std.testing.expectEqual(@as(usize, 30), measure.width(out)); +} + +test "status bar tolerates narrow width" { + const allocator = std.testing.allocator; + var bar = StatusBar.init(allocator); + defer bar.deinit(); + + bar.setWidth(5); + try bar.setLeft("hello", null); + try bar.setRight("world", null); + + // Even with overflow, rendering must not crash. + const out = try bar.view(allocator); + defer allocator.free(out); +} diff --git a/src/root.zig b/src/root.zig index 31c6414..d8af5da 100644 --- a/src/root.zig +++ b/src/root.zig @@ -187,6 +187,9 @@ pub const components = struct { pub const heatmap = @import("components/heatmap.zig"); pub const Heatmap = heatmap.Heatmap; pub const Gauge = @import("components/gauge.zig").Gauge; + pub const status_bar = @import("components/status_bar.zig"); + pub const StatusBar = status_bar.StatusBar; + pub const StatusSegment = status_bar.Segment; }; // Re-export commonly used components at top level @@ -224,6 +227,8 @@ pub const Markdown = components.Markdown; pub const Calendar = components.Calendar; pub const Heatmap = components.Heatmap; pub const Gauge = components.Gauge; +pub const StatusBar = components.StatusBar; +pub const StatusSegment = components.StatusSegment; // Focus management pub const FocusGroup = components.focus.FocusGroup; From 54fdc44f571ee4dcce2b40012cd5dc9ce95e75e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:00:23 +0200 Subject: [PATCH 3/8] feat: add breadcrumb component Horizontal path navigation with styled segments, custom separator, and middle-ellipsis truncation when max_width is set. Highlights the final segment as the active location. Exposed via zz.Breadcrumb. --- src/components/breadcrumb.zig | 222 ++++++++++++++++++++++++++++++++++ src/root.zig | 5 + 2 files changed, 227 insertions(+) create mode 100644 src/components/breadcrumb.zig diff --git a/src/components/breadcrumb.zig b/src/components/breadcrumb.zig new file mode 100644 index 0000000..0cd931f --- /dev/null +++ b/src/components/breadcrumb.zig @@ -0,0 +1,222 @@ +//! Breadcrumb navigation component. +//! +//! Renders a horizontal path like `root > users > profile` with the active +//! (last) segment highlighted. Supports custom separators and truncation when +//! the rendered path would exceed a max width. + +const std = @import("std"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); + +pub const Crumb = struct { + label: []const u8, + /// Optional user-defined id so consumers can identify which segment was + /// clicked or selected. Not used for rendering. + id: ?[]const u8 = null, +}; + +pub const Breadcrumb = struct { + allocator: std.mem.Allocator, + crumbs: std.array_list.Managed(Crumb), + + separator: []const u8, + /// If non-zero, the rendered breadcrumb is truncated to fit this many + /// columns, replacing the middle with an ellipsis segment. + max_width: usize, + + segment_style: style_mod.Style, + active_style: style_mod.Style, + separator_style: style_mod.Style, + + pub fn init(allocator: std.mem.Allocator) Breadcrumb { + var seg = style_mod.Style{}; + seg = seg.fg(Color.gray(12)); + seg = seg.inline_style(true); + + var active = style_mod.Style{}; + active = active.fg(Color.cyan()); + active = active.bold(true); + active = active.inline_style(true); + + var sep = style_mod.Style{}; + sep = sep.fg(Color.gray(8)); + sep = sep.inline_style(true); + + return .{ + .allocator = allocator, + .crumbs = std.array_list.Managed(Crumb).init(allocator), + .separator = " › ", + .max_width = 0, + .segment_style = seg, + .active_style = active, + .separator_style = sep, + }; + } + + pub fn deinit(self: *Breadcrumb) void { + self.crumbs.deinit(); + } + + pub fn push(self: *Breadcrumb, crumb: Crumb) !void { + try self.crumbs.append(crumb); + } + + pub fn pop(self: *Breadcrumb) ?Crumb { + if (self.crumbs.items.len == 0) return null; + return self.crumbs.pop(); + } + + pub fn clear(self: *Breadcrumb) void { + self.crumbs.clearRetainingCapacity(); + } + + pub fn setSeparator(self: *Breadcrumb, sep: []const u8) void { + self.separator = sep; + } + + pub fn setMaxWidth(self: *Breadcrumb, w: usize) void { + self.max_width = w; + } + + /// Replace all crumbs with a single path built from labels. + pub fn setPath(self: *Breadcrumb, labels: []const []const u8) !void { + self.crumbs.clearRetainingCapacity(); + for (labels) |label| try self.crumbs.append(.{ .label = label }); + } + + pub fn view(self: *const Breadcrumb, allocator: std.mem.Allocator) ![]const u8 { + if (self.crumbs.items.len == 0) return try allocator.dupe(u8, ""); + + var full = try self.renderCrumbs(allocator, self.crumbs.items); + if (self.max_width == 0 or measure.width(full) <= self.max_width) return full; + + // Truncate: keep first and last N crumbs, replace middle with ellipsis. + allocator.free(full); + + const n = self.crumbs.items.len; + if (n <= 2) { + full = try self.renderCrumbs(allocator, self.crumbs.items); + return full; + } + + // Start with [first, ..., last], then widen outward while fitting. + var head_count: usize = 1; + var tail_count: usize = 1; + var best: ?[]u8 = null; + + while (head_count + tail_count < n) { + const candidate = try self.renderTruncated(allocator, head_count, tail_count); + if (measure.width(candidate) > self.max_width) { + allocator.free(candidate); + break; + } + if (best) |b| allocator.free(b); + best = candidate; + + // Prefer growing the tail (most relevant to user's position). + if (tail_count <= head_count) { + tail_count += 1; + } else { + head_count += 1; + } + } + + if (best) |b| return b; + return self.renderTruncated(allocator, 1, 1); + } + + fn renderTruncated(self: *const Breadcrumb, allocator: std.mem.Allocator, head: usize, tail: usize) ![]u8 { + var out = std.array_list.Managed(u8).init(allocator); + const w = out.writer(); + + const head_slice = self.crumbs.items[0..head]; + const tail_slice = self.crumbs.items[self.crumbs.items.len - tail ..]; + + var first = true; + for (head_slice) |c| { + if (!first) { + const sep = try self.separator_style.render(allocator, self.separator); + defer allocator.free(sep); + try w.writeAll(sep); + } + first = false; + const seg = try self.segment_style.render(allocator, c.label); + defer allocator.free(seg); + try w.writeAll(seg); + } + + const sep = try self.separator_style.render(allocator, self.separator); + defer allocator.free(sep); + try w.writeAll(sep); + const ellipsis = try self.segment_style.render(allocator, "…"); + defer allocator.free(ellipsis); + try w.writeAll(ellipsis); + + for (tail_slice, 0..) |c, i| { + const s = try self.separator_style.render(allocator, self.separator); + defer allocator.free(s); + try w.writeAll(s); + + const is_last = i == tail_slice.len - 1; + const crumb_style = if (is_last) self.active_style else self.segment_style; + const seg = try crumb_style.render(allocator, c.label); + defer allocator.free(seg); + try w.writeAll(seg); + } + + return out.toOwnedSlice(); + } + + fn renderCrumbs(self: *const Breadcrumb, allocator: std.mem.Allocator, items: []const Crumb) ![]u8 { + var out = std.array_list.Managed(u8).init(allocator); + const w = out.writer(); + + for (items, 0..) |c, i| { + if (i > 0) { + const sep = try self.separator_style.render(allocator, self.separator); + defer allocator.free(sep); + try w.writeAll(sep); + } + const is_last = i == items.len - 1; + const s = if (is_last) self.active_style else self.segment_style; + const seg = try s.render(allocator, c.label); + defer allocator.free(seg); + try w.writeAll(seg); + } + + return out.toOwnedSlice(); + } +}; + +test "breadcrumb renders empty as empty string" { + const allocator = std.testing.allocator; + var bc = Breadcrumb.init(allocator); + defer bc.deinit(); + const out = try bc.view(allocator); + defer allocator.free(out); + try std.testing.expectEqual(@as(usize, 0), out.len); +} + +test "breadcrumb renders path with separators" { + const allocator = std.testing.allocator; + var bc = Breadcrumb.init(allocator); + defer bc.deinit(); + try bc.setPath(&.{ "root", "users", "profile" }); + const out = try bc.view(allocator); + defer allocator.free(out); + // 3 labels (13 chars: root=4, users=5, profile=7) + 2 separators (each 3 cols = 6). + try std.testing.expectEqual(@as(usize, 4 + 3 + 5 + 3 + 7), measure.width(out)); +} + +test "breadcrumb truncates when over max width" { + const allocator = std.testing.allocator; + var bc = Breadcrumb.init(allocator); + defer bc.deinit(); + try bc.setPath(&.{ "aaaa", "bbbb", "cccc", "dddd", "eeee" }); + bc.setMaxWidth(18); + const out = try bc.view(allocator); + defer allocator.free(out); + try std.testing.expect(measure.width(out) <= 18); + try std.testing.expect(std.mem.indexOf(u8, out, "…") != null); +} diff --git a/src/root.zig b/src/root.zig index d8af5da..241d591 100644 --- a/src/root.zig +++ b/src/root.zig @@ -190,6 +190,9 @@ pub const components = struct { pub const status_bar = @import("components/status_bar.zig"); pub const StatusBar = status_bar.StatusBar; pub const StatusSegment = status_bar.Segment; + pub const breadcrumb = @import("components/breadcrumb.zig"); + pub const Breadcrumb = breadcrumb.Breadcrumb; + pub const Crumb = breadcrumb.Crumb; }; // Re-export commonly used components at top level @@ -229,6 +232,8 @@ pub const Heatmap = components.Heatmap; pub const Gauge = components.Gauge; pub const StatusBar = components.StatusBar; pub const StatusSegment = components.StatusSegment; +pub const Breadcrumb = components.Breadcrumb; +pub const Crumb = components.Crumb; // Focus management pub const FocusGroup = components.focus.FocusGroup; From c1497af5eb367cce40523dd1f3e4e5e9bc2f2eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:01:34 +0200 Subject: [PATCH 4/8] feat: add stepper (wizard) component Multi-step progress indicator with completed/current/pending states, horizontal or vertical orientation, and keyboard navigation. Useful for wizard-style flows. Exposed via zz.Stepper. --- src/components/stepper.zig | 253 +++++++++++++++++++++++++++++++++++++ src/root.zig | 8 ++ 2 files changed, 261 insertions(+) create mode 100644 src/components/stepper.zig diff --git a/src/components/stepper.zig b/src/components/stepper.zig new file mode 100644 index 0000000..360859b --- /dev/null +++ b/src/components/stepper.zig @@ -0,0 +1,253 @@ +//! Stepper (wizard) component. +//! +//! Renders a numbered sequence of steps with state indicators: completed, +//! current, and pending. Supports horizontal and vertical orientations and +//! exposes methods for navigating through the flow. + +const std = @import("std"); +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Step = struct { + title: []const u8, + description: []const u8 = "", +}; + +pub const Orientation = enum { horizontal, vertical }; + +pub const StepState = enum { pending, current, completed }; + +pub const Stepper = struct { + allocator: std.mem.Allocator, + steps: std.array_list.Managed(Step), + + current: usize, + orientation: Orientation, + + completed_marker: []const u8, + current_marker: []const u8, + pending_marker: []const u8, + /// Horizontal connector drawn between steps in horizontal layout. + connector: []const u8, + + completed_style: style_mod.Style, + current_style: style_mod.Style, + pending_style: style_mod.Style, + connector_style: style_mod.Style, + title_style: style_mod.Style, + description_style: style_mod.Style, + + pub fn init(allocator: std.mem.Allocator) Stepper { + var completed = style_mod.Style{}; + completed = completed.fg(Color.green()); + completed = completed.inline_style(true); + + var current = style_mod.Style{}; + current = current.fg(Color.cyan()); + current = current.bold(true); + current = current.inline_style(true); + + var pending = style_mod.Style{}; + pending = pending.fg(Color.gray(8)); + pending = pending.inline_style(true); + + var connector = style_mod.Style{}; + connector = connector.fg(Color.gray(6)); + connector = connector.inline_style(true); + + var title = style_mod.Style{}; + title = title.inline_style(true); + + var desc = style_mod.Style{}; + desc = desc.fg(Color.gray(10)); + desc = desc.inline_style(true); + + return .{ + .allocator = allocator, + .steps = std.array_list.Managed(Step).init(allocator), + .current = 0, + .orientation = .horizontal, + .completed_marker = "✓", + .current_marker = "●", + .pending_marker = "○", + .connector = "──", + .completed_style = completed, + .current_style = current, + .pending_style = pending, + .connector_style = connector, + .title_style = title, + .description_style = desc, + }; + } + + pub fn deinit(self: *Stepper) void { + self.steps.deinit(); + } + + pub fn addStep(self: *Stepper, step: Step) !void { + try self.steps.append(step); + } + + pub fn next(self: *Stepper) void { + if (self.current + 1 < self.steps.items.len) self.current += 1; + } + + pub fn prev(self: *Stepper) void { + if (self.current > 0) self.current -= 1; + } + + pub fn goto(self: *Stepper, idx: usize) void { + self.current = @min(idx, self.steps.items.len -| 1); + } + + pub fn reset(self: *Stepper) void { + self.current = 0; + } + + pub fn isComplete(self: *const Stepper) bool { + return self.steps.items.len > 0 and self.current >= self.steps.items.len - 1; + } + + pub fn stateOf(self: *const Stepper, idx: usize) StepState { + if (idx < self.current) return .completed; + if (idx == self.current) return .current; + return .pending; + } + + pub fn handleKey(self: *Stepper, key: keys.KeyEvent) void { + switch (key.key) { + .left => self.prev(), + .right => self.next(), + .up => if (self.orientation == .vertical) self.prev(), + .down => if (self.orientation == .vertical) self.next(), + else => {}, + } + } + + pub fn view(self: *const Stepper, allocator: std.mem.Allocator) ![]const u8 { + return switch (self.orientation) { + .horizontal => self.viewHorizontal(allocator), + .vertical => self.viewVertical(allocator), + }; + } + + fn viewHorizontal(self: *const Stepper, allocator: std.mem.Allocator) ![]const u8 { + var out = std.array_list.Managed(u8).init(allocator); + const w = out.writer(); + + for (self.steps.items, 0..) |step, i| { + if (i > 0) { + const conn = try self.connector_style.render(allocator, self.connector); + defer allocator.free(conn); + try w.writeAll(conn); + } + + const state = self.stateOf(i); + const marker = switch (state) { + .completed => self.completed_marker, + .current => self.current_marker, + .pending => self.pending_marker, + }; + const marker_style = switch (state) { + .completed => self.completed_style, + .current => self.current_style, + .pending => self.pending_style, + }; + + const styled_marker = try marker_style.render(allocator, marker); + defer allocator.free(styled_marker); + try w.writeAll(styled_marker); + try w.writeByte(' '); + + const title_style = if (state == .current) self.current_style else self.title_style; + const styled_title = try title_style.render(allocator, step.title); + defer allocator.free(styled_title); + try w.writeAll(styled_title); + } + + return out.toOwnedSlice(); + } + + fn viewVertical(self: *const Stepper, allocator: std.mem.Allocator) ![]const u8 { + var out = std.array_list.Managed(u8).init(allocator); + const w = out.writer(); + + for (self.steps.items, 0..) |step, i| { + if (i > 0) try w.writeByte('\n'); + + const state = self.stateOf(i); + const marker = switch (state) { + .completed => self.completed_marker, + .current => self.current_marker, + .pending => self.pending_marker, + }; + const marker_style = switch (state) { + .completed => self.completed_style, + .current => self.current_style, + .pending => self.pending_style, + }; + + const styled_marker = try marker_style.render(allocator, marker); + defer allocator.free(styled_marker); + try w.writeAll(styled_marker); + try w.writeByte(' '); + + const title_style = if (state == .current) self.current_style else self.title_style; + const styled_title = try title_style.render(allocator, step.title); + defer allocator.free(styled_title); + try w.writeAll(styled_title); + + if (step.description.len > 0) { + try w.writeAll("\n "); + const styled_desc = try self.description_style.render(allocator, step.description); + defer allocator.free(styled_desc); + try w.writeAll(styled_desc); + } + } + + return out.toOwnedSlice(); + } +}; + +test "stepper step state transitions" { + const allocator = std.testing.allocator; + var s = Stepper.init(allocator); + defer s.deinit(); + + try s.addStep(.{ .title = "first" }); + try s.addStep(.{ .title = "second" }); + try s.addStep(.{ .title = "third" }); + + try std.testing.expectEqual(StepState.current, s.stateOf(0)); + try std.testing.expectEqual(StepState.pending, s.stateOf(1)); + + s.next(); + try std.testing.expectEqual(StepState.completed, s.stateOf(0)); + try std.testing.expectEqual(StepState.current, s.stateOf(1)); + + s.next(); + s.next(); // clamped + try std.testing.expect(s.isComplete()); +} + +test "stepper prev does not go negative" { + const allocator = std.testing.allocator; + var s = Stepper.init(allocator); + defer s.deinit(); + try s.addStep(.{ .title = "a" }); + s.prev(); + try std.testing.expectEqual(@as(usize, 0), s.current); +} + +test "stepper horizontal render contains each title" { + const allocator = std.testing.allocator; + var s = Stepper.init(allocator); + defer s.deinit(); + try s.addStep(.{ .title = "setup" }); + try s.addStep(.{ .title = "review" }); + const out = try s.view(allocator); + defer allocator.free(out); + try std.testing.expect(std.mem.indexOf(u8, out, "setup") != null); + try std.testing.expect(std.mem.indexOf(u8, out, "review") != null); +} diff --git a/src/root.zig b/src/root.zig index 241d591..73eb953 100644 --- a/src/root.zig +++ b/src/root.zig @@ -193,6 +193,11 @@ pub const components = struct { pub const breadcrumb = @import("components/breadcrumb.zig"); pub const Breadcrumb = breadcrumb.Breadcrumb; pub const Crumb = breadcrumb.Crumb; + pub const stepper = @import("components/stepper.zig"); + pub const Stepper = stepper.Stepper; + pub const Step = stepper.Step; + pub const StepState = stepper.StepState; + pub const StepperOrientation = stepper.Orientation; }; // Re-export commonly used components at top level @@ -234,6 +239,9 @@ pub const StatusBar = components.StatusBar; pub const StatusSegment = components.StatusSegment; pub const Breadcrumb = components.Breadcrumb; pub const Crumb = components.Crumb; +pub const Stepper = components.Stepper; +pub const Step = components.Step; +pub const StepState = components.StepState; // Focus management pub const FocusGroup = components.focus.FocusGroup; From d1a54561264332fe25711fe8241862584f0a0f4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:02:54 +0200 Subject: [PATCH 5/8] feat: add split pane component Two-pane container with orientation, draggable divider (via growA/growB or arrow keys), min-size clamping, and string composition helper. Caller renders each pane using the sizes returned by dims(). Exposed via zz.SplitPane. --- src/components/split_pane.zig | 246 ++++++++++++++++++++++++++++++++++ src/root.zig | 5 + 2 files changed, 251 insertions(+) create mode 100644 src/components/split_pane.zig diff --git a/src/components/split_pane.zig b/src/components/split_pane.zig new file mode 100644 index 0000000..2b39218 --- /dev/null +++ b/src/components/split_pane.zig @@ -0,0 +1,246 @@ +//! Split pane component. +//! +//! A two-pane container with a user-draggable divider. Stores the split ratio +//! (0–1) and total size, and produces sizes for each pane. Rendering itself is +//! delegated to the caller: a typical flow is +//! +//! var split = SplitPane.init(.horizontal); +//! split.setSize(w, h); +//! const dims = split.dims(); +//! const left = try renderLeft(dims.a); +//! const right = try renderRight(dims.b); +//! const view = try split.compose(alloc, left, right); +//! +//! The divider is a single cell between the two panes, styled like a border. + +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 join = @import("../layout/join.zig"); +const measure = @import("../layout/measure.zig"); + +pub const Orientation = enum { + /// Panes sit side-by-side, divider is vertical. + horizontal, + /// Panes stack, divider is horizontal. + vertical, +}; + +pub const Dims = struct { + a_width: u16, + a_height: u16, + b_width: u16, + b_height: u16, +}; + +pub const SplitPane = struct { + orientation: Orientation, + width: u16, + height: u16, + /// Ratio of total size given to pane A (0.0-1.0), before the divider. + ratio: f32, + min_size: u16, + resize_step: u16, + + divider_style: style_mod.Style, + divider_char_vertical: []const u8, + divider_char_horizontal: []const u8, + + pub fn init(orientation: Orientation) SplitPane { + var ds = style_mod.Style{}; + ds = ds.fg(Color.gray(6)); + ds = ds.inline_style(true); + return .{ + .orientation = orientation, + .width = 80, + .height = 24, + .ratio = 0.5, + .min_size = 3, + .resize_step = 1, + .divider_style = ds, + .divider_char_vertical = "│", + .divider_char_horizontal = "─", + }; + } + + pub fn setSize(self: *SplitPane, w: u16, h: u16) void { + self.width = w; + self.height = h; + } + + pub fn setRatio(self: *SplitPane, r: f32) void { + self.ratio = std.math.clamp(r, 0.0, 1.0); + } + + pub fn dims(self: *const SplitPane) Dims { + return switch (self.orientation) { + .horizontal => self.horizontalDims(), + .vertical => self.verticalDims(), + }; + } + + fn horizontalDims(self: *const SplitPane) Dims { + const total = self.width; + // Reserve one column for the divider when there's room for it. + const available: u16 = if (total > 1) total - 1 else total; + const a_raw: u16 = @intFromFloat(@as(f32, @floatFromInt(available)) * self.ratio); + const min = @min(self.min_size, available / 2); + const a = std.math.clamp(a_raw, min, available -| min); + const b = available -| a; + return .{ + .a_width = a, + .a_height = self.height, + .b_width = b, + .b_height = self.height, + }; + } + + fn verticalDims(self: *const SplitPane) Dims { + const total = self.height; + const available: u16 = if (total > 1) total - 1 else total; + const a_raw: u16 = @intFromFloat(@as(f32, @floatFromInt(available)) * self.ratio); + const min = @min(self.min_size, available / 2); + const a = std.math.clamp(a_raw, min, available -| min); + const b = available -| a; + return .{ + .a_width = self.width, + .a_height = a, + .b_width = self.width, + .b_height = b, + }; + } + + /// Grow pane A by `resize_step` cells. + pub fn growA(self: *SplitPane) void { + self.adjust(@as(i32, self.resize_step)); + } + + /// Grow pane B by `resize_step` cells. + pub fn growB(self: *SplitPane) void { + self.adjust(-@as(i32, self.resize_step)); + } + + fn adjust(self: *SplitPane, delta_cells: i32) void { + const total: u16 = switch (self.orientation) { + .horizontal => if (self.width > 1) self.width - 1 else self.width, + .vertical => if (self.height > 1) self.height - 1 else self.height, + }; + if (total == 0) return; + + const current_cells: i32 = @intFromFloat(@as(f32, @floatFromInt(total)) * self.ratio); + var next = current_cells + delta_cells; + const min: i32 = @intCast(@min(self.min_size, total / 2)); + const max: i32 = @as(i32, total) - min; + if (min > max) return; + next = std.math.clamp(next, min, max); + self.ratio = @as(f32, @floatFromInt(next)) / @as(f32, @floatFromInt(total)); + } + + /// Handle arrow-key driven resize. Returns true when the event was + /// consumed. + pub fn handleResize(self: *SplitPane, key: keys.KeyEvent) bool { + switch (self.orientation) { + .horizontal => switch (key.key) { + .left => { + self.growB(); + return true; + }, + .right => { + self.growA(); + return true; + }, + else => return false, + }, + .vertical => switch (key.key) { + .up => { + self.growB(); + return true; + }, + .down => { + self.growA(); + return true; + }, + else => return false, + }, + } + } + + /// Compose two pre-rendered pane strings with a divider between them. + pub fn compose(self: *const SplitPane, allocator: std.mem.Allocator, pane_a: []const u8, pane_b: []const u8) ![]const u8 { + return switch (self.orientation) { + .horizontal => self.composeHorizontal(allocator, pane_a, pane_b), + .vertical => self.composeVertical(allocator, pane_a, pane_b), + }; + } + + fn composeHorizontal(self: *const SplitPane, allocator: std.mem.Allocator, a: []const u8, b: []const u8) ![]const u8 { + const rows: usize = @max(self.height, 1); + var divider_lines = std.array_list.Managed(u8).init(allocator); + defer divider_lines.deinit(); + for (0..rows) |i| { + if (i > 0) try divider_lines.append('\n'); + const ch = try self.divider_style.render(allocator, self.divider_char_vertical); + defer allocator.free(ch); + try divider_lines.appendSlice(ch); + } + return join.horizontal(allocator, .top, &.{ a, divider_lines.items, b }); + } + + fn composeVertical(self: *const SplitPane, allocator: std.mem.Allocator, a: []const u8, b: []const u8) ![]const u8 { + const cols: usize = @max(self.width, 1); + var divider = std.array_list.Managed(u8).init(allocator); + defer divider.deinit(); + for (0..cols) |_| try divider.appendSlice(self.divider_char_horizontal); + const styled = try self.divider_style.render(allocator, divider.items); + defer allocator.free(styled); + return join.vertical(allocator, .left, &.{ a, styled, b }); + } +}; + +test "horizontal split divides width minus divider" { + var s = SplitPane.init(.horizontal); + s.setSize(21, 10); + s.setRatio(0.5); + const d = s.dims(); + try std.testing.expectEqual(@as(u16, 10), d.a_width); + try std.testing.expectEqual(@as(u16, 10), d.b_width); + try std.testing.expectEqual(@as(u16, 10), d.a_height); +} + +test "ratio clamped to min size" { + var s = SplitPane.init(.horizontal); + s.setSize(20, 10); + s.min_size = 5; + s.setRatio(0.0); + const d = s.dims(); + try std.testing.expect(d.a_width >= 5); +} + +test "growA increases ratio" { + var s = SplitPane.init(.horizontal); + s.setSize(40, 10); + s.setRatio(0.5); + const before = s.dims().a_width; + s.growA(); + const after = s.dims().a_width; + try std.testing.expect(after > before); +} + +test "vertical split divides height minus divider" { + var s = SplitPane.init(.vertical); + s.setSize(40, 11); + s.setRatio(0.5); + const d = s.dims(); + try std.testing.expectEqual(@as(u16, 5), d.a_height); + try std.testing.expectEqual(@as(u16, 5), d.b_height); +} + +test "compose keeps output non-empty" { + const allocator = std.testing.allocator; + var s = SplitPane.init(.horizontal); + s.setSize(10, 2); + const out = try s.compose(allocator, "ab\ncd", "xy\nzw"); + defer allocator.free(out); + try std.testing.expect(out.len > 0); +} diff --git a/src/root.zig b/src/root.zig index 73eb953..104dc7c 100644 --- a/src/root.zig +++ b/src/root.zig @@ -198,6 +198,10 @@ pub const components = struct { pub const Step = stepper.Step; pub const StepState = stepper.StepState; pub const StepperOrientation = stepper.Orientation; + pub const split_pane = @import("components/split_pane.zig"); + pub const SplitPane = split_pane.SplitPane; + pub const SplitPaneOrientation = split_pane.Orientation; + pub const SplitPaneDims = split_pane.Dims; }; // Re-export commonly used components at top level @@ -242,6 +246,7 @@ pub const Crumb = components.Crumb; pub const Stepper = components.Stepper; pub const Step = components.Step; pub const StepState = components.StepState; +pub const SplitPane = components.SplitPane; // Focus management pub const FocusGroup = components.focus.FocusGroup; From a7cf7362e287ca85a4f80ebc5843d61c89c22478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:05:18 +0200 Subject: [PATCH 6/8] feat: add command palette component Fuzzy-filtered command launcher with prompt, placeholder, description and shortcut columns, arrow-key navigation, and escape/enter semantics returned via KeyResult. Pairs with the new fuzzy matcher utility. --- src/components/command_palette.zig | 349 +++++++++++++++++++++++++++++ src/root.zig | 6 + 2 files changed, 355 insertions(+) create mode 100644 src/components/command_palette.zig diff --git a/src/components/command_palette.zig b/src/components/command_palette.zig new file mode 100644 index 0000000..f82ccde --- /dev/null +++ b/src/components/command_palette.zig @@ -0,0 +1,349 @@ +//! Command palette component. +//! +//! Fuzzy-filtered command launcher, modeled on VS Code's Ctrl-P. Holds a list +//! of commands (label + description + id) and a filter prompt. Renders a +//! bordered pop-up suitable for placing on top of other content using +//! layout.place or layout.layer. Consumers drive it with handleKey and read +//! back selected(). + +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 measure = @import("../layout/measure.zig"); +const fuzzy = @import("../core/fuzzy.zig"); + +pub const Command = struct { + id: []const u8, + label: []const u8, + description: []const u8 = "", + /// Optional shortcut hint shown on the right ("⌘K", "Ctrl+P", etc). + shortcut: []const u8 = "", +}; + +/// Result returned by handleKey so the caller knows whether to dismiss or run. +pub const KeyResult = enum { + ignored, + consumed, + accepted, + cancelled, +}; + +pub const CommandPalette = struct { + allocator: std.mem.Allocator, + + commands: std.array_list.Managed(Command), + /// Indices into commands, filtered and sorted by fuzzy score. + filtered: std.array_list.Managed(usize), + /// Filter text entered by the user. + query: std.array_list.Managed(u8), + + cursor: usize, + max_visible: u16, + width: u16, + prompt: []const u8, + /// Placeholder shown in the input when the query is empty. + placeholder: []const u8, + + border_chars: border_mod.BorderChars, + prompt_style: style_mod.Style, + input_style: style_mod.Style, + placeholder_style: style_mod.Style, + label_style: style_mod.Style, + description_style: style_mod.Style, + shortcut_style: style_mod.Style, + selected_style: style_mod.Style, + selected_label_style: style_mod.Style, + empty_style: style_mod.Style, + + pub fn init(allocator: std.mem.Allocator) !CommandPalette { + var prompt_s = style_mod.Style{}; + prompt_s = prompt_s.fg(Color.cyan()); + prompt_s = prompt_s.bold(true); + prompt_s = prompt_s.inline_style(true); + + var input_s = style_mod.Style{}; + input_s = input_s.inline_style(true); + + var placeholder_s = style_mod.Style{}; + placeholder_s = placeholder_s.fg(Color.gray(8)); + placeholder_s = placeholder_s.inline_style(true); + + var label_s = style_mod.Style{}; + label_s = label_s.inline_style(true); + + var desc_s = style_mod.Style{}; + desc_s = desc_s.fg(Color.gray(10)); + desc_s = desc_s.inline_style(true); + + var shortcut_s = style_mod.Style{}; + shortcut_s = shortcut_s.fg(Color.gray(8)); + shortcut_s = shortcut_s.inline_style(true); + + var selected_s = style_mod.Style{}; + selected_s = selected_s.bg(Color.gray(4)); + selected_s = selected_s.inline_style(true); + + var selected_label_s = style_mod.Style{}; + selected_label_s = selected_label_s.bg(Color.gray(4)); + selected_label_s = selected_label_s.fg(Color.cyan()); + selected_label_s = selected_label_s.bold(true); + selected_label_s = selected_label_s.inline_style(true); + + var empty_s = style_mod.Style{}; + empty_s = empty_s.fg(Color.gray(8)); + empty_s = empty_s.italic(true); + empty_s = empty_s.inline_style(true); + + var palette = CommandPalette{ + .allocator = allocator, + .commands = std.array_list.Managed(Command).init(allocator), + .filtered = std.array_list.Managed(usize).init(allocator), + .query = std.array_list.Managed(u8).init(allocator), + .cursor = 0, + .max_visible = 8, + .width = 60, + .prompt = "> ", + .placeholder = "Type a command…", + .border_chars = border_mod.Border.rounded, + .prompt_style = prompt_s, + .input_style = input_s, + .placeholder_style = placeholder_s, + .label_style = label_s, + .description_style = desc_s, + .shortcut_style = shortcut_s, + .selected_style = selected_s, + .selected_label_style = selected_label_s, + .empty_style = empty_s, + }; + _ = &palette; + return palette; + } + + pub fn deinit(self: *CommandPalette) void { + self.commands.deinit(); + self.filtered.deinit(); + self.query.deinit(); + } + + pub fn addCommand(self: *CommandPalette, cmd: Command) !void { + try self.commands.append(cmd); + try self.rebuildFilter(); + } + + pub fn setCommands(self: *CommandPalette, cmds: []const Command) !void { + self.commands.clearRetainingCapacity(); + try self.commands.appendSlice(cmds); + try self.rebuildFilter(); + } + + pub fn clear(self: *CommandPalette) !void { + self.query.clearRetainingCapacity(); + self.cursor = 0; + try self.rebuildFilter(); + } + + /// Returns the currently highlighted command, if any. + pub fn selected(self: *const CommandPalette) ?Command { + if (self.cursor >= self.filtered.items.len) return null; + return self.commands.items[self.filtered.items[self.cursor]]; + } + + pub fn handleKey(self: *CommandPalette, key: keys.KeyEvent) !KeyResult { + switch (key.key) { + .escape => return .cancelled, + .enter => { + if (self.selected() == null) return .consumed; + return .accepted; + }, + .up => { + if (self.cursor > 0) self.cursor -= 1; + return .consumed; + }, + .down => { + if (self.cursor + 1 < self.filtered.items.len) self.cursor += 1; + return .consumed; + }, + .backspace => { + if (self.query.items.len > 0) { + _ = self.query.pop(); + try self.rebuildFilter(); + } + return .consumed; + }, + .char => |c| { + if (c < 0x20) return .ignored; + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(c, &buf) catch return .ignored; + try self.query.appendSlice(buf[0..n]); + try self.rebuildFilter(); + return .consumed; + }, + else => return .ignored, + } + } + + fn rebuildFilter(self: *CommandPalette) !void { + self.filtered.clearRetainingCapacity(); + if (self.query.items.len == 0) { + for (0..self.commands.items.len) |i| try self.filtered.append(i); + } else { + var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); + defer scored.deinit(); + + for (self.commands.items, 0..) |cmd, i| { + const s = fuzzy.scoreIgnoreCase(cmd.label, self.query.items); + if (s > 0) try scored.append(.{ .index = i, .score = s }); + } + + std.mem.sort(fuzzy.Ranked, scored.items, {}, struct { + fn lt(_: void, a: fuzzy.Ranked, b: fuzzy.Ranked) bool { + return a.score > b.score; + } + }.lt); + + for (scored.items) |r| try self.filtered.append(r.index); + } + + if (self.cursor >= self.filtered.items.len) { + self.cursor = self.filtered.items.len -| 1; + } + } + + pub fn view(self: *const CommandPalette, allocator: std.mem.Allocator) ![]const u8 { + var inner = std.array_list.Managed(u8).init(allocator); + defer inner.deinit(); + const w = inner.writer(); + + // Input row. + const prompt_styled = try self.prompt_style.render(allocator, self.prompt); + defer allocator.free(prompt_styled); + try w.writeAll(prompt_styled); + + if (self.query.items.len == 0) { + const ph = try self.placeholder_style.render(allocator, self.placeholder); + defer allocator.free(ph); + try w.writeAll(ph); + } else { + const q = try self.input_style.render(allocator, self.query.items); + defer allocator.free(q); + try w.writeAll(q); + } + try w.writeByte('\n'); + + // Results. + if (self.filtered.items.len == 0) { + const empty = try self.empty_style.render(allocator, "No commands match"); + defer allocator.free(empty); + try w.writeAll(empty); + } else { + const visible = @min(@as(usize, self.max_visible), self.filtered.items.len); + const start = if (self.cursor >= visible) self.cursor - visible + 1 else 0; + const end = @min(start + visible, self.filtered.items.len); + + for (start..end) |i| { + if (i > start) try w.writeByte('\n'); + const is_sel = i == self.cursor; + const cmd = self.commands.items[self.filtered.items[i]]; + try self.renderRow(allocator, w.any(), cmd, is_sel); + } + } + + const rendered = try inner.toOwnedSlice(); + defer allocator.free(rendered); + + var box_style = style_mod.Style{}; + box_style = box_style.borderAll(self.border_chars); + box_style = box_style.width(self.width); + return try box_style.render(allocator, rendered); + } + + fn renderRow( + self: *const CommandPalette, + allocator: std.mem.Allocator, + w: std.io.AnyWriter, + cmd: Command, + is_sel: bool, + ) !void { + const prefix = if (is_sel) "▸ " else " "; + if (is_sel) { + const styled_prefix = try self.selected_label_style.render(allocator, prefix); + defer allocator.free(styled_prefix); + try w.writeAll(styled_prefix); + + const styled_label = try self.selected_label_style.render(allocator, cmd.label); + defer allocator.free(styled_label); + try w.writeAll(styled_label); + } else { + try w.writeAll(prefix); + const styled_label = try self.label_style.render(allocator, cmd.label); + defer allocator.free(styled_label); + try w.writeAll(styled_label); + } + + if (cmd.description.len > 0) { + try w.writeByte(' '); + const desc = try std.fmt.allocPrint(allocator, "— {s}", .{cmd.description}); + defer allocator.free(desc); + const desc_style = if (is_sel) self.selected_style else self.description_style; + const styled = try desc_style.render(allocator, desc); + defer allocator.free(styled); + try w.writeAll(styled); + } + + if (cmd.shortcut.len > 0) { + try w.writeAll(" "); + const shortcut_style = if (is_sel) self.selected_style else self.shortcut_style; + const styled = try shortcut_style.render(allocator, cmd.shortcut); + defer allocator.free(styled); + try w.writeAll(styled); + } + } +}; + +test "command palette filters by fuzzy score" { + const allocator = std.testing.allocator; + var p = try CommandPalette.init(allocator); + defer p.deinit(); + + try p.setCommands(&.{ + .{ .id = "open", .label = "Open File" }, + .{ .id = "save", .label = "Save File" }, + .{ .id = "close", .label = "Close Window" }, + }); + + try p.query.appendSlice("of"); + try p.rebuildFilter(); + + try std.testing.expect(p.filtered.items.len >= 1); + const sel = p.selected().?; + try std.testing.expectEqualStrings("open", sel.id); +} + +test "enter accepts, escape cancels" { + const allocator = std.testing.allocator; + var p = try CommandPalette.init(allocator); + defer p.deinit(); + try p.setCommands(&.{.{ .id = "a", .label = "Alpha" }}); + + const accepted = try p.handleKey(.{ .key = .enter, .modifiers = .{} }); + try std.testing.expectEqual(KeyResult.accepted, accepted); + + const cancelled = try p.handleKey(.{ .key = .escape, .modifiers = .{} }); + try std.testing.expectEqual(KeyResult.cancelled, cancelled); +} + +test "typing characters updates the filter" { + const allocator = std.testing.allocator; + var p = try CommandPalette.init(allocator); + defer p.deinit(); + try p.setCommands(&.{ + .{ .id = "alpha", .label = "Alpha" }, + .{ .id = "beta", .label = "Beta" }, + }); + + _ = try p.handleKey(.{ .key = .{ .char = 'b' }, .modifiers = .{} }); + try std.testing.expectEqual(@as(usize, 1), p.filtered.items.len); + try std.testing.expectEqualStrings("beta", p.selected().?.id); +} diff --git a/src/root.zig b/src/root.zig index 104dc7c..eb6ce09 100644 --- a/src/root.zig +++ b/src/root.zig @@ -202,6 +202,10 @@ pub const components = struct { pub const SplitPane = split_pane.SplitPane; pub const SplitPaneOrientation = split_pane.Orientation; pub const SplitPaneDims = split_pane.Dims; + pub const command_palette = @import("components/command_palette.zig"); + pub const CommandPalette = command_palette.CommandPalette; + pub const Command = command_palette.Command; + pub const CommandPaletteKeyResult = command_palette.KeyResult; }; // Re-export commonly used components at top level @@ -247,6 +251,8 @@ pub const Stepper = components.Stepper; pub const Step = components.Step; pub const StepState = components.StepState; pub const SplitPane = components.SplitPane; +pub const CommandPalette = components.CommandPalette; +pub const Command = components.Command; // Focus management pub const FocusGroup = components.focus.FocusGroup; From ce736a65ba51446ddbf9cc7a53e8e8be530d49c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:06:37 +0200 Subject: [PATCH 7/8] feat: add snapshot testing harness expectSnapshot compares rendered output against a golden file and writes the snapshot when missing. ANSI-aware: by default strips escape codes and trailing whitespace for stable goldens. Set ZIGZAG_UPDATE_SNAPSHOTS=1 to regenerate existing snapshots. Exposed via zz.testing. --- src/root.zig | 7 ++ src/testing/snapshot.zig | 232 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 239 insertions(+) create mode 100644 src/testing/snapshot.zig diff --git a/src/root.zig b/src/root.zig index eb6ce09..f932ea6 100644 --- a/src/root.zig +++ b/src/root.zig @@ -127,6 +127,13 @@ pub const AccessibleLabel = accessibility.AccessibleLabel; // Unicode pub const unicode = @import("unicode.zig"); +// Testing utilities +pub const testing = struct { + pub const snapshot = @import("testing/snapshot.zig"); + pub const expectSnapshot = snapshot.expectSnapshot; + pub const expectSnapshotOpts = snapshot.expectSnapshotOpts; +}; + // Components pub const components = struct { pub const TextInput = @import("components/text_input.zig").TextInput; diff --git a/src/testing/snapshot.zig b/src/testing/snapshot.zig new file mode 100644 index 0000000..b230bdf --- /dev/null +++ b/src/testing/snapshot.zig @@ -0,0 +1,232 @@ +//! Snapshot testing utilities. +//! +//! Lets tests assert that a rendered view matches a golden file on disk. When +//! a snapshot does not exist, it is written on the first run. Set the +//! environment variable `ZIGZAG_UPDATE_SNAPSHOTS=1` to overwrite existing +//! snapshots, e.g. after an intentional change: +//! +//! ZIGZAG_UPDATE_SNAPSHOTS=1 zig build test +//! +//! Typical usage inside a test: +//! +//! try zz.testing.expectSnapshot( +//! std.testing.allocator, +//! "tests/snapshots/welcome.snap", +//! rendered_output, +//! ); + +const std = @import("std"); +const ansi = @import("../terminal/ansi.zig"); + +pub const SnapshotError = error{ + SnapshotMismatch, +} || std.fs.File.OpenError || std.fs.File.WriteError || std.mem.Allocator.Error; + +pub const Options = struct { + /// If true, the rendered output has ANSI CSI escape sequences stripped + /// before comparison and before writing new snapshots. This produces + /// stable golden files for components whose styling is decorative. + strip_ansi: bool = true, + /// Trailing spaces on each line are stripped before comparison. Helps + /// when padding fluctuates between renders. + trim_trailing_whitespace: bool = true, +}; + +/// Assert that `actual` matches the snapshot stored at `path`. +/// +/// If the file does not exist, it is created with the current output and the +/// test passes. If the environment variable `ZIGZAG_UPDATE_SNAPSHOTS=1` is +/// set, the file is overwritten with the current output and the test passes. +/// Otherwise the stored and actual content must match byte-for-byte after +/// applying `Options`. +pub fn expectSnapshot( + allocator: std.mem.Allocator, + path: []const u8, + actual: []const u8, +) SnapshotError!void { + return expectSnapshotOpts(allocator, path, actual, .{}); +} + +pub fn expectSnapshotOpts( + allocator: std.mem.Allocator, + path: []const u8, + actual: []const u8, + opts: Options, +) SnapshotError!void { + const normalized = try normalize(allocator, actual, opts); + defer allocator.free(normalized); + + // Ensure parent directory exists so callers don't have to mkdir. + if (std.fs.path.dirname(path)) |dir| { + std.fs.cwd().makePath(dir) catch {}; + } + + const update_env = std.posix.getenv("ZIGZAG_UPDATE_SNAPSHOTS"); + const update = update_env != null and update_env.?.len > 0 and !std.mem.eql(u8, update_env.?, "0"); + + if (update) { + try writeAll(path, normalized); + return; + } + + const existing = std.fs.cwd().readFileAlloc(allocator, path, 16 * 1024 * 1024) catch |err| switch (err) { + error.FileNotFound => { + try writeAll(path, normalized); + return; + }, + else => return err, + }; + defer allocator.free(existing); + + const existing_norm = try normalize(allocator, existing, opts); + defer allocator.free(existing_norm); + + if (!std.mem.eql(u8, existing_norm, normalized)) { + // Print a unified-ish diff to stderr so the mismatch is actionable. + printDiff(path, existing_norm, normalized); + return SnapshotError.SnapshotMismatch; + } +} + +fn writeAll(path: []const u8, contents: []const u8) !void { + const file = try std.fs.cwd().createFile(path, .{ .truncate = true }); + defer file.close(); + var buf: [4096]u8 = undefined; + var w = file.writer(&buf); + try w.interface.writeAll(contents); + try w.interface.flush(); +} + +fn normalize(allocator: std.mem.Allocator, input: []const u8, opts: Options) ![]u8 { + var work: []u8 = try allocator.dupe(u8, input); + errdefer allocator.free(work); + + if (opts.strip_ansi) { + const stripped = try stripAnsi(allocator, work); + allocator.free(work); + work = stripped; + } + + if (opts.trim_trailing_whitespace) { + const trimmed = try trimTrailingWhitespace(allocator, work); + allocator.free(work); + work = trimmed; + } + + return work; +} + +fn stripAnsi(allocator: std.mem.Allocator, input: []const u8) ![]u8 { + var out = try std.array_list.Managed(u8).initCapacity(allocator, input.len); + errdefer out.deinit(); + + var i: usize = 0; + while (i < input.len) { + const c = input[i]; + if (c != 0x1b) { + try out.append(c); + i += 1; + continue; + } + + // ESC encountered. Consume the sequence. + i += 1; + if (i >= input.len) break; + + const next = input[i]; + if (next == '[') { + // CSI: ESC [ ... final + i += 1; + while (i < input.len) { + const b = input[i]; + i += 1; + if ((b >= '@' and b <= '~')) break; + } + } else if (next == ']') { + // OSC: ESC ] ... ST or BEL + i += 1; + while (i < input.len) { + const b = input[i]; + if (b == 0x07) { + i += 1; + break; + } + if (b == 0x1b and i + 1 < input.len and input[i + 1] == '\\') { + i += 2; + break; + } + i += 1; + } + } else { + // Two-byte ESC sequence (ESC Fe / Fp / Fs). + i += 1; + } + } + + return out.toOwnedSlice(); +} + +fn trimTrailingWhitespace(allocator: std.mem.Allocator, input: []const u8) ![]u8 { + var out = try std.array_list.Managed(u8).initCapacity(allocator, input.len); + errdefer out.deinit(); + + var lines = std.mem.splitScalar(u8, input, '\n'); + var first = true; + while (lines.next()) |line| { + if (!first) try out.append('\n'); + first = false; + var end = line.len; + while (end > 0 and (line[end - 1] == ' ' or line[end - 1] == '\t' or line[end - 1] == '\r')) { + end -= 1; + } + try out.appendSlice(line[0..end]); + } + return out.toOwnedSlice(); +} + +fn printDiff(path: []const u8, expected: []const u8, actual: []const u8) void { + // Avoid allocating in diff path — just dump both snippets. + const stderr = std.debug; + stderr.print( + "\nSnapshot mismatch: {s}\n" ++ + " run with ZIGZAG_UPDATE_SNAPSHOTS=1 to update.\n" ++ + "--- expected ---\n{s}\n" ++ + "--- actual ---\n{s}\n" ++ + "----------------\n", + .{ path, expected, actual }, + ); +} + +test "stripAnsi removes CSI and OSC" { + const allocator = std.testing.allocator; + const input = "\x1b[31mred\x1b[0m \x1b]0;title\x07plain"; + const stripped = try stripAnsi(allocator, input); + defer allocator.free(stripped); + try std.testing.expectEqualStrings("red plain", stripped); +} + +test "trimTrailingWhitespace" { + const allocator = std.testing.allocator; + const out = try trimTrailingWhitespace(allocator, "hello \nworld \t\n"); + defer allocator.free(out); + try std.testing.expectEqualStrings("hello\nworld\n", out); +} + +test "expectSnapshot creates file when missing" { + const allocator = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + + // Change cwd to tmp so relative paths resolve there. + var orig = try std.fs.cwd().openDir(".", .{}); + defer orig.close(); + try tmp.dir.setAsCwd(); + defer orig.setAsCwd() catch {}; + + try expectSnapshot(allocator, "snap.txt", "hello world"); + try expectSnapshot(allocator, "snap.txt", "hello world"); + + // Different content should mismatch. + const err = expectSnapshot(allocator, "snap.txt", "hello there"); + try std.testing.expectError(SnapshotError.SnapshotMismatch, err); +} From d1c8783162d7d569b724ce437ace66199c6f8152 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20M=C3=A9sz=C3=A1ros=20=28Laptop=29?= Date: Mon, 20 Apr 2026 13:08:58 +0200 Subject: [PATCH 8/8] feat: add record/replay utility for TUI sessions Recorder captures timestamped key events to a line-based text format; Player parses them back for deterministic replay of demos and bug reports. Supports modifiers, character codepoints, and escaped paste strings. Exposed via zz.testing.Recorder and zz.testing.Player. --- src/root.zig | 4 + src/testing/record_replay.zig | 371 ++++++++++++++++++++++++++++++++++ 2 files changed, 375 insertions(+) create mode 100644 src/testing/record_replay.zig diff --git a/src/root.zig b/src/root.zig index f932ea6..72e3f28 100644 --- a/src/root.zig +++ b/src/root.zig @@ -132,6 +132,10 @@ pub const testing = struct { pub const snapshot = @import("testing/snapshot.zig"); pub const expectSnapshot = snapshot.expectSnapshot; pub const expectSnapshotOpts = snapshot.expectSnapshotOpts; + pub const record_replay = @import("testing/record_replay.zig"); + pub const Recorder = record_replay.Recorder; + pub const Player = record_replay.Player; + pub const RecordedEvent = record_replay.Event; }; // Components diff --git a/src/testing/record_replay.zig b/src/testing/record_replay.zig new file mode 100644 index 0000000..43c707f --- /dev/null +++ b/src/testing/record_replay.zig @@ -0,0 +1,371 @@ +//! Record/replay utility for TUI sessions. +//! +//! Captures a sequence of timestamped key events to disk so demos and bug +//! reports become reproducible. The file format is a small line-oriented +//! text format: +//! +//! ms=0 key=char ch=104 +//! ms=40 key=char ch=105 +//! ms=120 key=enter +//! ms=200 mod=ctrl+key=char ch=99 +//! +//! Each line is: `ms= [mod=+]key= [ch=] [str=]`. +//! +//! `Recorder` appends events to an in-memory buffer which can be written to a +//! file at the end of a session. `Player` reads a file and exposes an +//! iterator of `Event` values, optionally gated on wall-clock time so the +//! replay feels natural. + +const std = @import("std"); +const keys = @import("../input/keys.zig"); + +pub const Event = struct { + elapsed_ms: u64, + event: keys.KeyEvent, +}; + +pub const Recorder = struct { + allocator: std.mem.Allocator, + events: std.array_list.Managed(Event), + start_ns: i128, + + pub fn init(allocator: std.mem.Allocator) Recorder { + return .{ + .allocator = allocator, + .events = std.array_list.Managed(Event).init(allocator), + .start_ns = std.time.nanoTimestamp(), + }; + } + + pub fn deinit(self: *Recorder) void { + self.events.deinit(); + } + + pub fn reset(self: *Recorder) void { + self.events.clearRetainingCapacity(); + self.start_ns = std.time.nanoTimestamp(); + } + + /// Record an event that occurred at the current wall-clock time. + pub fn record(self: *Recorder, event: keys.KeyEvent) !void { + const now = std.time.nanoTimestamp(); + const elapsed_ns = now - self.start_ns; + const ms: u64 = if (elapsed_ns < 0) 0 else @intCast(@divTrunc(elapsed_ns, std.time.ns_per_ms)); + try self.events.append(.{ .elapsed_ms = ms, .event = event }); + } + + /// Record an event at an explicit elapsed millisecond offset from start. + pub fn recordAt(self: *Recorder, elapsed_ms: u64, event: keys.KeyEvent) !void { + try self.events.append(.{ .elapsed_ms = elapsed_ms, .event = event }); + } + + /// Serialize the recording to a writer. + pub fn write(self: *const Recorder, writer: std.io.AnyWriter) !void { + for (self.events.items) |e| { + try writeEvent(writer, e); + } + } + + /// Serialize the recording to a file at `path`. + pub fn writeToFile(self: *const Recorder, path: []const u8) !void { + const file = try std.fs.cwd().createFile(path, .{ .truncate = true }); + defer file.close(); + var buf: [4096]u8 = undefined; + var fw = file.writer(&buf); + try self.write(fw.interface.any()); + try fw.interface.flush(); + } +}; + +pub const Player = struct { + allocator: std.mem.Allocator, + events: []Event, + cursor: usize, + + pub fn load(allocator: std.mem.Allocator, path: []const u8) !Player { + const contents = try std.fs.cwd().readFileAlloc(allocator, path, 16 * 1024 * 1024); + defer allocator.free(contents); + return parse(allocator, contents); + } + + pub fn parse(allocator: std.mem.Allocator, contents: []const u8) !Player { + var list = std.array_list.Managed(Event).init(allocator); + errdefer { + for (list.items) |e| freeEvent(allocator, e.event); + list.deinit(); + } + + var lines = std.mem.splitScalar(u8, contents, '\n'); + while (lines.next()) |line| { + const trimmed = std.mem.trim(u8, line, " \r\t"); + if (trimmed.len == 0 or trimmed[0] == '#') continue; + const event = try parseLine(allocator, trimmed); + try list.append(event); + } + + return .{ + .allocator = allocator, + .events = try list.toOwnedSlice(), + .cursor = 0, + }; + } + + pub fn deinit(self: *Player) void { + for (self.events) |e| freeEvent(self.allocator, e.event); + self.allocator.free(self.events); + } + + /// Return the next event, or null if exhausted. + pub fn next(self: *Player) ?Event { + if (self.cursor >= self.events.len) return null; + const e = self.events[self.cursor]; + self.cursor += 1; + return e; + } + + pub fn reset(self: *Player) void { + self.cursor = 0; + } + + pub fn len(self: *const Player) usize { + return self.events.len; + } +}; + +fn freeEvent(allocator: std.mem.Allocator, event: keys.KeyEvent) void { + switch (event.key) { + .paste => |s| allocator.free(s), + .unknown => |s| allocator.free(s), + else => {}, + } +} + +fn writeEvent(writer: std.io.AnyWriter, e: Event) !void { + try writer.print("ms={d}", .{e.elapsed_ms}); + + const m = e.event.modifiers; + if (m.any()) { + try writer.writeAll(" mod="); + var first = true; + if (m.ctrl) { + try writer.writeAll("ctrl"); + first = false; + } + if (m.alt) { + if (!first) try writer.writeByte('+'); + try writer.writeAll("alt"); + first = false; + } + if (m.shift) { + if (!first) try writer.writeByte('+'); + try writer.writeAll("shift"); + first = false; + } + if (m.super) { + if (!first) try writer.writeByte('+'); + try writer.writeAll("super"); + } + } + + try writer.print(" key={s}", .{e.event.key.name()}); + + switch (e.event.key) { + .char => |c| try writer.print(" ch={d}", .{c}), + .paste => |s| { + try writer.writeAll(" str="); + try writeEscaped(writer, s); + }, + .unknown => |s| { + try writer.writeAll(" str="); + try writeEscaped(writer, s); + }, + else => {}, + } + try writer.writeByte('\n'); +} + +fn writeEscaped(writer: std.io.AnyWriter, s: []const u8) !void { + for (s) |c| { + switch (c) { + '\n' => try writer.writeAll("\\n"), + '\r' => try writer.writeAll("\\r"), + '\t' => try writer.writeAll("\\t"), + '\\' => try writer.writeAll("\\\\"), + ' ' => try writer.writeAll("\\s"), + else => if (c < 0x20) { + try writer.print("\\x{x:0>2}", .{c}); + } else { + try writer.writeByte(c); + }, + } + } +} + +fn unescape(allocator: std.mem.Allocator, s: []const u8) ![]u8 { + var out = try std.array_list.Managed(u8).initCapacity(allocator, s.len); + errdefer out.deinit(); + + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (s[i] != '\\') { + try out.append(s[i]); + continue; + } + if (i + 1 >= s.len) return error.InvalidEscape; + i += 1; + switch (s[i]) { + 'n' => try out.append('\n'), + 'r' => try out.append('\r'), + 't' => try out.append('\t'), + '\\' => try out.append('\\'), + 's' => try out.append(' '), + 'x' => { + if (i + 2 >= s.len) return error.InvalidEscape; + const hex = s[i + 1 .. i + 3]; + const byte = try std.fmt.parseInt(u8, hex, 16); + try out.append(byte); + i += 2; + }, + else => return error.InvalidEscape, + } + } + + return out.toOwnedSlice(); +} + +fn parseSimpleKey(name: []const u8) ?keys.Key { + const table = [_]struct { name: []const u8, key: keys.Key }{ + .{ .name = "up", .key = .up }, + .{ .name = "down", .key = .down }, + .{ .name = "left", .key = .left }, + .{ .name = "right", .key = .right }, + .{ .name = "home", .key = .home }, + .{ .name = "end", .key = .end }, + .{ .name = "page_up", .key = .page_up }, + .{ .name = "page_down", .key = .page_down }, + .{ .name = "insert", .key = .insert }, + .{ .name = "delete", .key = .delete }, + .{ .name = "backspace", .key = .backspace }, + .{ .name = "enter", .key = .enter }, + .{ .name = "tab", .key = .tab }, + .{ .name = "escape", .key = .escape }, + .{ .name = "space", .key = .space }, + .{ .name = "null", .key = .null_key }, + .{ .name = "f1", .key = .f1 }, + .{ .name = "f2", .key = .f2 }, + .{ .name = "f3", .key = .f3 }, + .{ .name = "f4", .key = .f4 }, + .{ .name = "f5", .key = .f5 }, + .{ .name = "f6", .key = .f6 }, + .{ .name = "f7", .key = .f7 }, + .{ .name = "f8", .key = .f8 }, + .{ .name = "f9", .key = .f9 }, + .{ .name = "f10", .key = .f10 }, + .{ .name = "f11", .key = .f11 }, + .{ .name = "f12", .key = .f12 }, + }; + for (table) |entry| { + if (std.mem.eql(u8, entry.name, name)) return entry.key; + } + return null; +} + +fn parseLine(allocator: std.mem.Allocator, line: []const u8) !Event { + var ms: u64 = 0; + var mods: keys.Modifiers = .{}; + var key_name: []const u8 = ""; + var codepoint: ?u21 = null; + var str_value: ?[]const u8 = null; + + var tokens = std.mem.splitScalar(u8, line, ' '); + while (tokens.next()) |tok| { + if (tok.len == 0) continue; + const eq = std.mem.indexOfScalar(u8, tok, '=') orelse return error.InvalidLine; + const name = tok[0..eq]; + const value = tok[eq + 1 ..]; + + if (std.mem.eql(u8, name, "ms")) { + ms = try std.fmt.parseInt(u64, value, 10); + } else if (std.mem.eql(u8, name, "mod")) { + var parts = std.mem.splitScalar(u8, value, '+'); + while (parts.next()) |p| { + if (std.mem.eql(u8, p, "ctrl")) { + mods.ctrl = true; + } else if (std.mem.eql(u8, p, "alt")) { + mods.alt = true; + } else if (std.mem.eql(u8, p, "shift")) { + mods.shift = true; + } else if (std.mem.eql(u8, p, "super")) { + mods.super = true; + } + } + } else if (std.mem.eql(u8, name, "key")) { + key_name = value; + } else if (std.mem.eql(u8, name, "ch")) { + codepoint = @intCast(try std.fmt.parseInt(u32, value, 10)); + } else if (std.mem.eql(u8, name, "str")) { + str_value = value; + } + } + + const key: keys.Key = key_blk: { + if (std.mem.eql(u8, key_name, "char")) { + break :key_blk .{ .char = codepoint orelse return error.InvalidLine }; + } + if (std.mem.eql(u8, key_name, "paste")) { + const raw = str_value orelse return error.InvalidLine; + break :key_blk .{ .paste = try unescape(allocator, raw) }; + } + if (std.mem.eql(u8, key_name, "unknown")) { + const raw = str_value orelse return error.InvalidLine; + break :key_blk .{ .unknown = try unescape(allocator, raw) }; + } + break :key_blk parseSimpleKey(key_name) orelse return error.UnknownKey; + }; + + return .{ .elapsed_ms = ms, .event = .{ .key = key, .modifiers = mods } }; +} + +test "record and replay roundtrip" { + const allocator = std.testing.allocator; + var rec = Recorder.init(allocator); + defer rec.deinit(); + + try rec.recordAt(0, .{ .key = .{ .char = 'h' } }); + try rec.recordAt(40, .{ .key = .{ .char = 'i' } }); + try rec.recordAt(120, .{ .key = .enter }); + try rec.recordAt(200, .{ .key = .{ .char = 'c' }, .modifiers = .{ .ctrl = true } }); + + var buf = std.array_list.Managed(u8).init(allocator); + defer buf.deinit(); + try rec.write(buf.writer().any()); + + var player = try Player.parse(allocator, buf.items); + defer player.deinit(); + + const e1 = player.next().?; + try std.testing.expectEqual(@as(u64, 0), e1.elapsed_ms); + try std.testing.expectEqual(@as(u21, 'h'), e1.event.key.char); + + const e3 = player.next().?; // skip second + _ = e3; + const enter_event = player.next().?; + try std.testing.expect(enter_event.event.key == .enter); + try std.testing.expectEqual(@as(u64, 120), enter_event.elapsed_ms); + + const ctrl_c = player.next().?; + try std.testing.expect(ctrl_c.event.modifiers.ctrl); +} + +test "parse ignores blank lines and comments" { + const allocator = std.testing.allocator; + const input = + \\# demo + \\ + \\ms=0 key=enter + \\ + ; + var player = try Player.parse(allocator, input); + defer player.deinit(); + try std.testing.expectEqual(@as(usize, 1), player.len()); +}