From 7d8bf2fea34e0d4531c8635e29eb6718fb8305d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:16:07 +0000 Subject: [PATCH 01/10] chore: update to zig 0.16 and zigzag v0.1.5 Migrates sshz to Zig 0.16's reworked I/O model, where filesystem, process, and network operations require an `Io` instance. The main entry point now takes `std.process.Init`, and `io` plus `environ_map` are threaded through ssh_config, meta, app, and checker. Notable changes: - main: `std.process.spawn(io, ...)` replaces `std.process.Child.init` - main: `std.Io.File.stdout()` replaces `std.fs.File{ .handle = ... }` - main: `init.minimal.args.toSlice(arena)` replaces `argsAlloc/argsFree` - ssh_config/meta: switch to `std.Io.Dir.cwd()` with buffered writers and `init.environ_map.get("HOME")` for env access - checker: use `std.Io.net.HostName.connect(io, port, .{})` for TCP status checks - views: `zz.Color.cyan`/`white` are now consts (not functions) - CI: install Zig 0.16.0 - build.zig.zon: bump zigzag to v0.1.5, set minimum_zig_version Note: the zigzag dependency hash needs to be regenerated with `zig fetch --save=zigzag ` against a real Zig 0.16 toolchain; the current value in build.zig.zon is the v0.1.2 hash and will be rejected at build time. --- .github/workflows/ci.yml | 4 +-- build.zig.zon | 3 +- src/app.zig | 24 +++++++------ src/checker.zig | 13 ++++--- src/main.zig | 56 +++++++++++++++--------------- src/meta.zig | 40 +++++++++++----------- src/ssh_config.zig | 74 ++++++++++++++++++++++------------------ src/views/forward.zig | 2 +- src/views/help.zig | 4 +-- src/views/host_form.zig | 6 ++-- src/views/host_list.zig | 2 +- 11 files changed, 122 insertions(+), 106 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c655013..4bcce53 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,8 @@ jobs: - name: Install Zig run: | - curl -sL "https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz" | tar -xJ - echo "$PWD/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" + curl -sL "https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz" | tar -xJ + echo "$PWD/zig-x86_64-linux-0.16.0" >> "$GITHUB_PATH" - name: Format check continue-on-error: true diff --git a/build.zig.zon b/build.zig.zon index 4fb7064..0334d67 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,10 +2,11 @@ .name = .sshz, .version = "0.1.0", .fingerprint = 0x138d7fea3306d410, + .minimum_zig_version = "0.16.0", .paths = .{ "build.zig", "build.zig.zon", "src" }, .dependencies = .{ .zigzag = .{ - .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.2.tar.gz", + .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", .hash = "zigzag-0.1.0-YXwYS20gCwATYmA0IOAYQVHykNP--Dl7bKfp2UDE0K2I", }, }, diff --git a/src/app.zig b/src/app.zig index 91a3d4e..e466e06 100644 --- a/src/app.zig +++ b/src/app.zig @@ -48,6 +48,8 @@ pub const Model = struct { connect_host: ?[]const u8 = null, checker_generation: u32 = 0, pa: std.mem.Allocator, + io: std.Io = undefined, + env: *const std.process.Environ.Map = undefined, pub const SortMode = enum { name, recent, tag }; @@ -58,27 +60,29 @@ pub const Model = struct { pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { self.pa = ctx.persistent_allocator; + self.io = ctx.io; + self.env = ctx.environ_map; self.hosts = .{}; self.search_text = .{}; self.all_tags = .{}; // Load config - self.config_path = ssh_config.defaultConfigPath(self.pa) catch "/dev/null"; - self.meta_path = meta_mod.defaultMetaPath(self.pa) catch "/dev/null"; - self.backup_dir = meta_mod.defaultBackupDir(self.pa) catch "/dev/null"; + self.config_path = ssh_config.defaultConfigPath(self.pa, self.env) catch "/dev/null"; + self.meta_path = meta_mod.defaultMetaPath(self.pa, self.env) catch "/dev/null"; + self.backup_dir = meta_mod.defaultBackupDir(self.pa, self.env) catch "/dev/null"; - self.config = ssh_config.readFile(self.pa, self.config_path) catch ssh_config.Config{ + self.config = ssh_config.readFile(self.pa, self.io, self.config_path) catch ssh_config.Config{ .hosts = &.{}, .raw_lines = &.{}, }; - self.meta_store = meta_mod.readFile(self.pa, self.meta_path) catch meta_mod.MetaStore.initWith(self.pa); + self.meta_store = meta_mod.readFile(self.pa, self.io, self.meta_path) catch meta_mod.MetaStore.initWith(self.pa); self.rebuildHostList(); // Status checker self.result_queue = checker_mod.ResultQueue.init(self.pa); - self.status_checker = checker_mod.StatusChecker.init(&self.result_queue, self.pa); + self.status_checker = checker_mod.StatusChecker.init(&self.result_queue, self.pa, self.io); self.startStatusChecks(); self.collectTags(); @@ -395,7 +399,7 @@ pub const Model = struct { if (self.selected >= self.hosts.items.len) return; const entry = self.hosts.items[self.selected]; self.meta_store.recordConnection(self.pa, entry.config.name) catch {}; - meta_mod.writeFile(self.pa, &self.meta_store, self.meta_path) catch {}; + meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; self.connect_host = self.pa.dupe(u8, entry.config.name) catch null; } @@ -446,7 +450,7 @@ pub const Model = struct { } ssh_config.addHost(self.pa, &self.config, new_host) catch {}; - ssh_config.writeFile(self.pa, &self.config, self.config_path, self.backup_dir) catch {}; + ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; // Save tags if (tags_val.len > 0) { @@ -459,7 +463,7 @@ pub const Model = struct { } self.meta_store.setTags(self.pa, name, tags.items) catch {}; } - meta_mod.writeFile(self.pa, &self.meta_store, self.meta_path) catch {}; + meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; self.rebuildHostList(); self.collectTags(); @@ -480,7 +484,7 @@ pub const Model = struct { if (config_index) |ci| { ssh_config.removeHost(self.pa, &self.config, ci) catch {}; - ssh_config.writeFile(self.pa, &self.config, self.config_path, self.backup_dir) catch {}; + ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; } self.rebuildHostList(); diff --git a/src/checker.zig b/src/checker.zig index 7bfcc99..1f2c7ed 100644 --- a/src/checker.zig +++ b/src/checker.zig @@ -56,14 +56,16 @@ pub const StatusChecker = struct { dispatcher_thread: ?std.Thread = null, generation: std.atomic.Value(u32), allocator: std.mem.Allocator, + io: std.Io, - pub fn init(queue: *ResultQueue, allocator: std.mem.Allocator) StatusChecker { + pub fn init(queue: *ResultQueue, allocator: std.mem.Allocator, io: std.Io) StatusChecker { return .{ .queue = queue, .active_count = std.atomic.Value(u32).init(0), .shutdown = std.atomic.Value(bool).init(false), .generation = std.atomic.Value(u32).init(0), .allocator = allocator, + .io = io, }; } @@ -145,13 +147,14 @@ pub const StatusChecker = struct { defer _ = self.active_count.fetchSub(1, .release); if (self.shutdown.load(.acquire)) return; - const status = tcpCheck(hostname, port); + const status = tcpCheck(self.io, hostname, port); self.queue.push(.{ .host_index = host_index, .status = status, .generation = gen }); } }; -fn tcpCheck(hostname: []const u8, port: u16) HostStatus { - const stream = std.net.tcpConnectToHost(std.heap.page_allocator, hostname, port) catch return .offline; - stream.close(); +fn tcpCheck(io: std.Io, hostname: []const u8, port: u16) HostStatus { + const host = std.Io.net.HostName.init(hostname) catch return .offline; + const stream = host.connect(io, port, .{}) catch return .offline; + stream.close(io); return .online; } diff --git a/src/main.zig b/src/main.zig index 948d29c..5d76a83 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5,23 +5,21 @@ const app = @import("app"); const version = "0.1.0"; -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + const allocator = init.gpa; + const arena_allocator = init.arena.allocator(); - const args = try std.process.argsAlloc(allocator); - defer std.process.argsFree(allocator, args); + const args = try init.minimal.args.toSlice(arena_allocator); if (args.len >= 2 and std.mem.eql(u8, args[1], "--help")) { - printUsage(); + printUsage(init.io); return; } if (args.len >= 2 and std.mem.eql(u8, args[1], "--version")) { - const file = std.fs.File{ .handle = std.posix.STDOUT_FILENO }; + const file = std.Io.File.stdout(); var buf: [256]u8 = undefined; - var w = file.writer(&buf); + var w = file.writer(init.io, &buf); try w.interface.print("sshz {s}\n", .{version}); try w.interface.flush(); return; @@ -29,18 +27,18 @@ pub fn main() !void { // sshz [command...] — direct connect if (args.len >= 2 and args[1][0] != '-') { - try directConnect(allocator, args[1], args[2..]); + try directConnect(allocator, init.io, init.environ_map, args[1], args[2..]); return; } // sshz — launch TUI - try launchTui(allocator); + try launchTui(init); } -fn printUsage() void { - const file = std.fs.File{ .handle = std.posix.STDOUT_FILENO }; +fn printUsage(io: std.Io) void { + const file = std.Io.File.stdout(); var buf: [4096]u8 = undefined; - var w = file.writer(&buf); + var w = file.writer(io, &buf); w.interface.print( \\SSHZ - SSH Connection Manager \\ @@ -55,8 +53,9 @@ fn printUsage() void { w.interface.flush() catch {}; } -fn launchTui(allocator: std.mem.Allocator) !void { - var program = try zz.Program(app.Model).init(allocator); +fn launchTui(init: std.process.Init) !void { + const allocator = init.gpa; + var program = try zz.Program(app.Model).init(init.gpa, init.io, init.environ_map); try program.run(); // Grab connect_host before deinit frees it @@ -73,20 +72,20 @@ fn launchTui(allocator: std.mem.Allocator) !void { program.deinit(); if (connect_host) |host_name| { - try directConnect(allocator, host_name, &.{}); + try directConnect(allocator, init.io, init.environ_map, host_name, &.{}); } } -fn directConnect(allocator: std.mem.Allocator, host_name: []const u8, extra_args: []const [:0]u8) !void { +fn directConnect(allocator: std.mem.Allocator, io: std.Io, env: *const std.process.Environ.Map, host_name: []const u8, extra_args: []const [:0]const u8) !void { // Record connection in meta.json - const meta_path = try meta_mod.defaultMetaPath(allocator); + const meta_path = try meta_mod.defaultMetaPath(allocator, env); defer allocator.free(meta_path); - var store = try meta_mod.readFile(allocator, meta_path); + var store = try meta_mod.readFile(allocator, io, meta_path); defer store.deinit(allocator); try store.recordConnection(allocator, host_name); - meta_mod.writeFile(allocator, &store, meta_path) catch {}; + meta_mod.writeFile(allocator, io, &store, meta_path) catch {}; // Build args var argv: std.ArrayList([]const u8) = .{}; @@ -97,15 +96,16 @@ fn directConnect(allocator: std.mem.Allocator, host_name: []const u8, extra_args for (extra_args) |arg| try argv.append(allocator, arg); // Exec ssh - var child = std.process.Child.init(argv.items, allocator); - child.stdin_behavior = .Inherit; - child.stdout_behavior = .Inherit; - child.stderr_behavior = .Inherit; - try child.spawn(); - const term = try child.wait(); + var child = try std.process.spawn(io, .{ + .argv = argv.items, + .stdin = .inherit, + .stdout = .inherit, + .stderr = .inherit, + }); + const term = try child.wait(io); switch (term) { - .Exited => |code| if (code != 0) std.process.exit(code), + .exited => |code| if (code != 0) std.process.exit(code), else => std.process.exit(1), } } diff --git a/src/meta.zig b/src/meta.zig index bc0bd6d..e1fc6bb 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -209,48 +209,50 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const return try buf.toOwnedSlice(allocator); } -pub fn readFile(allocator: std.mem.Allocator, path: []const u8) !MetaStore { - const file = std.fs.cwd().openFile(path, .{}) catch |err| switch (err) { +pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !MetaStore { + const cwd = std.Io.Dir.cwd(); + const content = cwd.readFileAlloc(io, allocator, path, .limited(1024 * 1024)) catch |err| switch (err) { error.FileNotFound => return MetaStore.initWith(allocator), else => return err, }; - defer file.close(); - const content = try file.readToEndAlloc(allocator, 1024 * 1024); defer allocator.free(content); return parse(allocator, content) catch MetaStore.initWith(allocator); } -pub fn writeFile(allocator: std.mem.Allocator, store: *const MetaStore, path: []const u8) !void { +pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, store: *const MetaStore, path: []const u8) !void { const content = try serialize(allocator, store); defer allocator.free(content); const dir_path = std.fs.path.dirname(path) orelse "."; const basename = std.fs.path.basename(path); - std.fs.cwd().makePath(dir_path) catch {}; + const cwd = std.Io.Dir.cwd(); + cwd.createDirPath(io, dir_path) catch {}; var tmp_buf: [256]u8 = undefined; const tmp_name = std.fmt.bufPrint(&tmp_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; - var dir_fd = try std.fs.cwd().openDir(dir_path, .{}); - defer dir_fd.close(); + var dir_fd = try cwd.openDir(io, dir_path, .{}); + defer dir_fd.close(io); - const tmp_file = try dir_fd.createFile(tmp_name, .{}); - tmp_file.writeAll(content) catch |e| { - tmp_file.close(); - return e; - }; - tmp_file.close(); + { + const tmp_file = try dir_fd.createFile(io, tmp_name, .{}); + defer tmp_file.close(io); + var write_buf: [4096]u8 = undefined; + var w = tmp_file.writer(io, &write_buf); + try w.interface.writeAll(content); + try w.interface.flush(); + } - try dir_fd.rename(tmp_name, basename); + try std.Io.Dir.rename(dir_fd, tmp_name, dir_fd, basename, io); } -pub fn defaultMetaPath(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultMetaPath(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.config/sshz/meta.json", .{home}); } -pub fn defaultBackupDir(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultBackupDir(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.config/sshz/backups", .{home}); } diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 84b406d..45dd1e8 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -285,16 +285,15 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! config.hosts = try new_hosts.toOwnedSlice(allocator); } -pub fn readFile(allocator: std.mem.Allocator, path: []const u8) !Config { - const file = try std.fs.cwd().openFile(path, .{}); - defer file.close(); - const content = try file.readToEndAlloc(allocator, 1024 * 1024); +pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Config { + const cwd = std.Io.Dir.cwd(); + const content = try cwd.readFileAlloc(io, allocator, path, .limited(1024 * 1024)); defer allocator.free(content); return parse(allocator, content); } -pub fn writeFile(allocator: std.mem.Allocator, config: *const Config, path: []const u8, backup_dir: []const u8) !void { - backupFile(allocator, path, backup_dir) catch {}; +pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config, path: []const u8, backup_dir: []const u8) !void { + backupFile(allocator, io, path, backup_dir) catch {}; const content = try serialize(allocator, config); defer allocator.free(content); @@ -305,24 +304,28 @@ pub fn writeFile(allocator: std.mem.Allocator, config: *const Config, path: []co var tmp_name_buf: [256]u8 = undefined; const tmp_name = std.fmt.bufPrint(&tmp_name_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; - var dir_fd = try std.fs.cwd().openDir(dir_path, .{}); - defer dir_fd.close(); - - const tmp_file = try dir_fd.createFile(tmp_name, .{}); - tmp_file.writeAll(content) catch |e| { - tmp_file.close(); - return e; - }; - tmp_file.close(); + const cwd = std.Io.Dir.cwd(); + var dir_fd = try cwd.openDir(io, dir_path, .{}); + defer dir_fd.close(io); + + { + const tmp_file = try dir_fd.createFile(io, tmp_name, .{}); + defer tmp_file.close(io); + var write_buf: [4096]u8 = undefined; + var w = tmp_file.writer(io, &write_buf); + try w.interface.writeAll(content); + try w.interface.flush(); + } - try dir_fd.rename(tmp_name, basename); + try std.Io.Dir.rename(dir_fd, tmp_name, dir_fd, basename, io); } -fn backupFile(allocator: std.mem.Allocator, source_path: []const u8, backup_dir: []const u8) !void { - std.fs.cwd().makePath(backup_dir) catch {}; +fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, backup_dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + cwd.createDirPath(io, backup_dir) catch {}; - const source = std.fs.cwd().openFile(source_path, .{}) catch return; - defer source.close(); + const content = cwd.readFileAlloc(io, allocator, source_path, .limited(1024 * 1024)) catch return; + defer allocator.free(content); const ts = std.time.timestamp(); var name_buf: [256]u8 = undefined; @@ -331,19 +334,22 @@ fn backupFile(allocator: std.mem.Allocator, source_path: []const u8, backup_dir: var path_buf: [512]u8 = undefined; const backup_path = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ backup_dir, backup_name }) catch return; - const content = source.readToEndAlloc(allocator, 1024 * 1024) catch return; - defer allocator.free(content); - - const dest = std.fs.cwd().createFile(backup_path, .{}) catch return; - defer dest.close(); - dest.writeAll(content) catch {}; + { + const dest = cwd.createFile(io, backup_path, .{}) catch return; + defer dest.close(io); + var write_buf: [4096]u8 = undefined; + var w = dest.writer(io, &write_buf); + w.interface.writeAll(content) catch return; + w.interface.flush() catch return; + } - rotateBackups(allocator, backup_dir) catch {}; + rotateBackups(allocator, io, backup_dir) catch {}; } -fn rotateBackups(allocator: std.mem.Allocator, backup_dir: []const u8) !void { - var dir = try std.fs.cwd().openDir(backup_dir, .{ .iterate = true }); - defer dir.close(); +fn rotateBackups(allocator: std.mem.Allocator, io: std.Io, backup_dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + var dir = try cwd.openDir(io, backup_dir, .{ .iterate = true }); + defer dir.close(io); var entries: std.ArrayList([]const u8) = .{}; defer { @@ -352,7 +358,7 @@ fn rotateBackups(allocator: std.mem.Allocator, backup_dir: []const u8) !void { } var it = dir.iterate(); - while (try it.next()) |entry| { + while (try it.next(io)) |entry| { if (std.mem.startsWith(u8, entry.name, "ssh_config_")) { try entries.append(allocator, try allocator.dupe(u8, entry.name)); } @@ -368,11 +374,11 @@ fn rotateBackups(allocator: std.mem.Allocator, backup_dir: []const u8) !void { const to_delete = entries.items.len - 10; for (entries.items[0..to_delete]) |name| { - dir.deleteFile(name) catch {}; + dir.deleteFile(io, name) catch {}; } } -pub fn defaultConfigPath(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultConfigPath(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.ssh/config", .{home}); } diff --git a/src/views/forward.zig b/src/views/forward.zig index ec4d1da..078e1c9 100644 --- a/src/views/forward.zig +++ b/src/views/forward.zig @@ -42,7 +42,7 @@ pub const ForwardState = struct { pub fn render(state: *const ForwardState, ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try std.fmt.allocPrint(a, " Connect to {s}", .{state.host_name}); const title_rendered = try title_style.render(a, title); diff --git a/src/views/help.zig b/src/views/help.zig index c880757..d4d94c3 100644 --- a/src/views/help.zig +++ b/src/views/help.zig @@ -4,7 +4,7 @@ const zz = @import("zigzag"); pub fn render(ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const key_style = (zz.Style{}).bold(true).fg(zz.Color.fromRgb(255, 200, 0)); const dim = (zz.Style{}).fg(zz.Color.gray(15)); @@ -43,7 +43,7 @@ pub fn render(ctx: *const zz.Context) ![]const u8 { return try (zz.Style{}) .borderAll(zz.Border.rounded) - .borderForeground(zz.Color.cyan()) + .borderForeground(zz.Color.cyan) .paddingAll(1) .width(@min(ctx.width -| 4, 50)) .render(a, content); diff --git a/src/views/host_form.zig b/src/views/host_form.zig index 0f21e2c..03d24d2 100644 --- a/src/views/host_form.zig +++ b/src/views/host_form.zig @@ -72,7 +72,7 @@ pub fn render(form: *const FormState, ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; const title_text = if (form.editing_host != null) " Edit Host" else " Add Host"; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try title_style.render(a, title_text); const dim = (zz.Style{}).fg(zz.Color.gray(12)); @@ -91,8 +91,8 @@ pub fn render(form: *const FormState, ctx: *const zz.Context) ![]const u8 { " Tags: ", }; - const label_style = (zz.Style{}).fg(zz.Color.white()).bold(true); - const focus_indicator = (zz.Style{}).fg(zz.Color.cyan()).bold(true); + const label_style = (zz.Style{}).fg(zz.Color.white).bold(true); + const focus_indicator = (zz.Style{}).fg(zz.Color.cyan).bold(true); var lines: std.ArrayList([]const u8) = .{}; defer lines.deinit(a); diff --git a/src/views/host_list.zig b/src/views/host_list.zig index 1fe82f6..e9e314b 100644 --- a/src/views/host_list.zig +++ b/src/views/host_list.zig @@ -9,7 +9,7 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const w = ctx.width; // Title - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try title_style.render(a, " sshz - SSH Manager"); // Host count From deb8056019635580ad5bde193a200430ca94fc84 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:18:31 +0000 Subject: [PATCH 02/10] fix: correct readFileAlloc/rename param order for zig 0.16 - readFileAlloc takes (io, sub_path, gpa, limit) not (io, gpa, sub_path, limit) - rename uses method call style: dir.rename(old_path, new_dir, new_path, io) --- src/meta.zig | 4 ++-- src/ssh_config.zig | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/meta.zig b/src/meta.zig index e1fc6bb..8d322f1 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -211,7 +211,7 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !MetaStore { const cwd = std.Io.Dir.cwd(); - const content = cwd.readFileAlloc(io, allocator, path, .limited(1024 * 1024)) catch |err| switch (err) { + const content = cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)) catch |err| switch (err) { error.FileNotFound => return MetaStore.initWith(allocator), else => return err, }; @@ -244,7 +244,7 @@ pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, store: *const MetaSto try w.interface.flush(); } - try std.Io.Dir.rename(dir_fd, tmp_name, dir_fd, basename, io); + try dir_fd.rename(tmp_name, dir_fd, basename, io); } pub fn defaultMetaPath(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 45dd1e8..418dd11 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -287,7 +287,7 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Config { const cwd = std.Io.Dir.cwd(); - const content = try cwd.readFileAlloc(io, allocator, path, .limited(1024 * 1024)); + const content = try cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)); defer allocator.free(content); return parse(allocator, content); } @@ -317,14 +317,14 @@ pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config try w.interface.flush(); } - try std.Io.Dir.rename(dir_fd, tmp_name, dir_fd, basename, io); + try dir_fd.rename(tmp_name, dir_fd, basename, io); } fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, backup_dir: []const u8) !void { const cwd = std.Io.Dir.cwd(); cwd.createDirPath(io, backup_dir) catch {}; - const content = cwd.readFileAlloc(io, allocator, source_path, .limited(1024 * 1024)) catch return; + const content = cwd.readFileAlloc(io, source_path, allocator, .limited(1024 * 1024)) catch return; defer allocator.free(content); const ts = std.time.timestamp(); From ab9af4c9f5fed4fe9c933b1554d85d63d39e1427 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:24:49 +0000 Subject: [PATCH 03/10] fix: use ArrayList .empty and std.Io.Mutex for zig 0.16 - Unmanaged std.ArrayList no longer has default field values, so .{} initialization fails; switch to .empty - std.Thread.Mutex is gone; use std.Io.Mutex with lockUncancelable(io) and unlock(io) - ResultQueue now also takes an Io instance so its mutex can lock --- src/app.zig | 6 +++--- src/checker.zig | 31 ++++++++++++++++--------------- src/main.zig | 2 +- src/meta.zig | 6 +++--- src/ssh_config.zig | 16 ++++++++-------- src/views/forward.zig | 4 ++-- src/views/help.zig | 2 +- src/views/host_form.zig | 2 +- src/views/host_list.zig | 4 ++-- 9 files changed, 37 insertions(+), 36 deletions(-) diff --git a/src/app.zig b/src/app.zig index e466e06..112fb8b 100644 --- a/src/app.zig +++ b/src/app.zig @@ -81,7 +81,7 @@ pub const Model = struct { self.rebuildHostList(); // Status checker - self.result_queue = checker_mod.ResultQueue.init(self.pa); + self.result_queue = checker_mod.ResultQueue.init(self.pa, self.io); self.status_checker = checker_mod.StatusChecker.init(&self.result_queue, self.pa, self.io); self.startStatusChecks(); self.collectTags(); @@ -113,7 +113,7 @@ pub const Model = struct { } fn startStatusChecks(self: *Model) void { - var requests: std.ArrayList(checker_mod.CheckRequest) = .{}; + var requests: std.ArrayList(checker_mod.CheckRequest) = .empty; defer requests.deinit(self.pa); for (self.hosts.items, 0..) |entry, i| { @@ -454,7 +454,7 @@ pub const Model = struct { // Save tags if (tags_val.len > 0) { - var tags: std.ArrayList([]const u8) = .{}; + var tags: std.ArrayList([]const u8) = .empty; defer tags.deinit(self.pa); var tag_it = std.mem.splitScalar(u8, tags_val, ','); while (tag_it.next()) |tag| { diff --git a/src/checker.zig b/src/checker.zig index 1f2c7ed..9e50412 100644 --- a/src/checker.zig +++ b/src/checker.zig @@ -20,12 +20,13 @@ pub const CheckRequest = struct { }; pub const ResultQueue = struct { - mutex: std.Thread.Mutex = .{}, - results: std.ArrayList(CheckResult) = .{}, + mutex: std.Io.Mutex = std.Io.Mutex.init, + results: std.ArrayList(CheckResult) = .empty, allocator: std.mem.Allocator, + io: std.Io, - pub fn init(allocator: std.mem.Allocator) ResultQueue { - return .{ .allocator = allocator }; + pub fn init(allocator: std.mem.Allocator, io: std.Io) ResultQueue { + return .{ .allocator = allocator, .io = io }; } pub fn deinit(self: *ResultQueue) void { @@ -33,14 +34,14 @@ pub const ResultQueue = struct { } pub fn push(self: *ResultQueue, result: CheckResult) void { - self.mutex.lock(); - defer self.mutex.unlock(); + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); self.results.append(self.allocator, result) catch {}; } pub fn drain(self: *ResultQueue, allocator: std.mem.Allocator) []CheckResult { - self.mutex.lock(); - defer self.mutex.unlock(); + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); if (self.results.items.len == 0) return &.{}; return self.results.toOwnedSlice(allocator) catch return &.{}; } @@ -51,8 +52,8 @@ pub const StatusChecker = struct { active_count: std.atomic.Value(u32), max_concurrent: u32 = 3, shutdown: std.atomic.Value(bool), - threads: std.ArrayList(std.Thread) = .{}, - threads_mutex: std.Thread.Mutex = .{}, + threads: std.ArrayList(std.Thread) = .empty, + threads_mutex: std.Io.Mutex = std.Io.Mutex.init, dispatcher_thread: ?std.Thread = null, generation: std.atomic.Value(u32), allocator: std.mem.Allocator, @@ -80,9 +81,9 @@ pub const StatusChecker = struct { } fn joinAllThreads(self: *StatusChecker) void { - self.threads_mutex.lock(); + self.threads_mutex.lockUncancelable(self.io); const threads = self.threads.toOwnedSlice(self.allocator) catch return; - self.threads_mutex.unlock(); + self.threads_mutex.unlock(self.io); for (threads) |t| t.join(); self.allocator.free(threads); } @@ -133,13 +134,13 @@ pub const StatusChecker = struct { _ = self.active_count.fetchSub(1, .release); continue; }; - self.threads_mutex.lock(); + self.threads_mutex.lockUncancelable(self.io); self.threads.append(self.allocator, thread) catch { - self.threads_mutex.unlock(); + self.threads_mutex.unlock(self.io); thread.join(); continue; }; - self.threads_mutex.unlock(); + self.threads_mutex.unlock(self.io); } } diff --git a/src/main.zig b/src/main.zig index 5d76a83..5c6a913 100644 --- a/src/main.zig +++ b/src/main.zig @@ -88,7 +88,7 @@ fn directConnect(allocator: std.mem.Allocator, io: std.Io, env: *const std.proce meta_mod.writeFile(allocator, io, &store, meta_path) catch {}; // Build args - var argv: std.ArrayList([]const u8) = .{}; + var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(allocator); try argv.append(allocator, "ssh"); diff --git a/src/meta.zig b/src/meta.zig index 8d322f1..852c4a7 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -121,7 +121,7 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { const name = try allocator.dupe(u8, entry.key_ptr.*); const obj = entry.value_ptr.object; - var tags_list: std.ArrayList([]const u8) = .{}; + var tags_list: std.ArrayList([]const u8) = .empty; defer tags_list.deinit(allocator); if (obj.get("tags")) |tags_val| { for (tags_val.array.items) |tag| { @@ -129,7 +129,7 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { } } - var fwds_list: std.ArrayList(PortForward) = .{}; + var fwds_list: std.ArrayList(PortForward) = .empty; defer fwds_list.deinit(allocator); if (obj.get("port_forwards")) |fwds_val| { for (fwds_val.array.items) |fwd| { @@ -158,7 +158,7 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { } pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const u8 { - var buf: std.ArrayList(u8) = .{}; + var buf: std.ArrayList(u8) = .empty; defer buf.deinit(allocator); try buf.appendSlice(allocator, "{\n \"version\": "); diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 418dd11..71c13b9 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -76,10 +76,10 @@ fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool { } pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { - var hosts: std.ArrayList(Host) = .{}; + var hosts: std.ArrayList(Host) = .empty; defer hosts.deinit(allocator); - var lines_list: std.ArrayList([]const u8) = .{}; + var lines_list: std.ArrayList([]const u8) = .empty; defer lines_list.deinit(allocator); var line_iter = std.mem.splitScalar(u8, content, '\n'); @@ -197,7 +197,7 @@ fn setHostField(h: *Host, key: []const u8, value: []const u8) void { } pub fn serialize(allocator: std.mem.Allocator, config: *const Config) ![]const u8 { - var result: std.ArrayList(u8) = .{}; + var result: std.ArrayList(u8) = .empty; defer result.deinit(allocator); for (config.raw_lines) |line| { @@ -209,7 +209,7 @@ pub fn serialize(allocator: std.mem.Allocator, config: *const Config) ![]const u } pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void { - var new_lines: std.ArrayList([]const u8) = .{}; + var new_lines: std.ArrayList([]const u8) = .empty; defer new_lines.deinit(allocator); for (config.raw_lines) |l| try new_lines.append(allocator, l); try new_lines.append(allocator, ""); @@ -242,7 +242,7 @@ pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void allocator.free(config.raw_lines); config.raw_lines = try new_lines.toOwnedSlice(allocator); - var new_hosts: std.ArrayList(Host) = .{}; + var new_hosts: std.ArrayList(Host) = .empty; defer new_hosts.deinit(allocator); for (config.hosts) |h| try new_hosts.append(allocator, h); var new_host = host; @@ -260,7 +260,7 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! const start = host.start_line; const end = @min(host.end_line, config.raw_lines.len); - var new_lines: std.ArrayList([]const u8) = .{}; + var new_lines: std.ArrayList([]const u8) = .empty; defer new_lines.deinit(allocator); for (config.raw_lines, 0..) |line, i| { if (i >= start and i < end) continue; @@ -270,7 +270,7 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! config.raw_lines = try new_lines.toOwnedSlice(allocator); const removed_count = end - start; - var new_hosts: std.ArrayList(Host) = .{}; + var new_hosts: std.ArrayList(Host) = .empty; defer new_hosts.deinit(allocator); for (config.hosts, 0..) |h, i| { if (i == index) continue; @@ -351,7 +351,7 @@ fn rotateBackups(allocator: std.mem.Allocator, io: std.Io, backup_dir: []const u var dir = try cwd.openDir(io, backup_dir, .{ .iterate = true }); defer dir.close(io); - var entries: std.ArrayList([]const u8) = .{}; + var entries: std.ArrayList([]const u8) = .empty; defer { for (entries.items) |name| allocator.free(@constCast(name)); entries.deinit(allocator); diff --git a/src/views/forward.zig b/src/views/forward.zig index 078e1c9..3db1194 100644 --- a/src/views/forward.zig +++ b/src/views/forward.zig @@ -13,7 +13,7 @@ pub const ForwardState = struct { selected: usize = 0, pub fn init(allocator: std.mem.Allocator, host_name: []const u8, forwards: []const meta_mod.PortForward) ForwardState { - var entries: std.ArrayList(ForwardEntry) = .{}; + var entries: std.ArrayList(ForwardEntry) = .empty; for (forwards) |fwd| { entries.append(allocator, .{ .forward = fwd }) catch {}; } @@ -51,7 +51,7 @@ pub fn render(state: *const ForwardState, ctx: *const zz.Context) ![]const u8 { @memset(sep_chars, '-'); const sep = try dim.render(a, sep_chars); - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, title_rendered); try lines.append(a, sep); diff --git a/src/views/help.zig b/src/views/help.zig index d4d94c3..6c2354d 100644 --- a/src/views/help.zig +++ b/src/views/help.zig @@ -23,7 +23,7 @@ pub fn render(ctx: *const zz.Context) ![]const u8 { .{ "q ", "Quit" }, }; - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, try title_style.render(a, " sshz Keybindings")); diff --git a/src/views/host_form.zig b/src/views/host_form.zig index 03d24d2..45c5d1b 100644 --- a/src/views/host_form.zig +++ b/src/views/host_form.zig @@ -94,7 +94,7 @@ pub fn render(form: *const FormState, ctx: *const zz.Context) ![]const u8 { const label_style = (zz.Style{}).fg(zz.Color.white).bold(true); const focus_indicator = (zz.Style{}).fg(zz.Color.cyan).bold(true); - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, title); try lines.append(a, sep); diff --git a/src/views/host_list.zig b/src/views/host_list.zig index e9e314b..52da0ee 100644 --- a/src/views/host_list.zig +++ b/src/views/host_list.zig @@ -34,7 +34,7 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const separator = try dim.render(a, sep_chars); // Build lines - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, header); try lines.append(a, separator); @@ -157,7 +157,7 @@ fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, var tags_str: []const u8 = ""; if (entry.meta) |m| { if (m.tags.len > 0) { - var tag_buf: std.ArrayList(u8) = .{}; + var tag_buf: std.ArrayList(u8) = .empty; defer tag_buf.deinit(a); try tag_buf.appendSlice(a, "["); for (m.tags, 0..) |tag, j| { From 6cf019e34e325acb8f3e8b0b7286250d4d2fcf6e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:29:45 +0000 Subject: [PATCH 04/10] fix: use std.Io.Timestamp.now() instead of removed std.time.timestamp --- src/app.zig | 2 +- src/main.zig | 2 +- src/meta.zig | 4 ++-- src/ssh_config.zig | 2 +- src/utils.zig | 4 ++-- src/views/host_list.zig | 6 +++--- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/app.zig b/src/app.zig index 112fb8b..37bca4f 100644 --- a/src/app.zig +++ b/src/app.zig @@ -398,7 +398,7 @@ pub const Model = struct { fn connectToSelected(self: *Model) void { if (self.selected >= self.hosts.items.len) return; const entry = self.hosts.items[self.selected]; - self.meta_store.recordConnection(self.pa, entry.config.name) catch {}; + self.meta_store.recordConnection(self.pa, self.io, entry.config.name) catch {}; meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; self.connect_host = self.pa.dupe(u8, entry.config.name) catch null; } diff --git a/src/main.zig b/src/main.zig index 5c6a913..7f10c2a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -84,7 +84,7 @@ fn directConnect(allocator: std.mem.Allocator, io: std.Io, env: *const std.proce var store = try meta_mod.readFile(allocator, io, meta_path); defer store.deinit(allocator); - try store.recordConnection(allocator, host_name); + try store.recordConnection(allocator, io, host_name); meta_mod.writeFile(allocator, io, &store, meta_path) catch {}; // Build args diff --git a/src/meta.zig b/src/meta.zig index 852c4a7..3a2fba8 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -45,8 +45,8 @@ pub const MetaStore = struct { return self.entries.getPtr(name); } - pub fn recordConnection(self: *MetaStore, allocator: std.mem.Allocator, name: []const u8) !void { - const now = std.time.timestamp(); + pub fn recordConnection(self: *MetaStore, allocator: std.mem.Allocator, io: std.Io, name: []const u8) !void { + const now = std.Io.Timestamp.now(io, .real).toSeconds(); if (self.entries.getPtr(name)) |entry| { entry.last_connected = now; entry.connect_count += 1; diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 71c13b9..1857cdc 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -327,7 +327,7 @@ fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, const content = cwd.readFileAlloc(io, source_path, allocator, .limited(1024 * 1024)) catch return; defer allocator.free(content); - const ts = std.time.timestamp(); + const ts = std.Io.Timestamp.now(io, .real).toSeconds(); var name_buf: [256]u8 = undefined; const backup_name = std.fmt.bufPrint(&name_buf, "ssh_config_{d}", .{ts}) catch return; diff --git a/src/utils.zig b/src/utils.zig index dfe8b96..e8dfe70 100644 --- a/src/utils.zig +++ b/src/utils.zig @@ -18,9 +18,9 @@ pub fn relativeTime(seconds_ago: i64, buf: *[32]u8) []const u8 { } } -pub fn relativeTimeFromTimestamp(timestamp: i64, buf: *[32]u8) []const u8 { +pub fn relativeTimeFromTimestamp(io: std.Io, timestamp: i64, buf: *[32]u8) []const u8 { if (timestamp == 0) return "never"; - const now = std.time.timestamp(); + const now = std.Io.Timestamp.now(io, .real).toSeconds(); const diff = now - timestamp; if (diff < 0) return "future"; return relativeTime(diff, buf); diff --git a/src/views/host_list.zig b/src/views/host_list.zig index 52da0ee..64d4337 100644 --- a/src/views/host_list.zig +++ b/src/views/host_list.zig @@ -53,7 +53,7 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { } const is_selected = (display_idx == model.selected); - const line = try renderHostLine(a, entry, is_selected, w); + const line = try renderHostLine(a, ctx.io, entry, is_selected, w); try lines.append(a, line); display_idx += 1; } @@ -125,7 +125,7 @@ fn hasTag(entry: App.HostEntry, tag: []const u8) bool { return false; } -fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, width: u16) ![]const u8 { +fn renderHostLine(a: std.mem.Allocator, io: std.Io, entry: App.HostEntry, is_selected: bool, width: u16) ![]const u8 { // Status indicator const StatusInfo = struct { sym: []const u8, color: zz.Color }; const status_info: StatusInfo = switch (entry.status) { @@ -172,7 +172,7 @@ fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, // Last connected var time_buf: [32]u8 = undefined; const last_time = if (entry.meta) |m| - utils.relativeTimeFromTimestamp(m.last_connected, &time_buf) + utils.relativeTimeFromTimestamp(io, m.last_connected, &time_buf) else "never"; From 018e79ee104e7bbbfaf400e256a4e6f26e03b2e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:32:35 +0000 Subject: [PATCH 05/10] fix: complete migration to zig 0.16 - build and tests pass - build.zig.zon: use real v0.1.5 hash from zig fetch - app.zig: ArrayList(...).empty (not .{}) for new unmanaged ArrayList - checker.zig: pass .mode = .stream for HostName.connect - meta.zig/utils.zig/ssh_config.zig: route io through for the new std.Io.Timestamp.now(.real) clock API - tests/test_meta.zig: pass std.testing.io to recordConnection Verified locally: zig 0.16.0 builds the exe, all 29 tests pass, and zig fmt --check src/ is clean. --- build.zig.zon | 2 +- src/app.zig | 20 +- src/checker.zig | 2 +- tests/test_meta.zig | 8 +- .../LICENSE | 21 + .../README.md | 1295 +++++++++++ .../build.zig | 164 ++ .../build.zig.zon | 14 + .../src/accessibility.zig | 169 ++ .../src/components/bar_chart.zig | 289 +++ .../src/components/braille_canvas.zig | 412 ++++ .../src/components/breadcrumb.zig | 223 ++ .../src/components/calendar.zig | 304 +++ .../src/components/canvas.zig | 484 +++++ .../src/components/chart.zig | 758 +++++++ .../src/components/charting.zig | 253 +++ .../src/components/checkbox.zig | 434 ++++ .../src/components/code_view.zig | 255 +++ .../src/components/command_palette.zig | 422 ++++ .../src/components/confirm.zig | 154 ++ .../src/components/context_menu.zig | 392 ++++ .../src/components/data_table.zig | 530 +++++ .../src/components/diff_view.zig | 285 +++ .../src/components/dropdown.zig | 719 +++++++ .../src/components/file_picker.zig | 419 ++++ .../src/components/focus.zig | 553 +++++ .../src/components/form.zig | 299 +++ .../src/components/gauge.zig | 249 +++ .../src/components/heatmap.zig | 250 +++ .../src/components/help.zig | 238 ++ .../src/components/keybinding.zig | 114 + .../src/components/list.zig | 490 +++++ .../src/components/markdown.zig | 350 +++ .../src/components/menu_bar.zig | 576 +++++ .../src/components/modal.zig | 761 +++++++ .../src/components/notification.zig | 139 ++ .../src/components/paginator.zig | 226 ++ .../src/components/progress.zig | 264 +++ .../src/components/radio_group.zig | 276 +++ .../src/components/rich_log.zig | 422 ++++ .../src/components/slider.zig | 291 +++ .../src/components/sortable_table.zig | 321 +++ .../src/components/sparkline.zig | 229 ++ .../src/components/spinner.zig | 146 ++ .../src/components/split_pane.zig | 246 +++ .../src/components/status_bar.zig | 215 ++ .../src/components/stepper.zig | 254 +++ .../src/components/styled_list.zig | 169 ++ .../src/components/tab_group.zig | 1066 +++++++++ .../src/components/table.zig | 469 ++++ .../src/components/text_area.zig | 1057 +++++++++ .../src/components/text_input.zig | 462 ++++ .../src/components/timer.zig | 223 ++ .../src/components/toast.zig | 444 ++++ .../src/components/tooltip.zig | 925 ++++++++ .../src/components/tree.zig | 185 ++ .../src/components/viewport.zig | 456 ++++ .../src/components/virtual_list.zig | 216 ++ .../src/core/action.zig | 410 ++++ .../src/core/animation.zig | 185 ++ .../src/core/async_task.zig | 108 + .../src/core/command.zig | 304 +++ .../src/core/context.zig | 382 ++++ .../src/core/dev_console.zig | 342 +++ .../src/core/fuzzy.zig | 171 ++ .../src/core/log.zig | 60 + .../src/core/message.zig | 90 + .../src/core/program.zig | 833 +++++++ .../src/core/screen_stack.zig | 393 ++++ .../src/core/sub_program.zig | 87 + .../src/input/hitbox.zig | 128 ++ .../src/input/keyboard.zig | 329 +++ .../src/input/keys.zig | 191 ++ .../src/input/mouse.zig | 164 ++ .../src/layout/flex.zig | 473 ++++ .../src/layout/join.zig | 225 ++ .../src/layout/layer.zig | 156 ++ .../src/layout/layout.zig | 41 + .../src/layout/measure.zig | 279 +++ .../src/layout/place.zig | 388 ++++ .../src/root.zig | 386 ++++ .../src/style/border.zig | 303 +++ .../src/style/color.zig | 310 +++ .../src/style/compress.zig | 156 ++ .../src/style/overflow.zig | 287 +++ .../src/style/style.zig | 1060 +++++++++ .../src/style/theme.zig | 481 +++++ .../src/terminal/ansi.zig | 372 ++++ .../src/terminal/platform/posix.zig | 204 ++ .../src/terminal/platform/wasm.zig | 178 ++ .../src/terminal/platform/windows.zig | 346 +++ .../src/terminal/screen.zig | 306 +++ .../src/terminal/terminal.zig | 1914 +++++++++++++++++ .../src/testing/snapshot.zig | 232 ++ .../src/unicode.zig | 96 + .../src/unicode/display_width.zig | 677 ++++++ 96 files changed, 33644 insertions(+), 12 deletions(-) create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig create mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig diff --git a/build.zig.zon b/build.zig.zon index 0334d67..5469450 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -7,7 +7,7 @@ .dependencies = .{ .zigzag = .{ .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", - .hash = "zigzag-0.1.0-YXwYS20gCwATYmA0IOAYQVHykNP--Dl7bKfp2UDE0K2I", + .hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv", }, }, } diff --git a/src/app.zig b/src/app.zig index 37bca4f..eea6edf 100644 --- a/src/app.zig +++ b/src/app.zig @@ -63,9 +63,9 @@ pub const Model = struct { self.io = ctx.io; self.env = ctx.environ_map; - self.hosts = .{}; - self.search_text = .{}; - self.all_tags = .{}; + self.hosts = .empty; + self.search_text = .empty; + self.all_tags = .empty; // Load config self.config_path = ssh_config.defaultConfigPath(self.pa, self.env) catch "/dev/null"; @@ -139,7 +139,10 @@ pub const Model = struct { for (entry.value_ptr.tags) |tag| { var found = false; for (self.all_tags.items) |existing| { - if (std.mem.eql(u8, existing, tag)) { found = true; break; } + if (std.mem.eql(u8, existing, tag)) { + found = true; + break; + } } if (!found) self.all_tags.append(self.pa, tag) catch {}; } @@ -187,7 +190,9 @@ pub const Model = struct { if (self.screen == .help) { switch (k.key) { .escape => self.screen = .list, - .char => |c| if (c == '?') { self.screen = .list; }, + .char => |c| if (c == '?') { + self.screen = .list; + }, else => {}, } return .none; @@ -478,7 +483,10 @@ pub const Model = struct { var display_i: usize = 0; for (self.config.hosts, 0..) |h, ci| { if (h.is_wildcard) continue; - if (display_i == self.selected) { config_index = ci; break; } + if (display_i == self.selected) { + config_index = ci; + break; + } display_i += 1; } diff --git a/src/checker.zig b/src/checker.zig index 9e50412..7ba32a7 100644 --- a/src/checker.zig +++ b/src/checker.zig @@ -155,7 +155,7 @@ pub const StatusChecker = struct { fn tcpCheck(io: std.Io, hostname: []const u8, port: u16) HostStatus { const host = std.Io.net.HostName.init(hostname) catch return .offline; - const stream = host.connect(io, port, .{}) catch return .offline; + const stream = host.connect(io, port, .{ .mode = .stream }) catch return .offline; stream.close(io); return .online; } diff --git a/tests/test_meta.zig b/tests/test_meta.zig index f7ee611..0903cf7 100644 --- a/tests/test_meta.zig +++ b/tests/test_meta.zig @@ -23,7 +23,7 @@ test "record connection creates new host entry" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "newhost"); + try store.recordConnection(allocator, std.testing.io, "newhost"); const host = store.getHost("newhost"); try std.testing.expect(host != null); @@ -36,8 +36,8 @@ test "record connection increments existing count" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "host1"); - try store.recordConnection(allocator, "host1"); + try store.recordConnection(allocator, std.testing.io, "host1"); + try store.recordConnection(allocator, std.testing.io, "host1"); const host = store.getHost("host1"); try std.testing.expectEqual(@as(u32, 2), host.?.connect_count); @@ -48,7 +48,7 @@ test "serialize and parse round-trip" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "roundtrip"); + try store.recordConnection(allocator, std.testing.io, "roundtrip"); const tags = [_][]const u8{ "dev", "local" }; try store.setTags(allocator, "roundtrip", &tags); diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE new file mode 100644 index 0000000..ea076d3 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Matthew Meszaros + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md new file mode 100644 index 0000000..13ae4f6 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md @@ -0,0 +1,1295 @@ +# ZigZag + +A delightful TUI framework for Zig, inspired by [Bubble Tea](https://github.com/charmbracelet/bubbletea) and [Lipgloss](https://github.com/charmbracelet/lipgloss). + +![Demo](assets/showcase.gif) + +## Features + +- **Elm Architecture** - Model-Update-View pattern for predictable state management +- **Rich Styling** - Comprehensive styling system with colors, borders, padding, margin backgrounds, per-side border colors, tab width control, style ranges, full style inheritance, text transforms, whitespace formatting controls, and unset methods +- **34+ Pre-built Components** - TextInput (with autocomplete/word movement), TextArea, List (fuzzy filtering), Table (interactive with row selection), SortableTable (column sorting, filtering), Viewport, VirtualList (lazy rendering for 100K+ items), Progress (color gradients), Gauge (bar, level meter, blocks with thresholds), Spinner, Tree, StyledList, Sparkline, Chart (linear, stepped, smoothed, area, scatter), BarChart, Heatmap (4 color scales), Canvas, Calendar/DatePicker, CodeView (syntax highlighting for 5 languages), DiffView (unified and side-by-side), Notification/Toast, Confirm dialog, Modal/Popup, Tooltip, Help, Paginator, Timer, FilePicker, TabGroup (multi-view routing), Form, Markdown, Dropdown, Checkbox/RadioGroup, Slider, MenuBar, ContextMenu +- **Focus Management** - `FocusGroup` with Tab/Shift+Tab cycling, comptime focusable protocol, `FocusStyle` for visual focus ring indicators +- **Keybinding Management** - Structured `KeyBinding`/`KeyMap` with matching, display formatting, and Help component integration +- **Color System** - ANSI 16, 256, and TrueColor with adaptive colors, color profile detection, and dark background detection +- **Command System** - Quit, tick, repeating tick (`every`), batch, sequence, suspend/resume, runtime terminal control (mouse, cursor, alt screen, title), print above program, comprehensive image rendering, AsyncRunner for background tasks +- **Sub-Programs** - Embed independent child models inside a parent with message routing and lifecycle management +- **Text Overflow** - Configurable overflow policies (hidden, ellipsis, word_wrap, char_wrap) integrated into the Style system +- **Image Rendering** - Kitty/iTerm2/Sixel with in-memory data, file paths, image caching (transmit once, display many), z-index layering, unicode placeholders for text reflow, protocol override, and file validation +- **Custom I/O** - Pipe-friendly with configurable input/output streams for testing and automation +- **Kitty Keyboard Protocol** - Modern keyboard handling with key release events and unambiguous key identification +- **Bracketed Paste** - Paste events delivered as a single message instead of individual keystrokes +- **Debug Logging** - File-based timestamped logging since stdout is owned by the renderer +- **Message Filtering** - Intercept and transform messages before they reach your model +- **ANSI Compression** - Reduce output overhead with diff-based style state tracking and redundant sequence elimination +- **Layout** - Horizontal/vertical joining, ANSI-aware measurement, 2D placement, float-based positioning, horizontal/vertical single-axis placement, overlay compositing, constraint-based Flexbox engine (fixed, percentage, min, max, ratio, fill), layer compositing with z-ordering +- **Cross-platform** - Works on macOS, Linux, and Windows +- **Zero Dependencies** - Pure Zig with no external dependencies + +## Installation + +Add ZigZag to your `build.zig.zon`: +```sh +zig fetch --save git+https://github.com/meszmate/zigzag#main +``` + +Then in your `build.zig`: + +```zig +const zigzag = b.dependency("zigzag", .{ + .target = target, + .optimize = optimize, +}); +exe.root_module.addImport("zigzag", zigzag.module("zigzag")); +``` + +## Quick Start + +```zig +const std = @import("std"); +const zz = @import("zigzag"); + +const Model = struct { + count: i32, + + pub const Msg = union(enum) { + key: zz.KeyEvent, + }; + + pub fn init(self: *Model, _: *zz.Context) zz.Cmd(Msg) { + self.* = .{ .count = 0 }; + return .none; + } + + pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { + switch (msg) { + .key => |k| switch (k.key) { + .char => |c| if (c == 'q') return .quit, + .up => self.count += 1, + .down => self.count -= 1, + else => {}, + }, + } + return .none; + } + + pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { + const style = (zz.Style{}).bold(true).fg(.cyan); + const text = std.fmt.allocPrint(ctx.allocator, "Count: {d}\n\nPress q to quit", .{self.count}) catch "Error"; + return style.render(ctx.allocator, text) catch text; + } +}; + +pub fn main(init: std.process.Init) !void { + var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); + defer program.deinit(); + try program.run(); +} +``` + +## Core Concepts + +### The Elm Architecture + +ZigZag uses the Elm Architecture (Model-Update-View): + +1. **Model** - Your application state +2. **Msg** - Messages that describe state changes +3. **init** - Initialize your model +4. **update** - Handle messages and update state +5. **view** - Render your model to a string + +### Commands + +Commands let you perform side effects: + +```zig +return .quit; // Quit the application +return .none; // Do nothing +return .{ .tick = ns }; // Request a tick after `ns` nanoseconds +return Cmd(Msg).everyMs(16); // Repeating tick every 16ms (~60fps) +return Cmd(Msg).tickMs(1000); // One-shot tick after 1 second +return .suspend_process; // Suspend (like Ctrl+Z) +return .enable_mouse; // Enable mouse tracking at runtime +return .disable_mouse; // Disable mouse tracking +return .show_cursor; // Show terminal cursor +return .hide_cursor; // Hide terminal cursor +return .{ .set_title = "My App" }; // Set terminal window title +return .{ .println = "Log message" }; // Print above the program output +return .{ .image_file = .{ // Draw image via Kitty/iTerm2/Sixel when available + .path = "assets/cat.png", + .width_cells = 40, + .height_cells = 20, + .placement = .center, // .cursor, .top_left, .top_center, .center + .row_offset = -6, // Negative = higher, positive = lower + .col_offset = 0, // Negative = left, positive = right + // .row = 2, .col = 10, // Optional absolute position override + .move_cursor = false, // Helpful for iTerm2 placement + .protocol = .auto, // .auto, .kitty, .iterm2, .sixel + .z_index = -1, // Kitty: render behind text + .unicode_placeholder = false, // Kitty: participate in text reflow +} }; +return .{ .image_data = .{ // Draw in-memory image data + .data = png_bytes, // Raw RGB, RGBA, or PNG bytes + .format = .png, // .rgb, .rgba, .png + .pixel_width = 100, // Required for RGB/RGBA + .pixel_height = 100, + .width_cells = 20, + .height_cells = 10, + .placement = .center, +} }; +return .{ .cache_image = .{ // Upload to Kitty cache (transmit once) + .source = .{ .file = "assets/logo.png" }, + .image_id = 1, +} }; +return .{ .place_cached_image = .{ // Display cached image (no re-upload) + .image_id = 1, + .placement = .center, + .width_cells = 20, + .height_cells = 10, +} }; +return .{ .delete_image = .{ .by_id = 1 } }; // Free cached image +return .{ .delete_image = .all }; // Free all cached images +``` + +### Styling + +The styling system is inspired by Lipgloss: + +```zig +const style = (zz.Style{}) + .bold(true) + .italic(true) + .fg(.cyan) + .bg(.black) + .paddingAll(1) + .marginAll(2) + .marginBackground(.gray(3)) + .borderAll(.rounded) + .borderForeground(.magenta) + .borderTopForeground(.cyan) // Per-side border colors + .borderBottomForeground(.green) + .tabWidth(4) + .width(40) + .alignH(.center); + +const output = try style.render(allocator, "Hello, World!"); +// render() does not append an implicit trailing '\n' + +// Text transforms +const upper_style = (zz.Style{}).transform(.uppercase); +const shouting = try upper_style.render(allocator, "hello"); // "HELLO" + +// Inline mode is useful when embedding block-styled output in a single line +const inline = (zz.Style{}).fg(.cyan).inline_style(true); + +// Whitespace formatting controls +const ws_style = (zz.Style{}) + .underline(true) + .setUnderlineSpaces(true) // Underline extends through spaces + .setColorWhitespace(false); // Don't apply bg color to whitespace + +// Unset individual properties +const derived = style.unsetBold().unsetPadding().unsetBorder(); + +// Style inheritance (unset values inherit from parent) +const child = (zz.Style{}).fg(.red).inherit(style); + +// Style ranges - apply different styles to byte ranges +const ranges = &[_]zz.StyleRange{ + .{ .start = 0, .end = 5, .s = (zz.Style{}).bold(true) }, +}; +const ranged = try zz.renderWithRanges(allocator, "Hello World", ranges); + +// Highlight specific positions (for fuzzy match results) +const highlighted = try zz.renderWithHighlights(allocator, "hello", &.{0, 2}, highlight_style, base_style); +``` + +### Colors + +```zig +// Basic ANSI colors +zz.Color.red +zz.Color.cyan +zz.Color.brightGreen + +// 256-color palette +zz.Color.color256(123) +zz.Color.gray(15) // 0-23 grayscale + +// True color (24-bit) +zz.Color.fromRgb(255, 128, 64) +zz.Color.hex("#FF8040") + +// Adaptive colors (change based on terminal capabilities) +const adaptive = zz.AdaptiveColor{ + .true_color = .hex("#FF8040"), + .color_256 = .color256(208), + .ansi = .red, +}; +const resolved = adaptive.resolve(ctx.true_color, ctx.color_256); + +// Color profile detection (automatic via context) +// ctx.color_profile: .ascii, .ansi, .ansi256, .true_color +// ctx.is_dark_background: bool + +// Color interpolation (for gradients) +const mid = zz.interpolateColor(.red, .green, 0.5); +``` + +### Borders + +```zig +zz.Border.normal // ┌─┐ +zz.Border.rounded // ╭─╮ +zz.Border.double // ╔═╗ +zz.Border.thick // ┏━┓ +zz.Border.ascii // +-+ +zz.Border.block // ███ +zz.Border.dashed // ┌╌┐ +zz.Border.dotted // ┌┈┐ +zz.Border.inner_half_block // ▗▄▖ +zz.Border.outer_half_block // ▛▀▜ +zz.Border.markdown // |-| +``` + +## Components + +### TextInput + +Single-line text input with cursor, validation, autocomplete, and word-level movement: + +```zig +var input = zz.TextInput.init(allocator); +input.setPlaceholder("Enter name..."); +input.setPrompt("> "); +input.setSuggestions(&.{ "hello", "help", "world" }); // Tab to accept +// Supports: Alt+Left/Right for word movement, Ctrl+W delete word +input.handleKey(key_event); +const view = try input.view(allocator); +``` + +### TextArea + +Multi-line text editor: + +```zig +var editor = zz.components.TextArea.init(allocator); +editor.setSize(80, 24); +editor.line_numbers = true; +editor.handleKey(key_event); +``` + +### List + +Selectable list with fuzzy filtering and status bar: + +```zig +var list = zz.List(MyItem).init(allocator); +list.multi_select = true; +list.show_item_count = true; // Shows "3/10 items" +try list.addItem(.init(item, "Item 1")); +// Fuzzy filtering: press / to filter, matches score by consecutive chars +list.handleKey(key_event); +``` + +### Viewport + +Scrollable content area with wrapping, horizontal scrolling, customizable scrollbar chars/styles, and built-in navigation keys (`j/k/h/l`, arrows, `PgUp/PgDn`, `g/G`, `d/u`): + +```zig +var viewport = zz.Viewport.init(allocator, 80, 24); +try viewport.setContent(long_text); +viewport.setWrap(true); +viewport.setScrollbarChars("·", "█"); +viewport.setScrollbarStyle( + (zz.Style{}).fg(.gray(8)).inline_style(true), + (zz.Style{}).fg(.cyan).inline_style(true), +); +viewport.handleKey(key_event); // Supports j/k, Page Up/Down, etc. +``` + +### Progress + +Progress bar with optional color gradients: + +```zig +var progress = zz.Progress.init(); +progress.setWidth(40); +progress.setGradient(.hex("#FF6B6B"), .hex("#4ECDC4")); +progress.setPercent(75); +const bar = try progress.view(allocator); +``` + +### Spinner + +Animated loading indicator: + +```zig +var spinner = zz.Spinner.init(); +spinner.update(elapsed_ns); +const view = try spinner.viewWithTitle(allocator, "Loading..."); +``` + +### Table + +Interactive tabular data display with row selection and navigation: + +```zig +var table = zz.Table(3).init(allocator); +table.setHeaders(.{ "Name", "Age", "City" }); +try table.addRow(.{ "Alice", "30", "NYC" }); +try table.addRow(.{ "Bob", "25", "LA" }); +table.focus(); // Enable interactive mode +table.show_row_borders = true; // Horizontal separators between rows +// Supports: j/k, up/down, pgup/pgdown, g/G for navigation +table.handleKey(key_event); +const selected = table.selectedRow(); // Get highlighted row index +``` + +### Tree + +Hierarchical tree view with customizable enumerators: + +```zig +var tree = zz.Tree(void).init(allocator); +const root = try tree.addRoot({}, "project/"); +const src = try tree.addChild(root, {}, "src/"); +_ = try tree.addChild(src, {}, "main.zig"); +const view = try tree.view(allocator); +// Output: +// project/ +// └── src/ +// └── main.zig +``` + +### StyledList + +Rendering list with enumerators (bullet, arabic, roman, alphabet): + +```zig +var list = zz.StyledList.init(allocator); +list.setEnumerator(.roman); +try list.addItem("First item"); +try list.addItem("Second item"); +try list.addItemNested("Sub-item", 1); +// Output: +// I. First item +// II. Second item +// I. Sub-item +``` + +### Sparkline + +Mini chart using Unicode block elements with configurable bucketing, ranges, and gradients: + +```zig +var spark = zz.Sparkline.init(allocator); +spark.setWidth(20); +spark.setSummary(.average); +spark.setGradient(.hex("#F97316"), .hex("#22C55E")); +try spark.push(10.0); +try spark.push(25.0); +try spark.push(15.0); +const chart = try spark.view(allocator); +``` + +### Chart + +Cartesian chart with multiple datasets, axes, grid lines, legends, selectable markers, and interpolation modes (`linear`, stepped, `catmull_rom`, `monotone_cubic`): + +Charts are passive views over your data. They do not animate on their own; they only change when your model updates the dataset. `zig build run-charts` and the `Charts` tab in `zig build run-showcase` demonstrate both static snapshot charts and slower sampled/live updates. The standalone `run-charts` demo now renders as a compact chart dashboard that fits like the other examples instead of behaving like a scrollable document. + +![Charts Example](assets/charts.jpg) + +```zig +var chart = zz.Chart.init(allocator); +chart.setSize(48, 16); +chart.setMarker(.braille); +chart.x_axis = .{ .title = "Time", .tick_count = 5, .show_grid = true }; +chart.y_axis = .{ .title = "CPU", .tick_count = 5, .show_grid = true }; + +var dataset = try zz.ChartDataset.init(allocator, "load"); +dataset.setStyle((zz.Style{}).fg(.cyan).bold(true)); +dataset.setShowPoints(true); +dataset.setInterpolation(.monotone_cubic); +dataset.setInterpolationSteps(10); +try dataset.setPoints(&.{ + .{ .x = 0, .y = 20 }, + .{ .x = 1, .y = 45 }, + .{ .x = 2, .y = 30 }, +}); +try chart.addDataset(dataset); + +const view = try chart.view(allocator); +``` + +### BarChart + +Vertical or horizontal bar chart with labels, values, and positive/negative baselines: + +```zig +var bars = zz.BarChart.init(allocator); +bars.setOrientation(.horizontal); +bars.show_values = true; +try bars.addBar(try .init(allocator, "api", 31)); +try bars.addBar(try .init(allocator, "db", -12)); +const view = try bars.view(allocator); +``` + +### Canvas + +Low-level plotting canvas for custom graphs, scatter plots, and braille-dot drawing: + +```zig +var canvas = zz.Canvas.init(allocator); +defer canvas.deinit(); + +canvas.setSize(24, 10); +canvas.setMarker(.braille); +canvas.setRanges(.{ .min = -1, .max = 1 }, .{ .min = -1, .max = 1 }); +try canvas.drawLineStyled(-1, -1, 1, 1, (zz.Style{}).fg(.yellow), null); +try canvas.drawPointStyled(0.25, 0.7, (zz.Style{}).fg(.cyan), null); +const view = try canvas.view(allocator); +``` + +### Notification/Toast + +Auto-dismissing timed messages with severity levels: + +```zig +var notifs = zz.Notification.init(allocator); +try notifs.push("Build complete!", .success, 3000, current_ns); +notifs.update(current_ns); // Removes expired notifications +const view = try notifs.view(allocator); +``` + +### Confirm + +Simple yes/no confirmation dialog: + +```zig +var confirm = zz.Confirm.init("Are you sure?"); +confirm.show(); +confirm.handleKey(key_event); // Left/Right, Enter, y/n +if (confirm.result()) |yes| { + if (yes) { /* confirmed */ } +} +``` + +### Modal + +Dialog overlay with buttons, backdrop, and focus support: + +```zig +var modal = zz.Modal.info("Notice", "Operation completed successfully."); +modal.show(); + +// In update: +modal.handleKey(key_event); +if (modal.getResult()) |res| { + switch (res) { + .button_pressed => |idx| { /* button at idx was pressed */ }, + .dismissed => { /* user pressed Escape */ }, + } +} + +// In view: +if (modal.isVisible()) { + return modal.viewWithBackdrop(allocator, ctx.width, ctx.height); +} +``` + +Presets: `Modal.info()`, `Modal.confirm()`, `Modal.warning()`, `Modal.err()`, or `Modal.init()` for full custom. + +### Tooltip + +Contextual hint positioned near a target element with cell-based overlay compositing: + +```zig +var tip = zz.Tooltip.init("Save the current document"); +tip.target_x = 10; +tip.target_y = 5; +tip.placement = .bottom; // .top, .bottom, .left, .right +tip.show(); + +// In view — overlays onto existing content: +if (tip.isVisible()) { + return tip.overlay(allocator, base_view, ctx.width, ctx.height); +} +``` + +Presets: `Tooltip.init(text)`, `Tooltip.titled(title, text)`, `Tooltip.help(text)`, `Tooltip.shortcut(label, key)`. Supports `border_bg`, `arrow_bg`, `content_bg`, and `inherit_bg` for full background control. + +### TabGroup + +Multi-screen tab navigation with fully customizable keymaps, styles, and optional per-tab route callbacks: + +```zig +var tabs = zz.TabGroup.init(allocator); +defer tabs.deinit(); + +tabs.show_numbers = true; +tabs.max_width = 60; // overflow-aware tab strip +tabs.overflow_mode = .scroll; // .none, .clip, .scroll +tabs.activate_on_focus = true; // set false for manual activation + +_ = try tabs.addTab(.{ .id = "home", .title = "Home" }); +_ = try tabs.addTab(.{ .id = "logs", .title = "Logs", .enabled = false }); +_ = try tabs.addTab(.{ .id = "settings", .title = "Settings" }); + +// In update: +const result = tabs.handleKey(key_event); // Left/Right, Home/End, 1..9 by default +_ = result.change; // optional active-tab change info + +// Optional: route unconsumed keys to active tab callback +const routed = tabs.handleKeyAndRoute(key_event).routed; +_ = routed; + +// In view: +const strip = try tabs.view(allocator); +const with_content = try tabs.viewWithContent(allocator, "No active tab"); +``` + +Per-tab route callback hooks: `render_fn`, `key_fn`, `on_enter_fn`, `on_leave_fn`. + +### Gauge + +Visual meter with bar, level meter, and block display styles: + +```zig +var gauge = zz.Gauge{}; +gauge.value = 73.5; +gauge.width = 40; +gauge.display_style = .bar; // .bar, .level_meter, .blocks +gauge.show_percent = true; +gauge.label = "CPU"; +gauge.full_char = "\xe2\x96\x88"; // Customizable fill character +gauge.empty_char = "\xe2\x96\x91"; // Customizable empty character +gauge.thresholds = &.{ + .{ .value = 80, .color = .yellow }, + .{ .value = 90, .color = .red }, +}; +const output = gauge.view(allocator); +``` + +### Heatmap + +2D data visualization with configurable color scales: + +```zig +var heatmap = zz.Heatmap.init(allocator); +heatmap.setData(7, 24, data); +heatmap.row_labels = &.{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; +heatmap.color_scale = .green_scale; // .green_scale, .cool_to_hot, .grayscale, .blue_red +heatmap.cell_width = 3; +heatmap.show_legend = true; +heatmap.show_values = true; +const output = heatmap.view(allocator); +``` + +### Calendar + +Month view date picker with keyboard navigation: + +```zig +var cal = zz.Calendar{}; +cal.year = 2026; +cal.month = 3; +cal.today_day = 30; +cal.today_month = 3; +cal.today_year = 2026; +cal.cell_width = 4; // Column width for alignment +cal.week_start_monday = true; +cal.day_headers_mon = .{ "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" }; // Customizable +cal.month_names = .{ "Jan", "Feb", ... }; // Customizable +cal.prev_symbol = "\xe2\x97\x80"; // Customizable nav symbols +cal.addMarkedDate(25, .red); +cal.update(key_event); // Arrows, Enter, PgUp/PgDn, Shift+L/R +const output = cal.view(allocator); +``` + +### VirtualList + +Efficient lazy-rendered list for large datasets (100K+ items): + +```zig +var vlist = zz.components.virtual_list.VirtualList(usize){}; +vlist.items = &huge_dataset; +vlist.viewport_height = 20; +vlist.render_fn = &myRenderFn; +vlist.wrap_around = true; // Cursor wraps at ends +vlist.empty_text = "No items"; // Custom empty state +vlist.cursor_symbol = "> "; // Customizable +vlist.show_scrollbar = true; +vlist.update(key_event); +const output = vlist.view(allocator); +``` + +### SortableTable + +Table with column sorting and text filtering: + +```zig +var table = zz.components.sortable_table.SortableTable(4).init(allocator); +table.setHeaders(.{ "Name", "Role", "City", "Score" }); +try table.addRow(.{ "Alice", "Engineer", "NYC", "95" }); +// Press 1-4 to sort by column, / to filter +table.update(key_event); +const output = table.view(allocator); +``` + +### CodeView + +Syntax-highlighted code display: + +```zig +var cv = zz.components.code_view.CodeView{}; +cv.source = source_code; +cv.language = .zig; // .zig, .python, .javascript, .go, .rust, .plain +cv.show_line_numbers = true; +cv.highlight_line = 5; // Highlight a specific line +cv.line_separator = "\xe2\x94\x82"; // Customizable separator +// All token styles are customizable: keyword_style, string_style, +// comment_style, number_style, type_style, builtin_style +const output = cv.view(allocator); +``` + +### DiffView + +Unified and side-by-side diff display: + +```zig +var dv = zz.components.diff_view.DiffView{}; +dv.old_text = old_source; +dv.new_text = new_source; +dv.old_label = "before"; +dv.new_label = "after"; +dv.mode = .unified; // .unified, .side_by_side +dv.side_width = 40; // Width per side in side-by-side mode +dv.add_prefix = "+"; // Customizable prefixes +dv.remove_prefix = "-"; +const output = dv.view(allocator); +``` + +### SubProgram + +Embed independent child models inside a parent: + +```zig +const Counter = struct { ... }; // Has Msg, init, update, view + +const Model = struct { + child: zz.SubProgram(Counter, Msg), + // ... + pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { + self.child = .{}; + _ = self.child.init(ctx); + } + pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) { + return self.child.update(.{ .key = k }, ctx); + } + pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { + return self.child.view(ctx); + } +}; +``` + +### AsyncRunner + +Spawn background tasks that deliver messages on completion: + +```zig +var runner = zz.AsyncRunner(Msg).init(allocator); +_ = runner.spawn(&myBackgroundTask); // Returns task ID +// Each frame: +const results = runner.poll(); // Collect completed messages +for (results) |msg| { /* process */ } +``` + +### Flexbox Layout + +Constraint-based layout engine: + +```zig +const areas = try zz.flex.layout(allocator, width, height, &.{ + .{ .constraint = .{ .fixed = 3 } }, // Header: 3 rows + .{ .constraint = .fill }, // Body: remaining space + .{ .constraint = .{ .percentage = 10 } }, // Footer: 10% +}, .{ .direction = .column, .gap = 1 }); +// areas[0].x, areas[0].y, areas[0].width, areas[0].height +``` + +Constraints: `fixed(n)`, `percentage(pct)`, `min(n)`, `max(n)`, `ratio(num, den)`, `fill`. Options: direction, gap, alignment, justify, wrap. + +### Layer Compositing + +Z-ordered overlay system for popups and modals: + +```zig +var stack = zz.layout.layer.LayerStack.init(allocator); +stack.setSize(width, height); +stack.push(.{ .content = background, .z = 0 }) catch {}; +stack.push(.{ .content = popup, .x = 10, .y = 5, .z = 10 }) catch {}; +const output = stack.render(allocator); +``` + +### Text Overflow + +Integrated into the Style system: + +```zig +var s = zz.Style{}; +s = s.width(40); +s = s.overflow(.ellipsis); // .visible, .hidden, .ellipsis, .word_wrap, .char_wrap +const output = try s.render(allocator, long_text); +``` + +### More Components + +- **Help** - Display key bindings with responsive truncation +- **Paginator** - Pagination controls +- **Timer** - Countdown/stopwatch with warning thresholds +- **FilePicker** - File system navigation + +### Keybinding Management + +Structured key binding definitions with matching and Help integration: + +```zig +var keymap = zz.KeyMap.init(allocator); +defer keymap.deinit(); + +try keymap.addChar('q', "Quit"); +try keymap.addCtrl('s', "Save"); +try keymap.add(.{ + .key_event = zz.KeyEvent{ .key = .up }, + .description = "Move up", + .short_desc = "up", +}); + +// Check if a key event matches any binding +if (keymap.match(key_event)) |binding| { + // Handle the matched binding + _ = binding.description; +} + +// Generate help text from keybindings +var help = try zz.components.Help.fromKeyMap(allocator, &keymap); +defer help.deinit(); +const help_view = try help.view(allocator); +``` + +### Focus Management + +Manage Tab/Shift+Tab cycling between interactive components with `FocusGroup`: + +```zig +const Model = struct { + name: zz.TextInput, + email: zz.TextInput, + focus: zz.FocusGroup(2), + focus_style: zz.FocusStyle, + + pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { + self.name = zz.TextInput.init(ctx.persistent_allocator); + self.email = zz.TextInput.init(ctx.persistent_allocator); + + self.focus = .{}; + self.focus.add(&self.name); // index 0 + self.focus.add(&self.email); // index 1 + self.focus.initFocus(); // focus first, blur rest + + self.focus_style = .{}; // cyan/gray borders by default + return .none; + } + + pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { + switch (msg) { + .key => |k| { + // Tab/Shift+Tab cycles focus (returns true if consumed) + if (self.focus.handleKey(k)) return .none; + // Forward to all — unfocused components auto-ignore + self.name.handleKey(k); + self.email.handleKey(k); + }, + } + return .none; + } + + pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { + // Apply focus ring (border color changes based on focus) + var style = zz.Style{}; + style = style.paddingAll(1); + const name_style = self.focus_style.apply(style, self.focus.isFocused(0)); + const email_style = self.focus_style.apply(style, self.focus.isFocused(1)); + // ... render with styled boxes ... + } +}; +``` + +Any component with `focused: bool`, `focus()`, and `blur()` methods works with `FocusGroup`. +Built-in focusable components: TextInput, TextArea, Table, List, Confirm, FilePicker. + +#### Custom navigation keys + +By default Tab moves forward and Shift+Tab moves backward. Add or replace bindings freely: + +```zig +// Add arrow keys and vim j/k alongside the default Tab +fg.addNextKey(.{ .key = .down }); // Down arrow +fg.addNextKey(.{ .key = .{ .char = 'j' } }); // vim j +fg.addPrevKey(.{ .key = .up }); // Up arrow +fg.addPrevKey(.{ .key = .{ .char = 'k' } }); // vim k + +// Or replace defaults entirely +fg.setNextKey(.{ .key = .down }); // Down only, Tab no longer works +fg.setPrevKey(.{ .key = .up }); // Up only + +// Clear all bindings (manual-only via focusNext/focusPrev) +fg.clearNextKeys(); +fg.clearPrevKeys(); + +// Modifier keys work too +fg.addNextKey(.{ .key = .{ .char = 'n' }, .modifiers = .{ .ctrl = true } }); // Ctrl+N +``` + +Up to 4 bindings per direction. Modifier matching is exact (Ctrl+Tab won't match a plain Tab binding). + +#### Additional API + +```zig +fg.focusAt(2); // Focus specific index +fg.focusNext(); // Manual next +fg.focusPrev(); // Manual prev +fg.blurAll(); // Remove focus from all +fg.focused(); // Get current index +fg.isFocused(1); // Check if index is focused +fg.len(); // Number of registered items + +// Disable wrapping (stop at ends instead of cycling) +var fg: zz.FocusGroup(3) = .{ .wrap = false }; + +// Custom focus ring colors +const fs = zz.FocusStyle{ + .focused_border_fg = .green, + .blurred_border_fg = .gray(8), + .border_chars = .double, +}; +``` + +## Options + +Configure the program with custom options: + +```zig +var program = try zz.Program(Model).initWithOptions(init.gpa, init.io, init.environ_map, .{ + .fps = 60, // Target frame rate + .alt_screen = true, // Use alternate screen buffer + .mouse = false, // Enable mouse tracking + .cursor = false, // Show cursor + .bracketed_paste = true, // Enable bracketed paste mode + .kitty_keyboard = false, // Enable Kitty keyboard protocol + .osc52 = .{ // OSC 52 clipboard defaults + .enabled = true, + .query_enabled = true, // Allow OSC 52 clipboard reads (query) + .target = .clipboard, // .primary, .secondary, .select, .cut_buffer, .raw + .terminator = .bel, // .bel or .st + .passthrough = .auto, // .auto, .none, .tmux, .dcs + .max_bytes = null, // Optional write payload limit + .query_timeout_ms = 180, + .max_read_bytes = null, // Optional decoded read limit + .strict_query_target = false, + }, + .unicode_width_strategy = null, // null=auto, .legacy_wcwidth, .unicode + .suspend_enabled = true, // Enable Ctrl+Z suspend/resume + .title = "My App", // Window title + .log_file = "debug.log", // Debug log file path + .input = custom_stdin, // Custom input (for testing/piping) + .output = custom_stdout, // Custom output (for testing/piping) +}); +``` + +Unicode width strategy can also be overridden per-process with `ZZ_UNICODE_WIDTH=auto|legacy|unicode`. +By default (`null`/`auto`), ZigZag: +- probes DEC mode `2027` and enables it when available, +- probes kitty text-sizing support, +- applies terminal/multiplexer heuristics (e.g. tmux/screen/zellij favor legacy width). + +### Allocator Lifetimes + +`ctx.allocator` is a frame allocator that is reset before each `tick()`. +Use it for temporary values (render strings, per-frame buffers). + +For model state that must live across frames, allocate with `ctx.persistent_allocator`. + +### Custom Event Loop + +For applications that need to do other work between frames (network polling, background processing, etc.), use `start()` + `tick()` instead of `run()`: + +```zig +var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); +defer program.deinit(); + +try program.start(); +while (program.isRunning()) { + try program.tick(); + // poll sockets, process jobs, etc. +} +``` + +### Debug Logging + +Since stdout is owned by the renderer, use file-based logging: + +```zig +// In your update function, log via context: +pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) { + ctx.log("received key: {s}", .{@tagName(msg)}); + // ... +} +``` + +### Message Filtering + +Intercept and transform messages before they reach your model: + +```zig +var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); +program.setFilter(&myFilter); + +fn myFilter(msg: Model.Msg) ?Model.Msg { + // Return null to drop the message, or modify it + return msg; +} +``` + +### Bracketed Paste + +Handle pasted text as a single event by adding a `paste` field to your Msg: + +```zig +pub const Msg = union(enum) { + key: zz.KeyEvent, + paste: []const u8, // Receives full pasted text +}; +``` + +### OSC 52 Clipboard (Copy + Query) + +Copy text/bytes to the system clipboard from your app: + +```zig +// Uses Program option defaults (.osc52) +_ = try ctx.setClipboard("Copied from ZigZag"); +``` + +Query clipboard bytes back from the terminal: + +```zig +if (try ctx.getClipboard(ctx.allocator)) |clip| { + // clip is decoded bytes from OSC 52 response +} +``` + +Per-call overrides for edge cases: + +```zig +_ = try ctx.setClipboardWithOptions("Primary selection", .{ + .target = .primary, + .terminator = .st, + .passthrough = .tmux, + .max_bytes = 64 * 1024, +}); + +if (try ctx.getClipboardWithOptions(ctx.allocator, .{ + .target = .clipboard, + .timeout_ms = 250, + .passthrough = .auto, + .strict_target = true, +})) |clip| { + _ = clip; +} +``` + +Advanced/extension example (non-standard selector string): + +```zig +_ = try ctx.setClipboardWithOptions("Custom selector", .{ + .target = .{ .raw = "c" }, +}); +``` + +Notes: +- Returns `false` when disabled (`.osc52.enabled = false`), blocked by guardrails (TTY/size), or unavailable in current output mode. +- Query returns `null` when disabled/blocked/timed out/no response/invalid payload. +- `.passthrough = .auto` detects tmux/screen-like environments and wraps OSC 52 in DCS passthrough when needed. +- Terminals differ in security policy and maximum accepted sequence length. Use `.max_bytes` to enforce an app-side ceiling if desired. +- The `run-clipboard_osc52` example also handles `Msg.paste` (bracketed paste input) to demonstrate inbound paste events. + +### Suspend/Resume + +Ctrl+Z support is enabled by default. Handle resume events by adding a `resumed` field: + +```zig +pub const Msg = union(enum) { + key: zz.KeyEvent, + resumed: void, // Sent after process resumes from Ctrl+Z +}; +``` + +### Images (Kitty + iTerm2 + Sixel) + +Image commands are automatically no-ops on unsupported terminals. All `draw*` functions return `bool` indicating success. + +#### Basic usage + +```zig +// Draw from file (auto-selects best protocol) +if (ctx.supportsImages()) { + _ = try ctx.drawImageFromFile("assets/cat.png", .{ + .width_cells = 40, + .height_cells = 20, + }); +} + +// Draw from file with specific protocol +_ = try ctx.drawImageFromFileWithProtocol("assets/cat.png", .{ + .width_cells = 40, + .z_index = -1, // Behind text (Kitty only) +}, .kitty); +``` + +#### In-memory image data + +Render raw pixels or PNG bytes directly from memory, without writing to disk: + +```zig +// Draw PNG bytes from memory +_ = try ctx.drawImageData(png_bytes, .{ + .format = .png, + .width_cells = 20, + .height_cells = 10, +}); + +// Draw raw RGBA pixels +_ = try ctx.drawImageData(rgba_pixels, .{ + .format = .rgba, + .pixel_width = 100, // Required for RGB/RGBA + .pixel_height = 100, + .width_cells = 20, +}); +``` + +#### Image caching (Kitty) + +Transmit an image once, display it many times without re-uploading: + +```zig +// Upload to cache (no display) +_ = try ctx.transmitKittyImageFromFile("assets/logo.png", .{ + .image_id = 1, +}); + +// Display cached image at different positions +_ = try ctx.placeKittyImage(.{ + .image_id = 1, + .width_cells = 10, + .height_cells = 5, +}); + +// Clean up when done +_ = try ctx.deleteKittyImage(.{ .by_id = 1 }); +_ = try ctx.deleteKittyImage(.all); // Delete everything +``` + +#### Z-index and unicode placeholders (Kitty) + +```zig +// Render image behind text +_ = try ctx.drawKittyImageFromFile("assets/bg.png", .{ + .z_index = -1, // Negative = behind text + .unicode_placeholder = true, // Image participates in text reflow/scrolling +}); +``` + +#### Protocol override + +Force a specific protocol instead of auto-selection (Kitty > iTerm2 > Sixel): + +```zig +_ = try ctx.drawImageFromFileWithProtocol("image.png", .{}, .iterm2); +_ = try ctx.drawImageDataWithProtocol(data, .{ .format = .png }, .sixel); +``` + +#### Querying capabilities + +```zig +const caps = ctx.getImageCapabilities(); +// caps.kitty_graphics: bool +// caps.iterm2_inline_image: bool +// caps.sixel: bool + +if (ctx.supportsKittyGraphics()) { /* ... */ } +if (ctx.supportsIterm2InlineImages()) { /* ... */ } +if (ctx.supportsSixel()) { /* ... */ } +``` + +#### Command-based API + +All image operations are also available as commands from `update()`: + +```zig +// File image with all options +return .{ .image_file = .{ + .path = "assets/cat.png", + .placement = .center, + .width_cells = 40, + .protocol = .auto, // .auto, .kitty, .iterm2, .sixel + .z_index = -1, // Behind text (Kitty) + .unicode_placeholder = true, // Text reflow (Kitty) +} }; + +// In-memory data +return .{ .image_data = .{ + .data = png_bytes, + .format = .png, // .rgb, .rgba, .png + .width_cells = 20, +} }; + +// Cache + place workflow +return .{ .batch = &.{ + .{ .cache_image = .{ .source = .{ .file = "logo.png" }, .image_id = 1 } }, + .{ .place_cached_image = .{ .image_id = 1, .placement = .center } }, +} }; + +// Delete cached images +return .{ .delete_image = .{ .by_id = 1 } }; +return .{ .delete_image = .all }; +``` + +#### Detection + +Detection combines runtime protocol probes with terminal feature/env hints: +- Kitty graphics: Kitty query command (`a=q`) for confirmation. +- iTerm2 inline images: `OSC 1337;Capabilities`/`TERM_FEATURES` when available. +- Sixel: iTerm/WezTerm `TERM_FEATURES` (`Sx`) and primary device attributes (`CSI c`, param `4`). + +Common terminals supported by default: +- Kitty and Ghostty via Kitty graphics protocol. +- iTerm2 and WezTerm via `OSC 1337` inline images. +- Sixel-capable terminals (for example xterm with Sixel, mlterm, contour). + +#### Notes + +- File paths are validated before sending; missing files return `false` instead of erroring. +- For iTerm2, large images (>750KB encoded) are sent with multipart `OSC 1337` sequences automatically. +- For Sixel, provide a `.sixel`/`.six` file or a regular image with `img2sixel` in `PATH`. Optional `-w`/`-h` pixel hints are passed through. +- Inside multiplexers (tmux/screen/zellij), image passthrough depends on multiplexer configuration. +- Image caching, z-index, and unicode placeholders are Kitty-specific features; they are silently ignored on other protocols. + +## Layout + +### Join + +Combine multiple strings: + +```zig +// Horizontal (side by side) +const row = try zz.joinHorizontal(allocator, &.{ left, middle, right }); + +// Vertical (stacked) +const col = try zz.joinVertical(allocator, &.{ top, middle, bottom }); +``` + +### Measure + +Get text dimensions (ANSI-aware): + +```zig +const w = zz.width("Hello"); // 5 +const h = zz.height("Line 1\nLine 2"); // 2 +``` + +### Place + +Position content in a bounding box: + +```zig +// 2D placement in a bounding box +const centered = try zz.place.place(allocator, 80, 24, .center, .middle, content); + +// Single-axis horizontal placement +const right_aligned = try zz.placeHorizontal(allocator, 80, .right, content); + +// Single-axis vertical placement +const bottom_aligned = try zz.placeVertical(allocator, 24, .bottom, content); + +// Float-based positioning (0.0 = left/top, 0.5 = center, 1.0 = right/bottom) +const placed = try zz.placeFloat(allocator, 80, 24, 0.75, 0.25, content); +``` + +## Examples + +Run the examples: + +```bash +zig build run-hello_world +zig build run-counter +zig build run-todo_list +zig build run-text_editor +zig build run-file_browser +zig build run-dashboard +zig build run-charts # Static snapshots plus slower sampled chart updates +zig build run-showcase # Multi-tab demo of all features +zig build run-focus_form # Focus management with Tab cycling +zig build run-tabs # TabGroup multi-screen routing +zig build run-clipboard_osc52 # OSC 52 clipboard output demo +zig build run-flex_layout # Flexbox constraint-based layout +zig build run-text_overflow # Overflow policies demo +zig build run-gauge # Gauge component styles +zig build run-heatmap # 2D data heatmap visualization +zig build run-calendar # Calendar date picker +zig build run-virtual_list # 100K item virtual scrolling +zig build run-layers # Z-ordered layer compositing +zig build run-sub_program # Nested sub-program models +zig build run-async_tasks # Background task execution +zig build run-sortable_table # Sortable/filterable table +zig build run-code_view # Syntax-highlighted code +zig build run-diff_view # Unified and side-by-side diff +``` + +## Building + +```bash +# Build the library +zig build + +# Run tests +zig build test + +# Build with optimizations +zig build -Doptimize=ReleaseFast +``` + +## Cross-compilation + +```bash +zig build -Dtarget=x86_64-linux +zig build -Dtarget=aarch64-macos +zig build -Dtarget=x86_64-windows +``` + +## Contributing + +Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. + +## License + +MIT License - see LICENSE file for details. + +## Acknowledgments + +- [Bubble Tea](https://github.com/charmbracelet/bubbletea) - The original Go TUI framework +- [Lipgloss](https://github.com/charmbracelet/lipgloss) - Style definitions for terminal applications +- [The Elm Architecture](https://guide.elm-lang.org/architecture/) - The pattern that inspired it all diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig new file mode 100644 index 0000000..24d73ee --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig @@ -0,0 +1,164 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + // Main library module + const zigzag_mod = b.addModule("zigzag", .{ + .root_source_file = b.path("src/root.zig"), + .target = target, + .optimize = optimize, + }); + + // Examples + const examples = [_][]const u8{ + "hello_world", + "counter", + "todo_list", + "text_editor", + "file_browser", + "dashboard", + "charts", + "showcase", + "focus_form", + "modal", + "tooltip", + "tabs", + "clipboard_osc52", + "theming", + "slider", + "menu_bar", + "checkbox_radio", + "dropdown", + "toast", + "context_menu", + "form", + "markdown", + "animation", + "mouse", + "accessibility", + "wasm_app", + "diff_view", + "code_view", + "sortable_table", + "text_overflow", + "async_tasks", + "sub_program", + "layers", + "virtual_list", + "calendar", + "heatmap", + "gauge", + "flex_layout", + "braille_canvas", + "rich_log", + "screen_stack", + "action_system", + "data_table", + "dev_console", + }; + + for (examples) |example_name| { + const example = b.addExecutable(.{ + .name = example_name, + .root_module = b.createModule(.{ + .root_source_file = b.path(b.fmt("examples/{s}.zig", .{example_name})), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "zigzag", .module = zigzag_mod }, + }, + }), + }); + b.installArtifact(example); + + const run_cmd = b.addRunArtifact(example); + run_cmd.step.dependOn(b.getInstallStep()); + if (b.args) |args| { + run_cmd.addArgs(args); + } + + const run_step = b.step( + b.fmt("run-{s}", .{example_name}), + b.fmt("Run the {s} example", .{example_name}), + ); + run_step.dependOn(&run_cmd.step); + } + + // Tests + const test_files = [_][]const u8{ + "tests/style_tests.zig", + "tests/input_tests.zig", + "tests/layout_tests.zig", + "tests/unicode_tests.zig", + "tests/program_tests.zig", + "tests/focus_tests.zig", + "tests/modal_tests.zig", + "tests/tooltip_tests.zig", + "tests/tab_group_tests.zig", + "tests/chart_tests.zig", + "tests/viewport_tests.zig", + "tests/theme_tests.zig", + "tests/slider_tests.zig", + "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", + "tests/animation_tests.zig", + "tests/accessibility_tests.zig", + "tests/mouse_tests.zig", + }; + + const test_step = b.step("test", "Run unit tests"); + + for (test_files) |test_file| { + const unit_tests = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path(test_file), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "zigzag", .module = zigzag_mod }, + }, + }), + }); + + const run_unit_tests = b.addRunArtifact(unit_tests); + test_step.dependOn(&run_unit_tests.step); + } + + // Also run tests on the main library + const lib_tests = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path("src/root.zig"), + .target = target, + .optimize = optimize, + }), + }); + const run_lib_tests = b.addRunArtifact(lib_tests); + test_step.dependOn(&run_lib_tests.step); + + // WASM library build (for browser-based terminals) + const wasm_step = b.step("wasm", "Build ZigZag as a WASM library"); + + const wasm_target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + }); + + const wasm_lib = b.addLibrary(.{ + .name = "zigzag", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/root.zig"), + .target = wasm_target, + .optimize = .ReleaseSmall, + }), + .linkage = .static, + }); + b.installArtifact(wasm_lib); + wasm_step.dependOn(&wasm_lib.step); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon new file mode 100644 index 0000000..473f6a5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon @@ -0,0 +1,14 @@ +.{ + .name = .zigzag, + .version = "0.1.2", + .fingerprint = 0xdffe16194b187c61, + .minimum_zig_version = "0.16.0", + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + "README.md", + "LICENSE", + }, + .dependencies = .{}, +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig new file mode 100644 index 0000000..04b7853 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig @@ -0,0 +1,169 @@ +//! Accessibility utilities for ZigZag TUI applications. +//! Provides WCAG contrast checking, screen reader announcements, +//! and semantic role annotations for terminal UIs. + +const std = @import("std"); +const Writer = std.Io.Writer; +const Color = @import("style/color.zig").Color; + +/// WCAG 2.1 contrast ratio levels. +pub const ContrastLevel = enum { + /// Fails WCAG minimum requirements (< 3:1) + fail, + /// Passes large text / UI component requirement (>= 3:1) + aa_large, + /// Passes normal text requirement (>= 4.5:1) + aa, + /// Passes enhanced contrast for normal text (>= 7:1) + aaa, +}; + +/// Check the WCAG compliance level for a foreground/background color pair. +pub fn checkContrast(fg: Color, bg: Color) ContrastLevel { + const ratio = fg.contrastRatio(bg); + if (ratio >= 7.0) return .aaa; + if (ratio >= 4.5) return .aa; + if (ratio >= 3.0) return .aa_large; + return .fail; +} + +/// Returns true if the color pair meets WCAG AA for normal text (4.5:1). +pub fn meetsAA(fg: Color, bg: Color) bool { + return fg.contrastRatio(bg) >= 4.5; +} + +/// Returns true if the color pair meets WCAG AAA for normal text (7:1). +pub fn meetsAAA(fg: Color, bg: Color) bool { + return fg.contrastRatio(bg) >= 7.0; +} + +/// Suggest a foreground color (white or black) that has better contrast +/// against the given background. +pub fn suggestForeground(bg: Color) Color { + const white = Color.white; + const black = Color.black; + const white_ratio = white.contrastRatio(bg); + const black_ratio = black.contrastRatio(bg); + return if (white_ratio >= black_ratio) white else black; +} + +/// Semantic roles for UI components, useful for screen reader hints +/// and accessible descriptions. +pub const Role = enum { + button, + checkbox, + radio, + textbox, + listbox, + option, + menu, + menuitem, + dialog, + alert, + status, + progressbar, + slider, + tab, + tabpanel, + tree, + treeitem, + heading, + separator, + tooltip, + form, + list, + listitem, + link, + img, + none, + + /// Get a human-readable label for this role. + pub fn label(self: Role) []const u8 { + return switch (self) { + .button => "button", + .checkbox => "checkbox", + .radio => "radio button", + .textbox => "text field", + .listbox => "list box", + .option => "option", + .menu => "menu", + .menuitem => "menu item", + .dialog => "dialog", + .alert => "alert", + .status => "status", + .progressbar => "progress bar", + .slider => "slider", + .tab => "tab", + .tabpanel => "tab panel", + .tree => "tree", + .treeitem => "tree item", + .heading => "heading", + .separator => "separator", + .tooltip => "tooltip", + .form => "form", + .list => "list", + .listitem => "list item", + .link => "link", + .img => "image", + .none => "", + }; + } +}; + +/// An accessible label attached to a UI element. +pub const AccessibleLabel = struct { + role: Role = .none, + name: []const u8 = "", + description: []const u8 = "", + value: []const u8 = "", + state: []const u8 = "", + + /// Format an accessible description string for screen readers. + pub fn format(self: AccessibleLabel, allocator: std.mem.Allocator) ![]const u8 { + var parts: Writer.Allocating = .init(allocator); + const w = &parts.writer; + + if (self.role != .none) { + try w.writeAll(self.role.label()); + } + + if (self.name.len > 0) { + if (parts.writer.buffered().len > 0) try w.writeAll(": "); + try w.writeAll(self.name); + } + + if (self.value.len > 0) { + if (parts.writer.buffered().len > 0) try w.writeAll(", "); + try w.writeAll(self.value); + } + + if (self.state.len > 0) { + if (parts.writer.buffered().len > 0) try w.writeAll(", "); + try w.writeAll(self.state); + } + + if (self.description.len > 0) { + if (parts.writer.buffered().len > 0) try w.writeAll(" - "); + try w.writeAll(self.description); + } + + return parts.toOwnedSlice(); + } +}; + +/// Generate a terminal announcement using the window title (OSC 0). +/// Some screen readers pick up title changes as announcements. +pub fn announceViaTitle(allocator: std.mem.Allocator, message: []const u8) ![]const u8 { + return std.fmt.allocPrint(allocator, "\x1b]0;{s}\x07", .{message}); +} + +/// Generate a terminal bell (BEL) to alert the user audibly. +pub fn bell() []const u8 { + return "\x07"; +} + +/// Format a progress value as an accessible string. +pub fn progressDescription(allocator: std.mem.Allocator, value: f64, max: f64) ![]const u8 { + const pct = if (max > 0) (value / max) * 100.0 else 0.0; + return std.fmt.allocPrint(allocator, "{d:.0}% complete", .{pct}); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig new file mode 100644 index 0000000..cd47f4d --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig @@ -0,0 +1,289 @@ +//! Bar chart widget with vertical and horizontal layouts. + +const std = @import("std"); +const charting = @import("charting.zig"); +const measure = @import("../layout/measure.zig"); +const join = @import("../layout/join.zig"); +const style_mod = @import("../style/style.zig"); + +pub const Style = style_mod.Style; +pub const DataRange = charting.DataRange; +pub const Orientation = charting.Orientation; +pub const ValueFormatter = charting.ValueFormatter; + +pub const Bar = struct { + allocator: std.mem.Allocator, + label: []const u8, + value: f64, + style: ?Style = null, + glyph: []const u8 = "█", + + pub fn init(allocator: std.mem.Allocator, label: []const u8, value: f64) !Bar { + return .{ + .allocator = allocator, + .label = try allocator.dupe(u8, label), + .value = value, + }; + } + + pub fn deinit(self: *Bar) void { + self.allocator.free(self.label); + } + + pub fn setStyle(self: *Bar, style: Style) void { + self.style = charting.inlineStyle(style); + } + + pub fn setGlyph(self: *Bar, glyph: []const u8) void { + self.glyph = glyph; + } +}; + +pub const BarChart = struct { + allocator: std.mem.Allocator, + width: u16, + height: u16, + orientation: Orientation, + bars: std.array_list.Managed(Bar), + bar_width: u16, + gap: u16, + domain: ?DataRange, + baseline: f64, + show_labels: bool, + show_values: bool, + axis_style: Style, + label_style: Style, + value_style: Style, + positive_style: Style, + negative_style: Style, + formatter: ?ValueFormatter, + + pub fn init(allocator: std.mem.Allocator) BarChart { + return .{ + .allocator = allocator, + .width = 40, + .height = 12, + .orientation = .vertical, + .bars = std.array_list.Managed(Bar).init(allocator), + .bar_width = 2, + .gap = 1, + .domain = null, + .baseline = 0, + .show_labels = true, + .show_values = false, + .axis_style = charting.inlineStyle(Style{}), + .label_style = charting.inlineStyle(Style{}), + .value_style = charting.inlineStyle(Style{}), + .positive_style = charting.inlineStyle(Style{}), + .negative_style = charting.inlineStyle(Style{}), + .formatter = null, + }; + } + + pub fn deinit(self: *BarChart) void { + for (self.bars.items) |*bar| bar.deinit(); + self.bars.deinit(); + } + + pub fn clear(self: *BarChart) void { + for (self.bars.items) |*bar| bar.deinit(); + self.bars.clearRetainingCapacity(); + } + + pub fn addBar(self: *BarChart, bar: Bar) !void { + try self.bars.append(bar); + } + + pub fn setSize(self: *BarChart, width: u16, height: u16) void { + self.width = @max(8, width); + self.height = @max(4, height); + } + + pub fn setOrientation(self: *BarChart, orientation: Orientation) void { + self.orientation = orientation; + } + + pub fn setBarWidth(self: *BarChart, bar_width: u16) void { + self.bar_width = @max(1, bar_width); + } + + pub fn setGap(self: *BarChart, gap: u16) void { + self.gap = gap; + } + + pub fn setDomain(self: *BarChart, domain: ?DataRange) void { + self.domain = if (domain) |d| d.normalized() else null; + } + + pub fn setBaseline(self: *BarChart, baseline: f64) void { + self.baseline = baseline; + } + + pub fn setFormatter(self: *BarChart, formatter: ?ValueFormatter) void { + self.formatter = formatter; + } + + pub fn view(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { + if (self.bars.items.len == 0) return try allocator.dupe(u8, ""); + + return switch (self.orientation) { + .vertical => self.renderVertical(allocator), + .horizontal => self.renderHorizontal(allocator), + }; + } + + fn resolvedDomain(self: *const BarChart) DataRange { + if (self.domain) |domain| return domain.normalized(); + + var min_value = self.baseline; + var max_value = self.baseline; + for (self.bars.items) |bar| { + min_value = @min(min_value, bar.value); + max_value = @max(max_value, bar.value); + } + + const range = DataRange{ .min = min_value, .max = max_value }; + return range.normalized(); + } + + fn renderVertical(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { + const domain = self.resolvedDomain(); + const label_rows: usize = if (self.show_labels) 1 else 0; + const plot_height = @max(@as(usize, 1), @as(usize, self.height) -| label_rows); + const total_slot_width = @as(usize, self.bar_width) + @as(usize, self.gap); + const plot_width = @max(@as(usize, self.width), self.bars.items.len * total_slot_width); + + var buffer = try charting.CellBuffer.init(allocator, plot_width, plot_height); + defer buffer.deinit(); + var owned_values = std.array_list.Managed([]const u8).init(allocator); + defer { + for (owned_values.items) |value| allocator.free(value); + owned_values.deinit(); + } + for (0..plot_height) |y| for (0..plot_width) |x| buffer.setSlice(x, y, " ", null); + + const baseline_row = charting.mapY(self.baseline, domain, plot_height); + for (0..plot_width) |x| buffer.setSlice(x, baseline_row, "─", self.axis_style); + + for (self.bars.items, 0..) |bar, index| { + const start_x = index * total_slot_width; + const end_x = @min(plot_width, start_x + @as(usize, self.bar_width)); + const target_row = charting.mapY(bar.value, domain, plot_height); + const top = @min(target_row, baseline_row); + const bottom = @max(target_row, baseline_row); + const bar_style = bar.style orelse if (bar.value >= self.baseline) self.positive_style else self.negative_style; + + for (top..bottom + 1) |y| { + for (start_x..end_x) |x| { + buffer.setSlice(x, y, bar.glyph, bar_style); + } + } + + if (self.show_values) { + const label = try self.formatValue(allocator, bar.value); + try owned_values.append(label); + const row = if (bar.value >= self.baseline) top -| 1 else @min(plot_height - 1, bottom + 1); + const start = start_x + ((end_x - start_x) -| measure.width(label)) / 2; + buffer.writeText(start, row, label, self.value_style); + } + } + + const plot = try buffer.render(allocator); + defer allocator.free(plot); + if (!self.show_labels) return try allocator.dupe(u8, plot); + + var label_row = try charting.CellBuffer.init(allocator, plot_width, 1); + defer label_row.deinit(); + var owned_labels = std.array_list.Managed([]const u8).init(allocator); + defer { + for (owned_labels.items) |label| allocator.free(label); + owned_labels.deinit(); + } + for (0..plot_width) |x| label_row.setSlice(x, 0, " ", null); + + for (self.bars.items, 0..) |bar, index| { + const start_x = index * total_slot_width; + const label_width = measure.width(bar.label); + const label_start = start_x + (@as(usize, self.bar_width) -| @min(label_width, @as(usize, self.bar_width))) / 2; + const clipped = try truncateLabel(allocator, bar.label, @as(usize, self.bar_width)); + try owned_labels.append(clipped); + label_row.writeText(label_start, 0, clipped, self.label_style); + } + + const labels = try label_row.render(allocator); + defer allocator.free(labels); + return try join.vertical(allocator, .left, &.{ plot, labels }); + } + + fn renderHorizontal(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { + const domain = self.resolvedDomain(); + const label_width = if (self.show_labels) self.maxLabelWidth() else 0; + const label_offset: usize = label_width + (if (label_width > 0) @as(usize, 1) else 0); + const plot_width = @max(@as(usize, 1), @as(usize, self.width) -| label_offset); + const total_slot_height = @as(usize, self.bar_width) + @as(usize, self.gap); + const plot_height = @max(@as(usize, self.height), self.bars.items.len * total_slot_height); + + var buffer = try charting.CellBuffer.init(allocator, label_offset + plot_width, plot_height); + defer buffer.deinit(); + var owned_values = std.array_list.Managed([]const u8).init(allocator); + defer { + for (owned_values.items) |value| allocator.free(value); + owned_values.deinit(); + } + for (0..buffer.height) |y| for (0..buffer.width) |x| buffer.setSlice(x, y, " ", null); + + const offset = label_offset; + const baseline_col = offset + charting.mapX(self.baseline, domain, plot_width); + for (0..plot_height) |y| buffer.setSlice(baseline_col, y, "│", self.axis_style); + + for (self.bars.items, 0..) |bar, index| { + const start_y = index * total_slot_height; + const end_y = @min(plot_height, start_y + @as(usize, self.bar_width)); + const target_col = offset + charting.mapX(bar.value, domain, plot_width); + const left = @min(target_col, baseline_col); + const right = @max(target_col, baseline_col); + const bar_style = bar.style orelse if (bar.value >= self.baseline) self.positive_style else self.negative_style; + + for (start_y..end_y) |y| { + if (self.show_labels and y == start_y) { + buffer.writeText(0, y, bar.label, self.label_style); + } + + for (left..right + 1) |x| { + buffer.setSlice(x, y, bar.glyph, bar_style); + } + + if (self.show_values and y == start_y) { + const value_text = try self.formatValue(allocator, bar.value); + try owned_values.append(value_text); + const text_x = if (bar.value >= self.baseline) + @min(buffer.width - measure.width(value_text), right + 1) + else + @max(offset, left -| (measure.width(value_text) + 1)); + buffer.writeText(text_x, y, value_text, self.value_style); + } + } + } + + return try buffer.render(allocator); + } + + fn maxLabelWidth(self: *const BarChart) usize { + var max_width: usize = 0; + for (self.bars.items) |bar| { + max_width = @max(max_width, measure.width(bar.label)); + } + return max_width; + } + + fn formatValue(self: *const BarChart, allocator: std.mem.Allocator, value: f64) ![]const u8 { + const formatter = self.formatter orelse charting.defaultFormatter; + return try formatter(allocator, value); + } +}; + +fn truncateLabel(allocator: std.mem.Allocator, label: []const u8, width: usize) ![]const u8 { + if (width == 0) return try allocator.dupe(u8, ""); + if (measure.width(label) <= width) return try allocator.dupe(u8, label); + return try measure.truncate(allocator, label, width); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig new file mode 100644 index 0000000..1cfdc3d --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig @@ -0,0 +1,412 @@ +//! Braille canvas with direct pixel-grid API. +//! +//! Each terminal cell holds 2x4 sub-cell "pixels" via Unicode braille +//! characters (U+2800..U+28FF). Pixel coordinates use (px, py) with origin at +//! top-left; cell coordinates use (col, row). +//! +//! For chart-style data plotting, see `Canvas`. This component is intended +//! for raw pixel work — world maps, scopes, simple bitmaps — where the +//! caller already knows pixel coordinates. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Style = style_mod.Style; + +const BRAILLE_BASE: u21 = 0x2800; + +/// Bit position within a braille cell for each (sub_x, sub_y) coordinate. +/// Layout matches Unicode braille: +/// 0 3 +/// 1 4 +/// 2 5 +/// 6 7 +const BRAILLE_BITS = [4][2]u8{ + .{ 0x01, 0x08 }, + .{ 0x02, 0x10 }, + .{ 0x04, 0x20 }, + .{ 0x40, 0x80 }, +}; + +const BrailleCell = struct { + bits: u8 = 0, + style: ?Style = null, +}; + +const TextOverlay = struct { + col: u16, + row: u16, + text: []const u8, + style: Style, +}; + +pub const BrailleCanvas = struct { + allocator: std.mem.Allocator, + /// Cell width (each cell = 2 pixels wide). + cell_width: u16, + /// Cell height (each cell = 4 pixels tall). + cell_height: u16, + + cells: []BrailleCell, + overlays: std.array_list.Managed(TextOverlay), + text_arena: std.heap.ArenaAllocator, + + default_style: Style, + background_glyph: []const u8, + + pub fn init(allocator: std.mem.Allocator, cell_width: u16, cell_height: u16) !BrailleCanvas { + const w = @max(@as(u16, 1), cell_width); + const h = @max(@as(u16, 1), cell_height); + const cells = try allocator.alloc(BrailleCell, @as(usize, w) * @as(usize, h)); + for (cells) |*c| c.* = .{}; + + var inline_style = Style{}; + inline_style = inline_style.inline_style(true); + + return .{ + .allocator = allocator, + .cell_width = w, + .cell_height = h, + .cells = cells, + .overlays = std.array_list.Managed(TextOverlay).init(allocator), + .text_arena = std.heap.ArenaAllocator.init(allocator), + .default_style = inline_style, + .background_glyph = " ", + }; + } + + pub fn deinit(self: *BrailleCanvas) void { + self.allocator.free(self.cells); + self.overlays.deinit(); + self.text_arena.deinit(); + } + + pub fn setSize(self: *BrailleCanvas, cell_width: u16, cell_height: u16) !void { + const w = @max(@as(u16, 1), cell_width); + const h = @max(@as(u16, 1), cell_height); + if (w == self.cell_width and h == self.cell_height) { + self.clear(); + return; + } + self.allocator.free(self.cells); + self.cells = try self.allocator.alloc(BrailleCell, @as(usize, w) * @as(usize, h)); + for (self.cells) |*c| c.* = .{}; + self.cell_width = w; + self.cell_height = h; + self.overlays.clearRetainingCapacity(); + _ = self.text_arena.reset(.retain_capacity); + } + + pub fn setStyle(self: *BrailleCanvas, style: Style) void { + var s = style; + s = s.inline_style(true); + self.default_style = s; + } + + pub fn setBackground(self: *BrailleCanvas, glyph: []const u8) void { + self.background_glyph = glyph; + } + + /// Pixel grid dimensions. + pub fn pixelWidth(self: *const BrailleCanvas) u16 { + return self.cell_width *| 2; + } + pub fn pixelHeight(self: *const BrailleCanvas) u16 { + return self.cell_height *| 4; + } + + pub fn clear(self: *BrailleCanvas) void { + for (self.cells) |*c| c.* = .{}; + self.overlays.clearRetainingCapacity(); + _ = self.text_arena.reset(.retain_capacity); + } + + pub fn setPixel(self: *BrailleCanvas, px: i32, py: i32) void { + self.setPixelStyled(px, py, self.default_style); + } + + pub fn setPixelStyled(self: *BrailleCanvas, px: i32, py: i32, style: Style) void { + if (px < 0 or py < 0) return; + const upx: u32 = @intCast(px); + const upy: u32 = @intCast(py); + if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return; + + const col: usize = upx / 2; + const row: usize = upy / 4; + const sx: usize = upx % 2; + const sy: usize = upy % 4; + + const idx = row * self.cell_width + col; + var cell = &self.cells[idx]; + cell.bits |= BRAILLE_BITS[sy][sx]; + var s = style; + s = s.inline_style(true); + cell.style = s; + } + + pub fn clearPixel(self: *BrailleCanvas, px: i32, py: i32) void { + if (px < 0 or py < 0) return; + const upx: u32 = @intCast(px); + const upy: u32 = @intCast(py); + if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return; + + const col: usize = upx / 2; + const row: usize = upy / 4; + const sx: usize = upx % 2; + const sy: usize = upy % 4; + + const idx = row * self.cell_width + col; + var cell = &self.cells[idx]; + cell.bits &= ~BRAILLE_BITS[sy][sx]; + if (cell.bits == 0) cell.style = null; + } + + pub fn togglePixel(self: *BrailleCanvas, px: i32, py: i32) void { + if (self.isPixelSet(px, py)) { + self.clearPixel(px, py); + } else { + self.setPixel(px, py); + } + } + + pub fn isPixelSet(self: *const BrailleCanvas, px: i32, py: i32) bool { + if (px < 0 or py < 0) return false; + const upx: u32 = @intCast(px); + const upy: u32 = @intCast(py); + if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return false; + const col: usize = upx / 2; + const row: usize = upy / 4; + const sx: usize = upx % 2; + const sy: usize = upy % 4; + const idx = row * self.cell_width + col; + return (self.cells[idx].bits & BRAILLE_BITS[sy][sx]) != 0; + } + + pub fn drawLine(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32) void { + self.drawLineStyled(x0, y0, x1, y1, self.default_style); + } + + pub fn drawLineStyled(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, style: Style) void { + // Bresenham. + var x = x0; + var y = y0; + const dx = @as(i32, @intCast(@abs(x1 - x0))); + const dy = -@as(i32, @intCast(@abs(y1 - y0))); + const sx: i32 = if (x0 < x1) 1 else -1; + const sy: i32 = if (y0 < y1) 1 else -1; + var err = dx + dy; + while (true) { + self.setPixelStyled(x, y, style); + if (x == x1 and y == y1) break; + const e2 = err * 2; + if (e2 >= dy) { + if (x == x1) break; + err += dy; + x += sx; + } + if (e2 <= dx) { + if (y == y1) break; + err += dx; + y += sy; + } + } + } + + pub fn drawRect(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, filled: bool) void { + self.drawRectStyled(x0, y0, x1, y1, filled, self.default_style); + } + + pub fn drawRectStyled(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, filled: bool, style: Style) void { + const lx = @min(x0, x1); + const hx = @max(x0, x1); + const ly = @min(y0, y1); + const hy = @max(y0, y1); + if (filled) { + var y = ly; + while (y <= hy) : (y += 1) { + var x = lx; + while (x <= hx) : (x += 1) { + self.setPixelStyled(x, y, style); + } + } + } else { + self.drawLineStyled(lx, ly, hx, ly, style); + self.drawLineStyled(lx, hy, hx, hy, style); + self.drawLineStyled(lx, ly, lx, hy, style); + self.drawLineStyled(hx, ly, hx, hy, style); + } + } + + pub fn drawCircle(self: *BrailleCanvas, cx: i32, cy: i32, radius: i32) void { + self.drawCircleStyled(cx, cy, radius, self.default_style); + } + + pub fn drawCircleStyled(self: *BrailleCanvas, cx: i32, cy: i32, radius: i32, style: Style) void { + if (radius <= 0) { + self.setPixelStyled(cx, cy, style); + return; + } + // Midpoint circle algorithm. + var x: i32 = radius; + var y: i32 = 0; + var err: i32 = 1 - radius; + while (x >= y) { + self.setPixelStyled(cx + x, cy + y, style); + self.setPixelStyled(cx + y, cy + x, style); + self.setPixelStyled(cx - y, cy + x, style); + self.setPixelStyled(cx - x, cy + y, style); + self.setPixelStyled(cx - x, cy - y, style); + self.setPixelStyled(cx - y, cy - x, style); + self.setPixelStyled(cx + y, cy - x, style); + self.setPixelStyled(cx + x, cy - y, style); + y += 1; + if (err < 0) { + err += 2 * y + 1; + } else { + x -= 1; + err += 2 * (y - x) + 1; + } + } + } + + /// Overlay text at cell coordinates, replacing the braille at those cells. + pub fn drawText(self: *BrailleCanvas, col: u16, row: u16, text: []const u8, style: Style) !void { + const owned = try self.text_arena.allocator().dupe(u8, text); + var s = style; + s = s.inline_style(true); + try self.overlays.append(.{ .col = col, .row = row, .text = owned, .style = s }); + } + + pub fn view(self: *const BrailleCanvas, allocator: std.mem.Allocator) ![]const u8 { + // Materialize each cell into a string (braille char or background), + // styled. Then apply text overlays. + const total_cells = @as(usize, self.cell_width) * @as(usize, self.cell_height); + var glyph_for_cell = try allocator.alloc(?[]const u8, total_cells); + defer allocator.free(glyph_for_cell); + for (glyph_for_cell) |*g| g.* = null; + + // Apply text overlays first so they take precedence. + for (self.overlays.items) |ov| { + if (ov.row >= self.cell_height) continue; + var col: u16 = ov.col; + var view_iter = std.unicode.Utf8View.init(ov.text) catch continue; + var iter = view_iter.iterator(); + while (iter.nextCodepointSlice()) |cp_slice| { + if (col >= self.cell_width) break; + const idx = @as(usize, ov.row) * self.cell_width + col; + glyph_for_cell[idx] = try ov.style.render(allocator, cp_slice); + col += 1; + } + } + + var result: Writer.Allocating = .init(allocator); + const w = &result.writer; + + var row: usize = 0; + while (row < self.cell_height) : (row += 1) { + if (row > 0) try w.writeByte('\n'); + var col: usize = 0; + while (col < self.cell_width) : (col += 1) { + const idx = row * self.cell_width + col; + if (glyph_for_cell[idx]) |overlay| { + try w.writeAll(overlay); + allocator.free(overlay); + continue; + } + + const cell = self.cells[idx]; + if (cell.bits == 0) { + try w.writeAll(self.background_glyph); + continue; + } + var buf: [4]u8 = undefined; + const cp: u21 = BRAILLE_BASE + @as(u21, cell.bits); + const len = std.unicode.utf8Encode(cp, &buf) catch { + try w.writeAll(self.background_glyph); + continue; + }; + const styled = try (cell.style orelse self.default_style).render(allocator, buf[0..len]); + defer allocator.free(styled); + try w.writeAll(styled); + } + } + + return result.toOwnedSlice(); + } +}; + +test "set and check pixel" { + var c = try BrailleCanvas.init(std.testing.allocator, 4, 4); + defer c.deinit(); + c.setPixel(0, 0); + try std.testing.expect(c.isPixelSet(0, 0)); + try std.testing.expect(!c.isPixelSet(1, 0)); + c.clearPixel(0, 0); + try std.testing.expect(!c.isPixelSet(0, 0)); +} + +test "out-of-bounds writes are ignored" { + var c = try BrailleCanvas.init(std.testing.allocator, 2, 2); + defer c.deinit(); + c.setPixel(-1, -1); + c.setPixel(100, 100); + // Nothing crashes; nothing set. + try std.testing.expect(!c.isPixelSet(0, 0)); +} + +test "drawLine sets endpoints" { + var c = try BrailleCanvas.init(std.testing.allocator, 8, 4); + defer c.deinit(); + c.drawLine(0, 0, 10, 10); + try std.testing.expect(c.isPixelSet(0, 0)); + try std.testing.expect(c.isPixelSet(10, 10)); +} + +test "drawCircle hits cardinal points" { + var c = try BrailleCanvas.init(std.testing.allocator, 16, 16); + defer c.deinit(); + c.drawCircle(10, 10, 5); + try std.testing.expect(c.isPixelSet(15, 10)); + try std.testing.expect(c.isPixelSet(5, 10)); + try std.testing.expect(c.isPixelSet(10, 15)); + try std.testing.expect(c.isPixelSet(10, 5)); +} + +test "view emits cell_height lines" { + const allocator = std.testing.allocator; + var c = try BrailleCanvas.init(allocator, 4, 3); + defer c.deinit(); + c.setPixel(0, 0); + c.setPixel(1, 1); + const out = try c.view(allocator); + defer allocator.free(out); + var newlines: usize = 0; + for (out) |b| if (b == '\n') { + newlines += 1; + }; + try std.testing.expectEqual(@as(usize, 2), newlines); +} + +test "drawText overlay replaces braille" { + const allocator = std.testing.allocator; + var c = try BrailleCanvas.init(allocator, 10, 2); + defer c.deinit(); + c.drawLine(0, 0, 19, 7); + try c.drawText(0, 0, "hi", Style{}); + const out = try c.view(allocator); + defer allocator.free(out); + // Both characters should appear somewhere; styling may sit between them. + try std.testing.expect(std.mem.indexOfScalar(u8, out, 'h') != null); + try std.testing.expect(std.mem.indexOfScalar(u8, out, 'i') != null); +} + +test "setSize resets cells" { + var c = try BrailleCanvas.init(std.testing.allocator, 2, 2); + defer c.deinit(); + c.setPixel(0, 0); + try c.setSize(4, 4); + try std.testing.expect(!c.isPixelSet(0, 0)); + try std.testing.expectEqual(@as(u16, 8), c.pixelWidth()); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig new file mode 100644 index 0000000..d4464c2 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig @@ -0,0 +1,223 @@ +//! 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 Writer = std.Io.Writer; +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(.gray(12)); + seg = seg.inline_style(true); + + var active = style_mod.Style{}; + active = active.fg(.cyan); + active = active.bold(true); + active = active.inline_style(true); + + var sep = style_mod.Style{}; + sep = sep.fg(.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: Writer.Allocating = .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: Writer.Allocating = .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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig new file mode 100644 index 0000000..bcd8839 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig @@ -0,0 +1,304 @@ +//! Calendar/DatePicker component. +//! Displays a month view grid with date selection and navigation. +//! Fully customizable: styles, labels, symbols, layout. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const keys = @import("../input/keys.zig"); + +pub const Calendar = struct { + year: u16 = 2026, + month: u8 = 1, + selected_day: u8 = 1, + cursor_day: u8 = 1, + /// Day to highlight as today (0 = none). + today_day: u8 = 0, + today_month: u8 = 0, + today_year: u16 = 0, + /// Week starts on Monday (true) or Sunday (false). + week_start_monday: bool = true, + /// Marked dates with colors. + marked_days: [31]?Color = .{null} ** 31, + /// Focused state. + focused: bool = true, + + // Customizable labels + /// Month names (12 entries). + month_names: [12][]const u8 = .{ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", + }, + /// Day-of-week headers when week starts Monday (7 entries). + day_headers_mon: [7][]const u8 = .{ "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" }, + /// Day-of-week headers when week starts Sunday (7 entries). + day_headers_sun: [7][]const u8 = .{ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }, + + // Navigation symbols + /// Previous month indicator in title. + prev_symbol: []const u8 = "<", + /// Next month indicator in title. + next_symbol: []const u8 = ">", + /// Title format: 0=prev_symbol, 1=month_name, 2=year, 3=next_symbol. + /// Set to "" to hide title. + title_prefix: []const u8 = " ", + title_suffix: []const u8 = " ", + + // Cell layout + /// Width of each day cell in characters (minimum 2). + cell_width: u8 = 4, + + // Styles + title_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + today_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + selected_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.blue); + s = s.inline_style(true); + break :blk s; + }, + cursor_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.bg(.blue); + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + weekend_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + header_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + normal_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + /// Style for the prev/next symbols in the title. + nav_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + /// Style for marked dates (applied when no custom color is set). + marked_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + + pub fn addMarkedDate(self: *Calendar, day: u8, c: Color) void { + if (day >= 1 and day <= 31) { + self.marked_days[day - 1] = c; + } + } + + pub fn clearMarkedDates(self: *Calendar) void { + self.marked_days = .{null} ** 31; + } + + pub fn update(self: *Calendar, key: keys.KeyEvent) void { + const dim = daysInMonth(self.year, self.month); + switch (key.key) { + .left => { + if (key.modifiers.shift) { + self.prevMonth(); + } else if (self.cursor_day > 1) { + self.cursor_day -= 1; + } + }, + .right => { + if (key.modifiers.shift) { + self.nextMonth(); + } else if (self.cursor_day < dim) { + self.cursor_day += 1; + } + }, + .up => { + if (self.cursor_day > 7) { + self.cursor_day -= 7; + } + }, + .down => { + if (self.cursor_day + 7 <= dim) { + self.cursor_day += 7; + } + }, + .char => |c| switch (c) { + 'h' => self.prevMonth(), + 'l' => self.nextMonth(), + else => {}, + }, + .enter => { + self.selected_day = self.cursor_day; + }, + .page_up => self.prevMonth(), + .page_down => self.nextMonth(), + else => {}, + } + } + + fn prevMonth(self: *Calendar) void { + if (self.month == 1) { + self.month = 12; + if (self.year > 1) self.year -= 1; + } else { + self.month -= 1; + } + const dim = daysInMonth(self.year, self.month); + if (self.cursor_day > dim) self.cursor_day = dim; + if (self.selected_day > dim) self.selected_day = dim; + } + + fn nextMonth(self: *Calendar) void { + if (self.month == 12) { + self.month = 1; + self.year += 1; + } else { + self.month += 1; + } + const dim = daysInMonth(self.year, self.month); + if (self.cursor_day > dim) self.cursor_day = dim; + if (self.selected_day > dim) self.selected_day = dim; + } + + pub fn view(self: *const Calendar, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const cw: usize = @max(2, self.cell_width); + + // Title: < month year > + const mname = if (self.month >= 1 and self.month <= 12) self.month_names[self.month - 1] else "?"; + const nav_prev = self.nav_style.render(allocator, self.prev_symbol) catch self.prev_symbol; + const nav_next = self.nav_style.render(allocator, self.next_symbol) catch self.next_symbol; + const title_text = std.fmt.allocPrint(allocator, "{s}{s}{s} {d}{s}{s}", .{ + self.title_prefix, nav_prev, mname, self.year, nav_next, self.title_suffix, + }) catch "?"; + writer.writeAll(self.title_style.render(allocator, title_text) catch title_text) catch {}; + writer.writeByte('\n') catch {}; + + // Day-of-week headers — aligned to cell_width columns + const headers = if (self.week_start_monday) &self.day_headers_mon else &self.day_headers_sun; + for (headers) |hdr| { + const padded = padCenter(allocator, hdr, cw); + writer.writeAll(self.header_style.render(allocator, padded) catch padded) catch {}; + } + writer.writeByte('\n') catch {}; + + // Calendar grid + const dim = daysInMonth(self.year, self.month); + var first_dow = dayOfWeek(self.year, self.month, 1); // 0=Monday + if (!self.week_start_monday) { + first_dow = (first_dow + 1) % 7; + } + + // Leading blanks — same cell width + for (0..first_dow) |_| { + for (0..cw) |_| writer.writeByte(' ') catch {}; + } + + var col = first_dow; + for (1..@as(usize, dim) + 1) |d| { + const day: u8 = @intCast(d); + const day_str = std.fmt.allocPrint(allocator, "{d}", .{day}) catch "??"; + + const is_today = (day == self.today_day and self.month == self.today_month and self.year == self.today_year); + const is_selected = (day == self.selected_day); + const is_cursor = (day == self.cursor_day and self.focused); + const is_weekend = if (self.week_start_monday) (col >= 5) else (col == 0 or col == 6); + + // Check marked + const marked_color: ?Color = if (day >= 1 and day <= 31) self.marked_days[day - 1] else null; + + var s: style_mod.Style = undefined; + if (is_cursor) { + s = self.cursor_style; + } else if (is_selected) { + s = self.selected_style; + } else if (is_today) { + s = self.today_style; + } else if (marked_color) |mc| { + var ms = self.marked_style; + ms = ms.fg(mc); + s = ms; + } else if (is_weekend) { + s = self.weekend_style; + } else { + s = self.normal_style; + } + + // Center the day number within cell_width + const padded = padCenter(allocator, day_str, cw); + writer.writeAll(s.render(allocator, padded) catch padded) catch {}; + + col += 1; + if (col >= 7) { + col = 0; + if (d < dim) writer.writeByte('\n') catch {}; + } + } + + return result.toArrayList().items; + } + + fn padCenter(allocator: std.mem.Allocator, text: []const u8, target: usize) []const u8 { + if (text.len >= target) return text[0..target]; + var buf = std.array_list.Managed(u8).init(allocator); + const pad = target - text.len; + const left = pad / 2; + const right = pad - left; + for (0..left) |_| buf.append(' ') catch {}; + buf.appendSlice(text) catch {}; + for (0..right) |_| buf.append(' ') catch {}; + return buf.items; + } + + // Calendar math + fn isLeapYear(y: u16) bool { + if (y % 400 == 0) return true; + if (y % 100 == 0) return false; + return y % 4 == 0; + } + + fn daysInMonth(y: u16, m: u8) u8 { + const days = [_]u8{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + if (m < 1 or m > 12) return 30; + if (m == 2 and isLeapYear(y)) return 29; + return days[m - 1]; + } + + /// Returns day of week: 0=Monday, 6=Sunday (Tomohiko Sakamoto's algorithm). + fn dayOfWeek(y_in: u16, m: u8, d: u8) u8 { + const t = [_]i8{ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; + var y: i32 = @intCast(y_in); + if (m < 3) y -= 1; + const mi: usize = @intCast(m - 1); + const r = @mod(y + @divTrunc(y, 4) - @divTrunc(y, 100) + @divTrunc(y, 400) + t[mi] + @as(i32, d), 7); + // r: 0=Sunday. Convert to 0=Monday. + return @intCast(@mod(r + 6, 7)); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig new file mode 100644 index 0000000..60cfa37 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig @@ -0,0 +1,484 @@ +//! Plotting canvas with braille and cell-based markers. + +const std = @import("std"); +const charting = @import("charting.zig"); +const style_mod = @import("../style/style.zig"); + +pub const Marker = charting.Marker; +pub const Point = charting.Point; +pub const DataRange = charting.DataRange; +pub const Style = style_mod.Style; + +pub const Canvas = struct { + allocator: std.mem.Allocator, + width: u16, + height: u16, + x_range: DataRange, + y_range: DataRange, + marker: Marker, + background_glyph: []const u8, + point_glyph: []const u8, + line_glyph: []const u8, + default_style: Style, + operations: std.array_list.Managed(Operation), + + const Operation = union(enum) { + point: PointOp, + line: LineOp, + rect: RectOp, + text: TextOp, + }; + + const PointOp = struct { + point: Point, + style: Style, + glyph: ?[]const u8 = null, + }; + + const LineOp = struct { + from: Point, + to: Point, + style: Style, + glyph: ?[]const u8 = null, + }; + + const RectOp = struct { + min: Point, + max: Point, + filled: bool, + style: Style, + glyph: ?[]const u8 = null, + }; + + const TextOp = struct { + origin: Point, + text: []const u8, + style: Style, + }; + + const BrailleCell = struct { + bits: u8 = 0, + style: ?Style = null, + }; + + pub fn init(allocator: std.mem.Allocator) Canvas { + return .{ + .allocator = allocator, + .width = 40, + .height = 12, + .x_range = .{ .min = 0, .max = 1 }, + .y_range = .{ .min = 0, .max = 1 }, + .marker = .braille, + .background_glyph = " ", + .point_glyph = "•", + .line_glyph = "█", + .default_style = charting.inlineStyle(Style{}), + .operations = std.array_list.Managed(Operation).init(allocator), + }; + } + + pub fn deinit(self: *Canvas) void { + self.operations.deinit(); + } + + pub fn clear(self: *Canvas) void { + self.operations.clearRetainingCapacity(); + } + + pub fn setSize(self: *Canvas, width: u16, height: u16) void { + self.width = @max(1, width); + self.height = @max(1, height); + } + + pub fn setRanges(self: *Canvas, x_range: DataRange, y_range: DataRange) void { + self.x_range = x_range.normalized(); + self.y_range = y_range.normalized(); + } + + pub fn setMarker(self: *Canvas, marker: Marker) void { + self.marker = marker; + } + + pub fn setStyle(self: *Canvas, style: Style) void { + self.default_style = charting.inlineStyle(style); + } + + pub fn setGlyphs(self: *Canvas, point_glyph: []const u8, line_glyph: []const u8) void { + self.point_glyph = point_glyph; + self.line_glyph = line_glyph; + } + + pub fn setBackground(self: *Canvas, glyph: []const u8) void { + self.background_glyph = glyph; + } + + pub fn drawPoint(self: *Canvas, x: f64, y: f64) !void { + try self.drawPointStyled(x, y, self.default_style, null); + } + + pub fn drawPointStyled(self: *Canvas, x: f64, y: f64, style: Style, glyph: ?[]const u8) !void { + try self.operations.append(.{ + .point = .{ + .point = .{ .x = x, .y = y }, + .style = charting.inlineStyle(style), + .glyph = glyph, + }, + }); + } + + pub fn drawLine(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64) !void { + try self.drawLineStyled(x0, y0, x1, y1, self.default_style, null); + } + + pub fn drawLineStyled(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64, style: Style, glyph: ?[]const u8) !void { + try self.operations.append(.{ + .line = .{ + .from = .{ .x = x0, .y = y0 }, + .to = .{ .x = x1, .y = y1 }, + .style = charting.inlineStyle(style), + .glyph = glyph, + }, + }); + } + + pub fn drawRect(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64, filled: bool, style: Style, glyph: ?[]const u8) !void { + try self.operations.append(.{ + .rect = .{ + .min = .{ .x = @min(x0, x1), .y = @min(y0, y1) }, + .max = .{ .x = @max(x0, x1), .y = @max(y0, y1) }, + .filled = filled, + .style = charting.inlineStyle(style), + .glyph = glyph, + }, + }); + } + + pub fn drawText(self: *Canvas, x: f64, y: f64, text: []const u8, style: Style) !void { + try self.operations.append(.{ + .text = .{ + .origin = .{ .x = x, .y = y }, + .text = text, + .style = charting.inlineStyle(style), + }, + }); + } + + pub fn view(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { + return switch (self.marker) { + .braille => self.renderBraille(allocator), + .block, .dot, .ascii => self.renderCells(allocator), + }; + } + + pub fn drawIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { + switch (self.marker) { + .braille => self.drawBrailleIntoBuffer(buffer), + .block, .dot, .ascii => self.drawCellIntoBuffer(buffer), + } + } + + fn renderCells(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { + var buffer = try charting.CellBuffer.init(allocator, self.width, self.height); + defer buffer.deinit(); + + for (0..self.height) |y| { + for (0..self.width) |x| { + buffer.setSlice(x, y, self.background_glyph, null); + } + } + + self.drawCellIntoBuffer(&buffer); + + return try buffer.render(allocator); + } + + fn renderBraille(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { + const cell_count = @as(usize, self.width) * @as(usize, self.height); + const braille_cells = try allocator.alloc(BrailleCell, cell_count); + defer allocator.free(braille_cells); + for (braille_cells) |*cell| cell.* = .{}; + + var overlay = try charting.CellBuffer.init(allocator, self.width, self.height); + defer overlay.deinit(); + + for (self.operations.items) |op| { + switch (op) { + .point => |point_op| { + const x = charting.mapX(point_op.point.x, self.x_range, @as(usize, self.width) * 2); + const y = charting.mapY(point_op.point.y, self.y_range, @as(usize, self.height) * 4); + setBraillePixel(braille_cells, self.width, x, y, point_op.style); + }, + .line => |line_op| { + const x0 = charting.mapX(line_op.from.x, self.x_range, @as(usize, self.width) * 2); + const y0 = charting.mapY(line_op.from.y, self.y_range, @as(usize, self.height) * 4); + const x1 = charting.mapX(line_op.to.x, self.x_range, @as(usize, self.width) * 2); + const y1 = charting.mapY(line_op.to.y, self.y_range, @as(usize, self.height) * 4); + drawBrailleLine(braille_cells, self.width, x0, y0, x1, y1, line_op.style); + }, + .rect => |rect_op| { + const min_x = charting.mapX(rect_op.min.x, self.x_range, @as(usize, self.width) * 2); + const min_y = charting.mapY(rect_op.max.y, self.y_range, @as(usize, self.height) * 4); + const max_x = charting.mapX(rect_op.max.x, self.x_range, @as(usize, self.width) * 2); + const max_y = charting.mapY(rect_op.min.y, self.y_range, @as(usize, self.height) * 4); + drawBrailleRect(braille_cells, self.width, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.style); + }, + .text => |text_op| { + const x = charting.mapX(text_op.origin.x, self.x_range, self.width); + const y = charting.mapY(text_op.origin.y, self.y_range, self.height); + overlay.writeText(x, y, text_op.text, text_op.style); + }, + } + } + + var final = try charting.CellBuffer.init(allocator, self.width, self.height); + defer final.deinit(); + + for (0..self.height) |y| { + for (0..self.width) |x| { + const cell = braille_cells[y * self.width + x]; + if (cell.bits == 0) { + final.setSlice(x, y, self.background_glyph, null); + } else { + final.setCodepoint(x, y, @as(u21, 0x2800) + cell.bits, cell.style); + } + } + } + + for (0..self.height) |y| { + for (0..self.width) |x| { + const cell = overlay.cells[y * self.width + x]; + if (glyphIsBlank(cell.glyph)) continue; + final.cells[y * self.width + x] = cell; + } + } + + return try final.render(allocator); + } + + fn drawCellIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { + for (self.operations.items) |op| { + switch (op) { + .point => |point_op| { + const x = charting.mapX(point_op.point.x, self.x_range, self.width); + const y = charting.mapY(point_op.point.y, self.y_range, self.height); + buffer.setSlice(x, y, point_op.glyph orelse self.defaultCellGlyph(), point_op.style); + }, + .line => |line_op| { + const x0 = charting.mapX(line_op.from.x, self.x_range, self.width); + const y0 = charting.mapY(line_op.from.y, self.y_range, self.height); + const x1 = charting.mapX(line_op.to.x, self.x_range, self.width); + const y1 = charting.mapY(line_op.to.y, self.y_range, self.height); + drawLineCells(buffer, x0, y0, x1, y1, line_op.glyph orelse self.lineCellGlyph(), line_op.style); + }, + .rect => |rect_op| { + const min_x = charting.mapX(rect_op.min.x, self.x_range, self.width); + const min_y = charting.mapY(rect_op.max.y, self.y_range, self.height); + const max_x = charting.mapX(rect_op.max.x, self.x_range, self.width); + const max_y = charting.mapY(rect_op.min.y, self.y_range, self.height); + drawRectCells(buffer, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.glyph orelse self.lineCellGlyph(), rect_op.style); + }, + .text => |text_op| { + const x = charting.mapX(text_op.origin.x, self.x_range, self.width); + const y = charting.mapY(text_op.origin.y, self.y_range, self.height); + buffer.writeText(x, y, text_op.text, text_op.style); + }, + } + } + } + + fn drawBrailleIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { + const cell_count = @as(usize, self.width) * @as(usize, self.height); + const braille_cells = buffer.allocator.alloc(BrailleCell, cell_count) catch return; + defer buffer.allocator.free(braille_cells); + for (braille_cells) |*cell| cell.* = .{}; + + for (self.operations.items) |op| { + switch (op) { + .point => |point_op| { + const x = charting.mapX(point_op.point.x, self.x_range, @as(usize, self.width) * 2); + const y = charting.mapY(point_op.point.y, self.y_range, @as(usize, self.height) * 4); + setBraillePixel(braille_cells, self.width, x, y, point_op.style); + }, + .line => |line_op| { + const x0 = charting.mapX(line_op.from.x, self.x_range, @as(usize, self.width) * 2); + const y0 = charting.mapY(line_op.from.y, self.y_range, @as(usize, self.height) * 4); + const x1 = charting.mapX(line_op.to.x, self.x_range, @as(usize, self.width) * 2); + const y1 = charting.mapY(line_op.to.y, self.y_range, @as(usize, self.height) * 4); + drawBrailleLine(braille_cells, self.width, x0, y0, x1, y1, line_op.style); + }, + .rect => |rect_op| { + const min_x = charting.mapX(rect_op.min.x, self.x_range, @as(usize, self.width) * 2); + const min_y = charting.mapY(rect_op.max.y, self.y_range, @as(usize, self.height) * 4); + const max_x = charting.mapX(rect_op.max.x, self.x_range, @as(usize, self.width) * 2); + const max_y = charting.mapY(rect_op.min.y, self.y_range, @as(usize, self.height) * 4); + drawBrailleRect(braille_cells, self.width, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.style); + }, + .text => |text_op| { + const x = charting.mapX(text_op.origin.x, self.x_range, self.width); + const y = charting.mapY(text_op.origin.y, self.y_range, self.height); + buffer.writeText(x, y, text_op.text, text_op.style); + }, + } + } + + for (0..self.height) |y| { + for (0..self.width) |x| { + const cell = braille_cells[y * self.width + x]; + if (cell.bits == 0) continue; + buffer.setCodepoint(x, y, @as(u21, 0x2800) + cell.bits, cell.style); + } + } + } + + fn defaultCellGlyph(self: *const Canvas) []const u8 { + return switch (self.marker) { + .braille => "•", + .block => if (self.point_glyph.len > 0) self.point_glyph else "█", + .dot => if (self.point_glyph.len > 0) self.point_glyph else "•", + .ascii => if (self.point_glyph.len > 0) self.point_glyph else "*", + }; + } + + fn lineCellGlyph(self: *const Canvas) []const u8 { + return switch (self.marker) { + .braille => "•", + .block => if (self.line_glyph.len > 0) self.line_glyph else "█", + .dot => if (self.line_glyph.len > 0) self.line_glyph else "•", + .ascii => if (self.line_glyph.len > 0) self.line_glyph else "*", + }; + } +}; + +fn glyphIsBlank(glyph: charting.Glyph) bool { + return switch (glyph) { + .slice => |slice| slice.len == 0 or std.mem.eql(u8, slice, " "), + .codepoint => |cp| cp == ' ' or cp == 0x2800, + }; +} + +fn drawLineCells(buffer: *charting.CellBuffer, x0: usize, y0: usize, x1: usize, y1: usize, glyph: []const u8, style: ?Style) void { + const dx = @as(isize, @intCast(x1)) - @as(isize, @intCast(x0)); + const dy = @as(isize, @intCast(y1)) - @as(isize, @intCast(y0)); + const steps = @max(@abs(dx), @abs(dy)); + if (steps == 0) { + buffer.setSlice(x0, y0, glyph, style); + return; + } + + const step_x = @as(f64, @floatFromInt(dx)) / @as(f64, @floatFromInt(steps)); + const step_y = @as(f64, @floatFromInt(dy)) / @as(f64, @floatFromInt(steps)); + + var x = @as(f64, @floatFromInt(x0)); + var y = @as(f64, @floatFromInt(y0)); + var i: usize = 0; + while (i <= @as(usize, @intCast(steps))) : (i += 1) { + buffer.setSlice( + @as(usize, @intFromFloat(@round(x))), + @as(usize, @intFromFloat(@round(y))), + glyph, + style, + ); + x += step_x; + y += step_y; + } +} + +fn drawRectCells(buffer: *charting.CellBuffer, min_x: usize, min_y: usize, max_x: usize, max_y: usize, filled: bool, glyph: []const u8, style: ?Style) void { + const left = @min(min_x, max_x); + const right = @max(min_x, max_x); + const top = @min(min_y, max_y); + const bottom = @max(min_y, max_y); + + if (filled) { + for (top..bottom + 1) |y| { + for (left..right + 1) |x| { + buffer.setSlice(x, y, glyph, style); + } + } + return; + } + + drawLineCells(buffer, left, top, right, top, glyph, style); + drawLineCells(buffer, left, bottom, right, bottom, glyph, style); + drawLineCells(buffer, left, top, left, bottom, glyph, style); + drawLineCells(buffer, right, top, right, bottom, glyph, style); +} + +fn setBraillePixel(cells: []Canvas.BrailleCell, width: u16, x: usize, y: usize, style: ?Style) void { + const cell_x = x / 2; + const cell_y = y / 4; + if (cell_x >= width) return; + const height = if (width == 0) 0 else cells.len / width; + if (cell_y >= height) return; + + const local_x = x % 2; + const local_y = y % 4; + + const bit = switch (local_x) { + 0 => switch (local_y) { + 0 => @as(u8, 0x01), + 1 => @as(u8, 0x02), + 2 => @as(u8, 0x04), + else => @as(u8, 0x40), + }, + else => switch (local_y) { + 0 => @as(u8, 0x08), + 1 => @as(u8, 0x10), + 2 => @as(u8, 0x20), + else => @as(u8, 0x80), + }, + }; + + const index = cell_y * width + cell_x; + cells[index].bits |= bit; + cells[index].style = style; +} + +fn drawBrailleLine(cells: []Canvas.BrailleCell, width: u16, x0: usize, y0: usize, x1: usize, y1: usize, style: ?Style) void { + const dx = @as(isize, @intCast(x1)) - @as(isize, @intCast(x0)); + const dy = @as(isize, @intCast(y1)) - @as(isize, @intCast(y0)); + const steps = @max(@abs(dx), @abs(dy)); + if (steps == 0) { + setBraillePixel(cells, width, x0, y0, style); + return; + } + + const step_x = @as(f64, @floatFromInt(dx)) / @as(f64, @floatFromInt(steps)); + const step_y = @as(f64, @floatFromInt(dy)) / @as(f64, @floatFromInt(steps)); + + var x = @as(f64, @floatFromInt(x0)); + var y = @as(f64, @floatFromInt(y0)); + var i: usize = 0; + while (i <= @as(usize, @intCast(steps))) : (i += 1) { + setBraillePixel( + cells, + width, + @as(usize, @intFromFloat(@round(x))), + @as(usize, @intFromFloat(@round(y))), + style, + ); + x += step_x; + y += step_y; + } +} + +fn drawBrailleRect(cells: []Canvas.BrailleCell, width: u16, min_x: usize, min_y: usize, max_x: usize, max_y: usize, filled: bool, style: ?Style) void { + const left = @min(min_x, max_x); + const right = @max(min_x, max_x); + const top = @min(min_y, max_y); + const bottom = @max(min_y, max_y); + + if (filled) { + for (top..bottom + 1) |y| { + for (left..right + 1) |x| { + setBraillePixel(cells, width, x, y, style); + } + } + return; + } + + drawBrailleLine(cells, width, left, top, right, top, style); + drawBrailleLine(cells, width, left, bottom, right, bottom, style); + drawBrailleLine(cells, width, left, top, left, bottom, style); + drawBrailleLine(cells, width, right, top, right, bottom, style); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig new file mode 100644 index 0000000..90eff91 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig @@ -0,0 +1,758 @@ +//! Cartesian chart widget with axes, legend, and multiple datasets. + +const std = @import("std"); +const Writer = std.Io.Writer; +const charting = @import("charting.zig"); +const canvas_mod = @import("canvas.zig"); +const join = @import("../layout/join.zig"); +const measure = @import("../layout/measure.zig"); +const style_mod = @import("../style/style.zig"); + +pub const Style = style_mod.Style; +pub const AxisLabel = charting.AxisLabel; +pub const DataRange = charting.DataRange; +pub const GraphType = charting.GraphType; +pub const Interpolation = charting.Interpolation; +pub const LegendPosition = charting.LegendPosition; +pub const Marker = charting.Marker; +pub const Point = charting.Point; +pub const ValueFormatter = charting.ValueFormatter; + +pub const Axis = struct { + title: []const u8 = "", + bounds: ?DataRange = null, + labels: []const AxisLabel = &.{}, + tick_count: u8 = 5, + show_line: bool = true, + show_labels: bool = true, + show_grid: bool = false, + style: Style = charting.inlineStyle(Style{}), + label_style: Style = charting.inlineStyle(Style{}), + title_style: Style = charting.inlineStyle((Style{}).bold(true)), + grid_style: Style = charting.inlineStyle(Style{}), + formatter: ?ValueFormatter = null, +}; + +pub const Dataset = struct { + allocator: std.mem.Allocator, + label: []const u8, + points: std.array_list.Managed(Point), + style: Style, + graph_type: GraphType, + interpolation: Interpolation, + interpolation_steps: u8, + curve_tension: f64, + show_points: bool, + point_glyph: ?[]const u8, + fill_to: ?f64, + + pub fn init(allocator: std.mem.Allocator, label: []const u8) !Dataset { + return .{ + .allocator = allocator, + .label = try allocator.dupe(u8, label), + .points = std.array_list.Managed(Point).init(allocator), + .style = charting.inlineStyle(Style{}), + .graph_type = .line, + .interpolation = .linear, + .interpolation_steps = 8, + .curve_tension = 0.5, + .show_points = false, + .point_glyph = null, + .fill_to = null, + }; + } + + pub fn deinit(self: *Dataset) void { + self.allocator.free(self.label); + self.points.deinit(); + } + + pub fn setStyle(self: *Dataset, style: Style) void { + self.style = charting.inlineStyle(style); + } + + pub fn setGraphType(self: *Dataset, graph_type: GraphType) void { + self.graph_type = graph_type; + } + + pub fn setInterpolation(self: *Dataset, interpolation: Interpolation) void { + self.interpolation = interpolation; + } + + pub fn setInterpolationSteps(self: *Dataset, steps: u8) void { + self.interpolation_steps = @max(@as(u8, 1), steps); + } + + pub fn setCurveTension(self: *Dataset, tension: f64) void { + self.curve_tension = std.math.clamp(tension, 0.0, 1.0); + } + + pub fn setShowPoints(self: *Dataset, show_points: bool) void { + self.show_points = show_points; + } + + pub fn setPointGlyph(self: *Dataset, glyph: ?[]const u8) void { + self.point_glyph = glyph; + } + + pub fn setFillBaseline(self: *Dataset, baseline: ?f64) void { + self.fill_to = baseline; + } + + pub fn appendPoint(self: *Dataset, point: Point) !void { + try self.points.append(point); + } + + pub fn setPoints(self: *Dataset, points: []const Point) !void { + self.points.clearRetainingCapacity(); + try self.points.appendSlice(points); + } +}; + +pub const Chart = struct { + allocator: std.mem.Allocator, + width: u16, + height: u16, + marker: Marker, + x_axis: Axis, + y_axis: Axis, + datasets: std.array_list.Managed(Dataset), + legend_position: LegendPosition, + legend_style: Style, + plot_background: []const u8, + + pub fn init(allocator: std.mem.Allocator) Chart { + return .{ + .allocator = allocator, + .width = 60, + .height = 18, + .marker = .braille, + .x_axis = .{}, + .y_axis = .{}, + .datasets = std.array_list.Managed(Dataset).init(allocator), + .legend_position = .bottom, + .legend_style = charting.inlineStyle((Style{}).bold(true)), + .plot_background = " ", + }; + } + + pub fn deinit(self: *Chart) void { + for (self.datasets.items) |*dataset| dataset.deinit(); + self.datasets.deinit(); + } + + pub fn clearDatasets(self: *Chart) void { + for (self.datasets.items) |*dataset| dataset.deinit(); + self.datasets.clearRetainingCapacity(); + } + + pub fn setSize(self: *Chart, width: u16, height: u16) void { + self.width = @max(10, width); + self.height = @max(6, height); + } + + pub fn setMarker(self: *Chart, marker: Marker) void { + self.marker = marker; + } + + pub fn setLegendPosition(self: *Chart, position: LegendPosition) void { + self.legend_position = position; + } + + pub fn setPlotBackground(self: *Chart, glyph: []const u8) void { + self.plot_background = glyph; + } + + pub fn addDataset(self: *Chart, dataset: Dataset) !void { + try self.datasets.append(dataset); + } + + pub fn view(self: *const Chart, allocator: std.mem.Allocator) ![]const u8 { + const resolved_x = self.resolveRange(.x); + const resolved_y = self.resolveRange(.y); + + var x_ticks = try TickSet.init(allocator, self.x_axis, resolved_x); + defer x_ticks.deinit(); + var y_ticks = try TickSet.init(allocator, self.y_axis, resolved_y); + defer y_ticks.deinit(); + + const y_label_width = if (self.y_axis.show_labels) y_ticks.maxLabelWidth() else 0; + const y_axis_offset: usize = if (self.y_axis.show_line) + 2 + else if (y_label_width > 0) + 1 + else + 0; + const left_gutter = y_label_width + y_axis_offset; + const x_axis_line_rows: usize = if (self.x_axis.show_line) 1 else 0; + const x_label_rows: usize = if (self.x_axis.show_labels) 1 else 0; + const x_title_rows: usize = if (self.x_axis.title.len > 0) 1 else 0; + const y_title_rows: usize = if (self.y_axis.title.len > 0) 1 else 0; + + const plot_width = @max(@as(usize, 1), @as(usize, self.width) -| left_gutter); + const plot_height = @max(@as(usize, 1), @as(usize, self.height) -| (x_axis_line_rows + x_label_rows + x_title_rows + y_title_rows)); + + x_ticks.updatePositions(plot_width); + y_ticks.updatePositions(plot_height); + + const plot = try self.renderPlot(allocator, plot_width, plot_height, resolved_x, resolved_y, &x_ticks, &y_ticks); + defer allocator.free(plot); + + var rows = std.array_list.Managed([]const u8).init(allocator); + defer { + for (rows.items) |row| allocator.free(row); + rows.deinit(); + } + + if (self.y_axis.title.len > 0) { + const row = try self.renderYAxisTitleRow(allocator, y_label_width, plot_width); + try rows.append(row); + } + + var plot_lines = std.mem.splitScalar(u8, plot, '\n'); + var row_index: usize = 0; + while (plot_lines.next()) |plot_line| : (row_index += 1) { + const row = try self.renderPlotRow(allocator, row_index, plot_line, plot_height, y_label_width, &y_ticks); + try rows.append(row); + } + + if (self.x_axis.show_line) { + const axis_row = try self.renderXAxisLineRow(allocator, plot_width, y_label_width); + try rows.append(axis_row); + } + + if (self.x_axis.show_labels) { + const label_row = try self.renderXAxisLabelsRow(allocator, plot_width, y_label_width, &x_ticks); + try rows.append(label_row); + } + + if (self.x_axis.title.len > 0) { + const title_row = try self.renderXAxisTitleRow(allocator, plot_width, y_label_width); + try rows.append(title_row); + } + + const chart_body = try join.vertical(allocator, .left, rows.items); + defer allocator.free(chart_body); + + const legend = try self.renderLegend(allocator); + defer allocator.free(legend); + + return switch (self.legend_position) { + .hidden => try allocator.dupe(u8, chart_body), + .top => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.vertical(allocator, .left, &.{ legend, chart_body }), + .bottom => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.vertical(allocator, .left, &.{ chart_body, legend }), + .left => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.horizontal(allocator, .top, &.{ legend, " ", chart_body }), + .right => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.horizontal(allocator, .top, &.{ chart_body, " ", legend }), + }; + } + + const AxisKind = enum { x, y }; + + fn resolveRange(self: *const Chart, axis_kind: AxisKind) DataRange { + const axis = switch (axis_kind) { + .x => self.x_axis, + .y => self.y_axis, + }; + if (axis.bounds) |bounds| return bounds.normalized(); + + var found = false; + var min_value: f64 = 0; + var max_value: f64 = 0; + + for (self.datasets.items) |dataset| { + for (dataset.points.items) |point| { + const value = switch (axis_kind) { + .x => point.x, + .y => point.y, + }; + if (!std.math.isFinite(value)) continue; + if (!found) { + min_value = value; + max_value = value; + found = true; + } else { + min_value = @min(min_value, value); + max_value = @max(max_value, value); + } + } + + if (axis_kind == .y and dataset.graph_type == .area) { + if (dataset.fill_to) |baseline| { + if (!found) { + min_value = baseline; + max_value = baseline; + found = true; + } else { + min_value = @min(min_value, baseline); + max_value = @max(max_value, baseline); + } + } + } + } + + if (!found) return .{ .min = 0, .max = 1 }; + const range = DataRange{ .min = min_value, .max = max_value }; + return range.normalized(); + } + + fn renderPlot(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, plot_height: usize, x_range: DataRange, y_range: DataRange, x_ticks: *const TickSet, y_ticks: *const TickSet) ![]const u8 { + var buffer = try charting.CellBuffer.init(allocator, plot_width, plot_height); + defer buffer.deinit(); + + for (0..plot_height) |y| { + for (0..plot_width) |x| { + buffer.setSlice(x, y, self.plot_background, null); + } + } + + if (self.y_axis.show_grid) { + for (y_ticks.positions.items) |y| { + if (y >= plot_height) continue; + for (0..plot_width) |x| { + setGridGlyph(&buffer, x, y, .horizontal, self.y_axis.grid_style); + } + } + } + + if (self.x_axis.show_grid) { + for (x_ticks.positions.items) |x| { + if (x >= plot_width) continue; + for (0..plot_height) |y| { + setGridGlyph(&buffer, x, y, .vertical, self.x_axis.grid_style); + } + } + } + + var plot = canvas_mod.Canvas.init(allocator); + defer plot.deinit(); + + plot.setSize(@intCast(plot_width), @intCast(plot_height)); + plot.setRanges(x_range, y_range); + plot.setMarker(self.marker); + + for (self.datasets.items) |dataset| { + var path = try sampledPath(allocator, &dataset); + defer path.deinit(); + + switch (dataset.graph_type) { + .line => { + if (dataset.points.items.len == 1) { + const point = dataset.points.items[0]; + try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); + } else if (path.items.len > 1) { + var i: usize = 1; + while (i < path.items.len) : (i += 1) { + const prev = path.items[i - 1]; + const point = path.items[i]; + try plot.drawLineStyled(prev.x, prev.y, point.x, point.y, dataset.style, null); + } + } + + if (dataset.show_points) { + for (dataset.points.items) |point| { + try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); + } + } + }, + .scatter => { + for (dataset.points.items) |point| { + try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); + } + }, + .area => { + if (path.items.len > 1) { + var i: usize = 1; + while (i < path.items.len) : (i += 1) { + const prev = path.items[i - 1]; + const point = path.items[i]; + try plot.drawLineStyled(prev.x, prev.y, point.x, point.y, dataset.style, null); + } + } + + const baseline = dataset.fill_to orelse y_range.min; + for (path.items) |point| { + try plot.drawLineStyled(point.x, baseline, point.x, point.y, dataset.style, null); + } + }, + } + } + + plot.drawIntoBuffer(&buffer); + return try buffer.render(allocator); + } + + fn renderYAxisTitleRow(self: *const Chart, allocator: std.mem.Allocator, y_label_width: usize, plot_width: usize) ![]const u8 { + const prefix_width = leftPrefixWidth(self, y_label_width); + var row = try charting.CellBuffer.init(allocator, prefix_width + plot_width, 1); + defer row.deinit(); + + for (0..row.width) |x| row.setSlice(x, 0, " ", null); + row.writeText(prefix_width, 0, self.y_axis.title, self.y_axis.title_style); + return try row.render(allocator); + } + + fn renderPlotRow(self: *const Chart, allocator: std.mem.Allocator, row_index: usize, plot_line: []const u8, plot_height: usize, y_label_width: usize, y_ticks: *const TickSet) ![]const u8 { + _ = plot_height; + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (self.y_axis.show_labels) { + const label = y_ticks.labelForRow(row_index) orelse ""; + const padded = try renderPaddedLabel(allocator, label, y_label_width, self.y_axis.label_style); + defer allocator.free(padded); + try writer.writeAll(padded); + } + + if (self.y_axis.show_line) { + const axis_glyph = try self.y_axis.style.render(allocator, " │"); + defer allocator.free(axis_glyph); + try writer.writeAll(axis_glyph); + } else if (y_label_width > 0) { + try writer.writeByte(' '); + } + + try writer.writeAll(plot_line); + return try result.toOwnedSlice(); + } + + fn renderXAxisLineRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (self.y_axis.show_labels) { + for (0..y_label_width) |_| try writer.writeByte(' '); + } + + if (self.y_axis.show_line) { + const corner = try self.x_axis.style.render(allocator, " └"); + defer allocator.free(corner); + try writer.writeAll(corner); + } else if (y_label_width > 0) { + try writer.writeByte(' '); + } + + var axis_style = self.x_axis.style; + axis_style = charting.inlineStyle(axis_style); + const segment = try axis_style.render(allocator, "─"); + defer allocator.free(segment); + for (0..plot_width) |_| try writer.writeAll(segment); + + return try result.toOwnedSlice(); + } + + fn renderXAxisLabelsRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize, x_ticks: *const TickSet) ![]const u8 { + const offset = leftPrefixWidth(self, y_label_width); + var row = try charting.CellBuffer.init(allocator, offset + plot_width, 1); + defer row.deinit(); + + for (0..row.width) |x| row.setSlice(x, 0, " ", null); + + for (x_ticks.positions.items, x_ticks.labels.items) |x, label| { + const label_width = measure.width(label); + const start = offset + x -| (label_width / 2); + row.writeText(start, 0, label, self.x_axis.label_style); + } + + return try row.render(allocator); + } + + fn renderXAxisTitleRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize) ![]const u8 { + const offset = leftPrefixWidth(self, y_label_width); + var row = try charting.CellBuffer.init(allocator, offset + plot_width, 1); + defer row.deinit(); + + for (0..row.width) |x| row.setSlice(x, 0, " ", null); + + const title_width = measure.width(self.x_axis.title); + const start = offset + (plot_width -| title_width) / 2; + row.writeText(start, 0, self.x_axis.title, self.x_axis.title_style); + return try row.render(allocator); + } + + fn renderLegend(self: *const Chart, allocator: std.mem.Allocator) ![]const u8 { + if (self.legend_position == .hidden or self.datasets.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + var pieces = std.array_list.Managed([]const u8).init(allocator); + defer { + for (pieces.items) |piece| allocator.free(piece); + pieces.deinit(); + } + + for (self.datasets.items) |dataset| { + const symbol_raw = switch (dataset.graph_type) { + .line => "──", + .scatter => dataset.point_glyph orelse "•", + .area => "██", + }; + const symbol = try dataset.style.render(allocator, symbol_raw); + defer allocator.free(symbol); + + const label = try self.legend_style.render(allocator, dataset.label); + defer allocator.free(label); + + const piece = try std.fmt.allocPrint(allocator, "{s} {s}", .{ symbol, label }); + try pieces.append(piece); + } + + return try join.horizontal(allocator, .top, pieces.items); + } +}; + +const TickSet = struct { + allocator: std.mem.Allocator, + range: DataRange, + values: std.array_list.Managed(f64), + positions: std.array_list.Managed(usize), + labels: std.array_list.Managed([]const u8), + + fn init(allocator: std.mem.Allocator, axis: Axis, range: DataRange) !TickSet { + var self = TickSet{ + .allocator = allocator, + .range = range, + .values = std.array_list.Managed(f64).init(allocator), + .positions = std.array_list.Managed(usize).init(allocator), + .labels = std.array_list.Managed([]const u8).init(allocator), + }; + + if (axis.labels.len > 0) { + for (axis.labels) |label| { + try self.values.append(label.value); + try self.positions.append(0); + try self.labels.append(try allocator.dupe(u8, label.text)); + } + return self; + } + + const tick_count = @max(@as(usize, 2), axis.tick_count); + var i: usize = 0; + while (i < tick_count) : (i += 1) { + const t = if (tick_count == 1) 0.0 else @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(tick_count - 1)); + const value = range.min + (range.max - range.min) * t; + try self.values.append(value); + try self.positions.append(0); + + const formatter = axis.formatter orelse charting.defaultFormatter; + const label = try formatter(allocator, value); + try self.labels.append(label); + } + + return self; + } + + fn updatePositions(self: *TickSet, span: usize) void { + const usable_span = @max(@as(usize, 1), span); + for (self.values.items, 0..) |value, index| { + self.positions.items[index] = charting.mapToResolution(value, self.range, usable_span); + } + } + + fn deinit(self: *TickSet) void { + for (self.labels.items) |label| self.allocator.free(label); + self.values.deinit(); + self.positions.deinit(); + self.labels.deinit(); + } + + fn maxLabelWidth(self: *const TickSet) usize { + var max_width: usize = 0; + for (self.labels.items) |label| { + max_width = @max(max_width, measure.width(label)); + } + return max_width; + } + + fn labelForRow(self: *const TickSet, row: usize) ?[]const u8 { + for (self.positions.items, self.labels.items) |tick_row, label| { + if (tick_row == row) return label; + } + return null; + } +}; + +const GridOrientation = enum { vertical, horizontal }; + +fn renderPaddedLabel(allocator: std.mem.Allocator, label: []const u8, width: usize, style: Style) ![]const u8 { + const label_width = measure.width(label); + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const padding = width -| label_width; + for (0..padding) |_| try writer.writeByte(' '); + + if (label.len > 0) { + const rendered = try style.render(allocator, label); + defer allocator.free(rendered); + try writer.writeAll(rendered); + } + + return try result.toOwnedSlice(); +} + +fn setGridGlyph(buffer: *charting.CellBuffer, x: usize, y: usize, orientation: GridOrientation, style: Style) void { + const current = buffer.cells[y * buffer.width + x]; + const next = switch (current.glyph) { + .slice => |slice| blk: { + if (orientation == .vertical and std.mem.eql(u8, slice, "─")) break :blk "┼"; + if (orientation == .horizontal and std.mem.eql(u8, slice, "│")) break :blk "┼"; + if (std.mem.eql(u8, slice, "┼")) break :blk "┼"; + break :blk if (orientation == .vertical) "│" else "─"; + }, + else => if (orientation == .vertical) "│" else "─", + }; + buffer.setSlice(x, y, next, style); +} + +fn leftPrefixWidth(self: *const Chart, y_label_width: usize) usize { + return y_label_width + (if (self.y_axis.show_line) + @as(usize, 2) + else if (y_label_width > 0) + @as(usize, 1) + else + @as(usize, 0)); +} + +fn sampledPath(allocator: std.mem.Allocator, dataset: *const Dataset) !std.array_list.Managed(Point) { + var path = std.array_list.Managed(Point).init(allocator); + if (dataset.points.items.len == 0) return path; + + switch (dataset.interpolation) { + .linear => try path.appendSlice(dataset.points.items), + .step_start => try appendSteppedPoints(&path, dataset.points.items, .step_start), + .step_center => try appendSteppedPoints(&path, dataset.points.items, .step_center), + .step_end => try appendSteppedPoints(&path, dataset.points.items, .step_end), + .catmull_rom => try appendCatmullRomPoints(&path, dataset.points.items, dataset.interpolation_steps, dataset.curve_tension), + .monotone_cubic => try appendMonotonePoints(allocator, &path, dataset.points.items, dataset.interpolation_steps), + } + + return path; +} + +fn appendSteppedPoints(path: *std.array_list.Managed(Point), points: []const Point, mode: Interpolation) !void { + if (points.len == 0) return; + try path.append(points[0]); + + for (points[1..], 1..) |point, index| { + const prev = points[index - 1]; + switch (mode) { + .step_start => { + try path.append(.{ .x = prev.x, .y = point.y }); + }, + .step_center => { + const mid_x = prev.x + (point.x - prev.x) / 2.0; + try path.append(.{ .x = mid_x, .y = prev.y }); + try path.append(.{ .x = mid_x, .y = point.y }); + }, + .step_end => { + try path.append(.{ .x = point.x, .y = prev.y }); + }, + else => unreachable, + } + try path.append(point); + } +} + +fn appendCatmullRomPoints(path: *std.array_list.Managed(Point), points: []const Point, steps: u8, tension: f64) !void { + if (points.len <= 2) { + try path.appendSlice(points); + return; + } + + const alpha = 1.0 - tension; + try path.append(points[0]); + + var i: usize = 0; + while (i + 1 < points.len) : (i += 1) { + const p0 = if (i == 0) points[i] else points[i - 1]; + const p1 = points[i]; + const p2 = points[i + 1]; + const p3 = if (i + 2 < points.len) points[i + 2] else points[i + 1]; + + var step: usize = 1; + while (step <= steps) : (step += 1) { + const t = @as(f64, @floatFromInt(step)) / @as(f64, @floatFromInt(steps)); + try path.append(catmullRomPoint(p0, p1, p2, p3, t, alpha)); + } + } +} + +fn catmullRomPoint(p0: Point, p1: Point, p2: Point, p3: Point, t: f64, alpha: f64) Point { + const t2 = t * t; + const t3 = t2 * t; + + const a0 = -alpha * t3 + 2.0 * alpha * t2 - alpha * t; + const a1 = (2.0 - alpha) * t3 + (alpha - 3.0) * t2 + 1.0; + const a2 = (alpha - 2.0) * t3 + (3.0 - 2.0 * alpha) * t2 + alpha * t; + const a3 = alpha * t3 - alpha * t2; + + return .{ + .x = a0 * p0.x + a1 * p1.x + a2 * p2.x + a3 * p3.x, + .y = a0 * p0.y + a1 * p1.y + a2 * p2.y + a3 * p3.y, + }; +} + +fn appendMonotonePoints(allocator: std.mem.Allocator, path: *std.array_list.Managed(Point), points: []const Point, steps: u8) !void { + if (points.len <= 2 or !strictlyIncreasingX(points)) { + try path.appendSlice(points); + return; + } + + const delta = try allocator.alloc(f64, points.len - 1); + defer allocator.free(delta); + const slopes = try allocator.alloc(f64, points.len); + defer allocator.free(slopes); + + for (0..points.len - 1) |i| { + const dx = points[i + 1].x - points[i].x; + if (dx <= 0) { + try path.appendSlice(points); + return; + } + delta[i] = (points[i + 1].y - points[i].y) / dx; + } + + slopes[0] = delta[0]; + slopes[points.len - 1] = delta[delta.len - 1]; + + for (1..points.len - 1) |i| { + if (delta[i - 1] == 0 or delta[i] == 0 or std.math.signbit(delta[i - 1]) != std.math.signbit(delta[i])) { + slopes[i] = 0; + } else { + const h0 = points[i].x - points[i - 1].x; + const h1 = points[i + 1].x - points[i].x; + const w1 = 2.0 * h1 + h0; + const w2 = h1 + 2.0 * h0; + slopes[i] = (w1 + w2) / (w1 / delta[i - 1] + w2 / delta[i]); + } + } + + try path.append(points[0]); + for (0..points.len - 1) |i| { + const p0 = points[i]; + const p1 = points[i + 1]; + const dx = p1.x - p0.x; + + var step: usize = 1; + while (step <= steps) : (step += 1) { + const t = @as(f64, @floatFromInt(step)) / @as(f64, @floatFromInt(steps)); + const t2 = t * t; + const t3 = t2 * t; + const h00 = 2.0 * t3 - 3.0 * t2 + 1.0; + const h10 = t3 - 2.0 * t2 + t; + const h01 = -2.0 * t3 + 3.0 * t2; + const h11 = t3 - t2; + try path.append(.{ + .x = p0.x + dx * t, + .y = h00 * p0.y + h10 * dx * slopes[i] + h01 * p1.y + h11 * dx * slopes[i + 1], + }); + } + } +} + +fn strictlyIncreasingX(points: []const Point) bool { + for (points[1..], 1..) |point, index| { + if (!(point.x > points[index - 1].x)) return false; + } + return true; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig new file mode 100644 index 0000000..0c2ac41 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig @@ -0,0 +1,253 @@ +//! Shared plotting primitives for chart-like components. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("../layout/measure.zig"); +const style_mod = @import("../style/style.zig"); + +pub const Style = style_mod.Style; + +pub const Point = struct { + x: f64, + y: f64, +}; + +pub const DataRange = struct { + min: f64, + max: f64, + + pub fn normalized(self: DataRange) DataRange { + if (!std.math.isFinite(self.min) or !std.math.isFinite(self.max)) { + return .{ .min = 0, .max = 1 }; + } + + if (self.min == self.max) { + return .{ + .min = self.min - 0.5, + .max = self.max + 0.5, + }; + } + + if (self.min < self.max) return self; + + return .{ + .min = self.max, + .max = self.min, + }; + } + + pub fn span(self: DataRange) f64 { + const normalized_range = self.normalized(); + return normalized_range.max - normalized_range.min; + } +}; + +pub const Marker = enum { + braille, + block, + dot, + ascii, +}; + +pub const GraphType = enum { + line, + scatter, + area, +}; + +pub const Interpolation = enum { + linear, + step_start, + step_center, + step_end, + catmull_rom, + monotone_cubic, +}; + +pub const Orientation = enum { + vertical, + horizontal, +}; + +pub const Summary = enum { + last, + average, + minimum, + maximum, + sum, +}; + +pub const LegendPosition = enum { + hidden, + top, + bottom, + left, + right, +}; + +pub const AxisLabel = struct { + value: f64, + text: []const u8, +}; + +pub const ValueFormatter = *const fn (std.mem.Allocator, f64) anyerror![]const u8; + +pub const Glyph = union(enum) { + slice: []const u8, + codepoint: u21, +}; + +pub const Cell = struct { + glyph: Glyph = .{ .slice = " " }, + style: ?Style = null, +}; + +pub const CellBuffer = struct { + allocator: std.mem.Allocator, + width: usize, + height: usize, + cells: []Cell, + + pub fn init(allocator: std.mem.Allocator, width: usize, height: usize) !CellBuffer { + const cells = try allocator.alloc(Cell, width * height); + for (cells) |*cell| cell.* = .{}; + + return .{ + .allocator = allocator, + .width = width, + .height = height, + .cells = cells, + }; + } + + pub fn deinit(self: *CellBuffer) void { + self.allocator.free(self.cells); + } + + pub fn clear(self: *CellBuffer) void { + for (self.cells) |*cell| cell.* = .{}; + } + + fn index(self: *const CellBuffer, x: usize, y: usize) usize { + return y * self.width + x; + } + + pub fn setGlyph(self: *CellBuffer, x: usize, y: usize, glyph: Glyph, style: ?Style) void { + if (x >= self.width or y >= self.height) return; + self.cells[self.index(x, y)] = .{ + .glyph = glyph, + .style = style, + }; + } + + pub fn setSlice(self: *CellBuffer, x: usize, y: usize, glyph: []const u8, style: ?Style) void { + self.setGlyph(x, y, .{ .slice = glyph }, style); + } + + pub fn setCodepoint(self: *CellBuffer, x: usize, y: usize, codepoint: u21, style: ?Style) void { + self.setGlyph(x, y, .{ .codepoint = codepoint }, style); + } + + pub fn writeText(self: *CellBuffer, x: usize, y: usize, text: []const u8, style: ?Style) void { + if (y >= self.height) return; + + var col = x; + var i: usize = 0; + while (i < text.len and col < self.width) { + const byte_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; + const end = @min(text.len, i + byte_len); + const glyph = text[i..end]; + + var codepoint_width: usize = 1; + if (end <= text.len) { + const cp = std.unicode.utf8Decode(glyph) catch 0; + if (cp != 0) { + codepoint_width = @max(1, measure.charWidth(cp)); + } + } + + self.setSlice(col, y, glyph, style); + if (codepoint_width > 1) { + var extra: usize = 1; + while (extra < codepoint_width and col + extra < self.width) : (extra += 1) { + self.setSlice(col + extra, y, " ", style); + } + } + + col += codepoint_width; + i = end; + } + } + + pub fn render(self: *const CellBuffer, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var glyph_buf: [4]u8 = undefined; + + for (0..self.height) |y| { + if (y > 0) try writer.writeByte('\n'); + + for (0..self.width) |x| { + const cell = self.cells[self.index(x, y)]; + const glyph = switch (cell.glyph) { + .slice => |slice| slice, + .codepoint => |cp| blk: { + const len = try std.unicode.utf8Encode(cp, &glyph_buf); + break :blk glyph_buf[0..len]; + }, + }; + + if (cell.style) |base_style| { + var inline_style = base_style.inline_style(true); + const rendered = try inline_style.render(allocator, glyph); + defer allocator.free(rendered); + try writer.writeAll(rendered); + } else { + try writer.writeAll(glyph); + } + } + } + + return try result.toOwnedSlice(); + } +}; + +pub fn inlineStyle(style: Style) Style { + return style.inline_style(true); +} + +pub fn clampUnit(value: f64) f64 { + if (value < 0) return 0; + if (value > 1) return 1; + return value; +} + +pub fn mapToResolution(value: f64, range: DataRange, resolution: usize) usize { + if (resolution <= 1) return 0; + + const normalized = range.normalized(); + const span = normalized.max - normalized.min; + if (span <= 0) return 0; + + const unit = clampUnit((value - normalized.min) / span); + return @intFromFloat(@round(unit * @as(f64, @floatFromInt(resolution - 1)))); +} + +pub fn mapX(value: f64, range: DataRange, width: usize) usize { + return mapToResolution(value, range, width); +} + +pub fn mapY(value: f64, range: DataRange, height: usize) usize { + if (height <= 1) return 0; + const mapped = mapToResolution(value, range, height); + return (height - 1) - mapped; +} + +pub fn defaultFormatter(allocator: std.mem.Allocator, value: f64) ![]const u8 { + if (value == @trunc(value)) { + return try std.fmt.allocPrint(allocator, "{d}", .{@as(i64, @intFromFloat(value))}); + } + + return try std.fmt.allocPrint(allocator, "{d:.2}", .{value}); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig new file mode 100644 index 0000000..9cdb38a --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig @@ -0,0 +1,434 @@ +//! Checkbox and CheckboxGroup components. +//! Standalone boolean toggle and multi-select checkbox group. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +/// Standalone checkbox - a single boolean toggle. +pub const Checkbox = struct { + label: []const u8, + checked: bool, + enabled: bool, + focused: bool, + + // Symbols + checked_symbol: []const u8, + unchecked_symbol: []const u8, + + // Styling + label_style: style_mod.Style, + checked_style: style_mod.Style, + unchecked_style: style_mod.Style, + focused_style: style_mod.Style, + disabled_style: style_mod.Style, + + pub fn init(label: []const u8) Checkbox { + return .{ + .label = label, + .checked = false, + .enabled = true, + .focused = true, + .checked_symbol = "[x] ", + .unchecked_symbol = "[ ] ", + .label_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .checked_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .unchecked_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .focused_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.magenta); + s = s.inline_style(true); + break :blk s; + }, + .disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn toggle(self: *Checkbox) void { + if (!self.enabled) return; + self.checked = !self.checked; + } + + pub fn setChecked(self: *Checkbox, value: bool) void { + self.checked = value; + } + + pub fn isChecked(self: *const Checkbox) bool { + return self.checked; + } + + pub fn focus(self: *Checkbox) void { + self.focused = true; + } + + pub fn blur(self: *Checkbox) void { + self.focused = false; + } + + pub fn handleKey(self: *Checkbox, key: keys.KeyEvent) void { + if (!self.focused or !self.enabled) return; + + switch (key.key) { + .space, .enter => self.toggle(), + else => {}, + } + } + + pub fn view(self: *const Checkbox, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const symbol = if (self.checked) self.checked_symbol else self.unchecked_symbol; + const sym_style = if (!self.enabled) + self.disabled_style + else if (self.checked) + self.checked_style + else + self.unchecked_style; + + const styled_symbol = try sym_style.render(allocator, symbol); + try writer.writeAll(styled_symbol); + + const lbl_style = if (!self.enabled) + self.disabled_style + else if (self.focused) + self.focused_style + else + self.label_style; + + const styled_label = try lbl_style.render(allocator, self.label); + try writer.writeAll(styled_label); + + return result.toOwnedSlice(); + } +}; + +/// Multi-select checkbox group. +pub fn CheckboxGroup(comptime T: type) type { + return struct { + allocator: std.mem.Allocator, + + // Items + items: std.array_list.Managed(Item), + + // Navigation + cursor: usize, + height: u16, + y_offset: usize, + + // Focus + focused: bool, + + // Constraints + min_selected: usize, + max_selected: ?usize, + + // Symbols + cursor_symbol: []const u8, + checked_symbol: []const u8, + unchecked_symbol: []const u8, + + // Styling + item_style: style_mod.Style, + checked_style: style_mod.Style, + cursor_style: style_mod.Style, + disabled_style: style_mod.Style, + + const Self = @This(); + + pub const Item = struct { + value: T, + label: []const u8, + description: []const u8, + enabled: bool, + checked: bool, + + pub fn init(value: T, label: []const u8) Item { + return .{ + .value = value, + .label = label, + .description = "", + .enabled = true, + .checked = false, + }; + } + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .items = std.array_list.Managed(Item).init(allocator), + .cursor = 0, + .height = 10, + .y_offset = 0, + .focused = true, + .min_selected = 0, + .max_selected = null, + .cursor_symbol = "> ", + .checked_symbol = "[x] ", + .unchecked_symbol = "[ ] ", + .item_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .checked_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.magenta); + s = s.inline_style(true); + break :blk s; + }, + .disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *Self) void { + self.items.deinit(); + } + + pub fn addItem(self: *Self, item: Item) !void { + try self.items.append(item); + } + + pub fn addItems(self: *Self, new_items: []const Item) !void { + try self.items.appendSlice(new_items); + } + + pub fn toggleCurrent(self: *Self) void { + if (self.cursor >= self.items.items.len) return; + const item = &self.items.items[self.cursor]; + if (!item.enabled) return; + + if (item.checked) { + // Check min constraint + if (self.checkedCount() <= self.min_selected) return; + item.checked = false; + } else { + // Check max constraint + if (self.max_selected) |max| { + if (self.checkedCount() >= max) return; + } + item.checked = true; + } + } + + pub fn selectAll(self: *Self) void { + for (self.items.items) |*item| { + if (item.enabled) item.checked = true; + } + } + + pub fn selectNone(self: *Self) void { + for (self.items.items) |*item| { + if (item.enabled) item.checked = false; + } + } + + pub fn invertSelection(self: *Self) void { + for (self.items.items) |*item| { + if (item.enabled) item.checked = !item.checked; + } + } + + pub fn checkedCount(self: *const Self) usize { + var count: usize = 0; + for (self.items.items) |item| { + if (item.checked) count += 1; + } + return count; + } + + pub fn checkedValues(self: *const Self, allocator: std.mem.Allocator) ![]const T { + var result = std.array_list.Managed(T).init(allocator); + for (self.items.items) |item| { + if (item.checked) try result.append(item.value); + } + return result.toOwnedSlice(); + } + + // Focus protocol + pub fn focus(self: *Self) void { + self.focused = true; + } + + pub fn blur(self: *Self) void { + self.focused = false; + } + + pub fn handleKey(self: *Self, key: keys.KeyEvent) void { + if (!self.focused) return; + + switch (key.key) { + .up => self.cursorUp(), + .down => self.cursorDown(), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoFirst(), + .end => self.gotoLast(), + .space => self.toggleCurrent(), + .char => |c| switch (c) { + 'j' => self.cursorDown(), + 'k' => self.cursorUp(), + 'g' => self.gotoFirst(), + 'G' => self.gotoLast(), + 'a' => self.selectAll(), + 'n' => self.selectNone(), + 'i' => self.invertSelection(), + else => {}, + }, + else => {}, + } + } + + fn cursorUp(self: *Self) void { + if (self.items.items.len == 0) return; + if (self.cursor > 0) { + self.cursor -= 1; + } else { + self.cursor = self.items.items.len - 1; + } + self.ensureVisible(); + } + + fn cursorDown(self: *Self) void { + if (self.items.items.len == 0) return; + if (self.cursor < self.items.items.len - 1) { + self.cursor += 1; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + fn pageUp(self: *Self) void { + if (self.cursor >= self.height) { + self.cursor -= self.height; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + fn pageDown(self: *Self) void { + if (self.cursor + self.height < self.items.items.len) { + self.cursor += self.height; + } else if (self.items.items.len > 0) { + self.cursor = self.items.items.len - 1; + } + self.ensureVisible(); + } + + fn gotoFirst(self: *Self) void { + self.cursor = 0; + self.y_offset = 0; + } + + fn gotoLast(self: *Self) void { + if (self.items.items.len > 0) { + self.cursor = self.items.items.len - 1; + self.ensureVisible(); + } + } + + fn ensureVisible(self: *Self) void { + if (self.cursor < self.y_offset) { + self.y_offset = self.cursor; + } else if (self.cursor >= self.y_offset + self.height) { + self.y_offset = self.cursor - self.height + 1; + } + } + + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var rendered: usize = 0; + while (rendered < self.height) : (rendered += 1) { + if (rendered > 0) try writer.writeByte('\n'); + + const idx = self.y_offset + rendered; + if (idx >= self.items.items.len) break; + + const item = self.items.items[idx]; + + // Cursor + if (idx == self.cursor and self.focused) { + const styled = try self.cursor_style.render(allocator, self.cursor_symbol); + try writer.writeAll(styled); + } else { + for (0..self.cursor_symbol.len) |_| { + try writer.writeByte(' '); + } + } + + // Check symbol + const check_sym = if (item.checked) self.checked_symbol else self.unchecked_symbol; + const check_s = if (!item.enabled) + self.disabled_style + else if (item.checked) + self.checked_style + else + self.item_style; + const styled_check = try check_s.render(allocator, check_sym); + try writer.writeAll(styled_check); + + // Label + const lbl_style = if (!item.enabled) + self.disabled_style + else if (idx == self.cursor and self.focused) + self.cursor_style + else if (item.checked) + self.checked_style + else + self.item_style; + const styled_label = try lbl_style.render(allocator, item.label); + try writer.writeAll(styled_label); + + // Description + if (item.description.len > 0) { + try writer.writeAll(" - "); + try writer.writeAll(item.description); + } + } + + return result.toOwnedSlice(); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig new file mode 100644 index 0000000..2798003 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig @@ -0,0 +1,255 @@ +//! Code viewer with syntax highlighting. +//! Provides keyword-based highlighting for common languages. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const CodeView = struct { + source: []const u8 = "", + language: Language = .zig, + show_line_numbers: bool = true, + start_line: usize = 1, + /// Highlight specific line (1-indexed, 0 = none). + highlight_line: usize = 0, + /// Line number width (number of digits, 0 = auto). + line_number_width: u8 = 4, + /// Separator between line numbers and code. + line_separator: []const u8 = "\xe2\x94\x82", + /// Tab display width. + tab_width: u8 = 4, + /// Operator style. + operator_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + + // Styles + keyword_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.magenta); + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + string_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + comment_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(10)); + s = s.italic(true); + s = s.inline_style(true); + break :blk s; + }, + number_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + type_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + builtin_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + line_number_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + highlight_bg: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bg(.fromRgb(40, 40, 60)); + s = s.inline_style(true); + break :blk s; + }, + + pub const Language = enum { + zig, + python, + javascript, + go, + rust, + plain, + }; + + pub fn view(self: *const CodeView, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var lines = std.mem.splitScalar(u8, self.source, '\n'); + var line_num: usize = self.start_line; + var first = true; + var in_multiline_comment = false; + + while (lines.next()) |line| { + if (!first) writer.writeByte('\n') catch {}; + first = false; + + // Line number + if (self.show_line_numbers) { + const num_str = std.fmt.allocPrint(allocator, "{d:>4} {s} ", .{ line_num, self.line_separator }) catch " ? | "; + writer.writeAll(self.line_number_style.render(allocator, num_str) catch num_str) catch {}; + } + + // Highlight line background + const is_highlighted = (self.highlight_line > 0 and line_num == self.highlight_line); + + // Syntax highlight the line + const highlighted = self.highlightLine(allocator, line, &in_multiline_comment); + if (is_highlighted) { + writer.writeAll(self.highlight_bg.render(allocator, highlighted) catch highlighted) catch {}; + } else { + writer.writeAll(highlighted) catch {}; + } + + line_num += 1; + } + + return result.toArrayList().items; + } + + fn highlightLine(self: *const CodeView, allocator: std.mem.Allocator, line: []const u8, in_multiline: *bool) []const u8 { + if (self.language == .plain) return line; + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var i: usize = 0; + while (i < line.len) { + // Multi-line comment continuation + if (in_multiline.*) { + if (i + 1 < line.len and line[i] == '*' and line[i + 1] == '/') { + writer.writeAll(self.comment_style.render(allocator, "*/") catch "*/") catch {}; + i += 2; + in_multiline.* = false; + continue; + } + writer.writeAll(self.comment_style.render(allocator, line[i .. i + 1]) catch line[i .. i + 1]) catch {}; + i += 1; + continue; + } + + // Line comments + if (isLineComment(self.language, line, i)) { + writer.writeAll(self.comment_style.render(allocator, line[i..]) catch line[i..]) catch {}; + break; + } + + // Multi-line comment start + if (i + 1 < line.len and line[i] == '/' and line[i + 1] == '*') { + in_multiline.* = true; + writer.writeAll(self.comment_style.render(allocator, "/*") catch "/*") catch {}; + i += 2; + continue; + } + + // Strings + if (line[i] == '"' or line[i] == '\'') { + const quote = line[i]; + const str_start = i; + i += 1; + while (i < line.len and line[i] != quote) { + if (line[i] == '\\') i += 1; // skip escape + i += 1; + } + if (i < line.len) i += 1; // closing quote + writer.writeAll(self.string_style.render(allocator, line[str_start..i]) catch line[str_start..i]) catch {}; + continue; + } + + // Builtins (Zig @-prefixed) + if (self.language == .zig and line[i] == '@' and i + 1 < line.len and std.ascii.isAlphabetic(line[i + 1])) { + const start = i; + i += 1; + while (i < line.len and (std.ascii.isAlphanumeric(line[i]) or line[i] == '_')) : (i += 1) {} + writer.writeAll(self.builtin_style.render(allocator, line[start..i]) catch line[start..i]) catch {}; + continue; + } + + // Numbers + if (std.ascii.isDigit(line[i])) { + const start = i; + while (i < line.len and (std.ascii.isDigit(line[i]) or line[i] == '.' or line[i] == 'x' or line[i] == '_')) : (i += 1) {} + writer.writeAll(self.number_style.render(allocator, line[start..i]) catch line[start..i]) catch {}; + continue; + } + + // Identifiers / keywords + if (std.ascii.isAlphabetic(line[i]) or line[i] == '_') { + const start = i; + while (i < line.len and (std.ascii.isAlphanumeric(line[i]) or line[i] == '_')) : (i += 1) {} + const word = line[start..i]; + + if (isKeyword(self.language, word)) { + writer.writeAll(self.keyword_style.render(allocator, word) catch word) catch {}; + } else if (isType(self.language, word)) { + writer.writeAll(self.type_style.render(allocator, word) catch word) catch {}; + } else { + writer.writeAll(word) catch {}; + } + continue; + } + + // Other characters + writer.writeByte(line[i]) catch {}; + i += 1; + } + + return result.toArrayList().items; + } + + fn isLineComment(lang: Language, line: []const u8, pos: usize) bool { + return switch (lang) { + .zig, .go, .rust, .javascript => pos + 1 < line.len and line[pos] == '/' and line[pos + 1] == '/', + .python => line[pos] == '#', + .plain => false, + }; + } + + fn isKeyword(lang: Language, word: []const u8) bool { + const keywords = switch (lang) { + .zig => &[_][]const u8{ "const", "var", "fn", "pub", "return", "if", "else", "while", "for", "switch", "break", "continue", "defer", "errdefer", "try", "catch", "comptime", "inline", "struct", "enum", "union", "error", "test", "unreachable", "undefined", "null", "true", "false", "and", "or", "orelse", "import" }, + .python => &[_][]const u8{ "def", "class", "if", "elif", "else", "for", "while", "return", "import", "from", "as", "try", "except", "finally", "with", "yield", "lambda", "pass", "break", "continue", "True", "False", "None", "and", "or", "not", "in", "is", "raise", "async", "await" }, + .javascript => &[_][]const u8{ "const", "let", "var", "function", "return", "if", "else", "for", "while", "switch", "case", "break", "continue", "class", "extends", "new", "this", "import", "export", "from", "async", "await", "try", "catch", "finally", "throw", "typeof", "instanceof", "true", "false", "null", "undefined" }, + .go => &[_][]const u8{ "func", "var", "const", "type", "struct", "interface", "return", "if", "else", "for", "switch", "case", "break", "continue", "defer", "go", "select", "chan", "map", "range", "import", "package", "true", "false", "nil" }, + .rust => &[_][]const u8{ "fn", "let", "mut", "const", "pub", "return", "if", "else", "for", "while", "loop", "match", "struct", "enum", "impl", "trait", "use", "mod", "crate", "self", "super", "move", "async", "await", "true", "false", "where" }, + .plain => &[_][]const u8{}, + }; + for (keywords) |kw| { + if (std.mem.eql(u8, word, kw)) return true; + } + return false; + } + + fn isType(lang: Language, word: []const u8) bool { + const types = switch (lang) { + .zig => &[_][]const u8{ "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "f32", "f64", "bool", "void", "usize", "isize", "type", "anytype", "anyerror", "noreturn" }, + .python => &[_][]const u8{ "int", "float", "str", "bool", "list", "dict", "tuple", "set", "bytes", "type", "object" }, + .javascript => &[_][]const u8{ "number", "string", "boolean", "object", "Array", "Promise", "Map", "Set" }, + .go => &[_][]const u8{ "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "string", "bool", "byte", "rune", "error" }, + .rust => &[_][]const u8{ "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "bool", "str", "String", "Vec", "Box", "Option", "Result", "usize", "isize" }, + .plain => &[_][]const u8{}, + }; + for (types) |t| { + if (std.mem.eql(u8, word, t)) return true; + } + return false; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig new file mode 100644 index 0000000..7c15e9e --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig @@ -0,0 +1,422 @@ +//! 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 Writer = std.Io.Writer; +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"); +const action_mod = @import("../core/action.zig"); +const ActionRegistry = action_mod.ActionRegistry; + +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(.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(.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(.gray(10)); + desc_s = desc_s.inline_style(true); + + var shortcut_s = style_mod.Style{}; + shortcut_s = shortcut_s.fg(.gray(8)); + shortcut_s = shortcut_s.inline_style(true); + + var selected_s = style_mod.Style{}; + selected_s = selected_s.bg(.gray(4)); + selected_s = selected_s.inline_style(true); + + var selected_label_s = style_mod.Style{}; + selected_label_s = selected_label_s.bg(.gray(4)); + selected_label_s = selected_label_s.fg(.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(.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 = .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.freeAllCommandStrings(); + self.commands.deinit(); + self.filtered.deinit(); + self.query.deinit(); + } + + /// Add a command. The palette clones every string in `cmd` (id, label, + /// description, shortcut) so the caller is free to pass arena-allocated, + /// formatted, or otherwise short-lived strings — no lifetime tracking + /// required. + pub fn addCommand(self: *CommandPalette, cmd: Command) !void { + const owned = try self.cloneCommand(cmd); + errdefer self.freeCommand(owned); + try self.commands.append(owned); + try self.rebuildFilter(); + } + + /// Replace all commands. Each input command's strings are cloned. Old + /// commands are freed. + pub fn setCommands(self: *CommandPalette, cmds: []const Command) !void { + self.freeAllCommandStrings(); + self.commands.clearRetainingCapacity(); + for (cmds) |cmd| { + const owned = try self.cloneCommand(cmd); + errdefer self.freeCommand(owned); + try self.commands.append(owned); + } + try self.rebuildFilter(); + } + + /// Convenience: load every enabled action from a registry, formatting its + /// binding as the shortcut hint. Cleaner than building Command structs by + /// hand and avoids the need to manage shortcut-string lifetimes. + pub fn setFromRegistry(self: *CommandPalette, registry: *const ActionRegistry) !void { + self.freeAllCommandStrings(); + self.commands.clearRetainingCapacity(); + for (registry.actions.items) |a| { + if (!a.enabled) continue; + const shortcut = if (a.binding) |b| + try ActionRegistry.formatKey(self.allocator, b) + else + try self.allocator.dupe(u8, ""); + // shortcut is heap-owned; cloneCommand will dup again, so free + // the temporary after. + defer self.allocator.free(shortcut); + + const owned = try self.cloneCommand(.{ + .id = a.id, + .label = a.label, + .description = a.description, + .shortcut = shortcut, + }); + errdefer self.freeCommand(owned); + try self.commands.append(owned); + } + try self.rebuildFilter(); + } + + /// Reset the typed query and cursor without touching the command list. + pub fn clear(self: *CommandPalette) !void { + self.query.clearRetainingCapacity(); + self.cursor = 0; + try self.rebuildFilter(); + } + + fn cloneCommand(self: *CommandPalette, cmd: Command) !Command { + const id = try self.allocator.dupe(u8, cmd.id); + errdefer self.allocator.free(id); + const label = try self.allocator.dupe(u8, cmd.label); + errdefer self.allocator.free(label); + const description = try self.allocator.dupe(u8, cmd.description); + errdefer self.allocator.free(description); + const shortcut = try self.allocator.dupe(u8, cmd.shortcut); + return .{ + .id = id, + .label = label, + .description = description, + .shortcut = shortcut, + }; + } + + fn freeCommand(self: *CommandPalette, cmd: Command) void { + self.allocator.free(cmd.id); + self.allocator.free(cmd.label); + self.allocator.free(cmd.description); + self.allocator.free(cmd.shortcut); + } + + fn freeAllCommandStrings(self: *CommandPalette) void { + for (self.commands.items) |c| self.freeCommand(c); + } + + /// 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: Writer.Allocating = .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, 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: *Writer, + 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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig new file mode 100644 index 0000000..5dc5b9b --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig @@ -0,0 +1,154 @@ +//! Confirmation dialog component. +//! Simple yes/no prompt with keyboard navigation. + +const std = @import("std"); +const keys = @import("../input/keys.zig"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Confirm = struct { + prompt_text: []const u8, + selected: Selection, + confirmed: ?bool, + active: bool, + focused: bool, + + // Styling + prompt_style: style_mod.Style, + active_style: style_mod.Style, + inactive_style: style_mod.Style, + + pub const Selection = enum { + yes, + no, + }; + + pub fn init(prompt_text: []const u8) Confirm { + return .{ + .prompt_text = prompt_text, + .selected = .yes, + .confirmed = null, + .active = false, + .focused = true, + .prompt_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .active_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .inactive_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + /// Show the confirmation dialog + pub fn show(self: *Confirm) void { + self.active = true; + self.confirmed = null; + self.selected = .yes; + } + + /// Hide the dialog + pub fn hide(self: *Confirm) void { + self.active = false; + } + + /// Check if confirmed (returns true for yes, false for no, null if not yet confirmed) + pub fn result(self: *const Confirm) ?bool { + return self.confirmed; + } + + /// Set focused state (for use with FocusGroup). + pub fn focus(self: *Confirm) void { + self.focused = true; + } + + /// Clear focused state (for use with FocusGroup). + pub fn blur(self: *Confirm) void { + self.focused = false; + } + + /// Handle a key event + pub fn handleKey(self: *Confirm, key: keys.KeyEvent) void { + if (!self.active or !self.focused) return; + + switch (key.key) { + .left, .right, .tab => { + self.selected = if (self.selected == .yes) .no else .yes; + }, + .char => |c| switch (c) { + 'y', 'Y' => { + self.confirmed = true; + self.active = false; + }, + 'n', 'N' => { + self.confirmed = false; + self.active = false; + }, + 'h' => self.selected = .yes, + 'l' => self.selected = .no, + else => {}, + }, + .enter => { + self.confirmed = (self.selected == .yes); + self.active = false; + }, + .escape => { + self.confirmed = false; + self.active = false; + }, + else => {}, + } + } + + /// Render the confirmation dialog + pub fn view(self: *const Confirm, allocator: std.mem.Allocator) ![]const u8 { + if (!self.active) { + return try allocator.dupe(u8, ""); + } + + var result_buf: Writer.Allocating = .init(allocator); + const writer = &result_buf.writer; + + // Prompt + const styled_prompt = try self.prompt_style.render(allocator, self.prompt_text); + try writer.writeAll(styled_prompt); + try writer.writeAll(" "); + + // Yes option + const yes_style = if (self.selected == .yes) self.active_style else self.inactive_style; + if (self.selected == .yes) { + const styled = try yes_style.render(allocator, "[Yes]"); + try writer.writeAll(styled); + } else { + const styled = try yes_style.render(allocator, " Yes "); + try writer.writeAll(styled); + } + + try writer.writeAll(" "); + + // No option + const no_style = if (self.selected == .no) self.active_style else self.inactive_style; + if (self.selected == .no) { + const styled = try no_style.render(allocator, "[No]"); + try writer.writeAll(styled); + } else { + const styled = try no_style.render(allocator, " No "); + try writer.writeAll(styled); + } + + return result_buf.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig new file mode 100644 index 0000000..6dcaee5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig @@ -0,0 +1,392 @@ +//! Context menu component. +//! Popup menu triggered by keyboard shortcut or mouse, positioned at a target location. + +const std = @import("std"); +const Writer = std.Io.Writer; +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"); + +pub fn ContextMenu(comptime Action: type) type { + return struct { + const max_items = 20; + + // Items + items: [max_items]?MenuItem, + item_count: usize, + + // State + visible: bool, + cursor: usize, + selected_action: ?Action, + + // Position + x: usize, + y: usize, + + // Styling + item_style: style_mod.Style, + active_style: style_mod.Style, + disabled_style: style_mod.Style, + separator_style: style_mod.Style, + shortcut_style: style_mod.Style, + border_chars: border_mod.BorderChars, + border_fg: Color, + + const Self = @This(); + + pub const MenuItem = union(enum) { + action: ActionItem, + separator: void, + }; + + pub const ActionItem = struct { + label: []const u8, + shortcut_display: []const u8, + action: Action, + enabled: bool, + }; + + pub fn init() Self { + return .{ + .items = [_]?MenuItem{null} ** max_items, + .item_count = 0, + .visible = false, + .cursor = 0, + .selected_action = null, + .x = 0, + .y = 0, + .item_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(18)); + s = s.inline_style(true); + break :blk s; + }, + .active_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.white); + s = s.bg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + .separator_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + .shortcut_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .border_chars = .rounded, + .border_fg = .gray(14), + }; + } + + /// Add an action item. + pub fn addItem(self: *Self, label: []const u8, shortcut: []const u8, action: Action) void { + if (self.item_count >= max_items) return; + self.items[self.item_count] = .{ .action = .{ + .label = label, + .shortcut_display = shortcut, + .action = action, + .enabled = true, + } }; + self.item_count += 1; + } + + /// Add a disabled item. + pub fn addDisabledItem(self: *Self, label: []const u8, action: Action) void { + if (self.item_count >= max_items) return; + self.items[self.item_count] = .{ .action = .{ + .label = label, + .shortcut_display = "", + .action = action, + .enabled = false, + } }; + self.item_count += 1; + } + + /// Add a separator. + pub fn addSeparator(self: *Self) void { + if (self.item_count >= max_items) return; + self.items[self.item_count] = .{ .separator = {} }; + self.item_count += 1; + } + + /// Show the menu at a position. + pub fn show(self: *Self, pos_x: usize, pos_y: usize) void { + self.visible = true; + self.cursor = 0; + self.selected_action = null; + self.x = pos_x; + self.y = pos_y; + self.skipToNextEnabled(); + } + + /// Show clamped to terminal bounds. + pub fn showClamped(self: *Self, pos_x: usize, pos_y: usize, term_width: usize, term_height: usize) void { + const menu_width = self.calcWidth() + 4; // borders + padding + const menu_height = self.item_count + 2; // borders + + const clamped_x = if (pos_x + menu_width > term_width) + term_width -| menu_width + else + pos_x; + + const clamped_y = if (pos_y + menu_height > term_height) + term_height -| menu_height + else + pos_y; + + self.show(clamped_x, clamped_y); + } + + /// Hide the menu. + pub fn hide(self: *Self) void { + self.visible = false; + } + + pub fn isVisible(self: *const Self) bool { + return self.visible; + } + + /// Get and consume the selected action. + pub fn getSelectedAction(self: *Self) ?Action { + const act = self.selected_action; + self.selected_action = null; + return act; + } + + /// Handle key events. Returns true if consumed. + pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { + if (!self.visible) return false; + + switch (key.key) { + .up => { + self.moveCursorUp(); + return true; + }, + .down => { + self.moveCursorDown(); + return true; + }, + .enter => { + self.selectCurrent(); + return true; + }, + .escape => { + self.hide(); + return true; + }, + .char => |c| { + switch (c) { + 'k' => { + self.moveCursorUp(); + return true; + }, + 'j' => { + self.moveCursorDown(); + return true; + }, + else => return false, + } + }, + else => return false, + } + } + + fn moveCursorUp(self: *Self) void { + if (self.item_count == 0) return; + var pos = self.cursor; + var attempts: usize = 0; + while (attempts < self.item_count) : (attempts += 1) { + if (pos == 0) { + pos = self.item_count - 1; + } else { + pos -= 1; + } + if (self.isSelectable(self.items[pos])) { + self.cursor = pos; + return; + } + } + } + + fn moveCursorDown(self: *Self) void { + if (self.item_count == 0) return; + var pos = self.cursor; + var attempts: usize = 0; + while (attempts < self.item_count) : (attempts += 1) { + pos = if (pos + 1 < self.item_count) pos + 1 else 0; + if (self.isSelectable(self.items[pos])) { + self.cursor = pos; + return; + } + } + } + + fn skipToNextEnabled(self: *Self) void { + if (self.item_count == 0) return; + if (self.isSelectable(self.items[self.cursor])) return; + self.moveCursorDown(); + } + + fn isSelectable(_: *const Self, maybe_item: ?MenuItem) bool { + const item = maybe_item orelse return false; + return switch (item) { + .action => |a| a.enabled, + .separator => false, + }; + } + + fn selectCurrent(self: *Self) void { + if (self.cursor >= self.item_count) return; + const item = self.items[self.cursor] orelse return; + switch (item) { + .action => |a| { + if (a.enabled) { + self.selected_action = a.action; + self.hide(); + } + }, + .separator => {}, + } + } + + fn calcWidth(self: *const Self) usize { + var max_label: usize = 0; + var max_shortcut: usize = 0; + for (self.items[0..self.item_count]) |maybe_item| { + const item = maybe_item orelse continue; + switch (item) { + .action => |a| { + const lw = measure.width(a.label); + if (lw > max_label) max_label = lw; + const sw = measure.width(a.shortcut_display); + if (sw > max_shortcut) max_shortcut = sw; + }, + .separator => {}, + } + } + return max_label + max_shortcut + 4; + } + + /// Render the context menu. + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + if (!self.visible) return try allocator.dupe(u8, ""); + + var result: Writer.Allocating = .init(allocator); + const w = &result.writer; + + const inner_width = self.calcWidth(); + + // Indent to x position + // Top border + try self.writeIndent(w, self.x); + try self.writeBorder(w, allocator, inner_width, .top); + try w.writeByte('\n'); + + // Items + for (self.items[0..self.item_count], 0..) |maybe_item, i| { + const item = maybe_item orelse continue; + + try self.writeIndent(w, self.x); + + switch (item) { + .separator => { + try self.writeBorder(w, allocator, inner_width, .middle); + }, + .action => |a| { + try self.writeBorderChar(w, allocator, .left); + + const is_active = (i == self.cursor); + const s = if (!a.enabled) self.disabled_style else if (is_active) self.active_style else self.item_style; + + var line: Writer.Allocating = .init(allocator); + const lw = &line.writer; + try lw.writeByte(' '); + try lw.writeAll(a.label); + + const label_w = measure.width(a.label); + const shortcut_w = measure.width(a.shortcut_display); + const gap = inner_width -| label_w -| shortcut_w -| 2; + for (0..gap) |_| try lw.writeByte(' '); + + if (a.shortcut_display.len > 0) { + try lw.writeAll(a.shortcut_display); + } + try lw.writeByte(' '); + + const line_text = try line.toOwnedSlice(); + const styled = try s.render(allocator, line_text); + try w.writeAll(styled); + + try self.writeBorderChar(w, allocator, .right); + }, + } + try w.writeByte('\n'); + } + + // Bottom border + try self.writeIndent(w, self.x); + try self.writeBorder(w, allocator, inner_width, .bottom); + + return result.toOwnedSlice(); + } + + const BorderPos = enum { top, middle, bottom }; + const BorderSide = enum { left, right }; + + fn writeIndent(_: *const Self, writer: *Writer, count: usize) !void { + for (0..count) |_| try writer.writeByte(' '); + } + + fn writeBorder(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { + var bs = style_mod.Style{}; + bs = bs.fg(self.border_fg); + bs = bs.inline_style(true); + + const bc = self.border_chars; + const cl = switch (pos) { + .top => bc.top_left, + .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, + .bottom => bc.bottom_left, + }; + const cr = switch (pos) { + .top => bc.top_right, + .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, + .bottom => bc.bottom_right, + }; + + try writer.writeAll(try bs.render(allocator, cl)); + for (0..width) |_| { + try writer.writeAll(try bs.render(allocator, bc.horizontal)); + } + try writer.writeAll(try bs.render(allocator, cr)); + } + + fn writeBorderChar(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { + var bs = style_mod.Style{}; + bs = bs.fg(self.border_fg); + bs = bs.inline_style(true); + const char = switch (side) { + .left, .right => self.border_chars.vertical, + }; + try writer.writeAll(try bs.render(allocator, char)); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig new file mode 100644 index 0000000..374416c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig @@ -0,0 +1,530 @@ +//! DataTable — table with cell-level cursor, frozen columns, and horizontal +//! scroll. +//! +//! Distinct from the existing `Table` (compile-time column count, row-only +//! cursor) and `SortableTable` (sorting and styling). DataTable targets the +//! "spreadsheet view" use case: many columns, navigable cell-by-cell, +//! leftmost columns pinned so they stay visible while the rest of the grid +//! scrolls horizontally. +//! +//! The column count is runtime, so it's a good fit for dynamic schemas +//! (database results, log fields, CSV files). + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const border_mod = @import("../style/border.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); + +pub const Align = enum { left, center, right }; + +pub const Column = struct { + header: []const u8, + /// Fixed display width in cells. Required (we don't auto-fit since the + /// row store may be huge or lazy-loaded). + width: u16, + @"align": Align = .left, +}; + +pub const DataTable = struct { + allocator: std.mem.Allocator, + + columns: std.array_list.Managed(Column), + /// Row store: each row is a slice of cell strings, length must match + /// columns.len. The DataTable does not own these strings; the caller + /// guarantees they live as long as the table is rendered. + rows: std.array_list.Managed([]const []const u8), + + cursor_row: usize, + cursor_col: usize, + /// Leftmost N columns never scroll out of view. + frozen_columns: usize, + + /// Display config. + width: u16, + height: u16, + show_header: bool, + show_borders: bool, + /// Horizontal scroll offset in *columns* (not cells), excluding frozen. + col_x_offset: usize, + /// Vertical scroll offset in rows. + y_offset: usize, + + /// Styling. + header_style: style_mod.Style, + cell_style: style_mod.Style, + cursor_cell_style: style_mod.Style, + cursor_row_style: style_mod.Style, + frozen_separator_style: style_mod.Style, + border_chars: border_mod.BorderChars, + + pub fn init(allocator: std.mem.Allocator) DataTable { + var header_s = style_mod.Style{}; + header_s = header_s.bold(true); + header_s = header_s.inline_style(true); + + var cell_s = style_mod.Style{}; + cell_s = cell_s.inline_style(true); + + var cursor_cell = style_mod.Style{}; + cursor_cell = cursor_cell.bg(.cyan); + cursor_cell = cursor_cell.fg(.black); + cursor_cell = cursor_cell.inline_style(true); + + var cursor_row = style_mod.Style{}; + cursor_row = cursor_row.bg(.gray(4)); + cursor_row = cursor_row.inline_style(true); + + var frozen_sep = style_mod.Style{}; + frozen_sep = frozen_sep.fg(.gray(8)); + frozen_sep = frozen_sep.inline_style(true); + + return .{ + .allocator = allocator, + .columns = std.array_list.Managed(Column).init(allocator), + .rows = std.array_list.Managed([]const []const u8).init(allocator), + .cursor_row = 0, + .cursor_col = 0, + .frozen_columns = 0, + .width = 80, + .height = 12, + .show_header = true, + .show_borders = false, + .col_x_offset = 0, + .y_offset = 0, + .header_style = header_s, + .cell_style = cell_s, + .cursor_cell_style = cursor_cell, + .cursor_row_style = cursor_row, + .frozen_separator_style = frozen_sep, + .border_chars = .normal, + }; + } + + pub fn deinit(self: *DataTable) void { + self.columns.deinit(); + self.rows.deinit(); + } + + pub fn setColumns(self: *DataTable, cols: []const Column) !void { + self.columns.clearRetainingCapacity(); + try self.columns.appendSlice(cols); + if (self.cursor_col >= self.columns.items.len) { + self.cursor_col = self.columns.items.len -| 1; + } + if (self.frozen_columns > self.columns.items.len) { + self.frozen_columns = self.columns.items.len; + } + } + + pub fn addRow(self: *DataTable, cells: []const []const u8) !void { + if (cells.len != self.columns.items.len) return error.ColumnCountMismatch; + try self.rows.append(cells); + } + + pub fn setRows(self: *DataTable, rows: []const []const []const u8) !void { + for (rows) |r| { + if (r.len != self.columns.items.len) return error.ColumnCountMismatch; + } + self.rows.clearRetainingCapacity(); + try self.rows.appendSlice(rows); + if (self.cursor_row >= self.rows.items.len) { + self.cursor_row = self.rows.items.len -| 1; + } + } + + pub fn setSize(self: *DataTable, w: u16, h: u16) void { + self.width = w; + self.height = h; + } + + pub fn setFrozenColumns(self: *DataTable, n: usize) void { + self.frozen_columns = @min(n, self.columns.items.len); + if (self.cursor_col < self.frozen_columns) { + // Frozen cells are still cursorable. + } + self.col_x_offset = 0; + } + + pub fn moveLeft(self: *DataTable) void { + if (self.cursor_col > 0) self.cursor_col -= 1; + self.ensureCursorVisible(); + } + + pub fn moveRight(self: *DataTable) void { + if (self.cursor_col + 1 < self.columns.items.len) self.cursor_col += 1; + self.ensureCursorVisible(); + } + + pub fn moveUp(self: *DataTable) void { + if (self.cursor_row > 0) self.cursor_row -= 1; + self.ensureCursorRowVisible(); + } + + pub fn moveDown(self: *DataTable) void { + if (self.cursor_row + 1 < self.rows.items.len) self.cursor_row += 1; + self.ensureCursorRowVisible(); + } + + pub fn pageUp(self: *DataTable) void { + const visible = self.dataRowsAvailable(); + self.cursor_row -|= visible; + self.ensureCursorRowVisible(); + } + + pub fn pageDown(self: *DataTable) void { + const visible = self.dataRowsAvailable(); + self.cursor_row = @min(self.cursor_row + visible, self.rows.items.len -| 1); + self.ensureCursorRowVisible(); + } + + pub fn gotoFirstRow(self: *DataTable) void { + self.cursor_row = 0; + self.y_offset = 0; + } + + pub fn gotoLastRow(self: *DataTable) void { + self.cursor_row = self.rows.items.len -| 1; + self.ensureCursorRowVisible(); + } + + pub fn gotoFirstColumn(self: *DataTable) void { + self.cursor_col = 0; + self.col_x_offset = 0; + } + + pub fn gotoLastColumn(self: *DataTable) void { + self.cursor_col = self.columns.items.len -| 1; + self.ensureCursorVisible(); + } + + pub fn handleKey(self: *DataTable, key: keys.KeyEvent) void { + switch (key.key) { + .left => self.moveLeft(), + .right => self.moveRight(), + .up => self.moveUp(), + .down => self.moveDown(), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoFirstColumn(), + .end => self.gotoLastColumn(), + .char => |c| switch (c) { + 'h' => self.moveLeft(), + 'l' => self.moveRight(), + 'k' => self.moveUp(), + 'j' => self.moveDown(), + 'g' => self.gotoFirstRow(), + 'G' => self.gotoLastRow(), + else => {}, + }, + else => {}, + } + } + + /// Number of data rows that fit in the viewport (excluding header). + fn dataRowsAvailable(self: *const DataTable) usize { + const header_lines: usize = if (self.show_header) 2 else 0; // header + separator + return @as(usize, self.height) -| header_lines; + } + + fn ensureCursorRowVisible(self: *DataTable) void { + const avail = self.dataRowsAvailable(); + if (avail == 0) return; + if (self.cursor_row < self.y_offset) { + self.y_offset = self.cursor_row; + } else if (self.cursor_row >= self.y_offset + avail) { + self.y_offset = self.cursor_row - avail + 1; + } + } + + fn ensureCursorVisible(self: *DataTable) void { + // Frozen cursors don't scroll. + if (self.cursor_col < self.frozen_columns) { + self.col_x_offset = 0; + return; + } + + // Compute non-frozen visible width. + const frozen_w = self.frozenWidth(); + const avail: usize = @as(usize, self.width) -| frozen_w; + + // Walk from col_x_offset to find which non-frozen columns fit. + const total_non_frozen = self.columns.items.len - self.frozen_columns; + const cursor_idx = self.cursor_col - self.frozen_columns; + + // First, scroll right if cursor is past visible. + var off = self.col_x_offset; + while (off < total_non_frozen) { + var used: usize = 0; + var i = off; + var found = false; + while (i < total_non_frozen) : (i += 1) { + const col_w = self.columns.items[self.frozen_columns + i].width; + if (used + col_w > avail) break; + used += col_w + 1; // 1 for column gap + if (i == cursor_idx) { + found = true; + break; + } + } + if (cursor_idx >= off and found) break; + if (cursor_idx < off) { + off = cursor_idx; + break; + } + off += 1; + } + self.col_x_offset = off; + } + + fn frozenWidth(self: *const DataTable) usize { + var sum: usize = 0; + for (self.columns.items[0..self.frozen_columns], 0..) |c, i| { + sum += c.width; + if (i + 1 < self.frozen_columns) sum += 1; + } + if (self.frozen_columns > 0 and self.frozen_columns < self.columns.items.len) { + sum += 2; // separator " │ " + } + return sum; + } + + pub fn view(self: *DataTable, allocator: std.mem.Allocator) ![]const u8 { + var out: Writer.Allocating = .init(allocator); + const w = &out.writer; + + const visible_cols = try self.computeVisibleColumns(allocator); + defer allocator.free(visible_cols); + + if (self.show_header) { + try self.renderRow(allocator, w, null, visible_cols, true); + try w.writeByte('\n'); + try self.renderHeaderSeparator(allocator, w, visible_cols); + try w.writeByte('\n'); + } + + const avail = self.dataRowsAvailable(); + const start = self.y_offset; + const end = @min(start + avail, self.rows.items.len); + var first = true; + for (start..end) |row_idx| { + if (!first) try w.writeByte('\n'); + first = false; + try self.renderRow(allocator, w, row_idx, visible_cols, false); + } + + return out.toOwnedSlice(); + } + + /// Indices of columns to render: all frozen + a slice of non-frozen + /// starting at col_x_offset that fits in the remaining width. + fn computeVisibleColumns(self: *const DataTable, allocator: std.mem.Allocator) ![]usize { + var list = std.array_list.Managed(usize).init(allocator); + errdefer list.deinit(); + + var i: usize = 0; + while (i < self.frozen_columns) : (i += 1) try list.append(i); + + const frozen_w = self.frozenWidth(); + const avail: usize = @as(usize, self.width) -| frozen_w; + var used: usize = 0; + i = self.frozen_columns + self.col_x_offset; + while (i < self.columns.items.len) : (i += 1) { + const c = self.columns.items[i]; + const need = c.width + (if (used > 0) @as(usize, 1) else 0); + if (used + need > avail) break; + used += need; + try list.append(i); + } + return list.toOwnedSlice(); + } + + fn renderRow(self: *const DataTable, allocator: std.mem.Allocator, writer: *Writer, row_idx: ?usize, visible_cols: []const usize, is_header: bool) !void { + for (visible_cols, 0..) |col_idx, i| { + // Frozen separator. + if (self.frozen_columns > 0 and i == self.frozen_columns) { + const sep = try self.frozen_separator_style.render(allocator, " │ "); + defer allocator.free(sep); + try writer.writeAll(sep); + } else if (i > 0) { + try writer.writeByte(' '); + } + + const col = self.columns.items[col_idx]; + const cell_text: []const u8 = if (is_header) + col.header + else + self.rows.items[row_idx.?][col_idx]; + + const formatted = try formatCell(allocator, cell_text, col.width, col.@"align"); + defer allocator.free(formatted); + + const is_cursor_cell = !is_header and row_idx.? == self.cursor_row and col_idx == self.cursor_col; + const is_cursor_row = !is_header and row_idx.? == self.cursor_row; + + const s = if (is_header) + self.header_style + else if (is_cursor_cell) + self.cursor_cell_style + else if (is_cursor_row) + self.cursor_row_style + else + self.cell_style; + + const styled = try s.render(allocator, formatted); + defer allocator.free(styled); + try writer.writeAll(styled); + } + } + + fn renderHeaderSeparator(self: *const DataTable, allocator: std.mem.Allocator, writer: *Writer, visible_cols: []const usize) !void { + for (visible_cols, 0..) |col_idx, i| { + if (self.frozen_columns > 0 and i == self.frozen_columns) { + const sep = try self.frozen_separator_style.render(allocator, "─┼─"); + defer allocator.free(sep); + try writer.writeAll(sep); + } else if (i > 0) { + try writer.writeAll("─"); + } + const col = self.columns.items[col_idx]; + const dashes = try allocator.alloc(u8, col.width * 3); // up to 3 bytes per UTF-8 dash + defer allocator.free(dashes); + const dash = "─"; + var written: usize = 0; + var k: usize = 0; + while (k < col.width) : (k += 1) { + @memcpy(dashes[written .. written + dash.len], dash); + written += dash.len; + } + const styled = try self.frozen_separator_style.render(allocator, dashes[0..written]); + defer allocator.free(styled); + try writer.writeAll(styled); + } + } +}; + +fn formatCell(allocator: std.mem.Allocator, text: []const u8, width: u16, align_: Align) ![]u8 { + const w = measure.width(text); + if (w == width) return allocator.dupe(u8, text); + if (w > width) { + const truncated = try measure.truncate(allocator, text, width); + // Always cast away const since we ultimately return `[]u8`. + return @constCast(truncated); + } + const padding = width - w; + return switch (align_) { + .left => @constCast(try measure.padRight(allocator, text, width)), + .right => @constCast(try measure.padLeft(allocator, text, width)), + .center => blk: { + const left = padding / 2; + const right = padding - left; + const out = try allocator.alloc(u8, left + text.len + right); + @memset(out[0..left], ' '); + @memcpy(out[left .. left + text.len], text); + @memset(out[left + text.len ..], ' '); + break :blk out; + }, + }; +} + +// `measure.padRight` and `padLeft` return `[]const u8`; cast for callers +// expecting `[]u8`. +fn padOwned(allocator: std.mem.Allocator, text: []const u8, w: usize, left: bool) ![]u8 { + const r = if (left) try measure.padLeft(allocator, text, w) else try measure.padRight(allocator, text, w); + return @constCast(r); +} + +// ── Tests ────────────────────────────────────────────────────────────── + +const testing = std.testing; + +test "moveRight clamps at last column" { + var t = DataTable.init(testing.allocator); + defer t.deinit(); + try t.setColumns(&.{ + .{ .header = "A", .width = 4 }, + .{ .header = "B", .width = 4 }, + }); + try t.addRow(&.{ "1", "2" }); + t.moveRight(); + try testing.expectEqual(@as(usize, 1), t.cursor_col); + t.moveRight(); + try testing.expectEqual(@as(usize, 1), t.cursor_col); +} + +test "moveDown advances cursor row" { + var t = DataTable.init(testing.allocator); + defer t.deinit(); + try t.setColumns(&.{.{ .header = "A", .width = 4 }}); + try t.addRow(&.{"1"}); + try t.addRow(&.{"2"}); + t.moveDown(); + try testing.expectEqual(@as(usize, 1), t.cursor_row); +} + +test "frozen columns stay at zero offset" { + var t = DataTable.init(testing.allocator); + defer t.deinit(); + try t.setColumns(&.{ + .{ .header = "id", .width = 4 }, + .{ .header = "name", .width = 6 }, + .{ .header = "x", .width = 4 }, + .{ .header = "y", .width = 4 }, + .{ .header = "z", .width = 4 }, + }); + try t.addRow(&.{ "1", "alice", "10", "20", "30" }); + t.setSize(20, 5); + t.setFrozenColumns(1); + t.cursor_col = 4; + t.moveLeft(); + t.moveLeft(); + t.moveLeft(); + t.moveLeft(); // back to col 0 (frozen) + try testing.expectEqual(@as(usize, 0), t.cursor_col); + try testing.expectEqual(@as(usize, 0), t.col_x_offset); +} + +test "view contains headers and data" { + const allocator = testing.allocator; + var t = DataTable.init(allocator); + defer t.deinit(); + try t.setColumns(&.{ + .{ .header = "id", .width = 4 }, + .{ .header = "name", .width = 6 }, + }); + try t.addRow(&.{ "42", "alice" }); + + const out = try t.view(allocator); + defer allocator.free(out); + try testing.expect(std.mem.indexOf(u8, out, "id") != null); + try testing.expect(std.mem.indexOf(u8, out, "alice") != null); + try testing.expect(std.mem.indexOf(u8, out, "42") != null); +} + +test "view renders frozen separator when columns are frozen" { + const allocator = testing.allocator; + var t = DataTable.init(allocator); + defer t.deinit(); + try t.setColumns(&.{ + .{ .header = "id", .width = 4 }, + .{ .header = "name", .width = 6 }, + .{ .header = "value", .width = 6 }, + }); + try t.addRow(&.{ "1", "alice", "10" }); + t.setFrozenColumns(1); + const out = try t.view(allocator); + defer allocator.free(out); + try testing.expect(std.mem.indexOf(u8, out, "│") != null); +} + +test "addRow rejects mismatched column count" { + var t = DataTable.init(testing.allocator); + defer t.deinit(); + try t.setColumns(&.{ + .{ .header = "A", .width = 4 }, + .{ .header = "B", .width = 4 }, + }); + try testing.expectError(error.ColumnCountMismatch, t.addRow(&.{"only one"})); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig new file mode 100644 index 0000000..2802284 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig @@ -0,0 +1,285 @@ +//! Diff viewer component. +//! Displays unified or side-by-side text diffs with syntax coloring. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const DiffView = struct { + old_text: []const u8 = "", + new_text: []const u8 = "", + old_label: []const u8 = "old", + new_label: []const u8 = "new", + mode: Mode = .unified, + show_line_numbers: bool = true, + context_lines: usize = 3, + /// Width of each side in side-by-side mode. + side_width: usize = 38, + /// Separator character for side-by-side mode. + separator: []const u8 = "\xe2\x94\x82", + /// Add prefix symbol. + add_prefix: []const u8 = "+", + /// Remove prefix symbol. + remove_prefix: []const u8 = "-", + /// Context prefix symbol. + context_prefix: []const u8 = " ", + + // Styles + add_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + remove_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + context_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + header_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + line_num_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + separator_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(6)); + s = s.inline_style(true); + break :blk s; + }, + + pub const Mode = enum { + unified, + side_by_side, + }; + + pub fn view(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { + return switch (self.mode) { + .unified => self.renderUnified(allocator), + .side_by_side => self.renderSideBySide(allocator), + }; + } + + fn renderUnified(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Header + const hdr = std.fmt.allocPrint(allocator, "--- {s}\n+++ {s}", .{ self.old_label, self.new_label }) catch ""; + writer.writeAll(self.header_style.render(allocator, hdr) catch hdr) catch {}; + writer.writeByte('\n') catch {}; + + // Compute diff using LCS-based approach + const old_lines = splitLines(allocator, self.old_text); + const new_lines = splitLines(allocator, self.new_text); + const ops = computeDiff(allocator, old_lines, new_lines); + + var old_num: usize = 1; + var new_num: usize = 1; + + for (ops) |op| { + switch (op) { + .equal => |line| { + if (self.show_line_numbers) { + const nums = std.fmt.allocPrint(allocator, "{d:>4} {d:>4} ", .{ old_num, new_num }) catch ""; + writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; + } + writer.writeAll(self.context_style.render(allocator, " ") catch " ") catch {}; + writer.writeAll(self.context_style.render(allocator, line) catch line) catch {}; + writer.writeByte('\n') catch {}; + old_num += 1; + new_num += 1; + }, + .delete => |line| { + if (self.show_line_numbers) { + const nums = std.fmt.allocPrint(allocator, "{d:>4} ", .{old_num}) catch ""; + writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; + } + const prefixed = std.fmt.allocPrint(allocator, "-{s}", .{line}) catch line; + writer.writeAll(self.remove_style.render(allocator, prefixed) catch prefixed) catch {}; + writer.writeByte('\n') catch {}; + old_num += 1; + }, + .insert => |line| { + if (self.show_line_numbers) { + const nums = std.fmt.allocPrint(allocator, " {d:>4} ", .{new_num}) catch ""; + writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; + } + const prefixed = std.fmt.allocPrint(allocator, "+{s}", .{line}) catch line; + writer.writeAll(self.add_style.render(allocator, prefixed) catch prefixed) catch {}; + writer.writeByte('\n') catch {}; + new_num += 1; + }, + } + } + + // Trim trailing newline + var array = result.toArrayList(); + if (array.items.len > 0 and array.items[array.items.len - 1] == '\n') { + _ = array.pop(); + } + + return array.items; + } + + fn renderSideBySide(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const old_lines = splitLines(allocator, self.old_text); + const new_lines = splitLines(allocator, self.new_text); + const ops = computeDiff(allocator, old_lines, new_lines); + + const half_width: usize = self.side_width; + + // Header + const old_hdr = padRight(allocator, self.old_label, half_width); + const new_hdr = self.new_label; + writer.writeAll(self.header_style.render(allocator, old_hdr) catch old_hdr) catch {}; + writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; + writer.writeAll(self.header_style.render(allocator, new_hdr) catch new_hdr) catch {}; + writer.writeByte('\n') catch {}; + + // Separator line + for (0..half_width) |_| writer.writeAll("\xe2\x94\x80") catch {}; + writer.writeAll("\xe2\x94\xbc") catch {}; + for (0..half_width + 2) |_| writer.writeAll("\xe2\x94\x80") catch {}; + writer.writeByte('\n') catch {}; + + for (ops) |op| { + switch (op) { + .equal => |line| { + const padded = padRight(allocator, line, half_width); + writer.writeAll(self.context_style.render(allocator, padded) catch padded) catch {}; + writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; + writer.writeAll(self.context_style.render(allocator, line) catch line) catch {}; + writer.writeByte('\n') catch {}; + }, + .delete => |line| { + const padded = padRight(allocator, line, half_width); + writer.writeAll(self.remove_style.render(allocator, padded) catch padded) catch {}; + writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; + writer.writeByte('\n') catch {}; + }, + .insert => |line| { + const blank = padRight(allocator, "", half_width); + writer.writeAll(blank) catch {}; + writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; + writer.writeAll(self.add_style.render(allocator, line) catch line) catch {}; + writer.writeByte('\n') catch {}; + }, + } + } + + var array = result.toArrayList(); + if (array.items.len > 0 and array.items[array.items.len - 1] == '\n') { + _ = array.pop(); + } + + return array.items; + } + + fn padRight(allocator: std.mem.Allocator, text: []const u8, target: usize) []const u8 { + if (text.len >= target) return text[0..target]; + var buf = std.array_list.Managed(u8).init(allocator); + buf.appendSlice(text) catch {}; + for (0..target - text.len) |_| buf.append(' ') catch {}; + return buf.items; + } + + fn splitLines(allocator: std.mem.Allocator, text: []const u8) []const []const u8 { + var lines = std.array_list.Managed([]const u8).init(allocator); + var iter = std.mem.splitScalar(u8, text, '\n'); + while (iter.next()) |line| { + lines.append(line) catch {}; + } + return lines.items; + } +}; + +/// Diff operation. +const DiffOp = union(enum) { + equal: []const u8, + delete: []const u8, + insert: []const u8, +}; + +/// Simple Myers-like diff: compute edit operations between old and new line arrays. +fn computeDiff(allocator: std.mem.Allocator, old: []const []const u8, new: []const []const u8) []const DiffOp { + var ops = std.array_list.Managed(DiffOp).init(allocator); + + // Simple O(n*m) LCS-based diff + const m = old.len; + const n = new.len; + + if (m == 0) { + for (new) |line| ops.append(.{ .insert = line }) catch {}; + return ops.items; + } + if (n == 0) { + for (old) |line| ops.append(.{ .delete = line }) catch {}; + return ops.items; + } + + // Build LCS table + const table = allocator.alloc(usize, (m + 1) * (n + 1)) catch { + // Fallback: show all as delete + insert + for (old) |line| ops.append(.{ .delete = line }) catch {}; + for (new) |line| ops.append(.{ .insert = line }) catch {}; + return ops.items; + }; + for (0..m + 1) |i| { + for (0..n + 1) |j| { + if (i == 0 or j == 0) { + table[i * (n + 1) + j] = 0; + } else if (std.mem.eql(u8, old[i - 1], new[j - 1])) { + table[i * (n + 1) + j] = table[(i - 1) * (n + 1) + (j - 1)] + 1; + } else { + table[i * (n + 1) + j] = @max(table[(i - 1) * (n + 1) + j], table[i * (n + 1) + (j - 1)]); + } + } + } + + // Backtrack to produce ops + var rev_ops = std.array_list.Managed(DiffOp).init(allocator); + var i: usize = m; + var j: usize = n; + while (i > 0 or j > 0) { + if (i > 0 and j > 0 and std.mem.eql(u8, old[i - 1], new[j - 1])) { + rev_ops.append(.{ .equal = old[i - 1] }) catch {}; + i -= 1; + j -= 1; + } else if (j > 0 and (i == 0 or table[i * (n + 1) + (j - 1)] >= table[(i - 1) * (n + 1) + j])) { + rev_ops.append(.{ .insert = new[j - 1] }) catch {}; + j -= 1; + } else if (i > 0) { + rev_ops.append(.{ .delete = old[i - 1] }) catch {}; + i -= 1; + } + } + + // Reverse + var idx: usize = rev_ops.items.len; + while (idx > 0) { + idx -= 1; + ops.append(rev_ops.items[idx]) catch {}; + } + + return ops.items; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig new file mode 100644 index 0000000..be6099f --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig @@ -0,0 +1,719 @@ +//! Dropdown/Select component. +//! Collapsible list for selecting one or more options. + +const std = @import("std"); +const keys = @import("../input/keys.zig"); +const Writer = std.Io.Writer; +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 { + allocator: std.mem.Allocator, + + // Items + items: std.array_list.Managed(Item), + filtered_indices: std.array_list.Managed(usize), + + // State + expanded: bool, + cursor: usize, + selected_index: ?usize, + selected_indices: std.AutoHashMap(usize, void), + + // Filtering + filter_text: std.array_list.Managed(u8), + filter_active: bool, + + // Scrolling + y_offset: usize, + max_visible: u16, + + // Focus + focused: bool, + + // Behavior + multi_select: bool, + close_on_select: bool, + wrap_around: bool, + + // Labels + label: []const u8, + placeholder: []const u8, + + // Symbols + expand_symbol: []const u8, + cursor_symbol: []const u8, + checked_symbol: []const u8, + unchecked_symbol: []const u8, + scroll_up_symbol: []const u8, + scroll_down_symbol: []const u8, + + // Styling + label_style: style_mod.Style, + trigger_style: style_mod.Style, + trigger_focused_style: style_mod.Style, + item_style: style_mod.Style, + cursor_item_style: style_mod.Style, + selected_item_style: style_mod.Style, + disabled_style: style_mod.Style, + filter_style: style_mod.Style, + border_chars: border_mod.BorderChars, + border_fg: Color, + + const Self = @This(); + + pub const Item = struct { + value: T, + label: []const u8, + description: []const u8, + enabled: bool, + + pub fn init(value: T, label_text: []const u8) Item { + return .{ + .value = value, + .label = label_text, + .description = "", + .enabled = true, + }; + } + + pub fn withDescription(value: T, label_text: []const u8, desc: []const u8) Item { + return .{ + .value = value, + .label = label_text, + .description = desc, + .enabled = true, + }; + } + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .items = std.array_list.Managed(Item).init(allocator), + .filtered_indices = std.array_list.Managed(usize).init(allocator), + .expanded = false, + .cursor = 0, + .selected_index = null, + .selected_indices = std.AutoHashMap(usize, void).init(allocator), + .filter_text = std.array_list.Managed(u8).init(allocator), + .filter_active = false, + .y_offset = 0, + .max_visible = 6, + .focused = true, + .multi_select = false, + .close_on_select = true, + .wrap_around = false, + .label = "", + .placeholder = "Select...", + .expand_symbol = "▼", + .cursor_symbol = "> ", + .checked_symbol = "[x] ", + .unchecked_symbol = "[ ] ", + .scroll_up_symbol = "▲", + .scroll_down_symbol = "▼", + .label_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .trigger_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + .trigger_focused_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .item_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .cursor_item_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .selected_item_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + .disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + .filter_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .border_chars = .rounded, + .border_fg = .gray(14), + }; + } + + pub fn deinit(self: *Self) void { + self.items.deinit(); + self.filtered_indices.deinit(); + self.selected_indices.deinit(); + self.filter_text.deinit(); + } + + // ── Item management ───────────────────────────── + + pub fn addItem(self: *Self, item: Item) !void { + try self.items.append(item); + try self.rebuildFilter(); + } + + pub fn addItems(self: *Self, new_items: []const Item) !void { + try self.items.appendSlice(new_items); + try self.rebuildFilter(); + } + + pub fn setItems(self: *Self, new_items: []const Item) !void { + self.items.clearRetainingCapacity(); + try self.items.appendSlice(new_items); + self.cursor = 0; + self.y_offset = 0; + self.selected_index = null; + self.selected_indices.clearRetainingCapacity(); + try self.rebuildFilter(); + } + + // ── State ─────────────────────────────────────── + + pub fn open(self: *Self) void { + self.expanded = true; + self.filter_active = false; + self.filter_text.clearRetainingCapacity(); + self.rebuildFilter() catch {}; + // Position cursor at selected item if any + if (self.selected_index) |sel| { + for (self.filtered_indices.items, 0..) |idx, i| { + if (idx == sel) { + self.cursor = i; + self.ensureVisible(); + break; + } + } + } + } + + pub fn close(self: *Self) void { + self.expanded = false; + self.filter_active = false; + self.filter_text.clearRetainingCapacity(); + } + + pub fn toggle(self: *Self) void { + if (self.expanded) self.close() else self.open(); + } + + pub fn isExpanded(self: *const Self) bool { + return self.expanded; + } + + // ── Selection ─────────────────────────────────── + + pub fn selectedItem(self: *const Self) ?*const Item { + if (self.selected_index) |idx| { + if (idx < self.items.items.len) { + return &self.items.items[idx]; + } + } + return null; + } + + pub fn selectedValue(self: *const Self) ?T { + if (self.selectedItem()) |item| { + return item.value; + } + return null; + } + + pub fn selectedItems(self: *const Self, allocator: std.mem.Allocator) ![]const *const Item { + var result = std.array_list.Managed(*const Item).init(allocator); + var iter = self.selected_indices.keyIterator(); + while (iter.next()) |idx| { + if (idx.* < self.items.items.len) { + try result.append(&self.items.items[idx.*]); + } + } + return result.toOwnedSlice(); + } + + fn selectAtCursor(self: *Self) void { + const visible = self.filtered_indices.items; + if (self.cursor >= visible.len) return; + const idx = visible[self.cursor]; + if (!self.items.items[idx].enabled) return; + + if (self.multi_select) { + if (self.selected_indices.contains(idx)) { + _ = self.selected_indices.remove(idx); + } else { + self.selected_indices.put(idx, {}) catch {}; + } + } else { + self.selected_index = idx; + if (self.close_on_select) { + self.close(); + } + } + } + + // ── Focus protocol ────────────────────────────── + + pub fn focus(self: *Self) void { + self.focused = true; + } + + pub fn blur(self: *Self) void { + self.focused = false; + } + + // ── Input handling ────────────────────────────── + + pub fn handleKey(self: *Self, key: keys.KeyEvent) void { + if (!self.focused) return; + + // When filter is active, capture typed characters + if (self.expanded and self.filter_active and key.key == .char and !key.modifiers.ctrl) { + const c = key.key.char; + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch return; + self.filter_text.appendSlice(buf[0..len]) catch {}; + self.rebuildFilter() catch {}; + return; + } + + if (self.expanded and self.filter_active and key.key == .backspace) { + if (self.filter_text.items.len > 0) { + _ = self.filter_text.pop(); + self.rebuildFilter() catch {}; + } + return; + } + + if (!self.expanded) { + // Collapsed state + switch (key.key) { + .enter, .space => self.open(), + .down => self.open(), + else => {}, + } + return; + } + + // Expanded state + switch (key.key) { + .up => self.cursorUp(), + .down => self.cursorDown(), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoFirst(), + .end => self.gotoLast(), + .enter => self.selectAtCursor(), + .space => if (self.multi_select) self.selectAtCursor(), + .escape => { + if (self.filter_active) { + self.filter_active = false; + self.filter_text.clearRetainingCapacity(); + self.rebuildFilter() catch {}; + } else { + self.close(); + } + }, + .char => |c| switch (c) { + 'j' => self.cursorDown(), + 'k' => self.cursorUp(), + 'g' => self.gotoFirst(), + 'G' => self.gotoLast(), + '/' => { + self.filter_active = true; + self.filter_text.clearRetainingCapacity(); + }, + 'q' => self.close(), + else => {}, + }, + else => {}, + } + } + + // ── Navigation ────────────────────────────────── + + fn cursorUp(self: *Self) void { + const visible = self.filtered_indices.items; + if (visible.len == 0) return; + if (self.cursor > 0) { + self.cursor -= 1; + } else if (self.wrap_around) { + self.cursor = visible.len - 1; + } + self.skipDisabledUp(); + self.ensureVisible(); + } + + fn cursorDown(self: *Self) void { + const visible = self.filtered_indices.items; + if (visible.len == 0) return; + if (self.cursor < visible.len - 1) { + self.cursor += 1; + } else if (self.wrap_around) { + self.cursor = 0; + } + self.skipDisabledDown(); + self.ensureVisible(); + } + + fn pageUp(self: *Self) void { + if (self.cursor >= self.max_visible) { + self.cursor -= self.max_visible; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + fn pageDown(self: *Self) void { + const visible = self.filtered_indices.items; + if (self.cursor + self.max_visible < visible.len) { + self.cursor += self.max_visible; + } else if (visible.len > 0) { + self.cursor = visible.len - 1; + } + self.ensureVisible(); + } + + fn gotoFirst(self: *Self) void { + self.cursor = 0; + self.y_offset = 0; + } + + fn gotoLast(self: *Self) void { + const visible = self.filtered_indices.items; + if (visible.len > 0) { + self.cursor = visible.len - 1; + self.ensureVisible(); + } + } + + fn skipDisabledDown(self: *Self) void { + const visible = self.filtered_indices.items; + const start = self.cursor; + while (self.cursor < visible.len) { + if (self.items.items[visible[self.cursor]].enabled) return; + self.cursor += 1; + } + self.cursor = start; // no enabled item found, revert + } + + fn skipDisabledUp(self: *Self) void { + const visible = self.filtered_indices.items; + if (visible.len == 0) return; + const start = self.cursor; + while (true) { + if (self.items.items[visible[self.cursor]].enabled) return; + if (self.cursor == 0) break; + self.cursor -= 1; + } + self.cursor = start; // revert + } + + fn ensureVisible(self: *Self) void { + if (self.cursor < self.y_offset) { + self.y_offset = self.cursor; + } else if (self.cursor >= self.y_offset + self.max_visible) { + self.y_offset = self.cursor - self.max_visible + 1; + } + } + + // ── Filtering ────────────────────────────────── + + fn rebuildFilter(self: *Self) !void { + self.filtered_indices.clearRetainingCapacity(); + + if (self.filter_text.items.len == 0) { + for (0..self.items.items.len) |i| { + try self.filtered_indices.append(i); + } + } else { + var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); + defer scored.deinit(); + + for (self.items.items, 0..) |item, i| { + const s = fuzzy.scoreIgnoreCase(item.label, self.filter_text.items); + if (s > 0) try scored.append(.{ .index = i, .score = s }); + } + + 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); + + for (scored.items) |s| { + try self.filtered_indices.append(s.index); + } + } + + 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(); + } + + // ── Rendering ─────────────────────────────────── + + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Label + if (self.label.len > 0) { + const styled_label = try self.label_style.render(allocator, self.label); + try writer.writeAll(styled_label); + try writer.writeAll(" "); + } + + // Trigger line + const display_text = if (self.selectedItem()) |item| + item.label + else if (self.multi_select and self.selectedCount() > 0) + try std.fmt.allocPrint(allocator, "{d} selected", .{self.selectedCount()}) + else + self.placeholder; + + const trig_style = if (self.focused) self.trigger_focused_style else self.trigger_style; + const styled_trigger = try trig_style.render(allocator, display_text); + try writer.writeAll(styled_trigger); + try writer.writeAll(" "); + + const expand_str = if (self.expanded) "▲" else self.expand_symbol; + try writer.writeAll(expand_str); + + if (!self.expanded) { + return result.toOwnedSlice(); + } + + // Expanded dropdown + try writer.writeByte('\n'); + + // Compute dropdown width + var max_item_width: usize = 0; + for (self.items.items) |item| { + const w = measure.width(item.label) + self.cursor_symbol.len; + const extra: usize = if (self.multi_select) self.checked_symbol.len else 0; + if (w + extra > max_item_width) max_item_width = w + extra; + } + max_item_width = @max(max_item_width, 10); + const inner_width = max_item_width + 2; // padding + + // Top border + try self.writeBorderLine(writer, allocator, inner_width, .top); + try writer.writeByte('\n'); + + // Filter line + if (self.filter_active) { + try self.writeBorderSide(writer, allocator, .left); + const filter_line = try std.fmt.allocPrint(allocator, " / {s}_", .{self.filter_text.items}); + const styled = try self.filter_style.render(allocator, filter_line); + try writer.writeAll(styled); + const used = measure.width(filter_line); + if (used < inner_width) { + try self.writePadding(writer, inner_width - used); + } + try self.writeBorderSide(writer, allocator, .right); + try writer.writeByte('\n'); + + // Separator + try self.writeBorderLine(writer, allocator, inner_width, .middle); + try writer.writeByte('\n'); + } + + // Scroll indicator (top) + const visible = self.filtered_indices.items; + const has_above = self.y_offset > 0; + const end_idx = @min(self.y_offset + self.max_visible, visible.len); + const has_below = end_idx < visible.len; + + if (has_above) { + try self.writeBorderSide(writer, allocator, .left); + const up_str = try std.fmt.allocPrint(allocator, " {s}", .{self.scroll_up_symbol}); + try writer.writeAll(up_str); + const used = measure.width(up_str); + if (used < inner_width) { + try self.writePadding(writer, inner_width - used); + } + try self.writeBorderSide(writer, allocator, .right); + try writer.writeByte('\n'); + } + + // Items + var rendered: usize = 0; + while (rendered < self.max_visible) : (rendered += 1) { + const idx = self.y_offset + rendered; + if (idx >= visible.len) break; + + if (rendered > 0 or has_above) { + // already have newline from previous + } + + try self.writeBorderSide(writer, allocator, .left); + + const item_idx = visible[idx]; + const item = self.items.items[item_idx]; + var line: Writer.Allocating = .init(allocator); + const line_writer = &line.writer; + + try line_writer.writeByte(' '); + + // Cursor symbol + if (idx == self.cursor) { + try line_writer.writeAll(self.cursor_symbol); + } else { + for (0..self.cursor_symbol.len) |_| { + try line_writer.writeByte(' '); + } + } + + // Multi-select check + if (self.multi_select) { + if (self.selected_indices.contains(item_idx)) { + try line_writer.writeAll(self.checked_symbol); + } else { + try line_writer.writeAll(self.unchecked_symbol); + } + } + + // Label + try line_writer.writeAll(item.label); + + const line_text = try line.toOwnedSlice(); + const item_s = if (!item.enabled) + self.disabled_style + else if (idx == self.cursor) + self.cursor_item_style + else if (self.isItemSelected(item_idx)) + self.selected_item_style + else + self.item_style; + + const styled_line = try item_s.render(allocator, line_text); + try writer.writeAll(styled_line); + + // Pad to width + const used = measure.width(line_text); + if (used < inner_width) { + try self.writePadding(writer, inner_width - used); + } + + try self.writeBorderSide(writer, allocator, .right); + if (rendered + 1 < self.max_visible and idx + 1 < visible.len) { + try writer.writeByte('\n'); + } + } + + // Scroll indicator (bottom) + if (has_below) { + try writer.writeByte('\n'); + try self.writeBorderSide(writer, allocator, .left); + const down_str = try std.fmt.allocPrint(allocator, " {s}", .{self.scroll_down_symbol}); + try writer.writeAll(down_str); + const used = measure.width(down_str); + if (used < inner_width) { + try self.writePadding(writer, inner_width - used); + } + try self.writeBorderSide(writer, allocator, .right); + } + + // Bottom border + try writer.writeByte('\n'); + try self.writeBorderLine(writer, allocator, inner_width, .bottom); + + return result.toOwnedSlice(); + } + + fn isItemSelected(self: *const Self, idx: usize) bool { + if (self.multi_select) { + return self.selected_indices.contains(idx); + } + return self.selected_index != null and self.selected_index.? == idx; + } + + fn selectedCount(self: *const Self) usize { + return self.selected_indices.count(); + } + + const BorderPos = enum { top, middle, bottom }; + const BorderSide = enum { left, right }; + + fn writeBorderLine(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { + const bc = self.border_chars; + var border_style = style_mod.Style{}; + border_style = border_style.fg(self.border_fg); + border_style = border_style.inline_style(true); + + const corner_l = switch (pos) { + .top => bc.top_left, + .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, + .bottom => bc.bottom_left, + }; + const corner_r = switch (pos) { + .top => bc.top_right, + .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, + .bottom => bc.bottom_right, + }; + + const styled_l = try border_style.render(allocator, corner_l); + try writer.writeAll(styled_l); + + for (0..width) |_| { + const styled = try border_style.render(allocator, bc.horizontal); + try writer.writeAll(styled); + } + + const styled_r = try border_style.render(allocator, corner_r); + try writer.writeAll(styled_r); + } + + fn writeBorderSide(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { + var border_style = style_mod.Style{}; + border_style = border_style.fg(self.border_fg); + border_style = border_style.inline_style(true); + + const char = switch (side) { + .left => self.border_chars.vertical, + .right => self.border_chars.vertical, + }; + const styled = try border_style.render(allocator, char); + try writer.writeAll(styled); + } + + fn writePadding(_: *const Self, writer: *Writer, count: usize) !void { + for (0..count) |_| { + try writer.writeByte(' '); + } + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig new file mode 100644 index 0000000..56720ad --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig @@ -0,0 +1,419 @@ +//! File picker component for file system navigation. +//! Allows browsing directories and selecting files. + +const std = @import("std"); +const Writer = std.Io.Writer; +const builtin = @import("builtin"); +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); +const Dir = std.Io.Dir; + +pub const FilePicker = struct { + allocator: std.mem.Allocator, + + // State + current_path: std.array_list.Managed(u8), + entries: std.array_list.Managed(Entry), + cursor: usize, + y_offset: usize, + + // Selection + selected_path: ?[]const u8, + + // Options + height: u16, + show_hidden: bool, + show_size: bool, + show_permissions: bool, + dir_only: bool, + file_only: bool, + allowed_extensions: ?[]const []const u8, + + // Styling + dir_style: style_mod.Style, + file_style: style_mod.Style, + cursor_style: style_mod.Style, + size_style: style_mod.Style, + path_style: style_mod.Style, + + // Focus + focused: bool, + + // Symbols + dir_icon: []const u8, + file_icon: []const u8, + link_icon: []const u8, + parent_icon: []const u8, + + pub const Entry = struct { + name: []const u8, + entry_type: EntryType, + size: u64, + is_hidden: bool, + + pub const EntryType = enum { + file, + directory, + symlink, + parent, + }; + }; + + pub fn init(allocator: std.mem.Allocator) FilePicker { + return .{ + .allocator = allocator, + .current_path = std.array_list.Managed(u8).init(allocator), + .entries = std.array_list.Managed(Entry).init(allocator), + .cursor = 0, + .y_offset = 0, + .selected_path = null, + .height = 15, + .show_hidden = false, + .show_size = true, + .show_permissions = false, + .dir_only = false, + .file_only = false, + .allowed_extensions = null, + .dir_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.blue); + s = s.inline_style(true); + break :blk s; + }, + .file_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .size_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .path_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .focused = true, + .dir_icon = "📁 ", + .file_icon = "📄 ", + .link_icon = "🔗 ", + .parent_icon = "📂 ", + }; + } + + pub fn deinit(self: *FilePicker) void { + self.current_path.deinit(); + for (self.entries.items) |entry| { + self.allocator.free(entry.name); + } + self.entries.deinit(); + if (self.selected_path) |path| { + self.allocator.free(path); + } + } + + /// Navigate to a directory + pub fn navigate(self: *FilePicker, io: std.Io, path: []const u8) !void { + // Update current path + self.current_path.clearRetainingCapacity(); + try self.current_path.appendSlice(path); + + // Clear old entries + for (self.entries.items) |entry| { + self.allocator.free(entry.name); + } + self.entries.clearRetainingCapacity(); + + // Add parent directory entry + if (!std.mem.eql(u8, path, "/")) { + const parent_name = try self.allocator.dupe(u8, ".."); + try self.entries.append(.{ + .name = parent_name, + .entry_type = .parent, + .size = 0, + .is_hidden = false, + }); + } + + // Read directory + var dir = Dir.openDirAbsolute(io, path, .{ .iterate = true }) catch { + return; + }; + defer dir.close(io); + + var iter = dir.iterate(); + while (iter.next(io) catch null) |entry| { + // Skip hidden files if not showing them + const is_hidden = entry.name.len > 0 and entry.name[0] == '.'; + if (is_hidden and !self.show_hidden) continue; + + // Skip files if dir_only + if (self.dir_only and entry.kind != .directory) continue; + + // Skip directories if file_only + if (self.file_only and entry.kind == .directory) continue; + + // Check extensions if specified + if (self.allowed_extensions) |exts| { + if (entry.kind != .directory) { + const ext = std.fs.path.extension(entry.name); + var found = false; + for (exts) |allowed_ext| { + if (std.mem.eql(u8, ext, allowed_ext)) { + found = true; + break; + } + } + if (!found) continue; + } + } + + // Get file size + var size: u64 = 0; + if (entry.kind == .file) { + const stat = dir.statFile(io, entry.name, .{}) catch null; + if (stat) |s| { + size = s.size; + } + } + + const name_copy = try self.allocator.dupe(u8, entry.name); + try self.entries.append(.{ + .name = name_copy, + .entry_type = switch (entry.kind) { + .directory => .directory, + .sym_link => .symlink, + else => .file, + }, + .size = size, + .is_hidden = is_hidden, + }); + } + + // Sort entries (directories first, then alphabetically) + std.mem.sort(Entry, self.entries.items, {}, struct { + fn lessThan(_: void, a: Entry, b: Entry) bool { + // Parent always first + if (a.entry_type == .parent) return true; + if (b.entry_type == .parent) return false; + + // Directories before files + if (a.entry_type == .directory and b.entry_type != .directory) return true; + if (b.entry_type == .directory and a.entry_type != .directory) return false; + + // Alphabetical + return std.mem.lessThan(u8, a.name, b.name); + } + }.lessThan); + + self.cursor = 0; + self.y_offset = 0; + } + + /// Navigate to home directory using the supplied environment. + pub fn navigateHome(self: *FilePicker, io: std.Io, environ_map: *const std.process.Environ.Map) !void { + if (comptime builtin.os.tag == .windows) { + const home = environ_map.get("USERPROFILE") orelse "C:\\"; + try self.navigate(io, home); + } else { + const home = environ_map.get("HOME") orelse "/"; + try self.navigate(io, home); + } + } + + /// Move cursor up + pub fn cursorUp(self: *FilePicker) void { + if (self.cursor > 0) { + self.cursor -= 1; + self.ensureVisible(); + } + } + + /// Move cursor down + pub fn cursorDown(self: *FilePicker) void { + if (self.cursor < self.entries.items.len -| 1) { + self.cursor += 1; + self.ensureVisible(); + } + } + + /// Select current entry + pub fn selectCurrent(self: *FilePicker, io: std.Io) !bool { + if (self.cursor >= self.entries.items.len) return false; + + const entry = self.entries.items[self.cursor]; + + if (entry.entry_type == .directory or entry.entry_type == .parent) { + // Navigate into directory + if (entry.entry_type == .parent) { + const parent = std.fs.path.dirname(self.current_path.items) orelse "/"; + const parent_copy = try self.allocator.dupe(u8, parent); + defer self.allocator.free(parent_copy); + try self.navigate(io, parent_copy); + } else { + const new_path = try std.fs.path.join(self.allocator, &.{ self.current_path.items, entry.name }); + defer self.allocator.free(new_path); + try self.navigate(io, new_path); + } + return false; + } else { + // Select file + if (self.selected_path) |path| { + self.allocator.free(path); + } + self.selected_path = try std.fs.path.join(self.allocator, &.{ self.current_path.items, entry.name }); + return true; + } + } + + /// Set focused state (for use with FocusGroup). + pub fn focus(self: *FilePicker) void { + self.focused = true; + } + + /// Clear focused state (for use with FocusGroup). + pub fn blur(self: *FilePicker) void { + self.focused = false; + } + + /// Handle key event + pub fn handleKey( + self: *FilePicker, + io: std.Io, + environ_map: *const std.process.Environ.Map, + key: keys.KeyEvent, + ) !bool { + if (!self.focused) return false; + switch (key.key) { + .up => self.cursorUp(), + .down => self.cursorDown(), + .enter => return try self.selectCurrent(io), + .backspace => { + const parent = std.fs.path.dirname(self.current_path.items) orelse "/"; + const parent_copy = try self.allocator.dupe(u8, parent); + defer self.allocator.free(parent_copy); + try self.navigate(io, parent_copy); + }, + .char => |c| { + switch (c) { + 'j' => self.cursorDown(), + 'k' => self.cursorUp(), + 'h' => self.showHidden(io), + '~' => try self.navigateHome(io, environ_map), + else => {}, + } + }, + else => {}, + } + return false; + } + + fn showHidden(self: *FilePicker, io: std.Io) void { + self.show_hidden = !self.show_hidden; + const path_copy = self.allocator.dupe(u8, self.current_path.items) catch return; + defer self.allocator.free(path_copy); + self.navigate(io, path_copy) catch {}; + } + + fn ensureVisible(self: *FilePicker) void { + if (self.cursor < self.y_offset) { + self.y_offset = self.cursor; + } else if (self.cursor >= self.y_offset + self.height) { + self.y_offset = self.cursor - self.height + 1; + } + } + + /// Get selected path + pub fn getSelected(self: *const FilePicker) ?[]const u8 { + return self.selected_path; + } + + /// Format file size for display + fn formatSize(self: *const FilePicker, allocator: std.mem.Allocator, size: u64) ![]const u8 { + _ = self; + if (size < 1024) { + return try std.fmt.allocPrint(allocator, "{d}B", .{size}); + } else if (size < 1024 * 1024) { + return try std.fmt.allocPrint(allocator, "{d:.1}K", .{@as(f64, @floatFromInt(size)) / 1024.0}); + } else if (size < 1024 * 1024 * 1024) { + return try std.fmt.allocPrint(allocator, "{d:.1}M", .{@as(f64, @floatFromInt(size)) / (1024.0 * 1024.0)}); + } else { + return try std.fmt.allocPrint(allocator, "{d:.1}G", .{@as(f64, @floatFromInt(size)) / (1024.0 * 1024.0 * 1024.0)}); + } + } + + /// Render the file picker + pub fn view(self: *const FilePicker, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Current path header + const path_styled = try self.path_style.render(allocator, self.current_path.items); + try writer.writeAll(path_styled); + try writer.writeByte('\n'); + try writer.writeByte('\n'); + + // Entries + var rendered: usize = 0; + while (rendered < self.height -| 2) : (rendered += 1) { + if (rendered > 0) try writer.writeByte('\n'); + + const idx = self.y_offset + rendered; + if (idx >= self.entries.items.len) continue; + + const entry = self.entries.items[idx]; + const is_selected = idx == self.cursor; + + // Cursor indicator + if (is_selected) { + try writer.writeAll("> "); + } else { + try writer.writeAll(" "); + } + + // Icon + const icon = switch (entry.entry_type) { + .directory => self.dir_icon, + .parent => self.parent_icon, + .symlink => self.link_icon, + .file => self.file_icon, + }; + try writer.writeAll(icon); + + // Name + const name_style = if (is_selected) + self.cursor_style + else switch (entry.entry_type) { + .directory, .parent => self.dir_style, + else => self.file_style, + }; + const name_styled = try name_style.render(allocator, entry.name); + try writer.writeAll(name_styled); + + // Size (for files) + if (self.show_size and entry.entry_type == .file) { + const size_str = try self.formatSize(allocator, entry.size); + try writer.writeAll(" "); + const size_styled = try self.size_style.render(allocator, size_str); + try writer.writeAll(size_styled); + } + } + + return result.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig new file mode 100644 index 0000000..9e66964 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig @@ -0,0 +1,553 @@ +//! Focus management for ZigZag TUI applications. +//! Provides Tab/Shift+Tab cycling between focusable components and +//! focus-aware style helpers for rendering focus indicators. +//! +//! A component is "focusable" if it has: +//! - a `focused: bool` field +//! - a `pub fn focus(*Self) void` method +//! - a `pub fn blur(*Self) void` method +//! +//! TextInput, TextArea, Table, List, Confirm, and FilePicker all satisfy +//! this protocol out of the box. + +const std = @import("std"); +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const border_mod = @import("../style/border.zig"); +const Color = @import("../style/color.zig").Color; + +/// Comptime check: returns true if `T` satisfies the focusable protocol. +pub fn isFocusable(comptime T: type) bool { + return @hasField(T, "focused") and + @hasDecl(T, "focus") and + @hasDecl(T, "blur"); +} + +/// Maximum number of key bindings per action (next / prev). +const max_binds = 4; + +/// A key binding slot: a key plus optional modifiers. +pub const KeyBind = struct { + key: keys.Key, + modifiers: keys.Modifiers = .{}, + + /// Check if a KeyEvent matches this binding. + pub fn matches(self: KeyBind, event: keys.KeyEvent) bool { + return self.key.eql(event.key) and self.modifiers.eql(event.modifiers); + } +}; + +/// Default "next" bindings: Tab (no modifiers), Down arrow, 'j'. +pub const default_next_keys = [max_binds]?KeyBind{ + .{ .key = .tab }, + null, + null, + null, +}; + +/// Default "prev" bindings: Shift+Tab, Up arrow, 'k'. +pub const default_prev_keys = [max_binds]?KeyBind{ + .{ .key = .tab, .modifiers = .{ .shift = true } }, + null, + null, + null, +}; + +/// A group of focusable components with customizable key-driven cycling. +/// +/// `max_items` is the maximum number of components that can be registered. +/// The group uses a fixed-size array so it requires no allocation and can +/// be embedded directly in a Model struct. +/// +/// By default, Tab moves forward and Shift+Tab moves backward. +/// Override `next_keys` / `prev_keys` or call `addNextKey()` / `addPrevKey()` +/// to use any keys you want (arrows, vim j/k, etc.). +/// +/// Usage: +/// ``` +/// var fg: FocusGroup(3) = .{}; +/// fg.add(&self.input_a); +/// fg.add(&self.input_b); +/// fg.add(&self.table); +/// fg.initFocus(); // focus first, blur the rest +/// +/// // Optional: add extra navigation keys +/// fg.addNextKey(.{ .key = .down }); // Down arrow +/// fg.addNextKey(.{ .key = .{ .char = 'j' } }); // vim j +/// fg.addPrevKey(.{ .key = .up }); // Up arrow +/// fg.addPrevKey(.{ .key = .{ .char = 'k' } }); // vim k +/// ``` +pub fn FocusGroup(comptime max_items: usize) type { + return struct { + const Self = @This(); + + /// Type-erased handle to a focusable component. + pub const FocusItem = struct { + focus_fn: *const fn (*anyopaque) void, + blur_fn: *const fn (*anyopaque) void, + is_focused_fn: *const fn (*const anyopaque) bool, + ptr: *anyopaque, + }; + + items: [max_items]?FocusItem = [_]?FocusItem{null} ** max_items, + count: usize = 0, + active: usize = 0, + /// Whether cycling wraps from last to first (and vice versa). + wrap: bool = true, + /// Key bindings that trigger focusNext(). Up to 4 bindings. + next_keys: [max_binds]?KeyBind = default_next_keys, + /// Key bindings that trigger focusPrev(). Up to 4 bindings. + prev_keys: [max_binds]?KeyBind = default_prev_keys, + + /// Register a focusable component. + /// + /// The component must satisfy the focusable protocol + /// (`focused: bool`, `focus()`, `blur()`). A compile error is + /// emitted if the protocol is not satisfied. + /// + /// The pointer must remain valid for the lifetime of the FocusGroup + /// (which is naturally the case for fields in the same Model struct). + pub fn add(self: *Self, item_ptr: anytype) void { + const Ptr = @TypeOf(item_ptr); + const T = @typeInfo(Ptr).pointer.child; + + comptime { + if (!@hasField(T, "focused")) + @compileError("FocusGroup item must have a 'focused: bool' field. " ++ + "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); + if (!@hasDecl(T, "focus")) + @compileError("FocusGroup item must have a 'pub fn focus(*Self) void' method. " ++ + "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); + if (!@hasDecl(T, "blur")) + @compileError("FocusGroup item must have a 'pub fn blur(*Self) void' method. " ++ + "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); + } + + if (self.count >= max_items) return; + + self.items[self.count] = .{ + .focus_fn = @ptrCast(&struct { + fn call(raw_ptr: *anyopaque) void { + const ptr: *T = @ptrCast(@alignCast(raw_ptr)); + ptr.focus(); + } + }.call), + .blur_fn = @ptrCast(&struct { + fn call(raw_ptr: *anyopaque) void { + const ptr: *T = @ptrCast(@alignCast(raw_ptr)); + ptr.blur(); + } + }.call), + .is_focused_fn = @ptrCast(&struct { + fn call(raw_ptr: *const anyopaque) bool { + const ptr: *const T = @ptrCast(@alignCast(raw_ptr)); + return ptr.focused; + } + }.call), + .ptr = @ptrCast(item_ptr), + }; + self.count += 1; + } + + /// Focus the item at `index`, blurring all others. + /// Does nothing if `index` is out of range. + pub fn focusAt(self: *Self, index: usize) void { + if (index >= self.count) return; + for (0..self.count) |i| { + if (self.items[i]) |item| { + if (i == index) { + item.focus_fn(item.ptr); + } else { + item.blur_fn(item.ptr); + } + } + } + self.active = index; + } + + /// Move focus to the next item (Tab behavior). + pub fn focusNext(self: *Self) void { + if (self.count == 0) return; + if (self.active + 1 < self.count) { + self.focusAt(self.active + 1); + } else if (self.wrap) { + self.focusAt(0); + } + } + + /// Move focus to the previous item (Shift+Tab behavior). + pub fn focusPrev(self: *Self) void { + if (self.count == 0) return; + if (self.active > 0) { + self.focusAt(self.active - 1); + } else if (self.wrap) { + self.focusAt(self.count - 1); + } + } + + /// Handle a key event for focus cycling. + /// + /// Checks the event against `next_keys` and `prev_keys`. + /// Returns `true` if the key was consumed (matched a binding), + /// `false` if it should be forwarded to the active component. + pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { + for (self.next_keys) |maybe_bind| { + if (maybe_bind) |bind| { + if (bind.matches(key)) { + self.focusNext(); + return true; + } + } + } + for (self.prev_keys) |maybe_bind| { + if (maybe_bind) |bind| { + if (bind.matches(key)) { + self.focusPrev(); + return true; + } + } + } + return false; + } + + /// Add an extra key binding for "focus next". + /// Returns false if all 4 slots are full. + pub fn addNextKey(self: *Self, bind: KeyBind) bool { + for (&self.next_keys) |*slot| { + if (slot.* == null) { + slot.* = bind; + return true; + } + } + return false; + } + + /// Add an extra key binding for "focus prev". + /// Returns false if all 4 slots are full. + pub fn addPrevKey(self: *Self, bind: KeyBind) bool { + for (&self.prev_keys) |*slot| { + if (slot.* == null) { + slot.* = bind; + return true; + } + } + return false; + } + + /// Replace all "next" bindings with a single key. + pub fn setNextKey(self: *Self, bind: KeyBind) void { + self.next_keys = .{ bind, null, null, null }; + } + + /// Replace all "prev" bindings with a single key. + pub fn setPrevKey(self: *Self, bind: KeyBind) void { + self.prev_keys = .{ bind, null, null, null }; + } + + /// Clear all "next" key bindings. + pub fn clearNextKeys(self: *Self) void { + self.next_keys = .{ null, null, null, null }; + } + + /// Clear all "prev" key bindings. + pub fn clearPrevKeys(self: *Self) void { + self.prev_keys = .{ null, null, null, null }; + } + + /// Get the index of the currently focused item. + pub fn focused(self: *const Self) usize { + return self.active; + } + + /// Check if the item at `index` is the currently focused one. + pub fn isFocused(self: *const Self, index: usize) bool { + return self.active == index; + } + + /// Initialize focus: focuses the first item and blurs all others. + /// Call this after adding all components. + pub fn initFocus(self: *Self) void { + if (self.count > 0) { + self.focusAt(0); + } + } + + /// Blur all items (none focused). + pub fn blurAll(self: *Self) void { + for (0..self.count) |i| { + if (self.items[i]) |item| { + item.blur_fn(item.ptr); + } + } + } + + /// Returns the total number of registered items. + pub fn len(self: *const Self) usize { + return self.count; + } + }; +} + +/// Style helper for rendering focus-aware borders. +/// +/// Apply to a base `Style` in your `view()` function to get a border +/// that changes color depending on focus state. +/// +/// ``` +/// const fs = FocusStyle{}; +/// var style = zz.Style{}; +/// style = style.paddingAll(1); +/// style = fs.apply(style, is_focused); +/// const rendered = style.render(allocator, content); +/// ``` +pub const FocusStyle = struct { + /// Border color when focused (default: cyan). + focused_border_fg: Color = .cyan, + /// Border color when not focused (default: dark gray). + blurred_border_fg: Color = .gray(12), + /// Border character set (default: rounded). + border_chars: border_mod.BorderChars = .rounded, + + /// Apply focus-aware border styling to `base`. + /// Returns a new Style with the appropriate border and color. + pub fn apply(self: FocusStyle, base: style_mod.Style, is_focused: bool) style_mod.Style { + var s = base; + s = s.borderAll(self.border_chars); + if (is_focused) { + s = s.borderForeground(self.focused_border_fg); + } else { + s = s.borderForeground(self.blurred_border_fg); + } + return s; + } +}; + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +test "isFocusable positive" { + const Focusable = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + try std.testing.expect(isFocusable(Focusable)); +} + +test "isFocusable negative — missing field" { + const NotFocusable = struct { + pub fn focus(_: *@This()) void {} + pub fn blur(_: *@This()) void {} + }; + try std.testing.expect(!isFocusable(NotFocusable)); +} + +test "isFocusable negative — missing method" { + const NotFocusable = struct { + focused: bool = false, + pub fn focus(_: *@This()) void {} + }; + try std.testing.expect(!isFocusable(NotFocusable)); +} + +test "FocusGroup — basic cycling" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + var c = Item{}; + + var fg: FocusGroup(3) = .{}; + fg.add(&a); + fg.add(&b); + fg.add(&c); + fg.initFocus(); + + // After init: first item focused + try std.testing.expect(a.focused); + try std.testing.expect(!b.focused); + try std.testing.expect(!c.focused); + try std.testing.expectEqual(@as(usize, 0), fg.focused()); + + // focusNext + fg.focusNext(); + try std.testing.expect(!a.focused); + try std.testing.expect(b.focused); + try std.testing.expect(!c.focused); + try std.testing.expectEqual(@as(usize, 1), fg.focused()); + + // focusNext again + fg.focusNext(); + try std.testing.expectEqual(@as(usize, 2), fg.focused()); + try std.testing.expect(c.focused); + + // focusNext wraps + fg.focusNext(); + try std.testing.expectEqual(@as(usize, 0), fg.focused()); + try std.testing.expect(a.focused); + try std.testing.expect(!c.focused); +} + +test "FocusGroup — prev cycling" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + + var fg: FocusGroup(2) = .{}; + fg.add(&a); + fg.add(&b); + fg.initFocus(); + + // focusPrev wraps from 0 to last + fg.focusPrev(); + try std.testing.expectEqual(@as(usize, 1), fg.focused()); + try std.testing.expect(b.focused); + try std.testing.expect(!a.focused); + + // focusPrev goes back + fg.focusPrev(); + try std.testing.expectEqual(@as(usize, 0), fg.focused()); + try std.testing.expect(a.focused); +} + +test "FocusGroup — no wrap" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + + var fg: FocusGroup(2) = .{ .wrap = false }; + fg.add(&a); + fg.add(&b); + fg.initFocus(); + + // At first item, prev should NOT wrap + fg.focusPrev(); + try std.testing.expectEqual(@as(usize, 0), fg.focused()); + + // At last item, next should NOT wrap + fg.focusAt(1); + fg.focusNext(); + try std.testing.expectEqual(@as(usize, 1), fg.focused()); +} + +test "FocusGroup — handleKey Tab" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + + var fg: FocusGroup(2) = .{}; + fg.add(&a); + fg.add(&b); + fg.initFocus(); + + // Tab moves forward + const tab_event = keys.KeyEvent{ .key = .tab, .modifiers = .{} }; + const consumed = fg.handleKey(tab_event); + try std.testing.expect(consumed); + try std.testing.expectEqual(@as(usize, 1), fg.focused()); + + // Shift+Tab moves backward + const shift_tab = keys.KeyEvent{ .key = .tab, .modifiers = .{ .shift = true } }; + const consumed2 = fg.handleKey(shift_tab); + try std.testing.expect(consumed2); + try std.testing.expectEqual(@as(usize, 0), fg.focused()); + + // Other keys not consumed + const other = keys.KeyEvent{ .key = .{ .char = 'a' }, .modifiers = .{} }; + const consumed3 = fg.handleKey(other); + try std.testing.expect(!consumed3); +} + +test "FocusGroup — focusAt and isFocused" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + var c = Item{}; + + var fg: FocusGroup(3) = .{}; + fg.add(&a); + fg.add(&b); + fg.add(&c); + + fg.focusAt(2); + try std.testing.expect(!fg.isFocused(0)); + try std.testing.expect(!fg.isFocused(1)); + try std.testing.expect(fg.isFocused(2)); + try std.testing.expect(!a.focused); + try std.testing.expect(!b.focused); + try std.testing.expect(c.focused); +} + +test "FocusGroup — blurAll" { + const Item = struct { + focused: bool = false, + pub fn focus(self: *@This()) void { + self.focused = true; + } + pub fn blur(self: *@This()) void { + self.focused = false; + } + }; + + var a = Item{}; + var b = Item{}; + + var fg: FocusGroup(2) = .{}; + fg.add(&a); + fg.add(&b); + fg.initFocus(); + try std.testing.expect(a.focused); + + fg.blurAll(); + try std.testing.expect(!a.focused); + try std.testing.expect(!b.focused); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig new file mode 100644 index 0000000..d740943 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig @@ -0,0 +1,299 @@ +//! Form component. +//! Composes multiple input fields with focus management, labels, and validation. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const border_mod = @import("../style/border.zig"); +const focus_mod = @import("focus.zig"); + +/// Universally-supported submit bindings. Ctrl+S works in every terminal +/// (no encoding ambiguity). Ctrl+Enter is included for terminals that +/// implement the Kitty keyboard protocol — most don't (notably macOS +/// Terminal.app, basic xterm), so it's a bonus, not the primary binding. +const default_submit_keys = [_]keys.KeyEvent{ + keys.KeyEvent.ctrl('s'), + .{ .key = .enter, .modifiers = .{ .ctrl = true } }, +}; + +const default_cancel_keys = [_]keys.KeyEvent{ + .{ .key = .escape }, +}; + +pub fn Form(comptime max_fields: usize) type { + return struct { + // Fields + fields: [max_fields]?Field, + field_count: usize, + + // Focus + focus_group: focus_mod.FocusGroup(max_fields), + + // State + submitted: bool, + cancelled: bool, + + // Layout + label_width: u16, + spacing: u16, + show_required_marker: bool, + + // Submit bindings. Multiple keys can submit the form. Default + // includes Ctrl+S (works in every terminal) and Ctrl+Enter (only + // works in terminals that implement the Kitty keyboard protocol — + // Terminal.app and most basic xterms cannot tell Ctrl+Enter from + // plain Enter, so we don't rely on it). + submit_keys: []const keys.KeyEvent, + cancel_keys: []const keys.KeyEvent, + /// Human-readable description of submit/cancel bindings shown in the + /// footer hint. Override if you change submit_keys/cancel_keys. + hint_text: []const u8, + + // Styling + label_style: style_mod.Style, + required_style: style_mod.Style, + error_style: style_mod.Style, + border_chars: border_mod.BorderChars, + border_fg: Color, + border_focus_fg: Color, + title: []const u8, + title_style: style_mod.Style, + + const Self = @This(); + + pub const Field = struct { + label: []const u8, + required: bool, + error_msg: ?[]const u8, + // Type-erased component + ptr: *anyopaque, + view_fn: *const fn (*anyopaque, std.mem.Allocator) anyerror![]const u8, + handle_key_fn: *const fn (*anyopaque, keys.KeyEvent) void, + validate_fn: ?*const fn (*anyopaque) ?[]const u8, + }; + + pub fn init() Self { + return .{ + .fields = [_]?Field{null} ** max_fields, + .field_count = 0, + .focus_group = .{}, + .submitted = false, + .cancelled = false, + .label_width = 15, + .spacing = 1, + .show_required_marker = true, + .submit_keys = &default_submit_keys, + .cancel_keys = &default_cancel_keys, + .hint_text = "Tab: next field | Ctrl+S: submit | Esc: cancel", + .label_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .required_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + .error_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + .border_chars = .rounded, + .border_fg = .gray(10), + .border_focus_fg = .cyan, + .title = "", + .title_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + /// Add a focusable component as a form field. + pub fn addField(self: *Self, label: []const u8, component: anytype, options: struct { + required: bool = false, + validate_fn: ?*const fn (*anyopaque) ?[]const u8 = null, + }) void { + if (self.field_count >= max_fields) return; + + const Ptr = @TypeOf(component); + const T = @typeInfo(Ptr).pointer.child; + + self.fields[self.field_count] = .{ + .label = label, + .required = options.required, + .error_msg = null, + .ptr = @ptrCast(component), + .view_fn = @ptrCast(&struct { + fn call(raw_ptr: *anyopaque, allocator: std.mem.Allocator) anyerror![]const u8 { + const ptr: *T = @ptrCast(@alignCast(raw_ptr)); + return ptr.view(allocator); + } + }.call), + .handle_key_fn = @ptrCast(&struct { + fn call(raw_ptr: *anyopaque, key: keys.KeyEvent) void { + const ptr: *T = @ptrCast(@alignCast(raw_ptr)); + ptr.handleKey(key); + } + }.call), + .validate_fn = options.validate_fn, + }; + + self.focus_group.add(component); + self.field_count += 1; + } + + /// Initialize focus on first field. + pub fn initFocus(self: *Self) void { + self.focus_group.initFocus(); + } + + /// Check if form was submitted. + pub fn isSubmitted(self: *const Self) bool { + return self.submitted; + } + + /// Check if form was cancelled. + pub fn isCancelled(self: *const Self) bool { + return self.cancelled; + } + + /// Reset submission state. + pub fn reset(self: *Self) void { + self.submitted = false; + self.cancelled = false; + for (0..self.field_count) |i| { + if (self.fields[i]) |*field| { + field.error_msg = null; + } + } + } + + /// Validate all fields. Returns true if all pass. + pub fn validate(self: *Self) bool { + var all_valid = true; + for (0..self.field_count) |i| { + if (self.fields[i]) |*field| { + if (field.validate_fn) |vfn| { + field.error_msg = vfn(field.ptr); + if (field.error_msg != null) all_valid = false; + } + } + } + return all_valid; + } + + /// Get current focused field index. + pub fn focusedIndex(self: *const Self) usize { + return self.focus_group.focused(); + } + + /// Handle key events. + pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { + // Submit on any configured submit key. + for (self.submit_keys) |sk| { + if (sk.eql(key)) { + if (self.validate()) { + self.submitted = true; + } + return true; + } + } + + // Cancel on any configured cancel key. + for (self.cancel_keys) |ck| { + if (ck.eql(key)) { + self.cancelled = true; + return true; + } + } + + // Tab/Shift+Tab for focus cycling + if (self.focus_group.handleKey(key)) { + return true; + } + + // Forward to active field + const active = self.focus_group.focused(); + if (active < self.field_count) { + if (self.fields[active]) |field| { + field.handle_key_fn(field.ptr, key); + return true; + } + } + + return false; + } + + /// Render the form. + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Title + if (self.title.len > 0) { + const styled_title = try self.title_style.render(allocator, self.title); + try writer.writeAll(styled_title); + try writer.writeByte('\n'); + try writer.writeByte('\n'); + } + + // Fields + for (0..self.field_count) |i| { + const field = self.fields[i] orelse continue; + + if (i > 0) { + for (0..self.spacing) |_| try writer.writeByte('\n'); + } + + // Label + const label_text = if (field.required and self.show_required_marker) + try std.fmt.allocPrint(allocator, "{s} *", .{field.label}) + else + field.label; + + const is_focused = self.focus_group.isFocused(i); + const lbl_style = if (is_focused) blk: { + var s = self.label_style; + s = s.fg(self.border_focus_fg); + break :blk s; + } else self.label_style; + + const styled_label = try lbl_style.render(allocator, label_text); + try writer.writeAll(styled_label); + try writer.writeByte('\n'); + + // Component view + const component_view = field.view_fn(field.ptr, allocator) catch try allocator.dupe(u8, "render error"); + try writer.writeAll(component_view); + + // Error message + if (field.error_msg) |err_msg| { + try writer.writeByte('\n'); + const styled_err = try self.error_style.render(allocator, err_msg); + try writer.writeAll(styled_err); + } + } + + // Footer + try writer.writeAll("\n\n"); + var hint_style = style_mod.Style{}; + hint_style = hint_style.fg(.gray(12)); + hint_style = hint_style.inline_style(true); + const hint = try hint_style.render(allocator, self.hint_text); + try writer.writeAll(hint); + + return result.toOwnedSlice(); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig new file mode 100644 index 0000000..5fb67e3 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig @@ -0,0 +1,249 @@ +//! Gauge component for displaying a value within a range. +//! Supports bar, level meter, and block display styles with thresholds and gradients. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Gauge = struct { + /// Current value. + value: f64 = 0, + /// Minimum value. + min: f64 = 0, + /// Maximum value. + max: f64 = 100, + /// Display width in cells. + width: u16 = 40, + /// Display style. + display_style: DisplayStyle = .bar, + /// Show value label. + show_value: bool = true, + /// Show percentage. + show_percent: bool = false, + /// Label format (prefix text). + label: []const u8 = "", + /// Thresholds for color changes. + thresholds: []const Threshold = &.{}, + /// Base color (used when below all thresholds). + base_color: Color = .green, + /// Empty/background color. + empty_color: Color = .gray(6), + /// Label style. + label_style: style_mod.Style = .{}, + /// Value/percent label style. + value_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + /// Filled bar character. + full_char: []const u8 = "\xe2\x96\x88", + /// Empty bar character. + empty_char: []const u8 = "\xe2\x96\x91", + /// Level meter bracket left. + bracket_left: []const u8 = "[", + /// Level meter bracket right. + bracket_right: []const u8 = "]", + /// Number of segments in level meter. + level_segments: usize = 10, + /// Value format string prefix. + value_prefix: []const u8 = "", + /// Value format string suffix. + value_suffix: []const u8 = "", + + pub const DisplayStyle = enum { + /// Horizontal bar with fill characters. + bar, + /// Vertical level meter segments. + level_meter, + /// Block characters showing intensity. + blocks, + }; + + pub const Threshold = struct { + value: f64, + color: Color, + }; + + /// Set the gauge value clamped to min/max. + pub fn setValue(self: *Gauge, v: f64) void { + self.value = @max(self.min, @min(v, self.max)); + } + + /// Get the ratio (0.0 to 1.0). + pub fn ratio(self: *const Gauge) f64 { + const range = self.max - self.min; + if (range <= 0) return 0; + return (self.value - self.min) / range; + } + + /// Get the active color based on thresholds. + fn activeColor(self: *const Gauge) Color { + var result = self.base_color; + for (self.thresholds) |t| { + if (self.value >= t.value) result = t.color; + } + return result; + } + + /// Render the gauge. + pub fn view(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { + return switch (self.display_style) { + .bar => self.renderBar(allocator), + .level_meter => self.renderLevelMeter(allocator), + .blocks => self.renderBlocks(allocator), + }; + } + + fn renderBar(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { + const pct = self.ratio(); + const active_color = self.activeColor(); + const bar_width: usize = self.width; + const filled: usize = @intFromFloat(@as(f64, @floatFromInt(bar_width)) * pct); + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Label + if (self.label.len > 0) { + if (self.label_style.bold_attr != null or !self.label_style.foreground.isNone()) { + writer.writeAll(self.label_style.render(allocator, self.label) catch self.label) catch {}; + } else { + writer.writeAll(self.label) catch {}; + } + writer.writeByte(' ') catch {}; + } + + // Filled portion + var fill_style = style_mod.Style{}; + fill_style = fill_style.fg(active_color); + fill_style = fill_style.inline_style(true); + + var empty_style = style_mod.Style{}; + empty_style = empty_style.fg(self.empty_color); + empty_style = empty_style.inline_style(true); + + for (0..bar_width) |col| { + if (col < filled) { + writer.writeAll(fill_style.render(allocator, "\xe2\x96\x88") catch "\xe2\x96\x88") catch {}; + } else if (col == filled and pct > 0) { + // Partial fill using fractional blocks + const frac = (@as(f64, @floatFromInt(bar_width)) * pct) - @as(f64, @floatFromInt(filled)); + const block_idx: usize = @intFromFloat(frac * 8); + const partial_blocks = [_][]const u8{ + " ", + "\xe2\x96\x8f", // ▏ + "\xe2\x96\x8e", // ▎ + "\xe2\x96\x8d", // ▍ + "\xe2\x96\x8c", // ▌ + "\xe2\x96\x8b", // ▋ + "\xe2\x96\x8a", // ▊ + "\xe2\x96\x89", // ▉ + }; + const ch = if (block_idx < partial_blocks.len) partial_blocks[block_idx] else "\xe2\x96\x88"; + writer.writeAll(fill_style.render(allocator, ch) catch ch) catch {}; + } else { + writer.writeAll(empty_style.render(allocator, "\xe2\x96\x91") catch "\xe2\x96\x91") catch {}; + } + } + + // Value/percent label + if (self.show_value or self.show_percent) { + writer.writeByte(' ') catch {}; + if (self.show_percent) { + const pct_val = pct * 100; + writer.print("{d:.0}%", .{pct_val}) catch {}; + } else { + writer.print("{d:.1}/{d:.1}", .{ self.value, self.max }) catch {}; + } + } + + return result.toArrayList().items; + } + + fn renderLevelMeter(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { + const pct = self.ratio(); + const levels: usize = 10; + const filled: usize = @intFromFloat(@as(f64, @floatFromInt(levels)) * pct); + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (self.label.len > 0) { + writer.writeAll(self.label) catch {}; + writer.writeByte(' ') catch {}; + } + + writer.writeAll("[") catch {}; + for (0..levels) |lvl| { + const level_pct = @as(f64, @floatFromInt(lvl)) / @as(f64, @floatFromInt(levels)); + const c = self.colorForLevel(level_pct); + var s = style_mod.Style{}; + s = s.fg(c); + s = s.inline_style(true); + + if (lvl < filled) { + writer.writeAll(s.render(allocator, "\xe2\x96\x88") catch "\xe2\x96\x88") catch {}; + } else { + writer.writeAll("\xe2\x96\x91") catch {}; + } + } + writer.writeAll("]") catch {}; + + if (self.show_percent) { + writer.print(" {d:.0}%", .{pct * 100}) catch {}; + } + + return result.toArrayList().items; + } + + fn renderBlocks(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { + const pct = self.ratio(); + const active_color = self.activeColor(); + const block_count: usize = self.width; + + // Use shade characters based on intensity + const shades = [_][]const u8{ " ", "\xe2\x96\x91", "\xe2\x96\x92", "\xe2\x96\x93", "\xe2\x96\x88" }; + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (self.label.len > 0) { + writer.writeAll(self.label) catch {}; + writer.writeByte(' ') catch {}; + } + + var s = style_mod.Style{}; + s = s.fg(active_color); + s = s.inline_style(true); + + for (0..block_count) |col| { + const col_pct = @as(f64, @floatFromInt(col)) / @as(f64, @floatFromInt(block_count)); + if (col_pct < pct) { + // Full block for cells well below the value + const local_pct = (pct - col_pct) * @as(f64, @floatFromInt(block_count)); + const shade_idx: usize = @intFromFloat(@min(local_pct, 4)); + const ch = if (shade_idx < shades.len) shades[shade_idx] else shades[4]; + writer.writeAll(s.render(allocator, ch) catch ch) catch {}; + } else { + writer.writeByte(' ') catch {}; + } + } + + if (self.show_percent) { + writer.print(" {d:.0}%", .{pct * 100}) catch {}; + } + + return result.toArrayList().items; + } + + fn colorForLevel(self: *const Gauge, level_pct: f64) Color { + const value = self.min + (self.max - self.min) * level_pct; + var result = self.base_color; + for (self.thresholds) |t| { + if (value >= t.value) result = t.color; + } + return result; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig new file mode 100644 index 0000000..766ff7d --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig @@ -0,0 +1,250 @@ +//! Heatmap component for 2D data visualization. +//! Displays data as a colored grid with configurable color scales. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Heatmap = struct { + allocator: std.mem.Allocator, + /// 2D data stored row-major. + data: []const f64 = &.{}, + rows: usize = 0, + cols: usize = 0, + /// Row labels (optional). + row_labels: []const []const u8 = &.{}, + /// Column labels (optional). + col_labels: []const []const u8 = &.{}, + /// Color scale. + color_scale: ColorScale = .green_scale, + /// Cell width in characters. + cell_width: u8 = 2, + /// Manual min/max (auto-detect if null). + min_val: ?f64 = null, + max_val: ?f64 = null, + /// Show legend. + show_legend: bool = true, + /// Show values in cells. + show_values: bool = false, + /// Title. + title: []const u8 = "", + /// Cell height in rows (1 = single line). + cell_height: u8 = 1, + /// Title style. + title_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + /// Row label style. + row_label_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + /// Column label style. + col_label_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + /// Legend label style. + legend_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + /// Number of steps in the legend gradient. + legend_steps: usize = 10, + /// Empty cell character (used when value is zero/min). + empty_char: []const u8 = " ", + + pub const ColorScale = enum { + /// Dark green to bright green (GitHub contributions style). + green_scale, + /// Blue to cyan to green to yellow to red. + cool_to_hot, + /// Black to white. + grayscale, + /// Blue to red. + blue_red, + }; + + pub fn init(allocator: std.mem.Allocator) Heatmap { + return .{ .allocator = allocator }; + } + + /// Set data as a flat array with dimensions. + pub fn setData(self: *Heatmap, r: usize, c: usize, d: []const f64) void { + self.rows = r; + self.cols = c; + self.data = d; + } + + fn getMinMax(self: *const Heatmap) struct { min: f64, max: f64 } { + const mn = self.min_val orelse blk: { + var m: f64 = std.math.inf(f64); + for (self.data) |v| m = @min(m, v); + break :blk m; + }; + const mx = self.max_val orelse blk: { + var m: f64 = -std.math.inf(f64); + for (self.data) |v| m = @max(m, v); + break :blk m; + }; + return .{ .min = mn, .max = mx }; + } + + fn normalize(val: f64, mn: f64, mx: f64) f64 { + if (mx <= mn) return 0; + return @max(0, @min(1, (val - mn) / (mx - mn))); + } + + fn scaleColor(self: *const Heatmap, t: f64) Color { + return switch (self.color_scale) { + .green_scale => { + if (t < 0.01) return .gray(2); + const g: u8 = @intFromFloat(80 + 175 * t); + return .fromRgb(0, g, 0); + }, + .cool_to_hot => { + if (t < 0.25) { + const lt = t * 4; + return .fromRgb(0, @intFromFloat(lt * 255), 255); + } else if (t < 0.5) { + const lt = (t - 0.25) * 4; + return .fromRgb(0, 255, @intFromFloat(255 - lt * 255)); + } else if (t < 0.75) { + const lt = (t - 0.5) * 4; + return .fromRgb(@intFromFloat(lt * 255), 255, 0); + } else { + const lt = (t - 0.75) * 4; + return .fromRgb(255, @intFromFloat(255 - lt * 255), 0); + } + }, + .grayscale => { + const v: u8 = @intFromFloat(t * 255); + return .fromRgb(v, v, v); + }, + .blue_red => { + const r: u8 = @intFromFloat(t * 255); + const b: u8 = @intFromFloat((1 - t) * 255); + return .fromRgb(r, 0, b); + }, + }; + } + + pub fn view(self: *const Heatmap, allocator: std.mem.Allocator) []const u8 { + if (self.rows == 0 or self.cols == 0) return ""; + + const mm = self.getMinMax(); + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Title + if (self.title.len > 0) { + writer.writeAll(self.title_style.render(allocator, self.title) catch self.title) catch {}; + writer.writeByte('\n') catch {}; + } + + // Column labels + if (self.col_labels.len > 0) { + // Padding for row labels + const label_pad: usize = if (self.row_labels.len > 0) maxLabelWidth(self.row_labels) + 1 else 0; + for (0..label_pad) |_| writer.writeByte(' ') catch {}; + + for (self.col_labels, 0..) |label, ci| { + if (ci >= self.cols) break; + const cw = self.cell_width; + if (label.len >= cw) { + writer.writeAll(label[0..cw]) catch {}; + } else { + writer.writeAll(label) catch {}; + for (0..cw - label.len) |_| writer.writeByte(' ') catch {}; + } + } + writer.writeByte('\n') catch {}; + } + + // Data rows + for (0..self.rows) |r| { + // Row label + if (r < self.row_labels.len) { + const max_lw = maxLabelWidth(self.row_labels); + const label = self.row_labels[r]; + // Right-align + if (label.len < max_lw) { + for (0..max_lw - label.len) |_| writer.writeByte(' ') catch {}; + } + writer.writeAll(label) catch {}; + writer.writeByte(' ') catch {}; + } + + // Cells + for (0..self.cols) |c| { + const idx = r * self.cols + c; + const val = if (idx < self.data.len) self.data[idx] else 0; + const t = normalize(val, mm.min, mm.max); + const bg_color = self.scaleColor(t); + + var cs = style_mod.Style{}; + cs = cs.bg(bg_color); + cs = cs.inline_style(true); + + if (self.show_values and self.cell_width >= 3) { + const val_str = std.fmt.allocPrint(allocator, "{d:.0}", .{val}) catch " "; + const padded = padCenter(allocator, val_str, self.cell_width); + // Choose foreground for contrast + cs = cs.fg(if (t > 0.5) .black else .white); + writer.writeAll(cs.render(allocator, padded) catch padded) catch {}; + } else { + var cell_buf: [8]u8 = undefined; + const cw = @min(self.cell_width, 8); + for (0..cw) |i| cell_buf[i] = ' '; + writer.writeAll(cs.render(allocator, cell_buf[0..cw]) catch cell_buf[0..cw]) catch {}; + } + } + if (r < self.rows - 1) writer.writeByte('\n') catch {}; + } + + // Legend + if (self.show_legend) { + writer.writeAll("\n\n") catch {}; + const steps: usize = 10; + for (0..steps) |s| { + const t = @as(f64, @floatFromInt(s)) / @as(f64, @floatFromInt(steps - 1)); + const c = self.scaleColor(t); + var ls = style_mod.Style{}; + ls = ls.bg(c); + ls = ls.inline_style(true); + writer.writeAll(ls.render(allocator, " ") catch " ") catch {}; + } + const min_str = std.fmt.allocPrint(allocator, " {d:.0}", .{mm.min}) catch ""; + const max_str = std.fmt.allocPrint(allocator, " - {d:.0}", .{mm.max}) catch ""; + writer.writeAll(min_str) catch {}; + writer.writeAll(max_str) catch {}; + } + + return result.toArrayList().items; + } + + fn maxLabelWidth(labels: []const []const u8) usize { + var max: usize = 0; + for (labels) |l| max = @max(max, l.len); + return max; + } + + fn padCenter(allocator: std.mem.Allocator, text: []const u8, target_width: u8) []const u8 { + if (text.len >= target_width) return text[0..target_width]; + const total_pad = target_width - text.len; + const left_pad = total_pad / 2; + const right_pad = total_pad - left_pad; + var buf = std.array_list.Managed(u8).init(allocator); + for (0..left_pad) |_| buf.append(' ') catch {}; + buf.appendSlice(text) catch {}; + for (0..right_pad) |_| buf.append(' ') catch {}; + return buf.items; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig new file mode 100644 index 0000000..fce7398 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig @@ -0,0 +1,238 @@ +//! Help component for displaying key bindings. +//! Shows keyboard shortcuts and their descriptions. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); +const join = @import("../layout/join.zig"); + +pub const Help = struct { + allocator: std.mem.Allocator, + + // Bindings + bindings: std.array_list.Managed(Binding), + + // Appearance + separator: []const u8, + ellipsis: []const u8, + max_width: ?u16, + short_mode: bool, + + // Styling + key_style: style_mod.Style, + desc_style: style_mod.Style, + sep_style: style_mod.Style, + + pub const Binding = struct { + key: []const u8, + description: []const u8, + short_desc: ?[]const u8, + }; + + pub fn init(allocator: std.mem.Allocator) Help { + return .{ + .allocator = allocator, + .bindings = std.array_list.Managed(Binding).init(allocator), + .separator = " • ", + .ellipsis = "...", + .max_width = null, + .short_mode = false, + .key_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .desc_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(18)); + s = s.inline_style(true); + break :blk s; + }, + .sep_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *Help) void { + self.bindings.deinit(); + } + + /// Create a Help component from a KeyMap + pub fn fromKeyMap(allocator: std.mem.Allocator, keymap: anytype) !Help { + var help = Help.init(allocator); + const bindings = try keymap.toHelpBindings(allocator); + try help.setBindings(bindings); + return help; + } + + /// Add a key binding + pub fn addBinding(self: *Help, key: []const u8, description: []const u8) !void { + try self.bindings.append(.{ + .key = key, + .description = description, + .short_desc = null, + }); + } + + /// Add a key binding with short description + pub fn addBindingShort(self: *Help, key: []const u8, description: []const u8, short_desc: []const u8) !void { + try self.bindings.append(.{ + .key = key, + .description = description, + .short_desc = short_desc, + }); + } + + /// Set bindings from a list + pub fn setBindings(self: *Help, bindings: []const Binding) !void { + self.bindings.clearRetainingCapacity(); + try self.bindings.appendSlice(bindings); + } + + /// Clear all bindings + pub fn clear(self: *Help) void { + self.bindings.clearRetainingCapacity(); + } + + /// Set max width (enables truncation) + pub fn setMaxWidth(self: *Help, width: u16) void { + self.max_width = width; + } + + /// Enable/disable short mode + pub fn setShortMode(self: *Help, short: bool) void { + self.short_mode = short; + } + + /// Render the help + pub fn view(self: *const Help, allocator: std.mem.Allocator) ![]const u8 { + if (self.bindings.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var total_width: usize = 0; + + for (self.bindings.items, 0..) |binding, i| { + // Calculate this binding's width + const desc = if (self.short_mode and binding.short_desc != null) + binding.short_desc.? + else + binding.description; + + const binding_text = try std.fmt.allocPrint(allocator, "{s} {s}", .{ binding.key, desc }); + const binding_width = measure.width(binding_text); + + // Check if we need truncation + if (self.max_width) |max_w| { + const sep_width = if (i > 0) measure.width(self.separator) else 0; + if (total_width + sep_width + binding_width > max_w) { + // Add ellipsis and stop + if (i > 0) { + const sep_styled = try self.sep_style.render(allocator, self.separator); + try writer.writeAll(sep_styled); + } + try writer.writeAll(self.ellipsis); + break; + } + } + + // Add separator + if (i > 0) { + const sep_styled = try self.sep_style.render(allocator, self.separator); + try writer.writeAll(sep_styled); + total_width += measure.width(self.separator); + } + + // Add key + const key_styled = try self.key_style.render(allocator, binding.key); + try writer.writeAll(key_styled); + + // Add description + try writer.writeByte(' '); + const desc_styled = try self.desc_style.render(allocator, desc); + try writer.writeAll(desc_styled); + + total_width += binding_width; + } + + return result.toOwnedSlice(); + } + + /// Render as a vertical list + pub fn viewVertical(self: *const Help, allocator: std.mem.Allocator) ![]const u8 { + if (self.bindings.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + // Find max key width + var max_key_width: usize = 0; + for (self.bindings.items) |binding| { + max_key_width = @max(max_key_width, measure.width(binding.key)); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (self.bindings.items, 0..) |binding, i| { + if (i > 0) try writer.writeByte('\n'); + + // Key with padding + const key_styled = try self.key_style.render(allocator, binding.key); + try writer.writeAll(key_styled); + + const key_width = measure.width(binding.key); + for (0..(max_key_width - key_width + 2)) |_| { + try writer.writeByte(' '); + } + + // Description + const desc = if (self.short_mode and binding.short_desc != null) + binding.short_desc.? + else + binding.description; + const desc_styled = try self.desc_style.render(allocator, desc); + try writer.writeAll(desc_styled); + } + + return result.toOwnedSlice(); + } +}; + +/// Common key binding sets +pub const CommonBindings = struct { + pub const navigation = [_]Help.Binding{ + .{ .key = "↑/k", .description = "Move up", .short_desc = "up" }, + .{ .key = "↓/j", .description = "Move down", .short_desc = "down" }, + .{ .key = "←/h", .description = "Move left", .short_desc = "left" }, + .{ .key = "→/l", .description = "Move right", .short_desc = "right" }, + }; + + pub const quit = Help.Binding{ + .key = "q", + .description = "Quit", + .short_desc = "quit", + }; + + pub const enter = Help.Binding{ + .key = "enter", + .description = "Select", + .short_desc = "select", + }; + + pub const escape = Help.Binding{ + .key = "esc", + .description = "Cancel", + .short_desc = "cancel", + }; +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig new file mode 100644 index 0000000..e8bbfb7 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig @@ -0,0 +1,114 @@ +//! Keybinding management component. +//! Provides structured key binding definitions with matching and help integration. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const Key = keys.Key; +const KeyEvent = keys.KeyEvent; +const Modifiers = keys.Modifiers; +const Help = @import("help.zig").Help; + +/// A single key binding with description and enabled state +pub const KeyBinding = struct { + key_event: KeyEvent, + description: []const u8, + short_desc: ?[]const u8 = null, + enabled: bool = true, + + /// Check if a key event matches this binding + pub fn matches(self: *const KeyBinding, event: KeyEvent) bool { + if (!self.enabled) return false; + return self.key_event.eql(event); + } + + /// Get a display string for the key + pub fn keyDisplay(self: *const KeyBinding, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (self.key_event.modifiers.ctrl) try writer.writeAll("ctrl+"); + if (self.key_event.modifiers.alt) try writer.writeAll("alt+"); + if (self.key_event.modifiers.shift) try writer.writeAll("shift+"); + if (self.key_event.modifiers.super) try writer.writeAll("super+"); + + switch (self.key_event.key) { + .char => |c| { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch 0; + try writer.writeAll(buf[0..len]); + }, + else => try writer.writeAll(self.key_event.key.name()), + } + + return result.toOwnedSlice(); + } +}; + +/// A collection of key bindings with matching and management +pub const KeyMap = struct { + bindings: std.array_list.Managed(KeyBinding), + + pub fn init(allocator: std.mem.Allocator) KeyMap { + return .{ + .bindings = std.array_list.Managed(KeyBinding).init(allocator), + }; + } + + pub fn deinit(self: *KeyMap) void { + self.bindings.deinit(); + } + + /// Add a key binding + pub fn add(self: *KeyMap, binding: KeyBinding) !void { + try self.bindings.append(binding); + } + + /// Add a simple character binding + pub fn addChar(self: *KeyMap, c: u21, description: []const u8) !void { + try self.bindings.append(.{ + .key_event = KeyEvent.char(c), + .description = description, + }); + } + + /// Add a ctrl+character binding + pub fn addCtrl(self: *KeyMap, c: u21, description: []const u8) !void { + try self.bindings.append(.{ + .key_event = KeyEvent.ctrl(c), + .description = description, + }); + } + + /// Find the first matching binding for an event + pub fn match(self: *const KeyMap, event: KeyEvent) ?*const KeyBinding { + for (self.bindings.items) |*binding| { + if (binding.matches(event)) return binding; + } + return null; + } + + /// Enable or disable a binding by description + pub fn setEnabled(self: *KeyMap, description: []const u8, enabled: bool) void { + for (self.bindings.items) |*binding| { + if (std.mem.eql(u8, binding.description, description)) { + binding.enabled = enabled; + } + } + } + + /// Convert to Help.Binding format for use with Help component + pub fn toHelpBindings(self: *const KeyMap, allocator: std.mem.Allocator) ![]Help.Binding { + var result = std.array_list.Managed(Help.Binding).init(allocator); + for (self.bindings.items) |*binding| { + if (!binding.enabled) continue; + const key_str = try binding.keyDisplay(allocator); + try result.append(.{ + .key = key_str, + .description = binding.description, + .short_desc = binding.short_desc, + }); + } + return result.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig new file mode 100644 index 0000000..5cf72f5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig @@ -0,0 +1,490 @@ +//! Selectable list component. +//! Displays a list of items with selection and optional filtering. + +const std = @import("std"); +const Writer = std.Io.Writer; +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 { + allocator: std.mem.Allocator, + + // Items + items: std.array_list.Managed(Item), + filtered_indices: std.array_list.Managed(usize), + + // Selection + cursor: usize, + selected: std.AutoHashMap(usize, void), + + // Filtering + filter_text: std.array_list.Managed(u8), + filter_enabled: bool, + + // Appearance + height: u16, + y_offset: usize, + + // Styling + item_style: style_mod.Style, + selected_style: style_mod.Style, + cursor_style: style_mod.Style, + filter_style: style_mod.Style, + + // Symbols + cursor_symbol: []const u8, + selected_symbol: []const u8, + unselected_symbol: []const u8, + + // Focus + focused: bool, + + // Behavior + multi_select: bool, + wrap_around: bool, + + // Status + status_message: ?[]const u8, + show_item_count: bool, + + const Self = @This(); + + pub const Item = struct { + value: T, + title: []const u8, + description: []const u8, + enabled: bool, + + pub fn init(value: T, title: []const u8) Item { + return .{ + .value = value, + .title = title, + .description = "", + .enabled = true, + }; + } + + pub fn withDescription(value: T, title: []const u8, desc: []const u8) Item { + return .{ + .value = value, + .title = title, + .description = desc, + .enabled = true, + }; + } + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .items = std.array_list.Managed(Item).init(allocator), + .filtered_indices = std.array_list.Managed(usize).init(allocator), + .cursor = 0, + .selected = std.AutoHashMap(usize, void).init(allocator), + .filter_text = std.array_list.Managed(u8).init(allocator), + .filter_enabled = false, + .height = 10, + .y_offset = 0, + .item_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .selected_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.magenta); + s = s.inline_style(true); + break :blk s; + }, + .filter_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .cursor_symbol = "> ", + .selected_symbol = "[x] ", + .unselected_symbol = "[ ] ", + .focused = true, + .multi_select = false, + .wrap_around = true, + .status_message = null, + .show_item_count = false, + }; + } + + pub fn deinit(self: *Self) void { + self.items.deinit(); + self.filtered_indices.deinit(); + self.selected.deinit(); + self.filter_text.deinit(); + } + + /// Add an item to the list + pub fn addItem(self: *Self, item: Item) !void { + try self.items.append(item); + try self.updateFilter(); + } + + /// Add multiple items + pub fn addItems(self: *Self, items: []const Item) !void { + try self.items.appendSlice(items); + try self.updateFilter(); + } + + /// Set items (replaces all) + pub fn setItems(self: *Self, items: []const Item) !void { + self.items.clearRetainingCapacity(); + try self.items.appendSlice(items); + self.cursor = 0; + self.y_offset = 0; + try self.updateFilter(); + } + + /// Clear all items + pub fn clear(self: *Self) void { + self.items.clearRetainingCapacity(); + self.filtered_indices.clearRetainingCapacity(); + self.selected.clearRetainingCapacity(); + self.cursor = 0; + self.y_offset = 0; + } + + /// Get selected item + pub fn selectedItem(self: *const Self) ?*const Item { + const visible = self.visibleItems(); + if (self.cursor < visible.len) { + const idx = visible[self.cursor]; + return &self.items.items[idx]; + } + return null; + } + + /// Get selected value + pub fn selectedValue(self: *const Self) ?T { + if (self.selectedItem()) |item| { + return item.value; + } + return null; + } + + /// Get all selected items (for multi-select) + pub fn selectedItems(self: *const Self, allocator: std.mem.Allocator) ![]const *const Item { + var result = std.array_list.Managed(*const Item).init(allocator); + var iter = self.selected.keyIterator(); + while (iter.next()) |idx| { + if (idx.* < self.items.items.len) { + try result.append(&self.items.items[idx.*]); + } + } + return result.toOwnedSlice(); + } + + /// Move cursor up + pub fn cursorUp(self: *Self) void { + const visible = self.visibleItems(); + if (visible.len == 0) return; + + if (self.cursor > 0) { + self.cursor -= 1; + } else if (self.wrap_around) { + self.cursor = visible.len - 1; + } + + self.ensureVisible(); + } + + /// Move cursor down + pub fn cursorDown(self: *Self) void { + const visible = self.visibleItems(); + if (visible.len == 0) return; + + if (self.cursor < visible.len - 1) { + self.cursor += 1; + } else if (self.wrap_around) { + self.cursor = 0; + } + + self.ensureVisible(); + } + + /// Page up + pub fn pageUp(self: *Self) void { + if (self.cursor >= self.height) { + self.cursor -= self.height; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + /// Page down + pub fn pageDown(self: *Self) void { + const visible = self.visibleItems(); + if (self.cursor + self.height < visible.len) { + self.cursor += self.height; + } else if (visible.len > 0) { + self.cursor = visible.len - 1; + } + self.ensureVisible(); + } + + /// Go to first item + pub fn gotoFirst(self: *Self) void { + self.cursor = 0; + self.y_offset = 0; + } + + /// Go to last item + pub fn gotoLast(self: *Self) void { + const visible = self.visibleItems(); + if (visible.len > 0) { + self.cursor = visible.len - 1; + self.ensureVisible(); + } + } + + /// Toggle selection of current item + pub fn toggleSelection(self: *Self) void { + const visible = self.visibleItems(); + if (self.cursor >= visible.len) return; + + const idx = visible[self.cursor]; + + if (self.multi_select) { + if (self.selected.contains(idx)) { + _ = self.selected.remove(idx); + } else { + self.selected.put(idx, {}) catch {}; + } + } else { + self.selected.clearRetainingCapacity(); + self.selected.put(idx, {}) catch {}; + } + } + + /// Select current item + pub fn selectCurrent(self: *Self) void { + const visible = self.visibleItems(); + if (self.cursor >= visible.len) return; + + const idx = visible[self.cursor]; + if (!self.multi_select) { + self.selected.clearRetainingCapacity(); + } + self.selected.put(idx, {}) catch {}; + } + + /// Enable filtering + pub fn enableFilter(self: *Self) void { + self.filter_enabled = true; + } + + /// Disable filtering + pub fn disableFilter(self: *Self) void { + self.filter_enabled = false; + self.filter_text.clearRetainingCapacity(); + self.updateFilter() catch {}; + } + + /// Set filter text + pub fn setFilter(self: *Self, text: []const u8) !void { + self.filter_text.clearRetainingCapacity(); + try self.filter_text.appendSlice(text); + try self.updateFilter(); + } + + /// Set focused state (for use with FocusGroup). + pub fn focus(self: *Self) void { + self.focused = true; + } + + /// Clear focused state (for use with FocusGroup). + pub fn blur(self: *Self) void { + self.focused = false; + } + + /// Handle key event + pub fn handleKey(self: *Self, key: keys.KeyEvent) void { + if (!self.focused) return; + if (self.filter_enabled and key.key == .char and !key.modifiers.ctrl) { + // Add to filter + const c = key.key.char; + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch return; + self.filter_text.appendSlice(buf[0..len]) catch {}; + self.updateFilter() catch {}; + return; + } + + if (self.filter_enabled and key.key == .backspace) { + if (self.filter_text.items.len > 0) { + _ = self.filter_text.pop(); + self.updateFilter() catch {}; + } + return; + } + + switch (key.key) { + .up => self.cursorUp(), + .down => self.cursorDown(), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoFirst(), + .end => self.gotoLast(), + .space => if (self.multi_select) self.toggleSelection(), + .enter => self.selectCurrent(), + .char => |c| { + switch (c) { + 'j' => self.cursorDown(), + 'k' => self.cursorUp(), + 'g' => self.gotoFirst(), + 'G' => self.gotoLast(), + '/' => self.enableFilter(), + else => {}, + } + }, + .escape => if (self.filter_enabled) self.disableFilter(), + else => {}, + } + } + + fn visibleItems(self: *const Self) []const usize { + return self.filtered_indices.items; + } + + pub fn updateFilter(self: *Self) !void { + self.filtered_indices.clearRetainingCapacity(); + + if (self.filter_text.items.len == 0) { + for (0..self.items.items.len) |i| { + try self.filtered_indices.append(i); + } + } else { + var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); + defer scored.deinit(); + + for (self.items.items, 0..) |item, i| { + const s = fuzzy.scoreIgnoreCase(item.title, self.filter_text.items); + if (s > 0) try scored.append(.{ .index = i, .score = s }); + } + + 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); + + for (scored.items) |s| { + try self.filtered_indices.append(s.index); + } + } + + 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 ensureVisible(self: *Self) void { + if (self.cursor < self.y_offset) { + self.y_offset = self.cursor; + } else if (self.cursor >= self.y_offset + self.height) { + self.y_offset = self.cursor - self.height + 1; + } + } + + /// Render the list + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Filter line + if (self.filter_enabled) { + const filter_line = try std.fmt.allocPrint(allocator, "Filter: {s}", .{self.filter_text.items}); + const styled = try self.filter_style.render(allocator, filter_line); + try writer.writeAll(styled); + try writer.writeByte('\n'); + } + + const visible = self.visibleItems(); + + // Render visible items + var rendered: usize = 0; + while (rendered < self.height) : (rendered += 1) { + if (rendered > 0) try writer.writeByte('\n'); + + const idx = self.y_offset + rendered; + if (idx < visible.len) { + const item_idx = visible[idx]; + const item = self.items.items[item_idx]; + + // Cursor + if (idx == self.cursor) { + const cursor_styled = try self.cursor_style.render(allocator, self.cursor_symbol); + try writer.writeAll(cursor_styled); + } else { + for (0..self.cursor_symbol.len) |_| { + try writer.writeByte(' '); + } + } + + // Selection indicator (multi-select) + if (self.multi_select) { + if (self.selected.contains(item_idx)) { + const sel_styled = try self.selected_style.render(allocator, self.selected_symbol); + try writer.writeAll(sel_styled); + } else { + try writer.writeAll(self.unselected_symbol); + } + } + + // Item text + const item_rendered = if (idx == self.cursor) + try self.cursor_style.render(allocator, item.title) + else if (self.selected.contains(item_idx)) + try self.selected_style.render(allocator, item.title) + else + try self.item_style.render(allocator, item.title); + + try writer.writeAll(item_rendered); + + // Description + if (item.description.len > 0) { + try writer.writeAll(" - "); + try writer.writeAll(item.description); + } + } + } + + // Status bar + if (self.show_item_count or self.status_message != null) { + try writer.writeAll("\n"); + if (self.show_item_count) { + const count_str = try std.fmt.allocPrint(allocator, "{d}/{d} items", .{ + visible.len, + self.items.items.len, + }); + const count_styled = try self.filter_style.render(allocator, count_str); + try writer.writeAll(count_styled); + } + if (self.status_message) |msg| { + if (self.show_item_count) try writer.writeAll(" "); + try writer.writeAll(msg); + } + } + + return result.toOwnedSlice(); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig new file mode 100644 index 0000000..e29ef6b --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig @@ -0,0 +1,350 @@ +//! Markdown renderer for terminal output. +//! Converts a subset of markdown to ANSI-styled text. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const border_mod = @import("../style/border.zig"); + +pub const Markdown = struct { + // Styling + h1_style: style_mod.Style, + h2_style: style_mod.Style, + h3_style: style_mod.Style, + bold_style: style_mod.Style, + italic_style: style_mod.Style, + code_style: style_mod.Style, + code_block_style: style_mod.Style, + code_block_border: style_mod.Style, + link_style: style_mod.Style, + blockquote_style: style_mod.Style, + blockquote_bar: style_mod.Style, + list_bullet_style: style_mod.Style, + hr_style: style_mod.Style, + text_style: style_mod.Style, + + // Layout + width: u16, + hr_char: []const u8, + + pub fn init() Markdown { + return .{ + .h1_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.magenta); + s = s.underline(true); + s = s.inline_style(true); + break :blk s; + }, + .h2_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .h3_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + .bold_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .italic_style = blk: { + var s = style_mod.Style{}; + s = s.italic(true); + s = s.inline_style(true); + break :blk s; + }, + .code_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.bg(.fromRgb(40, 40, 40)); + s = s.inline_style(true); + break :blk s; + }, + .code_block_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + .code_block_border = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + .link_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.underline(true); + s = s.inline_style(true); + break :blk s; + }, + .blockquote_style = blk: { + var s = style_mod.Style{}; + s = s.italic(true); + s = s.fg(.gray(14)); + s = s.inline_style(true); + break :blk s; + }, + .blockquote_bar = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + .list_bullet_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .hr_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + .text_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .width = 80, + .hr_char = "─", + }; + } + + /// Render markdown text to styled terminal output. + pub fn render(self: *const Markdown, allocator: std.mem.Allocator, source: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + errdefer result.deinit(); + const writer = &result.writer; + + // Intermediate styled spans get freed in bulk at end of render. + var arena = std.heap.ArenaAllocator.init(allocator); + defer arena.deinit(); + const tmp = arena.allocator(); + + var lines_iter = std.mem.splitScalar(u8, source, '\n'); + var in_code_block = false; + var first_line = true; + + while (lines_iter.next()) |line| { + if (!first_line) try writer.writeByte('\n'); + first_line = false; + + // Code block toggle + if (std.mem.startsWith(u8, std.mem.trimStart(u8, line, " "), "```")) { + in_code_block = !in_code_block; + if (in_code_block) { + // Opening fence + const bar = try self.code_block_border.render(tmp, "┌"); + try writer.writeAll(bar); + const dash = try self.code_block_border.render(tmp, "─"); + for (0..@min(self.width - 2, 40)) |_| { + try writer.writeAll(dash); + } + const end = try self.code_block_border.render(tmp, "┐"); + try writer.writeAll(end); + } else { + // Closing fence + const bar = try self.code_block_border.render(tmp, "└"); + try writer.writeAll(bar); + const dash = try self.code_block_border.render(tmp, "─"); + for (0..@min(self.width - 2, 40)) |_| { + try writer.writeAll(dash); + } + const end = try self.code_block_border.render(tmp, "┘"); + try writer.writeAll(end); + } + continue; + } + + if (in_code_block) { + const bar = try self.code_block_border.render(tmp, "│ "); + try writer.writeAll(bar); + const styled = try self.code_block_style.render(tmp, line); + try writer.writeAll(styled); + continue; + } + + const trimmed = std.mem.trimStart(u8, line, " "); + + // Horizontal rule + if (trimmed.len >= 3 and isAllChar(trimmed, '-')) { + const dash = try self.hr_style.render(tmp, self.hr_char); + for (0..@min(self.width, 60)) |_| { + try writer.writeAll(dash); + } + continue; + } + + if (trimmed.len >= 3 and isAllChar(trimmed, '*') and !std.mem.startsWith(u8, trimmed, "**")) { + const dash = try self.hr_style.render(tmp, self.hr_char); + for (0..@min(self.width, 60)) |_| { + try writer.writeAll(dash); + } + continue; + } + + // Headers + if (std.mem.startsWith(u8, trimmed, "### ")) { + const content = trimmed[4..]; + const styled = try self.h3_style.render(tmp, content); + try writer.writeAll(styled); + continue; + } + if (std.mem.startsWith(u8, trimmed, "## ")) { + const content = trimmed[3..]; + const styled = try self.h2_style.render(tmp, content); + try writer.writeAll(styled); + continue; + } + if (std.mem.startsWith(u8, trimmed, "# ")) { + const content = trimmed[2..]; + const styled = try self.h1_style.render(tmp, content); + try writer.writeAll(styled); + continue; + } + + // Blockquote + if (std.mem.startsWith(u8, trimmed, "> ")) { + const content = trimmed[2..]; + const bar = try self.blockquote_bar.render(tmp, "│ "); + try writer.writeAll(bar); + const styled = try self.blockquote_style.render(tmp, content); + try writer.writeAll(styled); + continue; + } + + // Unordered list + if (std.mem.startsWith(u8, trimmed, "- ") or std.mem.startsWith(u8, trimmed, "* ")) { + const indent = line.len - trimmed.len; + for (0..indent) |_| try writer.writeByte(' '); + const bullet = try self.list_bullet_style.render(tmp, "• "); + try writer.writeAll(bullet); + const content = trimmed[2..]; + const styled = try self.renderInline(tmp, content); + try writer.writeAll(styled); + continue; + } + + // Ordered list (simple: "1. ", "2. ", etc.) + if (trimmed.len >= 3 and trimmed[0] >= '0' and trimmed[0] <= '9') { + if (std.mem.indexOf(u8, trimmed[0..@min(4, trimmed.len)], ". ")) |dot_pos| { + const indent = line.len - trimmed.len; + for (0..indent) |_| try writer.writeByte(' '); + const num = try self.list_bullet_style.render(tmp, trimmed[0 .. dot_pos + 2]); + try writer.writeAll(num); + const content = trimmed[dot_pos + 2 ..]; + const styled = try self.renderInline(tmp, content); + try writer.writeAll(styled); + continue; + } + } + + // Empty line + if (trimmed.len == 0) { + continue; + } + + // Regular paragraph with inline formatting + const styled = try self.renderInline(tmp, line); + try writer.writeAll(styled); + } + + return result.toOwnedSlice(); + } + + /// Render inline formatting: **bold**, *italic*, `code`, [links](url) + /// `allocator` should be a short-lived/arena allocator: intermediate styled + /// spans are leaked into it (freed in bulk when the arena is reset). + fn renderInline(self: *const Markdown, allocator: std.mem.Allocator, text: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + errdefer result.deinit(); + const writer = &result.writer; + + var i: usize = 0; + while (i < text.len) { + // Bold: **text** + if (i + 1 < text.len and text[i] == '*' and text[i + 1] == '*') { + if (std.mem.indexOf(u8, text[i + 2 ..], "**")) |end| { + const content = text[i + 2 .. i + 2 + end]; + const styled = try self.bold_style.render(allocator, content); + try writer.writeAll(styled); + i += 4 + end; + continue; + } + } + + // Italic: *text* + if (text[i] == '*' and (i + 1 >= text.len or text[i + 1] != '*')) { + if (std.mem.indexOfScalar(u8, text[i + 1 ..], '*')) |end| { + const content = text[i + 1 .. i + 1 + end]; + const styled = try self.italic_style.render(allocator, content); + try writer.writeAll(styled); + i += 2 + end; + continue; + } + } + + // Inline code: `code` + if (text[i] == '`') { + if (std.mem.indexOfScalar(u8, text[i + 1 ..], '`')) |end| { + const content = text[i + 1 .. i + 1 + end]; + const styled = try self.code_style.render(allocator, content); + try writer.writeAll(styled); + i += 2 + end; + continue; + } + } + + // Link: [text](url) + if (text[i] == '[') { + if (std.mem.indexOfScalar(u8, text[i + 1 ..], ']')) |text_end| { + const link_text = text[i + 1 .. i + 1 + text_end]; + const after_bracket = i + 2 + text_end; + if (after_bracket < text.len and text[after_bracket] == '(') { + if (std.mem.indexOfScalar(u8, text[after_bracket + 1 ..], ')')) |url_end| { + const url = text[after_bracket + 1 .. after_bracket + 1 + url_end]; + const styled_text = try self.link_style.render(allocator, link_text); + try writer.writeAll(styled_text); + var dim = style_mod.Style{}; + dim = dim.fg(.gray(10)); + dim = dim.inline_style(true); + const url_str = try std.fmt.allocPrint(allocator, " ({s})", .{url}); + const styled_url = try dim.render(allocator, url_str); + try writer.writeAll(styled_url); + i = after_bracket + 2 + url_end; + continue; + } + } + } + } + + // Regular character + try writer.writeByte(text[i]); + i += 1; + } + + return result.toOwnedSlice(); + } + + fn isAllChar(s: []const u8, c: u8) bool { + for (s) |ch| { + if (ch != c and ch != ' ') return false; + } + return true; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig new file mode 100644 index 0000000..ba34b01 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig @@ -0,0 +1,576 @@ +//! Menu bar component. +//! Horizontal menu bar with dropdown menus and keyboard navigation. + +const std = @import("std"); +const Writer = std.Io.Writer; +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"); + +pub fn MenuBar(comptime Action: type) type { + return struct { + const max_menus = 10; + const max_items = 20; + + // Menus + menus: [max_menus]?Menu, + menu_count: usize, + + // State + state: State, + active_menu: usize, + active_item: usize, + + // Result + selected_action: ?Action, + + // Styling + bar_style: style_mod.Style, + bar_item_style: style_mod.Style, + bar_active_style: style_mod.Style, + item_style: style_mod.Style, + item_active_style: style_mod.Style, + item_disabled_style: style_mod.Style, + separator_style: style_mod.Style, + shortcut_style: style_mod.Style, + border_chars: border_mod.BorderChars, + border_fg: Color, + + // Layout + gap: usize, + + const Self = @This(); + + pub const State = enum { + closed, + bar_focused, + dropdown_open, + }; + + pub const MenuItem = union(enum) { + action: ActionItem, + separator: void, + }; + + pub const ActionItem = struct { + label: []const u8, + shortcut_display: []const u8, + action: Action, + enabled: bool, + checked: ?bool, + }; + + pub const Menu = struct { + label: []const u8, + accelerator: ?u8, + items: [max_items]?MenuItem, + item_count: usize, + }; + + pub fn init() Self { + return .{ + .menus = [_]?Menu{null} ** max_menus, + .menu_count = 0, + .state = .closed, + .active_menu = 0, + .active_item = 0, + .selected_action = null, + .bar_style = blk: { + var s = style_mod.Style{}; + s = s.bg(.fromRgb(40, 40, 50)); + s = s.inline_style(true); + break :blk s; + }, + .bar_item_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(18)); + s = s.inline_style(true); + break :blk s; + }, + .bar_active_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.white); + s = s.bg(.fromRgb(60, 60, 80)); + s = s.inline_style(true); + break :blk s; + }, + .item_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(18)); + s = s.inline_style(true); + break :blk s; + }, + .item_active_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.white); + s = s.bg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .item_disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + .separator_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + .shortcut_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .border_chars = .normal, + .border_fg = .gray(14), + .gap = 2, + }; + } + + /// Add a menu to the bar. + pub fn addMenu(self: *Self, label: []const u8, accelerator: ?u8, items: []const MenuItem) void { + if (self.menu_count >= max_menus) return; + + var menu = Menu{ + .label = label, + .accelerator = accelerator, + .items = [_]?MenuItem{null} ** max_items, + .item_count = 0, + }; + + for (items) |item| { + if (menu.item_count >= max_items) break; + menu.items[menu.item_count] = item; + menu.item_count += 1; + } + + self.menus[self.menu_count] = menu; + self.menu_count += 1; + } + + /// Create an action menu item. + pub fn action(label: []const u8, shortcut: []const u8, act: Action) MenuItem { + return .{ .action = .{ + .label = label, + .shortcut_display = shortcut, + .action = act, + .enabled = true, + .checked = null, + } }; + } + + /// Create a disabled action menu item. + pub fn disabledAction(label: []const u8, shortcut: []const u8, act: Action) MenuItem { + return .{ .action = .{ + .label = label, + .shortcut_display = shortcut, + .action = act, + .enabled = false, + .checked = null, + } }; + } + + /// Create a checked action menu item. + pub fn checkedAction(label: []const u8, act: Action, is_checked: bool) MenuItem { + return .{ .action = .{ + .label = label, + .shortcut_display = "", + .action = act, + .enabled = true, + .checked = is_checked, + } }; + } + + /// Create a separator. + pub fn separator() MenuItem { + return .{ .separator = {} }; + } + + // ── State management ───────────────────────── + + pub fn isOpen(self: *const Self) bool { + return self.state != .closed; + } + + pub fn activate(self: *Self) void { + self.state = .bar_focused; + self.selected_action = null; + } + + pub fn deactivate(self: *Self) void { + self.state = .closed; + } + + pub fn getSelectedAction(self: *Self) ?Action { + const act = self.selected_action; + self.selected_action = null; + return act; + } + + // ── Input handling ─────────────────────────── + + pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { + // Check for Alt+letter accelerators + if (key.modifiers.alt and key.key == .char) { + const c = key.key.char; + for (self.menus[0..self.menu_count], 0..) |maybe_menu, i| { + if (maybe_menu) |menu| { + if (menu.accelerator) |acc| { + if (toLowerChar(c) == toLowerChar(acc)) { + self.active_menu = i; + self.active_item = 0; + self.state = .dropdown_open; + self.skipToNextEnabled(); + return true; + } + } + } + } + } + + switch (self.state) { + .closed => return false, + .bar_focused => return self.handleBarKey(key), + .dropdown_open => return self.handleDropdownKey(key), + } + } + + fn handleBarKey(self: *Self, key: keys.KeyEvent) bool { + switch (key.key) { + .left => { + if (self.active_menu > 0) { + self.active_menu -= 1; + } else if (self.menu_count > 0) { + self.active_menu = self.menu_count - 1; + } + return true; + }, + .right => { + if (self.active_menu + 1 < self.menu_count) { + self.active_menu += 1; + } else { + self.active_menu = 0; + } + return true; + }, + .down, .enter => { + self.state = .dropdown_open; + self.active_item = 0; + self.skipToNextEnabled(); + return true; + }, + .escape => { + self.state = .closed; + return true; + }, + else => return false, + } + } + + fn handleDropdownKey(self: *Self, key: keys.KeyEvent) bool { + switch (key.key) { + .up => { + self.moveCursorUp(); + return true; + }, + .down => { + self.moveCursorDown(); + return true; + }, + .left => { + if (self.active_menu > 0) { + self.active_menu -= 1; + } else if (self.menu_count > 0) { + self.active_menu = self.menu_count - 1; + } + self.active_item = 0; + self.skipToNextEnabled(); + return true; + }, + .right => { + if (self.active_menu + 1 < self.menu_count) { + self.active_menu += 1; + } else { + self.active_menu = 0; + } + self.active_item = 0; + self.skipToNextEnabled(); + return true; + }, + .enter => { + self.selectCurrentItem(); + return true; + }, + .escape => { + self.state = .bar_focused; + return true; + }, + else => return false, + } + } + + fn moveCursorUp(self: *Self) void { + const menu = self.menus[self.active_menu] orelse return; + if (menu.item_count == 0) return; + + var pos = self.active_item; + var attempts: usize = 0; + while (attempts < menu.item_count) : (attempts += 1) { + if (pos == 0) { + pos = menu.item_count - 1; + } else { + pos -= 1; + } + if (self.isSelectableItem(menu.items[pos])) { + self.active_item = pos; + return; + } + } + } + + fn moveCursorDown(self: *Self) void { + const menu = self.menus[self.active_menu] orelse return; + if (menu.item_count == 0) return; + + var pos = self.active_item; + var attempts: usize = 0; + while (attempts < menu.item_count) : (attempts += 1) { + pos = if (pos + 1 < menu.item_count) pos + 1 else 0; + if (self.isSelectableItem(menu.items[pos])) { + self.active_item = pos; + return; + } + } + } + + fn skipToNextEnabled(self: *Self) void { + const menu = self.menus[self.active_menu] orelse return; + if (menu.item_count == 0) return; + + if (self.isSelectableItem(menu.items[self.active_item])) return; + self.moveCursorDown(); + } + + fn isSelectableItem(_: *const Self, maybe_item: ?MenuItem) bool { + const item = maybe_item orelse return false; + return switch (item) { + .action => |a| a.enabled, + .separator => false, + }; + } + + fn selectCurrentItem(self: *Self) void { + const menu = self.menus[self.active_menu] orelse return; + if (self.active_item >= menu.item_count) return; + + const item = menu.items[self.active_item] orelse return; + switch (item) { + .action => |a| { + if (a.enabled) { + self.selected_action = a.action; + self.state = .closed; + } + }, + .separator => {}, + } + } + + fn toLowerChar(c: u21) u21 { + return if (c >= 'A' and c <= 'Z') c + 32 else c; + } + + // ── Rendering ─────────────────────────────── + + pub fn view(self: *const Self, allocator: std.mem.Allocator, term_width: usize) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Render menu bar + var bar_content: Writer.Allocating = .init(allocator); + const bar_writer = &bar_content.writer; + + try bar_writer.writeAll(" "); + + for (self.menus[0..self.menu_count], 0..) |maybe_menu, i| { + const menu = maybe_menu orelse continue; + + if (i > 0) { + for (0..self.gap) |_| try bar_writer.writeByte(' '); + } + + const is_active = (self.state != .closed and self.active_menu == i); + const menu_style = if (is_active) self.bar_active_style else self.bar_item_style; + const padded = try std.fmt.allocPrint(allocator, " {s} ", .{menu.label}); + const styled = try menu_style.render(allocator, padded); + try bar_writer.writeAll(styled); + } + + // Pad bar to terminal width + const bar_text = try bar_content.toOwnedSlice(); + const bar_width = measure.width(bar_text); + try writer.writeAll(bar_text); + if (bar_width < term_width) { + const pad_text = try allocator.alloc(u8, term_width - bar_width); + @memset(pad_text, ' '); + const styled_pad = try self.bar_style.render(allocator, pad_text); + try writer.writeAll(styled_pad); + } + + // Render dropdown if open + if (self.state == .dropdown_open) { + if (self.menus[self.active_menu]) |menu| { + const dropdown = try self.renderDropdown(allocator, menu); + try writer.writeByte('\n'); + try writer.writeAll(dropdown); + } + } + + return result.toOwnedSlice(); + } + + fn renderDropdown(self: *const Self, allocator: std.mem.Allocator, menu: Menu) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const w = &result.writer; + + // Calculate width + var max_label_width: usize = 0; + var max_shortcut_width: usize = 0; + for (menu.items[0..menu.item_count]) |maybe_item| { + const item = maybe_item orelse continue; + switch (item) { + .action => |a| { + const lw = measure.width(a.label) + if (a.checked != null) @as(usize, 2) else 0; + if (lw > max_label_width) max_label_width = lw; + const sw = measure.width(a.shortcut_display); + if (sw > max_shortcut_width) max_shortcut_width = sw; + }, + .separator => {}, + } + } + + const inner_width = max_label_width + max_shortcut_width + 4; // padding + gap + + // Calculate x offset for dropdown + var x_offset: usize = 1; + for (self.menus[0..self.active_menu]) |maybe_menu| { + if (maybe_menu) |m| { + x_offset += measure.width(m.label) + 2 + self.gap; + } + } + // Indent dropdown to align with menu item + for (0..x_offset) |_| try w.writeByte(' '); + + // Top border + try self.writeBorder(w, allocator, inner_width, .top); + try w.writeByte('\n'); + + // Items + for (menu.items[0..menu.item_count], 0..) |maybe_item, i| { + const item = maybe_item orelse continue; + + for (0..x_offset) |_| try w.writeByte(' '); + + switch (item) { + .separator => { + try self.writeBorder(w, allocator, inner_width, .middle); + }, + .action => |a| { + try self.writeBorderChar(w, allocator, .left); + + const is_active = (i == self.active_item); + const s = if (!a.enabled) self.item_disabled_style else if (is_active) self.item_active_style else self.item_style; + + // Build line content + var line: Writer.Allocating = .init(allocator); + const lw = &line.writer; + + try lw.writeByte(' '); + + // Check mark + if (a.checked) |checked| { + if (checked) { + try lw.writeAll("\u{2713} "); + } else { + try lw.writeAll(" "); + } + } + + try lw.writeAll(a.label); + + // Pad between label and shortcut + const label_width = measure.width(a.label) + if (a.checked != null) @as(usize, 2) else @as(usize, 0); + const gap_needed = inner_width -| label_width -| measure.width(a.shortcut_display) -| 2; + for (0..gap_needed) |_| try lw.writeByte(' '); + + if (a.shortcut_display.len > 0) { + try lw.writeAll(a.shortcut_display); + } + + try lw.writeByte(' '); + + const line_text = try line.toOwnedSlice(); + const styled = try s.render(allocator, line_text); + try w.writeAll(styled); + + try self.writeBorderChar(w, allocator, .right); + }, + } + + try w.writeByte('\n'); + } + + // Bottom border + for (0..x_offset) |_| try w.writeByte(' '); + try self.writeBorder(w, allocator, inner_width, .bottom); + + return result.toOwnedSlice(); + } + + const BorderPos = enum { top, middle, bottom }; + const BorderSide = enum { left, right }; + + fn writeBorder(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { + var bs = style_mod.Style{}; + bs = bs.fg(self.border_fg); + bs = bs.inline_style(true); + + const bc = self.border_chars; + const cl = switch (pos) { + .top => bc.top_left, + .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, + .bottom => bc.bottom_left, + }; + const cr = switch (pos) { + .top => bc.top_right, + .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, + .bottom => bc.bottom_right, + }; + + try writer.writeAll(try bs.render(allocator, cl)); + for (0..width) |_| { + try writer.writeAll(try bs.render(allocator, bc.horizontal)); + } + try writer.writeAll(try bs.render(allocator, cr)); + } + + fn writeBorderChar(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { + var bs = style_mod.Style{}; + bs = bs.fg(self.border_fg); + bs = bs.inline_style(true); + const char = switch (side) { + .left => self.border_chars.vertical, + .right => self.border_chars.vertical, + }; + try writer.writeAll(try bs.render(allocator, char)); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig new file mode 100644 index 0000000..e8a3a23 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig @@ -0,0 +1,761 @@ +//! Modal/Popup/Overlay component. +//! State-managed dialog that captures focus, renders on top, and returns a result. +//! Supports confirmation dialogs, input prompts, selection menus, error popups, +//! and fully custom content. +//! +//! ## Quick Start +//! +//! ```zig +//! // Create an info modal +//! var modal = Modal.info("Notice", "Operation completed successfully."); +//! modal.show(); +//! +//! // In your update function: +//! modal.handleKey(key_event); +//! if (modal.getResult()) |res| { +//! switch (res) { +//! .button_pressed => |idx| { /* button at idx was pressed */ }, +//! .dismissed => { /* user pressed Escape */ }, +//! } +//! } +//! +//! // In your view function: +//! if (modal.isVisible()) { +//! return modal.viewWithBackdrop(allocator, ctx.width, ctx.height); +//! } +//! ``` +//! +//! ## Presets +//! +//! - `Modal.info(title, body)` — informational dialog with OK button (cyan border) +//! - `Modal.confirm(title, body)` — yes/no confirmation (yellow border) +//! - `Modal.warning(title, body)` — warning with OK button (yellow border) +//! - `Modal.err(title, body)` — error with OK button (red border) +//! - `Modal.init()` — blank modal for full custom configuration +//! +//! ## Focus Protocol +//! +//! Modal satisfies the focusable protocol (`focused`, `focus()`, `blur()`) and +//! can be registered with a `FocusGroup`. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const border_mod = @import("../style/border.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); +const place = @import("../layout/place.zig"); + +const max_buttons = 8; + +pub const Modal = struct { + // ── State ────────────────────────────────────────────────────────── + + visible: bool = false, + focused: bool = false, + result: ?Result = null, + + // ── Content ──────────────────────────────────────────────────────── + + title: []const u8 = "", + body: []const u8 = "", + footer: ?[]const u8 = null, + + // ── Buttons ──────────────────────────────────────────────────────── + + buttons: [max_buttons]?Button = [_]?Button{null} ** max_buttons, + button_count: usize = 0, + selected_button: usize = 0, + + // ── Layout ───────────────────────────────────────────────────────── + + width: Size = .{ .percent = 0.5 }, + height: Size = .auto, + h_position: f32 = 0.5, + v_position: f32 = 0.5, + padding: Padding = .{ .top = 1, .right = 2, .bottom = 1, .left = 2 }, + button_align: ButtonAlign = .right, + + // ── Behavior ─────────────────────────────────────────────────────── + + close_on_escape: bool = true, + + // ── Styling ──────────────────────────────────────────────────────── + + border_chars: border_mod.BorderChars = .rounded, + border_fg: Color = .gray(18), + content_bg: Color = .none, + title_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white }), + body_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(20) }), + footer_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(12), .italic_v = true }), + button_active_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white, .bg_color = .cyan }), + button_inactive_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(14) }), + backdrop: ?Backdrop = null, + + // ── Types ────────────────────────────────────────────────────────── + + pub const Result = union(enum) { + button_pressed: usize, + dismissed: void, + }; + + pub const Button = struct { + label: []const u8, + shortcut: ?keys.Key = null, + }; + + pub const Size = union(enum) { + fixed: u16, + percent: f32, + auto: void, + }; + + pub const Padding = struct { + top: u16 = 0, + right: u16 = 0, + bottom: u16 = 0, + left: u16 = 0, + + pub fn all(n: u16) Padding { + return .{ .top = n, .right = n, .bottom = n, .left = n }; + } + + pub fn symmetric(vert: u16, horiz: u16) Padding { + return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; + } + }; + + pub const ButtonAlign = enum { left, center, right }; + + pub const Backdrop = struct { + /// Fill character (UTF-8 string, e.g. " ", "░", "▒", "▓", "█"). + char: []const u8 = " ", + /// Style applied to the backdrop fill. + style: style_mod.Style = makeStyle(.{ .bg_color = .gray(3) }), + + /// Dark semi-transparent backdrop (default). + pub const dark = Backdrop{}; + + /// Slightly lighter backdrop. + pub const medium = Backdrop{ + .style = makeStyle(.{ .bg_color = .gray(5) }), + }; + + /// Light backdrop. + pub const light = Backdrop{ + .style = makeStyle(.{ .bg_color = .gray(8) }), + }; + + /// Clear backdrop — uses the terminal's default background color. + pub const clear = Backdrop{ + .style = makeStyle(.{}), + }; + + /// Light shade fill character (░). + pub const shade_light = Backdrop{ + .char = "░", + .style = makeStyle(.{ .fg_color = .gray(5) }), + }; + + /// Medium shade fill character (▒). + pub const shade_medium = Backdrop{ + .char = "▒", + .style = makeStyle(.{ .fg_color = .gray(5) }), + }; + + /// Dense shade fill character (▓). + pub const shade_dense = Backdrop{ + .char = "▓", + .style = makeStyle(.{ .fg_color = .gray(4) }), + }; + + /// Create a solid-color backdrop. + pub fn solid(bg_color: Color) Backdrop { + return .{ .style = makeStyle(.{ .bg_color = bg_color }) }; + } + + /// Create a backdrop with a custom fill character and foreground color. + pub fn custom(char_str: []const u8, fg_color: Color, bg_color: Color) Backdrop { + return .{ + .char = char_str, + .style = makeStyle(.{ .fg_color = fg_color, .bg_color = bg_color }), + }; + } + }; + + // ── Preset Constructors ──────────────────────────────────────────── + + /// Informational dialog with a single OK button and cyan accent. + pub fn info(title: []const u8, body: []const u8) Modal { + var m: Modal = .{ + .title = title, + .body = body, + .border_fg = .cyan, + .title_style = makeStyle(.{ .bold_v = true, .fg_color = .cyan }), + }; + m.addButton("OK", .enter); + return m; + } + + /// Yes/No confirmation dialog with yellow accent. + pub fn confirm(title: []const u8, body: []const u8) Modal { + var m: Modal = .{ + .title = title, + .body = body, + .border_fg = .yellow, + .title_style = makeStyle(.{ .bold_v = true, .fg_color = .yellow }), + }; + m.addButton("Yes", .{ .char = 'y' }); + m.addButton("No", .{ .char = 'n' }); + return m; + } + + /// Warning dialog with a single OK button and yellow accent. + pub fn warning(title: []const u8, body: []const u8) Modal { + var m: Modal = .{ + .title = title, + .body = body, + .border_fg = .yellow, + .title_style = makeStyle(.{ .bold_v = true, .fg_color = .yellow }), + }; + m.addButton("OK", .enter); + return m; + } + + /// Error dialog with a single OK button and red accent. + pub fn err(title: []const u8, body: []const u8) Modal { + var m: Modal = .{ + .title = title, + .body = body, + .border_fg = .red, + .title_style = makeStyle(.{ .bold_v = true, .fg_color = .red }), + }; + m.addButton("OK", .enter); + return m; + } + + /// Blank modal with no preset content — configure everything yourself. + pub fn init() Modal { + return .{}; + } + + // ── Button Management ────────────────────────────────────────────── + + /// Add a button with an optional keyboard shortcut. + pub fn addButton(self: *Modal, label: []const u8, shortcut: ?keys.Key) void { + if (self.button_count >= max_buttons) return; + self.buttons[self.button_count] = .{ + .label = label, + .shortcut = shortcut, + }; + self.button_count += 1; + } + + /// Remove all buttons. + pub fn clearButtons(self: *Modal) void { + self.buttons = [_]?Button{null} ** max_buttons; + self.button_count = 0; + self.selected_button = 0; + } + + // ── State Management ─────────────────────────────────────────────── + + /// Show the modal and reset its result. + pub fn show(self: *Modal) void { + self.visible = true; + self.focused = true; + self.result = null; + self.selected_button = 0; + } + + /// Hide the modal without setting a result. + pub fn hide(self: *Modal) void { + self.visible = false; + self.focused = false; + } + + pub fn isVisible(self: *const Modal) bool { + return self.visible; + } + + /// Returns the result once the modal has been closed. + pub fn getResult(self: *const Modal) ?Result { + return self.result; + } + + /// Reset visibility, focus, and result. + pub fn reset(self: *Modal) void { + self.visible = false; + self.focused = false; + self.result = null; + self.selected_button = 0; + } + + // ── Focusable Protocol ───────────────────────────────────────────── + + pub fn focus(self: *Modal) void { + self.focused = true; + } + + pub fn blur(self: *Modal) void { + self.focused = false; + } + + // ── Input Handling ───────────────────────────────────────────────── + + /// Process a key event. Only acts when visible and focused. + pub fn handleKey(self: *Modal, key: keys.KeyEvent) void { + if (!self.visible or !self.focused) return; + + // Check button shortcuts first + for (self.buttons[0..self.button_count], 0..) |maybe_btn, i| { + if (maybe_btn) |btn| { + if (btn.shortcut) |sc| { + if (sc.eql(key.key)) { + self.result = .{ .button_pressed = i }; + self.visible = false; + return; + } + } + } + } + + switch (key.key) { + .escape => { + if (self.close_on_escape) { + self.result = .dismissed; + self.visible = false; + } + }, + .enter => { + if (self.button_count > 0) { + self.result = .{ .button_pressed = self.selected_button }; + self.visible = false; + } + }, + .tab => { + if (self.button_count > 1) { + if (key.modifiers.shift) { + self.selected_button = if (self.selected_button > 0) + self.selected_button - 1 + else + self.button_count - 1; + } else { + self.selected_button = if (self.selected_button + 1 < self.button_count) + self.selected_button + 1 + else + 0; + } + } + }, + .left => { + if (self.button_count > 1 and self.selected_button > 0) { + self.selected_button -= 1; + } + }, + .right => { + if (self.button_count > 1 and self.selected_button + 1 < self.button_count) { + self.selected_button += 1; + } + }, + else => {}, + } + } + + // ── Rendering ────────────────────────────────────────────────────── + + /// Render the modal box centered on a transparent (space-filled) canvas. + /// Returns empty string if not visible. + pub fn view(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { + if (!self.visible) return try allocator.dupe(u8, ""); + + const box = try self.renderBox(allocator, term_width, term_height); + return try place.placeFloat(allocator, term_width, term_height, self.h_position, self.v_position, box); + } + + /// Render the modal with a styled backdrop filling the entire terminal. + /// Returns empty string if not visible. + pub fn viewWithBackdrop(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { + if (!self.visible) return try allocator.dupe(u8, ""); + + const bd = self.backdrop orelse Backdrop{}; + const box = try self.renderBox(allocator, term_width, term_height); + const box_w = measure.maxLineWidth(box); + const box_h = measure.height(box); + + // Position + const h_space = if (term_width > box_w) term_width - box_w else 0; + const v_space = if (term_height > box_h) term_height - box_h else 0; + const modal_x: usize = @intFromFloat(@as(f32, @floatFromInt(h_space)) * clamp01(self.h_position)); + const modal_y: usize = @intFromFloat(@as(f32, @floatFromInt(v_space)) * clamp01(self.v_position)); + + // Collect modal lines + var modal_lines_list = std.array_list.Managed([]const u8).init(allocator); + defer modal_lines_list.deinit(); + var box_iter = std.mem.splitScalar(u8, box, '\n'); + while (box_iter.next()) |line| try modal_lines_list.append(line); + const modal_lines = modal_lines_list.items; + + // Build full-screen output + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (0..term_height) |row| { + if (row > 0) try writer.writeByte('\n'); + + const in_modal = row >= modal_y and row < modal_y + box_h; + if (in_modal) { + const mline_idx = row - modal_y; + if (mline_idx < modal_lines.len) { + // Left backdrop + if (modal_x > 0) { + try writer.writeAll(try renderBackdropSegment(allocator, bd, modal_x)); + } + // Modal line + try writer.writeAll(modal_lines[mline_idx]); + // Right backdrop + const mline_w = measure.width(modal_lines[mline_idx]); + const right_start = modal_x + mline_w; + if (right_start < term_width) { + try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width - right_start)); + } + } else { + try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width)); + } + } else { + try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width)); + } + } + + return result.toOwnedSlice(); + } + + /// Render just the modal box (no positioning or backdrop). + pub fn renderBox(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { + const bc = self.border_chars; + const box_w = self.computeWidth(term_width); + const inner_w: usize = if (box_w >= 2) box_w - 2 else 0; + const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); + const content_w: usize = if (inner_w >= pad_h) inner_w - pad_h else 0; + + // Compute height constraints + const box_h = self.computeHeight(term_height, inner_w); + const extras = self.computeExtras(); + const max_body_lines: usize = if (box_h > extras) box_h - extras else 0; + + // Inline styles for border and padding segments + var bdr_s = style_mod.Style{}; + bdr_s = bdr_s.fg(self.border_fg).inline_style(true); + if (!self.content_bg.isNone()) bdr_s = bdr_s.bg(self.content_bg); + + var pad_s = style_mod.Style{}; + pad_s = pad_s.inline_style(true); + if (!self.content_bg.isNone()) pad_s = pad_s.bg(self.content_bg); + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // ── Top border ── + try writer.writeAll(try bdr_s.render(allocator, bc.top_left)); + if (self.title.len > 0) { + const title_w = measure.width(self.title); + // top + space + title + space + remaining top chars + const used: usize = 3 + title_w; // 1 top + 1 space + title + 1 space + const remaining: usize = if (inner_w > used) inner_w - used else 0; + + try writer.writeAll(try bdr_s.render(allocator, bc.horizontal)); + try writer.writeAll(try bdr_s.render(allocator, " ")); + try writer.writeAll(try self.title_style.inline_style(true).render(allocator, self.title)); + try writer.writeAll(try bdr_s.render(allocator, " ")); + try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, remaining)); + } else { + try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); + } + try writer.writeAll(try bdr_s.render(allocator, bc.top_right)); + + // Helpers for inner lines + const styled_left = try bdr_s.render(allocator, bc.vertical); + const styled_right = try bdr_s.render(allocator, bc.vertical); + + // ── Top padding ── + for (0..self.padding.top) |_| { + try writer.writeByte('\n'); + try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + } + + // ── Body lines ── + var body_iter = std.mem.splitScalar(u8, self.body, '\n'); + var body_line_count: usize = 0; + while (body_iter.next()) |line| { + if (body_line_count >= max_body_lines) break; + body_line_count += 1; + + try writer.writeByte('\n'); + try writer.writeAll(styled_left); + + // Left padding + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); + + // Body text + var merged_body = self.body_style.inline_style(true); + if (!self.content_bg.isNone() and merged_body.background.isNone()) { + merged_body = merged_body.bg(self.content_bg); + } + try writer.writeAll(try merged_body.render(allocator, line)); + + // Right fill + const line_w = measure.width(line); + const fill: usize = if (content_w > line_w) content_w - line_w else 0; + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); + + try writer.writeAll(styled_right); + } + + // Pad body if fixed/percent height has more room + while (body_line_count < max_body_lines) : (body_line_count += 1) { + try writer.writeByte('\n'); + try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + } + + // ── Footer ── + if (self.footer) |footer_text| { + // Separator line + try writer.writeByte('\n'); + try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + + try writer.writeByte('\n'); + try writer.writeAll(styled_left); + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); + + var merged_footer = self.footer_style.inline_style(true); + if (!self.content_bg.isNone() and merged_footer.background.isNone()) { + merged_footer = merged_footer.bg(self.content_bg); + } + try writer.writeAll(try merged_footer.render(allocator, footer_text)); + + const fw = measure.width(footer_text); + const fill: usize = if (content_w > fw) content_w - fw else 0; + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); + try writer.writeAll(styled_right); + } + + // ── Buttons ── + if (self.button_count > 0) { + // Separator + try writer.writeByte('\n'); + try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + + // Render button row content + var btn_buf: Writer.Allocating = .init(allocator); + const btn_writer = &btn_buf.writer; + + for (self.buttons[0..self.button_count], 0..) |maybe_btn, i| { + if (maybe_btn) |btn| { + if (i > 0) { + try btn_writer.writeAll(try pad_s.render(allocator, " ")); + } + const label = try std.fmt.allocPrint(allocator, " {s} ", .{btn.label}); + var btn_style = if (i == self.selected_button) self.button_active_style else self.button_inactive_style; + btn_style = btn_style.inline_style(true); + if (!self.content_bg.isNone() and i != self.selected_button and btn_style.background.isNone()) { + btn_style = btn_style.bg(self.content_bg); + } + try btn_writer.writeAll(try btn_style.render(allocator, label)); + } + } + const btn_row = try btn_buf.toOwnedSlice(); + const btn_row_w = measure.width(btn_row); + + try writer.writeByte('\n'); + try writer.writeAll(styled_left); + + // Align buttons within inner_w + const left_spaces: usize = switch (self.button_align) { + .left => self.padding.left, + .center => if (inner_w > btn_row_w) (inner_w - btn_row_w) / 2 else 0, + .right => if (inner_w > btn_row_w + self.padding.right) + inner_w - btn_row_w - self.padding.right + else + 0, + }; + const right_spaces: usize = if (inner_w > left_spaces + btn_row_w) + inner_w - left_spaces - btn_row_w + else + 0; + + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, left_spaces))); + try writer.writeAll(btn_row); + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, right_spaces))); + + try writer.writeAll(styled_right); + } + + // ── Bottom padding ── + for (0..self.padding.bottom) |_| { + try writer.writeByte('\n'); + try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + } + + // ── Bottom border ── + try writer.writeByte('\n'); + try writer.writeAll(try bdr_s.render(allocator, bc.bottom_left)); + try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); + try writer.writeAll(try bdr_s.render(allocator, bc.bottom_right)); + + return result.toOwnedSlice(); + } + + // ── Private Helpers ──────────────────────────────────────────────── + + fn writeEmptyInnerLine( + self: *const Modal, + allocator: std.mem.Allocator, + writer: *Writer, + styled_left: []const u8, + styled_right: []const u8, + pad_s: style_mod.Style, + inner_w: usize, + ) !void { + _ = self; + try writer.writeAll(styled_left); + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, inner_w))); + try writer.writeAll(styled_right); + } + + fn computeWidth(self: *const Modal, term_width: usize) usize { + return switch (self.width) { + .fixed => |w| @min(@as(usize, w), term_width), + .percent => |p| @intFromFloat(@as(f32, @floatFromInt(term_width)) * clamp01(p)), + .auto => blk: { + const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); + var max_inner: usize = 0; + + // Title (in border): needs title_w + 4 + if (self.title.len > 0) { + max_inner = @max(max_inner, measure.width(self.title) + 4); + } + + // Content-area items need content_w + padding_h + var max_content: usize = 0; + + var body_iter = std.mem.splitScalar(u8, self.body, '\n'); + while (body_iter.next()) |line| { + max_content = @max(max_content, measure.width(line)); + } + + if (self.footer) |ft| { + max_content = @max(max_content, measure.width(ft)); + } + + var btn_w: usize = 0; + for (self.buttons[0..self.button_count]) |maybe_btn| { + if (maybe_btn) |btn| { + if (btn_w > 0) btn_w += 2; // gap + btn_w += measure.width(btn.label) + 2; // " Label " + } + } + max_content = @max(max_content, btn_w); + + max_inner = @max(max_inner, max_content + pad_h); + break :blk @min(max_inner + 2, term_width); // +2 for borders + }, + }; + } + + fn computeHeight(self: *const Modal, term_height: usize, inner_w: usize) usize { + _ = inner_w; + return switch (self.height) { + .fixed => |h| @min(@as(usize, h), term_height), + .percent => |p| @intFromFloat(@as(f32, @floatFromInt(term_height)) * clamp01(p)), + .auto => blk: { + var h: usize = 2; // top + bottom border + h += self.padding.top; + h += self.padding.bottom; + + // Body lines + var body_lines: usize = 0; + var iter = std.mem.splitScalar(u8, self.body, '\n'); + while (iter.next()) |_| body_lines += 1; + h += body_lines; + + if (self.footer != null) h += 2; // separator + footer + if (self.button_count > 0) h += 2; // separator + button row + + break :blk @min(h, term_height); + }, + }; + } + + fn computeExtras(self: *const Modal) usize { + var e: usize = 2; // borders + e += self.padding.top; + e += self.padding.bottom; + if (self.footer != null) e += 2; + if (self.button_count > 0) e += 2; + return e; + } + + fn renderBackdropSegment(allocator: std.mem.Allocator, bd: Backdrop, count: usize) ![]const u8 { + if (count == 0) return try allocator.dupe(u8, ""); + const ch = bd.char; + if (ch.len == 0) return try allocator.dupe(u8, ""); + const buf = try allocator.alloc(u8, ch.len * count); + for (0..count) |i| { + @memcpy(buf[i * ch.len ..][0..ch.len], ch); + } + return try bd.style.inline_style(true).render(allocator, buf); + } + + fn repeatStr(allocator: std.mem.Allocator, s: style_mod.Style, str: []const u8, count: usize) ![]const u8 { + if (count == 0 or str.len == 0) return try allocator.dupe(u8, ""); + // Build repeated plain string, then style once + const buf = try allocator.alloc(u8, str.len * count); + for (0..count) |i| { + @memcpy(buf[i * str.len ..][0..str.len], str); + } + return try s.render(allocator, buf); + } + + fn nSpaces(allocator: std.mem.Allocator, count: anytype) ![]const u8 { + const n: usize = switch (@typeInfo(@TypeOf(count))) { + .int, .comptime_int => @intCast(count), + else => count, + }; + if (n == 0) return try allocator.dupe(u8, ""); + const buf = try allocator.alloc(u8, n); + @memset(buf, ' '); + return buf; + } + + fn nChars(allocator: std.mem.Allocator, ch: u8, count: usize) ![]const u8 { + if (count == 0) return try allocator.dupe(u8, ""); + const buf = try allocator.alloc(u8, count); + @memset(buf, ch); + return buf; + } + + fn clamp01(v: f32) f32 { + return @max(0.0, @min(1.0, v)); + } + + // Comptime style builder to avoid runtime block initialization + const StyleOpts = struct { + bold_v: ?bool = null, + dim_v: ?bool = null, + italic_v: ?bool = null, + fg_color: Color = .none, + bg_color: Color = .none, + }; + + fn makeStyle(opts: StyleOpts) style_mod.Style { + var s = style_mod.Style{}; + if (opts.bold_v) |v| s.bold_attr = v; + if (opts.dim_v) |v| s.dim_attr = v; + if (opts.italic_v) |v| s.italic_attr = v; + if (!opts.fg_color.isNone()) s.foreground = opts.fg_color; + if (!opts.bg_color.isNone()) s.background = opts.bg_color; + s.inline_mode = true; + return s; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig new file mode 100644 index 0000000..f557161 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig @@ -0,0 +1,139 @@ +//! Notification/Toast component for timed messages. +//! Displays auto-dismissing messages with severity levels. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Level = enum { + info, + success, + warning, + err, +}; + +pub const ToastMessage = struct { + text: []const u8, + level: Level, + created_ns: u64, + duration_ms: u64, +}; + +pub const Notification = struct { + allocator: std.mem.Allocator, + messages: std.array_list.Managed(ToastMessage), + max_visible: usize, + + // Styling per level + info_style: style_mod.Style, + success_style: style_mod.Style, + warning_style: style_mod.Style, + err_style: style_mod.Style, + + pub fn init(allocator: std.mem.Allocator) Notification { + return .{ + .allocator = allocator, + .messages = std.array_list.Managed(ToastMessage).init(allocator), + .max_visible = 5, + .info_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .success_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + .warning_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .err_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *Notification) void { + self.messages.deinit(); + } + + /// Push a new notification + pub fn push(self: *Notification, 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, + }); + } + + /// Remove expired notifications + pub fn update(self: *Notification, current_ns: u64) void { + var i: usize = 0; + while (i < self.messages.items.len) { + const msg = self.messages.items[i]; + 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 Notification) bool { + return self.messages.items.len > 0; + } + + /// Render notifications + pub fn view(self: *const Notification, allocator: std.mem.Allocator) ![]const u8 { + if (self.messages.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const visible_count = @min(self.messages.items.len, self.max_visible); + const start = if (self.messages.items.len > self.max_visible) + self.messages.items.len - self.max_visible + else + 0; + + for (start..start + visible_count) |i| { + if (i > start) try writer.writeAll("\n"); + + const msg = self.messages.items[i]; + const icon = switch (msg.level) { + .info => "i ", + .success => "* ", + .warning => "! ", + .err => "x ", + }; + const active_style = switch (msg.level) { + .info => self.info_style, + .success => self.success_style, + .warning => self.warning_style, + .err => self.err_style, + }; + + const styled_icon = try active_style.render(allocator, icon); + try writer.writeAll(styled_icon); + const styled_text = try active_style.render(allocator, msg.text); + try writer.writeAll(styled_text); + } + + return result.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig new file mode 100644 index 0000000..deefad3 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig @@ -0,0 +1,226 @@ +//! Paginator component for pagination controls. +//! Displays page indicators and handles navigation. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Paginator = struct { + // State + current_page: usize, + total_pages: usize, + per_page: usize, + total_items: usize, + + // Appearance + paginator_type: Type, + active_dot: []const u8, + inactive_dot: []const u8, + + // Styling + active_style: style_mod.Style, + inactive_style: style_mod.Style, + + pub const Type = enum { + dots, + arabic, // 1/5, 2/5, etc. + compact, // [1] 2 3 4 5 + }; + + pub fn init() Paginator { + return .{ + .current_page = 0, + .total_pages = 1, + .per_page = 10, + .total_items = 0, + .paginator_type = .dots, + .active_dot = "●", + .inactive_dot = "○", + .active_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .inactive_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + /// Set total items and calculate pages + pub fn setTotalItems(self: *Paginator, total: usize) void { + self.total_items = total; + self.total_pages = if (total == 0) 1 else (total + self.per_page - 1) / self.per_page; + self.current_page = @min(self.current_page, self.total_pages -| 1); + } + + /// Set items per page + pub fn setPerPage(self: *Paginator, per_page: usize) void { + self.per_page = @max(1, per_page); + self.setTotalItems(self.total_items); + } + + /// Set total pages directly + pub fn setTotalPages(self: *Paginator, pages: usize) void { + self.total_pages = @max(1, pages); + self.current_page = @min(self.current_page, self.total_pages - 1); + } + + /// Go to specific page + pub fn gotoPage(self: *Paginator, page: usize) void { + self.current_page = @min(page, self.total_pages -| 1); + } + + /// Go to next page + pub fn nextPage(self: *Paginator) void { + if (self.current_page < self.total_pages - 1) { + self.current_page += 1; + } + } + + /// Go to previous page + pub fn prevPage(self: *Paginator) void { + if (self.current_page > 0) { + self.current_page -= 1; + } + } + + /// Go to first page + pub fn firstPage(self: *Paginator) void { + self.current_page = 0; + } + + /// Go to last page + pub fn lastPage(self: *Paginator) void { + self.current_page = self.total_pages -| 1; + } + + /// Check if on first page + pub fn onFirstPage(self: *const Paginator) bool { + return self.current_page == 0; + } + + /// Check if on last page + pub fn onLastPage(self: *const Paginator) bool { + return self.current_page >= self.total_pages -| 1; + } + + /// Get start index for current page + pub fn startIndex(self: *const Paginator) usize { + return self.current_page * self.per_page; + } + + /// Get end index for current page (exclusive) + pub fn endIndex(self: *const Paginator) usize { + return @min(self.startIndex() + self.per_page, self.total_items); + } + + /// Get items on current page + pub fn itemsOnPage(self: *const Paginator) usize { + return self.endIndex() - self.startIndex(); + } + + /// Handle key event + pub fn handleKey(self: *Paginator, key: keys.KeyEvent) void { + switch (key.key) { + .left => self.prevPage(), + .right => self.nextPage(), + .home => self.firstPage(), + .end => self.lastPage(), + .char => |c| { + switch (c) { + 'h' => self.prevPage(), + 'l' => self.nextPage(), + else => {}, + } + }, + else => {}, + } + } + + /// Render the paginator + pub fn view(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { + return switch (self.paginator_type) { + .dots => self.viewDots(allocator), + .arabic => self.viewArabic(allocator), + .compact => self.viewCompact(allocator), + }; + } + + fn viewDots(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (0..self.total_pages) |i| { + if (i > 0) try writer.writeByte(' '); + + if (i == self.current_page) { + const styled = try self.active_style.render(allocator, self.active_dot); + try writer.writeAll(styled); + } else { + const styled = try self.inactive_style.render(allocator, self.inactive_dot); + try writer.writeAll(styled); + } + } + + return result.toOwnedSlice(); + } + + fn viewArabic(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { + const text = try std.fmt.allocPrint(allocator, "{d}/{d}", .{ self.current_page + 1, self.total_pages }); + return self.active_style.render(allocator, text); + } + + fn viewCompact(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Show limited range of pages + const max_visible = 5; + var start: usize = 0; + var end = self.total_pages; + + if (self.total_pages > max_visible) { + const half = max_visible / 2; + if (self.current_page <= half) { + end = max_visible; + } else if (self.current_page >= self.total_pages - half) { + start = self.total_pages - max_visible; + } else { + start = self.current_page - half; + end = self.current_page + half + 1; + } + } + + // Previous indicator + if (start > 0) { + try writer.writeAll("< "); + } + + for (start..end) |i| { + if (i > start) try writer.writeByte(' '); + + const page_str = try std.fmt.allocPrint(allocator, "{d}", .{i + 1}); + if (i == self.current_page) { + const styled = try self.active_style.render(allocator, page_str); + try writer.writeAll(styled); + } else { + const styled = try self.inactive_style.render(allocator, page_str); + try writer.writeAll(styled); + } + } + + // Next indicator + if (end < self.total_pages) { + try writer.writeAll(" >"); + } + + return result.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig new file mode 100644 index 0000000..15ef751 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig @@ -0,0 +1,264 @@ +//! Progress bar component. +//! Displays progress with customizable appearance. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Progress = struct { + // Progress state + current: f64, + total: f64, + + // Appearance + width: u16, + show_percent: bool, + show_count: bool, + + // Characters + full_char: []const u8, + empty_char: []const u8, + head_char: ?[]const u8, + + // Styling + full_style: style.Style, + empty_style: style.Style, + percent_style: style.Style, + + // Gradient + gradient_start: ?Color, + gradient_end: ?Color, + + pub fn init() Progress { + return .{ + .current = 0, + .total = 100, + .width = 40, + .show_percent = true, + .show_count = false, + .full_char = "█", + .empty_char = "░", + .head_char = null, + .full_style = blk: { + var s = style.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .empty_style = blk: { + var s = style.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + .percent_style = blk: { + var s = style.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .gradient_start = null, + .gradient_end = null, + }; + } + + /// Set progress value (0 to total) + pub fn setValue(self: *Progress, value: f64) void { + self.current = @max(0, @min(value, self.total)); + } + + /// Set progress percentage (0 to 100) + pub fn setPercent(self: *Progress, pct: f64) void { + self.current = (pct / 100.0) * self.total; + } + + /// Increment progress + pub fn increment(self: *Progress, amount: f64) void { + self.setValue(self.current + amount); + } + + /// Set total value + pub fn setTotal(self: *Progress, total: f64) void { + self.total = total; + } + + /// Set bar width + pub fn setWidth(self: *Progress, width: u16) void { + self.width = width; + } + + /// Get current percentage (0-100) + pub fn percent(self: *const Progress) f64 { + if (self.total == 0) return 0; + return (self.current / self.total) * 100.0; + } + + /// Check if complete + pub fn isComplete(self: *const Progress) bool { + return self.current >= self.total; + } + + /// Set bar characters + pub fn setChars(self: *Progress, full: []const u8, empty: []const u8, head: ?[]const u8) void { + self.full_char = full; + self.empty_char = empty; + self.head_char = head; + } + + /// Use gradient style + pub fn useGradient(self: *Progress) void { + self.full_char = "█"; + self.empty_char = "░"; + self.head_char = "▓"; + } + + /// Use simple ASCII style + pub fn useAscii(self: *Progress) void { + self.full_char = "#"; + self.empty_char = "-"; + self.head_char = ">"; + } + + /// Use block style + pub fn useBlock(self: *Progress) void { + self.full_char = "■"; + self.empty_char = "□"; + self.head_char = null; + } + + /// Set color gradient for the filled portion + pub fn setGradient(self: *Progress, start: Color, end: Color) void { + self.gradient_start = start; + self.gradient_end = end; + } + + /// Render the progress bar + pub fn view(self: *const Progress, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const ratio = if (self.total > 0) self.current / self.total else 0; + const filled_width = @as(usize, @intFromFloat(ratio * @as(f64, @floatFromInt(self.width)))); + const empty_width = self.width -| @as(u16, @intCast(filled_width)); + + // Filled portion + for (0..filled_width) |i| { + const char = if (self.head_char != null and i == filled_width - 1 and empty_width > 0) + self.head_char.? + else + self.full_char; + + // Apply gradient color if set + if (self.gradient_start != null and self.gradient_end != null and filled_width > 0) { + const t: f64 = @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(@max(1, filled_width - 1))); + const color = interpolateColor(self.gradient_start.?, self.gradient_end.?, t); + var grad_style = style.Style{}; + grad_style = grad_style.fg(color); + grad_style = grad_style.inline_style(true); + const grad_styled = try grad_style.render(allocator, char); + try writer.writeAll(grad_styled); + } else { + const full_styled = try self.full_style.render(allocator, char); + try writer.writeAll(full_styled); + } + } + + // Empty portion + for (0..empty_width) |_| { + const empty_styled = try self.empty_style.render(allocator, self.empty_char); + try writer.writeAll(empty_styled); + } + + // Percentage + if (self.show_percent) { + const pct = self.percent(); + const pct_str = try std.fmt.allocPrint(allocator, " {d:.0}%", .{pct}); + const pct_styled = try self.percent_style.render(allocator, pct_str); + try writer.writeAll(pct_styled); + } + + // Count + if (self.show_count) { + const count_str = try std.fmt.allocPrint(allocator, " ({d}/{d})", .{ + @as(i64, @intFromFloat(self.current)), + @as(i64, @intFromFloat(self.total)), + }); + try writer.writeAll(count_str); + } + + return result.toOwnedSlice(); + } + + /// Render with a label + pub fn viewWithLabel(self: *const Progress, allocator: std.mem.Allocator, label: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + try writer.writeAll(label); + try writer.writeAll(" "); + + const bar = try self.view(allocator); + try writer.writeAll(bar); + + return result.toOwnedSlice(); + } +}; + +/// Progress bar styles +pub const ProgressStyle = struct { + /// Default style with gradient characters + pub fn gradient() Progress { + var p = Progress.init(); + p.useGradient(); + return p; + } + + /// ASCII-only style + pub fn ascii() Progress { + var p = Progress.init(); + p.useAscii(); + return p; + } + + /// Block style + pub fn block() Progress { + var p = Progress.init(); + p.useBlock(); + return p; + } + + /// Simple line style + pub fn simple() Progress { + var p = Progress.init(); + p.full_char = "="; + p.empty_char = " "; + p.head_char = ">"; + return p; + } + + /// Colored style + pub fn colored() Progress { + var p = Progress.init(); + var full_s = style.Style{}; + full_s = full_s.fg(.green); + full_s = full_s.inline_style(true); + p.full_style = full_s; + var empty_s = style.Style{}; + empty_s = empty_s.fg(.red); + empty_s = empty_s.inline_style(true); + p.empty_style = empty_s; + return p; + } +}; + +/// Interpolate between two colors using RGB lerp +pub fn interpolateColor(start: Color, end: Color, t: f64) Color { + const start_rgb = start.toRgb() orelse return start; + const end_rgb = end.toRgb() orelse return end; + + const r: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.r)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.r)) * t); + const g: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.g)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.g)) * t); + const b: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.b)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.b)) * t); + + return .fromRgb(r, g, b); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig new file mode 100644 index 0000000..7f754ab --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig @@ -0,0 +1,276 @@ +//! RadioGroup component. +//! Single-select option group with radio button semantics. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub fn RadioGroup(comptime T: type) type { + return struct { + allocator: std.mem.Allocator, + + // Items + items: std.array_list.Managed(Item), + + // State + selected: ?usize, + cursor: usize, + height: u16, + y_offset: usize, + + // Focus + focused: bool, + + // Symbols + cursor_symbol: []const u8, + selected_symbol: []const u8, + unselected_symbol: []const u8, + + // Styling + item_style: style_mod.Style, + selected_style: style_mod.Style, + cursor_style: style_mod.Style, + disabled_style: style_mod.Style, + + const Self = @This(); + + pub const Item = struct { + value: T, + label: []const u8, + description: []const u8, + enabled: bool, + + pub fn init(value: T, label: []const u8) Item { + return .{ + .value = value, + .label = label, + .description = "", + .enabled = true, + }; + } + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .items = std.array_list.Managed(Item).init(allocator), + .selected = null, + .cursor = 0, + .height = 10, + .y_offset = 0, + .focused = true, + .cursor_symbol = "> ", + .selected_symbol = "(●) ", + .unselected_symbol = "( ) ", + .item_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .selected_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.magenta); + s = s.inline_style(true); + break :blk s; + }, + .disabled_style = blk: { + var s = style_mod.Style{}; + s = s.dim(true); + s = s.fg(.gray(10)); + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *Self) void { + self.items.deinit(); + } + + pub fn addOption(self: *Self, item: Item) !void { + try self.items.append(item); + } + + pub fn addOptions(self: *Self, new_items: []const Item) !void { + try self.items.appendSlice(new_items); + } + + pub fn selectCurrent(self: *Self) void { + if (self.cursor >= self.items.items.len) return; + if (!self.items.items[self.cursor].enabled) return; + self.selected = self.cursor; + } + + pub fn selectedItem(self: *const Self) ?*const Item { + if (self.selected) |idx| { + if (idx < self.items.items.len) { + return &self.items.items[idx]; + } + } + return null; + } + + pub fn selectedValue(self: *const Self) ?T { + if (self.selectedItem()) |item| { + return item.value; + } + return null; + } + + // Focus protocol + pub fn focus(self: *Self) void { + self.focused = true; + } + + pub fn blur(self: *Self) void { + self.focused = false; + } + + pub fn handleKey(self: *Self, key: keys.KeyEvent) void { + if (!self.focused) return; + + switch (key.key) { + .up => self.cursorUp(), + .down => self.cursorDown(), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoFirst(), + .end => self.gotoLast(), + .space, .enter => self.selectCurrent(), + .char => |c| switch (c) { + 'j' => self.cursorDown(), + 'k' => self.cursorUp(), + 'g' => self.gotoFirst(), + 'G' => self.gotoLast(), + else => {}, + }, + else => {}, + } + } + + fn cursorUp(self: *Self) void { + if (self.items.items.len == 0) return; + if (self.cursor > 0) { + self.cursor -= 1; + } else { + self.cursor = self.items.items.len - 1; + } + self.ensureVisible(); + } + + fn cursorDown(self: *Self) void { + if (self.items.items.len == 0) return; + if (self.cursor < self.items.items.len - 1) { + self.cursor += 1; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + fn pageUp(self: *Self) void { + if (self.cursor >= self.height) { + self.cursor -= self.height; + } else { + self.cursor = 0; + } + self.ensureVisible(); + } + + fn pageDown(self: *Self) void { + if (self.cursor + self.height < self.items.items.len) { + self.cursor += self.height; + } else if (self.items.items.len > 0) { + self.cursor = self.items.items.len - 1; + } + self.ensureVisible(); + } + + fn gotoFirst(self: *Self) void { + self.cursor = 0; + self.y_offset = 0; + } + + fn gotoLast(self: *Self) void { + if (self.items.items.len > 0) { + self.cursor = self.items.items.len - 1; + self.ensureVisible(); + } + } + + fn ensureVisible(self: *Self) void { + if (self.cursor < self.y_offset) { + self.y_offset = self.cursor; + } else if (self.cursor >= self.y_offset + self.height) { + self.y_offset = self.cursor - self.height + 1; + } + } + + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var rendered: usize = 0; + while (rendered < self.height) : (rendered += 1) { + if (rendered > 0) try writer.writeByte('\n'); + + const idx = self.y_offset + rendered; + if (idx >= self.items.items.len) break; + + const item = self.items.items[idx]; + const is_selected = self.selected != null and self.selected.? == idx; + + // Cursor + if (idx == self.cursor and self.focused) { + const styled = try self.cursor_style.render(allocator, self.cursor_symbol); + try writer.writeAll(styled); + } else { + for (0..self.cursor_symbol.len) |_| { + try writer.writeByte(' '); + } + } + + // Radio symbol + const radio_sym = if (is_selected) self.selected_symbol else self.unselected_symbol; + const radio_s = if (!item.enabled) + self.disabled_style + else if (is_selected) + self.selected_style + else + self.item_style; + const styled_radio = try radio_s.render(allocator, radio_sym); + try writer.writeAll(styled_radio); + + // Label + const lbl_style = if (!item.enabled) + self.disabled_style + else if (idx == self.cursor and self.focused) + self.cursor_style + else if (is_selected) + self.selected_style + else + self.item_style; + const styled_label = try lbl_style.render(allocator, item.label); + try writer.writeAll(styled_label); + + // Description + if (item.description.len > 0) { + try writer.writeAll(" - "); + try writer.writeAll(item.description); + } + } + + return result.toOwnedSlice(); + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig new file mode 100644 index 0000000..895c72f --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig @@ -0,0 +1,422 @@ +//! Rich log widget — append-only, virtualized, level-aware. +//! +//! Stores a bounded ring buffer of log entries with severity levels and +//! optional timestamps. Renders only the visible window so cost stays O(rows) +//! regardless of buffer size. Supports follow-mode (auto-scroll to tail), +//! per-level styling, level filters, and substring search highlighting. +//! +//! Distinct from Viewport (raw text) and Toast (transient notification): this +//! is the right widget for a long-running app's persistent log/audit pane. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); + +pub const Style = style_mod.Style; + +pub const Level = enum { + trace, + debug, + info, + warn, + err, + + pub fn label(self: Level) []const u8 { + return switch (self) { + .trace => "TRACE", + .debug => "DEBUG", + .info => "INFO ", + .warn => "WARN ", + .err => "ERROR", + }; + } + + pub fn rank(self: Level) u8 { + return switch (self) { + .trace => 0, + .debug => 1, + .info => 2, + .warn => 3, + .err => 4, + }; + } +}; + +pub const Entry = struct { + level: Level, + /// Unix nanoseconds, populated by `append` from `std.Io.Timestamp.now(io, .real)`. + timestamp_ns: i128, + text: []u8, +}; + +pub const RichLog = struct { + allocator: std.mem.Allocator, + + /// Ring buffer of entries. + entries: std.array_list.Managed(Entry), + /// Maximum entries retained; older entries are dropped on append. + capacity: usize, + + /// Indices into `entries` after applying min_level + search filter. + /// Recomputed lazily. + visible: std.array_list.Managed(usize), + visible_dirty: bool, + + /// Display configuration. + width: u16, + height: u16, + y_offset: usize, + follow: bool, + + /// Filtering. + min_level: Level, + search_term: std.array_list.Managed(u8), + + /// Display options. + show_timestamps: bool, + show_level: bool, + + /// Styling. + timestamp_style: Style, + level_styles: [5]Style, + text_style: Style, + highlight_style: Style, + + pub fn init(allocator: std.mem.Allocator, capacity: usize) RichLog { + var ts = Style{}; + ts = ts.fg(.gray(8)); + ts = ts.inline_style(true); + + var trace_s = Style{}; + trace_s = trace_s.fg(.gray(6)); + trace_s = trace_s.inline_style(true); + var debug_s = Style{}; + debug_s = debug_s.fg(.gray(10)); + debug_s = debug_s.inline_style(true); + var info_s = Style{}; + info_s = info_s.fg(.cyan); + info_s = info_s.inline_style(true); + var warn_s = Style{}; + warn_s = warn_s.fg(.yellow); + warn_s = warn_s.inline_style(true); + var err_s = Style{}; + err_s = err_s.fg(.red); + err_s = err_s.bold(true); + err_s = err_s.inline_style(true); + + var text = Style{}; + text = text.inline_style(true); + + var hi = Style{}; + hi = hi.bg(.yellow); + hi = hi.fg(.black); + hi = hi.inline_style(true); + + return .{ + .allocator = allocator, + .entries = std.array_list.Managed(Entry).init(allocator), + .capacity = @max(capacity, 1), + .visible = std.array_list.Managed(usize).init(allocator), + .visible_dirty = true, + .width = 80, + .height = 10, + .y_offset = 0, + .follow = true, + .min_level = .trace, + .search_term = std.array_list.Managed(u8).init(allocator), + .show_timestamps = false, + .show_level = true, + .timestamp_style = ts, + .level_styles = .{ trace_s, debug_s, info_s, warn_s, err_s }, + .text_style = text, + .highlight_style = hi, + }; + } + + pub fn deinit(self: *RichLog) void { + for (self.entries.items) |e| self.allocator.free(e.text); + self.entries.deinit(); + self.visible.deinit(); + self.search_term.deinit(); + } + + pub fn setSize(self: *RichLog, w: u16, h: u16) void { + self.width = w; + self.height = h; + } + + pub fn setMinLevel(self: *RichLog, lvl: Level) void { + self.min_level = lvl; + self.visible_dirty = true; + } + + pub fn setSearch(self: *RichLog, term: []const u8) !void { + self.search_term.clearRetainingCapacity(); + try self.search_term.appendSlice(term); + self.visible_dirty = true; + } + + pub fn clearSearch(self: *RichLog) void { + self.search_term.clearRetainingCapacity(); + self.visible_dirty = true; + } + + /// Append an entry, dropping the oldest if at capacity. + pub fn append(self: *RichLog, io: std.Io, level: Level, text: []const u8) !void { + const owned = try self.allocator.dupe(u8, text); + if (self.entries.items.len >= self.capacity) { + const oldest = self.entries.orderedRemove(0); + self.allocator.free(oldest.text); + } + try self.entries.append(.{ + .level = level, + .timestamp_ns = std.Io.Timestamp.now(io, .real).toNanoseconds(), + .text = owned, + }); + self.visible_dirty = true; + if (self.follow) self.scrollToEnd(); + } + + /// Append using std.fmt-style formatting. + pub fn appendFmt(self: *RichLog, io: std.Io, level: Level, comptime fmt: []const u8, args: anytype) !void { + const formatted = try std.fmt.allocPrint(self.allocator, fmt, args); + defer self.allocator.free(formatted); + try self.append(io, level, formatted); + } + + pub fn clear(self: *RichLog) void { + for (self.entries.items) |e| self.allocator.free(e.text); + self.entries.clearRetainingCapacity(); + self.visible.clearRetainingCapacity(); + self.visible_dirty = false; + self.y_offset = 0; + } + + pub fn scrollUp(self: *RichLog, n: usize) void { + self.follow = false; + self.y_offset -|= n; + } + + pub fn scrollDown(self: *RichLog, n: usize) !void { + try self.refresh(); + const max_off = self.maxOffset(); + self.y_offset = @min(self.y_offset + n, max_off); + if (self.y_offset == max_off) self.follow = true; + } + + pub fn scrollToEnd(self: *RichLog) void { + self.refresh() catch return; + self.y_offset = self.maxOffset(); + self.follow = true; + } + + pub fn scrollToStart(self: *RichLog) void { + self.y_offset = 0; + self.follow = false; + } + + fn maxOffset(self: *const RichLog) usize { + const visible_count = self.visible.items.len; + if (visible_count <= self.height) return 0; + return visible_count - self.height; + } + + fn refresh(self: *RichLog) !void { + if (!self.visible_dirty) return; + self.visible.clearRetainingCapacity(); + for (self.entries.items, 0..) |e, i| { + if (e.level.rank() < self.min_level.rank()) continue; + if (self.search_term.items.len > 0 and + std.mem.indexOf(u8, e.text, self.search_term.items) == null) + { + continue; + } + try self.visible.append(i); + } + self.visible_dirty = false; + const max_off = self.maxOffset(); + if (self.y_offset > max_off) self.y_offset = max_off; + } + + pub fn handleKey(self: *RichLog, key: keys.KeyEvent) !void { + switch (key.key) { + .up => self.scrollUp(1), + .down => try self.scrollDown(1), + .page_up => self.scrollUp(self.height), + .page_down => try self.scrollDown(self.height), + .home => self.scrollToStart(), + .end => self.scrollToEnd(), + .char => |c| switch (c) { + 'g' => self.scrollToStart(), + 'G' => self.scrollToEnd(), + 'k' => self.scrollUp(1), + 'j' => try self.scrollDown(1), + else => {}, + }, + else => {}, + } + } + + pub fn view(self: *RichLog, allocator: std.mem.Allocator) ![]const u8 { + try self.refresh(); + + var out: Writer.Allocating = .init(allocator); + const w = &out.writer; + + const visible = self.visible.items; + if (visible.len == 0) { + return out.toOwnedSlice(); + } + + const start = self.y_offset; + const end = @min(start + self.height, visible.len); + + var first = true; + for (start..end) |row_idx| { + if (!first) try w.writeByte('\n'); + first = false; + const entry = self.entries.items[visible[row_idx]]; + try self.renderEntry(allocator, w, entry); + } + + return out.toOwnedSlice(); + } + + fn renderEntry(self: *const RichLog, allocator: std.mem.Allocator, w: *Writer, entry: Entry) !void { + if (self.show_timestamps) { + const ts = try formatTimestamp(allocator, entry.timestamp_ns); + defer allocator.free(ts); + const styled = try self.timestamp_style.render(allocator, ts); + defer allocator.free(styled); + try w.writeAll(styled); + try w.writeByte(' '); + } + + if (self.show_level) { + const lvl_style = self.level_styles[@intFromEnum(entry.level)]; + const styled = try lvl_style.render(allocator, entry.level.label()); + defer allocator.free(styled); + try w.writeAll(styled); + try w.writeByte(' '); + } + + // Render text with optional search highlighting. + if (self.search_term.items.len == 0) { + const styled = try self.text_style.render(allocator, entry.text); + defer allocator.free(styled); + try w.writeAll(styled); + } else { + try self.renderHighlighted(allocator, w, entry.text); + } + } + + fn renderHighlighted(self: *const RichLog, allocator: std.mem.Allocator, w: *Writer, text: []const u8) !void { + const term = self.search_term.items; + var rest = text; + while (std.mem.indexOf(u8, rest, term)) |pos| { + if (pos > 0) { + const before = try self.text_style.render(allocator, rest[0..pos]); + defer allocator.free(before); + try w.writeAll(before); + } + const hi = try self.highlight_style.render(allocator, rest[pos .. pos + term.len]); + defer allocator.free(hi); + try w.writeAll(hi); + rest = rest[pos + term.len ..]; + } + if (rest.len > 0) { + const tail = try self.text_style.render(allocator, rest); + defer allocator.free(tail); + try w.writeAll(tail); + } + } +}; + +fn formatTimestamp(allocator: std.mem.Allocator, ns: i128) ![]u8 { + const seconds_total: i64 = @intCast(@divTrunc(ns, std.time.ns_per_s)); + // HH:MM:SS in UTC. + const sec_in_day: u32 = @intCast(@mod(seconds_total, 86400)); + const hh = sec_in_day / 3600; + const mm = (sec_in_day % 3600) / 60; + const ss = sec_in_day % 60; + return std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hh, mm, ss }); +} + +test "append respects capacity" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 3); + defer log.deinit(); + try log.append(std.testing.io, .info, "a"); + try log.append(std.testing.io, .info, "b"); + try log.append(std.testing.io, .info, "c"); + try log.append(std.testing.io, .info, "d"); + try std.testing.expectEqual(@as(usize, 3), log.entries.items.len); + try std.testing.expectEqualStrings("b", log.entries.items[0].text); + try std.testing.expectEqualStrings("d", log.entries.items[2].text); +} + +test "min level filters entries" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 100); + defer log.deinit(); + try log.append(std.testing.io, .debug, "noise"); + try log.append(std.testing.io, .warn, "important"); + log.setMinLevel(.warn); + try log.refresh(); + try std.testing.expectEqual(@as(usize, 1), log.visible.items.len); +} + +test "search filter matches substring" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 10); + defer log.deinit(); + try log.append(std.testing.io, .info, "hello world"); + try log.append(std.testing.io, .info, "goodbye"); + try log.setSearch("hello"); + try log.refresh(); + try std.testing.expectEqual(@as(usize, 1), log.visible.items.len); +} + +test "follow mode auto-scrolls" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 100); + defer log.deinit(); + log.setSize(80, 2); + var i: usize = 0; + while (i < 5) : (i += 1) { + try log.appendFmt(std.testing.io, .info, "line {d}", .{i}); + } + try log.refresh(); + // Last two entries should fit; offset should be 3. + try std.testing.expectEqual(@as(usize, 3), log.y_offset); +} + +test "scrollUp disables follow" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 100); + defer log.deinit(); + try log.append(std.testing.io, .info, "a"); + log.scrollUp(1); + try std.testing.expect(!log.follow); +} + +test "view emits at most height lines" { + const allocator = std.testing.allocator; + var log = RichLog.init(allocator, 100); + defer log.deinit(); + log.setSize(80, 3); + var i: usize = 0; + while (i < 10) : (i += 1) { + try log.appendFmt(std.testing.io, .info, "line {d}", .{i}); + } + const out = try log.view(allocator); + defer allocator.free(out); + var newlines: usize = 0; + for (out) |b| if (b == '\n') { + newlines += 1; + }; + try std.testing.expect(newlines <= 2); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig new file mode 100644 index 0000000..c38bb44 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig @@ -0,0 +1,291 @@ +//! Slider component. +//! Interactive numeric range input with keyboard control. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const progress_mod = @import("progress.zig"); + +pub const Slider = struct { + // Value + value: f64, + min: f64, + max: f64, + step: f64, + large_step: f64, + + // Display + width: u16, + precision: u8, + show_value: bool, + show_bounds: bool, + show_percent: bool, + label: []const u8, + + // Characters + track_char: []const u8, + thumb_char: []const u8, + filled_char: []const u8, + + // Styling + track_style: style_mod.Style, + filled_style: style_mod.Style, + thumb_style: style_mod.Style, + label_style: style_mod.Style, + value_style: style_mod.Style, + + // Gradient + gradient_start: ?Color, + gradient_end: ?Color, + + // Focus + focused: bool, + + pub fn init(min: f64, max: f64) Slider { + return .{ + .value = min, + .min = min, + .max = max, + .step = 1, + .large_step = 10, + .width = 30, + .precision = 0, + .show_value = true, + .show_bounds = false, + .show_percent = false, + .label = "", + .track_char = "━", + .thumb_char = "●", + .filled_char = "━", + .track_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + .filled_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .thumb_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + .label_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .value_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .gradient_start = null, + .gradient_end = null, + .focused = true, + }; + } + + pub fn setValue(self: *Slider, val: f64) void { + self.value = @max(self.min, @min(val, self.max)); + } + + pub fn getValue(self: *const Slider) f64 { + return self.value; + } + + pub fn percent(self: *const Slider) f64 { + if (self.max == self.min) return 0; + return ((self.value - self.min) / (self.max - self.min)) * 100.0; + } + + pub fn setStep(self: *Slider, s: f64) void { + self.step = s; + } + + pub fn setLargeStep(self: *Slider, s: f64) void { + self.large_step = s; + } + + pub fn setWidth(self: *Slider, w: u16) void { + self.width = w; + } + + pub fn setPrecision(self: *Slider, p: u8) void { + self.precision = p; + } + + pub fn setGradient(self: *Slider, start: Color, end: Color) void { + self.gradient_start = start; + self.gradient_end = end; + } + + // Focus protocol + pub fn focus(self: *Slider) void { + self.focused = true; + } + + pub fn blur(self: *Slider) void { + self.focused = false; + } + + pub fn handleKey(self: *Slider, key: keys.KeyEvent) void { + if (!self.focused) return; + + switch (key.key) { + .left => self.decrement(self.step), + .right => self.increment(self.step), + .page_down => self.decrement(self.large_step), + .page_up => self.increment(self.large_step), + .home => self.setValue(self.min), + .end => self.setValue(self.max), + .char => |c| switch (c) { + 'h' => self.decrement(self.step), + 'l' => self.increment(self.step), + 'H' => self.decrement(self.large_step), + 'L' => self.increment(self.large_step), + '0' => self.setValue(self.min), + '$' => self.setValue(self.max), + else => {}, + }, + else => {}, + } + } + + fn increment(self: *Slider, amount: f64) void { + self.setValue(self.value + amount); + } + + fn decrement(self: *Slider, amount: f64) void { + self.setValue(self.value - amount); + } + + pub fn view(self: *const Slider, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Label + if (self.label.len > 0) { + const styled = try self.label_style.render(allocator, self.label); + try writer.writeAll(styled); + try writer.writeAll(" "); + } + + // Bounds (left) + if (self.show_bounds) { + const min_str = try self.formatValue(allocator, self.min); + try writer.writeAll(min_str); + try writer.writeAll(" "); + } + + // Track + const range = self.max - self.min; + const ratio: f64 = if (range > 0) (self.value - self.min) / range else 0; + const track_width = self.width; + const thumb_pos = @as(usize, @intFromFloat(ratio * @as(f64, @floatFromInt(track_width -| 1)))); + + for (0..track_width) |i| { + if (i == thumb_pos) { + // Thumb + const styled = try self.thumb_style.render(allocator, self.thumb_char); + try writer.writeAll(styled); + } else if (i < thumb_pos) { + // Filled portion + if (self.gradient_start != null and self.gradient_end != null and thumb_pos > 0) { + const t: f64 = @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(@max(1, thumb_pos))); + const col = progress_mod.interpolateColor(self.gradient_start.?, self.gradient_end.?, t); + var grad_style = style_mod.Style{}; + grad_style = grad_style.fg(col); + grad_style = grad_style.inline_style(true); + const styled = try grad_style.render(allocator, self.filled_char); + try writer.writeAll(styled); + } else { + const styled = try self.filled_style.render(allocator, self.filled_char); + try writer.writeAll(styled); + } + } else { + // Empty track + const styled = try self.track_style.render(allocator, self.track_char); + try writer.writeAll(styled); + } + } + + // Bounds (right) + if (self.show_bounds) { + try writer.writeAll(" "); + const max_str = try self.formatValue(allocator, self.max); + try writer.writeAll(max_str); + } + + // Value display + if (self.show_value) { + try writer.writeAll(" "); + const val_str = try self.formatValue(allocator, self.value); + const styled = try self.value_style.render(allocator, val_str); + try writer.writeAll(styled); + } + + // Percentage + if (self.show_percent) { + const pct = self.percent(); + const pct_str = try std.fmt.allocPrint(allocator, " ({d:.0}%)", .{pct}); + try writer.writeAll(pct_str); + } + + return result.toOwnedSlice(); + } + + fn formatValue(self: *const Slider, allocator: std.mem.Allocator, val: f64) ![]const u8 { + return switch (self.precision) { + 0 => std.fmt.allocPrint(allocator, "{d:.0}", .{val}), + 1 => std.fmt.allocPrint(allocator, "{d:.1}", .{val}), + 2 => std.fmt.allocPrint(allocator, "{d:.2}", .{val}), + else => std.fmt.allocPrint(allocator, "{d:.3}", .{val}), + }; + } +}; + +/// Slider style presets +pub const SliderStyle = struct { + pub fn block() Slider { + var s = Slider.init(0, 100); + s.filled_char = "█"; + s.track_char = "░"; + s.thumb_char = "▓"; + return s; + } + + pub fn ascii() Slider { + var s = Slider.init(0, 100); + s.filled_char = "="; + s.track_char = "-"; + s.thumb_char = ">"; + return s; + } + + pub fn thin() Slider { + var s = Slider.init(0, 100); + s.filled_char = "─"; + s.track_char = "─"; + s.thumb_char = "◆"; + return s; + } + + pub fn dots() Slider { + var s = Slider.init(0, 100); + s.filled_char = "•"; + s.track_char = "·"; + s.thumb_char = "◉"; + return s; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig new file mode 100644 index 0000000..58e7c75 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig @@ -0,0 +1,321 @@ +//! Sortable and filterable table component. +//! Extends basic table with column sorting and text filtering. + +const std = @import("std"); +const Writer = std.Io.Writer; +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 keys = @import("../input/keys.zig"); + +pub fn SortableTable(comptime num_cols: usize) type { + return struct { + allocator: std.mem.Allocator, + headers: [num_cols][]const u8, + rows: std.array_list.Managed([num_cols][]const u8), + /// Indices into rows for display order (sorted/filtered view). + view_indices: std.array_list.Managed(usize), + + // Sort state + sort_column: ?usize = null, + sort_ascending: bool = true, + + // Filter + filter_text: std.array_list.Managed(u8), + filter_column: ?usize = null, // null = search all columns + filter_active: bool = false, + + // Display + col_widths: [num_cols]?u16 = .{null} ** num_cols, + col_aligns: [num_cols]Align = .{.left} ** num_cols, + show_header: bool = true, + show_border: bool = true, + border_chars: border_mod.BorderChars = .normal, + + // Interactive + cursor_row: usize = 0, + y_offset: usize = 0, + visible_rows: u16 = 20, + focused: bool = true, + + // Styling + header_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + cell_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + cursor_row_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bg(.blue); + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + sort_indicator_asc: []const u8 = " \xe2\x96\xb2", + sort_indicator_desc: []const u8 = " \xe2\x96\xbc", + + const Self = @This(); + + pub const Align = enum { left, center, right }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .headers = .{""} ** num_cols, + .rows = std.array_list.Managed([num_cols][]const u8).init(allocator), + .view_indices = std.array_list.Managed(usize).init(allocator), + .filter_text = std.array_list.Managed(u8).init(allocator), + }; + } + + pub fn deinit(self: *Self) void { + self.rows.deinit(); + self.view_indices.deinit(); + self.filter_text.deinit(); + } + + pub fn setHeaders(self: *Self, hdrs: [num_cols][]const u8) void { + self.headers = hdrs; + } + + pub fn addRow(self: *Self, row: [num_cols][]const u8) !void { + try self.rows.append(row); + try self.rebuildView(); + } + + pub fn update(self: *Self, key: keys.KeyEvent) void { + const total = self.view_indices.items.len; + switch (key.key) { + .up => { + if (self.cursor_row > 0) self.cursor_row -= 1; + self.ensureVisible(); + }, + .down => { + if (self.cursor_row + 1 < total) self.cursor_row += 1; + self.ensureVisible(); + }, + .char => |c| { + if (c >= '1' and c <= '9') { + const col: usize = c - '1'; + if (col < num_cols) self.toggleSort(col); + } else if (c == '/') { + self.filter_active = true; + } else if (self.filter_active) { + if (c < 128) { + self.filter_text.append(@intCast(c)) catch {}; + self.rebuildView() catch {}; + } + } + }, + .backspace => { + if (self.filter_active and self.filter_text.items.len > 0) { + _ = self.filter_text.pop(); + self.rebuildView() catch {}; + } + }, + .escape => { + if (self.filter_active) { + self.filter_active = false; + self.filter_text.clearRetainingCapacity(); + self.rebuildView() catch {}; + } + }, + .enter => { + if (self.filter_active) { + self.filter_active = false; + } + }, + else => {}, + } + } + + fn toggleSort(self: *Self, col: usize) void { + if (self.sort_column == col) { + self.sort_ascending = !self.sort_ascending; + } else { + self.sort_column = col; + self.sort_ascending = true; + } + self.rebuildView() catch {}; + } + + fn rebuildView(self: *Self) !void { + self.view_indices.clearRetainingCapacity(); + const filter = self.filter_text.items; + + for (0..self.rows.items.len) |i| { + if (filter.len > 0) { + var matches = false; + for (self.rows.items[i]) |cell| { + if (containsIgnoreCase(cell, filter)) { + matches = true; + break; + } + } + if (!matches) continue; + } + try self.view_indices.append(i); + } + + // Sort using bubble sort (simple, avoids comptime context issues) + if (self.sort_column) |col| { + const indices = self.view_indices.items; + const rws = self.rows.items; + const asc = self.sort_ascending; + var sorted = false; + while (!sorted) { + sorted = true; + for (0..indices.len -| 1) |i| { + const va = rws[indices[i]][col]; + const vb = rws[indices[i + 1]][col]; + const cmp = std.mem.order(u8, va, vb); + const should_swap = if (asc) cmp == .gt else cmp == .lt; + if (should_swap) { + const tmp = indices[i]; + indices[i] = indices[i + 1]; + indices[i + 1] = tmp; + sorted = false; + } + } + } + } + + if (self.cursor_row >= self.view_indices.items.len and self.view_indices.items.len > 0) { + self.cursor_row = self.view_indices.items.len - 1; + } + } + + fn ensureVisible(self: *Self) void { + if (self.cursor_row < self.y_offset) self.y_offset = self.cursor_row; + if (self.cursor_row >= self.y_offset + self.visible_rows) { + self.y_offset = self.cursor_row - self.visible_rows + 1; + } + } + + pub fn view(self: *const Self, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Compute column widths + var widths: [num_cols]usize = undefined; + for (0..num_cols) |c| { + widths[c] = if (self.col_widths[c]) |w| w else blk: { + var max_w: usize = self.headers[c].len + 2; // room for sort indicator + for (self.rows.items) |row| { + max_w = @max(max_w, row[c].len); + } + break :blk max_w; + }; + } + + // Header + if (self.show_header) { + for (0..num_cols) |c| { + if (c > 0) writer.writeAll(" \xe2\x94\x82 ") catch {}; + const hdr = self.headers[c]; + writer.writeAll(self.header_style.render(allocator, hdr) catch hdr) catch {}; + + // Sort indicator + if (self.sort_column == c) { + if (self.sort_ascending) { + writer.writeAll(self.sort_indicator_asc) catch {}; + } else { + writer.writeAll(self.sort_indicator_desc) catch {}; + } + const used = hdr.len + 2; + if (used < widths[c]) { + for (0..widths[c] - used) |_| writer.writeByte(' ') catch {}; + } + } else { + if (hdr.len < widths[c]) { + for (0..widths[c] - hdr.len) |_| writer.writeByte(' ') catch {}; + } + } + } + writer.writeByte('\n') catch {}; + + // Separator + for (0..num_cols) |c| { + if (c > 0) writer.writeAll("\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80") catch {}; + for (0..widths[c]) |_| writer.writeAll("\xe2\x94\x80") catch {}; + } + writer.writeByte('\n') catch {}; + } + + // Rows + const end = @min(self.y_offset + self.visible_rows, self.view_indices.items.len); + for (self.y_offset..end) |vi| { + if (vi > self.y_offset) writer.writeByte('\n') catch {}; + const ri = self.view_indices.items[vi]; + const row = self.rows.items[ri]; + const is_cursor = (vi == self.cursor_row and self.focused); + + for (0..num_cols) |c| { + if (c > 0) writer.writeAll(" \xe2\x94\x82 ") catch {}; + const cell = row[c]; + const s = if (is_cursor) self.cursor_row_style else self.cell_style; + const padded = padTo(allocator, cell, widths[c], self.col_aligns[c]); + writer.writeAll(s.render(allocator, padded) catch padded) catch {}; + } + } + + // Filter bar + if (self.filter_active or self.filter_text.items.len > 0) { + writer.writeAll("\n\nFilter: ") catch {}; + writer.writeAll(self.filter_text.items) catch {}; + if (self.filter_active) writer.writeByte('_') catch {}; + } + + // Count + writer.writeByte('\n') catch {}; + const count = std.fmt.allocPrint(allocator, " {d}/{d} rows", .{ self.view_indices.items.len, self.rows.items.len }) catch ""; + var cs = style_mod.Style{}; + cs = cs.fg(.gray(10)); + cs = cs.inline_style(true); + writer.writeAll(cs.render(allocator, count) catch count) catch {}; + + return result.toArrayList().items; + } + + fn padTo(allocator: std.mem.Allocator, text: []const u8, target: usize, alignment: Align) []const u8 { + if (text.len >= target) return text; + var buf = std.array_list.Managed(u8).init(allocator); + const pad = target - text.len; + switch (alignment) { + .left => { + buf.appendSlice(text) catch {}; + for (0..pad) |_| buf.append(' ') catch {}; + }, + .right => { + for (0..pad) |_| buf.append(' ') catch {}; + buf.appendSlice(text) catch {}; + }, + .center => { + const left = pad / 2; + for (0..left) |_| buf.append(' ') catch {}; + buf.appendSlice(text) catch {}; + for (0..pad - left) |_| buf.append(' ') catch {}; + }, + } + return buf.items; + } + + fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool { + if (needle.len > haystack.len) return false; + outer: for (0..haystack.len - needle.len + 1) |i| { + for (0..needle.len) |j| { + if (std.ascii.toLower(haystack[i + j]) != std.ascii.toLower(needle[j])) continue :outer; + } + return true; + } + return false; + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig new file mode 100644 index 0000000..aeb4ed6 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig @@ -0,0 +1,229 @@ +//! Sparkline component with configurable aggregation and styling. + +const std = @import("std"); +const Writer = std.Io.Writer; +const charting = @import("charting.zig"); +const progress = @import("progress.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Style = style_mod.Style; +pub const Summary = charting.Summary; +pub const DataRange = charting.DataRange; + +pub const Sparkline = struct { + allocator: std.mem.Allocator, + data: std.array_list.Managed(f64), + display_width: u16, + summary: Summary, + retention_limit: ?usize, + spark_style: Style, + empty_char: []const u8, + glyphs: []const []const u8, + fixed_range: ?DataRange, + gradient_start: ?Color, + gradient_end: ?Color, + + const default_glyphs = [_][]const u8{ " ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" }; + + pub fn init(allocator: std.mem.Allocator) Sparkline { + return .{ + .allocator = allocator, + .data = std.array_list.Managed(f64).init(allocator), + .display_width = 40, + .summary = .last, + .retention_limit = 40, + .spark_style = blk: { + var s = Style{}; + s = s.fg(.green); + break :blk charting.inlineStyle(s); + }, + .empty_char = " ", + .glyphs = default_glyphs[0..], + .fixed_range = null, + .gradient_start = null, + .gradient_end = null, + }; + } + + pub fn deinit(self: *Sparkline) void { + self.data.deinit(); + } + + pub fn push(self: *Sparkline, value: f64) !void { + try self.data.append(value); + self.enforceRetention(); + } + + pub fn setData(self: *Sparkline, data: []const f64) !void { + self.data.clearRetainingCapacity(); + try self.data.appendSlice(data); + self.enforceRetention(); + } + + pub fn clear(self: *Sparkline) void { + self.data.clearRetainingCapacity(); + } + + pub fn setWidth(self: *Sparkline, width: u16) void { + self.display_width = @max(1, width); + if (self.retention_limit) |limit| { + if (limit < self.display_width) { + self.retention_limit = self.display_width; + } + } + self.enforceRetention(); + } + + pub fn setSummary(self: *Sparkline, summary: Summary) void { + self.summary = summary; + } + + pub fn setRetentionLimit(self: *Sparkline, limit: ?usize) void { + self.retention_limit = if (limit) |value| @max(value, self.display_width) else null; + self.enforceRetention(); + } + + pub fn setStyle(self: *Sparkline, style: Style) void { + self.spark_style = charting.inlineStyle(style); + } + + pub fn setEmptyChar(self: *Sparkline, empty_char: []const u8) void { + self.empty_char = empty_char; + } + + pub fn setGlyphs(self: *Sparkline, glyphs: []const []const u8) void { + if (glyphs.len > 0) self.glyphs = glyphs; + } + + pub fn setRange(self: *Sparkline, range: ?DataRange) void { + self.fixed_range = if (range) |value| value.normalized() else null; + } + + pub fn setGradient(self: *Sparkline, start: ?Color, end: ?Color) void { + self.gradient_start = start; + self.gradient_end = end; + } + + pub fn view(self: *const Sparkline, allocator: std.mem.Allocator) ![]const u8 { + if (self.display_width == 0) return try allocator.dupe(u8, ""); + + var visible = try self.bucketValues(allocator); + defer visible.deinit(); + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + if (visible.items.len == 0) { + for (0..self.display_width) |_| try writer.writeAll(self.empty_char); + return try result.toOwnedSlice(); + } + + const range = self.fixed_range orelse self.computeRange(visible.items); + const glyph_count = self.glyphs.len; + const max_index = glyph_count - 1; + + for (visible.items, 0..) |value, index| { + const normalized = if (range.span() > 0) + charting.clampUnit((value - range.min) / range.span()) + else + 0.5; + + const glyph_index = @min(max_index, @as(usize, @intFromFloat(@round(normalized * @as(f64, @floatFromInt(max_index)))))); + const glyph = self.glyphs[glyph_index]; + + if (self.gradient_start != null and self.gradient_end != null) { + const t = if (visible.items.len <= 1) 0.0 else @as(f64, @floatFromInt(index)) / @as(f64, @floatFromInt(visible.items.len - 1)); + const color = progress.interpolateColor(self.gradient_start.?, self.gradient_end.?, t); + var style = self.spark_style.fg(color); + style = charting.inlineStyle(style); + const rendered = try style.render(allocator, glyph); + defer allocator.free(rendered); + try writer.writeAll(rendered); + } else { + const rendered = try self.spark_style.render(allocator, glyph); + defer allocator.free(rendered); + try writer.writeAll(rendered); + } + } + + if (visible.items.len < self.display_width) { + for (0..(@as(usize, self.display_width) - visible.items.len)) |_| { + try writer.writeAll(self.empty_char); + } + } + + return try result.toOwnedSlice(); + } + + fn enforceRetention(self: *Sparkline) void { + if (self.retention_limit) |limit| { + while (self.data.items.len > limit) { + _ = self.data.orderedRemove(0); + } + } + } + + fn bucketValues(self: *const Sparkline, allocator: std.mem.Allocator) !std.array_list.Managed(f64) { + var buckets = std.array_list.Managed(f64).init(allocator); + const width = @as(usize, self.display_width); + if (self.data.items.len == 0 or width == 0) return buckets; + + if (self.data.items.len <= width) { + try buckets.appendSlice(self.data.items); + return buckets; + } + + const data_len_f = @as(f64, @floatFromInt(self.data.items.len)); + const width_f = @as(f64, @floatFromInt(width)); + + for (0..width) |bucket_index| { + const start = @min(self.data.items.len, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(bucket_index)) * data_len_f / width_f)))); + const end = @min(self.data.items.len, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(bucket_index + 1)) * data_len_f / width_f)))); + const slice = if (end > start) self.data.items[start..end] else self.data.items[start..@min(self.data.items.len, start + 1)]; + try buckets.append(summarize(slice, self.summary)); + } + + return buckets; + } + + fn computeRange(self: *const Sparkline, values: []const f64) DataRange { + _ = self; + var min_value = values[0]; + var max_value = values[0]; + for (values[1..]) |value| { + min_value = @min(min_value, value); + max_value = @max(max_value, value); + } + const range = DataRange{ .min = min_value, .max = max_value }; + return range.normalized(); + } +}; + +fn summarize(values: []const f64, summary: Summary) f64 { + if (values.len == 0) return 0; + + return switch (summary) { + .last => values[values.len - 1], + .average => blk: { + var total: f64 = 0; + for (values) |value| total += value; + break :blk total / @as(f64, @floatFromInt(values.len)); + }, + .minimum => blk: { + var value = values[0]; + for (values[1..]) |item| value = @min(value, item); + break :blk value; + }, + .maximum => blk: { + var value = values[0]; + for (values[1..]) |item| value = @max(value, item); + break :blk value; + }, + .sum => blk: { + var total: f64 = 0; + for (values) |value| total += value; + break :blk total; + }, + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig new file mode 100644 index 0000000..1922b7e --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig @@ -0,0 +1,146 @@ +//! Animated loading spinner component. +//! Provides various spinner styles and customization options. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Spinner = struct { + // Spinner configuration + frames: []const []const u8, + frame_index: usize, + fps: u32, + + // Styling + spinner_style: style.Style, + + // State + last_tick: i64, + + /// Predefined spinner styles + pub const Styles = struct { + pub const line = &[_][]const u8{ "|", "/", "-", "\\" }; + pub const dots = &[_][]const u8{ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" }; + pub const dots2 = &[_][]const u8{ "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" }; + pub const dots3 = &[_][]const u8{ "⠋", "⠙", "⠚", "⠞", "⠖", "⠦", "⠴", "⠲", "⠳", "⠓" }; + pub const globe = &[_][]const u8{ "🌍", "🌎", "🌏" }; + pub const moon = &[_][]const u8{ "🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘" }; + pub const circle = &[_][]const u8{ "◐", "◓", "◑", "◒" }; + pub const square = &[_][]const u8{ "◰", "◳", "◲", "◱" }; + pub const arrow = &[_][]const u8{ "←", "↖", "↑", "↗", "→", "↘", "↓", "↙" }; + pub const bounce = &[_][]const u8{ "⠁", "⠂", "⠄", "⠂" }; + pub const box_bounce = &[_][]const u8{ "▖", "▘", "▝", "▗" }; + pub const triangle = &[_][]const u8{ "◢", "◣", "◤", "◥" }; + pub const arc = &[_][]const u8{ "◜", "◠", "◝", "◞", "◡", "◟" }; + pub const pipe = &[_][]const u8{ "┤", "┘", "┴", "└", "├", "┌", "┬", "┐" }; + pub const simple_dots = &[_][]const u8{ ". ", ".. ", "...", " ..", " .", " " }; + pub const pulse = &[_][]const u8{ "█", "▓", "▒", "░", "▒", "▓" }; + }; + + pub fn init() Spinner { + return .{ + .frames = Styles.dots, + .frame_index = 0, + .fps = 10, + .spinner_style = blk: { + var s = style.Style{}; + s = s.fg(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .last_tick = 0, + }; + } + + /// Set spinner frames + pub fn setFrames(self: *Spinner, frames: []const []const u8) void { + self.frames = frames; + self.frame_index = 0; + } + + /// Set spinner style + pub fn setStyle(self: *Spinner, s: style.Style) void { + self.spinner_style = s; + } + + /// Set frames per second + pub fn setFps(self: *Spinner, fps: u32) void { + self.fps = fps; + } + + /// Advance to next frame + pub fn tick(self: *Spinner) void { + self.frame_index = (self.frame_index + 1) % self.frames.len; + } + + /// Update based on elapsed time (in nanoseconds) + pub fn update(self: *Spinner, elapsed_ns: i64) bool { + const frame_ns = @as(i64, @intCast(std.time.ns_per_s / self.fps)); + + if (elapsed_ns - self.last_tick >= frame_ns) { + self.tick(); + self.last_tick = elapsed_ns; + return true; // Frame changed + } + return false; + } + + /// Get current frame + pub fn currentFrame(self: *const Spinner) []const u8 { + return self.frames[self.frame_index]; + } + + /// Render the spinner + pub fn view(self: *const Spinner, allocator: std.mem.Allocator) ![]const u8 { + return self.spinner_style.render(allocator, self.currentFrame()); + } + + /// Render spinner with title + pub fn viewWithTitle(self: *const Spinner, allocator: std.mem.Allocator, title: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const rendered_spinner = try self.view(allocator); + try writer.writeAll(rendered_spinner); + try writer.writeByte(' '); + try writer.writeAll(title); + + return result.toOwnedSlice(); + } +}; + +/// Create a spinner with the given style +pub fn newSpinner(frames: []const []const u8) Spinner { + var s = Spinner.init(); + s.setFrames(frames); + return s; +} + +/// Create a dots spinner +pub fn dots() Spinner { + return Spinner.init(); +} + +/// Create a line spinner +pub fn line() Spinner { + var s = Spinner.init(); + s.setFrames(Spinner.Styles.line); + return s; +} + +/// Create a globe spinner +pub fn globe() Spinner { + var s = Spinner.init(); + s.setFrames(Spinner.Styles.globe); + s.setFps(4); + return s; +} + +/// Create a moon spinner +pub fn moon() Spinner { + var s = Spinner.init(); + s.setFrames(Spinner.Styles.moon); + s.setFps(6); + return s; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig new file mode 100644 index 0000000..78e942c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/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(.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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig new file mode 100644 index 0000000..7d64a2c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig @@ -0,0 +1,215 @@ +//! 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 Writer = std.Io.Writer; +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(.gray(4)); + base = base.fg(.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: Writer.Allocating = .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, allocator, gap); + try writer.writeAll(center_str); + const consumed = lw + gap + cw; + const trailing = (self.width -| rw) -| consumed; + try self.writeGap(writer, allocator, trailing); + } else { + const gap = (self.width -| rw) -| lw; + try self.writeGap(writer, 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: Writer.Allocating = .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.Writer, 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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig new file mode 100644 index 0000000..1a3bafb --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig @@ -0,0 +1,254 @@ +//! 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 Writer = std.Io.Writer; +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(.green); + completed = completed.inline_style(true); + + var current = style_mod.Style{}; + current = current.fg(.cyan); + current = current.bold(true); + current = current.inline_style(true); + + var pending = style_mod.Style{}; + pending = pending.fg(.gray(8)); + pending = pending.inline_style(true); + + var connector = style_mod.Style{}; + connector = connector.fg(.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(.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: Writer.Allocating = .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: Writer.Allocating = .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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig new file mode 100644 index 0000000..8f9bec5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig @@ -0,0 +1,169 @@ +//! Styled list component for rendering lists with various enumerators. +//! Non-interactive rendering-only list with bullet, numbered, roman, alphabet enumerators. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +/// Enumerator type for list items +pub const EnumeratorType = enum { + bullet, + arabic, + roman, + alphabet, + dash, + asterisk, + none, +}; + +pub const StyledList = struct { + allocator: std.mem.Allocator, + items: std.array_list.Managed(ListItem), + enumerator_type: EnumeratorType, + item_style: style_mod.Style, + enumerator_style: style_mod.Style, + + pub const ListItem = struct { + text: []const u8, + depth: usize, + style_override: ?style_mod.Style, + }; + + pub fn init(allocator: std.mem.Allocator) StyledList { + return .{ + .allocator = allocator, + .items = std.array_list.Managed(ListItem).init(allocator), + .enumerator_type = .bullet, + .item_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .enumerator_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *StyledList) void { + self.items.deinit(); + } + + /// Add an item at depth 0 + pub fn addItem(self: *StyledList, text: []const u8) !void { + try self.items.append(.{ + .text = text, + .depth = 0, + .style_override = null, + }); + } + + /// Add an item at specified depth + pub fn addItemNested(self: *StyledList, text: []const u8, depth: usize) !void { + try self.items.append(.{ + .text = text, + .depth = depth, + .style_override = null, + }); + } + + /// Set the enumerator type + pub fn setEnumerator(self: *StyledList, e: EnumeratorType) void { + self.enumerator_type = e; + } + + /// Render the list + pub fn view(self: *const StyledList, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Track counters per depth level + var counters: [16]usize = .{0} ** 16; + + for (self.items.items, 0..) |item, i| { + if (i > 0) try writer.writeAll("\n"); + + // Reset deeper counters when going to a shallower depth + const depth = @min(item.depth, 15); + for (depth + 1..16) |d| { + counters[d] = 0; + } + counters[depth] += 1; + + // Indent + for (0..depth) |_| { + try writer.writeAll(" "); + } + + // Enumerator + const enum_str = try self.formatEnumerator(allocator, counters[depth]); + const styled_enum = try self.enumerator_style.render(allocator, enum_str); + try writer.writeAll(styled_enum); + + // Item text + const active_style = item.style_override orelse self.item_style; + const styled_text = try active_style.render(allocator, item.text); + try writer.writeAll(styled_text); + } + + return result.toOwnedSlice(); + } + + fn formatEnumerator(self: *const StyledList, allocator: std.mem.Allocator, counter: usize) ![]const u8 { + return switch (self.enumerator_type) { + .bullet => try allocator.dupe(u8, "\u{2022} "), + .arabic => try std.fmt.allocPrint(allocator, "{d}. ", .{counter}), + .roman => blk: { + const roman = try toRoman(allocator, counter); + break :blk try std.fmt.allocPrint(allocator, "{s}. ", .{roman}); + }, + .alphabet => blk: { + const alpha = try toAlpha(allocator, counter); + break :blk try std.fmt.allocPrint(allocator, "{s}. ", .{alpha}); + }, + .dash => try allocator.dupe(u8, "- "), + .asterisk => try allocator.dupe(u8, "* "), + .none => try allocator.dupe(u8, ""), + }; + } +}; + +/// Convert number to Roman numerals +pub fn toRoman(allocator: std.mem.Allocator, n: usize) ![]const u8 { + if (n == 0) return try allocator.dupe(u8, "0"); + + var result: std.array_list.Managed(u8) = .init(allocator); + + const values = [_]usize{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; + const symbols = [_][]const u8{ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; + + var num = n; + for (values, symbols) |val, sym| { + while (num >= val) { + try result.appendSlice(sym); + num -= val; + } + } + + return result.toOwnedSlice(); +} + +/// Convert number to alphabetical representation (1=a, 2=b, ..., 26=z, 27=aa) +pub fn toAlpha(allocator: std.mem.Allocator, n: usize) ![]const u8 { + if (n == 0) return try allocator.dupe(u8, "?"); + + var result: std.array_list.Managed(u8) = .init(allocator); + var num = n - 1; + + while (true) { + const c: u8 = @intCast('a' + @as(u8, @intCast(num % 26))); + try result.insert(0, c); + if (num < 26) break; + num = num / 26 - 1; + } + + return result.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig new file mode 100644 index 0000000..0c9f23a --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig @@ -0,0 +1,1066 @@ +//! Tab group and multi-view routing component. +//! Provides tab-strip rendering, key-driven navigation, and optional +//! type-erased view routing for multi-screen applications. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const measure = @import("../layout/measure.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +/// Maximum number of key bindings tracked per action. +const max_binds = 8; + +/// A single key binding (key + optional modifiers). +pub const KeyBind = struct { + key: keys.Key, + modifiers: keys.Modifiers = .{}, + + pub fn matches(self: KeyBind, event: keys.KeyEvent) bool { + return self.key.eql(event.key) and self.modifiers.eql(event.modifiers); + } +}; + +/// Default next-tab bindings: Right, Tab. +pub const default_next_keys = [max_binds]?KeyBind{ + .{ .key = .right }, + .{ .key = .tab }, + null, + null, + null, + null, + null, + null, +}; + +/// Default previous-tab bindings: Left, Shift+Tab. +pub const default_prev_keys = [max_binds]?KeyBind{ + .{ .key = .left }, + .{ .key = .tab, .modifiers = .{ .shift = true } }, + null, + null, + null, + null, + null, + null, +}; + +/// Default "first tab" bindings: Home. +pub const default_first_keys = [max_binds]?KeyBind{ + .{ .key = .home }, + null, + null, + null, + null, + null, + null, + null, +}; + +/// Default "last tab" bindings: End. +pub const default_last_keys = [max_binds]?KeyBind{ + .{ .key = .end }, + null, + null, + null, + null, + null, + null, + null, +}; + +/// Default activation bindings (manual activation mode): Enter, Space. +pub const default_activate_keys = [max_binds]?KeyBind{ + .{ .key = .enter }, + .{ .key = .space }, + null, + null, + null, + null, + null, + null, +}; + +/// Why active tab changed. +pub const ChangeReason = enum { + init, + set_active, + next, + prev, + first, + last, + number_shortcut, + activate, + remove, + disable, + hide, + clear, +}; + +pub const Change = struct { + previous: ?usize, + current: ?usize, + reason: ChangeReason, +}; + +/// Result of handling a key event. +pub const KeyResult = struct { + consumed: bool = false, + change: ?Change = null, + routed: bool = false, +}; + +/// Tab label rendering context. +pub const LabelState = struct { + index: usize, + active: bool, + focused: bool, + enabled: bool, + visible: bool, +}; + +pub const OverflowMode = enum { + /// Render all tabs (no clipping). + none, + /// Render all tabs then truncate final output. + clip, + /// Keep active/focused tab visible and show scroll markers. + scroll, +}; + +pub const LabelRenderer = *const fn (ctx: *anyopaque, allocator: std.mem.Allocator, tab: Tab, state: LabelState) anyerror![]const u8; +pub const RouteRenderer = *const fn (ctx: *anyopaque, allocator: std.mem.Allocator) anyerror![]const u8; +pub const RouteKeyHandler = *const fn (ctx: *anyopaque, event: keys.KeyEvent) bool; +pub const RouteHook = *const fn (ctx: *anyopaque) void; + +/// Optional route callbacks attached to a tab. +pub const Route = struct { + ctx: *anyopaque, + render_fn: RouteRenderer, + key_fn: ?RouteKeyHandler = null, + on_enter_fn: ?RouteHook = null, + on_leave_fn: ?RouteHook = null, +}; + +pub const Tab = struct { + id: []const u8, + title: []const u8, + short_title: ?[]const u8 = null, + enabled: bool = true, + visible: bool = true, + closable: bool = false, + route: ?Route = null, + user_data: ?*anyopaque = null, +}; + +/// Tab strip + multi-view routing container. +pub const TabGroup = struct { + allocator: std.mem.Allocator, + tabs: std.array_list.Managed(Tab), + + active_index: ?usize, + focus_index: ?usize, + + // Focus protocol compatibility + focused: bool = true, + + // Navigation behavior + wrap: bool = true, + activate_on_focus: bool = true, + number_shortcuts: bool = true, + focus_disabled_tabs: bool = false, + + // Key maps + next_keys: [max_binds]?KeyBind = default_next_keys, + prev_keys: [max_binds]?KeyBind = default_prev_keys, + first_keys: [max_binds]?KeyBind = default_first_keys, + last_keys: [max_binds]?KeyBind = default_last_keys, + activate_keys: [max_binds]?KeyBind = default_activate_keys, + + // Rendering options + bar_style: style_mod.Style, + tab_style: style_mod.Style, + active_tab_style: style_mod.Style, + focused_tab_style: style_mod.Style, + disabled_tab_style: style_mod.Style, + separator_style: style_mod.Style, + overflow_style: style_mod.Style, + + separator: []const u8 = " ", + tab_prefix: []const u8 = " ", + tab_suffix: []const u8 = " ", + show_numbers: bool = false, + number_separator: []const u8 = ":", + + max_width: ?usize = null, + overflow_mode: OverflowMode = .scroll, + overflow_left: []const u8 = "… ", + overflow_right: []const u8 = " …", + + label_renderer: ?LabelRenderer = null, + label_renderer_ctx: ?*anyopaque = null, + + const Self = @This(); + + pub fn init(allocator: std.mem.Allocator) Self { + var tab_style = style_mod.Style{}; + tab_style = tab_style.fg(.gray(15)); + tab_style = tab_style.inline_style(true); + + var active_style = style_mod.Style{}; + active_style = active_style.fg(.cyan); + active_style = active_style.bold(true); + active_style = active_style.inline_style(true); + + var focused_style = style_mod.Style{}; + focused_style = focused_style.fg(.yellow); + focused_style = focused_style.bold(true); + focused_style = focused_style.inline_style(true); + + var disabled_style = style_mod.Style{}; + disabled_style = disabled_style.fg(.gray(9)); + disabled_style = disabled_style.dim(true); + disabled_style = disabled_style.inline_style(true); + + var sep_style = style_mod.Style{}; + sep_style = sep_style.fg(.gray(11)); + sep_style = sep_style.inline_style(true); + + var overflow_style = style_mod.Style{}; + overflow_style = overflow_style.fg(.gray(12)); + overflow_style = overflow_style.inline_style(true); + + return .{ + .allocator = allocator, + .tabs = std.array_list.Managed(Tab).init(allocator), + .active_index = null, + .focus_index = null, + .bar_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .tab_style = tab_style, + .active_tab_style = active_style, + .focused_tab_style = focused_style, + .disabled_tab_style = disabled_style, + .separator_style = sep_style, + .overflow_style = overflow_style, + }; + } + + pub fn deinit(self: *Self) void { + self.tabs.deinit(); + } + + pub fn focus(self: *Self) void { + self.focused = true; + } + + pub fn blur(self: *Self) void { + self.focused = false; + } + + pub fn len(self: *const Self) usize { + return self.tabs.items.len; + } + + pub fn hasTabs(self: *const Self) bool { + return self.tabs.items.len > 0; + } + + pub fn clear(self: *Self) ?Change { + const prev = self.active_index; + self.leaveActiveRoute(); + self.tabs.clearRetainingCapacity(); + self.active_index = null; + self.focus_index = null; + if (prev == null) return null; + return .{ + .previous = prev, + .current = null, + .reason = .clear, + }; + } + + pub fn addTab(self: *Self, tab: Tab) !usize { + try self.tabs.append(tab); + const idx = self.tabs.items.len - 1; + + if (self.focus_index == null) self.focus_index = idx; + + if (self.active_index == null and self.isActivatableIndex(idx)) { + _ = self.setActive(idx, .init); + } + + return idx; + } + + pub fn insertTab(self: *Self, index: usize, tab: Tab) !void { + const idx = @min(index, self.tabs.items.len); + try self.tabs.insert(idx, tab); + + if (self.active_index) |active| { + if (active >= idx) self.active_index = active + 1; + } + if (self.focus_index) |focus_idx| { + if (focus_idx >= idx) self.focus_index = focus_idx + 1; + } + + if (self.focus_index == null) self.focus_index = idx; + if (self.active_index == null and self.isActivatableIndex(idx)) { + _ = self.setActive(idx, .init); + } + } + + pub fn removeTabAt(self: *Self, index: usize) ?Change { + if (index >= self.tabs.items.len) return null; + + const prev_active = self.active_index; + const removed_was_active = prev_active != null and prev_active.? == index; + + if (removed_was_active) { + self.leaveActiveRoute(); + self.active_index = null; + } + + _ = self.tabs.orderedRemove(index); + + if (self.tabs.items.len == 0) { + self.active_index = null; + self.focus_index = null; + if (prev_active == null) return null; + return .{ + .previous = prev_active, + .current = null, + .reason = .remove, + }; + } + + if (self.active_index) |active_idx| { + if (active_idx > index) self.active_index = active_idx - 1; + } + if (self.focus_index) |focus_idx| { + if (focus_idx > index) { + self.focus_index = focus_idx - 1; + } else if (focus_idx == index) { + self.focus_index = self.pickFallbackFocusIndex(index); + } + } else { + self.focus_index = self.firstVisibleIndex() orelse self.firstIndex(); + } + + if (removed_was_active) { + const fallback = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); + if (fallback) |new_active| { + return self.setActive(new_active, .remove); + } + self.active_index = null; + return .{ + .previous = prev_active, + .current = null, + .reason = .remove, + }; + } + + self.ensureValidSelection(); + return null; + } + + pub fn removeTabById(self: *Self, id: []const u8) ?Change { + const idx = self.indexOf(id) orelse return null; + return self.removeTabAt(idx); + } + + pub fn indexOf(self: *const Self, id: []const u8) ?usize { + for (self.tabs.items, 0..) |tab, i| { + if (std.mem.eql(u8, tab.id, id)) return i; + } + return null; + } + + pub fn getTab(self: *Self, index: usize) ?*Tab { + if (index >= self.tabs.items.len) return null; + return &self.tabs.items[index]; + } + + pub fn getTabConst(self: *const Self, index: usize) ?*const Tab { + if (index >= self.tabs.items.len) return null; + return &self.tabs.items[index]; + } + + pub fn activeIndex(self: *const Self) ?usize { + return self.active_index; + } + + pub fn focusedIndex(self: *const Self) ?usize { + return self.focus_index; + } + + pub fn activeTab(self: *const Self) ?*const Tab { + const idx = self.active_index orelse return null; + return &self.tabs.items[idx]; + } + + pub fn activeRoute(self: *const Self) ?Route { + const idx = self.active_index orelse return null; + return self.tabs.items[idx].route; + } + + pub fn isActive(self: *const Self, index: usize) bool { + return self.active_index != null and self.active_index.? == index; + } + + pub fn isFocused(self: *const Self, index: usize) bool { + return self.focus_index != null and self.focus_index.? == index; + } + + pub fn setLabelRenderer(self: *Self, ctx: *anyopaque, renderer: LabelRenderer) void { + self.label_renderer_ctx = ctx; + self.label_renderer = renderer; + } + + pub fn clearLabelRenderer(self: *Self) void { + self.label_renderer_ctx = null; + self.label_renderer = null; + } + + pub fn setRoute(self: *Self, index: usize, route: ?Route) void { + if (index >= self.tabs.items.len) return; + self.tabs.items[index].route = route; + } + + pub fn setEnabled(self: *Self, index: usize, enabled: bool) ?Change { + if (index >= self.tabs.items.len) return null; + self.tabs.items[index].enabled = enabled; + if (enabled) { + if (self.active_index == null and self.isActivatableIndex(index)) { + return self.setActive(index, .set_active); + } + return null; + } + + const was_active = self.active_index != null and self.active_index.? == index; + if (!was_active) return null; + + const next_idx = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); + if (next_idx) |i| { + return self.setActive(i, .disable); + } + + const prev = self.active_index; + self.leaveActiveRoute(); + self.active_index = null; + return .{ + .previous = prev, + .current = null, + .reason = .disable, + }; + } + + pub fn setVisible(self: *Self, index: usize, visible: bool) ?Change { + if (index >= self.tabs.items.len) return null; + self.tabs.items[index].visible = visible; + + if (!visible) { + const was_active = self.active_index != null and self.active_index.? == index; + if (was_active) { + const fallback = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); + if (fallback) |i| { + return self.setActive(i, .hide); + } + const prev = self.active_index; + self.leaveActiveRoute(); + self.active_index = null; + return .{ + .previous = prev, + .current = null, + .reason = .hide, + }; + } + + if (self.focus_index != null and self.focus_index.? == index) { + self.focus_index = self.pickFallbackFocusIndex(index) orelse self.firstVisibleIndex(); + } + } else if (self.focus_index == null) { + self.focus_index = index; + } + + self.ensureValidSelection(); + return null; + } + + pub fn setActive(self: *Self, index: usize, reason: ChangeReason) ?Change { + if (!self.isActivatableIndex(index)) return null; + + const prev = self.active_index; + if (prev != null and prev.? == index) { + self.focus_index = index; + return null; + } + + self.leaveRoute(prev); + self.active_index = index; + self.focus_index = index; + self.enterRoute(index); + + return .{ + .previous = prev, + .current = index, + .reason = reason, + }; + } + + pub fn setActiveById(self: *Self, id: []const u8, reason: ChangeReason) ?Change { + const idx = self.indexOf(id) orelse return null; + return self.setActive(idx, reason); + } + + pub fn focusTab(self: *Self, index: usize) bool { + if (index >= self.tabs.items.len) return false; + if (!self.tabs.items[index].visible) return false; + if (!self.focus_disabled_tabs and !self.tabs.items[index].enabled) return false; + self.focus_index = index; + return true; + } + + pub fn focusFirst(self: *Self) bool { + const idx = self.firstFocusableIndex() orelse return false; + self.focus_index = idx; + if (self.activate_on_focus) _ = self.setActive(idx, .first); + return true; + } + + pub fn focusLast(self: *Self) bool { + const idx = self.lastFocusableIndex() orelse return false; + self.focus_index = idx; + if (self.activate_on_focus) _ = self.setActive(idx, .last); + return true; + } + + pub fn focusNext(self: *Self) bool { + const start = self.focus_index orelse self.active_index orelse return self.focusFirst(); + const idx = self.findNextFocusable(start) orelse return false; + self.focus_index = idx; + if (self.activate_on_focus) _ = self.setActive(idx, .next); + return true; + } + + pub fn focusPrev(self: *Self) bool { + const start = self.focus_index orelse self.active_index orelse return self.focusLast(); + const idx = self.findPrevFocusable(start) orelse return false; + self.focus_index = idx; + if (self.activate_on_focus) _ = self.setActive(idx, .prev); + return true; + } + + pub fn activateFocused(self: *Self) ?Change { + const idx = self.focus_index orelse return null; + return self.setActive(idx, .activate); + } + + pub fn handleKey(self: *Self, event: keys.KeyEvent) KeyResult { + if (!self.focused) return .{}; + + if (self.matchAny(event, self.next_keys)) { + const prev = self.active_index; + if (self.focusNext()) { + return .{ + .consumed = true, + .change = self.diffChange(prev, .next), + }; + } + return .{ .consumed = true }; + } + if (self.matchAny(event, self.prev_keys)) { + const prev = self.active_index; + if (self.focusPrev()) { + return .{ + .consumed = true, + .change = self.diffChange(prev, .prev), + }; + } + return .{ .consumed = true }; + } + if (self.matchAny(event, self.first_keys)) { + const prev = self.active_index; + if (self.focusFirst()) { + return .{ + .consumed = true, + .change = self.diffChange(prev, .first), + }; + } + return .{ .consumed = true }; + } + if (self.matchAny(event, self.last_keys)) { + const prev = self.active_index; + if (self.focusLast()) { + return .{ + .consumed = true, + .change = self.diffChange(prev, .last), + }; + } + return .{ .consumed = true }; + } + + if (!self.activate_on_focus and self.matchAny(event, self.activate_keys)) { + return .{ + .consumed = true, + .change = self.activateFocused(), + }; + } + + if (self.number_shortcuts and !event.modifiers.any()) { + if (event.key == .char) { + const c = event.key.char; + if (c >= '1' and c <= '9') { + const ordinal: usize = @intCast(c - '1'); + if (self.setActiveByVisibleOrdinal(ordinal)) |chg| { + return .{ + .consumed = true, + .change = chg, + }; + } + return .{ .consumed = true }; + } + } + } + + return .{}; + } + + /// Handle tab navigation keys; if not consumed, forward key to active route. + pub fn handleKeyAndRoute(self: *Self, event: keys.KeyEvent) KeyResult { + var res = self.handleKey(event); + if (!res.consumed) { + res.routed = self.routeKey(event); + res.consumed = res.routed; + } + return res; + } + + /// Route a key event to active tab route (if it has a key handler). + pub fn routeKey(self: *Self, event: keys.KeyEvent) bool { + const idx = self.active_index orelse return false; + const route = self.tabs.items[idx].route orelse return false; + const key_fn = route.key_fn orelse return false; + return key_fn(route.ctx, event); + } + + /// Render only the tab strip. + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + return self.renderStrip(allocator); + } + + /// Render only the active route content (if any). + pub fn viewActiveContent(self: *const Self, allocator: std.mem.Allocator) !?[]const u8 { + const idx = self.active_index orelse return null; + const route = self.tabs.items[idx].route orelse return null; + return try route.render_fn(route.ctx, allocator); + } + + /// Render `tabs + content`, with optional fallback content when route is missing. + pub fn viewWithContent(self: *const Self, allocator: std.mem.Allocator, fallback_content: ?[]const u8) ![]const u8 { + const tabs = try self.renderStrip(allocator); + const content = (try self.viewActiveContent(allocator)) orelse fallback_content orelse ""; + + if (content.len == 0) return tabs; + return std.fmt.allocPrint(allocator, "{s}\n{s}", .{ tabs, content }); + } + + fn renderStrip(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var pieces = std.array_list.Managed([]const u8).init(allocator); + defer pieces.deinit(); + + var visible_indices = std.array_list.Managed(usize).init(allocator); + defer visible_indices.deinit(); + + for (self.tabs.items, 0..) |tab, i| { + if (tab.visible) try visible_indices.append(i); + } + + if (visible_indices.items.len == 0) return allocator.dupe(u8, ""); + + for (visible_indices.items) |tab_idx| { + const piece = try self.renderTabLabel(allocator, tab_idx); + try pieces.append(piece); + } + + const sep = try self.separator_style.render(allocator, self.separator); + + const strip = switch (self.overflow_mode) { + .none => try joinPieces(allocator, pieces.items, sep), + .clip => blk: { + const raw = try joinPieces(allocator, pieces.items, sep); + if (self.max_width) |w| { + break :blk try measure.truncate(allocator, raw, w); + } + break :blk raw; + }, + .scroll => try self.renderScrolledStrip(allocator, pieces.items, visible_indices.items, sep), + }; + + return self.bar_style.render(allocator, strip); + } + + fn renderScrolledStrip(self: *const Self, allocator: std.mem.Allocator, pieces: []const []const u8, visible_indices: []const usize, sep: []const u8) ![]const u8 { + const max_w = self.max_width orelse return joinPieces(allocator, pieces, sep); + + const total_w = joinedWidth(pieces, sep); + if (total_w <= max_w) return joinPieces(allocator, pieces, sep); + + const left_marker = try self.overflow_style.render(allocator, self.overflow_left); + const right_marker = try self.overflow_style.render(allocator, self.overflow_right); + const left_w = measure.width(left_marker); + const right_w = measure.width(right_marker); + + const target_tab_idx = self.focus_index orelse self.active_index orelse visible_indices[0]; + var target_pos: usize = 0; + for (visible_indices, 0..) |idx, i| { + if (idx == target_tab_idx) { + target_pos = i; + break; + } + } + + var start = target_pos; + var end = target_pos + 1; + + while (true) { + var grew = false; + + if (start > 0) { + const cand_start = start - 1; + const width = rangeWidthWithMarkers(pieces, sep, cand_start, end, left_w, right_w, cand_start > 0, end < pieces.len); + if (width <= max_w) { + start = cand_start; + grew = true; + } + } + + if (end < pieces.len) { + const cand_end = end + 1; + const width = rangeWidthWithMarkers(pieces, sep, start, cand_end, left_w, right_w, start > 0, cand_end < pieces.len); + if (width <= max_w) { + end = cand_end; + grew = true; + } + } + + if (!grew) break; + } + + var truncated_single: ?[]const u8 = null; + + // Degenerate case: marker + single tab still wider than max. + const single_range_w = rangeWidthWithMarkers(pieces, sep, start, end, left_w, right_w, start > 0, end < pieces.len); + if (single_range_w > max_w and end == start + 1) { + const reserved = (if (start > 0) left_w else 0) + (if (end < pieces.len) right_w else 0); + if (reserved < max_w) { + const allow = max_w - reserved; + truncated_single = try measure.truncate(allocator, pieces[start], allow); + } + } + + var out: Writer.Allocating = .init(allocator); + const writer = &out.writer; + + if (start > 0) try writer.writeAll(left_marker); + for (start..end) |i| { + if (i > start) try writer.writeAll(sep); + if (truncated_single != null and i == start) { + try writer.writeAll(truncated_single.?); + } else { + try writer.writeAll(pieces[i]); + } + } + if (end < pieces.len) try writer.writeAll(right_marker); + + return out.toOwnedSlice(); + } + + fn renderTabLabel(self: *const Self, allocator: std.mem.Allocator, tab_index: usize) ![]const u8 { + const tab = self.tabs.items[tab_index]; + const state = LabelState{ + .index = tab_index, + .active = self.isActive(tab_index), + .focused = self.isFocused(tab_index), + .enabled = tab.enabled, + .visible = tab.visible, + }; + + if (self.label_renderer) |renderer| { + const ctx = self.label_renderer_ctx orelse return error.MissingLabelRendererContext; + return renderer(ctx, allocator, tab, state); + } + + var base: Writer.Allocating = .init(allocator); + const writer = &base.writer; + + try writer.writeAll(self.tab_prefix); + if (self.show_numbers) { + const number = try std.fmt.allocPrint(allocator, "{d}{s}", .{ self.visibleOrdinal(tab_index) + 1, self.number_separator }); + try writer.writeAll(number); + } + try writer.writeAll(tab.title); + try writer.writeAll(self.tab_suffix); + + const raw = try base.toOwnedSlice(); + + if (!tab.enabled) return self.disabled_tab_style.render(allocator, raw); + if (state.active) return self.active_tab_style.render(allocator, raw); + if (!self.activate_on_focus and state.focused) return self.focused_tab_style.render(allocator, raw); + return self.tab_style.render(allocator, raw); + } + + fn setActiveByVisibleOrdinal(self: *Self, ordinal: usize) ?Change { + var seen: usize = 0; + for (self.tabs.items, 0..) |tab, i| { + if (!tab.visible or !tab.enabled) continue; + if (seen == ordinal) { + return self.setActive(i, .number_shortcut); + } + seen += 1; + } + return null; + } + + fn visibleOrdinal(self: *const Self, index: usize) usize { + var ordinal: usize = 0; + for (self.tabs.items, 0..) |tab, i| { + if (!tab.visible) continue; + if (i == index) return ordinal; + ordinal += 1; + } + return ordinal; + } + + fn ensureValidSelection(self: *Self) void { + if (self.tabs.items.len == 0) { + self.active_index = null; + self.focus_index = null; + return; + } + + if (self.active_index) |idx| { + if (!self.isActivatableIndex(idx)) { + const fallback = self.pickFallbackActiveIndex(idx) orelse self.firstActivatableIndex(); + if (fallback) |new_idx| { + _ = self.setActive(new_idx, .set_active); + } else { + self.active_index = null; + } + } + } else if (self.firstActivatableIndex()) |idx| { + _ = self.setActive(idx, .init); + } + + if (self.focus_index) |idx| { + if (!self.isFocusableIndex(idx)) { + self.focus_index = self.firstFocusableIndex() orelse self.firstVisibleIndex() orelse self.firstIndex(); + } + } else { + self.focus_index = self.firstFocusableIndex() orelse self.firstVisibleIndex() orelse self.firstIndex(); + } + } + + fn firstIndex(self: *const Self) ?usize { + if (self.tabs.items.len == 0) return null; + return 0; + } + + fn firstVisibleIndex(self: *const Self) ?usize { + for (self.tabs.items, 0..) |tab, i| { + if (tab.visible) return i; + } + return null; + } + + fn firstActivatableIndex(self: *const Self) ?usize { + for (self.tabs.items, 0..) |tab, i| { + if (tab.visible and tab.enabled) return i; + } + return null; + } + + fn firstFocusableIndex(self: *const Self) ?usize { + for (self.tabs.items, 0..) |tab, i| { + if (!tab.visible) continue; + if (!self.focus_disabled_tabs and !tab.enabled) continue; + return i; + } + return null; + } + + fn lastFocusableIndex(self: *const Self) ?usize { + if (self.tabs.items.len == 0) return null; + var i = self.tabs.items.len; + while (i > 0) { + i -= 1; + const tab = self.tabs.items[i]; + if (!tab.visible) continue; + if (!self.focus_disabled_tabs and !tab.enabled) continue; + return i; + } + return null; + } + + fn isActivatableIndex(self: *const Self, index: usize) bool { + if (index >= self.tabs.items.len) return false; + const tab = self.tabs.items[index]; + return tab.visible and tab.enabled; + } + + fn isFocusableIndex(self: *const Self, index: usize) bool { + if (index >= self.tabs.items.len) return false; + const tab = self.tabs.items[index]; + if (!tab.visible) return false; + if (!self.focus_disabled_tabs and !tab.enabled) return false; + return true; + } + + fn pickFallbackActiveIndex(self: *const Self, removed_index: usize) ?usize { + if (self.tabs.items.len == 0) return null; + + var i = removed_index; + while (i < self.tabs.items.len) : (i += 1) { + if (self.isActivatableIndex(i)) return i; + } + + i = removed_index; + while (i > 0) { + i -= 1; + if (self.isActivatableIndex(i)) return i; + } + + return null; + } + + fn pickFallbackFocusIndex(self: *const Self, removed_index: usize) ?usize { + if (self.tabs.items.len == 0) return null; + + var i = removed_index; + while (i < self.tabs.items.len) : (i += 1) { + if (self.isFocusableIndex(i)) return i; + } + + i = removed_index; + while (i > 0) { + i -= 1; + if (self.isFocusableIndex(i)) return i; + } + + return self.firstVisibleIndex(); + } + + fn findNextFocusable(self: *const Self, start: usize) ?usize { + if (self.tabs.items.len == 0) return null; + + var i = start + 1; + while (i < self.tabs.items.len) : (i += 1) { + if (self.isFocusableIndex(i)) return i; + } + + if (!self.wrap) return null; + + i = 0; + while (i <= start and i < self.tabs.items.len) : (i += 1) { + if (self.isFocusableIndex(i)) return i; + } + + return null; + } + + fn findPrevFocusable(self: *const Self, start: usize) ?usize { + if (self.tabs.items.len == 0) return null; + if (start > self.tabs.items.len - 1) return self.lastFocusableIndex(); + + var i = start; + while (i > 0) { + i -= 1; + if (self.isFocusableIndex(i)) return i; + } + + if (!self.wrap) return null; + + i = self.tabs.items.len; + while (i > start + 1) { + i -= 1; + if (self.isFocusableIndex(i)) return i; + } + + return null; + } + + fn diffChange(self: *Self, previous_active: ?usize, reason: ChangeReason) ?Change { + if (previous_active == self.active_index) return null; + return .{ + .previous = previous_active, + .current = self.active_index, + .reason = reason, + }; + } + + fn matchAny(_: *Self, event: keys.KeyEvent, binds: [max_binds]?KeyBind) bool { + for (binds) |maybe_bind| { + if (maybe_bind) |bind| { + if (bind.matches(event)) return true; + } + } + return false; + } + + fn leaveActiveRoute(self: *const Self) void { + self.leaveRoute(self.active_index); + } + + fn leaveRoute(self: *const Self, idx: ?usize) void { + if (idx) |i| { + if (i < self.tabs.items.len) { + if (self.tabs.items[i].route) |route| { + if (route.on_leave_fn) |f| f(route.ctx); + } + } + } + } + + fn enterRoute(self: *const Self, idx: usize) void { + if (idx >= self.tabs.items.len) return; + if (self.tabs.items[idx].route) |route| { + if (route.on_enter_fn) |f| f(route.ctx); + } + } +}; + +fn joinedWidth(parts: []const []const u8, separator: []const u8) usize { + if (parts.len == 0) return 0; + + const sep_w = measure.width(separator); + var w: usize = 0; + for (parts, 0..) |part, i| { + if (i > 0) w += sep_w; + w += measure.width(part); + } + return w; +} + +fn rangeWidthWithMarkers(parts: []const []const u8, separator: []const u8, start: usize, end: usize, left_marker_w: usize, right_marker_w: usize, show_left: bool, show_right: bool) usize { + const slice = parts[start..end]; + var w = joinedWidth(slice, separator); + if (show_left) w += left_marker_w; + if (show_right) w += right_marker_w; + return w; +} + +fn joinPieces(allocator: std.mem.Allocator, parts: []const []const u8, separator: []const u8) ![]const u8 { + if (parts.len == 0) return allocator.dupe(u8, ""); + + var out: Writer.Allocating = .init(allocator); + const writer = &out.writer; + for (parts, 0..) |part, i| { + if (i > 0) try writer.writeAll(separator); + try writer.writeAll(part); + } + return out.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig new file mode 100644 index 0000000..c65a196 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig @@ -0,0 +1,469 @@ +//! Table component for displaying tabular data. +//! Supports column headers, alignment, and styling. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const border_mod = @import("../style/border.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); +const keys = @import("../input/keys.zig"); + +pub fn Table(comptime num_cols: usize) type { + return struct { + allocator: std.mem.Allocator, + + // Data + headers: [num_cols][]const u8, + rows: std.array_list.Managed([num_cols][]const u8), + + // Appearance + col_widths: [num_cols]?u16, + col_aligns: [num_cols]Align, + border_chars: border_mod.BorderChars, + show_header: bool, + show_border: bool, + + // Styling + header_style: style_mod.Style, + cell_style: style_mod.Style, + border_style: style_mod.Style, + alt_row_style: ?style_mod.Style, + cursor_row_style: style_mod.Style, + + // Interactive state + cursor_row: usize, + focused: bool, + y_offset: usize, + visible_rows: u16, + + // Row borders + show_row_borders: bool, + + // Per-cell styling callback + style_func: ?*const fn (usize, usize) ?style_mod.Style, + + const Self = @This(); + + pub const Align = enum { + left, + center, + right, + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .headers = .{""} ** num_cols, + .rows = std.array_list.Managed([num_cols][]const u8).init(allocator), + .col_widths = .{null} ** num_cols, + .col_aligns = .{.left} ** num_cols, + .border_chars = .normal, + .show_header = true, + .show_border = true, + .header_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .cell_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .border_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .alt_row_style = null, + .cursor_row_style = blk2: { + var s2 = style_mod.Style{}; + s2 = s2.bold(true); + s2 = s2.reverse(true); + s2 = s2.inline_style(true); + break :blk2 s2; + }, + .cursor_row = 0, + .focused = false, + .y_offset = 0, + .visible_rows = 10, + .show_row_borders = false, + .style_func = null, + }; + } + + pub fn deinit(self: *Self) void { + self.rows.deinit(); + } + + /// Set column headers + pub fn setHeaders(self: *Self, headers: [num_cols][]const u8) void { + self.headers = headers; + } + + /// Add a row + pub fn addRow(self: *Self, row: [num_cols][]const u8) !void { + try self.rows.append(row); + } + + /// Add multiple rows + pub fn addRows(self: *Self, rows: []const [num_cols][]const u8) !void { + try self.rows.appendSlice(rows); + } + + /// Clear all rows + pub fn clearRows(self: *Self) void { + self.rows.clearRetainingCapacity(); + } + + /// Set column width + pub fn setColumnWidth(self: *Self, col: usize, width: u16) void { + if (col < num_cols) { + self.col_widths[col] = width; + } + } + + /// Set column alignment + pub fn setColumnAlign(self: *Self, col: usize, align_val: Align) void { + if (col < num_cols) { + self.col_aligns[col] = align_val; + } + } + + /// Set border style + pub fn setBorder(self: *Self, border: border_mod.BorderChars) void { + self.border_chars = border; + } + + /// Focus the table for interactive mode + pub fn focus(self: *Self) void { + self.focused = true; + } + + /// Blur the table + pub fn blur(self: *Self) void { + self.focused = false; + } + + /// Get the currently selected row index + pub fn selectedRow(self: *const Self) usize { + return self.cursor_row; + } + + /// Handle key event for navigation + pub fn handleKey(self: *Self, key: keys.KeyEvent) void { + if (!self.focused) return; + + switch (key.key) { + .up => { + if (self.cursor_row > 0) self.cursor_row -= 1; + self.ensureRowVisible(); + }, + .down => { + if (self.rows.items.len > 0 and self.cursor_row < self.rows.items.len - 1) { + self.cursor_row += 1; + } + self.ensureRowVisible(); + }, + .page_up => { + if (self.cursor_row >= self.visible_rows) { + self.cursor_row -= self.visible_rows; + } else { + self.cursor_row = 0; + } + self.ensureRowVisible(); + }, + .page_down => { + self.cursor_row += self.visible_rows; + if (self.rows.items.len > 0 and self.cursor_row >= self.rows.items.len) { + self.cursor_row = self.rows.items.len - 1; + } + self.ensureRowVisible(); + }, + .home => { + self.cursor_row = 0; + self.y_offset = 0; + }, + .end => { + if (self.rows.items.len > 0) { + self.cursor_row = self.rows.items.len - 1; + } + self.ensureRowVisible(); + }, + .char => |c| switch (c) { + 'j' => { + if (self.rows.items.len > 0 and self.cursor_row < self.rows.items.len - 1) { + self.cursor_row += 1; + } + self.ensureRowVisible(); + }, + 'k' => { + if (self.cursor_row > 0) self.cursor_row -= 1; + self.ensureRowVisible(); + }, + 'g' => { + self.cursor_row = 0; + self.y_offset = 0; + }, + 'G' => { + if (self.rows.items.len > 0) { + self.cursor_row = self.rows.items.len - 1; + } + self.ensureRowVisible(); + }, + else => {}, + }, + else => {}, + } + } + + fn ensureRowVisible(self: *Self) void { + if (self.cursor_row < self.y_offset) { + self.y_offset = self.cursor_row; + } else if (self.cursor_row >= self.y_offset + self.visible_rows) { + self.y_offset = self.cursor_row - self.visible_rows + 1; + } + } + + /// Calculate actual column widths + fn calculateWidths(self: *const Self) [num_cols]usize { + var widths: [num_cols]usize = .{0} ** num_cols; + + // Check headers + for (0..num_cols) |i| { + if (self.col_widths[i]) |w| { + widths[i] = w; + } else { + widths[i] = @max(widths[i], measure.width(self.headers[i])); + } + } + + // Check rows + for (self.rows.items) |row| { + for (0..num_cols) |i| { + if (self.col_widths[i] == null) { + widths[i] = @max(widths[i], measure.width(row[i])); + } + } + } + + return widths; + } + + /// Render the table + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const widths = self.calculateWidths(); + + // Top border + if (self.show_border) { + try self.writeBorderLine(writer, allocator, widths, .top); + try writer.writeByte('\n'); + } + + // Header + if (self.show_header) { + try self.writeRow(writer, allocator, self.headers, widths, self.header_style); + try writer.writeByte('\n'); + + // Header separator + if (self.show_border) { + try self.writeBorderLine(writer, allocator, widths, .middle); + try writer.writeByte('\n'); + } + } + + // Data rows (with viewport if focused) + const start_row = if (self.focused) self.y_offset else 0; + const end_row = if (self.focused) + @min(start_row + self.visible_rows, self.rows.items.len) + else + self.rows.items.len; + + for (start_row..end_row) |row_idx| { + const row = self.rows.items[row_idx]; + const row_style = if (self.focused and row_idx == self.cursor_row) + self.cursor_row_style + else if (self.style_func) |func| blk: { + if (func(row_idx, 0)) |s| { + break :blk s; + } + break :blk if (self.alt_row_style != null and row_idx % 2 == 1) + self.alt_row_style.? + else + self.cell_style; + } else if (self.alt_row_style != null and row_idx % 2 == 1) + self.alt_row_style.? + else + self.cell_style; + + try self.writeRow(writer, allocator, row, widths, row_style); + if (row_idx < end_row - 1 or self.show_border) { + try writer.writeByte('\n'); + } + + // Row borders between data rows + if (self.show_row_borders and row_idx < end_row - 1) { + try self.writeBorderLine(writer, allocator, widths, .middle); + try writer.writeByte('\n'); + } + } + + // Bottom border + if (self.show_border) { + try self.writeBorderLine(writer, allocator, widths, .bottom); + } + + return result.toOwnedSlice(); + } + + fn writeRow( + self: *const Self, + writer: *Writer, + allocator: std.mem.Allocator, + row: [num_cols][]const u8, + widths: [num_cols]usize, + row_style: style_mod.Style, + ) !void { + if (self.show_border) { + const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); + try writer.writeAll(border_rendered); + } + + for (0..num_cols) |i| { + if (i > 0 and self.show_border) { + const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); + try writer.writeAll(border_rendered); + } + + try writer.writeByte(' '); + + const cell = row[i]; + const width = widths[i]; + const cell_width = measure.width(cell); + const padding = if (width > cell_width) width - cell_width else 0; + + switch (self.col_aligns[i]) { + .left => { + const styled = try row_style.render(allocator, cell); + try writer.writeAll(styled); + for (0..padding) |_| try writer.writeByte(' '); + }, + .center => { + const left_pad = padding / 2; + const right_pad = padding - left_pad; + for (0..left_pad) |_| try writer.writeByte(' '); + const styled = try row_style.render(allocator, cell); + try writer.writeAll(styled); + for (0..right_pad) |_| try writer.writeByte(' '); + }, + .right => { + for (0..padding) |_| try writer.writeByte(' '); + const styled = try row_style.render(allocator, cell); + try writer.writeAll(styled); + }, + } + + try writer.writeByte(' '); + } + + if (self.show_border) { + const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); + try writer.writeAll(border_rendered); + } + } + + const BorderPosition = enum { top, middle, bottom }; + + fn writeBorderLine( + self: *const Self, + writer: *Writer, + allocator: std.mem.Allocator, + widths: [num_cols]usize, + pos: BorderPosition, + ) !void { + const left = switch (pos) { + .top => self.border_chars.top_left, + .middle => self.border_chars.middle_left, + .bottom => self.border_chars.bottom_left, + }; + const mid = switch (pos) { + .top => self.border_chars.middle_top, + .middle => self.border_chars.cross, + .bottom => self.border_chars.middle_bottom, + }; + const right = switch (pos) { + .top => self.border_chars.top_right, + .middle => self.border_chars.middle_right, + .bottom => self.border_chars.bottom_right, + }; + + const left_styled = try self.border_style.render(allocator, left); + try writer.writeAll(left_styled); + + for (0..num_cols) |i| { + if (i > 0) { + const mid_styled = try self.border_style.render(allocator, mid); + try writer.writeAll(mid_styled); + } + + const h_styled = try self.border_style.render(allocator, self.border_chars.horizontal); + for (0..widths[i] + 2) |_| { + try writer.writeAll(h_styled); + } + } + + const right_styled = try self.border_style.render(allocator, right); + try writer.writeAll(right_styled); + } + }; +} + +/// Create a table with dynamic column count +pub fn DynamicTable(allocator: std.mem.Allocator) DynamicTableType { + return DynamicTableType.init(allocator); +} + +pub const DynamicTableType = struct { + allocator: std.mem.Allocator, + headers: std.array_list.Managed([]const u8), + rows: std.array_list.Managed(std.array_list.Managed([]const u8)), + border_chars: border_mod.BorderChars, + show_header: bool, + show_border: bool, + + pub fn init(allocator: std.mem.Allocator) DynamicTableType { + return .{ + .allocator = allocator, + .headers = std.array_list.Managed([]const u8).init(allocator), + .rows = std.array_list.Managed(std.array_list.Managed([]const u8)).init(allocator), + .border_chars = .normal, + .show_header = true, + .show_border = true, + }; + } + + pub fn deinit(self: *DynamicTableType) void { + self.headers.deinit(); + for (self.rows.items) |*row| { + row.deinit(); + } + self.rows.deinit(); + } + + pub fn setHeaders(self: *DynamicTableType, headers: []const []const u8) !void { + self.headers.clearRetainingCapacity(); + try self.headers.appendSlice(headers); + } + + pub fn addRow(self: *DynamicTableType, cells: []const []const u8) !void { + var row = std.array_list.Managed([]const u8).init(self.allocator); + try row.appendSlice(cells); + try self.rows.append(row); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig new file mode 100644 index 0000000..1e969b8 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig @@ -0,0 +1,1057 @@ +//! Multi-line text area component. +//! Provides text editing with multiple lines, cursor navigation, and scrolling. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const unicode = @import("../unicode.zig"); + +pub const TextArea = struct { + allocator: std.mem.Allocator, + + // Content + lines: std.array_list.Managed(std.array_list.Managed(u8)), + + // Cursor position + cursor_row: usize, + cursor_col: usize, + + // Viewport + viewport_row: usize, + viewport_col: usize, + width: u16, + height: u16, + + // Appearance + placeholder: []const u8, + line_numbers: bool, + word_wrap: bool, + + // Styling + text_style: style_mod.Style, + cursor_style: style_mod.Style, + line_number_style: style_mod.Style, + placeholder_style: style_mod.Style, + + // State + focused: bool, + + // Limits + max_lines: ?usize, + max_cols: ?usize, + char_limit: ?usize, + + const WrappedSegment = struct { + start: usize, + end: usize, + is_last: bool, + }; + + const WrappedRow = struct { + line_idx: usize, + start: usize, + end: usize, + is_first_segment: bool, + }; + + const CursorWrappedSegment = struct { + current_start: usize, + current_end: usize, + prev_start: ?usize, + is_last: bool, + }; + + pub fn init(allocator: std.mem.Allocator) TextArea { + var lines = std.array_list.Managed(std.array_list.Managed(u8)).init(allocator); + lines.append(std.array_list.Managed(u8).init(allocator)) catch {}; + + return .{ + .allocator = allocator, + .lines = lines, + .cursor_row = 0, + .cursor_col = 0, + .viewport_row = 0, + .viewport_col = 0, + .width = 80, + .height = 10, + .placeholder = "", + .line_numbers = false, + .word_wrap = false, + .text_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style_mod.Style{}; + s = s.reverse(true); + s = s.inline_style(true); + break :blk s; + }, + .line_number_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .placeholder_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .focused = true, + .max_lines = null, + .max_cols = null, + .char_limit = null, + }; + } + + pub fn deinit(self: *TextArea) void { + for (self.lines.items) |*line| { + line.deinit(); + } + self.lines.deinit(); + } + + /// Set the content + pub fn setValue(self: *TextArea, text: []const u8) !void { + // Clear existing lines + for (self.lines.items) |*line| { + line.deinit(); + } + self.lines.clearRetainingCapacity(); + + // Parse lines + var iter = std.mem.splitScalar(u8, text, '\n'); + while (iter.next()) |line_text| { + var line = std.array_list.Managed(u8).init(self.allocator); + try line.appendSlice(line_text); + try self.lines.append(line); + } + + if (self.lines.items.len == 0) { + try self.lines.append(std.array_list.Managed(u8).init(self.allocator)); + } + + // Reset cursor + self.cursor_row = 0; + self.cursor_col = 0; + self.viewport_row = 0; + } + + /// Get the content as a string + pub fn getValue(self: *const TextArea, allocator: std.mem.Allocator) ![]const u8 { + var result: std.array_list.Managed(u8) = .init(allocator); + + for (self.lines.items, 0..) |line, i| { + if (i > 0) try result.append('\n'); + try result.appendSlice(line.items); + } + + return result.toOwnedSlice(); + } + + /// Get total character count + pub fn charCount(self: *const TextArea) usize { + var count: usize = 0; + for (self.lines.items, 0..) |line, i| { + if (i > 0) count += 1; // Newline + count += line.items.len; + } + return count; + } + + /// Get line count + pub fn lineCount(self: *const TextArea) usize { + return self.lines.items.len; + } + + /// Set dimensions + pub fn setSize(self: *TextArea, width: u16, height: u16) void { + self.width = width; + self.height = height; + self.ensureVisible(); + } + + /// Focus the text area + pub fn focus(self: *TextArea) void { + self.focused = true; + } + + /// Blur the text area + pub fn blur(self: *TextArea) void { + self.focused = false; + } + + /// Handle key event + pub fn handleKey(self: *TextArea, key: keys.KeyEvent) void { + if (!self.focused) return; + + if (key.modifiers.ctrl) { + switch (key.key) { + .char => |c| switch (c) { + 'a' => self.cursor_col = 0, // Home + 'e' => self.cursor_col = self.currentLine().items.len, // End + 'k' => self.killToEndOfLine(), // Kill line + 'u' => self.killToStartOfLine(), // Kill to start + 'd' => self.deleteLine(), // Delete line + else => {}, + }, + else => {}, + } + return; + } + + switch (key.key) { + .char => |c| self.insertChar(c), + .paste => |text| self.insertText(text), + .enter => self.insertNewline(), + .backspace => self.deleteBackward(), + .delete => self.deleteForward(), + .up => self.moveCursorUp(), + .down => self.moveCursorDown(), + .left => self.moveCursorLeft(), + .right => self.moveCursorRight(), + .home => self.cursor_col = 0, + .end => self.cursor_col = self.currentLine().items.len, + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .tab => self.insertTab(), + else => {}, + } + + self.ensureVisible(); + } + + fn currentLine(self: *TextArea) *std.array_list.Managed(u8) { + return &self.lines.items[self.cursor_row]; + } + + fn insertChar(self: *TextArea, c: u21) void { + // Check char limit + if (self.char_limit) |limit| { + if (self.charCount() >= limit) return; + } + + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch return; + + const line = self.currentLine(); + const pos = @min(self.cursor_col, line.items.len); + line.insertSlice(pos, buf[0..len]) catch return; + self.cursor_col = pos + len; + } + + fn insertText(self: *TextArea, text: []const u8) void { + var i: usize = 0; + while (i < text.len) { + if (text[i] == '\r') { + self.insertNewline(); + if (i + 1 < text.len and text[i + 1] == '\n') i += 1; + i += 1; + continue; + } + if (text[i] == '\n') { + self.insertNewline(); + i += 1; + continue; + } + + const len = std.unicode.utf8ByteSequenceLength(text[i]) catch { + self.insertChar(text[i]); + i += 1; + continue; + }; + if (i + len > text.len) { + self.insertChar(text[i]); + i += 1; + continue; + } + + const codepoint = std.unicode.utf8Decode(text[i .. i + len]) catch { + self.insertChar(text[i]); + i += 1; + continue; + }; + self.insertChar(codepoint); + i += len; + } + } + + fn insertNewline(self: *TextArea) void { + if (self.max_lines) |max| { + if (self.lines.items.len >= max) return; + } + + self.clampCursorToLineBoundary(); + const line = self.currentLine(); + const rest = line.items[self.cursor_col..]; + + // Create new line with rest of content + var new_line = std.array_list.Managed(u8).init(self.allocator); + new_line.appendSlice(rest) catch return; + + // Truncate current line + line.shrinkRetainingCapacity(self.cursor_col); + + // Insert new line + self.lines.insert(self.cursor_row + 1, new_line) catch return; + + self.cursor_row += 1; + self.cursor_col = 0; + } + + fn insertTab(self: *TextArea) void { + // Insert spaces for tab + for (0..4) |_| { + self.insertChar(' '); + } + } + + fn deleteBackward(self: *TextArea) void { + if (self.cursor_col > 0) { + // Delete character before cursor + const line = self.currentLine(); + var pos = self.cursor_col - 1; + + // Find start of UTF-8 sequence + while (pos > 0 and (line.items[pos] & 0xC0) == 0x80) { + pos -= 1; + } + + const len = self.cursor_col - pos; + for (0..len) |_| { + _ = line.orderedRemove(pos); + } + self.cursor_col = pos; + } else if (self.cursor_row > 0) { + // Join with previous line + const current = self.lines.orderedRemove(self.cursor_row); + self.cursor_row -= 1; + const prev_line = self.currentLine(); + self.cursor_col = prev_line.items.len; + prev_line.appendSlice(current.items) catch {}; + @constCast(¤t).deinit(); + } + } + + fn deleteForward(self: *TextArea) void { + const line = self.currentLine(); + self.clampCursorToLineBoundary(); + if (self.cursor_col < line.items.len) { + // Delete character at cursor + const byte_len = std.unicode.utf8ByteSequenceLength(line.items[self.cursor_col]) catch 1; + for (0..byte_len) |_| { + if (self.cursor_col < line.items.len) { + _ = line.orderedRemove(self.cursor_col); + } + } + } else if (self.cursor_row < self.lines.items.len - 1) { + // Join with next line + const next = self.lines.orderedRemove(self.cursor_row + 1); + line.appendSlice(next.items) catch {}; + @constCast(&next).deinit(); + } + } + + fn killToEndOfLine(self: *TextArea) void { + self.clampCursorToLineBoundary(); + const line = self.currentLine(); + line.shrinkRetainingCapacity(self.cursor_col); + } + + fn killToStartOfLine(self: *TextArea) void { + self.clampCursorToLineBoundary(); + const line = self.currentLine(); + std.mem.copyForwards(u8, line.items[0..], line.items[self.cursor_col..]); + line.shrinkRetainingCapacity(line.items.len - self.cursor_col); + self.cursor_col = 0; + } + + fn deleteLine(self: *TextArea) void { + if (self.lines.items.len > 1) { + var removed = self.lines.orderedRemove(self.cursor_row); + removed.deinit(); + if (self.cursor_row >= self.lines.items.len) { + self.cursor_row = self.lines.items.len - 1; + } + self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); + self.clampCursorToLineBoundary(); + } else { + self.currentLine().clearRetainingCapacity(); + self.cursor_col = 0; + } + } + + fn moveCursorUp(self: *TextArea) void { + if (self.word_wrap) { + const max_width = self.textWidth(); + const line = self.currentLine().items; + const segment = self.findCursorWrappedSegment(line, max_width); + const target_col = displayWidthInRange(line, segment.current_start, self.cursor_col, max_width); + + if (segment.prev_start) |prev_start| { + const prev = wrappedSegmentAt(line, max_width, prev_start); + self.cursor_col = byteOffsetForDisplayCol(line, prev.start, prev.end, target_col, max_width); + return; + } + + if (self.cursor_row > 0) { + self.cursor_row -= 1; + const prev_line = self.currentLine().items; + const prev_start = lastWrappedSegmentStart(prev_line, max_width); + const prev = wrappedSegmentAt(prev_line, max_width, prev_start); + self.cursor_col = byteOffsetForDisplayCol(prev_line, prev.start, prev.end, target_col, max_width); + } + return; + } + + if (self.cursor_row > 0) { + self.cursor_row -= 1; + self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); + self.clampCursorToLineBoundary(); + } + } + + fn moveCursorDown(self: *TextArea) void { + if (self.word_wrap) { + const max_width = self.textWidth(); + const line = self.currentLine().items; + const segment = self.findCursorWrappedSegment(line, max_width); + const target_col = displayWidthInRange(line, segment.current_start, self.cursor_col, max_width); + + if (!segment.is_last) { + const next = wrappedSegmentAt(line, max_width, segment.current_end); + self.cursor_col = byteOffsetForDisplayCol(line, next.start, next.end, target_col, max_width); + return; + } + + if (self.cursor_row < self.lines.items.len - 1) { + self.cursor_row += 1; + const next_line = self.currentLine().items; + const next = wrappedSegmentAt(next_line, max_width, 0); + self.cursor_col = byteOffsetForDisplayCol(next_line, next.start, next.end, target_col, max_width); + } + return; + } + + if (self.cursor_row < self.lines.items.len - 1) { + self.cursor_row += 1; + self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); + self.clampCursorToLineBoundary(); + } + } + + fn moveCursorLeft(self: *TextArea) void { + self.clampCursorToLineBoundary(); + if (self.cursor_col > 0) { + self.cursor_col -= 1; + // Handle UTF-8 continuation bytes + const line = self.currentLine(); + while (self.cursor_col > 0 and (line.items[self.cursor_col] & 0xC0) == 0x80) { + self.cursor_col -= 1; + } + } else if (self.cursor_row > 0) { + self.cursor_row -= 1; + self.cursor_col = self.currentLine().items.len; + } + } + + fn moveCursorRight(self: *TextArea) void { + const line = self.currentLine(); + self.clampCursorToLineBoundary(); + if (self.cursor_col < line.items.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(line.items[self.cursor_col]) catch 1; + self.cursor_col = @min(self.cursor_col + byte_len, line.items.len); + } else if (self.cursor_row < self.lines.items.len - 1) { + self.cursor_row += 1; + self.cursor_col = 0; + } + } + + fn pageUp(self: *TextArea) void { + if (self.word_wrap) { + for (0..@max(@as(usize, 1), @as(usize, self.height))) |_| { + self.moveCursorUp(); + } + return; + } + + if (self.cursor_row >= self.height) { + self.cursor_row -= self.height; + } else { + self.cursor_row = 0; + } + self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); + self.clampCursorToLineBoundary(); + } + + fn pageDown(self: *TextArea) void { + if (self.word_wrap) { + for (0..@max(@as(usize, 1), @as(usize, self.height))) |_| { + self.moveCursorDown(); + } + return; + } + + if (self.cursor_row + self.height < self.lines.items.len) { + self.cursor_row += self.height; + } else { + self.cursor_row = self.lines.items.len - 1; + } + self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); + self.clampCursorToLineBoundary(); + } + + fn ensureVisible(self: *TextArea) void { + const visible_rows: usize = @max(@as(usize, 1), @as(usize, self.height)); + + if (self.word_wrap) { + const cursor_visual_row = self.cursorVisualRow(self.textWidth()); + if (cursor_visual_row < self.viewport_row) { + self.viewport_row = cursor_visual_row; + } else if (cursor_visual_row >= self.viewport_row + visible_rows) { + self.viewport_row = cursor_visual_row - visible_rows + 1; + } + self.viewport_col = 0; + return; + } + + // Vertical scrolling + if (self.cursor_row < self.viewport_row) { + self.viewport_row = self.cursor_row; + } else if (self.cursor_row >= self.viewport_row + visible_rows) { + self.viewport_row = self.cursor_row - visible_rows + 1; + } + + // Horizontal scrolling using display columns + const effective_width = self.width -| (if (self.line_numbers) @as(u16, 5) else 0); + const display_col = self.cursorDisplayCol(); + if (display_col < self.viewport_col) { + self.viewport_col = display_col; + } else if (display_col >= self.viewport_col + effective_width) { + self.viewport_col = display_col - effective_width + 1; + } + } + + /// Cursor column in terminal cells (display width), 0-indexed. + pub fn cursorDisplayColumn(self: *const TextArea) usize { + return self.cursorDisplayCol(); + } + + /// Render the text area + pub fn view(self: *const TextArea, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const line_num_width: usize = if (self.line_numbers) 5 else 0; + const text_width = self.width -| @as(u16, @intCast(line_num_width)); + + // Check for empty content + const is_empty = self.lines.items.len == 1 and self.lines.items[0].items.len == 0; + + if (self.word_wrap) { + for (0..self.height) |row| { + if (row > 0) try writer.writeByte('\n'); + + const visual_row = self.viewport_row + row; + const wrapped_row = self.wrappedRowAt(visual_row, text_width); + + // Line numbers (only on first wrapped segment of a physical line) + if (self.line_numbers) { + if (wrapped_row) |r| { + if (r.is_first_segment) { + const num_str = try std.fmt.allocPrint(allocator, "{d:>4} ", .{r.line_idx + 1}); + defer allocator.free(num_str); + const styled = try self.line_number_style.render(allocator, num_str); + defer allocator.free(styled); + try writer.writeAll(styled); + } else { + try writer.writeAll(" "); + } + } else { + try writer.writeAll(" "); + } + } + + if (wrapped_row) |r| { + const line = self.lines.items[r.line_idx]; + + // Show placeholder on first empty line + if (is_empty and r.line_idx == 0 and r.is_first_segment and self.placeholder.len > 0) { + try self.renderPlaceholder(writer, allocator, text_width); + continue; + } + + try self.renderWrappedLineSegment( + writer, + allocator, + line.items, + r.line_idx, + r.start, + r.end, + text_width, + ); + } else { + for (0..text_width) |_| { + try writer.writeByte(' '); + } + } + } + + return result.toOwnedSlice(); + } + + for (0..self.height) |row| { + if (row > 0) try writer.writeByte('\n'); + + const line_idx = self.viewport_row + row; + + // Line numbers + if (self.line_numbers) { + if (line_idx < self.lines.items.len) { + const num_str = try std.fmt.allocPrint(allocator, "{d:>4} ", .{line_idx + 1}); + defer allocator.free(num_str); + const styled = try self.line_number_style.render(allocator, num_str); + defer allocator.free(styled); + try writer.writeAll(styled); + } else { + try writer.writeAll(" "); + } + } + + if (line_idx < self.lines.items.len) { + const line = self.lines.items[line_idx]; + + // Show placeholder on first empty line + if (is_empty and line_idx == 0 and self.placeholder.len > 0) { + try self.renderPlaceholder(writer, allocator, text_width); + continue; + } + + // Render line content with cursor + try self.renderLine(writer, allocator, line.items, line_idx, text_width); + } else { + // Pad empty rows to full width + var i: usize = 0; + while (i < text_width) : (i += 1) { + try writer.writeByte(' '); + } + } + } + + return result.toOwnedSlice(); + } + + fn renderPlaceholder(self: *const TextArea, writer: *Writer, allocator: std.mem.Allocator, max_width: u16) !void { + const width_limit: usize = max_width; + if (width_limit == 0) return; + + var rendered_width: usize = 0; + var byte_idx: usize = 0; + while (byte_idx < self.placeholder.len and rendered_width < width_limit) { + const byte_len = std.unicode.utf8ByteSequenceLength(self.placeholder[byte_idx]) catch 1; + if (byte_idx + byte_len > self.placeholder.len) break; + const char_slice = self.placeholder[byte_idx..][0..byte_len]; + + const cp = std.unicode.utf8Decode(char_slice) catch { + byte_idx += 1; + rendered_width += 1; + continue; + }; + const cw = wrapDisplayWidth(unicode.charWidth(cp), width_limit); + if (rendered_width + cw > width_limit) break; + + const styled = try self.placeholder_style.render(allocator, char_slice); + defer allocator.free(styled); + try writer.writeAll(styled); + byte_idx += byte_len; + rendered_width += cw; + } + + while (rendered_width < width_limit) { + try writer.writeByte(' '); + rendered_width += 1; + } + } + + fn renderWrappedLineSegment( + self: *const TextArea, + writer: *Writer, + allocator: std.mem.Allocator, + line: []const u8, + line_idx: usize, + start: usize, + end: usize, + max_width: u16, + ) !void { + const is_cursor_line = line_idx == self.cursor_row; + const width_limit: usize = max_width; + + if (width_limit == 0) return; + + var rendered_width: usize = 0; + var byte_idx = start; + while (byte_idx < end and rendered_width < width_limit) { + const is_cursor = is_cursor_line and self.focused and byte_idx == self.cursor_col; + + const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; + if (byte_idx + byte_len > line.len) break; + const char_slice = line[byte_idx..][0..byte_len]; + + const cp = std.unicode.utf8Decode(char_slice) catch { + byte_idx += 1; + rendered_width += 1; + continue; + }; + const cw = wrapDisplayWidth(unicode.charWidth(cp), width_limit); + if (rendered_width + cw > width_limit) break; + + if (is_cursor) { + const styled = try self.cursor_style.render(allocator, char_slice); + defer allocator.free(styled); + try writer.writeAll(styled); + } else { + const styled = try self.text_style.render(allocator, char_slice); + defer allocator.free(styled); + try writer.writeAll(styled); + } + + byte_idx += byte_len; + rendered_width += cw; + } + + // Cursor at segment end + if (is_cursor_line and self.focused and self.cursor_col == end and end == line.len and rendered_width < width_limit) { + const styled = try self.cursor_style.render(allocator, " "); + defer allocator.free(styled); + try writer.writeAll(styled); + rendered_width += 1; + } + + while (rendered_width < width_limit) { + try writer.writeByte(' '); + rendered_width += 1; + } + } + + fn renderLine(self: *const TextArea, writer: *Writer, allocator: std.mem.Allocator, line: []const u8, line_idx: usize, max_width: u16) !void { + const is_cursor_line = line_idx == self.cursor_row; + + // Apply horizontal scroll + var col: usize = 0; + var byte_idx: usize = 0; + + // Skip to viewport_col (using display columns) + while (col < self.viewport_col and byte_idx < line.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; + if (byte_idx + byte_len <= line.len) { + const cp = std.unicode.utf8Decode(line[byte_idx..][0..byte_len]) catch { + byte_idx += 1; + col += 1; + continue; + }; + col += unicode.charWidth(cp); + } + byte_idx += byte_len; + } + + // Render visible portion + var rendered_width: usize = 0; + while (byte_idx < line.len and rendered_width < max_width) { + const is_cursor = is_cursor_line and self.focused and byte_idx == self.cursor_col; + + const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; + if (byte_idx + byte_len > line.len) break; + const char_slice = line[byte_idx..][0..byte_len]; + + const cp = std.unicode.utf8Decode(line[byte_idx..][0..byte_len]) catch { + byte_idx += 1; + rendered_width += 1; + continue; + }; + const cw = unicode.charWidth(cp); + + // Wide char won't fit — stop + if (rendered_width + cw > max_width) break; + + if (is_cursor) { + const styled = try self.cursor_style.render(allocator, char_slice); + defer allocator.free(styled); + try writer.writeAll(styled); + } else { + const styled = try self.text_style.render(allocator, char_slice); + defer allocator.free(styled); + try writer.writeAll(styled); + } + + byte_idx += byte_len; + col += cw; + rendered_width += cw; + } + + // Cursor at end of line + if (is_cursor_line and self.focused and byte_idx == self.cursor_col and rendered_width < max_width) { + const styled = try self.cursor_style.render(allocator, " "); + defer allocator.free(styled); + try writer.writeAll(styled); + rendered_width += 1; + } + + // Pad remaining width + while (rendered_width < max_width) { + try writer.writeByte(' '); + rendered_width += 1; + } + } + + /// Convert byte-offset cursor_col to display column width. + fn cursorDisplayCol(self: *const TextArea) usize { + const line = self.lines.items[self.cursor_row]; + var display_col: usize = 0; + var byte_idx: usize = 0; + while (byte_idx < self.cursor_col and byte_idx < line.items.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(line.items[byte_idx]) catch 1; + if (byte_idx + byte_len <= line.items.len) { + const cp = std.unicode.utf8Decode(line.items[byte_idx..][0..byte_len]) catch { + byte_idx += 1; + display_col += 1; + continue; + }; + display_col += unicode.charWidth(cp); + } + byte_idx += byte_len; + } + return display_col; + } + + fn textWidth(self: *const TextArea) usize { + const line_num_width: usize = if (self.line_numbers) 5 else 0; + return self.width -| @as(u16, @intCast(line_num_width)); + } + + fn cursorVisualRow(self: *const TextArea, max_width: usize) usize { + var row: usize = 0; + for (0..self.cursor_row) |idx| { + row += wrappedRowCount(self.lines.items[idx].items, max_width); + } + row += wrappedRowIndexForCursor(self.lines.items[self.cursor_row].items, self.cursor_col, max_width); + return row; + } + + fn wrappedRowAt(self: *const TextArea, visual_row: usize, max_width: u16) ?WrappedRow { + var row_index: usize = 0; + const width: usize = max_width; + + for (self.lines.items, 0..) |line, line_idx| { + const line_bytes = line.items; + if (line_bytes.len == 0) { + if (row_index == visual_row) { + return .{ + .line_idx = line_idx, + .start = 0, + .end = 0, + .is_first_segment = true, + }; + } + row_index += 1; + continue; + } + + var segment_start: usize = 0; + var first = true; + while (true) { + const segment = wrappedSegmentAt(line_bytes, width, segment_start); + if (row_index == visual_row) { + return .{ + .line_idx = line_idx, + .start = segment.start, + .end = segment.end, + .is_first_segment = first, + }; + } + + row_index += 1; + if (segment.is_last) break; + segment_start = segment.end; + first = false; + } + } + return null; + } + + fn findCursorWrappedSegment(self: *const TextArea, line: []const u8, max_width: usize) CursorWrappedSegment { + const clamped_cursor = clampToUtf8Boundary(line, self.cursor_col); + var segment_start: usize = 0; + var prev_start: ?usize = null; + while (true) { + const segment = wrappedSegmentAt(line, max_width, segment_start); + if (clamped_cursor < segment.end or segment.is_last) { + return .{ + .current_start = segment.start, + .current_end = segment.end, + .prev_start = prev_start, + .is_last = segment.is_last, + }; + } + + if (segment.is_last) break; + prev_start = segment_start; + segment_start = segment.end; + } + + return .{ + .current_start = 0, + .current_end = line.len, + .prev_start = null, + .is_last = true, + }; + } + + fn wrappedRowCount(line: []const u8, max_width: usize) usize { + if (line.len == 0) return 1; + if (max_width == 0) return 1; + + var count: usize = 0; + var segment_start: usize = 0; + while (true) { + const segment = wrappedSegmentAt(line, max_width, segment_start); + count += 1; + if (segment.is_last) break; + segment_start = segment.end; + } + return count; + } + + fn wrappedRowIndexForCursor(line: []const u8, cursor_col: usize, max_width: usize) usize { + if (line.len == 0) return 0; + if (max_width == 0) return 0; + + const clamped_cursor = clampToUtf8Boundary(line, cursor_col); + var index: usize = 0; + var segment_start: usize = 0; + while (true) { + const segment = wrappedSegmentAt(line, max_width, segment_start); + if (clamped_cursor < segment.end or segment.is_last) return index; + if (segment.is_last) return index; + index += 1; + segment_start = segment.end; + } + } + + fn lastWrappedSegmentStart(line: []const u8, max_width: usize) usize { + if (line.len == 0 or max_width == 0) return 0; + var segment_start: usize = 0; + while (true) { + const segment = wrappedSegmentAt(line, max_width, segment_start); + if (segment.is_last) return segment_start; + segment_start = segment.end; + } + } + + fn wrappedSegmentAt(line: []const u8, max_width: usize, start: usize) WrappedSegment { + if (line.len == 0 or max_width == 0 or start >= line.len) { + return .{ + .start = @min(start, line.len), + .end = @min(start, line.len), + .is_last = true, + }; + } + + var i = start; + var segment_width: usize = 0; + + while (i < line.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; + if (i + byte_len > line.len) break; + + const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { + if (segment_width > 0 and segment_width + 1 > max_width) break; + segment_width += 1; + i += 1; + continue; + }; + + const char_width = wrapDisplayWidth(unicode.charWidth(cp), max_width); + if (segment_width > 0 and segment_width + char_width > max_width) break; + + segment_width += char_width; + i += byte_len; + } + + return .{ + .start = start, + .end = i, + .is_last = i >= line.len, + }; + } + + fn displayWidthInRange(line: []const u8, start: usize, end: usize, max_width: usize) usize { + if (max_width == 0) return 0; + const clamped_end = clampToUtf8Boundary(line, @min(end, line.len)); + var width: usize = 0; + var i = @min(start, clamped_end); + while (i < clamped_end) { + const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; + if (i + byte_len > line.len) break; + const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { + width += 1; + i += 1; + continue; + }; + width += wrapDisplayWidth(unicode.charWidth(cp), max_width); + i += byte_len; + } + return width; + } + + fn byteOffsetForDisplayCol(line: []const u8, start: usize, end: usize, target_col: usize, max_width: usize) usize { + if (max_width == 0) return @min(start, line.len); + + const clamped_start = clampToUtf8Boundary(line, @min(start, line.len)); + const clamped_end = clampToUtf8Boundary(line, @min(end, line.len)); + var col: usize = 0; + var i = clamped_start; + while (i < clamped_end) { + if (col >= target_col) return i; + + const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; + if (i + byte_len > line.len) break; + const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { + if (col + 1 > target_col) return i; + col += 1; + i += 1; + continue; + }; + + const char_width = wrapDisplayWidth(unicode.charWidth(cp), max_width); + if (col + char_width > target_col) return i; + + col += char_width; + i += byte_len; + } + return clamped_end; + } + + fn wrapDisplayWidth(char_width: usize, max_width: usize) usize { + if (max_width == 0) return 0; + if (char_width == 0) return 0; + return @min(char_width, max_width); + } + + fn clampCursorToLineBoundary(self: *TextArea) void { + const line = self.currentLine(); + self.cursor_col = clampToUtf8Boundary(line.items, self.cursor_col); + } + + fn clampToUtf8Boundary(line: []const u8, pos: usize) usize { + var clamped = @min(pos, line.len); + while (clamped > 0 and clamped < line.len and (line[clamped] & 0xC0) == 0x80) { + clamped -= 1; + } + return clamped; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig new file mode 100644 index 0000000..5bd0fb8 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig @@ -0,0 +1,462 @@ +//! Single-line text input component. +//! Provides cursor navigation, text editing, and optional validation. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const style = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const TextInput = struct { + allocator: std.mem.Allocator, + + // Content + value: std.array_list.Managed(u8), + cursor: usize, + + // Appearance + placeholder: []const u8, + prompt: []const u8, + width: ?u16, + char_limit: ?usize, + echo_mode: EchoMode, + + // Styling + text_style: style.Style, + placeholder_style: style.Style, + cursor_style: style.Style, + prompt_style: style.Style, + + // State + focused: bool, + + // Validation + validate_fn: ?*const fn ([]const u8) bool, + + // Suggestions/autocomplete + suggestions: []const []const u8, + current_suggestion_idx: usize, + show_suggestions: bool, + suggestion_style: style.Style, + + pub const EchoMode = enum { + normal, + password, + none, + }; + + pub fn init(allocator: std.mem.Allocator) TextInput { + return .{ + .allocator = allocator, + .value = std.array_list.Managed(u8).init(allocator), + .cursor = 0, + .placeholder = "", + .prompt = "", + .width = null, + .char_limit = null, + .echo_mode = .normal, + .text_style = blk: { + var s = style.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .placeholder_style = blk: { + var s = style.Style{}; + s = s.fg(.gray(12)); + s = s.inline_style(true); + break :blk s; + }, + .cursor_style = blk: { + var s = style.Style{}; + s = s.reverse(true); + s = s.inline_style(true); + break :blk s; + }, + .prompt_style = blk: { + var s = style.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .focused = true, + .validate_fn = null, + .suggestions = &.{}, + .current_suggestion_idx = 0, + .show_suggestions = true, + .suggestion_style = blk2: { + var s2 = style.Style{}; + s2 = s2.dim(true); + s2 = s2.inline_style(true); + break :blk2 s2; + }, + }; + } + + pub fn deinit(self: *TextInput) void { + self.value.deinit(); + } + + /// Set the input value + pub fn setValue(self: *TextInput, text: []const u8) !void { + self.value.clearRetainingCapacity(); + try self.value.appendSlice(text); + self.cursor = @min(self.cursor, self.value.items.len); + } + + /// Get the current value + pub fn getValue(self: *const TextInput) []const u8 { + return self.value.items; + } + + /// Set placeholder text + pub fn setPlaceholder(self: *TextInput, text: []const u8) void { + self.placeholder = text; + } + + /// Set prompt text + pub fn setPrompt(self: *TextInput, text: []const u8) void { + self.prompt = text; + } + + /// Set width limit + pub fn setWidth(self: *TextInput, w: u16) void { + self.width = w; + } + + /// Set character limit + pub fn setCharLimit(self: *TextInput, limit: usize) void { + self.char_limit = limit; + } + + /// Set echo mode + pub fn setEchoMode(self: *TextInput, mode: EchoMode) void { + self.echo_mode = mode; + } + + /// Set validation function + pub fn setValidation(self: *TextInput, validate: *const fn ([]const u8) bool) void { + self.validate_fn = validate; + } + + /// Focus the input + pub fn focus(self: *TextInput) void { + self.focused = true; + } + + /// Blur the input + pub fn blur(self: *TextInput) void { + self.focused = false; + } + + /// Check if input is valid + pub fn isValid(self: *const TextInput) bool { + if (self.validate_fn) |validate| { + return validate(self.value.items); + } + return true; + } + + /// Set suggestion list + pub fn setSuggestions(self: *TextInput, list: []const []const u8) void { + self.suggestions = list; + self.current_suggestion_idx = 0; + } + + /// Get current matching suggestion + pub fn currentSuggestion(self: *const TextInput) ?[]const u8 { + if (self.suggestions.len == 0 or self.value.items.len == 0) return null; + const val = self.value.items; + var match_count: usize = 0; + for (self.suggestions) |s| { + if (s.len > val.len and std.mem.startsWith(u8, s, val)) { + if (match_count == self.current_suggestion_idx) { + return s; + } + match_count += 1; + } + } + return null; + } + + /// Handle a key event + pub fn handleKey(self: *TextInput, key: keys.KeyEvent) void { + if (!self.focused) return; + + // Alt+arrow for word movement + if (key.modifiers.alt) { + switch (key.key) { + .left => { + self.moveCursorWordLeft(); + return; + }, + .right => { + self.moveCursorWordRight(); + return; + }, + else => {}, + } + } + + if (key.modifiers.ctrl) { + switch (key.key) { + .char => |c| switch (c) { + 'a' => self.cursor = 0, // Home + 'e' => self.cursor = self.value.items.len, // End + 'k' => self.value.shrinkRetainingCapacity(self.cursor), // Kill to end + 'u' => { // Kill to start + std.mem.copyForwards(u8, self.value.items[0..], self.value.items[self.cursor..]); + self.value.shrinkRetainingCapacity(self.value.items.len - self.cursor); + self.cursor = 0; + }, + 'w' => self.deleteWordBackward(), // Delete word backward + else => {}, + }, + else => {}, + } + return; + } + + switch (key.key) { + .char => |c| self.insertChar(c), + .paste => |text| self.insertText(text), + .backspace => self.deleteBackward(), + .delete => self.deleteForward(), + .left => self.moveCursorLeft(), + .right => self.moveCursorRight(), + .home => self.cursor = 0, + .end => self.cursor = self.value.items.len, + .tab => { + // Accept current suggestion + if (self.currentSuggestion()) |suggestion| { + self.value.clearRetainingCapacity(); + self.value.appendSlice(suggestion) catch {}; + self.cursor = self.value.items.len; + } + }, + else => {}, + } + } + + fn insertChar(self: *TextInput, c: u21) void { + // Check char limit + if (self.char_limit) |limit| { + if (self.charCount() >= limit) return; + } + + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch return; + + // Insert at cursor position + self.value.insertSlice(self.cursor, buf[0..len]) catch return; + self.cursor += len; + } + + fn insertText(self: *TextInput, text: []const u8) void { + var i: usize = 0; + while (i < text.len) { + if (text[i] == '\r' or text[i] == '\n') { + i += 1; + continue; + } + + const len = std.unicode.utf8ByteSequenceLength(text[i]) catch { + self.insertChar(text[i]); + i += 1; + continue; + }; + if (i + len > text.len) { + self.insertChar(text[i]); + i += 1; + continue; + } + + const codepoint = std.unicode.utf8Decode(text[i .. i + len]) catch { + self.insertChar(text[i]); + i += 1; + continue; + }; + self.insertChar(codepoint); + i += len; + } + } + + fn deleteBackward(self: *TextInput) void { + if (self.cursor == 0) return; + + // Find start of previous character + var start = self.cursor - 1; + while (start > 0 and (self.value.items[start] & 0xC0) == 0x80) { + start -= 1; + } + + const len = self.cursor - start; + _ = self.value.orderedRemove(start); + for (1..len) |_| { + if (start < self.value.items.len) { + _ = self.value.orderedRemove(start); + } + } + self.cursor = start; + } + + fn deleteForward(self: *TextInput) void { + if (self.cursor >= self.value.items.len) return; + + // Find length of current character + const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; + + for (0..byte_len) |_| { + if (self.cursor < self.value.items.len) { + _ = self.value.orderedRemove(self.cursor); + } + } + } + + fn deleteWordBackward(self: *TextInput) void { + if (self.cursor == 0) return; + + // Skip trailing spaces + while (self.cursor > 0 and self.value.items[self.cursor - 1] == ' ') { + self.deleteBackward(); + } + + // Delete until space or start + while (self.cursor > 0 and self.value.items[self.cursor - 1] != ' ') { + self.deleteBackward(); + } + } + + fn moveCursorLeft(self: *TextInput) void { + if (self.cursor == 0) return; + + self.cursor -= 1; + while (self.cursor > 0 and (self.value.items[self.cursor] & 0xC0) == 0x80) { + self.cursor -= 1; + } + } + + fn moveCursorRight(self: *TextInput) void { + if (self.cursor >= self.value.items.len) return; + + const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; + self.cursor = @min(self.cursor + byte_len, self.value.items.len); + } + + fn moveCursorWordLeft(self: *TextInput) void { + if (self.cursor == 0) return; + // Skip whitespace + while (self.cursor > 0 and self.value.items[self.cursor - 1] == ' ') { + self.cursor -= 1; + } + // Skip word chars + while (self.cursor > 0 and self.value.items[self.cursor - 1] != ' ') { + self.cursor -= 1; + } + } + + fn moveCursorWordRight(self: *TextInput) void { + if (self.cursor >= self.value.items.len) return; + // Skip word chars + while (self.cursor < self.value.items.len and self.value.items[self.cursor] != ' ') { + self.cursor += 1; + } + // Skip whitespace + while (self.cursor < self.value.items.len and self.value.items[self.cursor] == ' ') { + self.cursor += 1; + } + } + + fn charCount(self: *const TextInput) usize { + var count: usize = 0; + var i: usize = 0; + while (i < self.value.items.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[i]) catch 1; + i += byte_len; + count += 1; + } + return count; + } + + /// Render the input to a string + pub fn view(self: *const TextInput, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Write prompt + if (self.prompt.len > 0) { + const rendered_prompt = try self.prompt_style.render(allocator, self.prompt); + try writer.writeAll(rendered_prompt); + } + + // Get display text + if (self.value.items.len == 0) { + // Show placeholder + if (self.placeholder.len > 0) { + const rendered = try self.placeholder_style.render(allocator, self.placeholder); + try writer.writeAll(rendered); + } + } else { + // Show value (possibly masked) + switch (self.echo_mode) { + .normal => { + // Render with cursor + if (self.focused) { + try self.renderWithCursor(writer, allocator); + } else { + const rendered = try self.text_style.render(allocator, self.value.items); + try writer.writeAll(rendered); + } + }, + .password => { + // Show asterisks + const char_count = self.charCount(); + const masked = try allocator.alloc(u8, char_count); + @memset(masked, '*'); + const rendered = try self.text_style.render(allocator, masked); + try writer.writeAll(rendered); + }, + .none => { + // Show nothing + }, + } + } + + return result.toOwnedSlice(); + } + + fn renderWithCursor(self: *const TextInput, writer: *Writer, allocator: std.mem.Allocator) !void { + // Text before cursor + if (self.cursor > 0) { + const before = try self.text_style.render(allocator, self.value.items[0..self.cursor]); + try writer.writeAll(before); + } + + // Cursor character + if (self.cursor < self.value.items.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; + const cursor_char = self.value.items[self.cursor..][0..byte_len]; + const cursor_rendered = try self.cursor_style.render(allocator, cursor_char); + try writer.writeAll(cursor_rendered); + + // Text after cursor + if (self.cursor + byte_len < self.value.items.len) { + const after = try self.text_style.render(allocator, self.value.items[self.cursor + byte_len ..]); + try writer.writeAll(after); + } + } else { + // Cursor at end - show cursor on space + const cursor_rendered = try self.cursor_style.render(allocator, " "); + try writer.writeAll(cursor_rendered); + } + + // Show ghost text for current suggestion + if (self.show_suggestions) { + if (self.currentSuggestion()) |suggestion| { + if (suggestion.len > self.value.items.len) { + const ghost = suggestion[self.value.items.len..]; + const ghost_rendered = try self.suggestion_style.render(allocator, ghost); + try writer.writeAll(ghost_rendered); + } + } + } + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig new file mode 100644 index 0000000..ca708f5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig @@ -0,0 +1,223 @@ +//! Timer component for countdowns and elapsed time. +//! Displays time in various formats. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +pub const Timer = struct { + // State + duration_ns: i128, + elapsed_ns: i128, + running: bool, + direction: Direction, + + // Display + format: Format, + show_milliseconds: bool, + + // Styling + timer_style: style_mod.Style, + warning_style: style_mod.Style, + danger_style: style_mod.Style, + + // Thresholds for countdown warnings (in seconds) + warning_threshold: ?u64, + danger_threshold: ?u64, + + pub const Direction = enum { + up, // Counts up (stopwatch) + down, // Counts down (timer) + }; + + pub const Format = enum { + compact, // 1:23 + long, // 01:23 + full, // 00:01:23 + verbose, // 1m 23s + }; + + pub fn init() Timer { + return .{ + .duration_ns = 0, + .elapsed_ns = 0, + .running = false, + .direction = .up, + .format = .long, + .show_milliseconds = false, + .timer_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.inline_style(true); + break :blk s; + }, + .warning_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .danger_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + .warning_threshold = 30, + .danger_threshold = 10, + }; + } + + /// Create a countdown timer + pub fn countdown(seconds: u64) Timer { + var t = init(); + t.direction = .down; + t.duration_ns = @as(i128, seconds) * std.time.ns_per_s; + return t; + } + + /// Create a stopwatch + pub fn stopwatch() Timer { + var t = init(); + t.direction = .up; + return t; + } + + /// Start the timer + pub fn start(self: *Timer) void { + self.running = true; + } + + /// Stop the timer + pub fn stop(self: *Timer) void { + self.running = false; + } + + /// Toggle running state + pub fn toggle(self: *Timer) void { + self.running = !self.running; + } + + /// Reset the timer + pub fn reset(self: *Timer) void { + self.elapsed_ns = 0; + } + + /// Set duration for countdown (in seconds) + pub fn setDuration(self: *Timer, seconds: u64) void { + self.duration_ns = @as(i128, seconds) * std.time.ns_per_s; + } + + /// Update timer with delta time (in nanoseconds) + pub fn update(self: *Timer, delta_ns: u64) void { + if (!self.running) return; + self.elapsed_ns += delta_ns; + } + + /// Get remaining time for countdown (in nanoseconds) + pub fn remaining(self: *const Timer) i128 { + if (self.direction == .down) { + return @max(0, self.duration_ns - self.elapsed_ns); + } + return self.elapsed_ns; + } + + /// Get elapsed time in seconds + pub fn elapsedSeconds(self: *const Timer) u64 { + return @intCast(@divFloor(self.elapsed_ns, std.time.ns_per_s)); + } + + /// Get remaining time in seconds (for countdown) + pub fn remainingSeconds(self: *const Timer) u64 { + return @intCast(@divFloor(self.remaining(), std.time.ns_per_s)); + } + + /// Check if countdown is finished + pub fn isFinished(self: *const Timer) bool { + if (self.direction == .down) { + return self.elapsed_ns >= self.duration_ns; + } + return false; + } + + /// Check if in warning state + pub fn isWarning(self: *const Timer) bool { + if (self.direction == .down and self.warning_threshold != null) { + const remaining_s = self.remainingSeconds(); + return remaining_s <= self.warning_threshold.? and remaining_s > (self.danger_threshold orelse 0); + } + return false; + } + + /// Check if in danger state + pub fn isDanger(self: *const Timer) bool { + if (self.direction == .down and self.danger_threshold != null) { + return self.remainingSeconds() <= self.danger_threshold.?; + } + return false; + } + + /// Render the timer + pub fn view(self: *const Timer, allocator: std.mem.Allocator) ![]const u8 { + const display_ns = if (self.direction == .down) self.remaining() else self.elapsed_ns; + + const total_seconds: u64 = @intCast(@divFloor(display_ns, std.time.ns_per_s)); + const milliseconds: u64 = @intCast(@mod(@divFloor(display_ns, std.time.ns_per_ms), 1000)); + + const hours = total_seconds / 3600; + const minutes = (total_seconds % 3600) / 60; + const seconds = total_seconds % 60; + + const time_str = switch (self.format) { + .compact => blk: { + if (hours > 0) { + break :blk try std.fmt.allocPrint(allocator, "{d}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }); + } else { + break :blk try std.fmt.allocPrint(allocator, "{d}:{d:0>2}", .{ minutes, seconds }); + } + }, + .long => blk: { + if (hours > 0) { + break :blk try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }); + } else { + break :blk try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}", .{ minutes, seconds }); + } + }, + .full => try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }), + .verbose => blk: { + if (hours > 0) { + break :blk try std.fmt.allocPrint(allocator, "{d}h {d}m {d}s", .{ hours, minutes, seconds }); + } else if (minutes > 0) { + break :blk try std.fmt.allocPrint(allocator, "{d}m {d}s", .{ minutes, seconds }); + } else { + break :blk try std.fmt.allocPrint(allocator, "{d}s", .{seconds}); + } + }, + }; + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Choose style based on state + const active_style = if (self.isDanger()) + self.danger_style + else if (self.isWarning()) + self.warning_style + else + self.timer_style; + + const styled = try active_style.render(allocator, time_str); + try writer.writeAll(styled); + + // Add milliseconds if enabled + if (self.show_milliseconds) { + const ms_str = try std.fmt.allocPrint(allocator, ".{d:0>3}", .{milliseconds}); + try writer.writeAll(ms_str); + } + + return result.toOwnedSlice(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig new file mode 100644 index 0000000..0ff9612 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig @@ -0,0 +1,444 @@ +//! Enhanced Toast/Snackbar notification system. +//! Supports positioning, stacking, icons, borders, and auto-dismiss with countdown. + +const std = @import("std"); +const Writer = std.Io.Writer; +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 = .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(.cyan); + s = s.inline_style(true); + break :blk s; + }, + .success_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + .warning_style = blk: { + var s = style_mod.Style{}; + s = s.fg(.yellow); + s = s.inline_style(true); + break :blk s; + }, + .err_style = blk: { + var s = style_mod.Style{}; + s = s.bold(true); + s = s.fg(.red); + s = s.inline_style(true); + break :blk s; + }, + .info_border_fg = .cyan, + .success_border_fg = .green, + .warning_border_fg = .yellow, + .err_border_fg = .red, + }; + } + + pub fn deinit(self: *Toast) void { + self.dismissAll(); + self.messages.deinit(); + } + + /// Push a notification. + pub fn push(self: *Toast, text: []const u8, level: Level, duration_ms: u64, current_ns: u64) !void { + const owned_text = try self.allocator.dupe(u8, text); + errdefer self.allocator.free(owned_text); + + try self.messages.append(.{ + .text = owned_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 { + const owned_text = try self.allocator.dupe(u8, text); + errdefer self.allocator.free(owned_text); + + try self.messages.append(.{ + .text = owned_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) { + const msg = self.messages.pop().?; + self.freeMessage(msg); + } + } + + /// Dismiss the oldest notification. + pub fn dismissOldest(self: *Toast) void { + if (self.messages.items.len > 0) { + self.removeAt(0); + } + } + + /// Dismiss all notifications. + pub fn dismissAll(self: *Toast) void { + for (self.messages.items) |msg| { + self.freeMessage(msg); + } + 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.removeAt(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: Writer.Allocating = .init(allocator); + errdefer result.deinit(); + const writer = &result.writer; + + const visible_count = @min(self.messages.items.len, self.max_visible); + + const total = self.messages.items.len; + for (0..visible_count) |render_idx| { + if (render_idx > 0) try writer.writeByte('\n'); + + const idx = switch (self.stack_order) { + .newest_first => total - 1 - render_idx, + .oldest_first => blk: { + const start = if (total > self.max_visible) total - self.max_visible else 0; + break :blk start + render_idx; + }, + }; + const msg = self.messages.items[idx]; + const toast_str = try self.renderSingleToast(allocator, msg, current_ns); + defer allocator.free(toast_str); + 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}); + defer allocator.free(overflow_text); + var dim_style = style_mod.Style{}; + dim_style = dim_style.fg(.gray(10)); + dim_style = dim_style.inline_style(true); + const styled = try dim_style.render(allocator, overflow_text); + defer allocator.free(styled); + 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; + defer allocator.free(toast_content); + + const place_mod = @import("../layout/place.zig"); + const line_alignment: style_mod.Align = switch (self.position) { + .top_left, .bottom_left => .left, + .top_center, .bottom_center => .center, + .top_right, .bottom_right => .right, + }; + const aligned_content = try alignLines(allocator, toast_content, line_alignment); + defer allocator.free(aligned_content); + + 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, + }; + + return place_mod.placeFloat(allocator, term_width, term_height, hpos, vpos, aligned_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: Writer.Allocating = .init(allocator); + errdefer line.deinit(); + const lw = &line.writer; + + const icon = if (self.show_icons) switch (msg.level) { + .info => self.info_icon, + .success => self.success_icon, + .warning => self.warning_icon, + .err => self.err_icon, + } else ""; + const icon_width = measure.width(icon); + + var countdown_text: []const u8 = ""; + var countdown_width: usize = 0; + 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; + countdown_text = try std.fmt.allocPrint(allocator, " ({d}s)", .{remaining_sec}); + countdown_width = measure.width(countdown_text); + } + defer if (countdown_text.len > 0) allocator.free(countdown_text); + + const max_inner_width = @max(self.minInnerWidth(), self.maxInnerWidth()); + const prefix_suffix_width = icon_width + countdown_width; + const available_text_width = max_inner_width -| prefix_suffix_width; + const display_text = if (measure.width(msg.text) > available_text_width) + try measure.truncate(allocator, msg.text, available_text_width) + else + try allocator.dupe(u8, msg.text); + defer allocator.free(display_text); + + // Icon + if (self.show_icons) { + const styled_icon = try active_style.render(allocator, icon); + defer allocator.free(styled_icon); + try lw.writeAll(styled_icon); + } + + // Text + const styled_text = try active_style.render(allocator, display_text); + defer allocator.free(styled_text); + try lw.writeAll(styled_text); + + // Countdown + if (countdown_text.len > 0) { + var dim_style = style_mod.Style{}; + dim_style = dim_style.fg(.gray(10)); + dim_style = dim_style.inline_style(true); + const styled_cd = try dim_style.render(allocator, countdown_text); + defer allocator.free(styled_cd); + try lw.writeAll(styled_cd); + } + + const line_content = try line.toOwnedSlice(); + + if (!self.show_border) { + return line_content; + } + + const target_inner_width = @max(self.minInnerWidth(), measure.width(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.width(@intCast(target_inner_width)); + box_style = box_style.inline_style(false); + + defer allocator.free(line_content); + 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, + }; + } + + fn freeMessage(self: *Toast, msg: ToastMessage) void { + self.allocator.free(msg.text); + } + + fn removeAt(self: *Toast, idx: usize) void { + const msg = self.messages.orderedRemove(idx); + self.freeMessage(msg); + } + + fn toastChromeWidth(self: *const Toast) usize { + if (!self.show_border) return 0; + return 4; // 2 border columns + 2 horizontal padding columns + } + + fn minInnerWidth(self: *const Toast) usize { + const min_total = @as(usize, self.min_width); + return if (min_total > self.toastChromeWidth()) + min_total - self.toastChromeWidth() + else + 0; + } + + fn maxInnerWidth(self: *const Toast) usize { + const min_inner = self.minInnerWidth(); + const max_total = @as(usize, self.max_width); + const max_inner = if (max_total > self.toastChromeWidth()) + max_total - self.toastChromeWidth() + else + 0; + return @max(min_inner, max_inner); + } +}; + +fn alignLines(allocator: std.mem.Allocator, content: []const u8, alignment: style_mod.Align) ![]const u8 { + const target_width = measure.maxLineWidth(content); + var result: Writer.Allocating = .init(allocator); + errdefer result.deinit(); + const writer = &result.writer; + + var lines = std.mem.splitScalar(u8, content, '\n'); + var first = true; + while (lines.next()) |line| { + if (!first) try writer.writeByte('\n'); + first = false; + + const line_width = measure.width(line); + const padding = target_width -| line_width; + const left_padding: usize = switch (alignment) { + .left => 0, + .center => padding / 2, + .right => padding, + }; + const right_padding: usize = switch (alignment) { + .left => padding, + .center => padding - left_padding, + .right => 0, + }; + + for (0..left_padding) |_| { + try writer.writeByte(' '); + } + try writer.writeAll(line); + for (0..right_padding) |_| { + try writer.writeByte(' '); + } + } + + return result.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig new file mode 100644 index 0000000..b5d52fb --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig @@ -0,0 +1,925 @@ +//! Tooltip component for displaying contextual hints near a target position. +//! +//! ## Quick Start +//! +//! ```zig +//! // Create a tooltip +//! var tip = Tooltip.init("Save the current document"); +//! +//! // Position it relative to a target +//! tip.target_x = 10; +//! tip.target_y = 5; +//! tip.placement = .bottom; +//! tip.show(); +//! +//! // In your view function: +//! const output = try tip.render(allocator, term_width, term_height); +//! ``` +//! +//! ## Placements +//! +//! - `.top` — above the target, arrow pointing down +//! - `.bottom` — below the target, arrow pointing up +//! - `.left` — to the left of the target, arrow pointing right +//! - `.right` — to the right of the target, arrow pointing left +//! +//! ## Presets +//! +//! - `Tooltip.init(text)` — simple tooltip with default style +//! - `Tooltip.titled(title, text)` — tooltip with a bold title line +//! - `Tooltip.help(text)` — dim, italic help-style tooltip +//! - `Tooltip.shortcut(label, key)` — "Label Ctrl+S" style tooltip + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const border_mod = @import("../style/border.zig"); +const Color = @import("../style/color.zig").Color; +const AnsiColor = @import("../style/color.zig").AnsiColor; +const measure = @import("../layout/measure.zig"); +const unicode = @import("../unicode.zig"); + +pub const Tooltip = struct { + // ── State ────────────────────────────────────────────────────────── + + visible: bool = false, + + // ── Content ──────────────────────────────────────────────────────── + + text: []const u8 = "", + title: ?[]const u8 = null, + + // ── Position ────────────────────────────────────────────────────── + + /// X coordinate of the target element (display column). + target_x: usize = 0, + /// Y coordinate of the target element (display row). + target_y: usize = 0, + /// Width of the target element (used for centering arrows). + target_width: usize = 1, + /// Where to place the tooltip relative to the target. + placement: Placement = .bottom, + /// Gap between tooltip and target (in cells). + gap: usize = 0, + + // ── Sizing ───────────────────────────────────────────────────────── + + /// Maximum width of the tooltip content area (excluding border/padding). + max_width: usize = 40, + /// Padding inside the tooltip box. + padding: Padding = .{ .top = 0, .right = 1, .bottom = 0, .left = 1 }, + + // ── Styling ──────────────────────────────────────────────────────── + + border_chars: border_mod.BorderChars = .rounded, + border_fg: Color = .gray(14), + /// Background for the content area (padding + text) inside the border. + content_bg: Color = .none, + /// Background for border characters. Three-state via `?Color`: + /// - `null` (default) — falls back to `content_bg` (same bg everywhere). + /// - `.none` — explicitly no bg; with `inherit_bg` the base shows through. + /// - any color — use that color for borders only. + border_bg: ?Color = null, + text_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(20) }), + title_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white }), + + /// Show an arrow pointing from tooltip toward the target. + show_arrow: bool = true, + /// Color of the arrow character. + arrow_fg: Color = .gray(14), + /// Background for the arrow character. Three-state via `?Color`: + /// - `null` (default) — no bg; with `inherit_bg` the base shows through. + /// - `.none` — explicitly no bg, even when `inherit_bg` is on. + /// - any color — use that color. + arrow_bg: ?Color = null, + /// Custom arrow characters per direction (what's shown when the tooltip + /// is placed in that direction). Set to "" to hide a specific arrow. + arrow_up: []const u8 = "▲", + arrow_down: []const u8 = "▼", + arrow_left: []const u8 = "◀", + arrow_right: []const u8 = "▶", + + /// When true in overlay mode, tooltip elements (arrow, border) inherit + /// the background color from the underlying base content. + inherit_bg: bool = true, + + // ── Types ────────────────────────────────────────────────────────── + + pub const Placement = enum { top, bottom, left, right }; + + pub const Padding = struct { + top: u16 = 0, + right: u16 = 0, + bottom: u16 = 0, + left: u16 = 0, + + pub fn all(n: u16) Padding { + return .{ .top = n, .right = n, .bottom = n, .left = n }; + } + + pub fn symmetric(vert: u16, horiz: u16) Padding { + return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; + } + }; + + // ── Preset Constructors ──────────────────────────────────────────── + + /// Simple tooltip with text content. + pub fn init(text: []const u8) Tooltip { + return .{ .text = text }; + } + + /// Tooltip with a bold title line above the text. + pub fn titled(title_text: []const u8, body: []const u8) Tooltip { + return .{ + .text = body, + .title = title_text, + }; + } + + /// Help-style tooltip with dim italic text. + pub fn help(text: []const u8) Tooltip { + return .{ + .text = text, + .text_style = makeStyle(.{ .dim_v = true, .italic_v = true, .fg_color = .gray(16) }), + .border_fg = .gray(10), + .arrow_fg = .gray(10), + }; + } + + /// Shortcut tooltip showing "Label Key". + pub fn shortcut(label: []const u8, key: []const u8) Tooltip { + return .{ + .text = key, + .title = label, + .title_style = makeStyle(.{ .fg_color = .gray(18) }), + .text_style = makeStyle(.{ .bold_v = true, .fg_color = .cyan }), + }; + } + + // ── State Management ─────────────────────────────────────────────── + + pub fn show(self: *Tooltip) void { + self.visible = true; + } + + pub fn hide(self: *Tooltip) void { + self.visible = false; + } + + pub fn toggle(self: *Tooltip) void { + self.visible = !self.visible; + } + + pub fn isVisible(self: *const Tooltip) bool { + return self.visible; + } + + // ── Rendering ────────────────────────────────────────────────────── + + /// Render the tooltip box (no positioning). Returns the box string. + pub fn renderBox(self: *const Tooltip, allocator: std.mem.Allocator) ![]const u8 { + const bc = self.border_chars; + + // Compute content lines + var content_lines = std.array_list.Managed([]const u8).init(allocator); + defer content_lines.deinit(); + + if (self.title) |t| { + try content_lines.append(t); + } + + var text_iter = std.mem.splitScalar(u8, self.text, '\n'); + while (text_iter.next()) |line| { + try content_lines.append(line); + } + + // Compute inner width + var max_content_w: usize = 0; + for (content_lines.items) |line| { + max_content_w = @max(max_content_w, measure.width(line)); + } + max_content_w = @min(max_content_w, self.max_width); + + const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); + const inner_w: usize = max_content_w + pad_h; + + // Inline styles + // border_bg: null → fall back to content_bg (backward compat) + // .none → explicitly no bg (transparent) + // color → use that color + const effective_border_bg = if (self.border_bg) |b| b else self.content_bg; + var bdr_s = style_mod.Style{}; + bdr_s = bdr_s.fg(self.border_fg).inline_style(true); + if (!effective_border_bg.isNone()) bdr_s = bdr_s.bg(effective_border_bg); + + var pad_s = style_mod.Style{}; + pad_s = pad_s.inline_style(true); + if (!self.content_bg.isNone()) pad_s = pad_s.bg(self.content_bg); + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // ── Top border ── + try writer.writeAll(try bdr_s.render(allocator, bc.top_left)); + try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); + try writer.writeAll(try bdr_s.render(allocator, bc.top_right)); + + const styled_left = try bdr_s.render(allocator, bc.vertical); + const styled_right = try bdr_s.render(allocator, bc.vertical); + + // ── Top padding ── + for (0..self.padding.top) |_| { + try writer.writeByte('\n'); + try writeEmptyLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + } + + // ── Content lines ── + for (content_lines.items, 0..) |line, idx| { + try writer.writeByte('\n'); + try writer.writeAll(styled_left); + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); + + // Pick style: title or body + const is_title_line = self.title != null and idx == 0; + var line_style = if (is_title_line) self.title_style else self.text_style; + line_style = line_style.inline_style(true); + if (!self.content_bg.isNone() and line_style.background.isNone()) { + line_style = line_style.bg(self.content_bg); + } + try writer.writeAll(try line_style.render(allocator, line)); + + const line_w = measure.width(line); + const fill: usize = if (max_content_w > line_w) max_content_w - line_w else 0; + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); + try writer.writeAll(styled_right); + } + + // ── Bottom padding ── + for (0..self.padding.bottom) |_| { + try writer.writeByte('\n'); + try writeEmptyLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); + } + + // ── Bottom border ── + try writer.writeByte('\n'); + try writer.writeAll(try bdr_s.render(allocator, bc.bottom_left)); + try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); + try writer.writeAll(try bdr_s.render(allocator, bc.bottom_right)); + + return result.toOwnedSlice(); + } + + /// Render the tooltip positioned on a full-screen canvas. + /// Returns empty string if not visible. + pub fn render(self: *const Tooltip, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { + if (!self.visible) return try allocator.dupe(u8, ""); + + const box = try self.renderBox(allocator); + const box_w = measure.maxLineWidth(box); + const box_h = measure.height(box); + + // Compute arrow position and tooltip position + const pos = self.computePosition(box_w, box_h, term_width, term_height); + + // Build full-screen output line by line + var result: Writer.Allocating = .init(allocator); + const wr = &result.writer; + + // Collect box lines + var box_lines = std.array_list.Managed([]const u8).init(allocator); + defer box_lines.deinit(); + var box_iter = std.mem.splitScalar(u8, box, '\n'); + while (box_iter.next()) |line| try box_lines.append(line); + + const is_horizontal = self.placement == .left or self.placement == .right; + + for (0..term_height) |row| { + if (row > 0) try wr.writeByte('\n'); + + const in_box = row >= pos.box_y and row < pos.box_y + box_h; + const is_arrow_row = self.show_arrow and row == pos.arrow_y; + + if (in_box) { + const box_line_idx = row - pos.box_y; + const box_line = if (box_line_idx < box_lines.items.len) box_lines.items[box_line_idx] else ""; + // For left/right placement, include arrow on the same row as the box + if (is_arrow_row and is_horizontal) { + try self.writeBoxRowWithSideArrow(allocator, wr, pos, box_line, term_width); + } else { + try wr.writeAll(try nSpaces(allocator, pos.box_x)); + try wr.writeAll(box_line); + const right = pos.box_x + measure.width(box_line); + if (right < term_width) try wr.writeAll(try nSpaces(allocator, term_width - right)); + } + } else if (is_arrow_row) { + // Top/bottom arrow on its own row + try self.writeArrowOnlyRow(allocator, wr, pos, term_width); + } else { + try wr.writeAll(try nSpaces(allocator, term_width)); + } + } + + return result.toOwnedSlice(); + } + + /// Render the tooltip composited onto the given base content. + /// + /// Uses **cell-based compositing** (like Ratatui, Textual, Cursive): + /// both base and tooltip are parsed into a cell grid, tooltip cells are + /// painted on top, then the grid is serialized back to an ANSI string. + /// This completely avoids ANSI-splice style bleeding. + pub fn overlay(self: *const Tooltip, allocator: std.mem.Allocator, base: []const u8, term_width: usize, term_height: usize) ![]const u8 { + if (!self.visible) return try allocator.dupe(u8, base); + + const box = try self.renderBox(allocator); + const box_w = measure.maxLineWidth(box); + const box_h = measure.height(box); + const pos = self.computePosition(box_w, box_h, term_width, term_height); + + // 1. Parse base content into cell grid + var grid = try CellGrid.parse(allocator, base, term_width, term_height); + + // 2. Parse tooltip box into cell grid + var box_grid = try CellGrid.parse(allocator, box, box_w, box_h); + + // 3. Paint tooltip box cells onto base grid + for (0..box_h) |r| { + const dst_r = pos.box_y + r; + if (dst_r >= term_height) break; + var c: usize = 0; + while (c < box_w) { + const dst_c = pos.box_x + c; + if (dst_c >= term_width) break; + + const src_cell = box_grid.get(r, c); + if (self.inherit_bg and src_cell.style.bg.eql(.none)) { + // Tooltip cell has no bg → inherit from base + var merged = src_cell; + merged.style.bg = grid.get(dst_r, dst_c).style.bg; + grid.set(dst_r, dst_c, merged); + } else { + grid.set(dst_r, dst_c, src_cell); + } + + // Skip continuation cells of wide characters + const w = if (src_cell.width > 1) src_cell.width else 1; + c += w; + } + } + + // 4. Paint arrow cell + if (self.show_arrow) { + const arrow_ch = self.arrowChar(); + if (arrow_ch.len > 0 and pos.arrow_y < term_height and pos.arrow_x < term_width) { + const aw = self.arrowDisplayWidth(); + var arrow_style = CellStyle{}; + arrow_style.fg = colorToCellColor(self.arrow_fg); + if (self.arrow_bg) |abg| { + // Explicitly set → use it (even .none = explicitly no bg) + if (!abg.isNone()) arrow_style.bg = colorToCellColor(abg); + } else if (self.inherit_bg) { + // Not specified → inherit from base when enabled + arrow_style.bg = grid.get(pos.arrow_y, pos.arrow_x).style.bg; + } + grid.set(pos.arrow_y, pos.arrow_x, .{ + .char = arrow_ch, + .style = arrow_style, + .width = @intCast(aw), + }); + // Clear continuation cells for wide arrow + for (1..aw) |dx| { + if (pos.arrow_x + dx < term_width) { + grid.set(pos.arrow_y, pos.arrow_x + dx, .{ + .char = "", + .style = arrow_style, + .width = 0, + }); + } + } + } + } + + // 5. Serialize cell grid back to ANSI string + return grid.render(allocator); + } + + // ── Position Computation ────────────────────────────────────────── + + const Position = struct { + box_x: usize, + box_y: usize, + arrow_x: usize, + arrow_y: usize, + }; + + fn computePosition(self: *const Tooltip, box_w: usize, box_h: usize, tw: usize, th: usize) Position { + var pos: Position = .{ .box_x = 0, .box_y = 0, .arrow_x = 0, .arrow_y = 0 }; + + const arrow_offset: usize = if (self.show_arrow) 1 else 0; + + switch (self.placement) { + .bottom => { + // Box below target + pos.arrow_y = self.target_y + 1 + self.gap; + pos.box_y = pos.arrow_y + arrow_offset; + // Center horizontally on target + const target_center = self.target_x + self.target_width / 2; + pos.box_x = if (target_center >= box_w / 2) target_center - box_w / 2 else 0; + pos.arrow_x = target_center; + }, + .top => { + // Box above target + const total_h = box_h + arrow_offset; + pos.box_y = if (self.target_y >= total_h + self.gap) self.target_y - total_h - self.gap else 0; + pos.arrow_y = pos.box_y + box_h; + const target_center = self.target_x + self.target_width / 2; + pos.box_x = if (target_center >= box_w / 2) target_center - box_w / 2 else 0; + pos.arrow_x = target_center; + }, + .right => { + // Box to the right of target + pos.box_x = self.target_x + self.target_width + self.gap + arrow_offset; + pos.arrow_x = self.target_x + self.target_width + self.gap; + // Center vertically on target + pos.box_y = if (self.target_y >= box_h / 2) self.target_y - box_h / 2 else 0; + pos.arrow_y = self.target_y; + }, + .left => { + // Box to the left of target + const total_w = box_w + arrow_offset; + pos.box_x = if (self.target_x >= total_w + self.gap) self.target_x - total_w - self.gap else 0; + pos.arrow_x = pos.box_x + box_w; + pos.box_y = if (self.target_y >= box_h / 2) self.target_y - box_h / 2 else 0; + pos.arrow_y = self.target_y; + }, + } + + // Clamp to terminal bounds + if (pos.box_x + box_w > tw) pos.box_x = if (tw >= box_w) tw - box_w else 0; + if (pos.box_y + box_h > th) pos.box_y = if (th >= box_h) th - box_h else 0; + if (pos.arrow_x >= tw) pos.arrow_x = tw -| 1; + if (pos.arrow_y >= th) pos.arrow_y = th -| 1; + + return pos; + } + + fn arrowChar(self: *const Tooltip) []const u8 { + return switch (self.placement) { + .bottom => self.arrow_up, + .top => self.arrow_down, + .left => self.arrow_right, + .right => self.arrow_left, + }; + } + + fn renderStyledArrow(self: *const Tooltip, allocator: std.mem.Allocator) ![]const u8 { + const ch = self.arrowChar(); + if (ch.len == 0) return try allocator.dupe(u8, ""); + var arrow_s = style_mod.Style{}; + arrow_s = arrow_s.fg(self.arrow_fg).inline_style(true); + return try arrow_s.render(allocator, ch); + } + + fn arrowDisplayWidth(self: *const Tooltip) usize { + const ch = self.arrowChar(); + if (ch.len == 0) return 0; + return measure.width(ch); + } + + // ── Render helpers (full-screen canvas) ──────────────────────────── + + /// Arrow on its own row (top/bottom placement). + fn writeArrowOnlyRow(self: *const Tooltip, allocator: std.mem.Allocator, writer: *Writer, pos: Position, tw: usize) !void { + try writer.writeAll(try nSpaces(allocator, pos.arrow_x)); + try writer.writeAll(try self.renderStyledArrow(allocator)); + const aw = self.arrowDisplayWidth(); + const used = pos.arrow_x + aw; + if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); + } + + /// Box row that also has a side arrow (left/right placement). + fn writeBoxRowWithSideArrow(self: *const Tooltip, allocator: std.mem.Allocator, writer: *Writer, pos: Position, box_line: []const u8, tw: usize) !void { + const box_line_w = measure.width(box_line); + const aw = self.arrowDisplayWidth(); + const styled_arrow = try self.renderStyledArrow(allocator); + + if (self.placement == .right) { + // Layout: [spaces] [arrow] [box_line] [spaces] + try writer.writeAll(try nSpaces(allocator, pos.arrow_x)); + try writer.writeAll(styled_arrow); + const gap_between = if (pos.box_x > pos.arrow_x + aw) pos.box_x - pos.arrow_x - aw else 0; + try writer.writeAll(try nSpaces(allocator, gap_between)); + try writer.writeAll(box_line); + const used = pos.arrow_x + aw + gap_between + box_line_w; + if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); + } else { + // .left — Layout: [spaces] [box_line] [arrow] [spaces] + try writer.writeAll(try nSpaces(allocator, pos.box_x)); + try writer.writeAll(box_line); + const gap_between = if (pos.arrow_x > pos.box_x + box_line_w) pos.arrow_x - pos.box_x - box_line_w else 0; + try writer.writeAll(try nSpaces(allocator, gap_between)); + try writer.writeAll(styled_arrow); + const used = pos.box_x + box_line_w + gap_between + aw; + if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); + } + } + + // ── Private Helpers ─────────────────────────────────────────────── + + fn writeEmptyLine(allocator: std.mem.Allocator, writer: *Writer, styled_left: []const u8, styled_right: []const u8, pad_s: style_mod.Style, inner_w: usize) !void { + try writer.writeAll(styled_left); + try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, inner_w))); + try writer.writeAll(styled_right); + } + + fn repeatStr(allocator: std.mem.Allocator, s: style_mod.Style, str: []const u8, count: usize) ![]const u8 { + if (count == 0 or str.len == 0) return try allocator.dupe(u8, ""); + const buf = try allocator.alloc(u8, str.len * count); + for (0..count) |i| { + @memcpy(buf[i * str.len ..][0..str.len], str); + } + return try s.render(allocator, buf); + } + + fn nSpaces(allocator: std.mem.Allocator, count: anytype) ![]const u8 { + const n: usize = switch (@typeInfo(@TypeOf(count))) { + .int, .comptime_int => @intCast(count), + else => count, + }; + if (n == 0) return try allocator.dupe(u8, ""); + const buf = try allocator.alloc(u8, n); + @memset(buf, ' '); + return buf; + } + + // Comptime style builder + const StyleOpts = struct { + bold_v: ?bool = null, + dim_v: ?bool = null, + italic_v: ?bool = null, + fg_color: Color = .none, + bg_color: Color = .none, + }; + + fn makeStyle(opts: StyleOpts) style_mod.Style { + var s = style_mod.Style{}; + if (opts.bold_v) |v| s.bold_attr = v; + if (opts.dim_v) |v| s.dim_attr = v; + if (opts.italic_v) |v| s.italic_attr = v; + if (!opts.fg_color.isNone()) s.foreground = opts.fg_color; + if (!opts.bg_color.isNone()) s.background = opts.bg_color; + s.inline_mode = true; + return s; + } + + /// Convert a framework Color to a CellColor for cell-based compositing. + fn colorToCellColor(c: Color) CellColor { + return switch (c) { + .none => .none, + .ansi => |a| .{ .ansi = a }, + .ansi256 => |n| .{ .ansi256 = n }, + .rgb => |v| .{ .rgb = .{ v.r, v.g, v.b } }, + }; + } +}; + +// ═══════════════════════════════════════════════════════════════════════ +// Cell-based compositing types (à la Ratatui Buffer / Textual Segment) +// ═══════════════════════════════════════════════════════════════════════ + +/// Color as parsed from raw ANSI SGR — independent of the framework Color type. +const CellColor = union(enum) { + none, + ansi: AnsiColor, + ansi256: u8, + rgb: [3]u8, + + fn eql(a: CellColor, b: CellColor) bool { + const tag_a = @intFromEnum(std.meta.activeTag(a)); + const tag_b = @intFromEnum(std.meta.activeTag(b)); + if (tag_a != tag_b) return false; + return switch (a) { + .none => true, + .ansi => |va| va == b.ansi, + .ansi256 => |va| va == b.ansi256, + .rgb => |va| va[0] == b.rgb[0] and va[1] == b.rgb[1] and va[2] == b.rgb[2], + }; + } + + fn writeFg(self: CellColor, wr: anytype) !void { + switch (self) { + .none => try wr.writeAll("\x1b[39m"), + .ansi => |a| try wr.print("\x1b[{d}m", .{a.fgCode()}), + .ansi256 => |n| try wr.print("\x1b[38;5;{d}m", .{n}), + .rgb => |c| try wr.print("\x1b[38;2;{d};{d};{d}m", .{ c[0], c[1], c[2] }), + } + } + + fn writeBg(self: CellColor, wr: anytype) !void { + switch (self) { + .none => try wr.writeAll("\x1b[49m"), + .ansi => |a| try wr.print("\x1b[{d}m", .{a.bgCode()}), + .ansi256 => |n| try wr.print("\x1b[48;5;{d}m", .{n}), + .rgb => |c| try wr.print("\x1b[48;2;{d};{d};{d}m", .{ c[0], c[1], c[2] }), + } + } +}; + +/// Per-cell style parsed from ANSI SGR sequences. +const CellStyle = struct { + fg: CellColor = .none, + bg: CellColor = .none, + bold: bool = false, + dim: bool = false, + italic: bool = false, + underline: bool = false, + strikethrough: bool = false, + + fn eql(a: CellStyle, b: CellStyle) bool { + return a.fg.eql(b.fg) and a.bg.eql(b.bg) and + a.bold == b.bold and a.dim == b.dim and + a.italic == b.italic and a.underline == b.underline and + a.strikethrough == b.strikethrough; + } +}; + +/// A single terminal cell. +const Cell = struct { + char: []const u8 = " ", + style: CellStyle = .{}, + width: u8 = 1, // display width; 0 = continuation cell of wide char +}; + +/// 2D grid of cells — the intermediate buffer for compositing. +const CellGrid = struct { + cells: []Cell, + w: usize, + h: usize, + + fn get(self: *const CellGrid, row: usize, col: usize) Cell { + if (row >= self.h or col >= self.w) return Cell{}; + return self.cells[row * self.w + col]; + } + + fn set(self: *CellGrid, row: usize, col: usize, cell: Cell) void { + if (row >= self.h or col >= self.w) return; + self.cells[row * self.w + col] = cell; + } + + /// Parse an ANSI-encoded string into a cell grid. + fn parse(allocator: std.mem.Allocator, str: []const u8, width: usize, height: usize) !CellGrid { + const total = width * height; + const cells = try allocator.alloc(Cell, total); + for (cells) |*c| c.* = Cell{}; + + var cur_style = CellStyle{}; + var row: usize = 0; + var col: usize = 0; + var i: usize = 0; + + while (i < str.len) { + const c = str[i]; + + // Newline → next row + if (c == '\n') { + row += 1; + col = 0; + i += 1; + continue; + } + + // ESC sequence + if (c == 0x1b and i + 1 < str.len and str[i + 1] == '[') { + i += 2; // skip ESC [ + const params_start = i; + // Scan to final byte (letter) + while (i < str.len and !isCSIFinal(str[i])) : (i += 1) {} + if (i < str.len) { + const final = str[i]; + i += 1; + if (final == 'm') { + // SGR — update current style + const params = str[params_start .. i - 1]; + applySgr(&cur_style, params); + } + // Other CSI sequences are silently consumed + } + continue; + } + + // Bare ESC (non-CSI) + if (c == 0x1b) { + i += 1; + continue; + } + + // Control chars (except newline handled above) + if (c < 0x20) { + i += 1; + continue; + } + + // Visible character + if (row >= height) { + i += 1; + continue; + } + + const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; + const end = @min(i + byte_len, str.len); + const ch_slice = str[i..end]; + + var cw: usize = 1; + if (i + byte_len <= str.len) { + if (std.unicode.utf8Decode(str[i..][0..byte_len])) |cp| { + cw = unicode.charWidth(cp); + } else |_| {} + } + + if (col < width) { + cells[row * width + col] = .{ + .char = ch_slice, + .style = cur_style, + .width = @intCast(cw), + }; + // Mark continuation cells for wide characters + for (1..cw) |dx| { + if (col + dx < width) { + cells[row * width + col + dx] = .{ + .char = "", + .style = cur_style, + .width = 0, + }; + } + } + col += cw; + } + + i = end; + } + + return .{ .cells = cells, .w = width, .h = height }; + } + + /// Serialize the cell grid back to an ANSI string. + /// Emits SGR sequences only when the style changes between cells + /// (like Ratatui's Buffer::diff), producing minimal output. + fn render(self: *const CellGrid, allocator: std.mem.Allocator) ![]const u8 { + var buf: Writer.Allocating = .init(allocator); + const wr = &buf.writer; + + var prev_style = CellStyle{}; + + for (0..self.h) |row| { + if (row > 0) try wr.writeByte('\n'); + + // Track trailing spaces to avoid emitting them + for (0..self.w) |col| { + const cell = self.cells[row * self.w + col]; + + // Skip continuation cells + if (cell.width == 0) continue; + + // Emit style change if needed + if (!cell.style.eql(prev_style)) { + try emitStyleDiff(wr, prev_style, cell.style); + prev_style = cell.style; + } + + // Emit character + if (cell.char.len > 0) { + try wr.writeAll(cell.char); + } + } + } + + // Final reset + try wr.writeAll("\x1b[0m"); + + return buf.toOwnedSlice(); + } +}; + +/// Check if a byte is a CSI final byte (letter). +fn isCSIFinal(c: u8) bool { + return (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'); +} + +/// Apply an SGR parameter string to a CellStyle. +fn applySgr(style: *CellStyle, params: []const u8) void { + // Empty params = reset + if (params.len == 0) { + style.* = CellStyle{}; + return; + } + + var iter = std.mem.splitScalar(u8, params, ';'); + while (iter.next()) |param| { + const n = std.fmt.parseInt(u32, param, 10) catch continue; + switch (n) { + 0 => style.* = CellStyle{}, + 1 => style.bold = true, + 2 => style.dim = true, + 3 => style.italic = true, + 4 => style.underline = true, + 9 => style.strikethrough = true, + 22 => { + style.bold = false; + style.dim = false; + }, + 23 => style.italic = false, + 24 => style.underline = false, + 29 => style.strikethrough = false, + // Foreground basic colors + 30...37 => { + style.fg = .{ .ansi = @enumFromInt(n - 30) }; + }, + 39 => style.fg = .none, + // Background basic colors + 40...47 => { + style.bg = .{ .ansi = @enumFromInt(n - 40) }; + }, + 49 => style.bg = .none, + // Extended foreground + 38 => { + const sub_str = iter.next() orelse return; + const sub = std.fmt.parseInt(u32, sub_str, 10) catch return; + if (sub == 5) { + const ci_str = iter.next() orelse return; + const ci = std.fmt.parseInt(u8, ci_str, 10) catch return; + style.fg = .{ .ansi256 = ci }; + } else if (sub == 2) { + const r = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + const g = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + const b = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + style.fg = .{ .rgb = .{ r, g, b } }; + } + }, + // Extended background + 48 => { + const sub_str = iter.next() orelse return; + const sub = std.fmt.parseInt(u32, sub_str, 10) catch return; + if (sub == 5) { + const ci_str = iter.next() orelse return; + const ci = std.fmt.parseInt(u8, ci_str, 10) catch return; + style.bg = .{ .ansi256 = ci }; + } else if (sub == 2) { + const r = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + const g = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + const b = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; + style.bg = .{ .rgb = .{ r, g, b } }; + } + }, + // Bright foreground + 90...97 => { + style.fg = .{ .ansi = @enumFromInt(n - 90 + 8) }; + }, + // Bright background + 100...107 => { + style.bg = .{ .ansi = @enumFromInt(n - 100 + 8) }; + }, + else => {}, + } + } +} + +/// Emit the minimal SGR diff to transition from one style to another. +fn emitStyleDiff(wr: anytype, prev: CellStyle, next: CellStyle) !void { + // If the new style is default, just reset + const default_style = CellStyle{}; + if (next.eql(default_style)) { + try wr.writeAll("\x1b[0m"); + return; + } + + // If any attribute was turned off (true→false), we need a reset first + // since SGR doesn't have individual "off" codes for all attributes reliably. + const needs_reset = (prev.bold and !next.bold) or + (prev.dim and !next.dim) or + (prev.italic and !next.italic) or + (prev.underline and !next.underline) or + (prev.strikethrough and !next.strikethrough); + + if (needs_reset) { + try wr.writeAll("\x1b[0m"); + // After reset, emit all attributes of the new style + if (next.bold) try wr.writeAll("\x1b[1m"); + if (next.dim) try wr.writeAll("\x1b[2m"); + if (next.italic) try wr.writeAll("\x1b[3m"); + if (next.underline) try wr.writeAll("\x1b[4m"); + if (next.strikethrough) try wr.writeAll("\x1b[9m"); + if (!next.fg.eql(.none)) try next.fg.writeFg(wr); + if (!next.bg.eql(.none)) try next.bg.writeBg(wr); + return; + } + + // Otherwise, emit only what changed + if (!prev.fg.eql(next.fg)) try next.fg.writeFg(wr); + if (!prev.bg.eql(next.bg)) try next.bg.writeBg(wr); + if (!prev.bold and next.bold) try wr.writeAll("\x1b[1m"); + if (!prev.dim and next.dim) try wr.writeAll("\x1b[2m"); + if (!prev.italic and next.italic) try wr.writeAll("\x1b[3m"); + if (!prev.underline and next.underline) try wr.writeAll("\x1b[4m"); + if (!prev.strikethrough and next.strikethrough) try wr.writeAll("\x1b[9m"); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig new file mode 100644 index 0000000..1b46f3c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig @@ -0,0 +1,185 @@ +//! Tree component for displaying hierarchical data. +//! Renders a tree structure with expandable nodes and customizable enumerators. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; + +/// Enumerator defines the prefix characters for tree rendering +pub const Enumerator = struct { + item_prefix: []const u8, + last_prefix: []const u8, + indent_prefix: []const u8, + empty_prefix: []const u8, +}; + +/// Default tree enumerator with box-drawing characters +pub const DefaultEnumerator = Enumerator{ + .item_prefix = "├── ", + .last_prefix = "└── ", + .indent_prefix = "│ ", + .empty_prefix = " ", +}; + +/// Rounded tree enumerator +pub const RoundedEnumerator = Enumerator{ + .item_prefix = "├── ", + .last_prefix = "╰── ", + .indent_prefix = "│ ", + .empty_prefix = " ", +}; + +pub fn Tree(comptime T: type) type { + return struct { + allocator: std.mem.Allocator, + nodes: std.array_list.Managed(Node), + root_indices: std.array_list.Managed(usize), + enumerator: Enumerator, + node_style: style_mod.Style, + label_style: style_mod.Style, + + const Self = @This(); + + pub const Node = struct { + value: T, + label: []const u8, + children: std.array_list.Managed(usize), + expanded: bool, + style_override: ?style_mod.Style, + + pub fn deinit(self: *Node) void { + self.children.deinit(); + } + }; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .nodes = std.array_list.Managed(Node).init(allocator), + .root_indices = std.array_list.Managed(usize).init(allocator), + .enumerator = DefaultEnumerator, + .node_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + .label_style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + }; + } + + pub fn deinit(self: *Self) void { + for (self.nodes.items) |*node| { + node.deinit(); + } + self.nodes.deinit(); + self.root_indices.deinit(); + } + + /// Add a root node, returns its index + pub fn addRoot(self: *Self, value: T, label: []const u8) !usize { + const idx = self.nodes.items.len; + try self.nodes.append(.{ + .value = value, + .label = label, + .children = std.array_list.Managed(usize).init(self.allocator), + .expanded = true, + .style_override = null, + }); + try self.root_indices.append(idx); + return idx; + } + + /// Add a child node to a parent, returns child index + pub fn addChild(self: *Self, parent: usize, value: T, label: []const u8) !usize { + const idx = self.nodes.items.len; + try self.nodes.append(.{ + .value = value, + .label = label, + .children = std.array_list.Managed(usize).init(self.allocator), + .expanded = true, + .style_override = null, + }); + try self.nodes.items[parent].children.append(idx); + return idx; + } + + /// Toggle expand/collapse of a node + pub fn toggleNode(self: *Self, idx: usize) void { + if (idx < self.nodes.items.len) { + self.nodes.items[idx].expanded = !self.nodes.items[idx].expanded; + } + } + + /// Set enumerator style + pub fn setEnumerator(self: *Self, e: Enumerator) void { + self.enumerator = e; + } + + /// Render the tree + pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (self.root_indices.items, 0..) |root_idx, i| { + if (i > 0) try writer.writeAll("\n"); + try self.renderNode(writer, allocator, root_idx, "", true); + } + + return result.toOwnedSlice(); + } + + fn renderNode( + self: *const Self, + writer: *Writer, + allocator: std.mem.Allocator, + node_idx: usize, + prefix: []const u8, + is_root: bool, + ) !void { + const node = self.nodes.items[node_idx]; + const active_style = node.style_override orelse self.label_style; + + // Write prefix + try writer.writeAll(prefix); + + // Write label + const styled_label = try active_style.render(allocator, node.label); + try writer.writeAll(styled_label); + + // Render children if expanded + if (node.expanded and node.children.items.len > 0) { + const children = node.children.items; + for (children, 0..) |child_idx, ci| { + try writer.writeAll("\n"); + const is_last = (ci == children.len - 1); + const connector = if (is_last) self.enumerator.last_prefix else self.enumerator.item_prefix; + const child_prefix = if (is_last) self.enumerator.empty_prefix else self.enumerator.indent_prefix; + + // Build new prefix for children + var new_prefix = std.array_list.Managed(u8).init(allocator); + if (!is_root) { + try new_prefix.appendSlice(prefix); + } + try new_prefix.appendSlice(child_prefix); + const new_prefix_str = try new_prefix.toOwnedSlice(); + + // Write connector and recurse + var connector_prefix = std.array_list.Managed(u8).init(allocator); + if (!is_root) { + try connector_prefix.appendSlice(prefix); + } + try connector_prefix.appendSlice(connector); + const connector_str = try connector_prefix.toOwnedSlice(); + + try self.renderNode(writer, allocator, child_idx, connector_str, false); + _ = new_prefix_str; + } + } + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig new file mode 100644 index 0000000..69085e5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig @@ -0,0 +1,456 @@ +//! Scrollable content viewport component. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const measure = @import("../layout/measure.zig"); +const style = @import("../style/style.zig"); +const ansi = @import("../terminal/ansi.zig"); +const unicode = @import("../unicode.zig"); + +pub const Viewport = struct { + allocator: std.mem.Allocator, + + // Content + content: []const u8, + owned_content: ?[]u8, + lines: std.array_list.Managed([]const u8), + + // Dimensions + width: u16, + height: u16, + + // Scroll position (visual rows, display columns) + y_offset: usize, + x_offset: usize, + + // Styling + viewport_style: style.Style, + scrollbar_track_style: style.Style, + scrollbar_thumb_style: style.Style, + + // Options + wrap: bool, + show_scrollbar: bool, + empty_char: []const u8, + scrollbar_track_char: []const u8, + scrollbar_thumb_char: []const u8, + + pub fn init(allocator: std.mem.Allocator, width: u16, height: u16) Viewport { + return .{ + .allocator = allocator, + .content = "", + .owned_content = null, + .lines = std.array_list.Managed([]const u8).init(allocator), + .width = width, + .height = height, + .y_offset = 0, + .x_offset = 0, + .viewport_style = blk: { + var s = style.Style{}; + break :blk s.inline_style(true); + }, + .scrollbar_track_style = blk: { + var s = style.Style{}; + break :blk s.inline_style(true); + }, + .scrollbar_thumb_style = blk: { + var s = style.Style{}; + break :blk s.inline_style(true); + }, + .wrap = false, + .show_scrollbar = true, + .empty_char = " ", + .scrollbar_track_char = "░", + .scrollbar_thumb_char = "█", + }; + } + + pub fn deinit(self: *Viewport) void { + if (self.owned_content) |content| self.allocator.free(content); + self.lines.deinit(); + } + + pub fn setContent(self: *Viewport, content: []const u8) !void { + if (self.owned_content) |existing| self.allocator.free(existing); + const owned = try self.allocator.dupe(u8, content); + self.owned_content = owned; + self.content = owned; + self.lines.clearRetainingCapacity(); + + var iter = std.mem.splitScalar(u8, self.content, '\n'); + while (iter.next()) |line| { + try self.lines.append(line); + } + + self.clampScroll(); + } + + pub fn setSize(self: *Viewport, width: u16, height: u16) void { + self.width = width; + self.height = height; + self.clampScroll(); + } + + pub fn setWrap(self: *Viewport, wrap: bool) void { + self.wrap = wrap; + if (wrap) self.x_offset = 0; + self.clampScroll(); + } + + pub fn setShowScrollbar(self: *Viewport, show_scrollbar: bool) void { + self.show_scrollbar = show_scrollbar; + self.clampScroll(); + } + + pub fn setStyle(self: *Viewport, viewport_style: style.Style) void { + self.viewport_style = viewport_style.inline_style(true); + } + + pub fn setScrollbarStyle(self: *Viewport, track_style: style.Style, thumb_style: style.Style) void { + self.scrollbar_track_style = track_style.inline_style(true); + self.scrollbar_thumb_style = thumb_style.inline_style(true); + } + + pub fn setScrollbarChars(self: *Viewport, track_char: []const u8, thumb_char: []const u8) void { + self.scrollbar_track_char = track_char; + self.scrollbar_thumb_char = thumb_char; + } + + pub fn setEmptyChar(self: *Viewport, empty_char: []const u8) void { + self.empty_char = empty_char; + } + + pub fn scrollDown(self: *Viewport, n: usize) void { + self.y_offset += n; + self.clampScroll(); + } + + pub fn scrollUp(self: *Viewport, n: usize) void { + self.y_offset -|= n; + } + + pub fn scrollRight(self: *Viewport, n: usize) void { + if (self.wrap) return; + self.x_offset += n; + self.clampScroll(); + } + + pub fn scrollLeft(self: *Viewport, n: usize) void { + self.x_offset -|= n; + } + + pub fn scrollTo(self: *Viewport, y_offset: usize, x_offset: usize) void { + self.y_offset = y_offset; + self.x_offset = if (self.wrap) 0 else x_offset; + self.clampScroll(); + } + + pub fn gotoTop(self: *Viewport) void { + self.y_offset = 0; + } + + pub fn gotoBottom(self: *Viewport) void { + const total = self.totalVisualLines(); + if (total > self.height) { + self.y_offset = total - self.height; + } else { + self.y_offset = 0; + } + } + + pub fn pageDown(self: *Viewport) void { + self.scrollDown(self.height); + } + + pub fn pageUp(self: *Viewport) void { + self.scrollUp(self.height); + } + + pub fn halfPageDown(self: *Viewport) void { + self.scrollDown(self.height / 2); + } + + pub fn halfPageUp(self: *Viewport) void { + self.scrollUp(self.height / 2); + } + + pub fn scrollPercent(self: *const Viewport) u8 { + const total = self.totalVisualLines(); + if (total <= self.height) return 100; + const max_offset = total - self.height; + return @intCast(@min(100, (self.y_offset * 100) / max_offset)); + } + + pub fn atTop(self: *const Viewport) bool { + return self.y_offset == 0; + } + + pub fn atBottom(self: *const Viewport) bool { + const total = self.totalVisualLines(); + if (total <= self.height) return true; + return self.y_offset >= total - self.height; + } + + pub fn totalLines(self: *const Viewport) usize { + return self.lines.items.len; + } + + pub fn totalVisualLines(self: *const Viewport) usize { + return self.totalVisualLinesForWidth(self.visibleWidth()); + } + + fn totalVisualLinesForWidth(self: *const Viewport, visible_width: usize) usize { + if (self.lines.items.len == 0) return 0; + if (visible_width == 0) return 0; + + if (!self.wrap) return self.lines.items.len; + + var total: usize = 0; + for (self.lines.items) |line| { + const line_width = measure.width(line); + total += @max(@as(usize, 1), std.math.divCeil(usize, line_width, visible_width) catch 1); + } + return total; + } + + pub fn contentWidth(self: *const Viewport) usize { + var max_width: usize = 0; + for (self.lines.items) |line| { + max_width = @max(max_width, measure.width(line)); + } + return max_width; + } + + pub fn handleKey(self: *Viewport, key: keys.KeyEvent) void { + switch (key.key) { + .up => self.scrollUp(1), + .down => self.scrollDown(1), + .left => self.scrollLeft(1), + .right => self.scrollRight(1), + .page_up => self.pageUp(), + .page_down => self.pageDown(), + .home => self.gotoTop(), + .end => self.gotoBottom(), + .char => |c| switch (c) { + 'j' => self.scrollDown(1), + 'k' => self.scrollUp(1), + 'h' => self.scrollLeft(1), + 'l' => self.scrollRight(1), + 'g' => self.gotoTop(), + 'G' => self.gotoBottom(), + 'd' => self.halfPageDown(), + 'u' => self.halfPageUp(), + else => {}, + }, + else => {}, + } + } + + fn clampScroll(self: *Viewport) void { + const total_visual_lines = self.totalVisualLines(); + if (total_visual_lines > self.height) { + self.y_offset = @min(self.y_offset, total_visual_lines - self.height); + } else { + self.y_offset = 0; + } + + if (self.wrap) { + self.x_offset = 0; + return; + } + + const visible_width = self.visibleWidth(); + const total_width = self.contentWidth(); + if (total_width > visible_width) { + self.x_offset = @min(self.x_offset, total_width - visible_width); + } else { + self.x_offset = 0; + } + } + + pub fn view(self: *const Viewport, allocator: std.mem.Allocator) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const visible_width = self.visibleWidth(); + + var row: usize = 0; + while (row < self.height) : (row += 1) { + if (row > 0) try writer.writeByte('\n'); + + const line_text = try self.lineForVisualRow(allocator, self.y_offset + row, visible_width); + defer allocator.free(line_text); + + const padded = try self.padLine(allocator, line_text, visible_width); + defer allocator.free(padded); + + const rendered = try self.viewport_style.render(allocator, padded); + defer allocator.free(rendered); + try writer.writeAll(rendered); + + if (self.show_scrollbar and self.totalVisualLines() > self.height) { + const scrollbar = try self.renderScrollbar(allocator, row); + defer allocator.free(scrollbar); + try writer.writeAll(scrollbar); + } + } + + return result.toOwnedSlice(); + } + + fn visibleWidth(self: *const Viewport) usize { + if (!self.show_scrollbar) return self.width; + const with_scrollbar = self.width -| 1; + if (self.totalVisualLinesForWidth(@max(@as(usize, 1), with_scrollbar)) > self.height) { + return with_scrollbar; + } + return self.width; + } + + fn lineForVisualRow(self: *const Viewport, allocator: std.mem.Allocator, visual_row: usize, visible_width: usize) ![]const u8 { + if (visible_width == 0 or self.lines.items.len == 0) { + return try allocator.dupe(u8, ""); + } + + if (!self.wrap) { + if (visual_row >= self.lines.items.len) return try allocator.dupe(u8, ""); + const line = self.lines.items[visual_row]; + if (self.x_offset >= measure.width(line)) return try allocator.dupe(u8, ""); + return try self.getSubstring(allocator, line, self.x_offset, visible_width); + } + + var remaining = visual_row; + for (self.lines.items) |line| { + const line_width = measure.width(line); + const segments = @max(@as(usize, 1), std.math.divCeil(usize, line_width, visible_width) catch 1); + if (remaining < segments) { + return try self.getSubstring(allocator, line, remaining * visible_width, visible_width); + } + remaining -= segments; + } + + return try allocator.dupe(u8, ""); + } + + fn padLine(self: *const Viewport, allocator: std.mem.Allocator, line: []const u8, visible_width: usize) ![]const u8 { + const current_width = measure.width(line); + if (current_width >= visible_width) return try allocator.dupe(u8, line); + + var out = std.array_list.Managed(u8).init(allocator); + try out.appendSlice(line); + for (0..(visible_width - current_width)) |_| { + try out.appendSlice(self.empty_char); + } + return out.toOwnedSlice(); + } + + fn getSubstring(self: *const Viewport, allocator: std.mem.Allocator, line: []const u8, start_col: usize, max_width: usize) ![]const u8 { + _ = self; + var result: std.array_list.Managed(u8) = .init(allocator); + + var col: usize = 0; + var i: usize = 0; + var wrote_escape = false; + + while (i < line.len and col < start_col) { + if (line[i] == 0x1b) { + const seq_end = ansiSequenceEnd(line, i); + if (seq_end > i) { + try result.appendSlice(line[i..seq_end]); + wrote_escape = true; + i = seq_end; + continue; + } + } + + const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; + if (i + byte_len <= line.len) { + const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { + i += 1; + col += 1; + continue; + }; + col += unicode.charWidth(cp); + } + i += byte_len; + } + + var output_width: usize = 0; + while (i < line.len and output_width < max_width) { + if (line[i] == 0x1b) { + const seq_end = ansiSequenceEnd(line, i); + if (seq_end > i) { + try result.appendSlice(line[i..seq_end]); + wrote_escape = true; + i = seq_end; + continue; + } + } + + const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; + if (i + byte_len <= line.len) { + const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { + try result.append(line[i]); + i += 1; + output_width += 1; + continue; + }; + const cw = unicode.charWidth(cp); + if (output_width + cw > max_width) break; + try result.appendSlice(line[i..][0..byte_len]); + output_width += cw; + } + i += byte_len; + } + + if (wrote_escape and !std.mem.endsWith(u8, result.items, ansi.reset)) { + try result.appendSlice(ansi.reset); + } + + return result.toOwnedSlice(); + } + + fn renderScrollbar(self: *const Viewport, allocator: std.mem.Allocator, row: usize) ![]const u8 { + const total = self.totalVisualLines(); + const visible = self.height; + + if (total <= visible) return try allocator.dupe(u8, ""); + + const scrollbar_height = @max(1, (visible * visible) / total); + const max_offset = total - visible; + const scrollbar_pos = if (max_offset == 0) 0 else (self.y_offset * (visible - scrollbar_height)) / max_offset; + + const glyph = if (row >= scrollbar_pos and row < scrollbar_pos + scrollbar_height) + try self.scrollbar_thumb_style.render(allocator, self.scrollbar_thumb_char) + else + try self.scrollbar_track_style.render(allocator, self.scrollbar_track_char); + + return glyph; + } +}; + +fn ansiSequenceEnd(line: []const u8, start: usize) usize { + if (start >= line.len or line[start] != 0x1b or start + 1 >= line.len) return start; + + const second = line[start + 1]; + if (second == '[') { + var i = start + 2; + while (i < line.len) : (i += 1) { + const c = line[i]; + if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) return i + 1; + } + return line.len; + } + + if (second == ']') { + var i = start + 2; + while (i < line.len) : (i += 1) { + if (line[i] == 0x07) return i + 1; + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '\\') return i + 2; + } + return line.len; + } + + return @min(line.len, start + 2); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig new file mode 100644 index 0000000..cfaadda --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig @@ -0,0 +1,216 @@ +//! Virtual list component for efficiently rendering large datasets. +//! Only renders items visible in the viewport. + +const std = @import("std"); +const Writer = std.Io.Writer; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const keys = @import("../input/keys.zig"); +const measure = @import("../layout/measure.zig"); + +pub fn VirtualList(comptime T: type) type { + return struct { + /// All items (not copied — references the original slice). + items: []const T = &.{}, + /// Number of visible rows. + viewport_height: u16 = 20, + /// Current cursor position (absolute index). + cursor: usize = 0, + /// Scroll offset (first visible item index). + offset: usize = 0, + /// Selection set. + selected: ?std.AutoHashMap(usize, void) = null, + /// Multi-select mode. + multi_select: bool = false, + /// Focused state. + focused: bool = true, + /// Render function: called for each visible item. + render_fn: ?*const fn (item: T, index: usize, selected: bool, allocator: std.mem.Allocator) []const u8 = null, + /// Wrap cursor around list ends. + wrap_around: bool = false, + /// Text shown when list is empty. + empty_text: []const u8 = "(empty)", + /// Width for each row (0 = no padding). + row_width: u16 = 0, + + // Styling + cursor_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.bg(.blue); + s = s.fg(.white); + s = s.inline_style(true); + break :blk s; + }, + item_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.inline_style(true); + break :blk s; + }, + selected_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.green); + s = s.inline_style(true); + break :blk s; + }, + scrollbar_style: style_mod.Style = blk: { + var s = style_mod.Style{}; + s = s.fg(.gray(8)); + s = s.inline_style(true); + break :blk s; + }, + /// Cursor prefix. + cursor_symbol: []const u8 = "> ", + /// Normal prefix. + normal_symbol: []const u8 = " ", + /// Show scrollbar. + show_scrollbar: bool = true, + /// Show item count. + show_count: bool = true, + + const Self = @This(); + + pub fn setItems(self: *Self, items: []const T) void { + self.items = items; + if (self.cursor >= items.len and items.len > 0) { + self.cursor = items.len - 1; + } + self.ensureVisible(); + } + + pub fn update(self: *Self, key: keys.KeyEvent) void { + const total = self.items.len; + if (total == 0) return; + + switch (key.key) { + .up => { + if (self.cursor > 0) { + self.cursor -= 1; + } else if (self.wrap_around and total > 0) { + self.cursor = total - 1; + } + self.ensureVisible(); + }, + .down => { + if (self.cursor + 1 < total) { + self.cursor += 1; + } else if (self.wrap_around) { + self.cursor = 0; + } + self.ensureVisible(); + }, + .page_up => { + if (self.cursor >= self.viewport_height) { + self.cursor -= self.viewport_height; + } else { + self.cursor = 0; + } + self.ensureVisible(); + }, + .page_down => { + self.cursor += self.viewport_height; + if (self.cursor >= total) self.cursor = total - 1; + self.ensureVisible(); + }, + .home => { + self.cursor = 0; + self.ensureVisible(); + }, + .end => { + if (total > 0) self.cursor = total - 1; + self.ensureVisible(); + }, + .char => |c| { + if (c == ' ' and self.multi_select) { + self.toggleSelection(self.cursor); + } + }, + .enter => { + self.toggleSelection(self.cursor); + }, + else => {}, + } + } + + fn toggleSelection(self: *Self, index: usize) void { + _ = self; + _ = index; + // Selection is managed externally; this is a placeholder for signaling + } + + fn ensureVisible(self: *Self) void { + if (self.cursor < self.offset) { + self.offset = self.cursor; + } + if (self.cursor >= self.offset + self.viewport_height) { + self.offset = self.cursor - self.viewport_height + 1; + } + } + + pub fn view(self: *const Self, allocator: std.mem.Allocator) []const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + const total = self.items.len; + const vh: usize = self.viewport_height; + + if (total == 0) { + writer.writeAll(self.empty_text) catch {}; + return result.toArrayList().items; + } + + const end = @min(self.offset + vh, total); + + for (self.offset..end) |i| { + if (i > self.offset) writer.writeByte('\n') catch {}; + + const is_cursor = (i == self.cursor and self.focused); + const is_selected = false; // Could check selection map + + // Get item text + const item_text = if (self.render_fn) |rf| + rf(self.items[i], i, is_selected, allocator) + else + defaultRender(self.items[i], i, allocator); + + // Apply style + const prefix = if (is_cursor) self.cursor_symbol else self.normal_symbol; + const s = if (is_cursor) self.cursor_style else if (is_selected) self.selected_style else self.item_style; + + const line = std.fmt.allocPrint(allocator, "{s}{s}", .{ prefix, item_text }) catch item_text; + writer.writeAll(s.render(allocator, line) catch line) catch {}; + + // Scrollbar + if (self.show_scrollbar and total > vh) { + const row = i - self.offset; + const thumb_start = (self.offset * vh) / total; + const thumb_size = @max(1, (vh * vh) / total); + const is_thumb = row >= thumb_start and row < thumb_start + thumb_size; + const sb_char: []const u8 = if (is_thumb) "\xe2\x96\x88" else "\xe2\x96\x91"; + writer.writeByte(' ') catch {}; + writer.writeAll(self.scrollbar_style.render(allocator, sb_char) catch sb_char) catch {}; + } + } + + // Item count + if (self.show_count) { + writer.writeByte('\n') catch {}; + const count_str = std.fmt.allocPrint(allocator, " {d}/{d}", .{ self.cursor + 1, total }) catch ""; + var cs = style_mod.Style{}; + cs = cs.fg(.gray(10)); + cs = cs.inline_style(true); + writer.writeAll(cs.render(allocator, count_str) catch count_str) catch {}; + } + + return result.toArrayList().items; + } + + fn defaultRender(item: T, index: usize, allocator: std.mem.Allocator) []const u8 { + if (comptime @typeInfo(T) == .pointer) { + if (comptime @typeInfo(std.meta.Child(T)) == .int) { + // T is []const u8 + return item; + } + } + return std.fmt.allocPrint(allocator, "Item {d}", .{index}) catch "?"; + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig new file mode 100644 index 0000000..2728a74 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig @@ -0,0 +1,410 @@ +//! Action / command registry — central source of truth for app actions. +//! +//! Inspired by Textual's action system. An `Action` couples a stable string +//! ID, a human label, an optional key binding, and an optional category to a +//! single registry. The same registry feeds: +//! +//! * the keybinding matcher (key event → action id) +//! * the auto-footer (one-line key hint bar) +//! * the command palette (filterable list of all actions) +//! * the help screen +//! +//! The user's `update` function looks up the matching action by id, eg.: +//! +//! if (registry.matchKey(key_event)) |action| { +//! return self.dispatch(action.id); +//! } +//! +//! and a `dispatch` switch on `action.id` calls the right handler. Optional +//! `handler` callbacks are also supported for fire-and-forget actions. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("../input/keys.zig"); +const KeyEvent = keys.KeyEvent; +const style_mod = @import("../style/style.zig"); +const Color = @import("../style/color.zig").Color; +const measure = @import("../layout/measure.zig"); +const fuzzy = @import("fuzzy.zig"); + +/// Optional callback shape. Receives the user-supplied context pointer the +/// registry was created with — typically the app model. +pub const Handler = *const fn (user_ctx: ?*anyopaque) void; + +pub const Action = struct { + /// Stable string identifier, eg. "app.quit", "file.save". + id: []const u8, + /// User-facing label, eg. "Quit", "Save File". + label: []const u8, + /// Longer description for palette / help. + description: []const u8 = "", + /// Optional category for grouping in help / palette, eg. "File", "Edit". + category: []const u8 = "", + /// Optional primary key binding. Other bindings can be added via + /// `addBinding` if you want chord-style or aliases. + binding: ?KeyEvent = null, + /// Whether this action shows up in match/footer/palette. + enabled: bool = true, + /// Whether this action is shown in the auto-footer hint bar. + show_in_footer: bool = false, + /// Optional fire-and-forget callback. The registry calls this when the + /// matching key fires, in addition to returning the action so the user's + /// update function can switch on the id. + handler: ?Handler = null, +}; + +pub const ActionRegistry = struct { + allocator: std.mem.Allocator, + actions: std.array_list.Managed(Action), + /// Optional aliases: extra key events that map to the same action. + aliases: std.array_list.Managed(Alias), + /// Pointer passed to `Handler` callbacks. Typically the app model. + user_ctx: ?*anyopaque, + + pub const Alias = struct { + id: []const u8, + binding: KeyEvent, + }; + + pub fn init(allocator: std.mem.Allocator) ActionRegistry { + return .{ + .allocator = allocator, + .actions = std.array_list.Managed(Action).init(allocator), + .aliases = std.array_list.Managed(Alias).init(allocator), + .user_ctx = null, + }; + } + + pub fn deinit(self: *ActionRegistry) void { + self.actions.deinit(); + self.aliases.deinit(); + } + + pub fn setUserContext(self: *ActionRegistry, ctx: *anyopaque) void { + self.user_ctx = ctx; + } + + pub fn register(self: *ActionRegistry, action: Action) !void { + // Detect duplicate ids early — registry is a "single source of truth". + for (self.actions.items) |existing| { + if (std.mem.eql(u8, existing.id, action.id)) return error.DuplicateActionId; + } + try self.actions.append(action); + } + + /// Replace an action's binding by id. Returns true if the action existed. + pub fn rebind(self: *ActionRegistry, id: []const u8, binding: ?KeyEvent) bool { + for (self.actions.items) |*a| { + if (std.mem.eql(u8, a.id, id)) { + a.binding = binding; + return true; + } + } + return false; + } + + pub fn setEnabled(self: *ActionRegistry, id: []const u8, enabled: bool) bool { + for (self.actions.items) |*a| { + if (std.mem.eql(u8, a.id, id)) { + a.enabled = enabled; + return true; + } + } + return false; + } + + /// Add an additional key alias for an existing action. + pub fn addAlias(self: *ActionRegistry, id: []const u8, binding: KeyEvent) !void { + // Validate the action exists. + for (self.actions.items) |a| { + if (std.mem.eql(u8, a.id, id)) { + try self.aliases.append(.{ .id = id, .binding = binding }); + return; + } + } + return error.UnknownAction; + } + + pub fn get(self: *const ActionRegistry, id: []const u8) ?*const Action { + for (self.actions.items) |*a| { + if (std.mem.eql(u8, a.id, id)) return a; + } + return null; + } + + /// Look up the action matching `event`. Returns null when no enabled + /// action is bound. Calls the action's handler if present. + pub fn matchKey(self: *const ActionRegistry, event: KeyEvent) ?*const Action { + for (self.actions.items) |*a| { + if (!a.enabled) continue; + if (a.binding) |b| { + if (b.eql(event)) { + if (a.handler) |h| h(self.user_ctx); + return a; + } + } + } + for (self.aliases.items) |alias| { + if (alias.binding.eql(event)) { + const a = self.get(alias.id) orelse continue; + if (!a.enabled) continue; + if (a.handler) |h| h(self.user_ctx); + return a; + } + } + return null; + } + + /// Invoke the action's handler explicitly (eg. selected from the palette). + /// Returns true if the action exists and is enabled. + pub fn invoke(self: *const ActionRegistry, id: []const u8) bool { + const a = self.get(id) orelse return false; + if (!a.enabled) return false; + if (a.handler) |h| h(self.user_ctx); + return true; + } + + /// Iterate enabled actions matching a fuzzy query. Caller owns the + /// returned slice. Useful for feeding a CommandPalette. + pub fn filter(self: *const ActionRegistry, allocator: std.mem.Allocator, query: []const u8) ![]const *const Action { + var out = std.array_list.Managed(*const Action).init(allocator); + errdefer out.deinit(); + if (query.len == 0) { + for (self.actions.items) |*a| { + if (a.enabled) try out.append(a); + } + return out.toOwnedSlice(); + } + + const Scored = struct { ptr: *const Action, score: i32 }; + var scored = std.array_list.Managed(Scored).init(allocator); + defer scored.deinit(); + + for (self.actions.items) |*a| { + if (!a.enabled) continue; + const s = fuzzy.scoreIgnoreCase(a.label, query); + if (s > 0) try scored.append(.{ .ptr = a, .score = s }); + } + + std.mem.sort(Scored, scored.items, {}, struct { + fn lt(_: void, l: Scored, r: Scored) bool { + return l.score > r.score; + } + }.lt); + + for (scored.items) |s| try out.append(s.ptr); + return out.toOwnedSlice(); + } + + /// Format a key event for display: "ctrl+s", "esc", "enter", etc. + pub fn formatKey(allocator: std.mem.Allocator, event: KeyEvent) ![]u8 { + var out: Writer.Allocating = .init(allocator); + const w = &out.writer; + if (event.modifiers.ctrl) try w.writeAll("ctrl+"); + if (event.modifiers.alt) try w.writeAll("alt+"); + if (event.modifiers.shift) try w.writeAll("shift+"); + if (event.modifiers.super) try w.writeAll("super+"); + switch (event.key) { + .char => |c| { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch 0; + try w.writeAll(buf[0..len]); + }, + .escape => try w.writeAll("esc"), + .enter => try w.writeAll("⏎"), + .space => try w.writeAll("space"), + .tab => try w.writeAll("⇥"), + .left => try w.writeAll("←"), + .right => try w.writeAll("→"), + .up => try w.writeAll("↑"), + .down => try w.writeAll("↓"), + else => try w.writeAll(event.key.name()), + } + return out.toOwnedSlice(); + } +}; + +/// Auto-rendered single-line footer that shows the bindings for actions +/// flagged with `show_in_footer = true`. Useful as a persistent key hint +/// bar at the bottom of the screen, kept in sync with the registry. +pub const Footer = struct { + registry: *const ActionRegistry, + width: u16 = 80, + separator: []const u8 = " ", + key_style: style_mod.Style, + label_style: style_mod.Style, + base_style: style_mod.Style, + + pub fn init(registry: *const ActionRegistry) Footer { + var key_s = style_mod.Style{}; + key_s = key_s.fg(.cyan); + key_s = key_s.bold(true); + key_s = key_s.inline_style(true); + var label_s = style_mod.Style{}; + label_s = label_s.fg(.gray(12)); + label_s = label_s.inline_style(true); + var base = style_mod.Style{}; + base = base.bg(.gray(3)); + base = base.inline_style(true); + return .{ + .registry = registry, + .key_style = key_s, + .label_style = label_s, + .base_style = base, + }; + } + + pub fn setWidth(self: *Footer, w: u16) void { + self.width = w; + } + + pub fn view(self: *const Footer, allocator: std.mem.Allocator) ![]const u8 { + var inner: Writer.Allocating = .init(allocator); + defer inner.deinit(); + const w = &inner.writer; + + var first = true; + for (self.registry.actions.items) |a| { + if (!a.enabled or !a.show_in_footer) continue; + const binding = a.binding orelse continue; + if (!first) try w.writeAll(self.separator); + first = false; + const key_str = try ActionRegistry.formatKey(allocator, binding); + defer allocator.free(key_str); + const styled_key = try self.key_style.render(allocator, key_str); + defer allocator.free(styled_key); + try w.writeAll(styled_key); + try w.writeByte(' '); + const styled_label = try self.label_style.render(allocator, a.label); + defer allocator.free(styled_label); + try w.writeAll(styled_label); + } + + // Pad / truncate to width and apply base background. + const text = try inner.toOwnedSlice(); + defer allocator.free(text); + const text_w = measure.width(text); + + var out: Writer.Allocating = .init(allocator); + const ow = &out.writer; + try ow.writeAll(text); + if (text_w < self.width) { + const pad = self.width - text_w; + const spaces = try allocator.alloc(u8, pad); + defer allocator.free(spaces); + @memset(spaces, ' '); + const styled_pad = try self.base_style.render(allocator, spaces); + defer allocator.free(styled_pad); + try ow.writeAll(styled_pad); + } + return out.toOwnedSlice(); + } +}; + +// ── Tests ────────────────────────────────────────────────────────────── + +const testing = std.testing; + +test "register and lookup by id" { + var reg = ActionRegistry.init(testing.allocator); + defer reg.deinit(); + + try reg.register(.{ .id = "app.quit", .label = "Quit" }); + const a = reg.get("app.quit").?; + try testing.expectEqualStrings("Quit", a.label); +} + +test "duplicate id rejected" { + var reg = ActionRegistry.init(testing.allocator); + defer reg.deinit(); + try reg.register(.{ .id = "x", .label = "X" }); + const r = reg.register(.{ .id = "x", .label = "X again" }); + try testing.expectError(error.DuplicateActionId, r); +} + +test "matchKey routes by binding" { + var reg = ActionRegistry.init(testing.allocator); + defer reg.deinit(); + try reg.register(.{ + .id = "file.save", + .label = "Save", + .binding = .{ .key = .{ .char = 's' }, .modifiers = .{ .ctrl = true } }, + }); + const event: KeyEvent = .{ .key = .{ .char = 's' }, .modifiers = .{ .ctrl = true } }; + const a = reg.matchKey(event).?; + try testing.expectEqualStrings("file.save", a.id); +} + +test "matchKey returns null for unbound" { + var reg = ActionRegistry.init(testing.allocator); + defer reg.deinit(); + try reg.register(.{ .id = "noop", .label = "Noop" }); + const ev: KeyEvent = .{ .key = .{ .char = 'q' } }; + try testing.expectEqual(@as(?*const Action, null), reg.matchKey(ev)); +} + +test "alias matches same action" { + var reg = ActionRegistry.init(testing.allocator); + defer reg.deinit(); + try reg.register(.{ + .id = "view.toggle", + .label = "Toggle", + .binding = .{ .key = .{ .char = 't' } }, + }); + try reg.addAlias("view.toggle", .{ .key = .f5 }); + const a = reg.matchKey(.{ .key = .f5 }).?; + try testing.expectEqualStrings("view.toggle", a.id); +} + +test "filter ranks by fuzzy match" { + const allocator = testing.allocator; + var reg = ActionRegistry.init(allocator); + defer reg.deinit(); + try reg.register(.{ .id = "open", .label = "Open File" }); + try reg.register(.{ .id = "save", .label = "Save File" }); + try reg.register(.{ .id = "close", .label = "Close Window" }); + + const matches = try reg.filter(allocator, "of"); + defer allocator.free(matches); + try testing.expect(matches.len >= 1); + try testing.expectEqualStrings("open", matches[0].id); +} + +test "footer shows only flagged actions" { + const allocator = testing.allocator; + var reg = ActionRegistry.init(allocator); + defer reg.deinit(); + try reg.register(.{ + .id = "app.quit", + .label = "Quit", + .binding = .{ .key = .{ .char = 'q' } }, + .show_in_footer = true, + }); + try reg.register(.{ + .id = "internal", + .label = "Hidden", + .binding = .{ .key = .{ .char = 'h' } }, + .show_in_footer = false, + }); + + const footer = Footer.init(®); + const out = try footer.view(allocator); + defer allocator.free(out); + + try testing.expect(std.mem.indexOf(u8, out, "Quit") != null); + try testing.expect(std.mem.indexOf(u8, out, "Hidden") == null); +} + +test "formatKey produces readable strings" { + const allocator = testing.allocator; + const ctrl_s = try ActionRegistry.formatKey(allocator, .{ + .key = .{ .char = 's' }, + .modifiers = .{ .ctrl = true }, + }); + defer allocator.free(ctrl_s); + try testing.expectEqualStrings("ctrl+s", ctrl_s); + + const escape = try ActionRegistry.formatKey(allocator, .{ .key = .escape }); + defer allocator.free(escape); + try testing.expectEqualStrings("esc", escape); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig new file mode 100644 index 0000000..3296928 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig @@ -0,0 +1,185 @@ +//! Animation and tween system. +//! Provides easing functions and a Tween for interpolating values over time. + +const std = @import("std"); +const Color = @import("../style/color.zig").Color; +const progress_mod = @import("../components/progress.zig"); + +/// Easing functions that map t in [0,1] to an output in [0,1]. +pub const Easing = enum { + linear, + ease_in, + ease_out, + ease_in_out, + ease_in_cubic, + ease_out_cubic, + ease_in_out_cubic, + bounce, + elastic, + + pub fn apply(self: Easing, t: f64) f64 { + const clamped = @max(0.0, @min(1.0, t)); + return switch (self) { + .linear => clamped, + .ease_in => clamped * clamped, + .ease_out => 1.0 - (1.0 - clamped) * (1.0 - clamped), + .ease_in_out => if (clamped < 0.5) + 2.0 * clamped * clamped + else + 1.0 - std.math.pow(f64, -2.0 * clamped + 2.0, 2) / 2.0, + .ease_in_cubic => clamped * clamped * clamped, + .ease_out_cubic => 1.0 - std.math.pow(f64, 1.0 - clamped, 3), + .ease_in_out_cubic => if (clamped < 0.5) + 4.0 * clamped * clamped * clamped + else + 1.0 - std.math.pow(f64, -2.0 * clamped + 2.0, 3) / 2.0, + .bounce => blk: { + var b = 1.0 - clamped; + if (b < 1.0 / 2.75) { + break :blk 1.0 - (7.5625 * b * b); + } else if (b < 2.0 / 2.75) { + b -= 1.5 / 2.75; + break :blk 1.0 - (7.5625 * b * b + 0.75); + } else if (b < 2.5 / 2.75) { + b -= 2.25 / 2.75; + break :blk 1.0 - (7.5625 * b * b + 0.9375); + } else { + b -= 2.625 / 2.75; + break :blk 1.0 - (7.5625 * b * b + 0.984375); + } + }, + .elastic => if (clamped == 0.0 or clamped == 1.0) + clamped + else + -std.math.pow(f64, 2.0, 10.0 * clamped - 10.0) * + @sin((clamped * 10.0 - 10.75) * (2.0 * std.math.pi / 3.0)), + }; + } +}; + +/// A tween that interpolates a f64 value from `start` to `end` over `duration_ns`. +pub const Tween = struct { + start_val: f64, + end_val: f64, + duration_ns: u64, + elapsed_ns: u64, + easing: Easing, + state: State, + loop_mode: LoopMode, + + pub const State = enum { + idle, + running, + finished, + }; + + pub const LoopMode = enum { + once, + loop, + ping_pong, + }; + + /// Create a new tween. + pub fn init(from: f64, to: f64, duration_ms: u64) Tween { + return .{ + .start_val = from, + .end_val = to, + .duration_ns = duration_ms * std.time.ns_per_ms, + .elapsed_ns = 0, + .easing = .linear, + .state = .idle, + .loop_mode = .once, + }; + } + + /// Set easing function. + pub fn setEasing(self: *Tween, easing: Easing) void { + self.easing = easing; + } + + /// Set loop mode. + pub fn setLoop(self: *Tween, mode: LoopMode) void { + self.loop_mode = mode; + } + + /// Start the tween. + pub fn start(self: *Tween) void { + self.state = .running; + self.elapsed_ns = 0; + } + + /// Reset to beginning. + pub fn reset(self: *Tween) void { + self.elapsed_ns = 0; + self.state = .idle; + } + + /// Update with delta time in nanoseconds. + pub fn update(self: *Tween, delta_ns: u64) void { + if (self.state != .running) return; + + self.elapsed_ns += delta_ns; + + if (self.elapsed_ns >= self.duration_ns) { + switch (self.loop_mode) { + .once => { + self.elapsed_ns = self.duration_ns; + self.state = .finished; + }, + .loop => { + self.elapsed_ns = self.elapsed_ns % self.duration_ns; + }, + .ping_pong => { + self.elapsed_ns = self.elapsed_ns % (self.duration_ns * 2); + }, + } + } + } + + /// Get the current interpolated value. + pub fn value(self: *const Tween) f64 { + if (self.duration_ns == 0) return self.end_val; + + var t: f64 = @as(f64, @floatFromInt(self.elapsed_ns)) / @as(f64, @floatFromInt(self.duration_ns)); + + // Ping-pong: reverse in second half + if (self.loop_mode == .ping_pong and t > 1.0) { + t = 2.0 - t; + } + + t = @max(0.0, @min(1.0, t)); + const eased = self.easing.apply(t); + return self.start_val + (self.end_val - self.start_val) * eased; + } + + /// Get value as integer. + pub fn intValue(self: *const Tween) i64 { + return @intFromFloat(self.value()); + } + + /// Check if finished (only relevant for .once mode). + pub fn isFinished(self: *const Tween) bool { + return self.state == .finished; + } + + /// Check if running. + pub fn isRunning(self: *const Tween) bool { + return self.state == .running; + } + + /// Get normalized progress [0, 1]. + pub fn progress(self: *const Tween) f64 { + if (self.duration_ns == 0) return 1.0; + return @min(1.0, @as(f64, @floatFromInt(self.elapsed_ns)) / @as(f64, @floatFromInt(self.duration_ns))); + } +}; + +/// Interpolate between two colors using a tween. +pub fn tweenColor(start: Color, end: Color, t: f64) Color { + return progress_mod.interpolateColor(start, end, @max(0.0, @min(1.0, t))); +} + +/// Convenience: lerp between two f64 values. +pub fn lerp(a: f64, b: f64, t: f64) f64 { + return a + (b - a) * @max(0.0, @min(1.0, t)); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig new file mode 100644 index 0000000..f4e1dd9 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig @@ -0,0 +1,108 @@ +//! Async task runner for background work in ZigZag. +//! Spawns threads that execute functions and queue result messages. + +const std = @import("std"); + +/// Thread-safe result queue for async tasks. +pub fn AsyncRunner(comptime Msg: type) type { + return struct { + allocator: std.mem.Allocator, + results: ResultQueue, + next_id: u32 = 1, + + const Self = @This(); + const ResultQueue = std.array_list.Managed(?Msg); + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .results = ResultQueue.init(allocator), + }; + } + + pub fn deinit(self: *Self) void { + self.results.deinit(); + } + + /// Spawn a background task. The function runs on a new thread and + /// its return value is queued as a message for the next frame. + pub fn spawn(self: *Self, func: *const fn () ?Msg) u32 { + const id = self.next_id; + self.next_id += 1; + + const ctx = self.allocator.create(SpawnContext) catch return 0; + ctx.* = .{ .func = func, .runner = self }; + + _ = std.Thread.spawn(.{}, runTask, .{ctx}) catch { + self.allocator.destroy(ctx); + return 0; + }; + + return id; + } + + /// Spawn with a context argument. + pub fn spawnWithArg(self: *Self, comptime ArgT: type, arg: ArgT, func: *const fn (ArgT) ?Msg) u32 { + const id = self.next_id; + self.next_id += 1; + + const Closure = struct { + arg_val: ArgT, + func_ptr: *const fn (ArgT) ?Msg, + runner_ptr: *Self, + + fn execute(closure: *@This()) void { + const result = closure.func_ptr(closure.arg_val); + if (result) |m| { + closure.runner_ptr.pushResult(m); + } + } + }; + + const closure = self.allocator.create(Closure) catch return 0; + closure.* = .{ .arg_val = arg, .func_ptr = func, .runner_ptr = self }; + + _ = std.Thread.spawn(.{}, struct { + fn run(c: *Closure) void { + c.execute(); + } + }.run, .{closure}) catch { + self.allocator.destroy(closure); + return 0; + }; + + return id; + } + + /// Poll for completed results. Returns messages from finished tasks. + /// Call this each frame to collect async results. + pub fn poll(self: *Self) []Msg { + if (self.results.items.len == 0) return &.{}; + + var msgs = std.array_list.Managed(Msg).init(self.allocator); + for (self.results.items) |maybe_msg| { + if (maybe_msg) |m| { + msgs.append(m) catch {}; + } + } + self.results.clearRetainingCapacity(); + return msgs.items; + } + + fn pushResult(self: *Self, m: Msg) void { + self.results.append(m) catch {}; + } + + const SpawnContext = struct { + func: *const fn () ?Msg, + runner: *Self, + }; + + fn runTask(ctx: *SpawnContext) void { + const result = ctx.func(); + if (result) |m| { + ctx.runner.pushResult(m); + } + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig new file mode 100644 index 0000000..bb504aa --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig @@ -0,0 +1,304 @@ +//! Command system for the ZigZag TUI framework. +//! Commands represent side effects and actions to be performed. + +const std = @import("std"); + +/// Parameters for image rendering by file path. +pub const ImagePlacement = enum { + /// Use the current cursor position. + cursor, + /// Draw from top-left corner. + top_left, + /// Draw from top-center using width hint. + top_center, + /// Center using provided width/height cell hints. + center, +}; + +/// Preferred image protocol for rendering. +pub const ImageProtocol = enum { + /// Auto-select best available (Kitty > iTerm2 > Sixel). + auto, + /// Force Kitty graphics protocol. + kitty, + /// Force iTerm2 inline image protocol. + iterm2, + /// Force Sixel graphics protocol. + sixel, +}; + +/// Pixel format for in-memory image data. +pub const ImageFormat = enum(u16) { + rgb = 24, + rgba = 32, + png = 100, +}; + +/// Parameters for image rendering by file path. +pub const ImageFile = struct { + path: []const u8, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + placement: ImagePlacement = .top_left, + /// Optional absolute row (0-indexed). Overrides anchor row when provided. + row: ?u16 = null, + /// Optional absolute column (0-indexed). Overrides anchor column when provided. + col: ?u16 = null, + /// Signed row offset (in terminal cells) applied after anchor/absolute position. + row_offset: i16 = 0, + /// Signed column offset (in terminal cells) applied after anchor/absolute position. + col_offset: i16 = 0, + preserve_aspect_ratio: bool = true, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + /// Preferred protocol (default: auto-select). + protocol: ImageProtocol = .auto, + /// Z-index for layering (Kitty only). Negative = behind text. + z_index: ?i32 = null, + /// Enable unicode placeholders (Kitty only). Images participate in text reflow. + unicode_placeholder: bool = false, +}; + +/// Parameters for rendering in-memory image data. +pub const ImageData = struct { + /// Raw pixel data (RGB, RGBA, or PNG bytes). + data: []const u8, + /// Pixel format of the data. + format: ImageFormat = .png, + /// Pixel width of the image (required for RGB/RGBA). + pixel_width: ?u32 = null, + /// Pixel height of the image (required for RGB/RGBA). + pixel_height: ?u32 = null, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + placement: ImagePlacement = .top_left, + row: ?u16 = null, + col: ?u16 = null, + row_offset: i16 = 0, + col_offset: i16 = 0, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + protocol: ImageProtocol = .auto, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// Transmit an image to the terminal without displaying it (Kitty cache). +pub const CacheImage = struct { + /// File path or in-memory data source. + source: ImageSource, + /// Unique image ID for later reference. Required. + image_id: u32, + /// Pixel format (only for in-memory data). + format: ImageFormat = .png, + /// Pixel width (required for RGB/RGBA in-memory data). + pixel_width: ?u32 = null, + /// Pixel height (required for RGB/RGBA in-memory data). + pixel_height: ?u32 = null, + quiet: bool = true, +}; + +/// Source for an image: file path or in-memory bytes. +pub const ImageSource = union(enum) { + file: []const u8, + data: []const u8, +}; + +/// Display a previously cached image by ID (Kitty virtual placement). +pub const PlaceCachedImage = struct { + /// Image ID from a previous cache_image command. + image_id: u32, + placement_id: ?u32 = null, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + placement: ImagePlacement = .top_left, + row: ?u16 = null, + col: ?u16 = null, + row_offset: i16 = 0, + col_offset: i16 = 0, + move_cursor: bool = true, + quiet: bool = true, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// Delete a cached image or placement (Kitty). +pub const DeleteImage = union(enum) { + /// Delete all placements of a specific image ID. + by_id: u32, + /// Delete a specific placement of an image. + by_placement: struct { image_id: u32, placement_id: u32 }, + /// Delete all images and placements. + all, +}; + +/// Backward-compatible alias for existing Kitty-only APIs. +pub const KittyImageFile = ImageFile; + +/// Command type parameterized by the user's message type +pub fn Cmd(comptime Msg: type) type { + return union(enum) { + /// No operation + none, + + /// Quit the application + quit, + + /// Request a tick after the specified duration (nanoseconds) + tick: u64, + + /// Request repeating tick at interval (nanoseconds) + every: u64, + + /// Execute a batch of commands + batch: []const Cmd(Msg), + + /// Execute commands in sequence (wait for each to complete) + sequence: []const Cmd(Msg), + + /// Send a message to the update function + msg: Msg, + + /// Execute a custom function that produces a message + perform: *const fn () ?Msg, + + /// Suspend the program (Ctrl+Z behavior) + suspend_process, + + /// Runtime terminal commands + enable_mouse, + disable_mouse, + show_cursor, + hide_cursor, + enter_alt_screen, + exit_alt_screen, + set_title: []const u8, + + /// Print a line above the program output + println: []const u8, + + /// Draw an image file using the best available protocol (Kitty, iTerm2, Sixel) + image_file: ImageFile, + + /// Draw an image file via Kitty graphics protocol (no-op if unsupported) + kitty_image_file: KittyImageFile, + + /// Draw in-memory image data (RGB, RGBA, or PNG bytes) + image_data: ImageData, + + /// Transmit an image to the terminal cache without displaying (Kitty) + cache_image: CacheImage, + + /// Display a previously cached image (Kitty virtual placement) + place_cached_image: PlaceCachedImage, + + /// Delete a cached image or placement (Kitty) + delete_image: DeleteImage, + + const Self = @This(); + + /// Create a none command + pub fn none_cmd() Self { + return .none; + } + + /// Create a quit command + pub fn quit_cmd() Self { + return .quit; + } + + /// Request a tick after milliseconds + pub fn tickMs(ms: u64) Self { + return .{ .tick = ms * std.time.ns_per_ms }; + } + + /// Request a tick after seconds + pub fn tickSec(sec: u64) Self { + return .{ .tick = sec * std.time.ns_per_s }; + } + + /// Request a repeating tick every `ms` milliseconds + pub fn everyMs(ms: u64) Self { + return .{ .every = ms * std.time.ns_per_ms }; + } + + /// Request a repeating tick every `sec` seconds + pub fn everySec(sec: u64) Self { + return .{ .every = sec * std.time.ns_per_s }; + } + + /// Create a batch of commands + pub fn batchOf(cmds: []const Self) Self { + return .{ .batch = cmds }; + } + + /// Create a sequence of commands + pub fn sequenceOf(cmds: []const Self) Self { + return .{ .sequence = cmds }; + } + + /// Send a message + pub fn send(message: Msg) Self { + return .{ .msg = message }; + } + + /// Execute a function to get a message + pub fn performFn(func: *const fn () ?Msg) Self { + return .{ .perform = func }; + } + + /// Check if command is none + pub fn isNone(self: Self) bool { + return self == .none; + } + + /// Check if command is quit + pub fn isQuit(self: Self) bool { + return self == .quit; + } + }; +} + +/// Standard commands without message type +pub const StandardCmd = union(enum) { + none, + quit, + tick: u64, + set_title: []const u8, + enable_mouse, + disable_mouse, + show_cursor, + hide_cursor, + enter_alt_screen, + exit_alt_screen, + image_file: ImageFile, + kitty_image_file: KittyImageFile, + image_data: ImageData, + cache_image: CacheImage, + place_cached_image: PlaceCachedImage, + delete_image: DeleteImage, +}; + +/// Combine multiple commands into a batch +pub fn batch(comptime Msg: type, cmds: []const Cmd(Msg)) Cmd(Msg) { + return .{ .batch = cmds }; +} + +/// Combine multiple commands into a sequence +pub fn sequence(comptime Msg: type, cmds: []const Cmd(Msg)) Cmd(Msg) { + return .{ .sequence = cmds }; +} + +/// Create a tick command with millisecond duration +pub fn tick(comptime Msg: type, ms: u64) Cmd(Msg) { + return Cmd(Msg).tickMs(ms); +} + +/// Create a tick command that fires every frame +pub fn everyFrame(comptime Msg: type) Cmd(Msg) { + return Cmd(Msg).tickMs(16); // ~60fps +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig new file mode 100644 index 0000000..608fb53 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig @@ -0,0 +1,382 @@ +//! Runtime context for ZigZag applications. +//! Provides access to terminal state and resources. + +const std = @import("std"); +const terminal_mod = @import("../terminal/terminal.zig"); +const Terminal = terminal_mod.Terminal; +const ImageCapabilities = terminal_mod.ImageCapabilities; +const color_mod = @import("../style/color.zig"); +const unicode_mod = @import("../unicode.zig"); +const Logger = @import("log.zig").Logger; +const theme_mod = @import("../style/theme.zig"); + +/// Runtime context passed to init, update, and view functions +pub const Context = struct { + /// Allocator for temporary allocations (reset each frame) + allocator: std.mem.Allocator, + + /// Persistent allocator for model state (not reset between frames) + persistent_allocator: std.mem.Allocator, + + /// Process environment for env-driven detection (color, multiplexer, locale). + environ_map: *const std.process.Environ.Map, + + /// Asynchronous I/O facilities (file, network, time, sleep). + io: std.Io, + + /// Terminal width in columns + width: u16, + + /// Terminal height in rows + height: u16, + + /// Current frame number + frame: u64, + + /// Time since program start (nanoseconds) + elapsed: u64, + + /// Delta time since last frame (nanoseconds) + delta: u64, + + /// Whether the terminal supports true color + true_color: bool, + + /// Whether the terminal supports 256 colors + color_256: bool, + + /// Color profile of the terminal + color_profile: color_mod.ColorProfile, + + /// Whether the terminal has a dark background + is_dark_background: bool, + + /// Active Unicode width strategy for text measurement + unicode_width_strategy: unicode_mod.WidthStrategy, + + /// Whether DEC mode 2027 was successfully negotiated + terminal_mode_2027: bool, + + /// Whether kitty text sizing support was detected + kitty_text_sizing: bool, + + /// Active theme for the application + theme: theme_mod.Theme = theme_mod.Theme.fromPalette(theme_mod.Palette.default_dark), + + /// Access to internal state (for advanced use) + _terminal: ?*Terminal, + + /// Logger for debug output + _logger: ?*Logger = null, + + /// Log a debug message (writes to log file if configured) + pub fn log(self: *const Context, comptime fmt: []const u8, args: anytype) void { + if (self._logger) |logger| { + logger.log(fmt, args); + } + } + + pub fn init( + allocator: std.mem.Allocator, + persistent_allocator: std.mem.Allocator, + io: std.Io, + environ_map: *const std.process.Environ.Map, + ) Context { + const profile = color_mod.ColorProfile.detect(environ_map); + return .{ + .allocator = allocator, + .persistent_allocator = persistent_allocator, + .io = io, + .environ_map = environ_map, + .width = 80, + .height = 24, + .frame = 0, + .elapsed = 0, + .delta = 0, + .true_color = profile.supportsTrueColor(), + .color_256 = profile.supports256(), + .color_profile = profile, + .is_dark_background = color_mod.hasDarkBackground(environ_map), + .unicode_width_strategy = unicode_mod.getWidthStrategy(), + .terminal_mode_2027 = false, + .kitty_text_sizing = false, + ._terminal = null, + }; + } + + /// Set the active theme from a palette. + pub fn setTheme(self: *Context, p: theme_mod.Palette) void { + self.theme = theme_mod.Theme.fromPalette(p); + } + + /// Get the current palette. + pub fn getPalette(self: *const Context) theme_mod.Palette { + return self.theme.palette; + } + + /// Get the aspect ratio (width / height) + pub fn aspectRatio(self: *const Context) f32 { + if (self.height == 0) return 1.0; + return @as(f32, @floatFromInt(self.width)) / @as(f32, @floatFromInt(self.height)); + } + + /// Get center coordinates + pub fn center(self: *const Context) struct { x: u16, y: u16 } { + return .{ + .x = self.width / 2, + .y = self.height / 2, + }; + } + + /// Check if a position is within bounds + pub fn inBounds(self: *const Context, x: u16, y: u16) bool { + return x < self.width and y < self.height; + } + + /// Get elapsed time in seconds (floating point) + pub fn elapsedSec(self: *const Context) f64 { + return @as(f64, @floatFromInt(self.elapsed)) / @as(f64, @floatFromInt(std.time.ns_per_s)); + } + + /// Get delta time in seconds (floating point) + pub fn deltaSec(self: *const Context) f64 { + return @as(f64, @floatFromInt(self.delta)) / @as(f64, @floatFromInt(std.time.ns_per_s)); + } + + /// Get frames per second (based on delta) + pub fn fps(self: *const Context) f64 { + if (self.delta == 0) return 0.0; + return @as(f64, @floatFromInt(std.time.ns_per_s)) / @as(f64, @floatFromInt(self.delta)); + } + + /// Clamp a value to screen bounds + pub fn clampX(self: *const Context, x: i32) u16 { + if (x < 0) return 0; + if (x >= self.width) return self.width -| 1; + return @intCast(x); + } + + pub fn clampY(self: *const Context, y: i32) u16 { + if (y < 0) return 0; + if (y >= self.height) return self.height -| 1; + return @intCast(y); + } + + /// Returns whether Kitty graphics protocol is available. + pub fn supportsKittyGraphics(self: *const Context) bool { + if (self._terminal) |term| { + return term.supportsKittyGraphics(); + } + return false; + } + + /// Returns whether iTerm2 inline images are available. + pub fn supportsIterm2InlineImages(self: *const Context) bool { + if (self._terminal) |term| { + return term.supportsIterm2InlineImages(); + } + return false; + } + + /// Returns whether Sixel graphics are available. + pub fn supportsSixel(self: *const Context) bool { + if (self._terminal) |term| { + return term.supportsSixel(); + } + return false; + } + + /// Returns whether any inline image protocol is available. + pub fn supportsImages(self: *const Context) bool { + if (self._terminal) |term| { + return term.supportsImages(); + } + return false; + } + + /// Copy bytes to the system clipboard via OSC 52 using terminal defaults. + /// Returns false when clipboard output is unavailable or disabled. + pub fn setClipboard(self: *Context, bytes: []const u8) !bool { + if (self._terminal) |term| { + return term.setClipboard(bytes); + } + return false; + } + + /// Copy bytes to the system clipboard via OSC 52 with per-call overrides. + pub fn setClipboardWithOptions(self: *Context, bytes: []const u8, options: terminal_mod.Osc52WriteOptions) !bool { + if (self._terminal) |term| { + return term.setClipboardWithOptions(bytes, options); + } + return false; + } + + /// Query clipboard bytes via OSC 52 using terminal defaults. + /// Returns null when unavailable, blocked, or timed out. + pub fn getClipboard(self: *Context, allocator: std.mem.Allocator) !?[]u8 { + if (self._terminal) |term| { + return term.getClipboard(allocator); + } + return null; + } + + /// Query clipboard bytes via OSC 52 with per-call overrides. + /// Returns null when unavailable, blocked, or timed out. + pub fn getClipboardWithOptions(self: *Context, allocator: std.mem.Allocator, options: terminal_mod.Osc52ReadOptions) !?[]u8 { + if (self._terminal) |term| { + return term.getClipboardWithOptions(allocator, options); + } + return null; + } + + /// Draw a PNG image file via Kitty graphics protocol (`t=f`). + /// Returns false when unsupported or path is empty. + pub fn drawKittyImageFromFile(self: *Context, path: []const u8, options: Terminal.KittyImageFileOptions) !bool { + if (self._terminal) |term| { + return term.drawKittyImageFromFile(path, options); + } + return false; + } + + /// Draw in-memory image data via Kitty graphics protocol (`t=d`). + /// Returns false when unsupported or data is empty. + pub fn drawKittyImage(self: *Context, data: []const u8, options: Terminal.KittyImageOptions) !bool { + if (self._terminal) |term| { + return term.drawKittyImage(data, options); + } + return false; + } + + /// Transmit an image to the Kitty cache without displaying. + /// Use `placeCachedImage` later to display by ID. + pub fn transmitKittyImage(self: *Context, payload: []const u8, options: Terminal.KittyTransmitOptions) !bool { + if (self._terminal) |term| { + return term.transmitKittyImage(payload, options); + } + return false; + } + + /// Transmit a file to the Kitty cache without displaying. + pub fn transmitKittyImageFromFile(self: *Context, path: []const u8, options: Terminal.KittyTransmitOptions) !bool { + if (self._terminal) |term| { + return term.transmitKittyImageFromFile(path, options); + } + return false; + } + + /// Display a previously cached Kitty image by ID. + pub fn placeKittyImage(self: *Context, options: Terminal.KittyPlaceOptions) !bool { + if (self._terminal) |term| { + return term.placeKittyImage(options); + } + return false; + } + + /// Delete cached Kitty images/placements. + pub fn deleteKittyImage(self: *Context, target: Terminal.KittyDeleteTarget) !bool { + if (self._terminal) |term| { + return term.deleteKittyImage(target); + } + return false; + } + + /// Draw a Sixel image from file (or convert via `img2sixel` when available). + /// Returns false when unsupported or path is empty. + pub fn drawSixelFromFile(self: *Context, path: []const u8, options: Terminal.SixelImageFileOptions) !bool { + if (self._terminal) |term| { + return term.drawSixelFromFile(path, options); + } + return false; + } + + /// Draw an image file using the best available protocol. + /// Returns false when unsupported or path is empty. + pub fn drawImageFromFile(self: *Context, path: []const u8, options: Terminal.ImageFileOptions) !bool { + if (self._terminal) |term| { + return term.drawImageFromFile(path, options); + } + return false; + } + + /// Draw an image file using a specific protocol. + pub fn drawImageFromFileWithProtocol(self: *Context, path: []const u8, options: Terminal.ImageFileOptions, protocol: Terminal.ImageProtocol) !bool { + if (self._terminal) |term| { + return term.drawImageFromFileWithProtocol(path, options, protocol); + } + return false; + } + + /// Draw in-memory image data using the best available protocol. + pub fn drawImageData(self: *Context, data: []const u8, options: Terminal.ImageDataOptions) !bool { + if (self._terminal) |term| { + return term.drawImageData(data, options); + } + return false; + } + + /// Draw in-memory image data using a specific protocol. + pub fn drawImageDataWithProtocol(self: *Context, data: []const u8, options: Terminal.ImageDataOptions, protocol: Terminal.ImageProtocol) !bool { + if (self._terminal) |term| { + return term.drawImageDataWithProtocol(data, options, protocol); + } + return false; + } + + /// Draw in-memory image data via iTerm2 inline image protocol. + pub fn drawIterm2ImageData(self: *Context, data: []const u8, options: Terminal.Iterm2ImageDataOptions) !bool { + if (self._terminal) |term| { + return term.drawIterm2ImageData(data, options); + } + return false; + } + + /// Get the current image capabilities of the terminal. + pub fn getImageCapabilities(self: *const Context) ImageCapabilities { + if (self._terminal) |term| { + return term.getImageCapabilities(); + } + return .{}; + } +}; + +/// Options that can be modified during runtime +pub const Options = struct { + /// Target frame rate (frames per second) + fps: u32 = 60, + + /// Enable mouse tracking + mouse: bool = false, + + /// Show cursor + cursor: bool = false, + + /// Use alternate screen buffer + alt_screen: bool = true, + + /// Enable bracketed paste mode + bracketed_paste: bool = true, + + /// Window title + title: ?[]const u8 = null, + + /// Custom input file (default: stdin) + input: ?std.Io.File = null, + + /// Custom output file (default: stdout) + output: ?std.Io.File = null, + + /// Log file path for debug output + log_file: ?[]const u8 = null, + + /// Enable Kitty keyboard protocol + kitty_keyboard: bool = false, + + /// OSC 52 clipboard configuration + osc52: terminal_mod.Osc52Config = .{}, + + /// Force Unicode width strategy (`null` = auto-detect) + unicode_width_strategy: ?unicode_mod.WidthStrategy = null, + + /// Enable suspend/resume with Ctrl+Z + suspend_enabled: bool = true, +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig new file mode 100644 index 0000000..1167c9b --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig @@ -0,0 +1,342 @@ +//! Dev console — log streamer to a separate viewer. +//! +//! Solves a fundamental TUI debugging problem: stdout is owned by the +//! renderer, so `std.debug.print` would garble the screen. This module +//! routes structured log events to a separate sink so a developer can run +//! the TUI in one terminal and `tail -f` (or `nc`) the log stream in +//! another. +//! +//! Sinks supported: +//! +//! * `.file` — append to a log file. Pair with `tail -f path.log`. +//! * `.tcp` — listen on a TCP port. Pair with `nc localhost 9999`. +//! * `.stderr` — write to stderr. Useful when stderr is redirected. +//! * `.multi` — fan-out to several sinks at once. +//! +//! Each event has a level (trace/debug/info/warn/err) and a timestamp. +//! The console is safe to call from any thread; writes are mutex-guarded. + +const std = @import("std"); +const Writer = std.Io.Writer; + +pub const Level = enum { + trace, + debug, + info, + warn, + err, + + pub fn label(self: Level) []const u8 { + return switch (self) { + .trace => "TRACE", + .debug => "DEBUG", + .info => "INFO ", + .warn => "WARN ", + .err => "ERROR", + }; + } + + pub fn rank(self: Level) u8 { + return switch (self) { + .trace => 0, + .debug => 1, + .info => 2, + .warn => 3, + .err => 4, + }; + } +}; + +pub const SinkConfig = union(enum) { + /// Append-mode log file at this path. + file: []const u8, + /// TCP listener on the given host:port. The dev console writes to *all* + /// currently-connected clients; new connections receive future events. + tcp: struct { + host: []const u8 = "127.0.0.1", + port: u16, + }, + /// Write to stderr (file descriptor 2). + stderr, +}; + +pub const DevConsole = struct { + allocator: std.mem.Allocator, + io: std.Io, + sinks: std.array_list.Managed(Sink), + mutex: std.Io.Mutex, + /// Filter: events below this level are dropped. + min_level: Level, + /// Whether to prefix each line with a timestamp. + show_timestamps: bool, + + const Sink = union(enum) { + file: struct { + file: std.Io.File, + /// Append cursor. Only advanced after a successful flush — a failed + /// write leaves it pointing at the truncated record's start, so the + /// next entry overwrites the partial one. Not safe under concurrent + /// writers to the same file. + end_pos: u64, + }, + tcp: *TcpSink, + stderr, + }; + + const TcpSink = struct { + io: std.Io, + allocator: std.mem.Allocator, + listen_address: std.Io.net.IpAddress, + server: std.Io.net.Server, + thread: std.Thread, + connections: std.array_list.Managed(std.Io.net.Stream), + mutex: std.Io.Mutex, + /// Set to true to signal the accept thread to stop. + stopping: std.atomic.Value(bool), + }; + + pub fn init(allocator: std.mem.Allocator, io: std.Io) DevConsole { + return .{ + .allocator = allocator, + .io = io, + .sinks = std.array_list.Managed(Sink).init(allocator), + .mutex = .init, + .min_level = .trace, + .show_timestamps = true, + }; + } + + pub fn deinit(self: *DevConsole) void { + const io = self.io; + for (self.sinks.items) |*sink| { + switch (sink.*) { + .file => |*f| f.file.close(io), + .tcp => |tcp| { + tcp.stopping.store(true, .seq_cst); + // Wake the listener by connecting once. + if (tcp.listen_address.connect(io, .{ .mode = .stream })) |conn| { + conn.close(io); + } else |_| {} + tcp.thread.join(); + tcp.server.deinit(io); + for (tcp.connections.items) |*c| c.close(io); + tcp.connections.deinit(); + self.allocator.destroy(tcp); + }, + .stderr => {}, + } + } + self.sinks.deinit(); + } + + pub fn setMinLevel(self: *DevConsole, lvl: Level) void { + self.min_level = lvl; + } + + pub fn addSink(self: *DevConsole, cfg: SinkConfig) !void { + const io = self.io; + switch (cfg) { + .file => |path| { + const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = false }); + const end_pos = std.Io.File.length(file, io) catch 0; + try self.sinks.append(.{ .file = .{ .file = file, .end_pos = end_pos } }); + }, + .stderr => { + try self.sinks.append(.stderr); + }, + .tcp => |t| { + const addr = try std.Io.net.IpAddress.parse(t.host, t.port); + var server = try addr.listen(io, .{ .reuse_address = true }); + errdefer server.deinit(io); + + const tcp_ptr = try self.allocator.create(TcpSink); + errdefer self.allocator.destroy(tcp_ptr); + tcp_ptr.* = .{ + .io = io, + .allocator = self.allocator, + .listen_address = addr, + .server = server, + .thread = undefined, + .connections = std.array_list.Managed(std.Io.net.Stream).init(self.allocator), + .mutex = .init, + .stopping = std.atomic.Value(bool).init(false), + }; + + tcp_ptr.thread = try std.Thread.spawn(.{}, acceptLoop, .{tcp_ptr}); + try self.sinks.append(.{ .tcp = tcp_ptr }); + }, + } + } + + fn acceptLoop(tcp: *TcpSink) void { + const io = tcp.io; + while (!tcp.stopping.load(.seq_cst)) { + const conn = tcp.server.accept(io) catch break; + if (tcp.stopping.load(.seq_cst)) { + conn.close(io); + break; + } + tcp.mutex.lockUncancelable(io); + tcp.connections.append(conn) catch { + conn.close(io); + tcp.mutex.unlock(io); + continue; + }; + tcp.mutex.unlock(io); + } + } + + pub fn log(self: *DevConsole, level: Level, comptime fmt: []const u8, args: anytype) void { + if (level.rank() < self.min_level.rank()) return; + + // Build the line in a stack buffer (or heap-fall-back) once. + var stack_buf: [4096]u8 = undefined; + const line = self.format(stack_buf[0..], level, fmt, args) catch return; + + const io = self.io; + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + for (self.sinks.items) |*sink| { + switch (sink.*) { + .file => |*f| { + var write_buf: [1024]u8 = undefined; + var w = f.file.writer(io, &write_buf); + w.seekTo(f.end_pos) catch continue; + w.interface.writeAll(line) catch continue; + w.interface.flush() catch continue; + f.end_pos = w.logicalPos(); + }, + .stderr => { + std.debug.print("{s}", .{line}); + }, + .tcp => |tcp| { + var keep = std.array_list.Managed(std.Io.net.Stream).init(self.allocator); + defer keep.deinit(); + + tcp.mutex.lockUncancelable(io); + defer tcp.mutex.unlock(io); + for (tcp.connections.items) |conn| { + var write_buf: [1024]u8 = undefined; + var w = conn.writer(io, &write_buf); + if (w.interface.writeAll(line)) |_| { + if (w.interface.flush()) |_| { + keep.append(conn) catch continue; + } else |_| {} + } else |_| {} + } + // Drop dead connections. + if (keep.items.len != tcp.connections.items.len) { + for (tcp.connections.items) |conn| { + var still_alive = false; + for (keep.items) |k| { + if (k.socket.handle == conn.socket.handle) { + still_alive = true; + break; + } + } + if (!still_alive) conn.close(io); + } + tcp.connections.clearRetainingCapacity(); + tcp.connections.appendSlice(keep.items) catch {}; + } + }, + } + } + } + + fn format(self: *const DevConsole, buf: []u8, level: Level, comptime fmt: []const u8, args: anytype) ![]u8 { + var writer: Writer = .fixed(buf); + if (self.show_timestamps) { + const now = std.Io.Timestamp.now(self.io, .real).toSeconds(); + const epoch = std.time.epoch.EpochSeconds{ .secs = @intCast(now) }; + const day = epoch.getDaySeconds(); + try writer.print("[{d:0>2}:{d:0>2}:{d:0>2}] ", .{ + day.getHoursIntoDay(), + day.getMinutesIntoHour(), + day.getSecondsIntoMinute(), + }); + } + try writer.print("{s} ", .{level.label()}); + try writer.print(fmt, args); + try writer.writeByte('\n'); + return writer.buffered(); + } + + // Convenience wrappers. + pub fn trace(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { + self.log(.trace, fmt, args); + } + pub fn debug(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { + self.log(.debug, fmt, args); + } + pub fn info(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { + self.log(.info, fmt, args); + } + pub fn warn(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { + self.log(.warn, fmt, args); + } + pub fn err(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { + self.log(.err, fmt, args); + } +}; + +// ── Tests ────────────────────────────────────────────────────────────── + +const testing = std.testing; + +test "file sink writes formatted log lines" { + const allocator = testing.allocator; + const io = testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + + var orig = try std.Io.Dir.cwd().openDir(io, ".", .{}); + defer orig.close(io); + try std.process.setCurrentDir(io, tmp.dir); + defer std.process.setCurrentDir(io, orig) catch {}; + + var console = DevConsole.init(allocator, io); + defer console.deinit(); + try console.addSink(.{ .file = "console.log" }); + + console.info("hello {s}", .{"world"}); + console.warn("careful", .{}); + + var buf: [4096]u8 = undefined; + const contents = try std.Io.Dir.cwd().readFile(io, "console.log", &buf); + + try testing.expect(std.mem.indexOf(u8, contents, "hello world") != null); + try testing.expect(std.mem.indexOf(u8, contents, "INFO") != null); + try testing.expect(std.mem.indexOf(u8, contents, "WARN") != null); +} + +test "min level filter" { + const allocator = testing.allocator; + const io = testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + + var orig = try std.Io.Dir.cwd().openDir(io, ".", .{}); + defer orig.close(io); + try std.process.setCurrentDir(io, tmp.dir); + defer std.process.setCurrentDir(io, orig) catch {}; + + var console = DevConsole.init(allocator, io); + defer console.deinit(); + try console.addSink(.{ .file = "filtered.log" }); + console.setMinLevel(.warn); + + console.debug("hidden", .{}); + console.warn("visible", .{}); + + var buf: [4096]u8 = undefined; + const contents = try std.Io.Dir.cwd().readFile(io, "filtered.log", &buf); + try testing.expect(std.mem.indexOf(u8, contents, "hidden") == null); + try testing.expect(std.mem.indexOf(u8, contents, "visible") != null); +} + +test "level rank ordering" { + try testing.expect(Level.trace.rank() < Level.err.rank()); + try testing.expect(Level.warn.rank() < Level.err.rank()); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig new file mode 100644 index 0000000..296e227 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig new file mode 100644 index 0000000..3c2b607 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig @@ -0,0 +1,60 @@ +//! Debug file logging for ZigZag applications. +//! Since stdout is owned by the renderer, this provides file-based logging. + +const std = @import("std"); + +/// Logger that writes timestamped messages to a file +pub const Logger = struct { + io: std.Io, + file: std.Io.File, + /// Append cursor. Only advanced after a successful flush — a failed write + /// leaves it pointing at where the truncated record started, so the next + /// log line will overwrite the partial one. Acceptable for a debug logger; + /// not safe under concurrent writers to the same file. + end_pos: u64, + mutex: std.Io.Mutex, + + /// Initialize a logger that writes to the given file path + pub fn init(io: std.Io, path: []const u8) !Logger { + const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = false }); + // Capture current length so subsequent writes append. + const end_pos = std.Io.File.length(file, io) catch 0; + return .{ + .io = io, + .file = file, + .end_pos = end_pos, + .mutex = .init, + }; + } + + /// Close the log file + pub fn deinit(self: *Logger) void { + self.file.close(self.io); + } + + /// Write a log message with timestamp prefix + pub fn log(self: *Logger, comptime fmt: []const u8, args: anytype) void { + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); + + var buf: [1024]u8 = undefined; + var w = self.file.writer(self.io, &buf); + w.seekTo(self.end_pos) catch return; + + const now = std.Io.Timestamp.now(self.io, .real).toSeconds(); + const epoch_seconds = std.time.epoch.EpochSeconds{ .secs = @intCast(now) }; + const day_seconds = epoch_seconds.getDaySeconds(); + + w.interface.print("[{d:0>2}:{d:0>2}:{d:0>2}] ", .{ + day_seconds.getHoursIntoDay(), + day_seconds.getMinutesIntoHour(), + day_seconds.getSecondsIntoMinute(), + }) catch return; + + w.interface.print(fmt, args) catch return; + w.interface.writeByte('\n') catch return; + w.interface.flush() catch return; + + self.end_pos = w.logicalPos(); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig new file mode 100644 index 0000000..e230a42 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig @@ -0,0 +1,90 @@ +//! Message types for the ZigZag TUI framework. +//! Messages represent events that can occur in the application. + +const std = @import("std"); +const keyboard = @import("../input/keyboard.zig"); +const mouse = @import("../input/mouse.zig"); + +/// Key event message +pub const Key = keyboard.KeyEvent; + +/// Mouse event message +pub const Mouse = mouse.MouseEvent; + +/// Window size change message +pub const WindowSize = struct { + width: u16, + height: u16, +}; + +/// Tick message for timer-based updates +pub const Tick = struct { + /// Monotonic timestamp in nanoseconds since program start. + timestamp: i64, + delta: u64, // nanoseconds since last tick +}; + +/// Focus change message +pub const Focus = enum { + gained, + lost, +}; + +/// Batch of messages +pub const Batch = struct { + messages: []const SystemMsg, +}; + +/// System messages that the framework generates +pub const SystemMsg = union(enum) { + /// Keyboard input + key: Key, + /// Mouse input + mouse: Mouse, + /// Window was resized + window_size: WindowSize, + /// Timer tick + tick: Tick, + /// Focus change + focus: Focus, + /// Batch of messages + batch: Batch, + /// No message + none, + + pub fn isQuit(self: SystemMsg) bool { + return switch (self) { + .key => |k| k.key == .{ .char = 'c' } and k.modifiers.ctrl, + else => false, + }; + } +}; + +/// Convert a key to a character if possible +pub fn keyToChar(key: Key) ?u21 { + return key.key.toChar(); +} + +/// Check if a key matches a specific character +pub fn isChar(key: Key, c: u21) bool { + return switch (key.key) { + .char => |ch| ch == c and !key.modifiers.any(), + else => false, + }; +} + +/// Check if a key is a specific character with ctrl modifier +pub fn isCtrl(key: Key, c: u21) bool { + return switch (key.key) { + .char => |ch| ch == c and key.modifiers.ctrl and !key.modifiers.alt and !key.modifiers.shift, + else => false, + }; +} + +/// Check if a key is a specific character with alt modifier +pub fn isAlt(key: Key, c: u21) bool { + return switch (key.key) { + .char => |ch| ch == c and key.modifiers.alt and !key.modifiers.ctrl and !key.modifiers.shift, + else => false, + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig new file mode 100644 index 0000000..7195d34 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig @@ -0,0 +1,833 @@ +//! Program runtime for the ZigZag TUI framework. +//! Implements the Model-Update-View pattern with an event loop. + +const std = @import("std"); +const builtin = @import("builtin"); +const Terminal = @import("../terminal/terminal.zig").Terminal; +const ansi = @import("../terminal/ansi.zig"); +const keyboard = @import("../input/keyboard.zig"); +const Context = @import("context.zig").Context; +const Options = @import("context.zig").Options; +const message = @import("message.zig"); +const command = @import("command.zig"); +const Logger = @import("log.zig").Logger; +const unicode = @import("../unicode.zig"); + +pub const Cmd = command.Cmd; +pub const Msg = message; + +const PendingImage = union(enum) { + auto: command.ImageFile, + kitty: command.KittyImageFile, + data: command.ImageData, + place_cached: command.PlaceCachedImage, +}; + +/// Program runtime that manages the application lifecycle +pub fn Program(comptime Model: type) type { + // Ensure Model has required declarations + comptime { + if (!@hasDecl(Model, "Msg")) { + @compileError("Model must have a 'Msg' type declaration"); + } + if (!@hasDecl(Model, "init")) { + @compileError("Model must have an 'init' function"); + } + if (!@hasDecl(Model, "update")) { + @compileError("Model must have an 'update' function"); + } + if (!@hasDecl(Model, "view")) { + @compileError("Model must have a 'view' function"); + } + } + + const UserMsg = Model.Msg; + const UserCmd = Cmd(UserMsg); + + return struct { + allocator: std.mem.Allocator, + io: std.Io, + environ_map: *const std.process.Environ.Map, + arena: std.heap.ArenaAllocator, + model: Model, + terminal: ?Terminal, + context: Context, + options: Options, + running: bool, + /// Boot-clock epoch from which `last_frame_time` and `context.elapsed` are measured. + /// `.boot` includes time the system was suspended, giving a monotonic reading + /// without gaps on resume. + clock_epoch: std.Io.Clock.Timestamp, + last_frame_time: u64, + pending_tick: ?u64, + every_interval: ?u64, + last_every_tick: u64, + last_view_hash: u64, + last_line_count: usize, + pending_image: ?PendingImage, + logger: ?Logger, + + /// Message filter function + filter: ?*const fn (UserMsg) ?UserMsg, + + const Self = @This(); + + /// Initialize the program + pub fn init( + allocator: std.mem.Allocator, + io: std.Io, + environ_map: *const std.process.Environ.Map, + ) !Self { + return initWithOptions(allocator, io, environ_map, .{}); + } + + /// Initialize with custom options + pub fn initWithOptions( + allocator: std.mem.Allocator, + io: std.Io, + environ_map: *const std.process.Environ.Map, + options: Options, + ) !Self { + const arena = std.heap.ArenaAllocator.init(allocator); + const clock_epoch = std.Io.Clock.Timestamp.now(io, .boot); + const self = Self{ + .allocator = allocator, + .io = io, + .environ_map = environ_map, + .arena = arena, + .model = undefined, + .terminal = null, + // `self` is returned by value, so don't capture an arena allocator here. + // It would point at this function's stack copy and dangle after return. + .context = Context.init(allocator, allocator, io, environ_map), + .options = options, + .running = false, + .clock_epoch = clock_epoch, + .last_frame_time = 0, + .pending_tick = null, + .every_interval = null, + .last_every_tick = 0, + .last_view_hash = 0, + .last_line_count = 0, + .pending_image = null, + .logger = null, + .filter = null, + }; + + return self; + } + + /// Clean up resources + pub fn deinit(self: *Self) void { + if (self.terminal) |*term| { + term.deinit(); + } + if (self.logger) |*l| { + l.deinit(); + } + self.arena.deinit(); + + // Call model's deinit if it exists + if (@hasDecl(Model, "deinit")) { + self.model.deinit(); + } + } + + /// Set a message filter function + pub fn setFilter(self: *Self, f: ?*const fn (UserMsg) ?UserMsg) void { + self.filter = f; + } + + /// Run the program with the built-in event loop. + /// For custom event loops, use `start()` + `tick()` instead. + pub fn run(self: *Self) !void { + try self.start(); + + // Main event loop + while (self.running) { + try self.tick(); + } + } + + /// Initialize the terminal and model without entering the event loop. + /// After calling this, drive the program manually by calling `tick()` + /// in your own loop. Check `isRunning()` to know when to stop. + /// + /// Example: + /// ``` + /// try program.start(); + /// while (program.isRunning()) { + /// try program.tick(); + /// // ... do other work between frames ... + /// } + /// ``` + pub fn start(self: *Self) !void { + // Initialize logger if configured + if (self.options.log_file) |log_path| { + self.logger = Logger.init(self.io, log_path) catch null; + if (self.logger != null) { + self.context._logger = &self.logger.?; + } + } + + // Initialize terminal + self.terminal = try Terminal.init(self.io, self.environ_map, .{ + .alt_screen = self.options.alt_screen, + .hide_cursor = !self.options.cursor, + .mouse = self.options.mouse, + .bracketed_paste = self.options.bracketed_paste, + .input = self.options.input, + .output = self.options.output, + .kitty_keyboard = self.options.kitty_keyboard, + .osc52 = self.options.osc52, + }); + + // Set title if provided + if (self.options.title) |title| { + try self.terminal.?.setTitle(title); + } + + // Get initial size + const size = try self.terminal.?.getSize(); + self.context.width = size.cols; + self.context.height = size.rows; + self.context._terminal = &self.terminal.?; + + const width_caps = self.terminal.?.getUnicodeWidthCapabilities(); + const effective_width_strategy = self.resolveUnicodeWidthStrategy(width_caps.strategy); + self.context.unicode_width_strategy = effective_width_strategy; + self.context.terminal_mode_2027 = width_caps.mode_2027; + self.context.kitty_text_sizing = width_caps.kitty_text_sizing; + unicode.setWidthStrategy(effective_width_strategy); + + self.clock_epoch = std.Io.Clock.Timestamp.now(self.io, .boot); + self.last_frame_time = 0; + self.context.elapsed = 0; + self.context.delta = 0; + self.context.frame = 0; + + self.resetFrameAllocator(); + + // Initialize the model + const init_cmd = self.model.init(&self.context); + try self.processCommand(init_cmd); + + self.running = true; + } + + /// Returns true if the program is still running. + pub fn isRunning(self: *const Self) bool { + return self.running; + } + + /// Execute a single frame: poll input, process events, render. + pub fn tick(self: *Self) !void { + const now = self.elapsedNs(); + const delta = now - self.last_frame_time; + + // Enforce framerate limit + const min_frame_time_ns: u64 = if (self.options.fps > 0) + @divFloor(std.time.ns_per_s, self.options.fps) + else + 16_666_666; // ~60fps default + + if (delta < min_frame_time_ns) { + sleepNs(self.io, min_frame_time_ns - delta); + } + + const frame_time = self.elapsedNs(); + const actual_delta = frame_time - self.last_frame_time; + self.last_frame_time = frame_time; + + self.context.delta = actual_delta; + self.context.elapsed = frame_time; + self.context.frame += 1; + + self.resetFrameAllocator(); + + // Check for resize + if (self.terminal.?.checkResize()) { + const size = try self.terminal.?.getSize(); + self.context.width = size.cols; + self.context.height = size.rows; + + // Only send window_size message if the user model supports it + if (@hasField(UserMsg, "window_size")) { + const cmd = self.dispatchToModel(.{ .window_size = .{ + .width = size.cols, + .height = size.rows, + } }); + try self.processCommand(cmd); + } + } + + // Read input + var input_buf: [256]u8 = undefined; + const bytes_read = try self.terminal.?.readInput(&input_buf, 16); + + if (bytes_read > 0) { + const events = try keyboard.parseAll(self.context.allocator, input_buf[0..bytes_read]); + for (events) |event| { + const user_cmd = switch (event) { + .key => |k| self.processKeyEvent(k), + .mouse => |m| self.processMouseEvent(m), + .none => null, + }; + if (user_cmd) |cmd| { + try self.processCommand(cmd); + } + } + } + + // Handle pending tick + if (self.pending_tick) |tick_ns| { + if (self.context.elapsed >= tick_ns) { + self.pending_tick = null; + // Deliver tick to user's update if Model.Msg has a tick variant + if (@hasField(UserMsg, "tick")) { + const user_msg = UserMsg{ .tick = .{ + .timestamp = @intCast(frame_time), + .delta = actual_delta, + } }; + const cmd = self.dispatchToModel(user_msg); + try self.processCommand(cmd); + } + } + } + + // Handle repeating tick + if (self.every_interval) |interval| { + if (self.context.elapsed - self.last_every_tick >= interval) { + self.last_every_tick = self.context.elapsed; + if (@hasField(UserMsg, "tick")) { + const user_msg = UserMsg{ .tick = .{ + .timestamp = @intCast(frame_time), + .delta = actual_delta, + } }; + const cmd = self.dispatchToModel(user_msg); + try self.processCommand(cmd); + } + } + } + + // Render + try self.render(); + try self.flushPendingImage(); + } + + /// Dispatch a message to the model, applying the filter if set + fn dispatchToModel(self: *Self, user_msg: UserMsg) UserCmd { + if (self.filter) |f| { + if (f(user_msg)) |filtered_msg| { + return self.model.update(filtered_msg, &self.context); + } + return .none; + } + return self.model.update(user_msg, &self.context); + } + + fn processKeyEvent(self: *Self, key: keyboard.KeyEvent) ?UserCmd { + // Check for Ctrl+C to quit + if (key.modifiers.ctrl) { + switch (key.key) { + .char => |c| { + if (c == 'c') { + self.running = false; + return null; + } + // Handle Ctrl+Z for suspend + if (c == 'z' and self.options.suspend_enabled) { + self.performSuspend(); + return null; + } + }, + else => {}, + } + } + + // Handle paste events + if (key.key == .paste) { + if (@hasField(UserMsg, "paste")) { + const user_msg = UserMsg{ .paste = key.key.paste }; + return self.dispatchToModel(user_msg); + } + // If model doesn't handle paste, send as individual key events + if (@hasField(UserMsg, "key")) { + const user_msg = UserMsg{ .key = key }; + return self.dispatchToModel(user_msg); + } + return null; + } + + // Convert to user message if Model.Msg has a key variant + if (@hasField(UserMsg, "key")) { + const user_msg = UserMsg{ .key = key }; + return self.dispatchToModel(user_msg); + } + + return null; + } + + fn resolveUnicodeWidthStrategy(self: *const Self, detected: unicode.WidthStrategy) unicode.WidthStrategy { + if (self.options.unicode_width_strategy) |forced| { + return forced; + } + if (envUnicodeWidthOverride(self.environ_map)) |from_env| { + return from_env; + } + return detected; + } + + fn envUnicodeWidthOverride(environ_map: *const std.process.Environ.Map) ?unicode.WidthStrategy { + const raw = environ_map.get("ZZ_UNICODE_WIDTH") orelse return null; + if (std.ascii.eqlIgnoreCase(raw, "unicode")) return .unicode; + if (std.ascii.eqlIgnoreCase(raw, "legacy")) return .legacy_wcwidth; + if (std.ascii.eqlIgnoreCase(raw, "auto")) return null; + return null; + } + + fn processMouseEvent(self: *Self, mouse_event: keyboard.MouseEvent) ?UserCmd { + if (@hasField(UserMsg, "mouse")) { + const user_msg = UserMsg{ .mouse = mouse_event }; + return self.dispatchToModel(user_msg); + } + + return null; + } + + /// Perform suspend (Ctrl+Z) — POSIX only + fn performSuspend(self: *Self) void { + if (builtin.os.tag == .windows) return; + + // Cleanup terminal + if (self.terminal) |*term| { + term.cleanup(); + } + + // Raise SIGTSTP to suspend process + if (builtin.os.tag != .windows) { + const posix = std.posix; + _ = posix.raise(posix.SIG.TSTP) catch {}; + } + + // When we resume (after `fg`), re-setup terminal + if (self.terminal) |*term| { + term.setup() catch {}; + } + + // Avoid a large post-resume frame delta. + self.last_frame_time = self.elapsedNs(); + + // Force re-render + self.last_view_hash = 0; + + // Dispatch resumed message if model supports it + if (@hasField(UserMsg, "resumed")) { + const cmd = self.dispatchToModel(.{ .resumed = {} }); + self.processCommand(cmd) catch {}; + } + } + + fn processCommand(self: *Self, cmd: UserCmd) !void { + switch (cmd) { + .none => {}, + .quit => { + self.running = false; + }, + .tick => |ns| { + self.pending_tick = self.context.elapsed + ns; + }, + .every => |ns| { + self.every_interval = ns; + self.last_every_tick = self.context.elapsed; + }, + .batch => |cmds| { + for (cmds) |c| { + try self.processCommand(c); + } + }, + .sequence => |cmds| { + for (cmds) |c| { + try self.processCommand(c); + } + }, + .msg => |m| { + const new_cmd = self.dispatchToModel(m); + try self.processCommand(new_cmd); + }, + .perform => |func| { + if (func()) |m| { + const new_cmd = self.dispatchToModel(m); + try self.processCommand(new_cmd); + } + }, + .suspend_process => { + self.performSuspend(); + }, + .enable_mouse => { + if (self.terminal) |*term| { + try term.enableMouse(); + } + }, + .disable_mouse => { + if (self.terminal) |*term| { + try term.disableMouse(); + } + }, + .show_cursor => { + if (self.terminal) |*term| { + const writer = term.writer(); + try writer.writeAll(ansi.cursor_show); + try term.flush(); + } + }, + .hide_cursor => { + if (self.terminal) |*term| { + const writer = term.writer(); + try writer.writeAll(ansi.cursor_hide); + try term.flush(); + } + }, + .enter_alt_screen => { + if (self.terminal) |*term| { + const writer = term.writer(); + try writer.writeAll(ansi.alt_screen_enter); + try term.flush(); + } + }, + .exit_alt_screen => { + if (self.terminal) |*term| { + const writer = term.writer(); + try writer.writeAll(ansi.alt_screen_exit); + try term.flush(); + } + }, + .set_title => |title| { + if (self.terminal) |*term| { + try term.setTitle(title); + } + }, + .println => |line| { + if (self.terminal) |*term| { + const writer = term.writer(); + try writer.writeAll(ansi.cursor_save); + try writer.writeAll(ansi.cursor_home); + try writer.writeAll(line); + try writer.writeAll("\n"); + try writer.writeAll(ansi.cursor_restore); + try term.flush(); + } + }, + .image_file => |image| { + self.pending_image = .{ .auto = image }; + }, + .kitty_image_file => |image| { + self.pending_image = .{ .kitty = image }; + }, + .image_data => |image| { + self.pending_image = .{ .data = image }; + }, + .cache_image => |cache| { + if (self.terminal) |*term| { + switch (cache.source) { + .file => |path| { + _ = term.transmitKittyImageFromFile(path, .{ + .image_id = cache.image_id, + .format = @enumFromInt(@intFromEnum(cache.format)), + .quiet = cache.quiet, + .pixel_width = cache.pixel_width, + .pixel_height = cache.pixel_height, + }) catch {}; + }, + .data => |data| { + _ = term.transmitKittyImage(data, .{ + .image_id = cache.image_id, + .format = @enumFromInt(@intFromEnum(cache.format)), + .quiet = cache.quiet, + .pixel_width = cache.pixel_width, + .pixel_height = cache.pixel_height, + }) catch {}; + }, + } + term.flush() catch {}; + } + }, + .place_cached_image => |place| { + self.pending_image = .{ .place_cached = place }; + }, + .delete_image => |del| { + if (self.terminal) |*term| { + const target: @import("../terminal/terminal.zig").KittyDeleteTarget = switch (del) { + .by_id => |id| .{ .by_id = id }, + .by_placement => |bp| .{ .by_placement = .{ .image_id = bp.image_id, .placement_id = bp.placement_id } }, + .all => .all, + }; + _ = term.deleteKittyImage(target) catch {}; + term.flush() catch {}; + } + }, + } + } + + fn flushPendingImage(self: *Self) !void { + const TerminalMod = @import("../terminal/terminal.zig"); + const pending = self.pending_image orelse return; + self.pending_image = null; + if (self.terminal) |*term| { + switch (pending) { + .auto => |image| { + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_save); + } + try self.positionPendingImage(term, image); + const protocol: TerminalMod.ImageProtocol = switch (image.protocol) { + .auto => .auto, + .kitty => .kitty, + .iterm2 => .iterm2, + .sixel => .sixel, + }; + _ = try term.drawImageFromFileWithProtocol(image.path, .{ + .width_cells = image.width_cells, + .height_cells = image.height_cells, + .preserve_aspect_ratio = image.preserve_aspect_ratio, + .image_id = image.image_id, + .placement_id = image.placement_id, + .move_cursor = image.move_cursor, + .quiet = image.quiet, + .z_index = image.z_index, + .unicode_placeholder = image.unicode_placeholder, + }, protocol); + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_restore); + } + }, + .kitty => |image| { + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_save); + } + try self.positionPendingImage(term, image); + _ = try term.drawKittyImageFromFile(image.path, .{ + .width_cells = image.width_cells, + .height_cells = image.height_cells, + .image_id = image.image_id, + .placement_id = image.placement_id, + .move_cursor = image.move_cursor, + .quiet = image.quiet, + .z_index = image.z_index, + .unicode_placeholder = image.unicode_placeholder, + }); + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_restore); + } + }, + .data => |image| { + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_save); + } + try self.positionPendingImageData(term, image); + const protocol: TerminalMod.ImageProtocol = switch (image.protocol) { + .auto => .auto, + .kitty => .kitty, + .iterm2 => .iterm2, + .sixel => .sixel, + }; + _ = try term.drawImageDataWithProtocol(image.data, .{ + .format = @enumFromInt(@intFromEnum(image.format)), + .pixel_width = image.pixel_width, + .pixel_height = image.pixel_height, + .width_cells = image.width_cells, + .height_cells = image.height_cells, + .image_id = image.image_id, + .placement_id = image.placement_id, + .move_cursor = image.move_cursor, + .quiet = image.quiet, + .z_index = image.z_index, + .unicode_placeholder = image.unicode_placeholder, + }, protocol); + if (!image.move_cursor) { + try term.writer().writeAll(ansi.cursor_restore); + } + }, + .place_cached => |place| { + if (!place.move_cursor) { + try term.writer().writeAll(ansi.cursor_save); + } + try self.positionPendingCachedImage(term, place); + _ = try term.placeKittyImage(.{ + .image_id = place.image_id, + .placement_id = place.placement_id, + .width_cells = place.width_cells, + .height_cells = place.height_cells, + .move_cursor = place.move_cursor, + .quiet = place.quiet, + .z_index = place.z_index, + .unicode_placeholder = place.unicode_placeholder, + }); + if (!place.move_cursor) { + try term.writer().writeAll(ansi.cursor_restore); + } + }, + } + try term.flush(); + } + } + + fn positionPendingImage(self: *Self, term: *Terminal, image: command.ImageFile) !void { + try self.positionByPlacement(term, image.placement, image.width_cells, image.height_cells, image.row, image.col, image.row_offset, image.col_offset); + } + + fn positionPendingImageData(self: *Self, term: *Terminal, image: command.ImageData) !void { + try self.positionByPlacement(term, image.placement, image.width_cells, image.height_cells, image.row, image.col, image.row_offset, image.col_offset); + } + + fn positionPendingCachedImage(self: *Self, term: *Terminal, place: command.PlaceCachedImage) !void { + try self.positionByPlacement(term, place.placement, place.width_cells, place.height_cells, place.row, place.col, place.row_offset, place.col_offset); + } + + fn positionByPlacement( + self: *Self, + term: *Terminal, + placement: command.ImagePlacement, + width_cells: ?u16, + height_cells: ?u16, + opt_row: ?u16, + opt_col: ?u16, + row_offset: i16, + col_offset: i16, + ) !void { + var row: u16 = 0; + var col: u16 = 0; + + switch (placement) { + .cursor => return, + .top_left => { + row = 0; + col = 0; + }, + .top_center => { + if (width_cells) |w_cells| { + const term_width = @as(usize, self.context.width); + const image_width = @as(usize, w_cells); + if (term_width > image_width) { + col = @intCast((term_width - image_width) / 2); + } + } + row = 0; + }, + .center => { + if (width_cells) |w_cells| { + const term_width = @as(usize, self.context.width); + const image_width = @as(usize, w_cells); + if (term_width > image_width) { + col = @intCast((term_width - image_width) / 2); + } + } + if (height_cells) |h_cells| { + const term_height = @as(usize, self.context.height); + const image_height = @as(usize, h_cells); + if (term_height > image_height) { + row = @intCast((term_height - image_height) / 2); + } + } + }, + } + + if (opt_row) |r| row = r; + if (opt_col) |c| col = c; + + const max_row = if (height_cells) |h| self.context.height -| h else self.context.height -| 1; + const max_col = if (width_cells) |w| self.context.width -| w else self.context.width -| 1; + row = applySignedOffsetClamped(row, row_offset, max_row); + col = applySignedOffsetClamped(col, col_offset, max_col); + + try term.moveTo(row, col); + } + + fn applySignedOffsetClamped(base: u16, offset: i16, max: u16) u16 { + const base_i32 = @as(i32, @intCast(base)); + const offset_i32 = @as(i32, offset); + const max_i32 = @as(i32, @intCast(max)); + var value = base_i32 + offset_i32; + if (value < 0) value = 0; + if (value > max_i32) value = max_i32; + return @intCast(value); + } + + /// Nanoseconds elapsed on the boot clock since `clock_epoch`. + fn elapsedNs(self: *const Self) u64 { + const dur = self.clock_epoch.untilNow(self.io); + const ns = dur.raw.nanoseconds; + if (ns <= 0) return 0; + return @intCast(ns); + } + + fn sleepNs(io: std.Io, nanoseconds: u64) void { + if (nanoseconds == 0) return; + std.Io.sleep(io, .fromNanoseconds(nanoseconds), .boot) catch unreachable; + } + + fn resetFrameAllocator(self: *Self) void { + _ = self.arena.reset(.retain_capacity); + self.context.allocator = self.arena.allocator(); + } + + fn render(self: *Self) !void { + const view_output = self.model.view(&self.context); + + // Compute hash of view output + const view_hash = std.hash.Wyhash.hash(0, view_output); + + // Only redraw if view changed + if (view_hash != self.last_view_hash) { + const writer = self.terminal.?.writer(); + + // Start synchronized output (prevents tearing on supporting terminals) + try writer.writeAll(ansi.sync_start); + + // Move cursor home (don't clear entire screen to reduce flicker) + try writer.writeAll(ansi.cursor_home); + + // Write each line, clearing to end of line + var lines = std.mem.splitScalar(u8, view_output, '\n'); + var first = true; + var line_count: usize = 0; + while (lines.next()) |line| { + if (!first) try writer.writeAll("\r\n"); + first = false; + try writer.writeAll(line); + try writer.writeAll(ansi.line_clear_right); + line_count += 1; + } + + // Clear remaining lines if previous content was taller + if (self.last_line_count > line_count) { + var remaining = self.last_line_count - line_count; + while (remaining > 0) : (remaining -= 1) { + try writer.writeAll("\r\n"); + try writer.writeAll(ansi.line_clear); + } + } + self.last_line_count = line_count; + + // End synchronized output + try writer.writeAll(ansi.sync_end); + + try self.terminal.?.flush(); + + // Save hash for comparison + self.last_view_hash = view_hash; + } + } + + /// Send a message to the model + pub fn send(self: *Self, m: UserMsg) !void { + const cmd = self.dispatchToModel(m); + try self.processCommand(cmd); + } + + /// Stop the program + pub fn quit(self: *Self) void { + self.running = false; + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig new file mode 100644 index 0000000..acbd197 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig @@ -0,0 +1,393 @@ +//! Screen stack / router. +//! +//! Manages a stack of independent screens (each with its own state, key +//! handler, and view), letting an app push/pop modal or full-screen layers +//! the way a browser navigates pages. Distinct from `SubProgram` which is a +//! static-typed wrapper for one child model: a `ScreenStack` holds a runtime +//! stack of heterogeneous screens via a small vtable interface. +//! +//! Usage outline: +//! +//! var stack = zz.ScreenStack.init(allocator); +//! defer stack.deinit(); +//! try stack.push(login_screen); +//! // In your top-level update: +//! switch (try stack.handleKey(key, ctx)) { +//! .none => {}, +//! .quit => return .quit, +//! .pushed, .popped, .replaced => {}, +//! } +//! // In your top-level view: +//! return try stack.view(ctx, allocator); +//! +//! Screens marked `modal = true` render layered on top of the screen below, +//! so the previous screen stays visible behind a centered overlay (commonly +//! used for confirm dialogs or command palettes). + +const std = @import("std"); +const Writer = std.Io.Writer; +const Context = @import("context.zig").Context; +const keys = @import("../input/keys.zig"); +const measure = @import("../layout/measure.zig"); +const join = @import("../layout/join.zig"); + +/// Result of a key handler. Tells the stack how to mutate itself. +pub const Action = union(enum) { + /// Do nothing. + none, + /// Pop this screen off the top. + pop, + /// Pop this screen and push another. + replace: Screen, + /// Push a new screen on top of this one. + push: Screen, + /// Quit the whole program. + quit, +}; + +/// Outcome of a `handleKey` call to the stack — useful when the parent wants +/// to react to navigation. +pub const HandleResult = enum { none, pushed, popped, replaced, quit }; + +/// A single screen owned by the stack. Implemented via a tiny vtable so the +/// stack can hold heterogeneous screen types. +pub const Screen = struct { + ptr: *anyopaque, + vtable: *const VTable, + /// Title shown in breadcrumbs/diagnostics. Optional. + title: []const u8 = "", + /// If true, the screen behind this one is rendered first and this view + /// is overlaid (centered horizontally + vertically). + modal: bool = false, + + pub const VTable = struct { + update: *const fn (ctx: *anyopaque, msg_ctx: *Context, key: keys.KeyEvent) Action, + view: *const fn (ctx: *anyopaque, msg_ctx: *const Context, allocator: std.mem.Allocator) anyerror![]const u8, + /// Called by the stack when the screen is removed (pop or replace). + /// Use this to free per-screen resources. May be null. + deinit: ?*const fn (ctx: *anyopaque, allocator: std.mem.Allocator) void = null, + /// Called when the screen is pushed onto the stack. May be null. + on_enter: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, + /// Called when another screen is pushed on top, so this one is + /// covered. May be null. + on_suspend: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, + /// Called when this screen becomes the top again after a pop. + on_resume: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, + }; +}; + +pub const ScreenStack = struct { + allocator: std.mem.Allocator, + stack: std.array_list.Managed(Screen), + + pub fn init(allocator: std.mem.Allocator) ScreenStack { + return .{ + .allocator = allocator, + .stack = std.array_list.Managed(Screen).init(allocator), + }; + } + + pub fn deinit(self: *ScreenStack) void { + // Tear down in reverse order so on_suspend semantics make sense. + while (self.stack.pop()) |s| { + if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); + } + self.stack.deinit(); + } + + pub fn depth(self: *const ScreenStack) usize { + return self.stack.items.len; + } + + pub fn isEmpty(self: *const ScreenStack) bool { + return self.stack.items.len == 0; + } + + /// The currently-active (top-of-stack) screen, or null. + pub fn top(self: *const ScreenStack) ?Screen { + if (self.stack.items.len == 0) return null; + return self.stack.items[self.stack.items.len - 1]; + } + + pub fn push(self: *ScreenStack, screen: Screen) !void { + if (self.top()) |prev| { + if (prev.vtable.on_suspend) |fn_ptr| fn_ptr(prev.ptr, undefined); + } + try self.stack.append(screen); + if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, undefined); + } + + pub fn pushWithCtx(self: *ScreenStack, screen: Screen, ctx: *Context) !void { + if (self.top()) |prev| { + if (prev.vtable.on_suspend) |fn_ptr| fn_ptr(prev.ptr, ctx); + } + try self.stack.append(screen); + if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, ctx); + } + + pub fn pop(self: *ScreenStack) void { + if (self.stack.pop()) |s| { + if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); + if (self.top()) |new_top| { + if (new_top.vtable.on_resume) |fn_ptr| fn_ptr(new_top.ptr, undefined); + } + } + } + + pub fn popWithCtx(self: *ScreenStack, ctx: *Context) void { + if (self.stack.pop()) |s| { + if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); + if (self.top()) |new_top| { + if (new_top.vtable.on_resume) |fn_ptr| fn_ptr(new_top.ptr, ctx); + } + } + } + + pub fn replace(self: *ScreenStack, screen: Screen) !void { + if (self.stack.pop()) |s| { + if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); + } + try self.stack.append(screen); + if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, undefined); + } + + /// Forward a key event to the top screen and apply the returned action. + pub fn handleKey(self: *ScreenStack, ctx: *Context, key: keys.KeyEvent) !HandleResult { + const current = self.top() orelse return .none; + const action = current.vtable.update(current.ptr, ctx, key); + return self.applyAction(action, ctx); + } + + fn applyAction(self: *ScreenStack, action: Action, ctx: *Context) !HandleResult { + switch (action) { + .none => return .none, + .quit => return .quit, + .pop => { + self.popWithCtx(ctx); + return .popped; + }, + .push => |screen| { + try self.pushWithCtx(screen, ctx); + return .pushed; + }, + .replace => |screen| { + if (self.stack.pop()) |s| { + if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); + } + try self.stack.append(screen); + if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, ctx); + return .replaced; + }, + } + } + + /// Render the visible screens. Walks down from the top to find the + /// nearest non-modal "background" screen, then layers each modal on top. + pub fn view(self: *const ScreenStack, ctx: *const Context, allocator: std.mem.Allocator) ![]const u8 { + if (self.stack.items.len == 0) return try allocator.dupe(u8, ""); + + // Find the deepest screen we need to render: walk back until we hit + // a non-modal screen, that's our background. + var background_idx: usize = self.stack.items.len - 1; + while (background_idx > 0 and self.stack.items[background_idx].modal) { + background_idx -= 1; + } + + var current = try self.stack.items[background_idx].vtable.view( + self.stack.items[background_idx].ptr, + ctx, + allocator, + ); + + var i = background_idx + 1; + while (i < self.stack.items.len) : (i += 1) { + const overlay = try self.stack.items[i].vtable.view( + self.stack.items[i].ptr, + ctx, + allocator, + ); + defer allocator.free(overlay); + const composed = try compose(allocator, current, overlay); + allocator.free(current); + current = composed; + } + + return current; + } +}; + +/// Place `overlay` centered on top of `background`. The overlay's lines +/// replace the corresponding lines in the background; lines that don't +/// extend through the overlay region are kept as-is. The result has the +/// dimensions of the larger of the two. +fn compose(allocator: std.mem.Allocator, background: []const u8, overlay: []const u8) ![]const u8 { + const bg_w = measure.maxLineWidth(background); + const bg_h = measure.height(background); + const ov_w = measure.maxLineWidth(overlay); + const ov_h = measure.height(overlay); + + if (ov_w == 0 or ov_h == 0) return allocator.dupe(u8, background); + if (bg_w == 0 or bg_h == 0) return allocator.dupe(u8, overlay); + + // Vertical centering: place overlay starting at row (bg_h - ov_h) / 2. + const top: usize = if (bg_h > ov_h) (bg_h - ov_h) / 2 else 0; + const left: usize = if (bg_w > ov_w) (bg_w - ov_w) / 2 else 0; + + var bg_lines = std.array_list.Managed([]const u8).init(allocator); + defer bg_lines.deinit(); + { + var iter = std.mem.splitScalar(u8, background, '\n'); + while (iter.next()) |line| try bg_lines.append(line); + } + + var ov_lines = std.array_list.Managed([]const u8).init(allocator); + defer ov_lines.deinit(); + { + var iter = std.mem.splitScalar(u8, overlay, '\n'); + while (iter.next()) |line| try ov_lines.append(line); + } + + var result: Writer.Allocating = .init(allocator); + const w = &result.writer; + + var row: usize = 0; + while (row < bg_lines.items.len) : (row += 1) { + if (row > 0) try w.writeByte('\n'); + const ov_row_idx = if (row >= top) row - top else null; + if (ov_row_idx) |oidx| { + if (oidx < ov_lines.items.len) { + // Background prefix + overlay + background suffix. + const bg_line = bg_lines.items[row]; + const padded = try padOrTrim(allocator, bg_line, left); + defer allocator.free(padded); + try w.writeAll(padded); + try w.writeAll(ov_lines.items[oidx]); + continue; + } + } + try w.writeAll(bg_lines.items[row]); + } + + return result.toOwnedSlice(); +} + +fn padOrTrim(allocator: std.mem.Allocator, line: []const u8, target: usize) ![]u8 { + const w = measure.width(line); + if (w == target) return allocator.dupe(u8, line); + if (w < target) { + const pad = target - w; + const out = try allocator.alloc(u8, line.len + pad); + @memcpy(out[0..line.len], line); + @memset(out[line.len..], ' '); + return out; + } + // w > target: truncate visible width while preserving escapes. Best-effort. + const trimmed = try measure.truncate(allocator, line, target); + return @constCast(trimmed); +} + +// ── Tests ────────────────────────────────────────────────────────────── + +const testing = std.testing; + +const TestScreen = struct { + name: []const u8, + pop_on_q: bool = true, + quit_on_x: bool = false, + pub var enter_count: usize = 0; + pub var leave_count: usize = 0; + + fn update(ptr: *anyopaque, _: *Context, key: keys.KeyEvent) Action { + const self: *TestScreen = @ptrCast(@alignCast(ptr)); + switch (key.key) { + .char => |c| { + if (self.pop_on_q and c == 'q') return .pop; + if (self.quit_on_x and c == 'x') return .quit; + }, + else => {}, + } + return .none; + } + + fn view(ptr: *anyopaque, _: *const Context, allocator: std.mem.Allocator) ![]const u8 { + const self: *TestScreen = @ptrCast(@alignCast(ptr)); + return allocator.dupe(u8, self.name); + } + + fn onEnter(_: *anyopaque, _: *Context) void { + enter_count += 1; + } + + fn onSuspend(_: *anyopaque, _: *Context) void { + leave_count += 1; + } + + pub const vtable = Screen.VTable{ + .update = update, + .view = view, + .on_enter = onEnter, + .on_suspend = onSuspend, + }; +}; + +test "push and pop" { + var stack = ScreenStack.init(testing.allocator); + defer stack.deinit(); + + var s1 = TestScreen{ .name = "first" }; + var s2 = TestScreen{ .name = "second" }; + + try stack.push(.{ .ptr = &s1, .vtable = &TestScreen.vtable, .title = "first" }); + try testing.expectEqual(@as(usize, 1), stack.depth()); + try stack.push(.{ .ptr = &s2, .vtable = &TestScreen.vtable, .title = "second" }); + try testing.expectEqual(@as(usize, 2), stack.depth()); + + stack.pop(); + try testing.expectEqual(@as(usize, 1), stack.depth()); + const t = stack.top().?; + try testing.expectEqualStrings("first", t.title); +} + +test "handleKey processes pop action" { + var stack = ScreenStack.init(testing.allocator); + defer stack.deinit(); + + var s = TestScreen{ .name = "screen" }; + try stack.push(.{ .ptr = &s, .vtable = &TestScreen.vtable }); + + var ctx: Context = undefined; + const result = try stack.handleKey(&ctx, .{ .key = .{ .char = 'q' } }); + try testing.expectEqual(HandleResult.popped, result); + try testing.expect(stack.isEmpty()); +} + +test "quit action propagates" { + var stack = ScreenStack.init(testing.allocator); + defer stack.deinit(); + + var s = TestScreen{ .name = "screen", .quit_on_x = true }; + try stack.push(.{ .ptr = &s, .vtable = &TestScreen.vtable }); + + var ctx: Context = undefined; + const result = try stack.handleKey(&ctx, .{ .key = .{ .char = 'x' } }); + try testing.expectEqual(HandleResult.quit, result); +} + +test "modal screen overlays previous screen" { + var stack = ScreenStack.init(testing.allocator); + defer stack.deinit(); + + var bg = TestScreen{ .name = "background background background background\nbackground background background background\nbackground background background background\nbackground background background background" }; + var modal = TestScreen{ .name = "MODAL" }; + + try stack.push(.{ .ptr = &bg, .vtable = &TestScreen.vtable }); + try stack.push(.{ .ptr = &modal, .vtable = &TestScreen.vtable, .modal = true }); + + var ctx: Context = undefined; + const out = try stack.view(&ctx, testing.allocator); + defer testing.allocator.free(out); + + // Both background and modal should appear in output. + try testing.expect(std.mem.indexOf(u8, out, "background") != null); + try testing.expect(std.mem.indexOf(u8, out, "MODAL") != null); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig new file mode 100644 index 0000000..7a0e1a2 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig @@ -0,0 +1,87 @@ +//! Sub-program support for embedding child models inside a parent. +//! Allows composing independent Model-Update-View units with message routing. + +const std = @import("std"); +const Context = @import("context.zig").Context; +const command = @import("command.zig"); + +/// A wrapper that embeds a child Model inside a parent, with message mapping. +/// +/// - `ChildModel` must have `Msg`, `init`, `update`, `view` like a top-level model. +/// - `ParentMsg` is the parent's message type. +/// - The child's `.quit` command is converted to an optional parent message via `quit_msg`. +pub fn SubProgram(comptime ChildModel: type, comptime ParentMsg: type) type { + comptime { + if (!@hasDecl(ChildModel, "Msg")) @compileError("ChildModel must have a 'Msg' type"); + if (!@hasDecl(ChildModel, "init")) @compileError("ChildModel must have an 'init' function"); + if (!@hasDecl(ChildModel, "update")) @compileError("ChildModel must have an 'update' function"); + if (!@hasDecl(ChildModel, "view")) @compileError("ChildModel must have a 'view' function"); + } + + const ChildMsg = ChildModel.Msg; + const ChildCmd = command.Cmd(ChildMsg); + const ParentCmd = command.Cmd(ParentMsg); + + return struct { + model: ChildModel = undefined, + initialized: bool = false, + /// Optional message to send to parent when child issues .quit. + quit_msg: ?ParentMsg = null, + + const Self = @This(); + + /// Initialize the child model. + pub fn init(self: *Self, ctx: *Context) ParentCmd { + const child_cmd = self.model.init(ctx); + self.initialized = true; + return self.translateCmd(child_cmd); + } + + /// Forward a child message to the child's update, returning a parent command. + pub fn update(self: *Self, child_msg: ChildMsg, ctx: *Context) ParentCmd { + if (!self.initialized) return .none; + const child_cmd = self.model.update(child_msg, ctx); + return self.translateCmd(child_cmd); + } + + /// Render the child model. + pub fn view(self: *const Self, ctx: *const Context) []const u8 { + if (!self.initialized) return ""; + return self.model.view(ctx); + } + + /// Translate a child command into a parent command. + fn translateCmd(self: *const Self, cmd: ChildCmd) ParentCmd { + return switch (cmd) { + .none => .none, + .quit => if (self.quit_msg) |m| .{ .msg = m } else .none, + .tick => |ns| .{ .tick = ns }, + .every => |ns| .{ .every = ns }, + .msg => |child_msg| blk: { + // Child-internal messages: re-dispatch is not possible at parent level, + // so we drop them. The parent should call sub.update() with child messages. + _ = child_msg; + break :blk .none; + }, + .perform => .none, // Can't translate perform functions across types + .suspend_process => .suspend_process, + .enable_mouse => .enable_mouse, + .disable_mouse => .disable_mouse, + .show_cursor => .show_cursor, + .hide_cursor => .hide_cursor, + .enter_alt_screen => .enter_alt_screen, + .exit_alt_screen => .exit_alt_screen, + .set_title => |t| .{ .set_title = t }, + .println => |l| .{ .println = l }, + .batch => .none, // Complex: would need recursive translation + .sequence => .none, + .image_file => |img| .{ .image_file = img }, + .kitty_image_file => |img| .{ .kitty_image_file = img }, + .image_data => |img| .{ .image_data = img }, + .cache_image => |c| .{ .cache_image = c }, + .place_cached_image => |p| .{ .place_cached_image = p }, + .delete_image => |d| .{ .delete_image = d }, + }; + } + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig new file mode 100644 index 0000000..49ccd5c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig @@ -0,0 +1,128 @@ +//! Hit testing utilities for mouse interactions. +//! Provides rectangular region hit detection for UI components. + +const mouse = @import("mouse.zig"); +const MouseEvent = mouse.MouseEvent; + +/// A rectangular region for mouse hit testing. +pub const HitBox = struct { + x: u16, + y: u16, + width: u16, + height: u16, + + /// Create a hit box at the given position and size. + pub fn init(x: u16, y: u16, w: u16, h: u16) HitBox { + return .{ .x = x, .y = y, .width = w, .height = h }; + } + + /// Check whether a mouse event falls within this region. + pub fn contains(self: HitBox, event: MouseEvent) bool { + return event.x >= self.x and + event.x < self.x +| self.width and + event.y >= self.y and + event.y < self.y +| self.height; + } + + /// Check whether a coordinate falls within this region. + pub fn containsPoint(self: HitBox, x: u16, y: u16) bool { + return x >= self.x and + x < self.x +| self.width and + y >= self.y and + y < self.y +| self.height; + } + + /// Check if a click event (press with left button) occurred in this region. + pub fn clicked(self: HitBox, event: MouseEvent) bool { + return event.button == .left and + event.event_type == .press and + self.contains(event); + } + + /// Check if a right-click occurred in this region. + pub fn rightClicked(self: HitBox, event: MouseEvent) bool { + return event.button == .right and + event.event_type == .press and + self.contains(event); + } + + /// Get local coordinates relative to the hit box origin. + /// Returns null if the event is outside the region. + pub fn localCoords(self: HitBox, event: MouseEvent) ?struct { x: u16, y: u16 } { + if (!self.contains(event)) return null; + return .{ + .x = event.x - self.x, + .y = event.y - self.y, + }; + } + + /// Expand the hit box by a padding amount on all sides. + pub fn expand(self: HitBox, padding: u16) HitBox { + return .{ + .x = self.x -| padding, + .y = self.y -| padding, + .width = self.width +| padding *| 2, + .height = self.height +| padding *| 2, + }; + } + + /// Check if two hit boxes overlap. + pub fn overlaps(self: HitBox, other: HitBox) bool { + return self.x < other.x +| other.width and + self.x +| self.width > other.x and + self.y < other.y +| other.height and + self.y +| self.height > other.y; + } +}; + +/// Track mouse state across frames (hover, pressed, etc.) +pub const MouseState = struct { + hover: bool = false, + pressed: bool = false, + last_x: u16 = 0, + last_y: u16 = 0, + + /// Update state from a mouse event against a hit box. + /// Returns which interaction occurred. + pub fn update(self: *MouseState, hitbox: HitBox, event: MouseEvent) Interaction { + self.last_x = event.x; + self.last_y = event.y; + + const inside = hitbox.contains(event); + const was_hover = self.hover; + self.hover = inside; + + if (event.event_type == .press and event.button == .left and inside) { + self.pressed = true; + return .press; + } + + if (event.event_type == .release and event.button == .left) { + if (self.pressed and inside) { + self.pressed = false; + return .click; + } + self.pressed = false; + } + + if (inside and !was_hover) return .enter; + if (!inside and was_hover) return .leave; + if (inside and event.event_type == .move) return .hover; + + if (event.button == .wheel_up and inside) return .scroll_up; + if (event.button == .wheel_down and inside) return .scroll_down; + + return .none; + } +}; + +pub const Interaction = enum { + none, + press, + click, + enter, + leave, + hover, + scroll_up, + scroll_down, +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig new file mode 100644 index 0000000..f59c19c --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig @@ -0,0 +1,329 @@ +//! Keyboard input parsing for terminal applications. +//! Parses ANSI escape sequences into structured key events. + +const std = @import("std"); +const keys = @import("keys.zig"); +const mouse = @import("mouse.zig"); + +pub const Key = keys.Key; +pub const KeyEvent = keys.KeyEvent; +pub const Modifiers = keys.Modifiers; +pub const MouseEvent = mouse.MouseEvent; + +/// Result of parsing input data +pub const ParseResult = union(enum) { + key: KeyEvent, + mouse: MouseEvent, + none, +}; + +/// Return type for parse functions +pub const ParseReturn = struct { result: ParseResult, consumed: usize }; + +/// Parse a single input event from raw terminal data +pub fn parse(data: []const u8) ParseReturn { + if (data.len == 0) return .{ .result = .none, .consumed = 0 }; + + // Check for escape sequence + if (data[0] == 0x1b) { + if (data.len == 1) { + // Just escape key + return .{ .result = .{ .key = .{ .key = .escape } }, .consumed = 1 }; + } + + // CSI sequence + if (data.len >= 2 and data[1] == '[') { + if (parseCsi(data)) |result| { + return result; + } + } + + // SS3 sequence (F1-F4 on some terminals) + if (data.len >= 2 and data[1] == 'O') { + if (parseSs3(data)) |result| { + return result; + } + } + + // Alt + key + if (data.len >= 2 and data[1] != '[' and data[1] != 'O') { + const inner = parse(data[1..]); + if (inner.result == .key) { + var key_event = inner.result.key; + key_event.modifiers.alt = true; + return .{ .result = .{ .key = key_event }, .consumed = 1 + inner.consumed }; + } + } + + return .{ .result = .{ .key = .{ .key = .escape } }, .consumed = 1 }; + } + + // Control characters + if (data[0] < 32) { + const key_event = parseControl(data[0]); + return .{ .result = .{ .key = key_event }, .consumed = 1 }; + } + + // DEL character + if (data[0] == 127) { + return .{ .result = .{ .key = .{ .key = .backspace } }, .consumed = 1 }; + } + + // UTF-8 character + const len = std.unicode.utf8ByteSequenceLength(data[0]) catch 1; + if (len <= data.len) { + const codepoint = std.unicode.utf8Decode(data[0..len]) catch data[0]; + return .{ .result = .{ .key = .{ .key = .{ .char = codepoint } } }, .consumed = len }; + } + + return .{ .result = .{ .key = .{ .key = .{ .char = data[0] } } }, .consumed = 1 }; +} + +fn parseControl(c: u8) KeyEvent { + return switch (c) { + 0 => .{ .key = .null_key, .modifiers = .{ .ctrl = true } }, + 9 => .{ .key = .tab }, + // In raw mode 0x0a is sent by the terminal itself + // Some editor-integrated terminals (Zed, possibly VSCode) use this + // historical CR/LF split to encode Shift+Enter without a richer + // keyboard protocol -- plain Enter sends 0x0d, Shift+Enter sends + // 0x0a. Mapping LF onto Enter+Shift recovers the modifier, ensuring + // consistent behavior to other TUI applications / libraries. + 10 => .{ .key = .enter, .modifiers = .{ .shift = true } }, + 13 => .{ .key = .enter }, + 27 => .{ .key = .escape }, + 1...8, 11, 12, 14...26 => .{ + .key = .{ .char = 'a' + c - 1 }, + .modifiers = .{ .ctrl = true }, + }, + else => .{ .key = .{ .char = c } }, + }; +} + +fn parseCsi(data: []const u8) ?ParseReturn { + if (data.len < 3) return null; + if (data[0] != 0x1b or data[1] != '[') return null; + + // Check for bracketed paste start: ESC[200~ + if (data.len >= 6 and std.mem.startsWith(u8, data[2..], "200~")) { + return parseBracketedPaste(data); + } + + // Check for mouse SGR sequence + if (data.len >= 3 and data[2] == '<') { + if (mouse.parseSgr(data)) |m| { + return .{ .result = .{ .mouse = m.event }, .consumed = m.consumed }; + } + } + + var idx: usize = 2; + var params: [8]u16 = .{0} ** 8; + var param_count: usize = 0; + var has_colon = false; + var sub_params: [8]u16 = .{0} ** 8; + + // Parse parameters (supports both ; and : separators for Kitty protocol) + while (idx < data.len and param_count < params.len) { + const c = data[idx]; + if (c >= '0' and c <= '9') { + params[param_count] = params[param_count] * 10 + @as(u16, @intCast(c - '0')); + idx += 1; + } else if (c == ';') { + param_count += 1; + idx += 1; + } else if (c == ':') { + // Kitty protocol uses : for sub-parameters (e.g., modifiers:event_type) + has_colon = true; + sub_params[param_count] = 0; + idx += 1; + // Parse the sub-parameter value + while (idx < data.len and data[idx] >= '0' and data[idx] <= '9') { + sub_params[param_count] = sub_params[param_count] * 10 + @as(u16, @intCast(data[idx] - '0')); + idx += 1; + } + } else { + break; + } + } + param_count += 1; + + if (idx >= data.len) return null; + + const final_byte = data[idx]; + idx += 1; + + // Kitty keyboard protocol: final byte 'u' + if (final_byte == 'u') { + return parseKittyCsi(params[0..param_count], sub_params[0..param_count], has_colon, idx); + } + + // Determine modifiers from parameter + var modifiers = Modifiers{}; + if (param_count >= 2 and params[1] > 1) { + const mod_param = params[1] - 1; + modifiers.shift = (mod_param & 1) != 0; + modifiers.alt = (mod_param & 2) != 0; + modifiers.ctrl = (mod_param & 4) != 0; + } + + const key: Key = switch (final_byte) { + 'A' => .up, + 'B' => .down, + 'C' => .right, + 'D' => .left, + 'H' => .home, + 'F' => .end, + 'Z' => { + modifiers.shift = true; + return .{ .result = .{ .key = .{ .key = .tab, .modifiers = modifiers } }, .consumed = idx }; + }, + '~' => switch (params[0]) { + 1 => .home, + 2 => .insert, + 3 => .delete, + 4 => .end, + 5 => .page_up, + 6 => .page_down, + 7 => .home, + 8 => .end, + 11 => .f1, + 12 => .f2, + 13 => .f3, + 14 => .f4, + 15 => .f5, + 17 => .f6, + 18 => .f7, + 19 => .f8, + 20 => .f9, + 21 => .f10, + 23 => .f11, + 24 => .f12, + else => return null, + }, + else => return null, + }; + + return .{ .result = .{ .key = .{ .key = key, .modifiers = modifiers } }, .consumed = idx }; +} + +/// Parse Kitty keyboard protocol CSI sequence: CSI keycode;modifiers:event_type u +fn parseKittyCsi(params: []const u16, sub_params: []const u16, has_colon: bool, consumed: usize) ?ParseReturn { + if (params.len == 0) return null; + + const keycode = params[0]; + + // Determine modifiers + var modifiers = Modifiers{}; + if (params.len >= 2 and params[1] > 1) { + const mod_param = params[1] - 1; + modifiers.shift = (mod_param & 1) != 0; + modifiers.alt = (mod_param & 2) != 0; + modifiers.ctrl = (mod_param & 4) != 0; + modifiers.super = (mod_param & 8) != 0; + } + + // Determine event type from sub-parameter + var event_type: keys.KeyEventType = .press; + if (has_colon and params.len >= 2) { + event_type = switch (sub_params[1]) { + 2 => .repeat, + 3 => .release, + else => .press, + }; + } + + // Map keycode to Key + const key: Key = switch (keycode) { + 9 => .tab, + 13 => .enter, + 27 => .escape, + 32 => .space, + 127 => .backspace, + 57358 => .{ .char = 0 }, // caps_lock etc - map to null + else => blk: { + if (keycode >= 32 and keycode < 127) { + break :blk .{ .char = @intCast(keycode) }; + } + if (keycode > 127 and keycode <= 0x10FFFF) { + break :blk .{ .char = @intCast(keycode) }; + } + break :blk .null_key; + }, + }; + + return .{ + .result = .{ .key = .{ + .key = key, + .modifiers = modifiers, + .event_type = event_type, + } }, + .consumed = consumed, + }; +} + +/// Parse bracketed paste: ESC[200~ ... ESC[201~ +fn parseBracketedPaste(data: []const u8) ?ParseReturn { + // data starts with ESC[200~ + const paste_start = 6; // length of ESC[200~ + const end_marker = "\x1b[201~"; + + if (std.mem.indexOf(u8, data[paste_start..], end_marker)) |end_offset| { + const paste_content = data[paste_start .. paste_start + end_offset]; + const total_consumed = paste_start + end_offset + end_marker.len; + return .{ + .result = .{ .key = .{ + .key = .{ .paste = paste_content }, + } }, + .consumed = total_consumed, + }; + } + + // End marker not found — consume all available data as paste + // (paste may span multiple reads) + return .{ + .result = .{ .key = .{ + .key = .{ .paste = data[paste_start..] }, + } }, + .consumed = data.len, + }; +} + +fn parseSs3(data: []const u8) ?ParseReturn { + if (data.len < 3) return null; + if (data[0] != 0x1b or data[1] != 'O') return null; + + const key: Key = switch (data[2]) { + 'P' => .f1, + 'Q' => .f2, + 'R' => .f3, + 'S' => .f4, + 'A' => .up, + 'B' => .down, + 'C' => .right, + 'D' => .left, + 'H' => .home, + 'F' => .end, + else => return null, + }; + + return .{ .result = .{ .key = .{ .key = key } }, .consumed = 3 }; +} + +/// Parse all available input events from a buffer +pub fn parseAll(allocator: std.mem.Allocator, data: []const u8) ![]ParseResult { + var results = std.array_list.Managed(ParseResult).init(allocator); + errdefer results.deinit(); + + var offset: usize = 0; + while (offset < data.len) { + const parsed = parse(data[offset..]); + if (parsed.consumed == 0) break; + + if (parsed.result != .none) { + try results.append(parsed.result); + } + offset += parsed.consumed; + } + + return results.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig new file mode 100644 index 0000000..b858fa2 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig @@ -0,0 +1,191 @@ +//! Key definitions for keyboard input handling. +//! Provides a comprehensive set of key types for terminal input. + +const std = @import("std"); +const Writer = std.Io.Writer; + +/// Modifier keys that can be combined with other keys +pub const Modifiers = packed struct { + shift: bool = false, + alt: bool = false, + ctrl: bool = false, + super: bool = false, + + pub const none = Modifiers{}; + + pub fn eql(self: Modifiers, other: Modifiers) bool { + return self.shift == other.shift and + self.alt == other.alt and + self.ctrl == other.ctrl and + self.super == other.super; + } + + pub fn any(self: Modifiers) bool { + return self.shift or self.alt or self.ctrl or self.super; + } +}; + +/// Represents a keyboard key +pub const Key = union(enum) { + // Character keys + char: u21, + + // Function keys + f1, + f2, + f3, + f4, + f5, + f6, + f7, + f8, + f9, + f10, + f11, + f12, + + // Navigation keys + up, + down, + left, + right, + home, + end, + page_up, + page_down, + + // Editing keys + insert, + delete, + backspace, + + // Control keys + enter, + tab, + escape, + space, + + // Paste (bracketed paste content) + paste: []const u8, + + // Special + null_key, + unknown: []const u8, + + pub fn eql(self: Key, other: Key) bool { + const self_tag = std.meta.activeTag(self); + const other_tag = std.meta.activeTag(other); + if (self_tag != other_tag) return false; + + return switch (self) { + .char => |c| c == other.char, + .paste => |s| std.mem.eql(u8, s, other.paste), + .unknown => |s| std.mem.eql(u8, s, other.unknown), + else => true, + }; + } + + /// Returns the character if this is a char key, null otherwise + pub fn toChar(self: Key) ?u21 { + return switch (self) { + .char => |c| c, + .space => ' ', + .enter => '\n', + .tab => '\t', + else => null, + }; + } + + /// Returns a human-readable string for the key + pub fn name(self: Key) []const u8 { + return switch (self) { + .char => "char", + .f1 => "f1", + .f2 => "f2", + .f3 => "f3", + .f4 => "f4", + .f5 => "f5", + .f6 => "f6", + .f7 => "f7", + .f8 => "f8", + .f9 => "f9", + .f10 => "f10", + .f11 => "f11", + .f12 => "f12", + .up => "up", + .down => "down", + .left => "left", + .right => "right", + .home => "home", + .end => "end", + .page_up => "page_up", + .page_down => "page_down", + .insert => "insert", + .delete => "delete", + .backspace => "backspace", + .enter => "enter", + .tab => "tab", + .escape => "escape", + .space => "space", + .paste => "paste", + .null_key => "null", + .unknown => "unknown", + }; + } +}; + +/// Key event type (for Kitty keyboard protocol) +pub const KeyEventType = enum { + press, + repeat, + release, +}; + +/// A key event with modifiers +pub const KeyEvent = struct { + key: Key, + modifiers: Modifiers = .{}, + event_type: KeyEventType = .press, + + pub fn eql(self: KeyEvent, other: KeyEvent) bool { + return self.key.eql(other.key) and self.modifiers.eql(other.modifiers); + } + + /// Create a key event from a character + pub fn char(c: u21) KeyEvent { + return .{ .key = .{ .char = c } }; + } + + /// Create a key event with ctrl modifier + pub fn ctrl(c: u21) KeyEvent { + return .{ + .key = .{ .char = c }, + .modifiers = .{ .ctrl = true }, + }; + } + + /// Create a key event with alt modifier + pub fn alt(c: u21) KeyEvent { + return .{ + .key = .{ .char = c }, + .modifiers = .{ .alt = true }, + }; + } + + /// Format the key event for display + pub fn format(self: KeyEvent, writer: *Writer) Writer.Error!void { + if (self.modifiers.ctrl) try writer.writeAll("ctrl+"); + if (self.modifiers.alt) try writer.writeAll("alt+"); + if (self.modifiers.shift) try writer.writeAll("shift+"); + if (self.modifiers.super) try writer.writeAll("super+"); + + switch (self.key) { + .char => |c| { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(c, &buf) catch 0; + try writer.writeAll(buf[0..len]); + }, + else => try writer.writeAll(self.key.name()), + } + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig new file mode 100644 index 0000000..795c66f --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig @@ -0,0 +1,164 @@ +//! Mouse event handling for terminal applications. +//! Supports standard terminal mouse protocols. + +const std = @import("std"); +const Writer = std.Io.Writer; +const keys = @import("keys.zig"); + +/// Mouse button types +pub const Button = enum { + left, + middle, + right, + wheel_up, + wheel_down, + wheel_left, + wheel_right, + button_8, + button_9, + button_10, + button_11, + none, +}; + +/// Mouse event types +pub const EventType = enum { + press, + release, + drag, + move, +}; + +/// A mouse event +pub const MouseEvent = struct { + x: u16, + y: u16, + button: Button, + event_type: EventType, + modifiers: keys.Modifiers = .{}, + + pub fn format(self: MouseEvent, writer: *Writer) Writer.Error!void { + try writer.print("{s} {s} at ({d}, {d})", .{ + @tagName(self.event_type), + @tagName(self.button), + self.x, + self.y, + }); + + if (self.modifiers.any()) { + try writer.writeAll(" with "); + if (self.modifiers.ctrl) try writer.writeAll("ctrl "); + if (self.modifiers.alt) try writer.writeAll("alt "); + if (self.modifiers.shift) try writer.writeAll("shift "); + } + } +}; + +/// Mouse tracking modes +pub const TrackingMode = enum { + /// No mouse tracking + none, + /// Report button press events only + normal, + /// Report button press and release events + button, + /// Report all mouse events including motion + all, +}; + +/// Generate ANSI sequence to enable mouse tracking +pub fn enableSequence(mode: TrackingMode) []const u8 { + return switch (mode) { + .none => "", + .normal => "\x1b[?1000h\x1b[?1006h", + .button => "\x1b[?1002h\x1b[?1006h", + .all => "\x1b[?1003h\x1b[?1006h", + }; +} + +/// Generate ANSI sequence to disable mouse tracking +pub fn disableSequence(mode: TrackingMode) []const u8 { + return switch (mode) { + .none => "", + .normal => "\x1b[?1006l\x1b[?1000l", + .button => "\x1b[?1006l\x1b[?1002l", + .all => "\x1b[?1006l\x1b[?1003l", + }; +} + +/// Parse SGR mouse event (\x1b[<...M or \x1b[<...m) +pub fn parseSgr(data: []const u8) ?struct { event: MouseEvent, consumed: usize } { + // Format: \x1b[= '0' and c <= '9') { + params[param_idx] = params[param_idx] * 10 + @as(u16, @intCast(c - '0')); + idx += 1; + } else if (c == ';') { + param_idx += 1; + idx += 1; + } else if (c == 'M' or c == 'm') { + idx += 1; + break; + } else { + return null; + } + } + + if (param_idx < 2) return null; + if (idx == 0 or (data[idx - 1] != 'M' and data[idx - 1] != 'm')) return null; + + const cb = params[0]; + const is_release = data[idx - 1] == 'm'; + + var modifiers = keys.Modifiers{}; + if (cb & 4 != 0) modifiers.shift = true; + if (cb & 8 != 0) modifiers.alt = true; + if (cb & 16 != 0) modifiers.ctrl = true; + + const button_bits = cb & 0b11000011; + const is_motion = cb & 32 != 0; + + const button: Button = switch (button_bits) { + 0 => .left, + 1 => .middle, + 2 => .right, + 3 => .none, + 64 => .wheel_up, + 65 => .wheel_down, + 66 => .wheel_left, + 67 => .wheel_right, + 128 => .button_8, + 129 => .button_9, + 130 => .button_10, + 131 => .button_11, + else => .none, + }; + + const event_type: EventType = if (is_release) + .release + else if (is_motion and button == .none) + .move + else if (is_motion) + .drag + else + .press; + + return .{ + .event = .{ + .x = if (params[1] > 0) params[1] - 1 else 0, + .y = if (params[2] > 0) params[2] - 1 else 0, + .button = button, + .event_type = event_type, + .modifiers = modifiers, + }, + .consumed = idx, + }; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig new file mode 100644 index 0000000..fca1d49 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig @@ -0,0 +1,473 @@ +//! Constraint-based Flexbox layout engine for ZigZag TUI. +//! +//! Resolves sizing constraints and computes rectangular areas +//! for a list of flex items along a main axis (row or column), +//! with support for gaps, cross-axis alignment, main-axis +//! justification, and line wrapping. +//! +//! ## Example +//! +//! ```zig +//! const areas = try flex.layout(allocator, 80, 24, &.{ +//! .{ .constraint = .{ .percentage = 30 } }, +//! .{ .constraint = .{ .min = 10 } }, +//! .{ .constraint = .fill }, +//! }, .{ .direction = .row, .gap = 1 }); +//! ``` + +const std = @import("std"); + +// --------------------------------------------------------------------------- +// Public types +// --------------------------------------------------------------------------- + +/// A sizing constraint for one flex item. +pub const Constraint = union(enum) { + /// Exactly `n` cells. + fixed: u16, + /// A percentage of total available space (0-100). + percentage: u8, + /// At least `n` cells (can grow to fill). + min: u16, + /// At most `n` cells (can shrink to fit). + max: u16, + /// Ratio: `num / den` of available space. + ratio: struct { num: u16, den: u16 }, + /// Take all remaining space after fixed/percentage items. + fill, +}; + +/// Main-axis direction. +pub const Direction = enum { + row, + column, +}; + +/// Cross-axis alignment. +pub const Alignment = enum { + start, + center, + end, + stretch, +}; + +/// Main-axis content distribution. +pub const Justify = enum { + start, + center, + end, + space_between, + space_around, + space_evenly, +}; + +/// Describes a single flex child. +pub const Item = struct { + constraint: Constraint = .fill, +}; + +/// Layout options. +pub const FlexOptions = struct { + direction: Direction = .row, + gap: u16 = 0, + alignment: Alignment = .stretch, + justify: Justify = .start, + wrap: bool = false, +}; + +/// An output rectangle (in cell coordinates). +pub const Rect = struct { + x: u16, + y: u16, + width: u16, + height: u16, +}; + +// --------------------------------------------------------------------------- +// Core layout algorithm +// --------------------------------------------------------------------------- + +/// Compute layout rectangles for `items` inside a container of +/// `total_width` x `total_height` cells. +/// +/// Returns a slice of `Rect` allocated with `allocator`. +pub fn layout( + allocator: std.mem.Allocator, + total_width: u16, + total_height: u16, + items: []const Item, + options: FlexOptions, +) ![]Rect { + if (items.len == 0) { + return try allocator.alloc(Rect, 0); + } + + if (options.wrap) { + return layoutWrapped(allocator, total_width, total_height, items, options); + } + + return layoutLine(allocator, total_width, total_height, items, options, 0, 0); +} + +/// Layout a single line of items (no wrapping). +fn layoutLine( + allocator: std.mem.Allocator, + total_width: u16, + total_height: u16, + items: []const Item, + options: FlexOptions, + origin_x: u16, + origin_y: u16, +) ![]Rect { + const n = items.len; + const is_row = options.direction == .row; + const main_total: u16 = if (is_row) total_width else total_height; + const cross_total: u16 = if (is_row) total_height else total_width; + + // Total gap space + const gap_count: u16 = if (n > 1) @intCast(n - 1) else 0; + const total_gap: u16 = gap_count * options.gap; + const avail: u16 = if (main_total > total_gap) main_total - total_gap else 0; + + // -- Phase 1: resolve constraints to sizes -------------------------------- + var sizes = try allocator.alloc(u16, n); + defer allocator.free(sizes); + + var fill_count: u16 = 0; + var used: u32 = 0; + + for (items, 0..) |item, i| { + switch (item.constraint) { + .fixed => |v| { + sizes[i] = v; + used += v; + }, + .percentage => |pct| { + const clamped: u32 = @min(pct, 100); + const sz: u16 = @intCast((@as(u32, avail) * clamped) / 100); + sizes[i] = sz; + used += sz; + }, + .min => |v| { + sizes[i] = v; + used += v; + }, + .max => |v| { + sizes[i] = v; + used += v; + }, + .ratio => |r| { + const sz: u16 = if (r.den == 0) 0 else @intCast((@as(u32, avail) * r.num) / r.den); + sizes[i] = sz; + used += sz; + }, + .fill => { + sizes[i] = 0; + fill_count += 1; + }, + } + } + + // -- Phase 2: distribute remaining space among fill items ----------------- + const remaining: u16 = if (avail > @as(u16, @intCast(@min(used, avail)))) avail - @as(u16, @intCast(@min(used, avail))) else 0; + if (fill_count > 0 and remaining > 0) { + const per_fill: u16 = remaining / fill_count; + var leftover: u16 = remaining - per_fill * fill_count; + for (items, 0..) |item, i| { + if (item.constraint == .fill) { + sizes[i] = per_fill; + if (leftover > 0) { + sizes[i] += 1; + leftover -= 1; + } + } + } + } + + // Grow `min` items if there is leftover space + if (fill_count == 0 and remaining > 0) { + var min_count: u16 = 0; + for (items) |item| { + if (item.constraint == .min) min_count += 1; + } + if (min_count > 0) { + const per_min: u16 = remaining / min_count; + var leftover: u16 = remaining - per_min * min_count; + for (items, 0..) |item, i| { + if (item.constraint == .min) { + sizes[i] += per_min; + if (leftover > 0) { + sizes[i] += 1; + leftover -= 1; + } + } + } + } + } + + // Shrink `max` items so they don't exceed their cap + for (items, 0..) |item, i| { + if (item.constraint == .max) { + const cap = item.constraint.max; + if (sizes[i] > cap) sizes[i] = cap; + } + } + + // Clamp all sizes so total doesn't exceed available space + { + var sum: u32 = 0; + for (sizes) |s| sum += s; + if (sum > avail) { + const scale_num: u32 = avail; + const scale_den: u32 = sum; + for (sizes, 0..) |_, i| { + sizes[i] = @intCast((@as(u32, sizes[i]) * scale_num) / scale_den); + } + } + } + + // -- Phase 3: compute positions using justification ---------------------- + var positions = try allocator.alloc(u16, n); + defer allocator.free(positions); + + { + var total_sizes: u32 = 0; + for (sizes) |s| total_sizes += s; + const total_content: u32 = total_sizes + total_gap; + const free_space: u16 = if (main_total > @as(u16, @intCast(@min(total_content, main_total)))) main_total - @as(u16, @intCast(total_content)) else 0; + + var cursor: u16 = switch (options.justify) { + .start => 0, + .center => free_space / 2, + .end => free_space, + .space_between => 0, + .space_around => 0, + .space_evenly => 0, + }; + + // Compute per-item extra spacing for space_* modes + var between_extra: u16 = 0; + var before_first: u16 = 0; + + switch (options.justify) { + .space_between => { + if (n > 1) { + between_extra = free_space / @as(u16, @intCast(n - 1)); + } + }, + .space_around => { + const slot: u16 = free_space / @as(u16, @intCast(n)); + before_first = slot / 2; + between_extra = slot; + cursor = before_first; + }, + .space_evenly => { + const slot: u16 = free_space / @as(u16, @intCast(n + 1)); + before_first = slot; + between_extra = slot; + cursor = before_first; + }, + else => {}, + } + + for (0..n) |i| { + positions[i] = cursor; + cursor += sizes[i]; + if (i < n - 1) { + cursor += options.gap + between_extra; + } + } + } + + // -- Phase 4: build output Rects ----------------------------------------- + var rects = try allocator.alloc(Rect, n); + + for (0..n) |i| { + const main_pos = positions[i]; + const main_size = sizes[i]; + + const cross_pos: u16 = 0; + const cross_size: u16 = cross_total; + + if (is_row) { + rects[i] = .{ + .x = origin_x + main_pos, + .y = origin_y + cross_pos, + .width = main_size, + .height = cross_size, + }; + } else { + rects[i] = .{ + .x = origin_x + cross_pos, + .y = origin_y + main_pos, + .width = cross_size, + .height = main_size, + }; + } + } + + return rects; +} + +// --------------------------------------------------------------------------- +// Wrapped layout +// --------------------------------------------------------------------------- + +fn layoutWrapped( + allocator: std.mem.Allocator, + total_width: u16, + total_height: u16, + items: []const Item, + options: FlexOptions, +) ![]Rect { + const is_row = options.direction == .row; + const main_total: u16 = if (is_row) total_width else total_height; + + // First pass: figure out which items go on which line + var lines = std.array_list.Managed(LineRange).init(allocator); + defer lines.deinit(); + + var line_start: usize = 0; + var line_used: u32 = 0; + + for (items, 0..) |item, i| { + const item_size = estimateSize(item.constraint, main_total); + const gap_needed: u32 = if (i > line_start) options.gap else 0; + + if (line_used + gap_needed + item_size > main_total and i > line_start) { + try lines.append(.{ .start = line_start, .end = i }); + line_start = i; + line_used = item_size; + } else { + line_used += gap_needed + item_size; + } + } + // Last line + if (line_start < items.len) { + try lines.append(.{ .start = line_start, .end = items.len }); + } + + const num_lines = lines.items.len; + if (num_lines == 0) { + return try allocator.alloc(Rect, 0); + } + + const cross_total: u16 = if (is_row) total_height else total_width; + const per_line: u16 = if (num_lines > 0) cross_total / @as(u16, @intCast(num_lines)) else cross_total; + + var rects = try allocator.alloc(Rect, items.len); + + var cross_cursor: u16 = 0; + for (lines.items) |line| { + const line_items = items[line.start..line.end]; + const line_main: u16 = if (is_row) total_width else per_line; + const line_cross: u16 = per_line; + const line_w: u16 = if (is_row) line_main else line_cross; + const line_h: u16 = if (is_row) line_cross else line_main; + const ox: u16 = if (is_row) 0 else cross_cursor; + const oy: u16 = if (is_row) cross_cursor else 0; + + const line_rects = try layoutLine(allocator, line_w, line_h, line_items, options, ox, oy); + defer allocator.free(line_rects); + + @memcpy(rects[line.start..line.end], line_rects); + cross_cursor += per_line; + } + + return rects; +} + +const LineRange = struct { + start: usize, + end: usize, +}; + +fn estimateSize(constraint: Constraint, total: u16) u32 { + return switch (constraint) { + .fixed => |v| v, + .percentage => |pct| (@as(u32, total) * @as(u32, @min(pct, 100))) / 100, + .min => |v| v, + .max => |v| v, + .ratio => |r| if (r.den == 0) 0 else (@as(u32, total) * r.num) / r.den, + .fill => 1, // minimum estimate for wrapping purposes + }; +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +test "basic row layout" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 100, 24, &.{ + .{ .constraint = .{ .fixed = 20 } }, + .{ .constraint = .fill }, + .{ .constraint = .{ .fixed = 30 } }, + }, .{ .direction = .row }); + defer allocator.free(rects); + + try std.testing.expectEqual(@as(usize, 3), rects.len); + try std.testing.expectEqual(@as(u16, 20), rects[0].width); + try std.testing.expectEqual(@as(u16, 30), rects[2].width); + try std.testing.expectEqual(@as(u16, 50), rects[1].width); + try std.testing.expectEqual(@as(u16, 0), rects[0].x); + try std.testing.expectEqual(@as(u16, 20), rects[1].x); + try std.testing.expectEqual(@as(u16, 70), rects[2].x); +} + +test "column layout" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 80, 40, &.{ + .{ .constraint = .{ .fixed = 3 } }, + .{ .constraint = .fill }, + .{ .constraint = .{ .fixed = 1 } }, + }, .{ .direction = .column }); + defer allocator.free(rects); + + try std.testing.expectEqual(@as(u16, 3), rects[0].height); + try std.testing.expectEqual(@as(u16, 36), rects[1].height); + try std.testing.expectEqual(@as(u16, 1), rects[2].height); +} + +test "percentage constraint" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 100, 10, &.{ + .{ .constraint = .{ .percentage = 30 } }, + .{ .constraint = .{ .percentage = 70 } }, + }, .{ .direction = .row }); + defer allocator.free(rects); + + try std.testing.expectEqual(@as(u16, 30), rects[0].width); + try std.testing.expectEqual(@as(u16, 70), rects[1].width); +} + +test "gap spacing" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 100, 10, &.{ + .{ .constraint = .{ .fixed = 20 } }, + .{ .constraint = .{ .fixed = 20 } }, + }, .{ .direction = .row, .gap = 5 }); + defer allocator.free(rects); + + try std.testing.expectEqual(@as(u16, 0), rects[0].x); + try std.testing.expectEqual(@as(u16, 25), rects[1].x); +} + +test "ratio constraint" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 90, 10, &.{ + .{ .constraint = .{ .ratio = .{ .num = 1, .den = 3 } } }, + .{ .constraint = .{ .ratio = .{ .num = 2, .den = 3 } } }, + }, .{ .direction = .row }); + defer allocator.free(rects); + + try std.testing.expectEqual(@as(u16, 30), rects[0].width); + try std.testing.expectEqual(@as(u16, 60), rects[1].width); +} + +test "empty items" { + const allocator = std.testing.allocator; + const rects = try layout(allocator, 80, 24, &.{}, .{}); + defer allocator.free(rects); + try std.testing.expectEqual(@as(usize, 0), rects.len); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig new file mode 100644 index 0000000..0a2b3d5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig @@ -0,0 +1,225 @@ +//! Layout joining utilities for combining multiple text blocks. +//! Provides horizontal and vertical joining with alignment options. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("measure.zig"); + +/// Vertical alignment for horizontal joins +pub const VAlign = enum { + top, + middle, + bottom, +}; + +/// Horizontal alignment for vertical joins +pub const HAlign = enum { + left, + center, + right, +}; + +/// Join multiple strings horizontally (side by side) +pub fn horizontal(allocator: std.mem.Allocator, valign: VAlign, parts: []const []const u8) ![]const u8 { + if (parts.len == 0) return try allocator.dupe(u8, ""); + if (parts.len == 1) return try allocator.dupe(u8, parts[0]); + + // Calculate dimensions + var max_height: usize = 0; + var widths = try allocator.alloc(usize, parts.len); + defer allocator.free(widths); + + for (parts, 0..) |part, i| { + widths[i] = measure.maxLineWidth(part); + max_height = @max(max_height, measure.height(part)); + } + + if (max_height == 0) max_height = 1; + + // Split all parts into lines + var all_lines = try allocator.alloc([][]const u8, parts.len); + defer { + for (all_lines) |lines| { + allocator.free(lines); + } + allocator.free(all_lines); + } + + for (parts, 0..) |part, i| { + var lines_list = std.array_list.Managed([]const u8).init(allocator); + var iter = std.mem.splitScalar(u8, part, '\n'); + while (iter.next()) |line| { + try lines_list.append(line); + } + all_lines[i] = try lines_list.toOwnedSlice(); + } + + // Build result + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (0..max_height) |row| { + if (row > 0) try writer.writeByte('\n'); + + for (parts, 0..) |_, part_idx| { + const lines = all_lines[part_idx]; + const part_height = lines.len; + const w = widths[part_idx]; + + // Calculate offset based on alignment + const offset: usize = switch (valign) { + .top => 0, + .middle => (max_height - part_height) / 2, + .bottom => max_height - part_height, + }; + + const line_idx = if (row >= offset and row < offset + part_height) + row - offset + else + null; + + if (line_idx) |idx| { + const line = lines[idx]; + try writer.writeAll(line); + // Pad to width + const line_width = measure.width(line); + if (line_width < w) { + for (0..(w - line_width)) |_| { + try writer.writeByte(' '); + } + } + } else { + // Empty line + for (0..w) |_| { + try writer.writeByte(' '); + } + } + } + } + + return result.toOwnedSlice(); +} + +/// Join multiple strings vertically (stacked) +pub fn vertical(allocator: std.mem.Allocator, halign: HAlign, parts: []const []const u8) ![]const u8 { + if (parts.len == 0) return try allocator.dupe(u8, ""); + if (parts.len == 1) return try allocator.dupe(u8, parts[0]); + + // Calculate max width + var max_width: usize = 0; + for (parts) |part| { + max_width = @max(max_width, measure.maxLineWidth(part)); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (parts, 0..) |part, part_idx| { + if (part_idx > 0) try writer.writeByte('\n'); + + var lines = std.mem.splitScalar(u8, part, '\n'); + var first_line = true; + + while (lines.next()) |line| { + if (!first_line) try writer.writeByte('\n'); + first_line = false; + + const line_width = measure.width(line); + const padding = if (max_width > line_width) max_width - line_width else 0; + + switch (halign) { + .left => { + try writer.writeAll(line); + for (0..padding) |_| { + try writer.writeByte(' '); + } + }, + .center => { + const left_pad = padding / 2; + const right_pad = padding - left_pad; + for (0..left_pad) |_| { + try writer.writeByte(' '); + } + try writer.writeAll(line); + for (0..right_pad) |_| { + try writer.writeByte(' '); + } + }, + .right => { + for (0..padding) |_| { + try writer.writeByte(' '); + } + try writer.writeAll(line); + }, + } + } + } + + return result.toOwnedSlice(); +} + +/// Join with a separator +pub fn horizontalSep( + allocator: std.mem.Allocator, + valign: VAlign, + separator: []const u8, + parts: []const []const u8, +) ![]const u8 { + if (parts.len == 0) return try allocator.dupe(u8, ""); + if (parts.len == 1) return try allocator.dupe(u8, parts[0]); + + // Create new parts array with separators + var with_seps = try allocator.alloc([]const u8, parts.len * 2 - 1); + defer allocator.free(with_seps); + + for (parts, 0..) |part, i| { + with_seps[i * 2] = part; + if (i < parts.len - 1) { + with_seps[i * 2 + 1] = separator; + } + } + + return horizontal(allocator, valign, with_seps[0 .. parts.len * 2 - 1]); +} + +/// Join with a separator +pub fn verticalSep( + allocator: std.mem.Allocator, + halign: HAlign, + separator: []const u8, + parts: []const []const u8, +) ![]const u8 { + if (parts.len == 0) return try allocator.dupe(u8, ""); + if (parts.len == 1) return try allocator.dupe(u8, parts[0]); + + // Create new parts array with separators + var with_seps = try allocator.alloc([]const u8, parts.len * 2 - 1); + defer allocator.free(with_seps); + + for (parts, 0..) |part, i| { + with_seps[i * 2] = part; + if (i < parts.len - 1) { + with_seps[i * 2 + 1] = separator; + } + } + + return vertical(allocator, halign, with_seps[0 .. parts.len * 2 - 1]); +} + +test "horizontal join" { + const testing = std.testing; + const alloc = testing.allocator; + + const result = try horizontal(alloc, .top, &[_][]const u8{ "A", "B", "C" }); + defer alloc.free(result); + try testing.expectEqualStrings("ABC", result); +} + +test "vertical join" { + const testing = std.testing; + const alloc = testing.allocator; + + const result = try vertical(alloc, .left, &[_][]const u8{ "A", "B", "C" }); + defer alloc.free(result); + try testing.expectEqualStrings("A\nB\nC", result); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig new file mode 100644 index 0000000..0232c2b --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig @@ -0,0 +1,156 @@ +//! Layer compositing system for z-ordered UI overlays. +//! Manages a stack of rendered text layers and composites them +//! into a single output with proper z-ordering and transparency. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("measure.zig"); + +/// A single layer in the stack. +pub const Layer = struct { + /// Rendered content string. + content: []const u8, + /// X position (column offset). + x: u16 = 0, + /// Y position (row offset). + y: u16 = 0, + /// Z-index for ordering. Higher = on top. + z: i16 = 0, + /// If true, space characters are transparent (show layer below). + transparent: bool = true, +}; + +/// Composites multiple layers into a single rendered output. +pub const LayerStack = struct { + allocator: std.mem.Allocator, + layers: std.array_list.Managed(Layer), + width: u16 = 80, + height: u16 = 24, + /// Background character for empty cells. + background: u8 = ' ', + + pub fn init(allocator: std.mem.Allocator) LayerStack { + return .{ + .allocator = allocator, + .layers = std.array_list.Managed(Layer).init(allocator), + }; + } + + pub fn deinit(self: *LayerStack) void { + self.layers.deinit(); + } + + pub fn setSize(self: *LayerStack, w: u16, h: u16) void { + self.width = w; + self.height = h; + } + + pub fn push(self: *LayerStack, layer: Layer) !void { + try self.layers.append(layer); + } + + pub fn clear(self: *LayerStack) void { + self.layers.clearRetainingCapacity(); + } + + /// Composite all layers and return the final rendered string. + pub fn render(self: *const LayerStack, allocator: std.mem.Allocator) []const u8 { + const w: usize = self.width; + const h: usize = self.height; + + // Create cell buffer: each cell stores a byte slice (content) and ANSI state + // For simplicity, we use a 2D grid of cells that stores display characters + const grid = allocator.alloc(Cell, w * h) catch return ""; + + // Fill with background + for (grid) |*cell| { + cell.* = .{ .char = self.background, .ansi_prefix = "" }; + } + + // Sort layers by z-index + const sorted = allocator.alloc(Layer, self.layers.items.len) catch return ""; + @memcpy(sorted, self.layers.items); + std.mem.sort(Layer, sorted, {}, struct { + fn lessThan(_: void, a: Layer, b: Layer) bool { + return a.z < b.z; + } + }.lessThan); + + // Paint each layer onto the grid + for (sorted) |layer| { + self.paintLayer(grid, w, h, layer); + } + + // Render grid to string + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (0..h) |row| { + if (row > 0) writer.writeByte('\n') catch {}; + for (0..w) |col| { + const cell = grid[row * w + col]; + if (cell.ansi_prefix.len > 0) { + writer.writeAll(cell.ansi_prefix) catch {}; + writer.writeByte(cell.char) catch {}; + writer.writeAll("\x1b[0m") catch {}; + } else { + writer.writeByte(cell.char) catch {}; + } + } + } + + return result.toArrayList().items; + } + + fn paintLayer(self: *const LayerStack, grid: []Cell, w: usize, h: usize, layer: Layer) void { + _ = self; + const content = layer.content; + var row: usize = layer.y; + var col: usize = layer.x; + var i: usize = 0; + var current_ansi: []const u8 = ""; + + while (i < content.len and row < h) { + if (content[i] == '\n') { + row += 1; + col = layer.x; + i += 1; + continue; + } + + // Detect ANSI escape sequence + if (content[i] == 0x1b and i + 1 < content.len and content[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < content.len and content[i] != 'm' and content[i] != 'H' and content[i] != 'J' and content[i] != 'K') : (i += 1) {} + if (i < content.len) { + i += 1; + // Check if it's a reset sequence + if (content[seq_start + 2 .. i - 1].len == 1 and content[seq_start + 2] == '0') { + current_ansi = ""; + } else { + current_ansi = content[seq_start..i]; + } + } + continue; + } + + if (col < w) { + const is_transparent = layer.transparent and content[i] == ' ' and current_ansi.len == 0; + if (!is_transparent) { + grid[row * w + col] = .{ + .char = content[i], + .ansi_prefix = current_ansi, + }; + } + col += 1; + } + i += 1; + } + } +}; + +const Cell = struct { + char: u8 = ' ', + ansi_prefix: []const u8 = "", +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig new file mode 100644 index 0000000..70530a4 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig @@ -0,0 +1,41 @@ +//! Layout module entry point. +//! Re-exports layout utilities for convenience. + +pub const measure = @import("measure.zig"); +pub const join = @import("join.zig"); +pub const place = @import("place.zig"); +pub const layer = @import("layer.zig"); +pub const flex = @import("flex.zig"); + +// Re-export common types +pub const VAlign = join.VAlign; +pub const HAlign = join.HAlign; +pub const HPosition = place.HPosition; +pub const VPosition = place.VPosition; + +// Convenience functions + +/// Calculate visible width of text +pub fn width(str: []const u8) usize { + return measure.width(str); +} + +/// Calculate height (line count) of text +pub fn height(str: []const u8) usize { + return measure.height(str); +} + +/// Join strings horizontally with top alignment +pub fn joinHorizontal(allocator: @import("std").mem.Allocator, parts: []const []const u8) ![]const u8 { + return join.horizontal(allocator, .top, parts); +} + +/// Join strings vertically with left alignment +pub fn joinVertical(allocator: @import("std").mem.Allocator, parts: []const []const u8) ![]const u8 { + return join.vertical(allocator, .left, parts); +} + +/// Place content centered in a box +pub fn placeCenter(allocator: @import("std").mem.Allocator, w: usize, h: usize, content: []const u8) ![]const u8 { + return place.place(allocator, w, h, .center, .middle, content); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig new file mode 100644 index 0000000..d71d31d --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig @@ -0,0 +1,279 @@ +//! Text measurement utilities for ANSI-aware width and height calculation. +//! Properly handles ANSI escape sequences and Unicode characters. + +const std = @import("std"); +const Writer = std.Io.Writer; +const unicode = @import("../unicode.zig"); + +/// Calculate the visible width of a string (excluding ANSI escape sequences) +pub fn width(str: []const u8) usize { + var w: usize = 0; + var max_width: usize = 0; + var in_escape = false; + var escape_bracket = false; + + var i: usize = 0; + while (i < str.len) { + const c = str[i]; + + if (c == 0x1b) { + in_escape = true; + escape_bracket = false; + i += 1; + continue; + } + + if (in_escape) { + if (c == '[') { + escape_bracket = true; + } else if (escape_bracket) { + // CSI sequence ends with letter + if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) { + in_escape = false; + escape_bracket = false; + } + } else if (c == ']') { + // OSC sequence - skip until BEL or ST + i += 1; + while (i < str.len and str[i] != 0x07) { + if (str[i] == 0x1b and i + 1 < str.len and str[i + 1] == '\\') { + i += 1; + break; + } + i += 1; + } + in_escape = false; + } else { + // Single-character escape + in_escape = false; + } + i += 1; + continue; + } + + if (c == '\n') { + max_width = @max(max_width, w); + w = 0; + i += 1; + continue; + } + + if (c == '\r' or c == '\t') { + if (c == '\t') { + w += 8 - (w % 8); // Tab stops every 8 characters + } + i += 1; + continue; + } + + // Handle UTF-8 characters + const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; + if (i + byte_len <= str.len) { + const codepoint = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { + w += 1; + i += 1; + continue; + }; + + w += unicode.charWidth(codepoint); + i += byte_len; + } else { + w += 1; + i += 1; + } + } + + return @max(max_width, w); +} + +/// Calculate the height of a string (number of lines) +pub fn height(str: []const u8) usize { + if (str.len == 0) return 0; + + var h: usize = 1; + for (str) |c| { + if (c == '\n') h += 1; + } + return h; +} + +/// Calculate both width and height +pub fn size(str: []const u8) struct { width: usize, height: usize } { + return .{ + .width = width(str), + .height = height(str), + }; +} + +/// Get the display width of a Unicode codepoint using full Unicode tables. +pub fn charWidth(codepoint: u21) usize { + return unicode.charWidth(codepoint); +} + +/// Get the width of a specific line +pub fn lineWidth(str: []const u8, line_num: usize) usize { + var lines = std.mem.splitScalar(u8, str, '\n'); + var current: usize = 0; + + while (lines.next()) |line| { + if (current == line_num) { + return width(line); + } + current += 1; + } + + return 0; +} + +/// Get the maximum line width +pub fn maxLineWidth(str: []const u8) usize { + var max_w: usize = 0; + var lines = std.mem.splitScalar(u8, str, '\n'); + + while (lines.next()) |line| { + max_w = @max(max_w, width(line)); + } + + return max_w; +} + +/// Pad a string to a specific width +pub fn padRight(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { + const current_width = width(str); + if (current_width >= target_width) return try allocator.dupe(u8, str); + + var result: std.array_list.Managed(u8) = .init(allocator); + try result.appendSlice(str); + + for (0..(target_width - current_width)) |_| { + try result.append(' '); + } + + return result.toOwnedSlice(); +} + +/// Pad a string on the left to a specific width +pub fn padLeft(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { + const current_width = width(str); + if (current_width >= target_width) return try allocator.dupe(u8, str); + + var result: std.array_list.Managed(u8) = .init(allocator); + + for (0..(target_width - current_width)) |_| { + try result.append(' '); + } + try result.appendSlice(str); + + return result.toOwnedSlice(); +} + +/// Center a string within a specific width +pub fn center(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { + const current_width = width(str); + if (current_width >= target_width) return try allocator.dupe(u8, str); + + const total_padding = target_width - current_width; + const left_padding = total_padding / 2; + const right_padding = total_padding - left_padding; + + var result: std.array_list.Managed(u8) = .init(allocator); + + for (0..left_padding) |_| { + try result.append(' '); + } + try result.appendSlice(str); + for (0..right_padding) |_| { + try result.append(' '); + } + + return result.toOwnedSlice(); +} + +/// Truncate string to fit within max width, adding ellipsis if needed +pub fn truncate(allocator: std.mem.Allocator, str: []const u8, max_width: usize) ![]const u8 { + if (max_width == 0) return try allocator.dupe(u8, ""); + if (width(str) <= max_width) return try allocator.dupe(u8, str); + + if (max_width <= 3) { + const result = try allocator.alloc(u8, max_width); + @memset(result, '.'); + return result; + } + + var result: std.array_list.Managed(u8) = .init(allocator); + var w: usize = 0; + var i: usize = 0; + var in_escape = false; + + const target = max_width - 3; // Leave room for "..." + + while (i < str.len and w < target) { + const c = str[i]; + + if (c == 0x1b) { + in_escape = true; + const start = i; + i += 1; + // Copy escape sequence + while (i < str.len) { + if (str[i] == '[') { + i += 1; + while (i < str.len and !((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z'))) { + i += 1; + } + if (i < str.len) i += 1; + break; + } else { + i += 1; + break; + } + } + try result.appendSlice(str[start..i]); + in_escape = false; + continue; + } + + // Regular character + const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; + if (i + byte_len <= str.len) { + const codepoint = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { + try result.append(c); + w += 1; + i += 1; + continue; + }; + const cw = unicode.charWidth(codepoint); + // Wide char would exceed target — stop here + if (w + cw > target) break; + try result.appendSlice(str[i..][0..byte_len]); + w += cw; + i += byte_len; + } else { + try result.append(c); + w += 1; + i += 1; + } + } + + try result.appendSlice("..."); + return result.toOwnedSlice(); +} + +test "width calculation" { + const testing = std.testing; + + try testing.expectEqual(@as(usize, 5), width("hello")); + try testing.expectEqual(@as(usize, 5), width("hello\n")); + try testing.expectEqual(@as(usize, 5), width("hello\nworld")); + try testing.expectEqual(@as(usize, 0), width("")); + try testing.expectEqual(@as(usize, 5), width("\x1b[31mhello\x1b[0m")); +} + +test "height calculation" { + const testing = std.testing; + + try testing.expectEqual(@as(usize, 1), height("hello")); + try testing.expectEqual(@as(usize, 2), height("hello\n")); + try testing.expectEqual(@as(usize, 2), height("hello\nworld")); + try testing.expectEqual(@as(usize, 0), height("")); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig new file mode 100644 index 0000000..249e657 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig @@ -0,0 +1,388 @@ +//! Positioning utilities for placing content within a bounding box. +//! Provides 2D positioning with horizontal and vertical alignment. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("measure.zig"); +const unicode = @import("../unicode.zig"); + +/// Horizontal position +pub const HPosition = enum { + left, + center, + right, +}; + +/// Vertical position +pub const VPosition = enum { + top, + middle, + bottom, +}; + +/// Position content within a bounding box +pub fn place( + allocator: std.mem.Allocator, + width: usize, + height: usize, + hpos: HPosition, + vpos: VPosition, + content: []const u8, +) ![]const u8 { + const content_width = measure.maxLineWidth(content); + const content_height = measure.height(content); + + // If content is larger than box, just return it + if (content_width >= width and content_height >= height) { + return try allocator.dupe(u8, content); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Calculate vertical offset + const v_padding = if (height > content_height) height - content_height else 0; + const top_padding: usize = switch (vpos) { + .top => 0, + .middle => v_padding / 2, + .bottom => v_padding, + }; + const bottom_padding = v_padding - top_padding; + + // Calculate horizontal offset + const h_padding = if (width > content_width) width - content_width else 0; + const left_padding: usize = switch (hpos) { + .left => 0, + .center => h_padding / 2, + .right => h_padding, + }; + + // Write top padding + for (0..top_padding) |_| { + for (0..width) |_| { + try writer.writeByte(' '); + } + try writer.writeByte('\n'); + } + + // Write content lines + var lines = std.mem.splitScalar(u8, content, '\n'); + var first_line = true; + while (lines.next()) |line| { + if (!first_line) try writer.writeByte('\n'); + first_line = false; + + // Left padding + for (0..left_padding) |_| { + try writer.writeByte(' '); + } + + // Content + try writer.writeAll(line); + + // Right padding + const line_width = measure.width(line); + const right_pad = if (width > left_padding + line_width) + width - left_padding - line_width + else + 0; + for (0..right_pad) |_| { + try writer.writeByte(' '); + } + } + + // Write bottom padding + for (0..bottom_padding) |_| { + try writer.writeByte('\n'); + for (0..width) |_| { + try writer.writeByte(' '); + } + } + + return result.toOwnedSlice(); +} + +/// Place content at absolute coordinates +pub fn placeAt( + allocator: std.mem.Allocator, + canvas_width: usize, + canvas_height: usize, + x: usize, + y: usize, + content: []const u8, +) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var lines = std.mem.splitScalar(u8, content, '\n'); + var content_lines = std.array_list.Managed([]const u8).init(allocator); + defer content_lines.deinit(); + + while (lines.next()) |line| { + try content_lines.append(line); + } + + for (0..canvas_height) |row| { + if (row > 0) try writer.writeByte('\n'); + + for (0..canvas_width) |col| { + // Check if this position is within the content + if (row >= y and col >= x) { + const content_row = row - y; + const content_col = col - x; + + if (content_row < content_lines.items.len) { + const line = content_lines.items[content_row]; + if (content_col < measure.width(line)) { + // Find the byte position for this display column + var byte_pos: usize = 0; + var current_col: usize = 0; + while (byte_pos < line.len and current_col < content_col) { + const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_pos]) catch 1; + if (byte_pos + byte_len <= line.len) { + const cp = std.unicode.utf8Decode(line[byte_pos..][0..byte_len]) catch { + byte_pos += 1; + current_col += 1; + continue; + }; + current_col += unicode.charWidth(cp); + } + byte_pos += byte_len; + } + + // If we landed inside a wide character, emit space + if (current_col > content_col) { + try writer.writeByte(' '); + continue; + } + + if (byte_pos < line.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_pos]) catch 1; + try writer.writeAll(line[byte_pos..][0..byte_len]); + continue; + } + } + } + } + try writer.writeByte(' '); + } + } + + return result.toOwnedSlice(); +} + +/// Overlay content on top of a base, preserving transparency (spaces in content show base) +pub fn overlay( + allocator: std.mem.Allocator, + base: []const u8, + content: []const u8, + x: usize, + y: usize, +) ![]const u8 { + const base_width = measure.maxLineWidth(base); + const base_height = measure.height(base); + + var base_lines = std.array_list.Managed([]const u8).init(allocator); + defer base_lines.deinit(); + var base_iter = std.mem.splitScalar(u8, base, '\n'); + while (base_iter.next()) |line| { + try base_lines.append(line); + } + + var content_lines = std.array_list.Managed([]const u8).init(allocator); + defer content_lines.deinit(); + var content_iter = std.mem.splitScalar(u8, content, '\n'); + while (content_iter.next()) |line| { + try content_lines.append(line); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + for (0..base_height) |row| { + if (row > 0) try writer.writeByte('\n'); + + const base_line = if (row < base_lines.items.len) base_lines.items[row] else ""; + const content_row = if (row >= y) row - y else base_height; + const content_line = if (content_row < content_lines.items.len) + content_lines.items[content_row] + else + ""; + + for (0..base_width) |col| { + const content_col = if (col >= x) col - x else base_width; + + // Try to get content character + var used_content = false; + if (content_col < measure.width(content_line)) { + // Find byte at display column + var byte_pos: usize = 0; + var current_col: usize = 0; + while (byte_pos < content_line.len and current_col < content_col) { + const byte_len = std.unicode.utf8ByteSequenceLength(content_line[byte_pos]) catch 1; + if (byte_pos + byte_len <= content_line.len) { + const cp = std.unicode.utf8Decode(content_line[byte_pos..][0..byte_len]) catch { + byte_pos += 1; + current_col += 1; + continue; + }; + current_col += unicode.charWidth(cp); + } + byte_pos += byte_len; + } + + // If we landed inside a wide character, emit space + if (current_col > content_col) { + try writer.writeByte(' '); + used_content = true; + } else if (byte_pos < content_line.len and content_line[byte_pos] != ' ') { + const byte_len = std.unicode.utf8ByteSequenceLength(content_line[byte_pos]) catch 1; + try writer.writeAll(content_line[byte_pos..][0..byte_len]); + used_content = true; + } + } + + if (!used_content) { + // Use base character + if (col < measure.width(base_line)) { + var byte_pos: usize = 0; + var current_col: usize = 0; + while (byte_pos < base_line.len and current_col < col) { + const byte_len = std.unicode.utf8ByteSequenceLength(base_line[byte_pos]) catch 1; + if (byte_pos + byte_len <= base_line.len) { + const cp = std.unicode.utf8Decode(base_line[byte_pos..][0..byte_len]) catch { + byte_pos += 1; + current_col += 1; + continue; + }; + current_col += unicode.charWidth(cp); + } + byte_pos += byte_len; + } + + if (current_col > col) { + try writer.writeByte(' '); + } else if (byte_pos < base_line.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(base_line[byte_pos]) catch 1; + try writer.writeAll(base_line[byte_pos..][0..byte_len]); + } else { + try writer.writeByte(' '); + } + } else { + try writer.writeByte(' '); + } + } + } + } + + return result.toOwnedSlice(); +} + +/// Place content with horizontal positioning only (height inferred from content) +pub fn placeHorizontal( + allocator: std.mem.Allocator, + width: usize, + hpos: HPosition, + content: []const u8, +) ![]const u8 { + const content_height = measure.height(content); + return place(allocator, width, content_height, hpos, .top, content); +} + +/// Place content with vertical positioning only (width inferred from content) +pub fn placeVertical( + allocator: std.mem.Allocator, + height: usize, + vpos: VPosition, + content: []const u8, +) ![]const u8 { + const content_width = measure.maxLineWidth(content); + return place(allocator, content_width, height, .left, vpos, content); +} + +/// Position content using float coordinates (0.0 = left/top, 0.5 = center, 1.0 = right/bottom) +pub fn placeFloat( + allocator: std.mem.Allocator, + width: usize, + height: usize, + hpos: f32, + vpos: f32, + content: []const u8, +) ![]const u8 { + const content_width = measure.maxLineWidth(content); + const content_height = measure.height(content); + + // If content is larger than box, just return it + if (content_width >= width and content_height >= height) { + return try allocator.dupe(u8, content); + } + + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + // Calculate offsets from float positions + const h_space = if (width > content_width) width - content_width else 0; + const v_space = if (height > content_height) height - content_height else 0; + + const clamped_h = @max(0.0, @min(1.0, hpos)); + const clamped_v = @max(0.0, @min(1.0, vpos)); + + const left_padding: usize = @intFromFloat(@as(f32, @floatFromInt(h_space)) * clamped_h); + const top_padding: usize = @intFromFloat(@as(f32, @floatFromInt(v_space)) * clamped_v); + const bottom_padding = v_space - top_padding; + + // Write top padding + for (0..top_padding) |_| { + for (0..width) |_| { + try writer.writeByte(' '); + } + try writer.writeByte('\n'); + } + + // Write content lines + var lines = std.mem.splitScalar(u8, content, '\n'); + var first_line = true; + while (lines.next()) |line| { + if (!first_line) try writer.writeByte('\n'); + first_line = false; + + // Left padding + for (0..left_padding) |_| { + try writer.writeByte(' '); + } + + // Content + try writer.writeAll(line); + + // Right padding + const line_width = measure.width(line); + const right_pad = if (width > left_padding + line_width) + width - left_padding - line_width + else + 0; + for (0..right_pad) |_| { + try writer.writeByte(' '); + } + } + + // Write bottom padding + for (0..bottom_padding) |_| { + try writer.writeByte('\n'); + for (0..width) |_| { + try writer.writeByte(' '); + } + } + + return result.toOwnedSlice(); +} + +test "place center" { + const testing = std.testing; + const alloc = testing.allocator; + + const result = try place(alloc, 5, 3, .center, .middle, "X"); + defer alloc.free(result); + + // Expected: 5x3 grid with X in center + try testing.expect(result.len > 0); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig new file mode 100644 index 0000000..7c96f94 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig @@ -0,0 +1,386 @@ +//! ZigZag - A TUI library for Zig inspired by Bubble Tea and Lipgloss +//! +//! ZigZag provides a framework for building terminal user interfaces using +//! the Elm architecture (Model-Update-View pattern). +//! +//! ## Quick Start +//! +//! ```zig +//! const std = @import("std"); +//! const zz = @import("zigzag"); +//! +//! const Model = struct { +//! count: i32, +//! +//! pub const Msg = union(enum) { +//! key: zz.KeyEvent, +//! }; +//! +//! pub fn init(self: *Model, _: *zz.Context) zz.Cmd(Msg) { +//! self.* = .{ .count = 0 }; +//! return .none; +//! } +//! +//! pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { +//! switch (msg) { +//! .key => |k| switch (k.key) { +//! .char => |c| if (c == 'q') return .quit, +//! .up => self.count += 1, +//! .down => self.count -= 1, +//! else => {}, +//! }, +//! } +//! return .none; +//! } +//! +//! pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { +//! return std.fmt.allocPrint(ctx.allocator, "Count: {d}\n\nPress q to quit", .{self.count}) catch "Error"; +//! } +//! }; +//! +//! pub fn main(init: std.process.Init) !void { +//! var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); +//! defer program.deinit(); +//! try program.run(); +//! } +//! ``` + +const std = @import("std"); + +// Core +pub const program = @import("core/program.zig"); +pub const Program = program.Program; +pub const Cmd = program.Cmd; +pub const command = @import("core/command.zig"); +pub const async_task = @import("core/async_task.zig"); +pub const AsyncRunner = async_task.AsyncRunner; +pub const SubProgram = @import("core/sub_program.zig").SubProgram; +pub const screen_stack = @import("core/screen_stack.zig"); +pub const ScreenStack = screen_stack.ScreenStack; +pub const Screen = screen_stack.Screen; +pub const ScreenAction = screen_stack.Action; +pub const ScreenHandleResult = screen_stack.HandleResult; +pub const Context = @import("core/context.zig").Context; +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 dev_console = @import("core/dev_console.zig"); +pub const DevConsole = dev_console.DevConsole; +pub const DevConsoleLevel = dev_console.Level; +pub const DevConsoleSink = dev_console.SinkConfig; +pub const fuzzy = @import("core/fuzzy.zig"); +pub const action = @import("core/action.zig"); +pub const Action = action.Action; +pub const ActionRegistry = action.ActionRegistry; +pub const ActionFooter = action.Footer; +pub const animation = @import("core/animation.zig"); +pub const Tween = animation.Tween; +pub const Easing = animation.Easing; +pub const tweenColor = animation.tweenColor; +pub const lerp = animation.lerp; + +// Terminal +pub const terminal = @import("terminal/terminal.zig"); +pub const Terminal = terminal.Terminal; +pub const ansi = terminal.ansi; +pub const screen = terminal.screen; + +// Input +pub const input = struct { + pub const keyboard = @import("input/keyboard.zig"); + pub const mouse = @import("input/mouse.zig"); + pub const keys = @import("input/keys.zig"); +}; +pub const Key = input.keys.Key; +pub const KeyEvent = input.keys.KeyEvent; +pub const Modifiers = input.keys.Modifiers; +pub const MouseEvent = input.mouse.MouseEvent; +pub const MouseButton = input.mouse.Button; +pub const MouseEventType = input.mouse.EventType; +pub const hitbox = @import("input/hitbox.zig"); +pub const HitBox = hitbox.HitBox; +pub const MouseState = hitbox.MouseState; +pub const MouseInteraction = hitbox.Interaction; + +// Style +pub const style = @import("style/style.zig"); +pub const Style = style.Style; +pub const color = @import("style/color.zig"); +pub const Color = color.Color; +pub const border = @import("style/border.zig"); +pub const Border = border.BorderChars; +pub const theme = @import("style/theme.zig"); +pub const Theme = theme.Theme; +pub const Palette = theme.Palette; +pub const AdaptivePalette = theme.AdaptivePalette; +pub const ThemeManager = theme.ThemeManager; + +// Layout +pub const layout = @import("layout/layout.zig"); +pub const measure = @import("layout/measure.zig"); +pub const join = @import("layout/join.zig"); +pub const place = @import("layout/place.zig"); +pub const flex = @import("layout/flex.zig"); +pub const Flex = flex; +pub const FlexConstraint = flex.Constraint; +pub const FlexItem = flex.Item; +pub const FlexOptions = flex.FlexOptions; +pub const FlexRect = flex.Rect; + +// Accessibility +pub const accessibility = @import("accessibility.zig"); +pub const a11y = accessibility; +pub const ContrastLevel = accessibility.ContrastLevel; +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; + pub const TextArea = @import("components/text_area.zig").TextArea; + pub const List = @import("components/list.zig").List; + pub const Viewport = @import("components/viewport.zig").Viewport; + pub const Progress = @import("components/progress.zig").Progress; + pub const Spinner = @import("components/spinner.zig").Spinner; + pub const Table = @import("components/table.zig").Table; + pub const data_table = @import("components/data_table.zig"); + pub const DataTable = data_table.DataTable; + pub const DataColumn = data_table.Column; + pub const DataAlign = data_table.Align; + pub const Paginator = @import("components/paginator.zig").Paginator; + pub const Help = @import("components/help.zig").Help; + pub const Timer = @import("components/timer.zig").Timer; + pub const FilePicker = @import("components/file_picker.zig").FilePicker; + pub const Tree = @import("components/tree.zig").Tree; + pub const StyledList = @import("components/styled_list.zig").StyledList; + pub const Sparkline = @import("components/sparkline.zig").Sparkline; + pub const charting = @import("components/charting.zig"); + pub const canvas = @import("components/canvas.zig"); + pub const Canvas = canvas.Canvas; + pub const braille_canvas = @import("components/braille_canvas.zig"); + pub const BrailleCanvas = braille_canvas.BrailleCanvas; + pub const chart = @import("components/chart.zig"); + pub const Chart = chart.Chart; + pub const BarChart = @import("components/bar_chart.zig").BarChart; + pub const notification = @import("components/notification.zig"); + pub const Notification = notification.Notification; + pub const Confirm = @import("components/confirm.zig").Confirm; + pub const modal = @import("components/modal.zig"); + pub const Modal = modal.Modal; + pub const tooltip = @import("components/tooltip.zig"); + pub const Tooltip = tooltip.Tooltip; + pub const focus = @import("components/focus.zig"); + pub const tab_group = @import("components/tab_group.zig"); + pub const TabGroup = tab_group.TabGroup; + pub const slider = @import("components/slider.zig"); + pub const Slider = slider.Slider; + pub const SliderStyle = slider.SliderStyle; + pub const MenuBar = @import("components/menu_bar.zig").MenuBar; + pub const checkbox = @import("components/checkbox.zig"); + pub const Checkbox = checkbox.Checkbox; + 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; + pub const diff_view = @import("components/diff_view.zig"); + pub const DiffView = diff_view.DiffView; + pub const code_view = @import("components/code_view.zig"); + pub const CodeView = code_view.CodeView; + pub const sortable_table = @import("components/sortable_table.zig"); + pub const SortableTable = sortable_table.SortableTable; + pub const virtual_list = @import("components/virtual_list.zig"); + pub const VirtualList = virtual_list.VirtualList; + pub const Calendar = @import("components/calendar.zig").Calendar; + 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; + 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; + 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; + 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; + pub const rich_log = @import("components/rich_log.zig"); + pub const RichLog = rich_log.RichLog; + pub const RichLogLevel = rich_log.Level; + pub const RichLogEntry = rich_log.Entry; +}; + +// Re-export commonly used components at top level +pub const TextInput = components.TextInput; +pub const TextArea = components.TextArea; +pub const List = components.List; +pub const Viewport = components.Viewport; +pub const Progress = components.Progress; +pub const Spinner = components.Spinner; +pub const Table = components.Table; +pub const DataTable = components.DataTable; +pub const DataColumn = components.DataColumn; +pub const Tree = components.Tree; +pub const StyledList = components.StyledList; +pub const Sparkline = components.Sparkline; +pub const Canvas = components.Canvas; +pub const BrailleCanvas = components.BrailleCanvas; +pub const Chart = components.Chart; +pub const BarChart = components.BarChart; +pub const Notification = components.Notification; +pub const Confirm = components.Confirm; +pub const Modal = components.Modal; +pub const Tooltip = components.Tooltip; +pub const TabGroup = components.TabGroup; +pub const Slider = components.Slider; +pub const SliderStyle = components.SliderStyle; +pub const MenuBar = components.MenuBar; +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; +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; +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; +pub const SplitPane = components.SplitPane; +pub const CommandPalette = components.CommandPalette; +pub const RichLog = components.RichLog; +pub const RichLogLevel = components.RichLogLevel; +pub const Command = components.Command; + +// Focus management +pub const FocusGroup = components.focus.FocusGroup; +pub const FocusStyle = components.focus.FocusStyle; +pub const KeyBind = components.focus.KeyBind; +pub const isFocusable = components.focus.isFocusable; +pub const TabChange = components.tab_group.Change; +pub const TabChangeReason = components.tab_group.ChangeReason; +pub const TabKeyResult = components.tab_group.KeyResult; +pub const TabKeyBind = components.tab_group.KeyBind; + +// Keybinding management +pub const keybinding = @import("components/keybinding.zig"); +pub const KeyBinding = keybinding.KeyBinding; +pub const KeyMap = keybinding.KeyMap; + +// Utility functions +pub fn joinHorizontal(allocator: std.mem.Allocator, parts: []const []const u8) ![]const u8 { + return join.horizontal(allocator, .top, parts); +} + +pub fn joinVertical(allocator: std.mem.Allocator, parts: []const []const u8) ![]const u8 { + return join.vertical(allocator, .left, parts); +} + +pub fn width(str: []const u8) usize { + return measure.width(str); +} + +pub fn height(str: []const u8) usize { + return measure.height(str); +} + +pub fn placeHorizontal(allocator: std.mem.Allocator, w: usize, hpos: place.HPosition, content: []const u8) ![]const u8 { + return place.placeHorizontal(allocator, w, hpos, content); +} + +pub fn placeVertical(allocator: std.mem.Allocator, h: usize, vpos: place.VPosition, content: []const u8) ![]const u8 { + return place.placeVertical(allocator, h, vpos, content); +} + +pub fn placeFloat(allocator: std.mem.Allocator, w: usize, h: usize, hpos: f32, vpos: f32, content: []const u8) ![]const u8 { + return place.placeFloat(allocator, w, h, hpos, vpos, content); +} + +// Image types +pub const ImageFile = command.ImageFile; +pub const ImageData = command.ImageData; +pub const ImagePlacement = command.ImagePlacement; +pub const ImageProtocol = command.ImageProtocol; +pub const ImageFormat = command.ImageFormat; +pub const ImageSource = command.ImageSource; +pub const CacheImage = command.CacheImage; +pub const PlaceCachedImage = command.PlaceCachedImage; +pub const DeleteImage = command.DeleteImage; +pub const ImageCapabilities = terminal.ImageCapabilities; +pub const Osc52Target = terminal.Osc52Target; +pub const Osc52Passthrough = terminal.Osc52Passthrough; +pub const Osc52Config = terminal.Osc52Config; +pub const Osc52WriteOptions = terminal.Osc52WriteOptions; +pub const Osc52ReadOptions = terminal.Osc52ReadOptions; +pub const OscTerminator = terminal.ansi.OscTerminator; + +// Color utilities +pub const ColorProfile = color.ColorProfile; +pub const AdaptiveColor = color.AdaptiveColor; +pub const CompleteColor = color.CompleteColor; +pub const CompleteAdaptiveColor = color.CompleteAdaptiveColor; + +// Overflow +pub const Overflow = style.Overflow; + +// Style utilities +pub const StyleRange = style.StyleRange; +pub const renderWithRanges = style.renderWithRanges; +pub const renderWithHighlights = style.renderWithHighlights; +pub const transforms = style.transforms; +pub const compress = @import("style/compress.zig"); +pub const StyleState = compress.StyleState; +pub const compressAnsi = compress.compressAnsi; + +// Progress helpers +pub const interpolateColor = @import("components/progress.zig").interpolateColor; +pub const PlotPoint = components.charting.Point; +pub const PlotRange = components.charting.DataRange; +pub const PlotMarker = components.charting.Marker; +pub const GraphType = components.chart.GraphType; +pub const ChartInterpolation = components.chart.Interpolation; +pub const Axis = components.chart.Axis; +pub const AxisLabel = components.chart.AxisLabel; +pub const ChartDataset = components.chart.Dataset; +pub const LegendPosition = components.chart.LegendPosition; +pub const Bar = @import("components/bar_chart.zig").Bar; +pub const ChartOrientation = components.charting.Orientation; +pub const SparkSummary = @import("components/sparkline.zig").Summary; + +test { + std.testing.refAllDecls(@This()); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig new file mode 100644 index 0000000..e55c292 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig @@ -0,0 +1,303 @@ +//! Border styles for terminal UI elements. +//! Provides various border character sets and drawing functions. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("../layout/measure.zig"); + +/// Border character set +pub const BorderChars = struct { + top_left: []const u8, + top_right: []const u8, + bottom_left: []const u8, + bottom_right: []const u8, + horizontal: []const u8, + vertical: []const u8, + middle_left: []const u8, + middle_right: []const u8, + middle_top: []const u8, + middle_bottom: []const u8, + cross: []const u8, + + /// No border + pub const none = BorderChars{ + .top_left = "", + .top_right = "", + .bottom_left = "", + .bottom_right = "", + .horizontal = "", + .vertical = "", + .middle_left = "", + .middle_right = "", + .middle_top = "", + .middle_bottom = "", + .cross = "", + }; + + /// Normal single-line border + pub const normal = BorderChars{ + .top_left = "┌", + .top_right = "┐", + .bottom_left = "└", + .bottom_right = "┘", + .horizontal = "─", + .vertical = "│", + .middle_left = "├", + .middle_right = "┤", + .middle_top = "┬", + .middle_bottom = "┴", + .cross = "┼", + }; + + /// Rounded corners + pub const rounded = BorderChars{ + .top_left = "╭", + .top_right = "╮", + .bottom_left = "╰", + .bottom_right = "╯", + .horizontal = "─", + .vertical = "│", + .middle_left = "├", + .middle_right = "┤", + .middle_top = "┬", + .middle_bottom = "┴", + .cross = "┼", + }; + + /// Double-line border + pub const double = BorderChars{ + .top_left = "╔", + .top_right = "╗", + .bottom_left = "╚", + .bottom_right = "╝", + .horizontal = "═", + .vertical = "║", + .middle_left = "╠", + .middle_right = "╣", + .middle_top = "╦", + .middle_bottom = "╩", + .cross = "╬", + }; + + /// Thick/bold border + pub const thick = BorderChars{ + .top_left = "┏", + .top_right = "┓", + .bottom_left = "┗", + .bottom_right = "┛", + .horizontal = "━", + .vertical = "┃", + .middle_left = "┣", + .middle_right = "┫", + .middle_top = "┳", + .middle_bottom = "┻", + .cross = "╋", + }; + + /// ASCII-only border (compatible with all terminals) + pub const ascii = BorderChars{ + .top_left = "+", + .top_right = "+", + .bottom_left = "+", + .bottom_right = "+", + .horizontal = "-", + .vertical = "|", + .middle_left = "+", + .middle_right = "+", + .middle_top = "+", + .middle_bottom = "+", + .cross = "+", + }; + + /// Block border using full block characters + pub const block = BorderChars{ + .top_left = "█", + .top_right = "█", + .bottom_left = "█", + .bottom_right = "█", + .horizontal = "█", + .vertical = "█", + .middle_left = "█", + .middle_right = "█", + .middle_top = "█", + .middle_bottom = "█", + .cross = "█", + }; + + /// Hidden border (uses spaces) + pub const hidden = BorderChars{ + .top_left = " ", + .top_right = " ", + .bottom_left = " ", + .bottom_right = " ", + .horizontal = " ", + .vertical = " ", + .middle_left = " ", + .middle_right = " ", + .middle_top = " ", + .middle_bottom = " ", + .cross = " ", + }; + + /// Dashed border + pub const dashed = BorderChars{ + .top_left = "┌", + .top_right = "┐", + .bottom_left = "└", + .bottom_right = "┘", + .horizontal = "╌", + .vertical = "╎", + .middle_left = "├", + .middle_right = "┤", + .middle_top = "┬", + .middle_bottom = "┴", + .cross = "┼", + }; + + /// Dotted border + pub const dotted = BorderChars{ + .top_left = "┌", + .top_right = "┐", + .bottom_left = "└", + .bottom_right = "┘", + .horizontal = "┈", + .vertical = "┊", + .middle_left = "├", + .middle_right = "┤", + .middle_top = "┬", + .middle_bottom = "┴", + .cross = "┼", + }; + + /// Inner half block border (uses inner half-block characters) + pub const inner_half_block = BorderChars{ + .top_left = "▗", + .top_right = "▖", + .bottom_left = "▝", + .bottom_right = "▘", + .horizontal = "▄", + .vertical = "▐", + .middle_left = "▐", + .middle_right = "▌", + .middle_top = "▄", + .middle_bottom = "▀", + .cross = "█", + }; + + /// Outer half block border (uses outer half-block characters) + pub const outer_half_block = BorderChars{ + .top_left = "▛", + .top_right = "▜", + .bottom_left = "▙", + .bottom_right = "▟", + .horizontal = "▀", + .vertical = "▌", + .middle_left = "▌", + .middle_right = "▐", + .middle_top = "▀", + .middle_bottom = "▄", + .cross = "█", + }; + + /// Markdown-style border (uses pipe and dashes) + pub const markdown = BorderChars{ + .top_left = "|", + .top_right = "|", + .bottom_left = "|", + .bottom_right = "|", + .horizontal = "-", + .vertical = "|", + .middle_left = "|", + .middle_right = "|", + .middle_top = "|", + .middle_bottom = "|", + .cross = "|", + }; +}; + +/// Sides specification for borders +pub const Sides = struct { + top: bool = true, + right: bool = true, + bottom: bool = true, + left: bool = true, + + pub const all = Sides{}; + pub const horizontal_only = Sides{ .left = false, .right = false }; + pub const vertical_only = Sides{ .top = false, .bottom = false }; + pub const top_only = Sides{ .right = false, .bottom = false, .left = false }; + pub const bottom_only = Sides{ .top = false, .right = false, .left = false }; + pub const left_only = Sides{ .top = false, .right = false, .bottom = false }; + pub const right_only = Sides{ .top = false, .bottom = false, .left = false }; + pub const none = Sides{ .top = false, .right = false, .bottom = false, .left = false }; +}; + +/// Draw a border around content +pub fn drawBorder( + allocator: std.mem.Allocator, + content: []const u8, + chars: BorderChars, + sides: Sides, + width: usize, + height: usize, +) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + const inner_width = if (sides.left and sides.right) width -| 2 else if (sides.left or sides.right) width -| 1 else width; + + // Top border + if (sides.top) { + if (sides.left) try writer.writeAll(chars.top_left); + for (0..inner_width) |_| { + try writer.writeAll(chars.horizontal); + } + if (sides.right) try writer.writeAll(chars.top_right); + try writer.writeByte('\n'); + } + + // Content lines with side borders + var lines = std.mem.splitScalar(u8, content, '\n'); + var line_count: usize = 0; + while (lines.next()) |line| : (line_count += 1) { + if (sides.left) try writer.writeAll(chars.vertical); + + // Write the line, padding to inner_width + const visible_width = visibleWidth(line); + try writer.writeAll(line); + if (visible_width < inner_width) { + for (0..(inner_width - visible_width)) |_| { + try writer.writeByte(' '); + } + } + + if (sides.right) try writer.writeAll(chars.vertical); + try writer.writeByte('\n'); + } + + // Pad remaining lines if needed + while (line_count < height -| (if (sides.top) @as(usize, 1) else 0) -| (if (sides.bottom) @as(usize, 1) else 0)) : (line_count += 1) { + if (sides.left) try writer.writeAll(chars.vertical); + for (0..inner_width) |_| { + try writer.writeByte(' '); + } + if (sides.right) try writer.writeAll(chars.vertical); + try writer.writeByte('\n'); + } + + // Bottom border + if (sides.bottom) { + if (sides.left) try writer.writeAll(chars.bottom_left); + for (0..inner_width) |_| { + try writer.writeAll(chars.horizontal); + } + if (sides.right) try writer.writeAll(chars.bottom_right); + } + + return result.toOwnedSlice(); +} + +/// Calculate visible width (excluding ANSI sequences), with proper Unicode width. +fn visibleWidth(str: []const u8) usize { + return measure.width(str); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig new file mode 100644 index 0000000..5ad9eb5 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig @@ -0,0 +1,310 @@ +//! Color types for terminal styling. +//! Supports ANSI 16, 256, and TrueColor (24-bit) colors. + +const std = @import("std"); +const Writer = std.Io.Writer; +const builtin = @import("builtin"); +const ansi = @import("../terminal/ansi.zig"); + +/// Color representation supporting multiple color modes +pub const Color = union(enum) { + /// No color (use terminal default) + none, + + /// Basic ANSI colors (0-15) + ansi: AnsiColor, + + /// 256-color palette (0-255) + ansi256: u8, + + /// True color (24-bit RGB) + rgb: RGB, + + pub const RGB = struct { + r: u8, + g: u8, + b: u8, + }; + + // Basic ANSI colors + pub const black: Color = .{ .ansi = .black }; + pub const red: Color = .{ .ansi = .red }; + pub const green: Color = .{ .ansi = .green }; + pub const yellow: Color = .{ .ansi = .yellow }; + pub const blue: Color = .{ .ansi = .blue }; + pub const magenta: Color = .{ .ansi = .magenta }; + pub const cyan: Color = .{ .ansi = .cyan }; + pub const white: Color = .{ .ansi = .white }; + + // Bright ANSI colors + pub const brightBlack: Color = .{ .ansi = .bright_black }; + pub const brightRed: Color = .{ .ansi = .bright_red }; + pub const brightGreen: Color = .{ .ansi = .bright_green }; + pub const brightYellow: Color = .{ .ansi = .bright_yellow }; + pub const brightBlue: Color = .{ .ansi = .bright_blue }; + pub const brightMagenta: Color = .{ .ansi = .bright_magenta }; + pub const brightCyan: Color = .{ .ansi = .bright_cyan }; + pub const brightWhite: Color = .{ .ansi = .bright_white }; + + /// Create a color from RGB values + pub fn fromRgb(r: u8, g: u8, b: u8) Color { + return .{ .rgb = .{ .r = r, .g = g, .b = b } }; + } + + /// Create a color from a hex string (e.g., "#FF5733" or "FF5733") + pub fn hex(str: []const u8) Color { + const s = if (str.len > 0 and str[0] == '#') str[1..] else str; + + if (s.len != 6) return .none; + + const r = std.fmt.parseInt(u8, s[0..2], 16) catch return .none; + const g = std.fmt.parseInt(u8, s[2..4], 16) catch return .none; + const b = std.fmt.parseInt(u8, s[4..6], 16) catch return .none; + + return .{ .rgb = .{ .r = r, .g = g, .b = b } }; + } + + /// Create a color from the 256-color palette + pub fn color256(n: u8) Color { + return .{ .ansi256 = n }; + } + + /// Create a grayscale color (0-23, where 0 is dark and 23 is light) + pub fn gray(level: u8) Color { + if (level > 23) return .{ .ansi256 = 255 }; + return .{ .ansi256 = 232 + level }; + } + + /// Check if this is a "no color" value + pub fn isNone(self: Color) bool { + return self == .none; + } + + /// Convert to RGB (approximating ANSI colors) + pub fn toRgb(self: Color) ?RGB { + return switch (self) { + .none => null, + .rgb => |c| c, + .ansi => |c| c.toRgb(), + .ansi256 => |n| ansi256ToRgb(n), + }; + } + + /// Write foreground color ANSI sequence + pub fn writeFg(self: Color, writer: *Writer) !void { + switch (self) { + .none => {}, + .ansi => |c| try writer.print(ansi.CSI ++ "{d}m", .{c.fgCode()}), + .ansi256 => |n| try ansi.fg256(writer, n), + .rgb => |c| try ansi.fgRgb(writer, c.r, c.g, c.b), + } + } + + /// Write background color ANSI sequence + pub fn writeBg(self: Color, writer: *Writer) !void { + switch (self) { + .none => {}, + .ansi => |c| try writer.print(ansi.CSI ++ "{d}m", .{c.bgCode()}), + .ansi256 => |n| try ansi.bg256(writer, n), + .rgb => |c| try ansi.bgRgb(writer, c.r, c.g, c.b), + } + } + + /// Calculate contrast ratio with another color + pub fn contrastRatio(self: Color, other: Color) f32 { + const rgb1 = self.toRgb() orelse return 1.0; + const rgb2 = other.toRgb() orelse return 1.0; + + const l1 = relativeLuminance(rgb1); + const l2 = relativeLuminance(rgb2); + + const lighter = @max(l1, l2); + const darker = @min(l1, l2); + + return (lighter + 0.05) / (darker + 0.05); + } + + fn relativeLuminance(c: RGB) f32 { + const r = gammaCorrect(@as(f32, @floatFromInt(c.r)) / 255.0); + const g = gammaCorrect(@as(f32, @floatFromInt(c.g)) / 255.0); + const b = gammaCorrect(@as(f32, @floatFromInt(c.b)) / 255.0); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + } + + fn gammaCorrect(v: f32) f32 { + return if (v <= 0.03928) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4); + } +}; + +/// Basic ANSI colors +pub const AnsiColor = enum(u8) { + black = 0, + red = 1, + green = 2, + yellow = 3, + blue = 4, + magenta = 5, + cyan = 6, + white = 7, + bright_black = 8, + bright_red = 9, + bright_green = 10, + bright_yellow = 11, + bright_blue = 12, + bright_magenta = 13, + bright_cyan = 14, + bright_white = 15, + + pub fn fgCode(self: AnsiColor) u8 { + const base: u8 = @intFromEnum(self); + return if (base < 8) 30 + base else 90 + base - 8; + } + + pub fn bgCode(self: AnsiColor) u8 { + const base: u8 = @intFromEnum(self); + return if (base < 8) 40 + base else 100 + base - 8; + } + + pub fn toRgb(self: AnsiColor) Color.RGB { + return switch (self) { + .black => .{ .r = 0, .g = 0, .b = 0 }, + .red => .{ .r = 128, .g = 0, .b = 0 }, + .green => .{ .r = 0, .g = 128, .b = 0 }, + .yellow => .{ .r = 128, .g = 128, .b = 0 }, + .blue => .{ .r = 0, .g = 0, .b = 128 }, + .magenta => .{ .r = 128, .g = 0, .b = 128 }, + .cyan => .{ .r = 0, .g = 128, .b = 128 }, + .white => .{ .r = 192, .g = 192, .b = 192 }, + .bright_black => .{ .r = 128, .g = 128, .b = 128 }, + .bright_red => .{ .r = 255, .g = 0, .b = 0 }, + .bright_green => .{ .r = 0, .g = 255, .b = 0 }, + .bright_yellow => .{ .r = 255, .g = 255, .b = 0 }, + .bright_blue => .{ .r = 0, .g = 0, .b = 255 }, + .bright_magenta => .{ .r = 255, .g = 0, .b = 255 }, + .bright_cyan => .{ .r = 0, .g = 255, .b = 255 }, + .bright_white => .{ .r = 255, .g = 255, .b = 255 }, + }; + } +}; + +/// Convert 256-color index to RGB +fn ansi256ToRgb(n: u8) Color.RGB { + if (n < 16) { + // Standard colors + return @as(AnsiColor, @enumFromInt(n)).toRgb(); + } else if (n < 232) { + // 6x6x6 color cube + const idx = n - 16; + const r: u8 = @intCast((idx / 36) % 6); + const g: u8 = @intCast((idx / 6) % 6); + const b: u8 = @intCast(idx % 6); + return .{ + .r = if (r == 0) 0 else r * 40 + 55, + .g = if (g == 0) 0 else g * 40 + 55, + .b = if (b == 0) 0 else b * 40 + 55, + }; + } else { + // Grayscale + const gray: u8 = (n - 232) * 10 + 8; + return .{ .r = gray, .g = gray, .b = gray }; + } +} + +/// Adaptive color that changes based on terminal capabilities +pub const AdaptiveColor = struct { + /// Color for terminals with true color support + true_color: Color, + /// Fallback for 256-color terminals + color_256: Color, + /// Fallback for basic 16-color terminals + ansi: Color, + + pub fn resolve(self: AdaptiveColor, supports_true_color: bool, supports_256: bool) Color { + if (supports_true_color) return self.true_color; + if (supports_256) return self.color_256; + return self.ansi; + } +}; + +/// Complete color for foreground and background +pub const CompleteColor = struct { + fg: Color = .none, + bg: Color = .none, +}; + +/// Complete adaptive color that changes based on terminal background +pub const CompleteAdaptiveColor = struct { + light: CompleteColor, + dark: CompleteColor, + + pub fn resolve(self: CompleteAdaptiveColor, is_dark: bool) CompleteColor { + return if (is_dark) self.dark else self.light; + } +}; + +/// Color profile representing terminal color capabilities +pub const ColorProfile = enum { + ascii, + ansi, + ansi256, + true_color, + + /// Detect terminal color profile from the supplied environment. + pub fn detect(environ_map: *const std.process.Environ.Map) ColorProfile { + if (comptime builtin.os.tag == .windows) { + // Windows Terminal supports true color VT sequences + return .true_color; + } + + if (environ_map.get("NO_COLOR")) |_| { + return .ascii; + } + + if (environ_map.get("COLORTERM")) |ct| { + if (std.mem.eql(u8, ct, "truecolor") or std.mem.eql(u8, ct, "24bit")) { + return .true_color; + } + } + + if (environ_map.get("TERM")) |term| { + if (std.mem.indexOf(u8, term, "256color") != null) { + return .ansi256; + } + } + + return .ansi; + } + + /// Check if this profile supports true color + pub fn supportsTrueColor(self: ColorProfile) bool { + return self == .true_color; + } + + /// Check if this profile supports 256 colors + pub fn supports256(self: ColorProfile) bool { + return self == .true_color or self == .ansi256; + } + + /// Check if this profile supports any color + pub fn supportsColor(self: ColorProfile) bool { + return self != .ascii; + } +}; + +/// Detect if terminal has a dark background using the supplied environment. +pub fn hasDarkBackground(environ_map: *const std.process.Environ.Map) bool { + if (comptime builtin.os.tag == .windows) { + return true; + } + + if (environ_map.get("COLORFGBG")) |val| { + // Format: "foreground;background" + if (std.mem.lastIndexOfScalar(u8, val, ';')) |idx| { + const bg_str = val[idx + 1 ..]; + const bg_num = std.fmt.parseInt(u8, bg_str, 10) catch return true; + // Low numbers typically mean dark background + return bg_num < 8; + } + } + return true; // Default to dark +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig new file mode 100644 index 0000000..7a3ec97 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig @@ -0,0 +1,156 @@ +//! ANSI output compression utilities. +//! Reduces ANSI escape sequence overhead by tracking terminal state and emitting only diffs. + +const std = @import("std"); +const Writer = std.Io.Writer; +const ansi = @import("../terminal/ansi.zig"); + +/// Tracks the current terminal style state for efficient transitions +pub const StyleState = struct { + bold: bool = false, + dim: bool = false, + italic: bool = false, + underline: bool = false, + blink: bool = false, + reverse: bool = false, + strikethrough: bool = false, + fg_set: bool = false, + bg_set: bool = false, + fg_r: u8 = 0, + fg_g: u8 = 0, + fg_b: u8 = 0, + bg_r: u8 = 0, + bg_g: u8 = 0, + bg_b: u8 = 0, + fg_ansi: ?u8 = null, + bg_ansi: ?u8 = null, + + /// Reset to default state + pub fn reset(self: *StyleState) void { + self.* = .{}; + } + + /// Emit only the ANSI escape sequences needed to transition to the target state + pub fn transitionTo(self: *StyleState, writer: *Writer, target: StyleState) !void { + // If target is fully default, just emit reset + if (!target.bold and !target.dim and !target.italic and !target.underline and + !target.blink and !target.reverse and !target.strikethrough and + !target.fg_set and !target.bg_set) + { + if (self.bold or self.dim or self.italic or self.underline or + self.blink or self.reverse or self.strikethrough or + self.fg_set or self.bg_set) + { + try writer.writeAll(ansi.reset); + self.reset(); + } + return; + } + + // Check if we need a full reset first (any attribute going from on to off) + const needs_reset = (self.bold and !target.bold) or + (self.dim and !target.dim) or + (self.italic and !target.italic) or + (self.underline and !target.underline) or + (self.blink and !target.blink) or + (self.reverse and !target.reverse) or + (self.strikethrough and !target.strikethrough); + + if (needs_reset) { + try writer.writeAll(ansi.reset); + self.reset(); + } + + // Now emit only the attributes that need to be turned on + if (target.bold and !self.bold) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); + if (target.dim and !self.dim) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); + if (target.italic and !self.italic) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); + if (target.underline and !self.underline) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + if (target.blink and !self.blink) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); + if (target.reverse and !self.reverse) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); + if (target.strikethrough and !self.strikethrough) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + + // Foreground color + if (target.fg_set) { + const fg_changed = !self.fg_set or + self.fg_r != target.fg_r or self.fg_g != target.fg_g or self.fg_b != target.fg_b or + (self.fg_ansi != target.fg_ansi); + if (fg_changed) { + if (target.fg_ansi) |a| { + try writer.print(ansi.CSI ++ "{d}m", .{a}); + } else { + try writer.print(ansi.CSI ++ "38;2;{d};{d};{d}m", .{ target.fg_r, target.fg_g, target.fg_b }); + } + } + } else if (self.fg_set) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.fg_default}); + } + + // Background color + if (target.bg_set) { + const bg_changed = !self.bg_set or + self.bg_r != target.bg_r or self.bg_g != target.bg_g or self.bg_b != target.bg_b or + (self.bg_ansi != target.bg_ansi); + if (bg_changed) { + if (target.bg_ansi) |a| { + try writer.print(ansi.CSI ++ "{d}m", .{a}); + } else { + try writer.print(ansi.CSI ++ "48;2;{d};{d};{d}m", .{ target.bg_r, target.bg_g, target.bg_b }); + } + } + } else if (self.bg_set) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bg_default}); + } + + // Update state + self.* = target; + } +}; + +/// Post-process an ANSI string to remove redundant escape sequences. +/// Strips consecutive resets and duplicate attribute settings. +pub fn compressAnsi(allocator: std.mem.Allocator, input: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var i: usize = 0; + var last_was_reset = false; + + while (i < input.len) { + // Check for ESC[ + if (i + 1 < input.len and input[i] == 0x1b and input[i + 1] == '[') { + // Find the end of the CSI sequence + var seq_end = i + 2; + while (seq_end < input.len) { + const c = input[seq_end]; + if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) { + seq_end += 1; + break; + } + seq_end += 1; + } + + const seq = input[i..seq_end]; + + // Check for reset sequence + if (std.mem.eql(u8, seq, ansi.reset)) { + if (!last_was_reset) { + try writer.writeAll(seq); + last_was_reset = true; + } + // Skip duplicate resets + } else { + try writer.writeAll(seq); + last_was_reset = false; + } + + i = seq_end; + } else { + try writer.writeByte(input[i]); + last_was_reset = false; + i += 1; + } + } + + return result.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig new file mode 100644 index 0000000..179a98a --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig @@ -0,0 +1,287 @@ +//! Text overflow handling for the ZigZag TUI framework. +//! Provides configurable overflow policies: clip, ellipsis, word-wrap, char-wrap. + +const std = @import("std"); +const Writer = std.Io.Writer; +const measure = @import("../layout/measure.zig"); + +/// Overflow policy for text that exceeds width constraints. +pub const Overflow = enum { + /// No overflow handling (default). + visible, + /// Clip text without indicator. + hidden, + /// Truncate with ellipsis character. + ellipsis, + /// Wrap at word boundaries. + word_wrap, + /// Wrap at character boundaries. + char_wrap, +}; + +/// Apply an overflow policy to text with a given max width. +/// Handles each line independently. ANSI-aware. +pub fn applyOverflow( + allocator: std.mem.Allocator, + text: []const u8, + max_width: u16, + policy: Overflow, +) ![]const u8 { + if (policy == .visible or max_width == 0) return text; + + var result: std.array_list.Managed(u8) = .init(allocator); + + var lines = std.mem.splitScalar(u8, text, '\n'); + var first_line = true; + while (lines.next()) |line| { + if (!first_line) try result.append('\n'); + first_line = false; + + switch (policy) { + .hidden => try applyClip(&result, line, max_width), + .ellipsis => try applyEllipsis(&result, line, max_width), + .word_wrap => try applyWordWrap(&result, line, max_width), + .char_wrap => try applyCharWrap(&result, line, max_width), + .visible => unreachable, + } + } + + return result.toOwnedSlice(); +} + +fn applyClip(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + var visible_width: usize = 0; + var i: usize = 0; + while (i < line.len) { + // Skip ANSI escape sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > max_width) break; + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + i += byte_len; + } +} + +fn applyEllipsis(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + const line_width = measure.width(line); + if (line_width <= max_width) { + try result.appendSlice(line); + return; + } + + if (max_width <= 1) { + if (max_width == 1) try result.appendSlice("\xe2\x80\xa6"); // … + return; + } + + // Truncate to max_width - 1 and add ellipsis + var visible_width: usize = 0; + var i: usize = 0; + const target_width = max_width - 1; + while (i < line.len) { + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > target_width) break; + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + i += byte_len; + } + + try result.appendSlice("\xe2\x80\xa6"); // … +} + +fn applyWordWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + if (measure.width(line) <= max_width) { + try result.appendSlice(line); + return; + } + + // Split line into words and re-flow them + var visible_width: usize = 0; + var i: usize = 0; + var line_start = true; + + while (i < line.len) { + // Skip ANSI sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + // Collect a word (non-space run) + if (line[i] == ' ') { + // Space: emit if it fits, otherwise start new line + if (visible_width + 1 > max_width) { + try result.append('\n'); + visible_width = 0; + line_start = true; + i += 1; + // Skip consecutive spaces at wrap point + while (i < line.len and line[i] == ' ') : (i += 1) {} + continue; + } + if (!line_start) { + try result.append(' '); + visible_width += 1; + } + i += 1; + continue; + } + + // Measure the next word + const word_start = i; + var word_width: usize = 0; + while (i < line.len and line[i] != ' ') { + // Skip ANSI inside word + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + continue; + } + word_width += charDisplayWidth(line, i); + i += charByteLen(line[i]); + } + const word = line[word_start..i]; + + // If word doesn't fit on current line, wrap + if (!line_start and visible_width + word_width > max_width) { + try result.append('\n'); + visible_width = 0; + line_start = true; + } + + // If single word is wider than max, just emit it (char-wrap fallback) + try result.appendSlice(word); + visible_width += word_width; + line_start = false; + } +} + +fn applyCharWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + if (measure.width(line) <= max_width) { + try result.appendSlice(line); + return; + } + + var visible_width: usize = 0; + var i: usize = 0; + var first_on_line = true; + + while (i < line.len) { + // Skip ANSI sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > max_width and !first_on_line) { + try result.append('\n'); + visible_width = 0; + first_on_line = true; + } + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + first_on_line = false; + i += byte_len; + } +} + +fn charDisplayWidth(text: []const u8, pos: usize) usize { + const byte = text[pos]; + if (byte < 0x80) return 1; + // Simple heuristic: CJK characters are 2-wide, others 1-wide + // Full-width ranges: U+1100-U+115F, U+2E80-U+A4CF, U+AC00-U+D7A3, etc. + const byte_len = charByteLen(byte); + if (byte_len >= 3 and pos + byte_len <= text.len) { + const cp = std.unicode.utf8Decode(text[pos..][0..byte_len]) catch return 1; + if (isWideCodepoint(cp)) return 2; + } + return 1; +} + +fn isWideCodepoint(cp: u21) bool { + return (cp >= 0x1100 and cp <= 0x115F) or + (cp >= 0x2E80 and cp <= 0x303E) or + (cp >= 0x3041 and cp <= 0x33BF) or + (cp >= 0x3400 and cp <= 0x4DBF) or + (cp >= 0x4E00 and cp <= 0xA4CF) or + (cp >= 0xAC00 and cp <= 0xD7A3) or + (cp >= 0xF900 and cp <= 0xFAFF) or + (cp >= 0xFE30 and cp <= 0xFE6F) or + (cp >= 0xFF01 and cp <= 0xFF60) or + (cp >= 0xFFE0 and cp <= 0xFFE6) or + (cp >= 0x20000 and cp <= 0x2FFFD) or + (cp >= 0x30000 and cp <= 0x3FFFD); +} + +fn charByteLen(first_byte: u8) usize { + if (first_byte < 0x80) return 1; + if (first_byte & 0xE0 == 0xC0) return 2; + if (first_byte & 0xF0 == 0xE0) return 3; + if (first_byte & 0xF8 == 0xF0) return 4; + return 1; +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +test "clip truncates at max width" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello, World!", 5, .hidden); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hello", result); +} + +test "ellipsis adds character" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello, World!", 6, .ellipsis); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hello\xe2\x80\xa6", result); +} + +test "visible returns original" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello", 3, .visible); + try std.testing.expectEqualStrings("Hello", result); +} + +test "short text unchanged with ellipsis" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hi", 10, .ellipsis); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hi", result); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig new file mode 100644 index 0000000..22b16e2 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig @@ -0,0 +1,1060 @@ +//! Style struct for terminal text styling (Lipgloss equivalent). +//! Provides a builder pattern for composing styles. + +const std = @import("std"); +const Writer = std.Io.Writer; +const color_mod = @import("color.zig"); +const border_mod = @import("border.zig"); +const ansi = @import("../terminal/ansi.zig"); +const measure = @import("../layout/measure.zig"); +const overflow_mod = @import("overflow.zig"); +pub const Overflow = overflow_mod.Overflow; + +pub const Color = color_mod.Color; +pub const BorderChars = border_mod.BorderChars; +pub const Sides = border_mod.Sides; + +/// Padding/Margin specification +pub const Spacing = struct { + top: u16 = 0, + right: u16 = 0, + bottom: u16 = 0, + left: u16 = 0, + + pub fn all(n: u16) Spacing { + return .{ .top = n, .right = n, .bottom = n, .left = n }; + } + + pub fn symmetric(vert: u16, horiz: u16) Spacing { + return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; + } + + pub fn horizontal(n: u16) Spacing { + return .{ .left = n, .right = n }; + } + + pub fn vertical(n: u16) Spacing { + return .{ .top = n, .bottom = n }; + } +}; + +/// Text alignment +pub const Align = enum { + left, + center, + right, +}; + +/// Vertical alignment +pub const VAlign = enum { + top, + middle, + bottom, +}; + +/// Built-in text transform functions +pub const transforms = struct { + pub fn uppercase(allocator: std.mem.Allocator, text: []const u8) []const u8 { + const result = allocator.alloc(u8, text.len) catch return text; + for (text, 0..) |c, i| { + result[i] = std.ascii.toUpper(c); + } + return result; + } + + pub fn lowercase(allocator: std.mem.Allocator, text: []const u8) []const u8 { + const result = allocator.alloc(u8, text.len) catch return text; + for (text, 0..) |c, i| { + result[i] = std.ascii.toLower(c); + } + return result; + } +}; + +/// Style definition with builder pattern +pub const Style = struct { + // Colors + foreground: Color = .none, + background: Color = .none, + + // Text attributes (nullable for unset semantics) + bold_attr: ?bool = null, + dim_attr: ?bool = null, + italic_attr: ?bool = null, + underline_attr: ?bool = null, + blink_attr: ?bool = null, + reverse_attr: ?bool = null, + strikethrough_attr: ?bool = null, + + // Spacing + padding_val: Spacing = .{}, + margin_val: Spacing = .{}, + + // Border + border_style: BorderChars = .none, + border_sides: Sides = .none, + border_fg: Color = .none, + border_bg: Color = .none, + + // Per-side border colors + border_top_fg: Color = .none, + border_top_bg: Color = .none, + border_right_fg: Color = .none, + border_right_bg: Color = .none, + border_bottom_fg: Color = .none, + border_bottom_bg: Color = .none, + border_left_fg: Color = .none, + border_left_bg: Color = .none, + + // Margin background + margin_bg: Color = .none, + + // Tab width + tab_width_val: ?u8 = null, + + // Size constraints + width_val: ?u16 = null, + height_val: ?u16 = null, + max_width_val: ?u16 = null, + max_height_val: ?u16 = null, + + // Alignment + align_horizontal: Align = .left, + align_vertical: VAlign = .top, + + // Inline (no newlines) + inline_mode: bool = false, + + // Transform function + transform_fn: ?*const fn (std.mem.Allocator, []const u8) []const u8 = null, + + // Text overflow + overflow_mode: Overflow = .visible, + + // Whitespace formatting controls + underline_spaces: bool = false, + strikethrough_spaces: bool = false, + color_whitespace: bool = true, + + const Self = @This(); + + // Color setters + pub fn foreground_color(self: Self, c: Color) Self { + var s = self; + s.foreground = c; + return s; + } + + pub fn background_color(self: Self, c: Color) Self { + var s = self; + s.background = c; + return s; + } + + pub fn fg(self: Self, c: Color) Self { + return self.foreground_color(c); + } + + pub fn bg(self: Self, c: Color) Self { + return self.background_color(c); + } + + // Text attribute setters + pub fn bold(self: Self, v: bool) Self { + var s = self; + s.bold_attr = v; + return s; + } + + pub fn dim(self: Self, v: bool) Self { + var s = self; + s.dim_attr = v; + return s; + } + + pub fn italic(self: Self, v: bool) Self { + var s = self; + s.italic_attr = v; + return s; + } + + pub fn underline(self: Self, v: bool) Self { + var s = self; + s.underline_attr = v; + return s; + } + + pub fn blink(self: Self, v: bool) Self { + var s = self; + s.blink_attr = v; + return s; + } + + pub fn reverse(self: Self, v: bool) Self { + var s = self; + s.reverse_attr = v; + return s; + } + + pub fn strikethrough(self: Self, v: bool) Self { + var s = self; + s.strikethrough_attr = v; + return s; + } + + // Unset methods + pub fn unsetBold(self: Self) Self { + var s = self; + s.bold_attr = null; + return s; + } + + pub fn unsetDim(self: Self) Self { + var s = self; + s.dim_attr = null; + return s; + } + + pub fn unsetItalic(self: Self) Self { + var s = self; + s.italic_attr = null; + return s; + } + + pub fn unsetUnderline(self: Self) Self { + var s = self; + s.underline_attr = null; + return s; + } + + pub fn unsetBlink(self: Self) Self { + var s = self; + s.blink_attr = null; + return s; + } + + pub fn unsetReverse(self: Self) Self { + var s = self; + s.reverse_attr = null; + return s; + } + + pub fn unsetStrikethrough(self: Self) Self { + var s = self; + s.strikethrough_attr = null; + return s; + } + + pub fn unsetFg(self: Self) Self { + var s = self; + s.foreground = .none; + return s; + } + + pub fn unsetBg(self: Self) Self { + var s = self; + s.background = .none; + return s; + } + + pub fn unsetPadding(self: Self) Self { + var s = self; + s.padding_val = .{}; + return s; + } + + pub fn unsetMargin(self: Self) Self { + var s = self; + s.margin_val = .{}; + return s; + } + + pub fn unsetBorder(self: Self) Self { + var s = self; + s.border_style = .none; + s.border_sides = .none; + s.border_fg = .none; + s.border_bg = .none; + s.border_top_fg = .none; + s.border_top_bg = .none; + s.border_right_fg = .none; + s.border_right_bg = .none; + s.border_bottom_fg = .none; + s.border_bottom_bg = .none; + s.border_left_fg = .none; + s.border_left_bg = .none; + return s; + } + + pub fn unsetWidth(self: Self) Self { + var s = self; + s.width_val = null; + return s; + } + + pub fn unsetHeight(self: Self) Self { + var s = self; + s.height_val = null; + return s; + } + + pub fn unsetMaxWidth(self: Self) Self { + var s = self; + s.max_width_val = null; + return s; + } + + pub fn unsetMaxHeight(self: Self) Self { + var s = self; + s.max_height_val = null; + return s; + } + + // Spacing setters + pub fn padding(self: Self, p: Spacing) Self { + var s = self; + s.padding_val = p; + return s; + } + + pub fn paddingAll(self: Self, n: u16) Self { + return self.padding(.all(n)); + } + + pub fn paddingLeft(self: Self, n: u16) Self { + var s = self; + s.padding_val.left = n; + return s; + } + + pub fn paddingRight(self: Self, n: u16) Self { + var s = self; + s.padding_val.right = n; + return s; + } + + pub fn paddingTop(self: Self, n: u16) Self { + var s = self; + s.padding_val.top = n; + return s; + } + + pub fn paddingBottom(self: Self, n: u16) Self { + var s = self; + s.padding_val.bottom = n; + return s; + } + + pub fn margin(self: Self, m: Spacing) Self { + var s = self; + s.margin_val = m; + return s; + } + + pub fn marginAll(self: Self, n: u16) Self { + return self.margin(.all(n)); + } + + pub fn marginLeft(self: Self, n: u16) Self { + var s = self; + s.margin_val.left = n; + return s; + } + + pub fn marginRight(self: Self, n: u16) Self { + var s = self; + s.margin_val.right = n; + return s; + } + + pub fn marginTop(self: Self, n: u16) Self { + var s = self; + s.margin_val.top = n; + return s; + } + + pub fn marginBottom(self: Self, n: u16) Self { + var s = self; + s.margin_val.bottom = n; + return s; + } + + // Border setters + pub fn border(self: Self, chars: BorderChars, sides: Sides) Self { + var s = self; + s.border_style = chars; + s.border_sides = sides; + return s; + } + + pub fn borderAll(self: Self, chars: BorderChars) Self { + return self.border(chars, .all); + } + + pub fn borderForeground(self: Self, c: Color) Self { + var s = self; + s.border_fg = c; + return s; + } + + pub fn borderBackground(self: Self, c: Color) Self { + var s = self; + s.border_bg = c; + return s; + } + + pub fn borderTopForeground(self: Self, c: Color) Self { + var s = self; + s.border_top_fg = c; + return s; + } + + pub fn borderTopBackground(self: Self, c: Color) Self { + var s = self; + s.border_top_bg = c; + return s; + } + + pub fn borderRightForeground(self: Self, c: Color) Self { + var s = self; + s.border_right_fg = c; + return s; + } + + pub fn borderRightBackground(self: Self, c: Color) Self { + var s = self; + s.border_right_bg = c; + return s; + } + + pub fn borderBottomForeground(self: Self, c: Color) Self { + var s = self; + s.border_bottom_fg = c; + return s; + } + + pub fn borderBottomBackground(self: Self, c: Color) Self { + var s = self; + s.border_bottom_bg = c; + return s; + } + + pub fn borderLeftForeground(self: Self, c: Color) Self { + var s = self; + s.border_left_fg = c; + return s; + } + + pub fn borderLeftBackground(self: Self, c: Color) Self { + var s = self; + s.border_left_bg = c; + return s; + } + + pub fn marginBackground(self: Self, c: Color) Self { + var s = self; + s.margin_bg = c; + return s; + } + + pub fn tabWidth(self: Self, n: u8) Self { + var s = self; + s.tab_width_val = n; + return s; + } + + // Size setters + pub fn width(self: Self, w: u16) Self { + var s = self; + s.width_val = w; + return s; + } + + pub fn height(self: Self, h: u16) Self { + var s = self; + s.height_val = h; + return s; + } + + pub fn maxWidth(self: Self, w: u16) Self { + var s = self; + s.max_width_val = w; + return s; + } + + pub fn maxHeight(self: Self, h: u16) Self { + var s = self; + s.max_height_val = h; + return s; + } + + // Overflow setter + pub fn overflow(self: Self, mode: Overflow) Self { + var s = self; + s.overflow_mode = mode; + return s; + } + + // Alignment setters + pub fn alignH(self: Self, a: Align) Self { + var s = self; + s.align_horizontal = a; + return s; + } + + pub fn valign(self: Self, a: VAlign) Self { + var s = self; + s.align_vertical = a; + return s; + } + + // Inline mode + pub fn inline_style(self: Self, v: bool) Self { + var s = self; + s.inline_mode = v; + return s; + } + + // Transform setter + pub fn transform(self: Self, func: *const fn (std.mem.Allocator, []const u8) []const u8) Self { + var s = self; + s.transform_fn = func; + return s; + } + + // Whitespace formatting control setters + pub fn setUnderlineSpaces(self: Self, v: bool) Self { + var s = self; + s.underline_spaces = v; + return s; + } + + pub fn setStrikethroughSpaces(self: Self, v: bool) Self { + var s = self; + s.strikethrough_spaces = v; + return s; + } + + pub fn setColorWhitespace(self: Self, v: bool) Self { + var s = self; + s.color_whitespace = v; + return s; + } + + /// Inherit unset values from another style + pub fn inherit(self: Self, other: Self) Self { + var s = self; + if (s.foreground == .none) s.foreground = other.foreground; + if (s.background == .none) s.background = other.background; + if (s.bold_attr == null) s.bold_attr = other.bold_attr; + if (s.dim_attr == null) s.dim_attr = other.dim_attr; + if (s.italic_attr == null) s.italic_attr = other.italic_attr; + if (s.underline_attr == null) s.underline_attr = other.underline_attr; + if (s.blink_attr == null) s.blink_attr = other.blink_attr; + if (s.reverse_attr == null) s.reverse_attr = other.reverse_attr; + if (s.strikethrough_attr == null) s.strikethrough_attr = other.strikethrough_attr; + if (s.padding_val.top == 0 and s.padding_val.bottom == 0 and s.padding_val.left == 0 and s.padding_val.right == 0) { + s.padding_val = other.padding_val; + } + if (s.margin_val.top == 0 and s.margin_val.bottom == 0 and s.margin_val.left == 0 and s.margin_val.right == 0) { + s.margin_val = other.margin_val; + } + if (s.border_fg == .none) s.border_fg = other.border_fg; + if (s.border_bg == .none) s.border_bg = other.border_bg; + if (s.width_val == null) s.width_val = other.width_val; + if (s.height_val == null) s.height_val = other.height_val; + if (s.max_width_val == null) s.max_width_val = other.max_width_val; + if (s.max_height_val == null) s.max_height_val = other.max_height_val; + if (s.margin_bg == .none) s.margin_bg = other.margin_bg; + if (s.tab_width_val == null) s.tab_width_val = other.tab_width_val; + if (s.transform_fn == null) s.transform_fn = other.transform_fn; + return s; + } + + /// Render styled text + pub fn render(self: Self, allocator: std.mem.Allocator, text: []const u8) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + defer result.deinit(); + + // Preprocess tabs if tab_width is set. Only allocate the scratch + // buffer when expansion is actually needed. + var processed_text = text; + if (self.tab_width_val) |tw| { + var buf: Writer.Allocating = .init(allocator); + defer buf.deinit(); + for (text) |c| { + if (c == '\t') { + for (0..tw) |_| { + try buf.writer.writeByte(' '); + } + } else { + try buf.writer.writeByte(c); + } + } + processed_text = try buf.toOwnedSlice(); + } + + // Apply transform function + if (self.transform_fn) |tf| { + processed_text = tf(allocator, processed_text); + } + + // Apply overflow policy before dimension calculation + if (self.overflow_mode != .visible) { + const ow = self.width_val orelse (self.max_width_val orelse 0); + if (ow > 0) { + processed_text = overflow_mod.applyOverflow(allocator, processed_text, ow, self.overflow_mode) catch processed_text; + } + } + + // Calculate content dimensions + const content_width = measure.width(processed_text); + const content_height = measure.height(processed_text); + + // Apply size constraints + var target_width = content_width; + var target_height = content_height; + + if (self.width_val) |w| target_width = w; + if (self.height_val) |h| target_height = h; + if (self.max_width_val) |mw| target_width = @min(target_width, mw); + if (self.max_height_val) |mh| target_height = @min(target_height, mh); + + // Add padding to target dimensions + target_width += self.padding_val.left + self.padding_val.right; + target_height += self.padding_val.top + self.padding_val.bottom; + + // Add border width + if (self.border_sides.left) target_width += 1; + if (self.border_sides.right) target_width += 1; + if (self.border_sides.top) target_height += 1; + if (self.border_sides.bottom) target_height += 1; + + // Write margin top + for (0..self.margin_val.top) |_| { + try self.writeMarginLeft(&result.writer); + if (!self.margin_bg.isNone()) { + try self.margin_bg.writeBg(&result.writer); + for (0..target_width) |_| { + try result.writer.writeByte(' '); + } + try self.writeMarginRight(&result.writer, target_width); + try result.writer.writeAll(ansi.reset); + } + try result.writer.writeByte('\n'); + } + + // Build styled content + try self.writeStyledContent(&result.writer, processed_text, target_width, target_height); + + // Write margin bottom + for (0..self.margin_val.bottom) |_| { + try result.writer.writeByte('\n'); + try self.writeMarginLeft(&result.writer); + if (!self.margin_bg.isNone()) { + try self.margin_bg.writeBg(&result.writer); + for (0..target_width) |_| { + try result.writer.writeByte(' '); + } + try self.writeMarginRight(&result.writer, target_width); + try result.writer.writeAll(ansi.reset); + } + } + + var array = result.toArrayList(); + if (!self.inline_mode and + array.items.len > 0 and + array.items[array.items.len - 1] == '\n') + _ = array.pop(); + + return array.toOwnedSlice(allocator); + } + + fn writeStyledContent(self: Self, writer: *Writer, text: []const u8, target_width: usize, target_height: usize) !void { + const inner_width = target_width -| + self.padding_val.left -| self.padding_val.right -| + @as(usize, if (self.border_sides.left) 1 else 0) -| + @as(usize, if (self.border_sides.right) 1 else 0); + + const inner_height = target_height -| + self.padding_val.top -| self.padding_val.bottom -| + @as(usize, if (self.border_sides.top) 1 else 0) -| + @as(usize, if (self.border_sides.bottom) 1 else 0); + + _ = inner_height; + + // Start style + try self.writeStyleStart(writer); + + // Top border + if (self.border_sides.top) { + try self.writeMarginLeft(writer); + try self.writeBorderColorSide(writer, .top); + if (self.border_sides.left) try writer.writeAll(self.border_style.top_left); + for (0..inner_width + self.padding_val.left + self.padding_val.right) |_| { + try writer.writeAll(self.border_style.horizontal); + } + if (self.border_sides.right) try writer.writeAll(self.border_style.top_right); + try writer.writeAll(ansi.reset); + try self.writeMarginRight(writer, target_width); + if (!self.inline_mode) try writer.writeByte('\n'); + } + + // Padding top + for (0..self.padding_val.top) |_| { + try self.writeContentLine(writer, "", inner_width); + } + + // Content lines + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + try self.writeContentLine(writer, line, inner_width); + } + + // Padding bottom + for (0..self.padding_val.bottom) |_| { + try self.writeContentLine(writer, "", inner_width); + } + + // Bottom border + if (self.border_sides.bottom) { + try self.writeMarginLeft(writer); + try self.writeBorderColorSide(writer, .bottom); + if (self.border_sides.left) try writer.writeAll(self.border_style.bottom_left); + for (0..inner_width + self.padding_val.left + self.padding_val.right) |_| { + try writer.writeAll(self.border_style.horizontal); + } + if (self.border_sides.right) try writer.writeAll(self.border_style.bottom_right); + try writer.writeAll(ansi.reset); + try self.writeMarginRight(writer, target_width); + } + } + + /// Check if whitespace-aware rendering is needed + fn needsWhitespaceAwareRendering(self: Self) bool { + return (!self.color_whitespace and !self.background.isNone()) or + (self.underline_spaces and (self.underline_attr orelse false)) or + (self.strikethrough_spaces and (self.strikethrough_attr orelse false)); + } + + fn writeContentLine(self: Self, writer: *Writer, line: []const u8, inner_width: usize) !void { + try self.writeMarginLeft(writer); + + // Left border + if (self.border_sides.left) { + try self.writeBorderColorSide(writer, .left); + try writer.writeAll(self.border_style.vertical); + try writer.writeAll(ansi.reset); + } + + // Start content style + try self.writeStyleStart(writer); + + // Left padding + for (0..self.padding_val.left) |_| { + try writer.writeByte(' '); + } + + // Content with alignment + const line_width = measure.width(line); + const content_pad = if (inner_width > line_width) inner_width - line_width else 0; + + if (self.needsWhitespaceAwareRendering()) { + // Whitespace-aware rendering: toggle attributes around spaces + switch (self.align_horizontal) { + .left => { + try self.writeWithWhitespaceControl(writer, line); + try self.writeSpacesWithControl(writer, content_pad); + }, + .center => { + const left_pad = content_pad / 2; + const right_pad = content_pad - left_pad; + try self.writeSpacesWithControl(writer, left_pad); + try self.writeWithWhitespaceControl(writer, line); + try self.writeSpacesWithControl(writer, right_pad); + }, + .right => { + try self.writeSpacesWithControl(writer, content_pad); + try self.writeWithWhitespaceControl(writer, line); + }, + } + } else { + switch (self.align_horizontal) { + .left => { + try writer.writeAll(line); + for (0..content_pad) |_| { + try writer.writeByte(' '); + } + }, + .center => { + const left_pad = content_pad / 2; + const right_pad = content_pad - left_pad; + for (0..left_pad) |_| { + try writer.writeByte(' '); + } + try writer.writeAll(line); + for (0..right_pad) |_| { + try writer.writeByte(' '); + } + }, + .right => { + for (0..content_pad) |_| { + try writer.writeByte(' '); + } + try writer.writeAll(line); + }, + } + } + + // Right padding + for (0..self.padding_val.right) |_| { + try writer.writeByte(' '); + } + + // Reset style + try writer.writeAll(ansi.reset); + + // Right border + if (self.border_sides.right) { + try self.writeBorderColorSide(writer, .right); + try writer.writeAll(self.border_style.vertical); + try writer.writeAll(ansi.reset); + } + + // Right margin + const total_content_width = inner_width + self.padding_val.left + self.padding_val.right + + @as(usize, if (self.border_sides.left) 1 else 0) + + @as(usize, if (self.border_sides.right) 1 else 0); + try self.writeMarginRight(writer, total_content_width); + + if (!self.inline_mode) try writer.writeByte('\n'); + } + + /// Write text with per-character whitespace attribute control + fn writeWithWhitespaceControl(self: Self, writer: *Writer, text: []const u8) !void { + var i: usize = 0; + while (i < text.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; + const end = @min(i + byte_len, text.len); + const ch = text[i..end]; + const is_space = ch.len == 1 and ch[0] == ' '; + + if (is_space) { + // For spaces: conditionally disable/enable attributes + if (!self.color_whitespace and !self.background.isNone()) { + try writer.writeAll(ansi.reset); + // Re-emit attributes that should apply to spaces + if (self.underline_spaces and (self.underline_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + } + if (self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + } + try writer.writeByte(' '); + // Restore full style + try self.writeStyleStart(writer); + } else { + // Color whitespace is on, but check underline/strikethrough + if (!self.underline_spaces and (self.underline_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.no_underline}); + } + if (!self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.no_strikethrough}); + } + try writer.writeByte(' '); + // Restore + if (!self.underline_spaces and (self.underline_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + } + if (!self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + } + } + } else { + try writer.writeAll(ch); + } + + i = end; + } + } + + /// Write N spaces with whitespace control + fn writeSpacesWithControl(self: Self, writer: *Writer, count: usize) !void { + if (count == 0) return; + if (!self.color_whitespace and !self.background.isNone()) { + try writer.writeAll(ansi.reset); + if (self.underline_spaces and (self.underline_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + } + if (self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + } + for (0..count) |_| { + try writer.writeByte(' '); + } + try self.writeStyleStart(writer); + } else { + for (0..count) |_| { + try writer.writeByte(' '); + } + } + } + + fn writeMarginLeft(self: Self, writer: *Writer) !void { + if (!self.margin_bg.isNone() and self.margin_val.left > 0) { + try self.margin_bg.writeBg(writer); + } + for (0..self.margin_val.left) |_| { + try writer.writeByte(' '); + } + if (!self.margin_bg.isNone() and self.margin_val.left > 0) { + try writer.writeAll(ansi.reset); + } + } + + fn writeMarginRight(self: Self, writer: *Writer, content_width: usize) !void { + _ = content_width; + if (self.margin_val.right > 0) { + if (!self.margin_bg.isNone()) { + try self.margin_bg.writeBg(writer); + } + for (0..self.margin_val.right) |_| { + try writer.writeByte(' '); + } + if (!self.margin_bg.isNone()) { + try writer.writeAll(ansi.reset); + } + } + } + + fn writeStyleStart(self: Self, writer: *Writer) !void { + if (self.bold_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); + if (self.dim_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); + if (self.italic_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); + if (self.underline_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + if (self.blink_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); + if (self.reverse_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); + if (self.strikethrough_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + + try self.foreground.writeFg(writer); + try self.background.writeBg(writer); + } + + const BorderSide = enum { top, right, bottom, left }; + + fn writeBorderColorSide(self: Self, writer: *Writer, side: BorderSide) !void { + const side_fg = switch (side) { + .top => self.border_top_fg, + .right => self.border_right_fg, + .bottom => self.border_bottom_fg, + .left => self.border_left_fg, + }; + const side_bg = switch (side) { + .top => self.border_top_bg, + .right => self.border_right_bg, + .bottom => self.border_bottom_bg, + .left => self.border_left_bg, + }; + const resolved_fg = if (!side_fg.isNone()) side_fg else self.border_fg; + const resolved_bg = if (!side_bg.isNone()) side_bg else self.border_bg; + try resolved_fg.writeFg(writer); + try resolved_bg.writeBg(writer); + } + + fn writeBorderColor(self: Self, writer: *Writer) !void { + try self.border_fg.writeFg(writer); + try self.border_bg.writeBg(writer); + } + + /// Copy style + pub fn copy(self: Self) Self { + return self; + } +}; + +/// Style range for applying different styles to byte ranges +pub const StyleRange = struct { + start: usize, + end: usize, + s: Style, +}; + +/// Render text with different styles applied to specific byte ranges +pub fn renderWithRanges(allocator: std.mem.Allocator, text: []const u8, ranges: []const StyleRange) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var pos: usize = 0; + while (pos < text.len) { + // Find if this position is in a range + var found_range: ?StyleRange = null; + for (ranges) |r| { + if (pos >= r.start and pos < r.end) { + found_range = r; + break; + } + } + + if (found_range) |r| { + const end = @min(r.end, text.len); + const chunk = text[pos..end]; + const styled = try r.s.render(allocator, chunk); + try writer.writeAll(styled); + pos = end; + } else { + // Find next range start or end of text + var next_start: usize = text.len; + for (ranges) |r| { + if (r.start > pos and r.start < next_start) { + next_start = r.start; + } + } + try writer.writeAll(text[pos..next_start]); + pos = next_start; + } + } + + return result.toOwnedSlice(); +} + +/// Render text with specific byte positions highlighted +pub fn renderWithHighlights( + allocator: std.mem.Allocator, + text: []const u8, + positions: []const usize, + highlight_style: Style, + base_style: Style, +) ![]const u8 { + var result: Writer.Allocating = .init(allocator); + const writer = &result.writer; + + var pos: usize = 0; + var pi: usize = 0; // position index + + while (pos < text.len) { + if (pi < positions.len and pos == positions[pi]) { + // Highlighted character + const byte_len = std.unicode.utf8ByteSequenceLength(text[pos]) catch 1; + const end = @min(pos + byte_len, text.len); + const ch = text[pos..end]; + const styled = try highlight_style.render(allocator, ch); + try writer.writeAll(styled); + pos = end; + pi += 1; + } else { + // Find next highlight position or end of text + var next_pos: usize = text.len; + if (pi < positions.len) { + next_pos = @min(positions[pi], text.len); + } + const chunk = text[pos..next_pos]; + if (chunk.len > 0) { + const styled = try base_style.render(allocator, chunk); + try writer.writeAll(styled); + } + pos = next_pos; + } + } + + return result.toOwnedSlice(); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig new file mode 100644 index 0000000..4657e38 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig @@ -0,0 +1,481 @@ +//! Theming system for ZigZag. +//! Provides centralized color palettes and component-specific themes. + +const std = @import("std"); +const Color = @import("color.zig").Color; +const style_mod = @import("style.zig"); + +/// Semantic color palette. Defines named colors for a theme. +pub const Palette = struct { + // Primary colors + primary: Color, + secondary: Color, + accent: Color, + + // Surfaces + background: Color, + surface: Color, + overlay: Color, + + // Text + foreground: Color, + muted: Color, + subtle: Color, + + // Feedback + success: Color, + warning: Color, + danger: Color, + info: Color, + + // Borders + border_color: Color, + border_focus: Color, + + // Highlight + highlight: Color, + highlight_text: Color, + + // ── Built-in presets ────────────────────────────── + + pub const default_dark = Palette{ + .primary = .cyan, + .secondary = .magenta, + .accent = .yellow, + .background = .fromRgb(24, 24, 32), + .surface = .fromRgb(32, 32, 42), + .overlay = .fromRgb(40, 40, 52), + .foreground = .white, + .muted = .gray(14), + .subtle = .gray(10), + .success = .green, + .warning = .yellow, + .danger = .red, + .info = .cyan, + .border_color = .gray(12), + .border_focus = .cyan, + .highlight = .fromRgb(60, 60, 80), + .highlight_text = .white, + }; + + pub const default_light = Palette{ + .primary = .fromRgb(0, 120, 180), + .secondary = .fromRgb(140, 60, 160), + .accent = .fromRgb(180, 120, 0), + .background = .fromRgb(250, 250, 250), + .surface = .fromRgb(240, 240, 240), + .overlay = .fromRgb(230, 230, 230), + .foreground = .fromRgb(30, 30, 30), + .muted = .fromRgb(100, 100, 100), + .subtle = .fromRgb(160, 160, 160), + .success = .fromRgb(40, 160, 40), + .warning = .fromRgb(200, 150, 0), + .danger = .fromRgb(200, 40, 40), + .info = .fromRgb(0, 120, 180), + .border_color = .fromRgb(180, 180, 180), + .border_focus = .fromRgb(0, 120, 180), + .highlight = .fromRgb(200, 220, 240), + .highlight_text = .fromRgb(30, 30, 30), + }; + + pub const catppuccin_mocha = Palette{ + .primary = .fromRgb(137, 180, 250), // blue + .secondary = .fromRgb(203, 166, 247), // mauve + .accent = .fromRgb(249, 226, 175), // yellow + .background = .fromRgb(30, 30, 46), // base + .surface = .fromRgb(49, 50, 68), // surface0 + .overlay = .fromRgb(69, 71, 90), // surface1 + .foreground = .fromRgb(205, 214, 244), // text + .muted = .fromRgb(166, 173, 200), // subtext0 + .subtle = .fromRgb(127, 132, 156), // overlay1 + .success = .fromRgb(166, 227, 161), // green + .warning = .fromRgb(249, 226, 175), // yellow + .danger = .fromRgb(243, 139, 168), // red + .info = .fromRgb(137, 180, 250), // blue + .border_color = .fromRgb(88, 91, 112), // overlay0 + .border_focus = .fromRgb(137, 180, 250), // blue + .highlight = .fromRgb(49, 50, 68), // surface0 + .highlight_text = .fromRgb(205, 214, 244), // text + }; + + pub const catppuccin_latte = Palette{ + .primary = .fromRgb(30, 102, 245), // blue + .secondary = .fromRgb(136, 57, 239), // mauve + .accent = .fromRgb(223, 142, 29), // yellow + .background = .fromRgb(239, 241, 245), // base + .surface = .fromRgb(204, 208, 218), // surface0 + .overlay = .fromRgb(188, 192, 204), // surface1 + .foreground = .fromRgb(76, 79, 105), // text + .muted = .fromRgb(108, 111, 133), // subtext0 + .subtle = .fromRgb(140, 143, 161), // overlay1 + .success = .fromRgb(64, 160, 43), // green + .warning = .fromRgb(223, 142, 29), // yellow + .danger = .fromRgb(210, 15, 57), // red + .info = .fromRgb(30, 102, 245), // blue + .border_color = .fromRgb(156, 160, 176), // overlay0 + .border_focus = .fromRgb(30, 102, 245), // blue + .highlight = .fromRgb(204, 208, 218), // surface0 + .highlight_text = .fromRgb(76, 79, 105), // text + }; + + pub const dracula = Palette{ + .primary = .fromRgb(189, 147, 249), // purple + .secondary = .fromRgb(255, 121, 198), // pink + .accent = .fromRgb(241, 250, 140), // yellow + .background = .fromRgb(40, 42, 54), // background + .surface = .fromRgb(68, 71, 90), // current line + .overlay = .fromRgb(68, 71, 90), // current line + .foreground = .fromRgb(248, 248, 242), // foreground + .muted = .fromRgb(98, 114, 164), // comment + .subtle = .fromRgb(98, 114, 164), // comment + .success = .fromRgb(80, 250, 123), // green + .warning = .fromRgb(255, 184, 108), // orange + .danger = .fromRgb(255, 85, 85), // red + .info = .fromRgb(139, 233, 253), // cyan + .border_color = .fromRgb(98, 114, 164), // comment + .border_focus = .fromRgb(189, 147, 249), // purple + .highlight = .fromRgb(68, 71, 90), // current line + .highlight_text = .fromRgb(248, 248, 242), // foreground + }; + + pub const nord = Palette{ + .primary = .fromRgb(136, 192, 208), // nord8 frost + .secondary = .fromRgb(129, 161, 193), // nord9 + .accent = .fromRgb(235, 203, 139), // nord13 aurora yellow + .background = .fromRgb(46, 52, 64), // nord0 polar night + .surface = .fromRgb(59, 66, 82), // nord1 + .overlay = .fromRgb(67, 76, 94), // nord2 + .foreground = .fromRgb(236, 239, 244), // nord6 snow storm + .muted = .fromRgb(216, 222, 233), // nord4 + .subtle = .fromRgb(76, 86, 106), // nord3 + .success = .fromRgb(163, 190, 140), // nord14 aurora green + .warning = .fromRgb(235, 203, 139), // nord13 + .danger = .fromRgb(191, 97, 106), // nord11 aurora red + .info = .fromRgb(136, 192, 208), // nord8 + .border_color = .fromRgb(76, 86, 106), // nord3 + .border_focus = .fromRgb(136, 192, 208), // nord8 + .highlight = .fromRgb(59, 66, 82), // nord1 + .highlight_text = .fromRgb(236, 239, 244), // nord6 + }; + + pub const high_contrast = Palette{ + .primary = .fromRgb(0, 200, 255), + .secondary = .fromRgb(255, 100, 255), + .accent = .fromRgb(255, 255, 0), + .background = .fromRgb(0, 0, 0), + .surface = .fromRgb(20, 20, 20), + .overlay = .fromRgb(40, 40, 40), + .foreground = .fromRgb(255, 255, 255), + .muted = .fromRgb(200, 200, 200), + .subtle = .fromRgb(150, 150, 150), + .success = .fromRgb(0, 255, 0), + .warning = .fromRgb(255, 255, 0), + .danger = .fromRgb(255, 0, 0), + .info = .fromRgb(0, 200, 255), + .border_color = .fromRgb(200, 200, 200), + .border_focus = .fromRgb(0, 200, 255), + .highlight = .fromRgb(0, 80, 120), + .highlight_text = .fromRgb(255, 255, 255), + }; + + pub const tokyo_night = Palette{ + .primary = .fromRgb(122, 162, 247), // blue + .secondary = .fromRgb(187, 154, 247), // purple + .accent = .fromRgb(224, 175, 104), // yellow + .background = .fromRgb(26, 27, 38), // bg + .surface = .fromRgb(36, 40, 59), // bg_highlight + .overlay = .fromRgb(41, 46, 66), // terminal_black + .foreground = .fromRgb(192, 202, 245), // fg + .muted = .fromRgb(144, 153, 191), // comment + .subtle = .fromRgb(86, 95, 137), // dark5 + .success = .fromRgb(158, 206, 106), // green + .warning = .fromRgb(224, 175, 104), // yellow + .danger = .fromRgb(247, 118, 142), // red + .info = .fromRgb(125, 207, 255), // cyan + .border_color = .fromRgb(41, 46, 66), + .border_focus = .fromRgb(122, 162, 247), + .highlight = .fromRgb(41, 46, 66), + .highlight_text = .fromRgb(192, 202, 245), + }; + + pub const gruvbox_dark = Palette{ + .primary = .fromRgb(131, 165, 152), // aqua + .secondary = .fromRgb(211, 134, 155), // purple + .accent = .fromRgb(250, 189, 47), // yellow + .background = .fromRgb(40, 40, 40), // bg + .surface = .fromRgb(60, 56, 54), // bg1 + .overlay = .fromRgb(80, 73, 69), // bg2 + .foreground = .fromRgb(235, 219, 178), // fg + .muted = .fromRgb(168, 153, 132), // gray + .subtle = .fromRgb(124, 111, 100), // bg4 + .success = .fromRgb(184, 187, 38), // green + .warning = .fromRgb(250, 189, 47), // yellow + .danger = .fromRgb(251, 73, 52), // red + .info = .fromRgb(131, 165, 152), // aqua + .border_color = .fromRgb(80, 73, 69), + .border_focus = .fromRgb(131, 165, 152), + .highlight = .fromRgb(80, 73, 69), + .highlight_text = .fromRgb(235, 219, 178), + }; + + pub const solarized_dark = Palette{ + .primary = .fromRgb(38, 139, 210), // blue + .secondary = .fromRgb(108, 113, 196), // violet + .accent = .fromRgb(181, 137, 0), // yellow + .background = .fromRgb(0, 43, 54), // base03 + .surface = .fromRgb(7, 54, 66), // base02 + .overlay = .fromRgb(88, 110, 117), // base01 + .foreground = .fromRgb(131, 148, 150), // base0 + .muted = .fromRgb(101, 123, 131), // base00 + .subtle = .fromRgb(88, 110, 117), // base01 + .success = .fromRgb(133, 153, 0), // green + .warning = .fromRgb(181, 137, 0), // yellow + .danger = .fromRgb(220, 50, 47), // red + .info = .fromRgb(42, 161, 152), // cyan + .border_color = .fromRgb(88, 110, 117), + .border_focus = .fromRgb(38, 139, 210), + .highlight = .fromRgb(7, 54, 66), + .highlight_text = .fromRgb(147, 161, 161), + }; + + pub const solarized_light = Palette{ + .primary = .fromRgb(38, 139, 210), // blue + .secondary = .fromRgb(108, 113, 196), // violet + .accent = .fromRgb(181, 137, 0), // yellow + .background = .fromRgb(253, 246, 227), // base3 + .surface = .fromRgb(238, 232, 213), // base2 + .overlay = .fromRgb(147, 161, 161), // base1 + .foreground = .fromRgb(101, 123, 131), // base00 + .muted = .fromRgb(131, 148, 150), // base0 + .subtle = .fromRgb(147, 161, 161), // base1 + .success = .fromRgb(133, 153, 0), // green + .warning = .fromRgb(181, 137, 0), // yellow + .danger = .fromRgb(220, 50, 47), // red + .info = .fromRgb(42, 161, 152), // cyan + .border_color = .fromRgb(147, 161, 161), + .border_focus = .fromRgb(38, 139, 210), + .highlight = .fromRgb(238, 232, 213), + .highlight_text = .fromRgb(88, 110, 117), + }; + + /// List of all built-in palette names for iteration. + pub const builtins = [_]struct { name: []const u8, palette: Palette }{ + .{ .name = "Default Dark", .palette = default_dark }, + .{ .name = "Default Light", .palette = default_light }, + .{ .name = "Catppuccin Mocha", .palette = catppuccin_mocha }, + .{ .name = "Catppuccin Latte", .palette = catppuccin_latte }, + .{ .name = "Dracula", .palette = dracula }, + .{ .name = "Nord", .palette = nord }, + .{ .name = "Tokyo Night", .palette = tokyo_night }, + .{ .name = "Gruvbox Dark", .palette = gruvbox_dark }, + .{ .name = "Solarized Dark", .palette = solarized_dark }, + .{ .name = "Solarized Light", .palette = solarized_light }, + .{ .name = "High Contrast", .palette = high_contrast }, + }; +}; + +/// Adaptive palette that resolves based on dark/light background. +pub const AdaptivePalette = struct { + light: Palette, + dark: Palette, + + pub fn resolve(self: AdaptivePalette, is_dark: bool) Palette { + return if (is_dark) self.dark else self.light; + } + + pub const catppuccin = AdaptivePalette{ + .light = .catppuccin_latte, + .dark = .catppuccin_mocha, + }; + + pub const default = AdaptivePalette{ + .light = .default_light, + .dark = .default_dark, + }; + + pub const solarized = AdaptivePalette{ + .light = .solarized_light, + .dark = .solarized_dark, + }; +}; + +/// Manages the active theme at runtime. +/// Holds a current theme and provides methods to switch between palettes. +pub const ThemeManager = struct { + current: Theme, + is_dark: bool, + palette_index: usize, + + /// Initialize with dark/light background detected from `environ_map`. + pub fn init(environ_map: *const std.process.Environ.Map) ThemeManager { + const is_dark = @import("color.zig").hasDarkBackground(environ_map); + const palette = AdaptivePalette.default.resolve(is_dark); + return .{ + .current = .fromPalette(palette), + .is_dark = is_dark, + .palette_index = 0, + }; + } + + /// Initialize with a specific palette and `environ_map`-detected dark/light hint. + pub fn initWithPalette(environ_map: *const std.process.Environ.Map, palette: Palette) ThemeManager { + const is_dark = @import("color.zig").hasDarkBackground(environ_map); + return .{ + .current = .fromPalette(palette), + .is_dark = is_dark, + .palette_index = 0, + }; + } + + /// Switch to a specific palette. + pub fn setPalette(self: *ThemeManager, palette: Palette) void { + self.current = .fromPalette(palette); + } + + /// Switch to a named built-in palette by index. + pub fn setBuiltinByIndex(self: *ThemeManager, index: usize) void { + if (index < Palette.builtins.len) { + self.palette_index = index; + self.current = .fromPalette(Palette.builtins[index].palette); + } + } + + /// Cycle to the next built-in palette. + pub fn nextBuiltin(self: *ThemeManager) void { + self.palette_index = (self.palette_index + 1) % Palette.builtins.len; + self.current = .fromPalette(Palette.builtins[self.palette_index].palette); + } + + /// Cycle to the previous built-in palette. + pub fn prevBuiltin(self: *ThemeManager) void { + self.palette_index = if (self.palette_index == 0) Palette.builtins.len - 1 else self.palette_index - 1; + self.current = .fromPalette(Palette.builtins[self.palette_index].palette); + } + + /// Get the name of the current built-in palette. + pub fn currentName(self: *const ThemeManager) []const u8 { + return Palette.builtins[self.palette_index].name; + } + + /// Get the total number of built-in palettes. + pub fn builtinCount() usize { + return Palette.builtins.len; + } +}; + +/// Theme contains a palette and derived component styles. +pub const Theme = struct { + palette: Palette, + + // Derived styles for components + text: TextTheme, + list: ListTheme, + progress: ProgressTheme, + modal: ModalTheme, + notification: NotificationTheme, + tab: TabTheme, + + pub const TextTheme = struct { + text_fg: Color, + placeholder_fg: Color, + prompt_fg: Color, + border_fg: Color, + border_focus_fg: Color, + }; + + pub const ListTheme = struct { + item_fg: Color, + selected_fg: Color, + cursor_fg: Color, + filter_fg: Color, + }; + + pub const ProgressTheme = struct { + filled_fg: Color, + empty_fg: Color, + percent_fg: Color, + }; + + pub const ModalTheme = struct { + border_fg: Color, + title_fg: Color, + body_fg: Color, + button_fg: Color, + button_active_bg: Color, + }; + + pub const NotificationTheme = struct { + info_fg: Color, + success_fg: Color, + warning_fg: Color, + err_fg: Color, + }; + + pub const TabTheme = struct { + bar_fg: Color, + active_fg: Color, + active_bg: Color, + inactive_fg: Color, + }; + + /// Create a Theme from a Palette with sensible defaults. + pub fn fromPalette(p: Palette) Theme { + return .{ + .palette = p, + .text = .{ + .text_fg = p.foreground, + .placeholder_fg = p.subtle, + .prompt_fg = p.primary, + .border_fg = p.border_color, + .border_focus_fg = p.border_focus, + }, + .list = .{ + .item_fg = p.foreground, + .selected_fg = p.primary, + .cursor_fg = p.secondary, + .filter_fg = p.accent, + }, + .progress = .{ + .filled_fg = p.primary, + .empty_fg = p.subtle, + .percent_fg = p.foreground, + }, + .modal = .{ + .border_fg = p.border_color, + .title_fg = p.foreground, + .body_fg = p.muted, + .button_fg = p.foreground, + .button_active_bg = p.primary, + }, + .notification = .{ + .info_fg = p.info, + .success_fg = p.success, + .warning_fg = p.warning, + .err_fg = p.danger, + }, + .tab = .{ + .bar_fg = p.muted, + .active_fg = p.foreground, + .active_bg = p.primary, + .inactive_fg = p.subtle, + }, + }; + } + + /// Helper to create a Style with foreground color from the theme. + pub fn styleWith(fg: Color) style_mod.Style { + var s = style_mod.Style{}; + s = s.fg(fg); + s = s.inline_style(true); + return s; + } + + /// Helper to create a bold Style with foreground color. + pub fn boldStyleWith(fg: Color) style_mod.Style { + var s = style_mod.Style{}; + s = s.fg(fg); + s = s.bold(true); + s = s.inline_style(true); + return s; + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig new file mode 100644 index 0000000..5030d03 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig @@ -0,0 +1,372 @@ +//! ANSI escape sequence generation for terminal control. +//! Provides functions to generate standard terminal control sequences. + +const std = @import("std"); +const Writer = std.Io.Writer; + +/// ANSI escape codes +pub const ESC = "\x1b"; +pub const CSI = ESC ++ "["; +pub const OSC = ESC ++ "]"; +pub const DCS = ESC ++ "P"; +pub const APC = ESC ++ "_"; +pub const ST = ESC ++ "\\"; + +pub const OscTerminator = enum { + bel, + st, +}; + +pub const Osc52Passthrough = enum { + none, + tmux, + dcs, +}; + +// Cursor control +pub const cursor_hide = CSI ++ "?25l"; +pub const cursor_show = CSI ++ "?25h"; +pub const cursor_save = CSI ++ "s"; +pub const cursor_restore = CSI ++ "u"; +pub const cursor_home = CSI ++ "H"; + +// Screen control +pub const screen_clear = CSI ++ "2J"; +pub const screen_clear_below = CSI ++ "J"; +pub const screen_clear_above = CSI ++ "1J"; +pub const line_clear = CSI ++ "2K"; +pub const line_clear_right = CSI ++ "K"; +pub const line_clear_left = CSI ++ "1K"; + +// Alternate screen buffer +pub const alt_screen_enter = CSI ++ "?1049h"; +pub const alt_screen_exit = CSI ++ "?1049l"; + +// Text attributes reset +pub const reset = CSI ++ "0m"; + +// Bracketed paste mode +pub const bracketed_paste_enable = CSI ++ "?2004h"; +pub const bracketed_paste_disable = CSI ++ "?2004l"; + +// Synchronized output (prevents tearing) +pub const sync_start = CSI ++ "?2026h"; +pub const sync_end = CSI ++ "?2026l"; + +// Unicode width mode (DECRQM/DECSET private mode 2027) +pub const unicode_width_mode_query = CSI ++ "?2027$p"; +pub const unicode_width_mode_enable = CSI ++ "?2027h"; +pub const unicode_width_mode_disable = CSI ++ "?2027l"; + +// Kitty keyboard protocol +pub const kitty_keyboard_enable = CSI ++ ">1u"; +pub const kitty_keyboard_disable = CSI ++ " 0) try writer.print(CSI ++ "{d}A", .{n}); +} + +/// Move cursor down +pub fn cursorDown(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}B", .{n}); +} + +/// Move cursor forward (right) +pub fn cursorForward(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}C", .{n}); +} + +/// Move cursor backward (left) +pub fn cursorBack(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}D", .{n}); +} + +/// Move cursor to column (1-indexed) +pub fn cursorToCol(writer: *Writer, col: u16) !void { + try writer.print(CSI ++ "{d}G", .{col}); +} + +/// Move cursor to column (0-indexed) +pub fn cursorToCol0(writer: *Writer, col: u16) !void { + try writer.print(CSI ++ "{d}G", .{col + 1}); +} + +/// Request cursor position (response: ESC[row;colR) +pub fn requestCursorPos(writer: *Writer) !void { + try writer.writeAll(CSI ++ "6n"); +} + +/// Set scrolling region +pub fn setScrollRegion(writer: *Writer, top: u16, bottom: u16) !void { + try writer.print(CSI ++ "{d};{d}r", .{ top, bottom }); +} + +/// Reset scrolling region +pub fn resetScrollRegion(writer: *Writer) !void { + try writer.writeAll(CSI ++ "r"); +} + +/// Scroll up (content moves up, blank lines at bottom) +pub fn scrollUp(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}S", .{n}); +} + +/// Scroll down (content moves down, blank lines at top) +pub fn scrollDown(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}T", .{n}); +} + +/// Erase n characters from cursor position +pub fn eraseChars(writer: *Writer, n: u16) !void { + try writer.print(CSI ++ "{d}X", .{n}); +} + +/// Insert n blank lines at cursor position +pub fn insertLines(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}L", .{n}); +} + +/// Delete n lines at cursor position +pub fn deleteLines(writer: *Writer, n: u16) !void { + if (n > 0) try writer.print(CSI ++ "{d}M", .{n}); +} + +/// Set window title +pub fn setTitle(writer: *Writer, title: []const u8) !void { + try writer.print(OSC ++ "0;{s}\x07", .{title}); +} + +fn writeOscTerminator(writer: *Writer, terminator: OscTerminator) !void { + switch (terminator) { + .bel => try writer.writeAll("\x07"), + .st => try writer.writeAll(ST), + } +} + +fn writeEscapedForDcs(writer: *Writer, bytes: []const u8) !void { + var start: usize = 0; + for (bytes, 0..) |byte, idx| { + if (byte != 0x1b) continue; + + if (idx > start) { + try writer.writeAll(bytes[start..idx]); + } + try writer.writeAll(ESC ++ ESC); + start = idx + 1; + } + + if (start < bytes.len) { + try writer.writeAll(bytes[start..]); + } +} + +/// Start an OSC 52 sequence and write the fixed header: +/// `OSC 52 ; ;` +pub fn osc52Start( + writer: *Writer, + target: []const u8, + passthrough: Osc52Passthrough, +) !void { + switch (passthrough) { + .none => { + try writer.writeAll(OSC ++ "52;"); + try writer.writeAll(target); + try writer.writeAll(";"); + }, + .tmux => { + try writer.writeAll(DCS ++ "tmux;"); + try writeEscapedForDcs(writer, OSC ++ "52;"); + try writeEscapedForDcs(writer, target); + try writeEscapedForDcs(writer, ";"); + }, + .dcs => { + try writer.writeAll(DCS); + try writeEscapedForDcs(writer, OSC ++ "52;"); + try writeEscapedForDcs(writer, target); + try writeEscapedForDcs(writer, ";"); + }, + } +} + +/// Finish an OSC 52 sequence started by `osc52Start`. +pub fn osc52End(writer: *Writer, terminator: OscTerminator, passthrough: Osc52Passthrough) !void { + switch (passthrough) { + .none => try writeOscTerminator(writer, terminator), + .tmux, .dcs => { + switch (terminator) { + .bel => try writer.writeAll("\x07"), + .st => try writer.writeAll(ESC ++ ESC ++ "\\"), + } + try writer.writeAll(ST); + }, + } +} + +/// Write a complete OSC 52 sequence with a pre-encoded base64 payload. +pub fn osc52Encoded( + writer: *Writer, + target: []const u8, + payload_b64: []const u8, + terminator: OscTerminator, + passthrough: Osc52Passthrough, +) !void { + try osc52Start(writer, target, passthrough); + try writer.writeAll(payload_b64); + try osc52End(writer, terminator, passthrough); +} + +/// SGR (Select Graphic Rendition) codes +pub const SGR = struct { + pub const reset = 0; + pub const bold = 1; + pub const dim = 2; + pub const italic = 3; + pub const underline = 4; + pub const blink = 5; + pub const blink_rapid = 6; + pub const reverse = 7; + pub const hidden = 8; + pub const strikethrough = 9; + + pub const no_bold = 22; + pub const no_italic = 23; + pub const no_underline = 24; + pub const no_blink = 25; + pub const no_reverse = 27; + pub const no_hidden = 28; + pub const no_strikethrough = 29; + + // Foreground colors + pub const fg_black = 30; + pub const fg_red = 31; + pub const fg_green = 32; + pub const fg_yellow = 33; + pub const fg_blue = 34; + pub const fg_magenta = 35; + pub const fg_cyan = 36; + pub const fg_white = 37; + pub const fg_default = 39; + + // Background colors + pub const bg_black = 40; + pub const bg_red = 41; + pub const bg_green = 42; + pub const bg_yellow = 43; + pub const bg_blue = 44; + pub const bg_magenta = 45; + pub const bg_cyan = 46; + pub const bg_white = 47; + pub const bg_default = 49; + + // Bright foreground colors + pub const fg_bright_black = 90; + pub const fg_bright_red = 91; + pub const fg_bright_green = 92; + pub const fg_bright_yellow = 93; + pub const fg_bright_blue = 94; + pub const fg_bright_magenta = 95; + pub const fg_bright_cyan = 96; + pub const fg_bright_white = 97; + + // Bright background colors + pub const bg_bright_black = 100; + pub const bg_bright_red = 101; + pub const bg_bright_green = 102; + pub const bg_bright_yellow = 103; + pub const bg_bright_blue = 104; + pub const bg_bright_magenta = 105; + pub const bg_bright_cyan = 106; + pub const bg_bright_white = 107; +}; + +/// Generate SGR sequence +pub fn sgr(writer: *Writer, codes: []const u8) !void { + try writer.writeAll(CSI); + for (codes, 0..) |code, i| { + if (i > 0) try writer.writeByte(';'); + try writer.print("{d}", .{code}); + } + try writer.writeByte('m'); +} + +/// Generate 256-color foreground +pub fn fg256(writer: *Writer, color: u8) !void { + try writer.print(CSI ++ "38;5;{d}m", .{color}); +} + +/// Generate 256-color background +pub fn bg256(writer: *Writer, color: u8) !void { + try writer.print(CSI ++ "48;5;{d}m", .{color}); +} + +/// Generate true color (24-bit) foreground +pub fn fgRgb(writer: *Writer, r: u8, g: u8, b: u8) !void { + try writer.print(CSI ++ "38;2;{d};{d};{d}m", .{ r, g, b }); +} + +/// Generate true color (24-bit) background +pub fn bgRgb(writer: *Writer, r: u8, g: u8, b: u8) !void { + try writer.print(CSI ++ "48;2;{d};{d};{d}m", .{ r, g, b }); +} + +/// Hyperlink (OSC 8) +pub fn hyperlink(writer: *Writer, url: []const u8, text: []const u8) !void { + try writer.print(OSC ++ "8;;{s}\x07{s}" ++ OSC ++ "8;;\x07", .{ url, text }); +} + +/// Kitty graphics protocol command (APC G ... ST) +pub fn kittyGraphics(writer: *Writer, params: []const u8, payload: []const u8) !void { + try writer.writeAll(APC ++ "G"); + try writer.writeAll(params); + try writer.writeAll(";"); + try writer.writeAll(payload); + try writer.writeAll(ST); +} + +/// iTerm2 inline image command (OSC 1337;File=...:... BEL) +pub fn iterm2InlineImage(writer: *Writer, params: []const u8, payload: []const u8) !void { + try writer.writeAll(OSC ++ "1337;File="); + try writer.writeAll(params); + try writer.writeAll(":"); + try writer.writeAll(payload); + try writer.writeAll("\x07"); +} + +test "osc52Encoded direct BEL" { + var buf: [128]u8 = undefined; + var writer: Writer = .fixed(&buf); + try osc52Encoded(&writer, "c", "YQ==", .bel, .none); + try std.testing.expectEqualStrings("\x1b]52;c;YQ==\x07", writer.buffered()); +} + +test "osc52Encoded direct ST" { + var buf: [128]u8 = undefined; + var writer: Writer = .fixed(&buf); + try osc52Encoded(&writer, "c", "YQ==", .st, .none); + try std.testing.expectEqualStrings("\x1b]52;c;YQ==\x1b\\", writer.buffered()); +} + +test "osc52Encoded tmux passthrough BEL" { + var buf: [256]u8 = undefined; + var writer: Writer = .fixed(&buf); + try osc52Encoded(&writer, "c", "YQ==", .bel, .tmux); + try std.testing.expectEqualStrings("\x1bPtmux;\x1b\x1b]52;c;YQ==\x07\x1b\\", writer.buffered()); +} + +test "osc52Encoded tmux passthrough ST" { + var buf: [256]u8 = undefined; + var writer: Writer = .fixed(&buf); + try osc52Encoded(&writer, "c", "YQ==", .st, .tmux); + try std.testing.expectEqualStrings("\x1bPtmux;\x1b\x1b]52;c;YQ==\x1b\x1b\\\x1b\\", writer.buffered()); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig new file mode 100644 index 0000000..b1261bb --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig @@ -0,0 +1,204 @@ +//! POSIX terminal implementation for Unix-like systems. +//! Handles raw mode, terminal size, and signal handling. + +const std = @import("std"); +const Writer = std.Io.Writer; +const posix = std.posix; +const ansi = @import("../ansi.zig"); + +pub const TerminalError = error{ + NotATty, + GetAttrFailed, + SetAttrFailed, + IoctlFailed, + PipeFailed, + SignalSetupFailed, +}; + +/// Terminal size +pub const Size = struct { + rows: u16, + cols: u16, +}; + +/// Original terminal state for restoration +pub const State = struct { + original_termios: ?posix.termios = null, + in_raw_mode: bool = false, + in_alt_screen: bool = false, + mouse_enabled: bool = false, + stdin_fd: posix.fd_t, + stdout_fd: posix.fd_t, + + pub fn init() State { + return .{ + .stdin_fd = posix.STDIN_FILENO, + .stdout_fd = posix.STDOUT_FILENO, + }; + } +}; + +/// Check if a file descriptor is a TTY by probing for terminal window size. +/// Replaces `posix.isatty`, which was removed in Zig 0.16; a successful +/// `TIOCGWINSZ` ioctl is only granted to terminal devices. +pub fn isTty(fd: posix.fd_t) bool { + var wsz: posix.winsize = undefined; + return posix.system.ioctl(fd, posix.T.IOCGWINSZ, @intFromPtr(&wsz)) == 0; +} + +/// Get terminal size using ioctl (falls back to 80x24 for non-TTY) +pub fn getSize(fd: posix.fd_t) !Size { + var wsz: posix.winsize = undefined; + const result = posix.system.ioctl(fd, posix.T.IOCGWINSZ, @intFromPtr(&wsz)); + if (result != 0) { + // Fallback to default size for non-TTY (e.g. pipes) + if (!isTty(fd)) { + return .{ .rows = 24, .cols = 80 }; + } + return TerminalError.IoctlFailed; + } + return .{ + .rows = wsz.row, + .cols = wsz.col, + }; +} + +/// Enable raw mode on the terminal +pub fn enableRawMode(state: *State) !void { + if (state.in_raw_mode) return; + + if (!isTty(state.stdin_fd)) { + // Non-TTY (e.g. pipe) — skip raw mode setup but mark as active + state.in_raw_mode = true; + return; + } + + // Save original settings + state.original_termios = posix.tcgetattr(state.stdin_fd) catch { + return TerminalError.GetAttrFailed; + }; + + var raw = state.original_termios.?; + + // Input flags: disable various input processing + raw.iflag.BRKINT = false; + raw.iflag.ICRNL = false; + raw.iflag.INPCK = false; + raw.iflag.ISTRIP = false; + raw.iflag.IXON = false; + + // Output flags: disable output processing + raw.oflag.OPOST = false; + + // Control flags: set 8-bit characters + raw.cflag.CSIZE = .CS8; + + // Local flags: disable echo, canonical mode, signals, extended input + raw.lflag.ECHO = false; + raw.lflag.ICANON = false; + raw.lflag.IEXTEN = false; + raw.lflag.ISIG = false; + + // Control characters: set read timeout + raw.cc[@intFromEnum(posix.V.MIN)] = 0; + raw.cc[@intFromEnum(posix.V.TIME)] = 1; // 0.1 seconds + + posix.tcsetattr(state.stdin_fd, .FLUSH, raw) catch { + return TerminalError.SetAttrFailed; + }; + + state.in_raw_mode = true; +} + +/// Disable raw mode and restore original settings +pub fn disableRawMode(state: *State) void { + if (!state.in_raw_mode) return; + + if (state.original_termios) |termios| { + posix.tcsetattr(state.stdin_fd, .FLUSH, termios) catch {}; + } + + state.in_raw_mode = false; +} + +/// Enter alternate screen buffer +pub fn enterAltScreen(state: *State, writer: *Writer) !void { + if (state.in_alt_screen) return; + + try writer.writeAll(ansi.alt_screen_enter); + state.in_alt_screen = true; +} + +/// Exit alternate screen buffer +pub fn exitAltScreen(state: *State, writer: *Writer) !void { + if (!state.in_alt_screen) return; + + try writer.writeAll(ansi.alt_screen_exit); + state.in_alt_screen = false; +} + +/// Enable mouse tracking +pub fn enableMouse(state: *State, writer: *Writer) !void { + if (state.mouse_enabled) return; + + // Enable SGR mouse mode with all motion tracking + try writer.writeAll("\x1b[?1003h\x1b[?1006h"); + state.mouse_enabled = true; +} + +/// Disable mouse tracking +pub fn disableMouse(state: *State, writer: *Writer) !void { + if (!state.mouse_enabled) return; + + try writer.writeAll("\x1b[?1006l\x1b[?1003l"); + state.mouse_enabled = false; +} + +/// Read available input with timeout +pub fn readInput(state: *State, buffer: []u8, timeout_ms: i32) !usize { + var pollfds = [_]posix.pollfd{ + .{ + .fd = state.stdin_fd, + .events = posix.POLL.IN, + .revents = 0, + }, + }; + + const result = posix.poll(&pollfds, timeout_ms) catch return 0; + + if (result > 0 and (pollfds[0].revents & posix.POLL.IN) != 0) { + return posix.read(state.stdin_fd, buffer) catch 0; + } + + return 0; +} + +/// Flush output +pub fn flush(fd: posix.fd_t) void { + _ = posix.system.fsync(fd); +} + +/// Signal handler state (for SIGWINCH) +var resize_signaled: std.atomic.Value(bool) = std.atomic.Value(bool).init(false); + +/// Setup signal handlers +pub fn setupSignals() !void { + const handler = posix.Sigaction{ + .handler = .{ + .handler = struct { + fn handle(_: posix.SIG) callconv(.c) void { + resize_signaled.store(true, .release); + } + }.handle, + }, + .mask = posix.sigemptyset(), + .flags = 0, + }; + + posix.sigaction(posix.SIG.WINCH, &handler, null); +} + +/// Check if resize was signaled +pub fn checkResize() bool { + return resize_signaled.swap(false, .acquire); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig new file mode 100644 index 0000000..8fdf695 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig @@ -0,0 +1,178 @@ +//! WebAssembly terminal implementation. +//! Communicates with a JavaScript host via imported/exported functions. +//! The JS host is responsible for rendering output to an xterm.js terminal +//! or similar browser-based terminal emulator. + +const std = @import("std"); +const Writer = std.Io.Writer; +const ansi = @import("../ansi.zig"); + +pub const TerminalError = error{ + NotATty, + GetAttrFailed, + SetAttrFailed, +}; + +/// Terminal size +pub const Size = struct { + rows: u16, + cols: u16, +}; + +// ── JS host imports ────────────────────────────────────────────────── +// The JavaScript host must provide these functions. + +extern "zigzag" fn jsWrite(ptr: [*]const u8, len: usize) void; +extern "zigzag" fn jsReadInput(ptr: [*]u8, max_len: usize) usize; +extern "zigzag" fn jsGetWidth() u16; +extern "zigzag" fn jsGetHeight() u16; +extern "zigzag" fn jsSetTitle(ptr: [*]const u8, len: usize) void; + +/// Terminal state for WASM +pub const State = struct { + in_raw_mode: bool = false, + in_alt_screen: bool = false, + mouse_enabled: bool = false, + width: u16 = 80, + height: u16 = 24, + /// Buffer for batching writes before flush. + output_buf: std.array_list.Managed(u8) = undefined, + output_buf_initialized: bool = false, + + pub fn init() State { + return .{}; + } +}; + +/// WASM is always considered a TTY (the JS host provides the terminal). +pub fn isTty(_: anytype) bool { + return true; +} + +/// Get terminal size from the JS host. +pub fn getSize(_: anytype) !Size { + return .{ + .rows = jsGetHeight(), + .cols = jsGetWidth(), + }; +} + +/// Enable raw mode (no-op for WASM, the JS host handles input modes). +pub fn enableRawMode(state: *State) !void { + state.in_raw_mode = true; +} + +/// Disable raw mode. +pub fn disableRawMode(state: *State) void { + state.in_raw_mode = false; +} + +/// Enter alternate screen buffer. +pub fn enterAltScreen(state: *State, writer: *Writer) !void { + if (state.in_alt_screen) return; + try writer.writeAll(ansi.alt_screen_enter); + state.in_alt_screen = true; +} + +/// Exit alternate screen buffer. +pub fn exitAltScreen(state: *State, writer: *Writer) !void { + if (!state.in_alt_screen) return; + try writer.writeAll(ansi.alt_screen_exit); + state.in_alt_screen = false; +} + +/// Enable mouse tracking. +pub fn enableMouse(state: *State, writer: *Writer) !void { + if (state.mouse_enabled) return; + try writer.writeAll("\x1b[?1003h\x1b[?1006h"); + state.mouse_enabled = true; +} + +/// Disable mouse tracking. +pub fn disableMouse(state: *State, writer: *Writer) !void { + if (!state.mouse_enabled) return; + try writer.writeAll("\x1b[?1006l\x1b[?1003l"); + state.mouse_enabled = false; +} + +/// Read available input from the JS host. +pub fn readInput(_: *State, buffer: []u8, _: i32) !usize { + return jsReadInput(buffer.ptr, buffer.len); +} + +/// Flush output to the JS host. +pub fn flush(_: anytype) void { + // Flushing is handled by the writer calling jsWrite directly. +} + +/// Setup signal handlers (no-op for WASM). +pub fn setupSignals() !void {} + +/// Check if resize was signaled. +/// The JS host should call the exported `zigzagResize` to signal this. +var resize_signaled: bool = false; + +pub fn checkResize() bool { + if (@atomicLoad(bool, &resize_signaled, .monotonic)) { + @atomicStore(bool, &resize_signaled, false, .monotonic); + return true; + } + return false; +} + +// ── Exported functions for the JS host to call ────────────────────── + +/// Called by JS when the terminal is resized. +export fn zigzagResize() void { + @atomicStore(bool, &resize_signaled, true, .monotonic); +} + +/// Called by JS to get a pointer to a write buffer. +/// The JS host writes input bytes here, then calls `jsReadInput` to report count. +var input_ring: [4096]u8 = undefined; +var input_write_pos: usize = 0; + +export fn zigzagInputBuffer() [*]u8 { + return &input_ring; +} + +export fn zigzagInputBufferLen() usize { + return input_ring.len; +} + +export fn zigzagPushInput(len: usize) void { + input_write_pos = @min(len, input_ring.len); +} + +/// Unbuffered `std.Io.Writer` adapter that drains bytes to the JS host. +pub const WasmWriter = struct { + writer: Writer, + + const vtable: Writer.VTable = .{ .drain = drain }; + + pub fn init() WasmWriter { + return .{ .writer = .{ .vtable = &vtable, .buffer = &.{} } }; + } + + fn drain(_: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { + // Empty data == pure flush; the splat pattern lives at the last + // element so we must early-return before indexing. + if (data.len == 0) return 0; + + var consumed: usize = 0; + if (data.len > 1) for (data[0 .. data.len - 1]) |chunk| { + if (chunk.len == 0) continue; + jsWrite(chunk.ptr, chunk.len); + consumed += chunk.len; + }; + const pattern = data[data.len - 1]; + if (pattern.len > 0 and splat > 0) { + var i: usize = 0; + while (i < splat) : (i += 1) jsWrite(pattern.ptr, pattern.len); + consumed += pattern.len * splat; + } + return consumed; + } +}; + +pub var wasm_writer_instance: WasmWriter = .init(); diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig new file mode 100644 index 0000000..d370a20 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig @@ -0,0 +1,346 @@ +//! Windows terminal implementation using Console API. +//! Provides terminal control for Windows systems. + +const std = @import("std"); +const Writer = std.Io.Writer; +const windows = std.os.windows; +const ansi = @import("../ansi.zig"); + +pub const TerminalError = error{ + NotATty, + GetAttrFailed, + SetAttrFailed, + GetConsoleFailed, + SetConsoleFailed, + InvalidHandle, +}; + +/// Terminal size +pub const Size = struct { + rows: u16, + cols: u16, +}; + +/// Console mode flags +const ENABLE_VIRTUAL_TERMINAL_PROCESSING: windows.DWORD = 0x0004; +const ENABLE_VIRTUAL_TERMINAL_INPUT: windows.DWORD = 0x0200; +const ENABLE_PROCESSED_INPUT: windows.DWORD = 0x0001; +const ENABLE_LINE_INPUT: windows.DWORD = 0x0002; +const ENABLE_ECHO_INPUT: windows.DWORD = 0x0004; +const ENABLE_MOUSE_INPUT: windows.DWORD = 0x0010; +const ENABLE_WINDOW_INPUT: windows.DWORD = 0x0008; +const ENABLE_EXTENDED_FLAGS: windows.DWORD = 0x0080; +const ENABLE_QUICK_EDIT_MODE: windows.DWORD = 0x0040; +const FILE_TYPE_CHAR: windows.DWORD = 0x0002; +const FILE_TYPE_PIPE: windows.DWORD = 0x0003; +const KEY_EVENT: windows.WORD = 0x0001; +const MOUSE_EVENT: windows.WORD = 0x0002; +const INFINITE: windows.DWORD = 0xFFFFFFFF; +const WAIT_OBJECT_0: windows.DWORD = 0x00000000; +const CP_UTF8: windows.UINT = 65001; + +/// Terminal state for Windows +pub const State = struct { + original_input_mode: windows.DWORD = 0, + original_output_mode: windows.DWORD = 0, + original_output_cp: windows.UINT = 0, + original_input_cp: windows.UINT = 0, + in_raw_mode: bool = false, + in_alt_screen: bool = false, + mouse_enabled: bool = false, + stdin_handle: windows.HANDLE, + stdout_handle: windows.HANDLE, + + pub fn init() State { + return .{ + .stdin_handle = std.Io.File.stdin().handle, + .stdout_handle = std.Io.File.stdout().handle, + }; + } +}; + +/// External Windows API declarations +extern "kernel32" fn GetConsoleMode(hConsole: windows.HANDLE, lpMode: *windows.DWORD) callconv(.winapi) windows.BOOL; +extern "kernel32" fn SetConsoleMode(hConsole: windows.HANDLE, dwMode: windows.DWORD) callconv(.winapi) windows.BOOL; +extern "kernel32" fn GetConsoleScreenBufferInfo(hConsole: windows.HANDLE, lpInfo: *CONSOLE_SCREEN_BUFFER_INFO) callconv(.winapi) windows.BOOL; +extern "kernel32" fn GetFileType(hFile: windows.HANDLE) callconv(.winapi) windows.DWORD; +extern "kernel32" fn PeekNamedPipe( + hNamedPipe: windows.HANDLE, + lpBuffer: ?*anyopaque, + nBufferSize: windows.DWORD, + lpBytesRead: ?*windows.DWORD, + lpTotalBytesAvail: ?*windows.DWORD, + lpBytesLeftThisMessage: ?*windows.DWORD, +) callconv(.winapi) windows.BOOL; +extern "kernel32" fn GetNumberOfConsoleInputEvents( + hConsoleInput: windows.HANDLE, + lpcNumberOfEvents: *windows.DWORD, +) callconv(.winapi) windows.BOOL; +extern "kernel32" fn PeekConsoleInputW( + hConsoleInput: windows.HANDLE, + lpBuffer: [*]INPUT_RECORD, + nLength: windows.DWORD, + lpNumberOfEventsRead: *windows.DWORD, +) callconv(.winapi) windows.BOOL; +extern "kernel32" fn ReadConsoleInputW( + hConsoleInput: windows.HANDLE, + lpBuffer: [*]INPUT_RECORD, + nLength: windows.DWORD, + lpNumberOfEventsRead: *windows.DWORD, +) callconv(.winapi) windows.BOOL; +extern "kernel32" fn WaitForSingleObject( + hHandle: windows.HANDLE, + dwMilliseconds: windows.DWORD, +) callconv(.winapi) windows.DWORD; +extern "kernel32" fn ReadFile( + hFile: windows.HANDLE, + lpBuffer: [*]u8, + nNumberOfBytesToRead: windows.DWORD, + lpNumberOfBytesRead: ?*windows.DWORD, + lpOverlapped: ?*anyopaque, +) callconv(.winapi) windows.BOOL; +extern "kernel32" fn GetConsoleOutputCP() callconv(.winapi) windows.UINT; +extern "kernel32" fn SetConsoleOutputCP(wCodePageID: windows.UINT) callconv(.winapi) windows.BOOL; +extern "kernel32" fn GetConsoleCP() callconv(.winapi) windows.UINT; +extern "kernel32" fn SetConsoleCP(wCodePageID: windows.UINT) callconv(.winapi) windows.BOOL; + +const CONSOLE_SCREEN_BUFFER_INFO = extern struct { + dwSize: COORD, + dwCursorPosition: COORD, + wAttributes: windows.WORD, + srWindow: SMALL_RECT, + dwMaximumWindowSize: COORD, +}; + +const COORD = extern struct { + X: windows.SHORT, + Y: windows.SHORT, +}; + +const SMALL_RECT = extern struct { + Left: windows.SHORT, + Top: windows.SHORT, + Right: windows.SHORT, + Bottom: windows.SHORT, +}; + +const INPUT_RECORD = extern struct { + EventType: windows.WORD, + Event: INPUT_EVENT, +}; + +const INPUT_EVENT = extern union { + KeyEvent: KEY_EVENT_RECORD, + MouseEvent: [16]u8, + WindowBufferSizeEvent: [4]u8, + MenuEvent: [4]u8, + FocusEvent: [4]u8, +}; + +const KEY_EVENT_RECORD = extern struct { + bKeyDown: windows.BOOL, + wRepeatCount: windows.WORD, + wVirtualKeyCode: windows.WORD, + wVirtualScanCode: windows.WORD, + uChar: extern union { + UnicodeChar: windows.WCHAR, + AsciiChar: windows.CHAR, + }, + dwControlKeyState: windows.DWORD, +}; + +/// Check if a handle is valid +pub fn isTty(handle: windows.HANDLE) bool { + if (handle == windows.INVALID_HANDLE_VALUE) return false; + var mode: windows.DWORD = 0; + return GetConsoleMode(handle, &mode).toBool(); +} + +/// Get terminal size +pub fn getSize(handle: windows.HANDLE) !Size { + var info: CONSOLE_SCREEN_BUFFER_INFO = undefined; + if (!GetConsoleScreenBufferInfo(handle, &info).toBool()) { + return TerminalError.GetConsoleFailed; + } + return .{ + .rows = @intCast(info.srWindow.Bottom - info.srWindow.Top + 1), + .cols = @intCast(info.srWindow.Right - info.srWindow.Left + 1), + }; +} + +/// Enable raw mode +pub fn enableRawMode(state: *State) !void { + if (state.in_raw_mode) return; + + if (state.stdin_handle == windows.INVALID_HANDLE_VALUE or + state.stdout_handle == windows.INVALID_HANDLE_VALUE) + { + return TerminalError.InvalidHandle; + } + + // Save original modes + if (!GetConsoleMode(state.stdin_handle, &state.original_input_mode).toBool()) { + return TerminalError.GetConsoleFailed; + } + if (!GetConsoleMode(state.stdout_handle, &state.original_output_mode).toBool()) { + return TerminalError.GetConsoleFailed; + } + + // Set input mode for raw input with VT processing. + // Avoid WINDOW_INPUT because it can signal wait handles without producing bytes for ReadFile. + const input_mode: windows.DWORD = ENABLE_VIRTUAL_TERMINAL_INPUT; + if (!SetConsoleMode(state.stdin_handle, input_mode).toBool()) { + return TerminalError.SetConsoleFailed; + } + + // Enable VT processing on output + const output_mode: windows.DWORD = state.original_output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (!SetConsoleMode(state.stdout_handle, output_mode).toBool()) { + // Restore input mode and fail + _ = SetConsoleMode(state.stdin_handle, state.original_input_mode); + return TerminalError.SetConsoleFailed; + } + + // Switch the console code pages to UTF-8 so multi-byte sequences (box-drawing, + // emoji, etc.) emitted by the renderer aren't reinterpreted as the OEM codepage. + state.original_output_cp = GetConsoleOutputCP(); + state.original_input_cp = GetConsoleCP(); + _ = SetConsoleOutputCP(CP_UTF8); + _ = SetConsoleCP(CP_UTF8); + + state.in_raw_mode = true; +} + +/// Disable raw mode +pub fn disableRawMode(state: *State) void { + if (!state.in_raw_mode) return; + + _ = SetConsoleMode(state.stdin_handle, state.original_input_mode); + _ = SetConsoleMode(state.stdout_handle, state.original_output_mode); + if (state.original_output_cp != 0) _ = SetConsoleOutputCP(state.original_output_cp); + if (state.original_input_cp != 0) _ = SetConsoleCP(state.original_input_cp); + + state.in_raw_mode = false; +} + +/// Enter alternate screen buffer +pub fn enterAltScreen(state: *State, writer: *Writer) !void { + if (state.in_alt_screen) return; + + try writer.writeAll(ansi.alt_screen_enter); + state.in_alt_screen = true; +} + +/// Exit alternate screen buffer +pub fn exitAltScreen(state: *State, writer: *Writer) !void { + if (!state.in_alt_screen) return; + + try writer.writeAll(ansi.alt_screen_exit); + state.in_alt_screen = false; +} + +/// Enable mouse tracking +pub fn enableMouse(state: *State, writer: *Writer) !void { + if (state.mouse_enabled) return; + + // Enable mouse input in console mode + if (state.stdin_handle != windows.INVALID_HANDLE_VALUE) { + var mode: windows.DWORD = 0; + if (GetConsoleMode(state.stdin_handle, &mode).toBool()) { + _ = SetConsoleMode(state.stdin_handle, mode | ENABLE_MOUSE_INPUT); + } + } + + // Also send ANSI sequences for VT mode + try writer.writeAll("\x1b[?1003h\x1b[?1006h"); + state.mouse_enabled = true; +} + +/// Disable mouse tracking +pub fn disableMouse(state: *State, writer: *Writer) !void { + if (!state.mouse_enabled) return; + + try writer.writeAll("\x1b[?1006l\x1b[?1003l"); + state.mouse_enabled = false; +} + +/// Read available input (Windows uses std.Io) +pub fn readInput(state: *State, buffer: []u8, timeout_ms: i32) !usize { + if (state.stdin_handle == windows.INVALID_HANDLE_VALUE) return 0; + + // Match POSIX behavior: wait up to timeout_ms for input, then return 0. + const wait_ms: windows.DWORD = if (timeout_ms < 0) + INFINITE + else + @intCast(timeout_ms); + + if (WaitForSingleObject(state.stdin_handle, wait_ms) != WAIT_OBJECT_0) return 0; + + const file_type = GetFileType(state.stdin_handle); + + // ConPTY/Windows Terminal can expose stdin as a pipe. Ensure there are bytes before reading. + if (file_type == FILE_TYPE_PIPE) { + var available: windows.DWORD = 0; + if (!PeekNamedPipe(state.stdin_handle, null, 0, null, &available, null).toBool() or available == 0) { + return 0; + } + } + + // Console handles may wake due non-byte events (focus/menu/window-size). Drain those first. + if (file_type == FILE_TYPE_CHAR and !hasReadableConsoleInput(state.stdin_handle)) { + return 0; + } + + // Read from the configured stdin handle after it is signaled as readable. + var bytes_read: windows.DWORD = 0; + if (!ReadFile(state.stdin_handle, buffer.ptr, @intCast(buffer.len), &bytes_read, null).toBool()) return 0; + return bytes_read; +} + +fn hasReadableConsoleInput(handle: windows.HANDLE) bool { + var record_buf: [1]INPUT_RECORD = undefined; + + while (true) { + var event_count: windows.DWORD = 0; + if (!GetNumberOfConsoleInputEvents(handle, &event_count).toBool() or event_count == 0) { + return false; + } + + var peeked: windows.DWORD = 0; + if (!PeekConsoleInputW(handle, &record_buf, 1, &peeked).toBool() or peeked == 0) { + return false; + } + + const record = record_buf[0]; + switch (record.EventType) { + KEY_EVENT => { + if (record.Event.KeyEvent.bKeyDown.toBool()) return true; + }, + MOUSE_EVENT => return true, + else => {}, + } + + var consumed: windows.DWORD = 0; + if (!ReadConsoleInputW(handle, &record_buf, 1, &consumed).toBool() or consumed == 0) { + return false; + } + } +} + +/// Flush output +pub fn flush(handle: windows.HANDLE) void { + _ = handle; + // Windows typically auto-flushes +} + +/// Setup signal handlers (Windows uses console events differently) +pub fn setupSignals() !void { + // Windows handles resize through WINDOW_BUFFER_SIZE_EVENT + // This is handled in the input loop +} + +/// Check if resize was signaled +pub fn checkResize() bool { + // On Windows, resize is handled through console events + return false; +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig new file mode 100644 index 0000000..e877467 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig @@ -0,0 +1,306 @@ +//! Screen buffer management for efficient terminal rendering. +//! Provides double-buffering to minimize flickering and optimize updates. + +const std = @import("std"); +const Writer = std.Io.Writer; +const ansi = @import("ansi.zig"); +const unicode = @import("../unicode.zig"); + +/// A cell in the screen buffer +pub const Cell = struct { + char: u21 = ' ', + fg: ?Color = null, + bg: ?Color = null, + bold: bool = false, + dim: bool = false, + italic: bool = false, + underline: bool = false, + blink: bool = false, + reverse: bool = false, + strikethrough: bool = false, + /// True if this cell is the continuation (right half) of a wide character. + wide: bool = false, + + pub fn eql(self: Cell, other: Cell) bool { + return self.char == other.char and + eqlOptColor(self.fg, other.fg) and + eqlOptColor(self.bg, other.bg) and + self.bold == other.bold and + self.dim == other.dim and + self.italic == other.italic and + self.underline == other.underline and + self.blink == other.blink and + self.reverse == other.reverse and + self.strikethrough == other.strikethrough and + self.wide == other.wide; + } + + fn eqlOptColor(a: ?Color, b: ?Color) bool { + if (a == null and b == null) return true; + if (a == null or b == null) return false; + return a.?.eql(b.?); + } +}; + +/// Color representation +pub const Color = struct { + r: u8, + g: u8, + b: u8, + + pub fn eql(self: Color, other: Color) bool { + return self.r == other.r and self.g == other.g and self.b == other.b; + } +}; + +/// Screen buffer for rendering +pub const Screen = struct { + allocator: std.mem.Allocator, + cells: []Cell, + width: u16, + height: u16, + + pub fn init(allocator: std.mem.Allocator, width: u16, height: u16) !Screen { + const size = @as(usize, width) * @as(usize, height); + const cells = try allocator.alloc(Cell, size); + @memset(cells, Cell{}); + + return .{ + .allocator = allocator, + .cells = cells, + .width = width, + .height = height, + }; + } + + pub fn deinit(self: *Screen) void { + self.allocator.free(self.cells); + } + + pub fn resize(self: *Screen, new_width: u16, new_height: u16) !void { + const new_size = @as(usize, new_width) * @as(usize, new_height); + const new_cells = try self.allocator.alloc(Cell, new_size); + @memset(new_cells, Cell{}); + + // Copy existing content + const copy_height = @min(self.height, new_height); + const copy_width = @min(self.width, new_width); + + for (0..copy_height) |y| { + const old_row_start = y * self.width; + const new_row_start = y * new_width; + @memcpy( + new_cells[new_row_start..][0..copy_width], + self.cells[old_row_start..][0..copy_width], + ); + } + + self.allocator.free(self.cells); + self.cells = new_cells; + self.width = new_width; + self.height = new_height; + } + + pub fn clear(self: *Screen) void { + @memset(self.cells, Cell{}); + } + + pub fn getCell(self: *const Screen, x: u16, y: u16) ?*const Cell { + if (x >= self.width or y >= self.height) return null; + return &self.cells[@as(usize, y) * self.width + x]; + } + + pub fn setCell(self: *Screen, x: u16, y: u16, cell: Cell) void { + if (x >= self.width or y >= self.height) return; + const idx = @as(usize, y) * self.width + x; + + // If we're overwriting a wide-char continuation cell, clear the left half + if (self.cells[idx].wide and x > 0) { + self.cells[idx - 1] = Cell{}; + } + // If we're overwriting the left half of a wide char, clear the continuation + if (!self.cells[idx].wide and x + 1 < self.width and self.cells[idx + 1].wide) { + self.cells[idx + 1] = Cell{}; + } + + self.cells[idx] = cell; + + // If this is a wide character, set the continuation cell + const cw = unicode.charWidth(cell.char); + if (cw == 2 and x + 1 < self.width) { + var cont = Cell{}; + cont.wide = true; + cont.fg = cell.fg; + cont.bg = cell.bg; + self.cells[idx + 1] = cont; + } + } + + pub fn setChar(self: *Screen, x: u16, y: u16, char: u21) void { + if (x >= self.width or y >= self.height) return; + var cell = self.cells[@as(usize, y) * self.width + x]; + cell.char = char; + cell.wide = false; + self.setCell(x, y, cell); + } + + /// Write a string to the screen at the given position + pub fn writeString(self: *Screen, x: u16, y: u16, str: []const u8) u16 { + var col = x; + var utf8 = std.unicode.Utf8View.init(str) catch return 0; + var iter = utf8.iterator(); + + while (iter.nextCodepoint()) |cp| { + const cw = unicode.charWidth(cp); + if (cw == 0) continue; // Skip zero-width characters + if (col + cw > self.width) break; // Wide char won't fit + self.setChar(col, y, cp); + col += @intCast(cw); + } + + return col - x; + } + + /// Render screen differences to the writer + pub fn renderDiff(self: *const Screen, prev: *const Screen, writer: *Writer) !void { + var last_x: u16 = 0; + var last_y: u16 = 0; + var need_move = true; + var current_cell = Cell{}; + + for (0..self.height) |y_usize| { + const y: u16 = @intCast(y_usize); + var x_usize: usize = 0; + while (x_usize < self.width) { + const x: u16 = @intCast(x_usize); + const idx = y_usize * self.width + x_usize; + const cell = self.cells[idx]; + + // Skip wide continuation cells + if (cell.wide) { + x_usize += 1; + need_move = true; + continue; + } + + const prev_cell = if (idx < prev.cells.len) prev.cells[idx] else Cell{}; + + if (!cell.eql(prev_cell)) { + // Need to update this cell + if (need_move or x != last_x + 1 or y != last_y) { + try ansi.cursorTo0(writer, y, x); + need_move = false; + } + + // Apply style changes + try applyStyle(writer, ¤t_cell, cell); + current_cell = cell; + + // Write character + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(cell.char, &buf) catch 1; + try writer.writeAll(buf[0..len]); + + const cw = unicode.charWidth(cell.char); + last_x = if (cw == 2) x + 1 else x; + last_y = y; + x_usize += cw; + } else { + x_usize += 1; + } + } + } + + // Reset styles at the end + try writer.writeAll(ansi.reset); + } + + /// Render entire screen to writer + pub fn render(self: *const Screen, writer: *Writer) !void { + try writer.writeAll(ansi.cursor_home); + try writer.writeAll(ansi.reset); + + var current_cell = Cell{}; + + for (0..self.height) |y_usize| { + if (y_usize > 0) { + try writer.writeAll("\r\n"); + } + + var x_usize: usize = 0; + while (x_usize < self.width) { + const idx = y_usize * self.width + x_usize; + const cell = self.cells[idx]; + + // Skip wide continuation cells + if (cell.wide) { + x_usize += 1; + continue; + } + + try applyStyle(writer, ¤t_cell, cell); + current_cell = cell; + + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(cell.char, &buf) catch 1; + try writer.writeAll(buf[0..len]); + + const cw = unicode.charWidth(cell.char); + x_usize += if (cw > 0) cw else 1; + } + } + + try writer.writeAll(ansi.reset); + } + + fn applyStyle(writer: *Writer, current: *Cell, new: Cell) !void { + var needs_reset = false; + + // Check if we need to reset (turning off attributes) + if ((current.bold and !new.bold) or + (current.dim and !new.dim) or + (current.italic and !new.italic) or + (current.underline and !new.underline) or + (current.blink and !new.blink) or + (current.reverse and !new.reverse) or + (current.strikethrough and !new.strikethrough)) + { + needs_reset = true; + try writer.writeAll(ansi.reset); + current.* = Cell{}; + } + + // Apply foreground color + if (!eqlOptColor(current.fg, new.fg)) { + if (new.fg) |fg| { + try ansi.fgRgb(writer, fg.r, fg.g, fg.b); + } else { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.fg_default}); + } + } + + // Apply background color + if (!eqlOptColor(current.bg, new.bg)) { + if (new.bg) |bg| { + try ansi.bgRgb(writer, bg.r, bg.g, bg.b); + } else { + try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bg_default}); + } + } + + // Apply text attributes + if (!current.bold and new.bold) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); + if (!current.dim and new.dim) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); + if (!current.italic and new.italic) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); + if (!current.underline and new.underline) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); + if (!current.blink and new.blink) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); + if (!current.reverse and new.reverse) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); + if (!current.strikethrough and new.strikethrough) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); + } + + fn eqlOptColor(a: ?Color, b: ?Color) bool { + if (a == null and b == null) return true; + if (a == null or b == null) return false; + return a.?.eql(b.?); + } +}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig new file mode 100644 index 0000000..0e07e58 --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig @@ -0,0 +1,1914 @@ +//! Terminal abstraction layer providing cross-platform terminal control. +//! Handles raw mode, alternate screen, mouse tracking, and input/output. + +const std = @import("std"); +const FixedWriter = std.Io.Writer.fixed; +const builtin = @import("builtin"); +pub const ansi = @import("ansi.zig"); +pub const screen = @import("screen.zig"); +const unicode = @import("../unicode.zig"); + +// Platform-specific implementation +const is_wasm = builtin.os.tag == .wasi or builtin.cpu.arch == .wasm32 or builtin.cpu.arch == .wasm64; +const platform = if (is_wasm) + @import("platform/wasm.zig") +else if (builtin.os.tag == .windows) + @import("platform/windows.zig") +else + @import("platform/posix.zig"); + +pub const Size = platform.Size; +pub const TerminalError = platform.TerminalError; + +pub const UnicodeWidthCapabilities = struct { + mode_2027: bool = false, + kitty_text_sizing: bool = false, + strategy: unicode.WidthStrategy = .legacy_wcwidth, +}; + +pub const ImageCapabilities = struct { + kitty_graphics: bool = false, + iterm2_inline_image: bool = false, + sixel: bool = false, +}; + +const Iterm2Capabilities = struct { + inline_image: bool = false, + sixel: bool = false, +}; + +pub const KittyImageFormat = enum(u16) { + rgb = 24, + rgba = 32, + png = 100, +}; + +pub const KittyImageOptions = struct { + format: KittyImageFormat = .png, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + /// Z-index for layering. Negative = behind text, positive = above. + z_index: ?i32 = null, + /// Enable unicode placeholders for text-reflow participation. + unicode_placeholder: bool = false, + /// Pixel width of the image (required for RGB/RGBA direct data). + pixel_width: ?u32 = null, + /// Pixel height of the image (required for RGB/RGBA direct data). + pixel_height: ?u32 = null, +}; + +pub const KittyImageFileOptions = struct { + width_cells: ?u16 = null, + height_cells: ?u16 = null, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// Options for transmitting an image to the Kitty cache without display. +pub const KittyTransmitOptions = struct { + image_id: u32, + format: KittyImageFormat = .png, + quiet: bool = true, + pixel_width: ?u32 = null, + pixel_height: ?u32 = null, +}; + +/// Options for placing a previously cached Kitty image. +pub const KittyPlaceOptions = struct { + image_id: u32, + placement_id: ?u32 = null, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + move_cursor: bool = true, + quiet: bool = true, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// What to delete from the Kitty image cache. +pub const KittyDeleteTarget = union(enum) { + by_id: u32, + by_placement: struct { image_id: u32, placement_id: u32 }, + all, +}; + +pub const Iterm2ImageFileOptions = struct { + width_cells: ?u16 = null, + height_cells: ?u16 = null, + preserve_aspect_ratio: bool = true, + move_cursor: bool = true, +}; + +/// Options for in-memory iTerm2 image rendering. +pub const Iterm2ImageDataOptions = struct { + width_cells: ?u16 = null, + height_cells: ?u16 = null, + preserve_aspect_ratio: bool = true, + move_cursor: bool = true, +}; + +pub const ImageFileOptions = struct { + width_cells: ?u16 = null, + height_cells: ?u16 = null, + preserve_aspect_ratio: bool = true, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// Options for rendering in-memory image data with auto protocol selection. +pub const ImageDataOptions = struct { + format: KittyImageFormat = .png, + pixel_width: ?u32 = null, + pixel_height: ?u32 = null, + width_cells: ?u16 = null, + height_cells: ?u16 = null, + preserve_aspect_ratio: bool = true, + image_id: ?u32 = null, + placement_id: ?u32 = null, + move_cursor: bool = true, + quiet: bool = true, + z_index: ?i32 = null, + unicode_placeholder: bool = false, +}; + +/// Preferred image protocol for protocol-selection overrides. +pub const ImageProtocol = enum { + auto, + kitty, + iterm2, + sixel, +}; + +pub const SixelImageFileOptions = struct { + /// Optional max captured converter output (bytes). + max_output_bytes: usize = 32 * 1024 * 1024, + /// Optional pixel width hint for img2sixel (-w flag). + width_pixels: ?u32 = null, + /// Optional pixel height hint for img2sixel (-h flag). + height_pixels: ?u32 = null, +}; + +/// OSC 52 clipboard target selector. +/// Standard values are `c`, `p`, `q`, `s`, or cut buffers `0`..`7`. +pub const Osc52Target = union(enum) { + clipboard, + primary, + secondary, + select, + cut_buffer: u3, + raw: []const u8, + + fn encode(self: Osc52Target, scratch: *[1]u8) []const u8 { + return switch (self) { + .clipboard => "c", + .primary => "p", + .secondary => "q", + .select => "s", + .cut_buffer => |n| blk: { + scratch[0] = @as(u8, '0') + @as(u8, n); + break :blk scratch[0..1]; + }, + .raw => |value| value, + }; + } +}; + +/// OSC 52 passthrough strategy. +/// `tmux` and `dcs` wrap OSC inside DCS passthrough for multiplexers. +pub const Osc52Passthrough = enum { + auto, + none, + tmux, + dcs, +}; + +/// Default OSC 52 behavior for this terminal instance. +pub const Osc52Config = struct { + /// Master switch for clipboard writes. + enabled: bool = true, + /// Allow OSC 52 clipboard queries (`?`) for reading clipboard content. + query_enabled: bool = true, + /// Require a TTY before sending OSC 52. + require_tty: bool = true, + /// Default target selection. + target: Osc52Target = .clipboard, + /// Sequence terminator (BEL is widely compatible). + terminator: ansi.OscTerminator = .bel, + /// Passthrough mode (`auto` detects tmux/screen-like environments). + passthrough: Osc52Passthrough = .auto, + /// Optional input payload limit (bytes). `null` = no library limit. + max_bytes: ?usize = null, + /// Query timeout for clipboard reads. + query_timeout_ms: i32 = 180, + /// Optional decoded output limit for clipboard reads. + max_read_bytes: ?usize = null, + /// Require selector match on responses (strict mode). + strict_query_target: bool = false, +}; + +/// Per-call OSC 52 overrides. +pub const Osc52WriteOptions = struct { + target: ?Osc52Target = null, + terminator: ?ansi.OscTerminator = null, + passthrough: ?Osc52Passthrough = null, + require_tty: ?bool = null, + max_bytes: ?usize = null, +}; + +/// Per-call OSC 52 clipboard query overrides. +pub const Osc52ReadOptions = struct { + target: ?Osc52Target = null, + terminator: ?ansi.OscTerminator = null, + passthrough: ?Osc52Passthrough = null, + require_tty: ?bool = null, + timeout_ms: ?i32 = null, + max_bytes: ?usize = null, + strict_target: ?bool = null, +}; + +/// Terminal configuration options +pub const Config = struct { + /// Use alternate screen buffer + alt_screen: bool = true, + /// Hide cursor during operation + hide_cursor: bool = true, + /// Enable mouse tracking + mouse: bool = false, + /// Enable bracketed paste mode + bracketed_paste: bool = true, + /// Custom input file (default: stdin) + input: ?std.Io.File = null, + /// Custom output file (default: stdout) + output: ?std.Io.File = null, + /// Enable Kitty keyboard protocol + kitty_keyboard: bool = false, + /// OSC 52 clipboard configuration + osc52: Osc52Config = .{}, +}; + +/// Terminal abstraction +pub const Terminal = struct { + io: std.Io, + environ_map: *const std.process.Environ.Map, + state: platform.State, + config: Config, + stdin: std.Io.File, + out: Writer, + pending_input: [8192]u8 = undefined, + pending_input_len: usize = 0, + unicode_width_caps: UnicodeWidthCapabilities = .{}, + image_caps: ImageCapabilities = .{}, + + pub fn init(io: std.Io, environ_map: *const std.process.Environ.Map, config: Config) !Terminal { + var state = platform.State.init(); + + var term: Terminal = if (is_wasm) .{ + .io = io, + .environ_map = environ_map, + .state = state, + .config = config, + .stdin = undefined, + .out = .init(io, {}), + } else blk: { + const stdout = config.output orelse std.Io.File.stdout(); + const stdin = config.input orelse std.Io.File.stdin(); + + // Apply custom fd overrides + if (builtin.os.tag != .windows) { + if (config.input) |inp| state.stdin_fd = inp.handle; + if (config.output) |o| state.stdout_fd = o.handle; + } else { + if (config.input) |inp| state.stdin_handle = inp.handle; + if (config.output) |o| state.stdout_handle = o.handle; + } + + break :blk .{ + .io = io, + .environ_map = environ_map, + .state = state, + .config = config, + .stdin = stdin, + .out = .init(io, stdout), + }; + }; + + try term.setup(); + return term; + } + + pub fn deinit(self: *Terminal) void { + self.cleanup(); + } + + pub fn setup(self: *Terminal) !void { + // Setup signal handlers + platform.setupSignals() catch {}; + + // Enable raw mode + try platform.enableRawMode(&self.state); + + // Enter alternate screen + if (self.config.alt_screen) { + try self.writeBytes(ansi.alt_screen_enter); + self.state.in_alt_screen = true; + } + + // Hide cursor + if (self.config.hide_cursor) { + try self.writeBytes(ansi.cursor_hide); + } + + // Enable mouse + if (self.config.mouse) { + try self.writeBytes("\x1b[?1003h\x1b[?1006h"); + self.state.mouse_enabled = true; + } + + // Enable bracketed paste + if (self.config.bracketed_paste) { + try self.writeBytes(ansi.bracketed_paste_enable); + } + + // Enable Kitty keyboard protocol + if (self.config.kitty_keyboard) { + try self.writeBytes(ansi.kitty_keyboard_enable); + } + + self.detectUnicodeWidthCapabilities(); + self.detectImageCapabilities(); + + // Clear screen + try self.writeBytes(ansi.screen_clear); + try self.writeBytes(ansi.cursor_home); + + try self.flush(); + } + + pub fn cleanup(self: *Terminal) void { + // Disable Kitty keyboard protocol + if (self.config.kitty_keyboard) { + self.writeBytes(ansi.kitty_keyboard_disable) catch {}; + } + + if (self.unicode_width_caps.mode_2027) { + self.writeBytes(ansi.unicode_width_mode_disable) catch {}; + self.unicode_width_caps.mode_2027 = false; + } + + // Disable bracketed paste + if (self.config.bracketed_paste) { + self.writeBytes(ansi.bracketed_paste_disable) catch {}; + } + + // Disable mouse + if (self.state.mouse_enabled) { + self.writeBytes("\x1b[?1006l\x1b[?1003l") catch {}; + self.state.mouse_enabled = false; + } + + // Show cursor + if (self.config.hide_cursor) { + self.writeBytes(ansi.cursor_show) catch {}; + } + + // Exit alternate screen + if (self.state.in_alt_screen) { + self.writeBytes(ansi.alt_screen_exit) catch {}; + self.state.in_alt_screen = false; + } + + // Reset attributes + self.writeBytes(ansi.reset) catch {}; + + self.flush() catch {}; + + // Restore terminal mode — always runs even if writes above failed + platform.disableRawMode(&self.state); + } + + /// Write bytes through the buffered terminal writer. + fn writeBytes(self: *Terminal, bytes: []const u8) !void { + try self.writer().writeAll(bytes); + } + + /// Get terminal size + pub fn getSize(self: *Terminal) !Size { + if (is_wasm) { + return platform.getSize({}); + } else if (builtin.os.tag == .windows) { + return platform.getSize(self.state.stdout_handle); + } else { + return platform.getSize(self.state.stdout_fd); + } + } + + /// Read input with timeout (in milliseconds) + pub fn readInput(self: *Terminal, buffer: []u8, timeout_ms: i32) !usize { + if (self.pending_input_len > 0) { + const take = @min(buffer.len, self.pending_input_len); + @memcpy(buffer[0..take], self.pending_input[0..take]); + if (take < self.pending_input_len) { + std.mem.copyForwards(u8, self.pending_input[0 .. self.pending_input_len - take], self.pending_input[take..self.pending_input_len]); + } + self.pending_input_len -= take; + return take; + } + return self.readPlatformInput(buffer, timeout_ms); + } + + /// Check if terminal was resized + pub fn checkResize(self: *Terminal) bool { + _ = self; + return platform.checkResize(); + } + + /// Get a Writer interface. + pub fn writer(self: *Terminal) *std.Io.Writer { + self.out.bind(); + return &self.out.writer; + } + + /// Flush buffered terminal output to the underlying sink. + pub fn flush(self: *Terminal) !void { + try self.writer().flush(); + } + + /// Clear the screen + pub fn clear(self: *Terminal) !void { + try self.writeBytes(ansi.screen_clear); + try self.writeBytes(ansi.cursor_home); + } + + /// Move cursor to position (0-indexed) + pub fn moveTo(self: *Terminal, row: u16, col: u16) !void { + var buf: [32]u8 = undefined; + const len = std.fmt.bufPrint(&buf, "\x1b[{d};{d}H", .{ row + 1, col + 1 }) catch return; + try self.writeBytes(len); + } + + /// Show the cursor + pub fn showCursor(self: *Terminal) !void { + try self.writeBytes(ansi.cursor_show); + } + + /// Hide the cursor + pub fn hideCursor(self: *Terminal) !void { + try self.writeBytes(ansi.cursor_hide); + } + + /// Enable mouse tracking + pub fn enableMouse(self: *Terminal) !void { + try self.writeBytes("\x1b[?1003h\x1b[?1006h"); + self.state.mouse_enabled = true; + } + + /// Disable mouse tracking + pub fn disableMouse(self: *Terminal) !void { + try self.writeBytes("\x1b[?1006l\x1b[?1003l"); + self.state.mouse_enabled = false; + } + + /// Set window title + pub fn setTitle(self: *Terminal, title: []const u8) !void { + try self.writeBytes("\x1b]0;"); + try self.writeBytes(title); + try self.writeBytes("\x07"); + } + + /// Copy bytes to the system clipboard using OSC 52 with instance defaults. + /// Returns `false` when disabled by config, rejected by local guardrails, or not suitable for this output. + pub fn setClipboard(self: *Terminal, bytes: []const u8) !bool { + return self.setClipboardWithOptions(bytes, .{}); + } + + /// Copy bytes to the system clipboard using OSC 52 with per-call overrides. + pub fn setClipboardWithOptions(self: *Terminal, bytes: []const u8, options: Osc52WriteOptions) !bool { + if (!self.config.osc52.enabled) return false; + + const require_tty = options.require_tty orelse self.config.osc52.require_tty; + if (require_tty and !self.isTty()) return false; + + const max_bytes = options.max_bytes orelse self.config.osc52.max_bytes; + if (max_bytes) |limit| { + if (bytes.len > limit) return false; + } + + const terminator = options.terminator orelse self.config.osc52.terminator; + const passthrough_mode = options.passthrough orelse self.config.osc52.passthrough; + const passthrough = self.resolveOsc52Passthrough(passthrough_mode); + + var target_scratch: [1]u8 = undefined; + const target = (options.target orelse self.config.osc52.target).encode(&target_scratch); + + try ansi.osc52Start(self.writer(), target, passthrough); + try self.writeBase64(bytes); + try ansi.osc52End(self.writer(), terminator, passthrough); + return true; + } + + /// Query clipboard bytes via OSC 52 (`...?;?`). + /// Returns `null` when unsupported, disabled, timed out, or rejected by guardrails. + pub fn getClipboard(self: *Terminal, allocator: std.mem.Allocator) !?[]u8 { + return self.getClipboardWithOptions(allocator, .{}); + } + + /// Query clipboard bytes via OSC 52 (`...?;?`) with per-call overrides. + /// Returns `null` when unsupported, disabled, timed out, or rejected by guardrails. + pub fn getClipboardWithOptions(self: *Terminal, allocator: std.mem.Allocator, options: Osc52ReadOptions) !?[]u8 { + if (!self.config.osc52.enabled or !self.config.osc52.query_enabled) return null; + + const require_tty = options.require_tty orelse self.config.osc52.require_tty; + if (require_tty and !self.isTty()) return null; + + const timeout_ms = options.timeout_ms orelse self.config.osc52.query_timeout_ms; + const strict_target = options.strict_target orelse self.config.osc52.strict_query_target; + const max_bytes = options.max_bytes orelse self.config.osc52.max_read_bytes; + + const terminator = options.terminator orelse self.config.osc52.terminator; + const passthrough_mode = options.passthrough orelse self.config.osc52.passthrough; + const passthrough = self.resolveOsc52Passthrough(passthrough_mode); + + var target_scratch: [1]u8 = undefined; + const target = (options.target orelse self.config.osc52.target).encode(&target_scratch); + + try ansi.osc52Start(self.writer(), target, passthrough); + try self.writeBytes("?"); + try ansi.osc52End(self.writer(), terminator, passthrough); + try self.flush(); + + var collected = std.array_list.Managed(u8).init(allocator); + defer collected.deinit(); + + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + while (withinDeadline(self.io, start, @intCast(@max(timeout_ms, 0)))) { + var chunk: [256]u8 = undefined; + const n = self.readPlatformInput(&chunk, 30) catch 0; + if (n == 0) continue; + try collected.appendSlice(chunk[0..n]); + + if (parseOsc52Response(collected.items, target, strict_target)) |parsed| { + const decoded = decodeOsc52Payload(allocator, parsed.payload_b64, max_bytes) catch null; + self.queueInputExceptRange(collected.items, parsed.consume_start, parsed.consume_end); + return decoded; + } + } + + self.queueInput(collected.items); + return null; + } + + /// Write a string at position + pub fn writeAt(self: *Terminal, row: u16, col: u16, str: []const u8) !void { + try self.moveTo(row, col); + try self.writeBytes(str); + } + + /// Check if stdin is a TTY + pub fn isTty(self: *Terminal) bool { + _ = self; + if (is_wasm) return true; + return platform.isTty(if (builtin.os.tag == .windows) + platform.State.init().stdin_handle + else + std.posix.STDIN_FILENO); + } + + pub fn getUnicodeWidthCapabilities(self: *const Terminal) UnicodeWidthCapabilities { + return self.unicode_width_caps; + } + + pub fn getImageCapabilities(self: *const Terminal) ImageCapabilities { + return self.image_caps; + } + + pub fn supportsKittyGraphics(self: *const Terminal) bool { + return self.image_caps.kitty_graphics; + } + + pub fn supportsIterm2InlineImages(self: *const Terminal) bool { + return self.image_caps.iterm2_inline_image; + } + + pub fn supportsImages(self: *const Terminal) bool { + return self.supportsKittyGraphics() or self.supportsIterm2InlineImages() or self.supportsSixel(); + } + + pub fn supportsSixel(self: *const Terminal) bool { + return self.image_caps.sixel; + } + + /// Draw image bytes using Kitty graphics protocol (`t=d`). + /// Returns `false` when unsupported or no data is provided. + pub fn drawKittyImage(self: *Terminal, image_data: []const u8, options: KittyImageOptions) !bool { + if (!self.image_caps.kitty_graphics or image_data.len == 0) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.print("a=T,t=d,f={d}", .{@intFromEnum(options.format)}); + if (options.quiet) try params_writer.writeAll(",q=2"); + if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); + if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); + if (options.image_id) |id| try params_writer.print(",i={d}", .{id}); + if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); + if (!options.move_cursor) try params_writer.writeAll(",C=1"); + if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); + if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); + if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); + if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); + + try self.sendKittyGraphicsPayload(params_writer.buffered(), image_data); + return true; + } + + /// Draw a PNG image by file path using Kitty graphics protocol (`t=f`). + /// Returns `false` when unsupported or path is empty. + pub fn drawKittyImageFromFile(self: *Terminal, path: []const u8, options: KittyImageFileOptions) !bool { + if (!self.image_caps.kitty_graphics or path.len == 0) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.writeAll("a=T,t=f,f=100"); + if (options.quiet) try params_writer.writeAll(",q=2"); + if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); + if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); + if (options.image_id) |id| try params_writer.print(",i={d}", .{id}); + if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); + if (!options.move_cursor) try params_writer.writeAll(",C=1"); + if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); + if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); + + try self.sendKittyGraphicsPayload(params_writer.buffered(), path); + return true; + } + + /// Transmit an image to the Kitty cache without displaying it (`a=t`). + /// Use `placeKittyImage` later to display it by ID. + pub fn transmitKittyImage(self: *Terminal, payload: []const u8, options: KittyTransmitOptions) !bool { + if (!self.image_caps.kitty_graphics or payload.len == 0) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.print("a=t,i={d}", .{options.image_id}); + if (options.quiet) try params_writer.writeAll(",q=2"); + + switch (options.format) { + .png => try params_writer.writeAll(",f=100"), + .rgb => { + try params_writer.writeAll(",f=24"); + if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); + if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); + }, + .rgba => { + try params_writer.writeAll(",f=32"); + if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); + if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); + }, + } + + try self.sendKittyGraphicsPayload(params_writer.buffered(), payload); + return true; + } + + /// Transmit an image file to the Kitty cache without displaying it (`a=t,t=f`). + pub fn transmitKittyImageFromFile(self: *Terminal, path: []const u8, options: KittyTransmitOptions) !bool { + if (!self.image_caps.kitty_graphics or path.len == 0) return false; + if (!fileExists(self.io, path)) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.print("a=t,t=f,f=100,i={d}", .{options.image_id}); + if (options.quiet) try params_writer.writeAll(",q=2"); + + try self.sendKittyGraphicsPayload(params_writer.buffered(), path); + return true; + } + + /// Display a previously cached image by ID (`a=p`). + pub fn placeKittyImage(self: *Terminal, options: KittyPlaceOptions) !bool { + if (!self.image_caps.kitty_graphics) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.print("a=p,i={d}", .{options.image_id}); + if (options.quiet) try params_writer.writeAll(",q=2"); + if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); + if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); + if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); + if (!options.move_cursor) try params_writer.writeAll(",C=1"); + if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); + if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); + + // Virtual placement has no payload. + try ansi.kittyGraphics(self.writer(), params_writer.buffered(), ""); + return true; + } + + /// Delete images/placements from the Kitty cache (`a=d`). + pub fn deleteKittyImage(self: *Terminal, target: KittyDeleteTarget) !bool { + if (!self.image_caps.kitty_graphics) return false; + + var params_buf: [128]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.writeAll("a=d,q=2"); + switch (target) { + .by_id => |id| try params_writer.print(",d=I,i={d}", .{id}), + .by_placement => |bp| try params_writer.print(",d=I,i={d},p={d}", .{ bp.image_id, bp.placement_id }), + .all => try params_writer.writeAll(",d=A"), + } + + try ansi.kittyGraphics(self.writer(), params_writer.buffered(), ""); + return true; + } + + /// Draw a file image via iTerm2 inline image protocol (`OSC 1337`). + /// Returns `false` when unsupported or path is empty. + pub fn drawIterm2ImageFromFile(self: *Terminal, path: []const u8, options: Iterm2ImageFileOptions) !bool { + if (!self.image_caps.iterm2_inline_image or path.len == 0) return false; + if (!fileExists(self.io, path)) return false; + + var file = try std.Io.Dir.cwd().openFile(self.io, path, .{}); + defer file.close(self.io); + const stat = try file.stat(self.io); + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.writeAll("inline=1"); + if (options.width_cells) |cols| try params_writer.print(";width={d}", .{cols}); + if (options.height_cells) |rows| try params_writer.print(";height={d}", .{rows}); + try params_writer.print(";preserveAspectRatio={d}", .{if (options.preserve_aspect_ratio) @as(u8, 1) else @as(u8, 0)}); + if (!options.move_cursor) try params_writer.writeAll(";doNotMoveCursor=1"); + try params_writer.print(";size={d}", .{stat.size}); + const file_name = std.fs.path.basename(path); + const file_name_b64_len = std.base64.standard.Encoder.calcSize(file_name.len); + if (file_name_b64_len <= 512) { + var file_name_b64_buf: [512]u8 = undefined; + const file_name_b64 = std.base64.standard.Encoder.encode(file_name_b64_buf[0..file_name_b64_len], file_name); + try params_writer.print(";name={s}", .{file_name_b64}); + } + + try self.sendIterm2InlineImagePayload(params_writer.buffered(), &file, stat.size); + return true; + } + + /// Draw in-memory image data via iTerm2 inline image protocol. + /// Returns `false` when unsupported or data is empty. + pub fn drawIterm2ImageData(self: *Terminal, data: []const u8, options: Iterm2ImageDataOptions) !bool { + if (!self.image_caps.iterm2_inline_image or data.len == 0) return false; + + var params_buf: [256]u8 = undefined; + var params_writer = FixedWriter(¶ms_buf); + + try params_writer.writeAll("inline=1"); + if (options.width_cells) |cols| try params_writer.print(";width={d}", .{cols}); + if (options.height_cells) |rows| try params_writer.print(";height={d}", .{rows}); + try params_writer.print(";preserveAspectRatio={d}", .{if (options.preserve_aspect_ratio) @as(u8, 1) else @as(u8, 0)}); + if (!options.move_cursor) try params_writer.writeAll(";doNotMoveCursor=1"); + try params_writer.print(";size={d}", .{data.len}); + + try self.sendIterm2InlineImageDataPayload(params_writer.buffered(), data); + return true; + } + + /// Draw an image file using the best available protocol. + /// Prefers Kitty graphics, then iTerm2 inline images, then Sixel. + /// Use `protocol` to override the auto-selection. + pub fn drawImageFromFile(self: *Terminal, path: []const u8, options: ImageFileOptions) !bool { + return self.drawImageFromFileWithProtocol(path, options, .auto); + } + + /// Draw an image file using a specific or auto-selected protocol. + pub fn drawImageFromFileWithProtocol(self: *Terminal, path: []const u8, options: ImageFileOptions, protocol: ImageProtocol) !bool { + if (path.len == 0) return false; + if (!fileExists(self.io, path)) return false; + + switch (protocol) { + .kitty => { + if (self.image_caps.kitty_graphics) { + return self.drawKittyImageFromFile(path, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .image_id = options.image_id, + .placement_id = options.placement_id, + .move_cursor = options.move_cursor, + .quiet = options.quiet, + .z_index = options.z_index, + .unicode_placeholder = options.unicode_placeholder, + }); + } + return false; + }, + .iterm2 => { + if (self.image_caps.iterm2_inline_image) { + return self.drawIterm2ImageFromFile(path, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .preserve_aspect_ratio = options.preserve_aspect_ratio, + .move_cursor = options.move_cursor, + }); + } + return false; + }, + .sixel => { + if (self.image_caps.sixel) { + return self.drawSixelFromFile(path, .{}); + } + return false; + }, + .auto => { + if (self.image_caps.kitty_graphics) { + return self.drawKittyImageFromFile(path, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .image_id = options.image_id, + .placement_id = options.placement_id, + .move_cursor = options.move_cursor, + .quiet = options.quiet, + .z_index = options.z_index, + .unicode_placeholder = options.unicode_placeholder, + }); + } + if (self.image_caps.iterm2_inline_image) { + return self.drawIterm2ImageFromFile(path, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .preserve_aspect_ratio = options.preserve_aspect_ratio, + .move_cursor = options.move_cursor, + }); + } + if (self.image_caps.sixel) { + return self.drawSixelFromFile(path, .{}); + } + return false; + }, + } + } + + /// Draw in-memory image data using the best available protocol. + pub fn drawImageData(self: *Terminal, data: []const u8, options: ImageDataOptions) !bool { + return self.drawImageDataWithProtocol(data, options, .auto); + } + + /// Draw in-memory image data using a specific or auto-selected protocol. + pub fn drawImageDataWithProtocol(self: *Terminal, data: []const u8, options: ImageDataOptions, protocol: ImageProtocol) !bool { + if (data.len == 0) return false; + + switch (protocol) { + .kitty => { + if (self.image_caps.kitty_graphics) { + return self.drawKittyImage(data, .{ + .format = options.format, + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .image_id = options.image_id, + .placement_id = options.placement_id, + .move_cursor = options.move_cursor, + .quiet = options.quiet, + .z_index = options.z_index, + .unicode_placeholder = options.unicode_placeholder, + .pixel_width = options.pixel_width, + .pixel_height = options.pixel_height, + }); + } + return false; + }, + .iterm2 => { + if (self.image_caps.iterm2_inline_image) { + return self.drawIterm2ImageData(data, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .preserve_aspect_ratio = options.preserve_aspect_ratio, + .move_cursor = options.move_cursor, + }); + } + return false; + }, + .sixel => { + // Sixel only supports pre-encoded data or file paths. + if (self.image_caps.sixel) { + self.sendSixelPayload(data) catch return false; + return true; + } + return false; + }, + .auto => { + if (self.image_caps.kitty_graphics) { + return self.drawKittyImage(data, .{ + .format = options.format, + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .image_id = options.image_id, + .placement_id = options.placement_id, + .move_cursor = options.move_cursor, + .quiet = options.quiet, + .z_index = options.z_index, + .unicode_placeholder = options.unicode_placeholder, + .pixel_width = options.pixel_width, + .pixel_height = options.pixel_height, + }); + } + if (self.image_caps.iterm2_inline_image) { + return self.drawIterm2ImageData(data, .{ + .width_cells = options.width_cells, + .height_cells = options.height_cells, + .preserve_aspect_ratio = options.preserve_aspect_ratio, + .move_cursor = options.move_cursor, + }); + } + if (self.image_caps.sixel) { + self.sendSixelPayload(data) catch return false; + return true; + } + return false; + }, + } + } + + /// Draw a Sixel image from file. + /// Supports either: + /// - pre-encoded `.sixel`/`.six` data files, or + /// - regular image files converted through `img2sixel` when available. + pub fn drawSixelFromFile(self: *Terminal, path: []const u8, options: SixelImageFileOptions) !bool { + if (!self.image_caps.sixel or path.len == 0) return false; + if (!fileExists(self.io, path)) return false; + + if (isSixelDataPath(path)) { + var file = try std.Io.Dir.cwd().openFile(self.io, path, .{}); + defer file.close(self.io); + try self.sendSixelPayloadFromFile(&file); + return true; + } + + if (!commandExists(self.io, "img2sixel")) return false; + + var argv_buf: [6][]const u8 = undefined; + var argc: usize = 0; + argv_buf[argc] = "img2sixel"; + argc += 1; + var w_buf: [16]u8 = undefined; + var h_buf: [16]u8 = undefined; + if (options.width_pixels) |wp| { + argv_buf[argc] = "-w"; + argc += 1; + argv_buf[argc] = std.fmt.bufPrint(&w_buf, "{d}", .{wp}) catch "0"; + argc += 1; + } + if (options.height_pixels) |hp| { + argv_buf[argc] = "-h"; + argc += 1; + argv_buf[argc] = std.fmt.bufPrint(&h_buf, "{d}", .{hp}) catch "0"; + argc += 1; + } + argv_buf[argc] = path; + argc += 1; + + const result = try std.process.run(std.heap.page_allocator, self.io, .{ + .argv = argv_buf[0..argc], + .stdout_limit = .limited(options.max_output_bytes), + .stderr_limit = .limited(options.max_output_bytes), + }); + defer std.heap.page_allocator.free(result.stdout); + defer std.heap.page_allocator.free(result.stderr); + + switch (result.term) { + .exited => |code| if (code != 0) return error.BrokenPipe, + else => return error.BrokenPipe, + } + + try self.sendSixelPayload(result.stdout); + return true; + } + + fn detectUnicodeWidthCapabilities(self: *Terminal) void { + if (is_wasm) { + self.unicode_width_caps = .{ .strategy = .legacy_wcwidth }; + return; + } + + self.unicode_width_caps = .{ + .kitty_text_sizing = self.queryKittyTextSizingSupport() catch false, + }; + + if (!self.isTty()) { + return; + } + + if (builtin.os.tag != .windows) { + self.unicode_width_caps.mode_2027 = self.queryMode2027Support() catch false; + if (self.unicode_width_caps.mode_2027) { + self.writeBytes(ansi.unicode_width_mode_enable) catch {}; + } + } + + self.unicode_width_caps.strategy = self.selectWidthStrategy(); + } + + fn detectImageCapabilities(self: *Terminal) void { + if (is_wasm) { + self.image_caps = .{}; + return; + } + + if (!self.isTty()) { + self.image_caps = .{}; + return; + } + + const term_features = self.environ_map.get("TERM_FEATURES") orelse ""; + + const kitty_candidate = looksLikeKittyTerminal(self.environ_map) or + envVarEquals(self.environ_map, "TERM_PROGRAM", "WezTerm") or + envVarContains(self.environ_map, "TERM", "wezterm") or + envVarContains(self.environ_map, "TERM", "ghostty"); + const iterm_candidate = looksLikeIterm2Terminal(self.environ_map) or + envVarEquals(self.environ_map, "TERM_PROGRAM", "WezTerm"); + const in_multiplexer = isInsideMultiplexer(self.environ_map); + + var kitty = false; + var iterm = iterm_candidate or termFeaturesContain(term_features, "F"); + var sixel = looksLikeSixelTerminal(self.environ_map) or termFeaturesContain(term_features, "Sx"); + + if (kitty_candidate) { + kitty = self.queryKittyGraphicsSupport() catch false; + // Keep an env fallback only outside multiplexers where probe failures are uncommon. + if (!kitty and !in_multiplexer) { + kitty = envVarExists(self.environ_map, "KITTY_WINDOW_ID"); + } + } + + if (iterm_candidate or term_features.len > 0) { + if (self.queryIterm2Capabilities() catch null) |caps| { + iterm = iterm or caps.inline_image; + sixel = sixel or caps.sixel; + } + } + + if (!sixel) sixel = self.queryPrimaryDeviceAttributesHasParam(4) catch false; + + self.image_caps = .{ + .kitty_graphics = kitty, + .iterm2_inline_image = iterm, + .sixel = sixel, + }; + } + + const Osc52ParsedResponse = struct { + payload_b64: []const u8, + consume_start: usize, + consume_end: usize, + }; + + fn parseOsc52Response(bytes: []const u8, expected_target: []const u8, strict_target: bool) ?Osc52ParsedResponse { + const prefix = "\x1b]52;"; + var search_from: usize = 0; + + while (search_from < bytes.len) { + const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; + const selector_start = start + prefix.len; + const selector_end = std.mem.indexOfScalarPos(u8, bytes, selector_start, ';') orelse return null; + const payload_start = selector_end + 1; + const osc_end = indexOfOscTerminator(bytes, payload_start) orelse return null; + const osc_term_len: usize = if (bytes[osc_end] == 0x07) 1 else 2; + + const selector = bytes[selector_start..selector_end]; + if (strict_target and !std.mem.eql(u8, selector, expected_target)) { + search_from = selector_end + 1; + continue; + } + + var payload_end = osc_end; + if (start > 0 and bytes[start - 1] == 0x1b and bytes[osc_end] == 0x1b and osc_end + 1 < bytes.len and bytes[osc_end + 1] == '\\') { + // DCS passthrough can encode inner ST as ESC ESC \. + if (payload_end > payload_start) payload_end -= 1; + } + + var consume_start = start; + var consume_end = osc_end + osc_term_len; + + if (findOpenDcsStart(bytes, start)) |dcs_start| { + if (indexOfSt(bytes, consume_end)) |outer_st| { + consume_start = dcs_start; + consume_end = outer_st + 2; + } + } + + return .{ + .payload_b64 = bytes[payload_start..payload_end], + .consume_start = consume_start, + .consume_end = consume_end, + }; + } + + return null; + } + + fn findOpenDcsStart(bytes: []const u8, pos: usize) ?usize { + if (pos == 0) return null; + + var i: usize = 0; + var open: ?usize = null; + while (i + 1 < pos) : (i += 1) { + if (bytes[i] != 0x1b) continue; + if (bytes[i + 1] == 'P') { + open = i; + i += 1; + continue; + } + if (bytes[i + 1] == '\\') { + open = null; + i += 1; + continue; + } + } + return open; + } + + fn decodeOsc52Payload(allocator: std.mem.Allocator, payload_b64: []const u8, max_bytes: ?usize) !?[]u8 { + if (payload_b64.len == 0 or (payload_b64.len == 1 and payload_b64[0] == '?')) return null; + + const decoder = std.base64.standard.Decoder; + const out_len = decoder.calcSizeForSlice(payload_b64) catch return null; + + if (max_bytes) |limit| { + if (out_len > limit) return null; + } + + const out = try allocator.alloc(u8, out_len); + errdefer allocator.free(out); + _ = decoder.decode(out, payload_b64) catch return null; + return out; + } + + fn readPlatformInput(self: *Terminal, buffer: []u8, timeout_ms: i32) !usize { + return platform.readInput(&self.state, buffer, timeout_ms); + } + + fn queueInput(self: *Terminal, bytes: []const u8) void { + if (bytes.len == 0) return; + + const free_space = self.pending_input.len - self.pending_input_len; + const take = @min(bytes.len, free_space); + if (take == 0) return; + + @memcpy(self.pending_input[self.pending_input_len .. self.pending_input_len + take], bytes[0..take]); + self.pending_input_len += take; + } + + fn queueInputExceptRange(self: *Terminal, bytes: []const u8, start: usize, end: usize) void { + if (start > 0) { + self.queueInput(bytes[0..start]); + } + if (end < bytes.len) { + self.queueInput(bytes[end..]); + } + } + + fn resolveOsc52Passthrough(self: *const Terminal, mode: Osc52Passthrough) ansi.Osc52Passthrough { + return switch (mode) { + .none => .none, + .tmux => .tmux, + .dcs => .dcs, + .auto => blk: { + if (envVarExists(self.environ_map, "TMUX")) break :blk .tmux; + if (envVarContains(self.environ_map, "TERM", "screen")) break :blk .dcs; + break :blk .none; + }, + }; + } + + fn writeBase64(self: *Terminal, bytes: []const u8) !void { + const encoder = std.base64.standard.Encoder; + var b64_buf: [4096]u8 = undefined; + const raw_chunk_max: usize = (b64_buf.len / 4) * 3; + + var src_index: usize = 0; + while (src_index < bytes.len) { + const take = @min(bytes.len - src_index, raw_chunk_max); + const chunk = bytes[src_index .. src_index + take]; + const encoded_len = encoder.calcSize(chunk.len); + const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); + try self.writeBytes(encoded); + src_index += take; + } + } + + fn sendKittyGraphicsPayload(self: *Terminal, first_params: []const u8, payload: []const u8) !void { + const encoder = std.base64.standard.Encoder; + var b64_buf: [4096]u8 = undefined; + const raw_chunk_max: usize = (b64_buf.len / 4) * 3; + + var src_index: usize = 0; + var first = true; + + while (true) { + const remaining = payload.len - src_index; + const take = @min(remaining, raw_chunk_max); + const chunk = payload[src_index .. src_index + take]; + + const encoded_len = encoder.calcSize(chunk.len); + const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); + const has_more = src_index + take < payload.len; + + if (first) { + var first_chunk_params: [192]u8 = undefined; + const params = try std.fmt.bufPrint( + &first_chunk_params, + "{s},m={d}", + .{ first_params, if (has_more) @as(u8, 1) else @as(u8, 0) }, + ); + try ansi.kittyGraphics(self.writer(), params, encoded); + first = false; + } else { + const params = if (has_more) "m=1" else "m=0"; + try ansi.kittyGraphics(self.writer(), params, encoded); + } + + if (!has_more) break; + src_index += take; + } + } + + fn sendIterm2InlineImagePayload(self: *Terminal, params: []const u8, file: *std.Io.File, file_size: u64) !void { + const encoder = std.base64.standard.Encoder; + var raw_buf: [3072]u8 = undefined; + var b64_buf: [4096]u8 = undefined; + const encoded_total = std.math.cast(usize, encoder.calcSize(@intCast(file_size))) orelse std.math.maxInt(usize); + const single_sequence_soft_limit: usize = 750 * 1024; + + if (encoded_total <= single_sequence_soft_limit) { + try self.writeBytes(ansi.OSC ++ "1337;File="); + try self.writeBytes(params); + try self.writeBytes(":"); + + while (true) { + const n = file.readStreaming(self.io, &.{&raw_buf}) catch |err| switch (err) { + error.EndOfStream => break, + else => |e| return e, + }; + if (n == 0) continue; + const encoded_len = encoder.calcSize(n); + const encoded = encoder.encode(b64_buf[0..encoded_len], raw_buf[0..n]); + try self.writeBytes(encoded); + } + try self.writeBytes("\x07"); + return; + } + + // iTerm2 supports multipart transfer to avoid oversized OSC sequences. + try self.writeBytes(ansi.OSC ++ "1337;MultipartFile="); + try self.writeBytes(params); + try self.writeBytes("\x07"); + + while (true) { + const n = file.readStreaming(self.io, &.{&raw_buf}) catch |err| switch (err) { + error.EndOfStream => break, + else => |e| return e, + }; + if (n == 0) break; + const encoded_len = encoder.calcSize(n); + const encoded = encoder.encode(b64_buf[0..encoded_len], raw_buf[0..n]); + try self.writeBytes(ansi.OSC ++ "1337;FilePart="); + try self.writeBytes(encoded); + try self.writeBytes("\x07"); + } + + try self.writeBytes(ansi.OSC ++ "1337;FileEnd\x07"); + } + + fn sendIterm2InlineImageDataPayload(self: *Terminal, params: []const u8, data: []const u8) !void { + const encoder = std.base64.standard.Encoder; + const encoded_total = encoder.calcSize(data.len); + const single_sequence_soft_limit: usize = 750 * 1024; + + if (encoded_total <= single_sequence_soft_limit) { + try self.writeBytes(ansi.OSC ++ "1337;File="); + try self.writeBytes(params); + try self.writeBytes(":"); + + var src_index: usize = 0; + var b64_buf: [4096]u8 = undefined; + const raw_chunk_max: usize = (b64_buf.len / 4) * 3; + while (src_index < data.len) { + const take = @min(data.len - src_index, raw_chunk_max); + const chunk = data[src_index .. src_index + take]; + const encoded_len = encoder.calcSize(chunk.len); + const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); + try self.writeBytes(encoded); + src_index += take; + } + try self.writeBytes("\x07"); + return; + } + + // Multipart transfer for large payloads. + try self.writeBytes(ansi.OSC ++ "1337;MultipartFile="); + try self.writeBytes(params); + try self.writeBytes("\x07"); + + var src_index: usize = 0; + var b64_buf: [4096]u8 = undefined; + const raw_chunk_max: usize = (b64_buf.len / 4) * 3; + while (src_index < data.len) { + const take = @min(data.len - src_index, raw_chunk_max); + const chunk = data[src_index .. src_index + take]; + const encoded_len = encoder.calcSize(chunk.len); + const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); + try self.writeBytes(ansi.OSC ++ "1337;FilePart="); + try self.writeBytes(encoded); + try self.writeBytes("\x07"); + src_index += take; + } + + try self.writeBytes(ansi.OSC ++ "1337;FileEnd\x07"); + } + + fn sendSixelPayloadFromFile(self: *Terminal, file: *std.Io.File) !void { + var payload_buf: [4096]u8 = undefined; + var first_read = true; + var wrapped = false; + + while (true) { + const n = file.readStreaming(self.io, &.{&payload_buf}) catch |err| switch (err) { + error.EndOfStream => break, + else => |e| return e, + }; + if (n == 0) break; + const chunk = payload_buf[0..n]; + + if (first_read) { + first_read = false; + if (isLikelyFullSixelSequence(chunk)) { + wrapped = true; + } else { + try self.writeBytes(ansi.DCS ++ "q"); + } + } + try self.writeBytes(chunk); + } + + if (!first_read and !wrapped) { + try self.writeBytes(ansi.ST); + } + } + + fn sendSixelPayload(self: *Terminal, bytes: []const u8) !void { + if (bytes.len == 0) return; + if (isLikelyFullSixelSequence(bytes)) { + try self.writeBytes(bytes); + return; + } + try self.writeBytes(ansi.DCS ++ "q"); + try self.writeBytes(bytes); + try self.writeBytes(ansi.ST); + } + + fn queryKittyGraphicsSupport(self: *Terminal) !bool { + const probe_id: u32 = 9931; + self.drainInput(); + try ansi.kittyGraphics(self.writer(), "a=q,i=9931,s=1,v=1,t=d,f=24", "AAAA"); + try self.flush(); + + var collected: [1024]u8 = undefined; + var collected_len: usize = 0; + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + + while (withinDeadline(self.io, start, 180)) { + var chunk: [128]u8 = undefined; + const n = self.readInput(&chunk, 30) catch 0; + if (n == 0) continue; + + const copy_len = @min(n, collected.len - collected_len); + if (copy_len > 0) { + @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); + collected_len += copy_len; + } + + if (parseKittyGraphicsProbeResponse(collected[0..collected_len], probe_id)) |supported| { + return supported; + } + } + + return false; + } + + fn parseKittyGraphicsProbeResponse(bytes: []const u8, probe_id: u32) ?bool { + const prefix = "\x1b_G"; + var search_from: usize = 0; + + var id_buf: [24]u8 = undefined; + const expected_id = std.fmt.bufPrint(&id_buf, "i={d}", .{probe_id}) catch return null; + + while (search_from < bytes.len) { + const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; + const content_start = start + prefix.len; + const semicolon = std.mem.indexOfScalarPos(u8, bytes, content_start, ';') orelse return null; + const st_index = indexOfSt(bytes, semicolon + 1) orelse return null; + + const params = bytes[content_start..semicolon]; + const payload = bytes[semicolon + 1 .. st_index]; + + if (std.mem.indexOf(u8, params, expected_id) != null) { + return std.mem.startsWith(u8, payload, "OK"); + } + + search_from = st_index + 2; + } + + return null; + } + + fn queryIterm2Capabilities(self: *Terminal) !?Iterm2Capabilities { + self.drainInput(); + try self.writeBytes(ansi.OSC ++ "1337;Capabilities\x07"); + try self.flush(); + + var collected: [2048]u8 = undefined; + var collected_len: usize = 0; + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + + while (withinDeadline(self.io, start, 180)) { + var chunk: [128]u8 = undefined; + const n = self.readInput(&chunk, 30) catch 0; + if (n == 0) continue; + + const copy_len = @min(n, collected.len - collected_len); + if (copy_len > 0) { + @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); + collected_len += copy_len; + } + + if (parseIterm2CapabilitiesResponse(collected[0..collected_len])) |caps| { + return caps; + } + } + + return null; + } + + fn parseIterm2CapabilitiesResponse(bytes: []const u8) ?Iterm2Capabilities { + const prefix = "\x1b]1337;Capabilities="; + const start = std.mem.indexOf(u8, bytes, prefix) orelse return null; + const payload_start = start + prefix.len; + const end = indexOfOscTerminator(bytes, payload_start) orelse return null; + const payload = bytes[payload_start..end]; + return .{ + .inline_image = termFeaturesContain(payload, "F"), + .sixel = termFeaturesContain(payload, "Sx"), + }; + } + + fn queryPrimaryDeviceAttributesHasParam(self: *Terminal, needle: u16) !bool { + self.drainInput(); + try self.writeBytes(ansi.CSI ++ "c"); + try self.flush(); + + var collected: [1024]u8 = undefined; + var collected_len: usize = 0; + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + + while (withinDeadline(self.io, start, 120)) { + var chunk: [128]u8 = undefined; + const n = self.readInput(&chunk, 25) catch 0; + if (n == 0) continue; + + const copy_len = @min(n, collected.len - collected_len); + if (copy_len > 0) { + @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); + collected_len += copy_len; + } + + if (parsePrimaryDeviceAttributes(collected[0..collected_len])) |params| { + return primaryDeviceAttributesHasParam(params, needle); + } + } + + return false; + } + + fn parsePrimaryDeviceAttributes(bytes: []const u8) ?[]const u8 { + const prefix = "\x1b["; + var search_from: usize = 0; + + while (search_from < bytes.len) { + const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; + var i = start + prefix.len; + + if (i < bytes.len and bytes[i] == '?') i += 1; + const params_start = i; + + while (i < bytes.len and ((bytes[i] >= '0' and bytes[i] <= '9') or bytes[i] == ';')) : (i += 1) {} + if (i >= bytes.len) return null; + + if (bytes[i] == 'c' and i > params_start) { + return bytes[params_start..i]; + } + + search_from = start + 1; + } + + return null; + } + + fn primaryDeviceAttributesHasParam(params: []const u8, needle: u16) bool { + var it = std.mem.splitScalar(u8, params, ';'); + while (it.next()) |part| { + if (part.len == 0) continue; + const value = std.fmt.parseInt(u16, part, 10) catch continue; + if (value == needle) return true; + } + return false; + } + + fn queryMode2027Support(self: *Terminal) !bool { + try self.writeBytes(ansi.unicode_width_mode_query); + try self.flush(); + + var collected: [512]u8 = undefined; + var collected_len: usize = 0; + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + + while (withinDeadline(self.io, start, 250)) { + var chunk: [128]u8 = undefined; + const n = self.readInput(&chunk, 40) catch 0; + if (n == 0) continue; + + const copy_len = @min(n, collected.len - collected_len); + if (copy_len > 0) { + @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); + collected_len += copy_len; + } + + if (parseMode2027Response(collected[0..collected_len])) |supported| { + return supported; + } + } + + return false; + } + + fn parseMode2027Response(bytes: []const u8) ?bool { + const prefix = "\x1b[?2027;"; + var search_from: usize = 0; + + while (search_from < bytes.len) { + const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; + var i = start + prefix.len; + var param: usize = 0; + var saw_digit = false; + + while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) { + saw_digit = true; + param = param * 10 + (bytes[i] - '0'); + } + + if (!saw_digit) { + search_from = start + 1; + continue; + } + + if (i + 1 < bytes.len and bytes[i] == '$' and bytes[i + 1] == 'y') { + return param != 0; + } + + search_from = start + 1; + } + + return null; + } + + fn selectWidthStrategy(self: *const Terminal) unicode.WidthStrategy { + if (isInsideMultiplexer(self.environ_map)) { + return .legacy_wcwidth; + } + + if (self.unicode_width_caps.mode_2027) { + return .unicode; + } + + if (self.unicode_width_caps.kitty_text_sizing) { + return .unicode; + } + + if (isKnownUnicodeWidthTerminal(self.environ_map)) { + return .unicode; + } + + return .legacy_wcwidth; + } + + fn queryKittyTextSizingSupport(self: *Terminal) !bool { + if (!looksLikeKittyTerminal(self.environ_map)) return false; + + const cpr = "\x1b[6n"; + // CR, CPR, draw 2-cell space via kitty OSC 66 width-only, CPR. + const probe = "\r" ++ cpr ++ "\x1b]66;w=2; \x07" ++ cpr; + try self.writeBytes(probe); + try self.flush(); + + var buf: [512]u8 = undefined; + var len: usize = 0; + const start = std.Io.Clock.Timestamp.now(self.io, .boot); + + while (withinDeadline(self.io, start, 250)) { + var chunk: [128]u8 = undefined; + const n = self.readInput(&chunk, 40) catch 0; + if (n == 0) continue; + + const copy_len = @min(n, buf.len - len); + if (copy_len > 0) { + @memcpy(buf[len .. len + copy_len], chunk[0..copy_len]); + len += copy_len; + } + + if (parseTwoCprColumns(buf[0..len])) |cols| { + return cols.second == cols.first + 2; + } + } + + return false; + } + + fn parseTwoCprColumns(bytes: []const u8) ?struct { first: usize, second: usize } { + var idx: usize = 0; + var found: [2]usize = .{ 0, 0 }; + var count: usize = 0; + + while (idx < bytes.len and count < 2) { + const esc = std.mem.indexOfPos(u8, bytes, idx, "\x1b[") orelse break; + var i = esc + 2; + + while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) {} + if (i >= bytes.len or bytes[i] != ';') { + idx = esc + 1; + continue; + } + i += 1; + + const col_start = i; + while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) {} + if (i >= bytes.len or bytes[i] != 'R' or col_start == i) { + idx = esc + 1; + continue; + } + + const col = std.fmt.parseInt(usize, bytes[col_start..i], 10) catch { + idx = esc + 1; + continue; + }; + found[count] = col; + count += 1; + idx = i + 1; + } + + if (count == 2) { + return .{ .first = found[0], .second = found[1] }; + } + return null; + } + + fn isInsideMultiplexer(environ_map: *const std.process.Environ.Map) bool { + return envVarExists(environ_map, "TMUX") or envVarExists(environ_map, "ZELLIJ") or envVarContains(environ_map, "TERM", "screen"); + } + + fn drainInput(self: *Terminal) void { + var buf: [128]u8 = undefined; + while (true) { + const n = self.readInput(&buf, 0) catch return; + if (n == 0) return; + } + } + + fn termFeaturesContain(features: []const u8, needle: []const u8) bool { + if (features.len == 0 or needle.len == 0) return false; + + var i: usize = 0; + while (i < features.len) { + if (!std.ascii.isUpper(features[i])) { + i += 1; + continue; + } + + var j = i + 1; + while (j < features.len and std.ascii.isLower(features[j])) : (j += 1) {} + const code = features[i..j]; + + while (j < features.len and std.ascii.isDigit(features[j])) : (j += 1) {} + if (std.mem.eql(u8, code, needle)) return true; + + i = j; + } + + return false; + } + + fn indexOfOscTerminator(bytes: []const u8, start: usize) ?usize { + var i = start; + while (i < bytes.len) : (i += 1) { + if (bytes[i] == 0x07) return i; + if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { + return i; + } + } + return null; + } + + fn indexOfSt(bytes: []const u8, start: usize) ?usize { + var i = start; + while (i + 1 < bytes.len) : (i += 1) { + if (bytes[i] == 0x1b and bytes[i + 1] == '\\') return i; + } + return null; + } + + fn isKnownUnicodeWidthTerminal(environ_map: *const std.process.Environ.Map) bool { + // Terminals known to use grapheme-aware width by default. + return envVarEquals(environ_map, "TERM_PROGRAM", "WezTerm") or + envVarEquals(environ_map, "TERM_PROGRAM", "iTerm.app") or + envVarContains(environ_map, "TERM", "wezterm") or + envVarContains(environ_map, "TERM", "ghostty"); + } + + fn looksLikeKittyTerminal(environ_map: *const std.process.Environ.Map) bool { + return envVarExists(environ_map, "KITTY_WINDOW_ID") or envVarContains(environ_map, "TERM", "kitty"); + } + + fn looksLikeIterm2Terminal(environ_map: *const std.process.Environ.Map) bool { + return envVarEquals(environ_map, "TERM_PROGRAM", "iTerm.app") or + envVarEquals(environ_map, "LC_TERMINAL", "iTerm2"); + } + + fn looksLikeSixelTerminal(environ_map: *const std.process.Environ.Map) bool { + return envVarContains(environ_map, "TERM", "sixel") or + envVarContains(environ_map, "TERM", "mlterm") or + envVarContains(environ_map, "TERM", "yaft") or + envVarContains(environ_map, "TERM", "contour"); + } + + fn isLikelyFullSixelSequence(bytes: []const u8) bool { + if (bytes.len == 0) return false; + return std.mem.startsWith(u8, bytes, ansi.DCS) or bytes[0] == 0x90; + } + + fn isSixelDataPath(path: []const u8) bool { + return std.mem.endsWith(u8, path, ".sixel") or + std.mem.endsWith(u8, path, ".SIXEL") or + std.mem.endsWith(u8, path, ".six") or + std.mem.endsWith(u8, path, ".SIX"); + } + + fn fileExists(io: std.Io, path: []const u8) bool { + std.Io.Dir.cwd().access(io, path, .{}) catch return false; + return true; + } + + fn withinDeadline(io: std.Io, start: std.Io.Clock.Timestamp, timeout_ms: u64) bool { + const elapsed_ns = start.untilNow(io).raw.nanoseconds; + const deadline_ns: i96 = @as(i96, @intCast(timeout_ms)) * std.time.ns_per_ms; + return elapsed_ns < deadline_ns; + } + + fn commandExists(io: std.Io, name: []const u8) bool { + const argv = [_][]const u8{ name, "--version" }; + const result = std.process.run(std.heap.page_allocator, io, .{ + .argv = &argv, + .stdout_limit = .limited(1024), + .stderr_limit = .limited(1024), + }) catch return false; + defer std.heap.page_allocator.free(result.stdout); + defer std.heap.page_allocator.free(result.stderr); + return true; + } + + fn envVarExists(environ_map: *const std.process.Environ.Map, name: []const u8) bool { + const value = environ_map.get(name) orelse return false; + return value.len > 0; + } + + fn envVarEquals(environ_map: *const std.process.Environ.Map, name: []const u8, expected: []const u8) bool { + const value = environ_map.get(name) orelse return false; + return std.ascii.eqlIgnoreCase(value, expected); + } + + fn envVarContains(environ_map: *const std.process.Environ.Map, name: []const u8, needle: []const u8) bool { + const value = environ_map.get(name) orelse return false; + return std.mem.indexOf(u8, value, needle) != null; + } + + /// Buffered writer that exposes a `std.Io.Writer` interface and drains to + /// the terminal's output sink (stdout file, or the wasm host on wasm). + pub const Writer = struct { + io: std.Io, + file: if (is_wasm) void else std.Io.File, + buffer: [4096]u8 = undefined, + writer: std.Io.Writer, + + const vtable: std.Io.Writer.VTable = .{ .drain = drain }; + + pub fn init(io: std.Io, file: if (is_wasm) void else std.Io.File) Writer { + return .{ + .io = io, + .file = file, + .writer = .{ .vtable = &vtable, .buffer = &.{} }, + }; + } + + /// Wires the `std.Io.Writer` to the local buffer. Called by the + /// containing `Terminal` whenever it hands the writer out, so the + /// buffer pointer stays valid even if the `Terminal` was moved. + /// `writer.end` is preserved across moves, so re-binding is safe. + pub fn bind(self: *Writer) void { + self.writer.buffer = &self.buffer; + } + + fn drain(io_w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const self: *Writer = @fieldParentPtr("writer", io_w); + + const buffered = io_w.buffered(); + if (buffered.len != 0) { + try self.sinkAll(buffered); + io_w.end = 0; + } + + // The std.Io.Writer.VTable contract treats data.len == 0 as a + // pure flush; the splat pattern lives at data[data.len - 1] so we + // must early-return before indexing. + if (data.len == 0) return 0; + + var consumed: usize = 0; + if (data.len > 1) { + for (data[0 .. data.len - 1]) |chunk| { + if (chunk.len == 0) continue; + try self.sinkAll(chunk); + consumed += chunk.len; + } + } + + const pattern = data[data.len - 1]; + if (pattern.len > 0 and splat > 0) { + var i: usize = 0; + while (i < splat) : (i += 1) try self.sinkAll(pattern); + consumed += pattern.len * splat; + } + + return consumed; + } + + fn sinkAll(self: *Writer, bytes: []const u8) std.Io.Writer.Error!void { + if (is_wasm) { + try platform.wasm_writer_instance.writer.writeAll(bytes); + } else { + self.file.writeStreamingAll(self.io, bytes) catch return error.WriteFailed; + } + } + }; +}; + +test "parseOsc52Response direct BEL" { + const bytes = "\x1b]52;c;YQ==\x07"; + const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; + try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); + try std.testing.expectEqual(bytes.len, parsed.consume_end); + try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); +} + +test "parseOsc52Response direct ST" { + const bytes = "\x1b]52;c;YQ==\x1b\\"; + const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; + try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); + try std.testing.expectEqual(bytes.len, parsed.consume_end); + try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); +} + +test "parseOsc52Response tmux passthrough BEL" { + const bytes = "\x1bPtmux;\x1b\x1b]52;c;YQ==\x07\x1b\\"; + const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; + try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); + try std.testing.expectEqual(bytes.len, parsed.consume_end); + try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); +} + +test "parseOsc52Response tmux passthrough ST" { + const bytes = "\x1bPtmux;\x1b\x1b]52;c;YQ==\x1b\x1b\\\x1b\\"; + const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; + try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); + try std.testing.expectEqual(bytes.len, parsed.consume_end); + try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig new file mode 100644 index 0000000..b230bdf --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/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); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig new file mode 100644 index 0000000..3f9cedf --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig @@ -0,0 +1,96 @@ +//! Unicode utilities for display width calculation. + +const std = @import("std"); + +pub const display_width = @import("unicode/display_width.zig"); + +/// Runtime width strategy. +/// - legacy_wcwidth: conservative fallback for terminals without negotiated width support. +/// - unicode: full Unicode table behavior. +pub const WidthStrategy = enum(u8) { + legacy_wcwidth, + unicode, +}; + +var width_strategy: std.atomic.Value(u8) = std.atomic.Value(u8).init(@intFromEnum(WidthStrategy.legacy_wcwidth)); + +pub fn setWidthStrategy(strategy: WidthStrategy) void { + width_strategy.store(@intFromEnum(strategy), .release); +} + +pub fn getWidthStrategy() WidthStrategy { + return @enumFromInt(width_strategy.load(.acquire)); +} + +pub fn charWidth(codepoint: u21) usize { + return switch (getWidthStrategy()) { + .legacy_wcwidth => charWidthLegacy(codepoint), + .unicode => display_width.charWidth(codepoint), + }; +} + +pub fn codepointWidth(codepoint: u21) i8 { + return switch (getWidthStrategy()) { + .unicode => @as(i8, display_width.codepointWidth(codepoint)), + .legacy_wcwidth => blk: { + const w = display_width.codepointWidth(codepoint); + if (w <= 0) break :blk @as(i8, w); + if (w == 2 and isLegacyAmbiguousWide(codepoint)) break :blk 1; + break :blk @as(i8, w); + }, + }; +} + +pub fn strWidth(str: []const u8) usize { + var total: usize = 0; + var i: usize = 0; + while (i < str.len) { + const len = std.unicode.utf8ByteSequenceLength(str[i]) catch { + total += 1; + i += 1; + continue; + }; + if (i + len > str.len) { + total += 1; + i += 1; + continue; + } + const cp = std.unicode.utf8Decode(str[i..][0..len]) catch { + total += 1; + i += 1; + continue; + }; + total += charWidth(cp); + i += len; + } + return total; +} + +fn charWidthLegacy(codepoint: u21) usize { + const w = display_width.charWidth(codepoint); + if (w == 2 and isLegacyAmbiguousWide(codepoint)) return 1; + return w; +} + +/// Legacy terminals often render many BMP symbol/emoji codepoints as narrow. +fn isLegacyAmbiguousWide(codepoint: u21) bool { + return (codepoint >= 0x2300 and codepoint <= 0x23FF) or + (codepoint >= 0x2600 and codepoint <= 0x27BF) or + (codepoint >= 0x2B00 and codepoint <= 0x2BFF); +} + +test { + _ = display_width; +} + +test "legacy strategy narrows ambiguous bmp symbols" { + setWidthStrategy(.legacy_wcwidth); + defer setWidthStrategy(.unicode); + try std.testing.expectEqual(@as(usize, 1), charWidth(0x2764)); // Heart +} + +test "unicode strategy keeps full table behavior" { + setWidthStrategy(.unicode); + defer setWidthStrategy(.legacy_wcwidth); + try std.testing.expectEqual(display_width.charWidth(0x2764), charWidth(0x2764)); +} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig new file mode 100644 index 0000000..5a31def --- /dev/null +++ b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig @@ -0,0 +1,677 @@ +//! Unicode display width lookup based on Unicode 16.0. +//! Provides wcwidth-equivalent functionality for determining how many +//! terminal columns a character occupies. + +const std = @import("std"); + +/// A Unicode codepoint range (inclusive). +const Range = struct { + first: u21, + last: u21, +}; + +/// Zero-width character ranges: combining marks (Mn/Me/Mc subset), format chars (Cf), +/// default ignorable code points, variation selectors, Hangul Jamo medials/finals, etc. +const zero_width_ranges = [_]Range{ + .{ .first = 0x00AD, .last = 0x00AD }, // SOFT HYPHEN + .{ .first = 0x0300, .last = 0x036F }, // Combining Diacritical Marks + .{ .first = 0x0483, .last = 0x0489 }, // Combining Cyrillic + .{ .first = 0x0591, .last = 0x05BD }, // Hebrew combining + .{ .first = 0x05BF, .last = 0x05BF }, + .{ .first = 0x05C1, .last = 0x05C2 }, + .{ .first = 0x05C4, .last = 0x05C5 }, + .{ .first = 0x05C7, .last = 0x05C7 }, + .{ .first = 0x0600, .last = 0x0605 }, // Arabic format + .{ .first = 0x0610, .last = 0x061A }, // Arabic combining + .{ .first = 0x061C, .last = 0x061C }, // Arabic Letter Mark + .{ .first = 0x064B, .last = 0x065F }, // Arabic combining + .{ .first = 0x0670, .last = 0x0670 }, + .{ .first = 0x06D6, .last = 0x06DD }, + .{ .first = 0x06DF, .last = 0x06E4 }, + .{ .first = 0x06E7, .last = 0x06E8 }, + .{ .first = 0x06EA, .last = 0x06ED }, + .{ .first = 0x070F, .last = 0x070F }, // Syriac Abbreviation Mark + .{ .first = 0x0711, .last = 0x0711 }, // Syriac combining + .{ .first = 0x0730, .last = 0x074A }, // Syriac combining + .{ .first = 0x07A6, .last = 0x07B0 }, // Thaana combining + .{ .first = 0x07EB, .last = 0x07F3 }, // NKo combining + .{ .first = 0x07FD, .last = 0x07FD }, + .{ .first = 0x0816, .last = 0x0819 }, // Samaritan combining + .{ .first = 0x081B, .last = 0x0823 }, + .{ .first = 0x0825, .last = 0x0827 }, + .{ .first = 0x0829, .last = 0x082D }, + .{ .first = 0x0859, .last = 0x085B }, // Mandaic combining + .{ .first = 0x0890, .last = 0x0891 }, // Arabic format + .{ .first = 0x0898, .last = 0x089F }, // Arabic combining + .{ .first = 0x08CA, .last = 0x08E1 }, // Arabic combining + .{ .first = 0x08E3, .last = 0x0902 }, // Arabic/Devanagari combining + .{ .first = 0x093A, .last = 0x093A }, + .{ .first = 0x093C, .last = 0x093C }, + .{ .first = 0x0941, .last = 0x0948 }, + .{ .first = 0x094D, .last = 0x094D }, + .{ .first = 0x0951, .last = 0x0957 }, + .{ .first = 0x0962, .last = 0x0963 }, + .{ .first = 0x0981, .last = 0x0981 }, // Bengali + .{ .first = 0x09BC, .last = 0x09BC }, + .{ .first = 0x09C1, .last = 0x09C4 }, + .{ .first = 0x09CD, .last = 0x09CD }, + .{ .first = 0x09E2, .last = 0x09E3 }, + .{ .first = 0x09FE, .last = 0x09FE }, + .{ .first = 0x0A01, .last = 0x0A02 }, // Gurmukhi + .{ .first = 0x0A3C, .last = 0x0A3C }, + .{ .first = 0x0A41, .last = 0x0A42 }, + .{ .first = 0x0A47, .last = 0x0A48 }, + .{ .first = 0x0A4B, .last = 0x0A4D }, + .{ .first = 0x0A51, .last = 0x0A51 }, + .{ .first = 0x0A70, .last = 0x0A71 }, + .{ .first = 0x0A75, .last = 0x0A75 }, + .{ .first = 0x0A81, .last = 0x0A82 }, // Gujarati + .{ .first = 0x0ABC, .last = 0x0ABC }, + .{ .first = 0x0AC1, .last = 0x0AC5 }, + .{ .first = 0x0AC7, .last = 0x0AC8 }, + .{ .first = 0x0ACD, .last = 0x0ACD }, + .{ .first = 0x0AE2, .last = 0x0AE3 }, + .{ .first = 0x0AFA, .last = 0x0AFF }, + .{ .first = 0x0B01, .last = 0x0B01 }, // Oriya + .{ .first = 0x0B3C, .last = 0x0B3C }, + .{ .first = 0x0B3F, .last = 0x0B3F }, + .{ .first = 0x0B41, .last = 0x0B44 }, + .{ .first = 0x0B4D, .last = 0x0B4D }, + .{ .first = 0x0B55, .last = 0x0B56 }, + .{ .first = 0x0B62, .last = 0x0B63 }, + .{ .first = 0x0B82, .last = 0x0B82 }, // Tamil + .{ .first = 0x0BC0, .last = 0x0BC0 }, + .{ .first = 0x0BCD, .last = 0x0BCD }, + .{ .first = 0x0C00, .last = 0x0C00 }, // Telugu + .{ .first = 0x0C04, .last = 0x0C04 }, + .{ .first = 0x0C3C, .last = 0x0C3C }, + .{ .first = 0x0C3E, .last = 0x0C40 }, + .{ .first = 0x0C46, .last = 0x0C48 }, + .{ .first = 0x0C4A, .last = 0x0C4D }, + .{ .first = 0x0C55, .last = 0x0C56 }, + .{ .first = 0x0C62, .last = 0x0C63 }, + .{ .first = 0x0C81, .last = 0x0C81 }, // Kannada + .{ .first = 0x0CBC, .last = 0x0CBC }, + .{ .first = 0x0CBF, .last = 0x0CBF }, + .{ .first = 0x0CC6, .last = 0x0CC6 }, + .{ .first = 0x0CCC, .last = 0x0CCD }, + .{ .first = 0x0CE2, .last = 0x0CE3 }, + .{ .first = 0x0D00, .last = 0x0D01 }, // Malayalam + .{ .first = 0x0D3B, .last = 0x0D3C }, + .{ .first = 0x0D41, .last = 0x0D44 }, + .{ .first = 0x0D4D, .last = 0x0D4D }, + .{ .first = 0x0D62, .last = 0x0D63 }, + .{ .first = 0x0D81, .last = 0x0D81 }, // Sinhala + .{ .first = 0x0DCA, .last = 0x0DCA }, + .{ .first = 0x0DD2, .last = 0x0DD4 }, + .{ .first = 0x0DD6, .last = 0x0DD6 }, + .{ .first = 0x0E31, .last = 0x0E31 }, // Thai + .{ .first = 0x0E34, .last = 0x0E3A }, + .{ .first = 0x0E47, .last = 0x0E4E }, + .{ .first = 0x0EB1, .last = 0x0EB1 }, // Lao + .{ .first = 0x0EB4, .last = 0x0EBC }, + .{ .first = 0x0EC8, .last = 0x0ECE }, + .{ .first = 0x0F18, .last = 0x0F19 }, // Tibetan + .{ .first = 0x0F35, .last = 0x0F35 }, + .{ .first = 0x0F37, .last = 0x0F37 }, + .{ .first = 0x0F39, .last = 0x0F39 }, + .{ .first = 0x0F71, .last = 0x0F7E }, + .{ .first = 0x0F80, .last = 0x0F84 }, + .{ .first = 0x0F86, .last = 0x0F87 }, + .{ .first = 0x0F8D, .last = 0x0F97 }, + .{ .first = 0x0F99, .last = 0x0FBC }, + .{ .first = 0x0FC6, .last = 0x0FC6 }, + .{ .first = 0x102D, .last = 0x1030 }, // Myanmar + .{ .first = 0x1032, .last = 0x1037 }, + .{ .first = 0x1039, .last = 0x103A }, + .{ .first = 0x103D, .last = 0x103E }, + .{ .first = 0x1058, .last = 0x1059 }, + .{ .first = 0x105E, .last = 0x1060 }, + .{ .first = 0x1071, .last = 0x1074 }, + .{ .first = 0x1082, .last = 0x1082 }, + .{ .first = 0x1085, .last = 0x1086 }, + .{ .first = 0x108D, .last = 0x108D }, + .{ .first = 0x109D, .last = 0x109D }, + .{ .first = 0x1160, .last = 0x11FF }, // Hangul Jamo medial vowels and final consonants + .{ .first = 0x135D, .last = 0x135F }, // Ethiopic combining + .{ .first = 0x1712, .last = 0x1714 }, // Tagalog + .{ .first = 0x1732, .last = 0x1733 }, // Hanunoo + .{ .first = 0x1752, .last = 0x1753 }, // Buhid + .{ .first = 0x1772, .last = 0x1773 }, // Tagbanwa + .{ .first = 0x17B4, .last = 0x17B5 }, // Khmer + .{ .first = 0x17B7, .last = 0x17BD }, + .{ .first = 0x17C6, .last = 0x17C6 }, + .{ .first = 0x17C9, .last = 0x17D3 }, + .{ .first = 0x17DD, .last = 0x17DD }, + .{ .first = 0x180B, .last = 0x180F }, // Mongolian format/combining + .{ .first = 0x1885, .last = 0x1886 }, // Mongolian combining + .{ .first = 0x18A9, .last = 0x18A9 }, + .{ .first = 0x1920, .last = 0x1922 }, // Limbu + .{ .first = 0x1927, .last = 0x1928 }, + .{ .first = 0x1932, .last = 0x1932 }, + .{ .first = 0x1939, .last = 0x193B }, + .{ .first = 0x1A17, .last = 0x1A18 }, // Buginese + .{ .first = 0x1A1B, .last = 0x1A1B }, + .{ .first = 0x1A56, .last = 0x1A56 }, // Tai Tham + .{ .first = 0x1A58, .last = 0x1A5E }, + .{ .first = 0x1A60, .last = 0x1A60 }, + .{ .first = 0x1A62, .last = 0x1A62 }, + .{ .first = 0x1A65, .last = 0x1A6C }, + .{ .first = 0x1A73, .last = 0x1A7C }, + .{ .first = 0x1A7F, .last = 0x1A7F }, + .{ .first = 0x1AB0, .last = 0x1ACE }, // Combining Diacritical Marks Extended + .{ .first = 0x1B00, .last = 0x1B03 }, // Balinese + .{ .first = 0x1B34, .last = 0x1B34 }, + .{ .first = 0x1B36, .last = 0x1B3A }, + .{ .first = 0x1B3C, .last = 0x1B3C }, + .{ .first = 0x1B42, .last = 0x1B42 }, + .{ .first = 0x1B6B, .last = 0x1B73 }, + .{ .first = 0x1B80, .last = 0x1B81 }, // Sundanese + .{ .first = 0x1BA2, .last = 0x1BA5 }, + .{ .first = 0x1BA8, .last = 0x1BA9 }, + .{ .first = 0x1BAB, .last = 0x1BAD }, + .{ .first = 0x1BE6, .last = 0x1BE6 }, // Batak + .{ .first = 0x1BE8, .last = 0x1BE9 }, + .{ .first = 0x1BED, .last = 0x1BED }, + .{ .first = 0x1BEF, .last = 0x1BF1 }, + .{ .first = 0x1C2C, .last = 0x1C33 }, // Lepcha + .{ .first = 0x1C36, .last = 0x1C37 }, + .{ .first = 0x1CD0, .last = 0x1CD2 }, // Vedic Extensions + .{ .first = 0x1CD4, .last = 0x1CE0 }, + .{ .first = 0x1CE2, .last = 0x1CE8 }, + .{ .first = 0x1CED, .last = 0x1CED }, + .{ .first = 0x1CF4, .last = 0x1CF4 }, + .{ .first = 0x1CF8, .last = 0x1CF9 }, + .{ .first = 0x1DC0, .last = 0x1DFF }, // Combining Diacritical Marks Supplement + .{ .first = 0x200B, .last = 0x200F }, // Zero-width/format chars + .{ .first = 0x202A, .last = 0x202E }, // Bidi format + .{ .first = 0x2060, .last = 0x2064 }, // Invisible operators + .{ .first = 0x2066, .last = 0x206F }, // Bidi format + .{ .first = 0x20D0, .last = 0x20F0 }, // Combining Diacritical Marks for Symbols + .{ .first = 0x2CEF, .last = 0x2CF1 }, // Coptic combining + .{ .first = 0x2D7F, .last = 0x2D7F }, // Tifinagh combining + .{ .first = 0x2DE0, .last = 0x2DFF }, // Cyrillic Extended-A combining + .{ .first = 0x302A, .last = 0x302D }, // CJK ideographic tone marks + .{ .first = 0x3099, .last = 0x309A }, // Japanese combining + .{ .first = 0xA66F, .last = 0xA672 }, // Combining Cyrillic + .{ .first = 0xA674, .last = 0xA67D }, + .{ .first = 0xA69E, .last = 0xA69F }, + .{ .first = 0xA6F0, .last = 0xA6F1 }, // Bamum combining + .{ .first = 0xA802, .last = 0xA802 }, // Syloti Nagri + .{ .first = 0xA806, .last = 0xA806 }, + .{ .first = 0xA80B, .last = 0xA80B }, + .{ .first = 0xA825, .last = 0xA826 }, + .{ .first = 0xA82C, .last = 0xA82C }, + .{ .first = 0xA8C4, .last = 0xA8C5 }, // Saurashtra + .{ .first = 0xA8E0, .last = 0xA8F1 }, // Devanagari Extended combining + .{ .first = 0xA8FF, .last = 0xA8FF }, + .{ .first = 0xA926, .last = 0xA92D }, // Kayah Li + .{ .first = 0xA947, .last = 0xA951 }, // Rejang + .{ .first = 0xA980, .last = 0xA982 }, // Javanese + .{ .first = 0xA9B3, .last = 0xA9B3 }, + .{ .first = 0xA9B6, .last = 0xA9B9 }, + .{ .first = 0xA9BC, .last = 0xA9BD }, + .{ .first = 0xA9E5, .last = 0xA9E5 }, // Myanmar Extended-B + .{ .first = 0xAA29, .last = 0xAA2E }, // Cham + .{ .first = 0xAA31, .last = 0xAA32 }, + .{ .first = 0xAA35, .last = 0xAA36 }, + .{ .first = 0xAA43, .last = 0xAA43 }, + .{ .first = 0xAA4C, .last = 0xAA4C }, + .{ .first = 0xAA7C, .last = 0xAA7C }, + .{ .first = 0xAAB0, .last = 0xAAB0 }, // Tai Viet + .{ .first = 0xAAB2, .last = 0xAAB4 }, + .{ .first = 0xAAB7, .last = 0xAAB8 }, + .{ .first = 0xAABE, .last = 0xAABF }, + .{ .first = 0xAAC1, .last = 0xAAC1 }, + .{ .first = 0xAAEC, .last = 0xAAED }, + .{ .first = 0xAAF6, .last = 0xAAF6 }, + .{ .first = 0xABE5, .last = 0xABE5 }, // Meetei Mayek + .{ .first = 0xABE8, .last = 0xABE8 }, + .{ .first = 0xABED, .last = 0xABED }, + .{ .first = 0xFB1E, .last = 0xFB1E }, // Hebrew combining + .{ .first = 0xFE00, .last = 0xFE0F }, // Variation Selectors + .{ .first = 0xFE20, .last = 0xFE2F }, // Combining Half Marks + .{ .first = 0xFEFF, .last = 0xFEFF }, // BOM / ZWNBSP + .{ .first = 0xFFF9, .last = 0xFFFB }, // Interlinear annotation + .{ .first = 0x101FD, .last = 0x101FD }, // Phaistos combining + .{ .first = 0x102E0, .last = 0x102E0 }, // Coptic Epact combining + .{ .first = 0x10376, .last = 0x1037A }, // Old Permic combining + .{ .first = 0x10A01, .last = 0x10A03 }, // Kharoshthi combining + .{ .first = 0x10A05, .last = 0x10A06 }, + .{ .first = 0x10A0C, .last = 0x10A0F }, + .{ .first = 0x10A38, .last = 0x10A3A }, + .{ .first = 0x10A3F, .last = 0x10A3F }, + .{ .first = 0x10AE5, .last = 0x10AE6 }, // Manichaean combining + .{ .first = 0x10D24, .last = 0x10D27 }, // Hanifi Rohingya + .{ .first = 0x10EAB, .last = 0x10EAC }, // Yezidi combining + .{ .first = 0x10EFD, .last = 0x10EFF }, // Arabic Extended-C + .{ .first = 0x10F46, .last = 0x10F50 }, // Sogdian combining + .{ .first = 0x10F82, .last = 0x10F85 }, // Old Uyghur combining + .{ .first = 0x11001, .last = 0x11001 }, // Brahmi + .{ .first = 0x11038, .last = 0x11046 }, + .{ .first = 0x11070, .last = 0x11070 }, + .{ .first = 0x11073, .last = 0x11074 }, + .{ .first = 0x1107F, .last = 0x11081 }, // Kaithi + .{ .first = 0x110B3, .last = 0x110B6 }, + .{ .first = 0x110B9, .last = 0x110BA }, + .{ .first = 0x110C2, .last = 0x110C2 }, + .{ .first = 0x11100, .last = 0x11102 }, // Chakma + .{ .first = 0x11127, .last = 0x1112B }, + .{ .first = 0x1112D, .last = 0x11134 }, + .{ .first = 0x11173, .last = 0x11173 }, // Mahajani + .{ .first = 0x11180, .last = 0x11181 }, // Sharada + .{ .first = 0x111B6, .last = 0x111BE }, + .{ .first = 0x111C9, .last = 0x111CC }, + .{ .first = 0x111CF, .last = 0x111CF }, + .{ .first = 0x1122F, .last = 0x11231 }, // Khojki + .{ .first = 0x11234, .last = 0x11234 }, + .{ .first = 0x11236, .last = 0x11237 }, + .{ .first = 0x1123E, .last = 0x1123E }, + .{ .first = 0x11241, .last = 0x11241 }, + .{ .first = 0x112DF, .last = 0x112DF }, // Khudawadi + .{ .first = 0x112E3, .last = 0x112EA }, + .{ .first = 0x11300, .last = 0x11301 }, // Grantha + .{ .first = 0x1133B, .last = 0x1133C }, + .{ .first = 0x11340, .last = 0x11340 }, + .{ .first = 0x11366, .last = 0x1136C }, + .{ .first = 0x11370, .last = 0x11374 }, + .{ .first = 0x11438, .last = 0x1143F }, // Newa + .{ .first = 0x11442, .last = 0x11444 }, + .{ .first = 0x11446, .last = 0x11446 }, + .{ .first = 0x1145E, .last = 0x1145E }, + .{ .first = 0x114B3, .last = 0x114B8 }, // Tirhuta + .{ .first = 0x114BA, .last = 0x114BA }, + .{ .first = 0x114BF, .last = 0x114C0 }, + .{ .first = 0x114C2, .last = 0x114C3 }, + .{ .first = 0x115B2, .last = 0x115B5 }, // Siddham + .{ .first = 0x115BC, .last = 0x115BD }, + .{ .first = 0x115BF, .last = 0x115C0 }, + .{ .first = 0x115DC, .last = 0x115DD }, + .{ .first = 0x11633, .last = 0x1163A }, // Modi + .{ .first = 0x1163D, .last = 0x1163D }, + .{ .first = 0x1163F, .last = 0x11640 }, + .{ .first = 0x116AB, .last = 0x116AB }, // Takri + .{ .first = 0x116AD, .last = 0x116AD }, + .{ .first = 0x116B0, .last = 0x116B5 }, + .{ .first = 0x116B7, .last = 0x116B7 }, + .{ .first = 0x1171D, .last = 0x1171F }, // Ahom + .{ .first = 0x11722, .last = 0x11725 }, + .{ .first = 0x11727, .last = 0x1172B }, + .{ .first = 0x1182F, .last = 0x11837 }, // Dogra + .{ .first = 0x11839, .last = 0x1183A }, + .{ .first = 0x1193B, .last = 0x1193C }, // Dives Akuru + .{ .first = 0x1193E, .last = 0x1193E }, + .{ .first = 0x11943, .last = 0x11943 }, + .{ .first = 0x119D4, .last = 0x119D7 }, // Nandinagari + .{ .first = 0x119DA, .last = 0x119DB }, + .{ .first = 0x119E0, .last = 0x119E0 }, + .{ .first = 0x11A01, .last = 0x11A0A }, // Zanabazar Square + .{ .first = 0x11A33, .last = 0x11A38 }, + .{ .first = 0x11A3B, .last = 0x11A3E }, + .{ .first = 0x11A47, .last = 0x11A47 }, + .{ .first = 0x11A51, .last = 0x11A56 }, // Soyombo + .{ .first = 0x11A59, .last = 0x11A5B }, + .{ .first = 0x11A8A, .last = 0x11A96 }, + .{ .first = 0x11A98, .last = 0x11A99 }, + .{ .first = 0x11C30, .last = 0x11C36 }, // Bhaiksuki + .{ .first = 0x11C38, .last = 0x11C3D }, + .{ .first = 0x11C3F, .last = 0x11C3F }, + .{ .first = 0x11C92, .last = 0x11CA7 }, // Marchen + .{ .first = 0x11CAA, .last = 0x11CB0 }, + .{ .first = 0x11CB2, .last = 0x11CB3 }, + .{ .first = 0x11CB5, .last = 0x11CB6 }, + .{ .first = 0x11D31, .last = 0x11D36 }, // Masaram Gondi + .{ .first = 0x11D3A, .last = 0x11D3A }, + .{ .first = 0x11D3C, .last = 0x11D3D }, + .{ .first = 0x11D3F, .last = 0x11D45 }, + .{ .first = 0x11D47, .last = 0x11D47 }, + .{ .first = 0x11D90, .last = 0x11D91 }, // Gunjala Gondi + .{ .first = 0x11D95, .last = 0x11D95 }, + .{ .first = 0x11D97, .last = 0x11D97 }, + .{ .first = 0x11EF3, .last = 0x11EF4 }, // Makasar + .{ .first = 0x11F00, .last = 0x11F01 }, // Siddham Extended + .{ .first = 0x11F36, .last = 0x11F3A }, + .{ .first = 0x11F40, .last = 0x11F40 }, + .{ .first = 0x11F42, .last = 0x11F42 }, + .{ .first = 0x13430, .last = 0x13440 }, // Egyptian Hieroglyph format + .{ .first = 0x13447, .last = 0x13455 }, + .{ .first = 0x16AF0, .last = 0x16AF4 }, // Bassa Vah combining + .{ .first = 0x16B30, .last = 0x16B36 }, // Pahawh Hmong combining + .{ .first = 0x16F4F, .last = 0x16F4F }, // Miao combining + .{ .first = 0x16F8F, .last = 0x16F92 }, + .{ .first = 0x16FE4, .last = 0x16FE4 }, // Ideographic combining + .{ .first = 0x1BC9D, .last = 0x1BC9E }, // Duployan combining + .{ .first = 0x1BCA0, .last = 0x1BCA3 }, // Shorthand format + .{ .first = 0x1CF00, .last = 0x1CF2D }, // Znamenny Musical combining + .{ .first = 0x1CF30, .last = 0x1CF46 }, + .{ .first = 0x1D167, .last = 0x1D169 }, // Musical Symbols combining + .{ .first = 0x1D173, .last = 0x1D182 }, + .{ .first = 0x1D185, .last = 0x1D18B }, + .{ .first = 0x1D1AA, .last = 0x1D1AD }, + .{ .first = 0x1D242, .last = 0x1D244 }, // Combining Greek Musical + .{ .first = 0x1DA00, .last = 0x1DA36 }, // Signwriting combining + .{ .first = 0x1DA3B, .last = 0x1DA6C }, + .{ .first = 0x1DA75, .last = 0x1DA75 }, + .{ .first = 0x1DA84, .last = 0x1DA84 }, + .{ .first = 0x1DA9B, .last = 0x1DA9F }, + .{ .first = 0x1DAA1, .last = 0x1DAAF }, + .{ .first = 0x1E000, .last = 0x1E006 }, // Glagolitic combining + .{ .first = 0x1E008, .last = 0x1E018 }, + .{ .first = 0x1E01B, .last = 0x1E021 }, + .{ .first = 0x1E023, .last = 0x1E024 }, + .{ .first = 0x1E026, .last = 0x1E02A }, + .{ .first = 0x1E08F, .last = 0x1E08F }, // Cyrillic Extended-D + .{ .first = 0x1E130, .last = 0x1E136 }, // Nyiakeng Puachue Hmong + .{ .first = 0x1E2AE, .last = 0x1E2AE }, // Wancho combining + .{ .first = 0x1E2EC, .last = 0x1E2EF }, // Mende Kikakui combining + .{ .first = 0x1E4EC, .last = 0x1E4EF }, // Cypro-Minoan + .{ .first = 0x1E8D0, .last = 0x1E8D6 }, // Mende Kikakui combining + .{ .first = 0x1E944, .last = 0x1E94A }, // Adlam combining + .{ .first = 0xE0001, .last = 0xE0001 }, // Language Tag + .{ .first = 0xE0020, .last = 0xE007F }, // Tag characters + .{ .first = 0xE0100, .last = 0xE01EF }, // Variation Selectors Supplement +}; + +/// Wide character ranges (2 cells): CJK, Hangul, fullwidth forms, emoji presentation, etc. +const wide_ranges = [_]Range{ + .{ .first = 0x1100, .last = 0x115F }, // Hangul Jamo initial consonants + .{ .first = 0x231A, .last = 0x231B }, // Watch, Hourglass + .{ .first = 0x2329, .last = 0x232A }, // Angle brackets + .{ .first = 0x23E9, .last = 0x23EC }, // Double triangles + .{ .first = 0x23F0, .last = 0x23F0 }, // Alarm clock + .{ .first = 0x23F3, .last = 0x23F3 }, // Hourglass flowing + .{ .first = 0x25FD, .last = 0x25FE }, // Medium small squares + .{ .first = 0x2614, .last = 0x2615 }, // Umbrella, Hot beverage + .{ .first = 0x2648, .last = 0x2653 }, // Zodiac signs + .{ .first = 0x267F, .last = 0x267F }, // Wheelchair + .{ .first = 0x2693, .last = 0x2693 }, // Anchor + .{ .first = 0x26A1, .last = 0x26A1 }, // High voltage + .{ .first = 0x26AA, .last = 0x26AB }, // Medium circles + .{ .first = 0x26BD, .last = 0x26BE }, // Soccer, Baseball + .{ .first = 0x26C4, .last = 0x26C5 }, // Snowman, Sun behind cloud + .{ .first = 0x26CE, .last = 0x26CE }, // Ophiuchus + .{ .first = 0x26D4, .last = 0x26D4 }, // No entry + .{ .first = 0x26EA, .last = 0x26EA }, // Church + .{ .first = 0x26F2, .last = 0x26F3 }, // Fountain, Golf + .{ .first = 0x26F5, .last = 0x26F5 }, // Sailboat + .{ .first = 0x26FA, .last = 0x26FA }, // Tent + .{ .first = 0x26FD, .last = 0x26FD }, // Fuel pump + .{ .first = 0x2702, .last = 0x2702 }, // Scissors + .{ .first = 0x2705, .last = 0x2705 }, // Check mark + .{ .first = 0x2708, .last = 0x270D }, // Airplane..Writing hand + .{ .first = 0x270F, .last = 0x270F }, // Pencil + .{ .first = 0x2712, .last = 0x2712 }, // Black nib + .{ .first = 0x2714, .last = 0x2714 }, // Check mark + .{ .first = 0x2716, .last = 0x2716 }, // Heavy multiplication + .{ .first = 0x271D, .last = 0x271D }, // Latin cross + .{ .first = 0x2721, .last = 0x2721 }, // Star of David + .{ .first = 0x2728, .last = 0x2728 }, // Sparkles + .{ .first = 0x2733, .last = 0x2734 }, // Eight spoked asterisk + .{ .first = 0x2744, .last = 0x2744 }, // Snowflake + .{ .first = 0x2747, .last = 0x2747 }, // Sparkle + .{ .first = 0x274C, .last = 0x274C }, // Cross mark + .{ .first = 0x274E, .last = 0x274E }, // Cross mark + .{ .first = 0x2753, .last = 0x2755 }, // Question marks + .{ .first = 0x2757, .last = 0x2757 }, // Exclamation mark + .{ .first = 0x2763, .last = 0x2764 }, // Heart exclamation, Heart + .{ .first = 0x2795, .last = 0x2797 }, // Plus, Minus, Division + .{ .first = 0x27A1, .last = 0x27A1 }, // Right arrow + .{ .first = 0x27B0, .last = 0x27B0 }, // Curly loop + .{ .first = 0x27BF, .last = 0x27BF }, // Double curly loop + .{ .first = 0x2934, .last = 0x2935 }, // Arrows + .{ .first = 0x2B05, .last = 0x2B07 }, // Arrows + .{ .first = 0x2B1B, .last = 0x2B1C }, // Large squares + .{ .first = 0x2B50, .last = 0x2B50 }, // Star + .{ .first = 0x2B55, .last = 0x2B55 }, // Large circle + .{ .first = 0x2E80, .last = 0x2E99 }, // CJK Radicals Supplement + .{ .first = 0x2E9B, .last = 0x2EF3 }, + .{ .first = 0x2F00, .last = 0x2FD5 }, // Kangxi Radicals + .{ .first = 0x2FF0, .last = 0x303E }, // Ideographic Description + CJK Symbols + .{ .first = 0x3041, .last = 0x3096 }, // Hiragana + .{ .first = 0x3099, .last = 0x30FF }, // Hiragana/Katakana + .{ .first = 0x3105, .last = 0x312F }, // Bopomofo + .{ .first = 0x3131, .last = 0x318E }, // Hangul Compatibility Jamo + .{ .first = 0x3190, .last = 0x31E3 }, // Kanbun + CJK Strokes + .{ .first = 0x31EF, .last = 0x321E }, // CJK Ideographic Telegraph + Enclosed CJK + .{ .first = 0x3220, .last = 0x3247 }, + .{ .first = 0x3250, .last = 0x4DBF }, // Enclosed CJK + CJK Unified Ext A + .{ .first = 0x4E00, .last = 0xA48C }, // CJK Unified Ideographs + Yi Syllables + .{ .first = 0xA490, .last = 0xA4C6 }, // Yi Radicals + .{ .first = 0xA960, .last = 0xA97C }, // Hangul Jamo Extended-A + .{ .first = 0xAC00, .last = 0xD7A3 }, // Hangul Syllables + .{ .first = 0xF900, .last = 0xFAFF }, // CJK Compatibility Ideographs + .{ .first = 0xFE10, .last = 0xFE19 }, // Vertical Forms + .{ .first = 0xFE30, .last = 0xFE6B }, // CJK Compatibility Forms + Small Form Variants + .{ .first = 0xFF01, .last = 0xFF60 }, // Fullwidth ASCII + Fullwidth punctuation + .{ .first = 0xFFE0, .last = 0xFFE6 }, // Fullwidth signs + .{ .first = 0x16FE0, .last = 0x16FE4 }, // Ideographic Symbols + .{ .first = 0x16FF0, .last = 0x16FF1 }, + .{ .first = 0x17000, .last = 0x187F7 }, // Tangut + .{ .first = 0x18800, .last = 0x18CD5 }, // Tangut Components + .{ .first = 0x18D00, .last = 0x18D08 }, // Tangut Supplement + .{ .first = 0x1AFF0, .last = 0x1AFF3 }, // Kana Extended-B + .{ .first = 0x1AFF5, .last = 0x1AFFB }, + .{ .first = 0x1AFFD, .last = 0x1AFFE }, + .{ .first = 0x1B000, .last = 0x1B122 }, // Kana Supplement + Kana Extended-A + .{ .first = 0x1B132, .last = 0x1B132 }, + .{ .first = 0x1B150, .last = 0x1B152 }, // Small Kana Extension + .{ .first = 0x1B155, .last = 0x1B155 }, + .{ .first = 0x1B164, .last = 0x1B167 }, + .{ .first = 0x1B170, .last = 0x1B2FB }, // Nushu + .{ .first = 0x1F004, .last = 0x1F004 }, // Mahjong tile + .{ .first = 0x1F0CF, .last = 0x1F0CF }, // Playing card + .{ .first = 0x1F18E, .last = 0x1F18E }, // AB button + .{ .first = 0x1F191, .last = 0x1F19A }, // Squared symbols + .{ .first = 0x1F1E0, .last = 0x1F1FF }, // Regional Indicators (flags) + .{ .first = 0x1F200, .last = 0x1F202 }, // Enclosed Ideographic Supplement + .{ .first = 0x1F210, .last = 0x1F23B }, + .{ .first = 0x1F240, .last = 0x1F248 }, + .{ .first = 0x1F250, .last = 0x1F251 }, + .{ .first = 0x1F260, .last = 0x1F265 }, + .{ .first = 0x1F300, .last = 0x1F320 }, // Miscellaneous Symbols and Pictographs + .{ .first = 0x1F32D, .last = 0x1F335 }, + .{ .first = 0x1F337, .last = 0x1F37C }, + .{ .first = 0x1F37E, .last = 0x1F393 }, + .{ .first = 0x1F3A0, .last = 0x1F3CA }, + .{ .first = 0x1F3CF, .last = 0x1F3D3 }, + .{ .first = 0x1F3E0, .last = 0x1F3F0 }, + .{ .first = 0x1F3F4, .last = 0x1F3F4 }, + .{ .first = 0x1F3F8, .last = 0x1F43E }, + .{ .first = 0x1F440, .last = 0x1F440 }, + .{ .first = 0x1F442, .last = 0x1F4FC }, + .{ .first = 0x1F4FF, .last = 0x1F53D }, + .{ .first = 0x1F54B, .last = 0x1F54E }, + .{ .first = 0x1F550, .last = 0x1F567 }, + .{ .first = 0x1F57A, .last = 0x1F57A }, + .{ .first = 0x1F595, .last = 0x1F596 }, + .{ .first = 0x1F5A4, .last = 0x1F5A4 }, + .{ .first = 0x1F5FB, .last = 0x1F64F }, + .{ .first = 0x1F680, .last = 0x1F6C5 }, + .{ .first = 0x1F6CC, .last = 0x1F6CC }, + .{ .first = 0x1F6D0, .last = 0x1F6D2 }, + .{ .first = 0x1F6D5, .last = 0x1F6D7 }, + .{ .first = 0x1F6DC, .last = 0x1F6DF }, + .{ .first = 0x1F6EB, .last = 0x1F6EC }, + .{ .first = 0x1F6F4, .last = 0x1F6FC }, + .{ .first = 0x1F7E0, .last = 0x1F7EB }, + .{ .first = 0x1F7F0, .last = 0x1F7F0 }, + .{ .first = 0x1F90C, .last = 0x1F93A }, + .{ .first = 0x1F93C, .last = 0x1F945 }, + .{ .first = 0x1F947, .last = 0x1F9FF }, + .{ .first = 0x1FA70, .last = 0x1FA7C }, + .{ .first = 0x1FA80, .last = 0x1FA89 }, + .{ .first = 0x1FA8F, .last = 0x1FAC6 }, + .{ .first = 0x1FACE, .last = 0x1FADC }, + .{ .first = 0x1FADF, .last = 0x1FAE9 }, + .{ .first = 0x1FAF0, .last = 0x1FAF8 }, + .{ .first = 0x20000, .last = 0x2FFFD }, // CJK Unified Ideographs Extension B-F + Supplementary + .{ .first = 0x30000, .last = 0x3FFFD }, // CJK Unified Ideographs Extension G-I + Tertiary +}; + +/// Binary search for a codepoint within sorted range tables. +fn inRanges(cp: u21, ranges: []const Range) bool { + var lo: usize = 0; + var hi: usize = ranges.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (cp > ranges[mid].last) { + lo = mid + 1; + } else if (cp < ranges[mid].first) { + hi = mid; + } else { + return true; + } + } + return false; +} + +/// Returns the display width of a Unicode codepoint. +/// -1 = non-printable control, 0 = zero-width, 1 = normal, 2 = wide (double-width). +pub fn codepointWidth(cp: u21) i3 { + // C0 controls (except HT, LF which callers handle) + if (cp < 0x20) return -1; + // DEL + if (cp == 0x7F) return -1; + // C1 controls + if (cp >= 0x80 and cp <= 0x9F) return -1; + + // Zero-width + if (inRanges(cp, &zero_width_ranges)) return 0; + + // Wide + if (inRanges(cp, &wide_ranges)) return 2; + + // Private Use Areas — treat as width 1 + // Noncharacters — treat as width 1 + + return 1; +} + +/// Convenience wrapper: returns display width clamped to 0 (controls treated as 0). +pub fn charWidth(cp: u21) usize { + const w = codepointWidth(cp); + return if (w > 0) @intCast(w) else 0; +} + +/// Calculate the display width of a UTF-8 string (no ANSI awareness). +pub fn strWidth(str: []const u8) usize { + var w: usize = 0; + var i: usize = 0; + while (i < str.len) { + const byte_len = std.unicode.utf8ByteSequenceLength(str[i]) catch { + i += 1; + continue; + }; + if (i + byte_len > str.len) break; + const cp = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { + i += 1; + continue; + }; + w += charWidth(cp); + i += byte_len; + } + return w; +} + +// ── Tests ────────────────────────────────────────────────────────────── + +test "ASCII characters are width 1" { + try std.testing.expectEqual(@as(usize, 1), charWidth('A')); + try std.testing.expectEqual(@as(usize, 1), charWidth('z')); + try std.testing.expectEqual(@as(usize, 1), charWidth(' ')); + try std.testing.expectEqual(@as(usize, 1), charWidth('~')); +} + +test "control characters are width 0 via charWidth" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0x00)); // NUL + try std.testing.expectEqual(@as(usize, 0), charWidth(0x01)); // SOH + try std.testing.expectEqual(@as(usize, 0), charWidth(0x7F)); // DEL + try std.testing.expectEqual(@as(usize, 0), charWidth(0x80)); // C1 + try std.testing.expectEqual(@as(usize, 0), charWidth(0x9F)); // C1 end +} + +test "control characters are -1 via codepointWidth" { + try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x00)); + try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x7F)); + try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x9F)); +} + +test "combining marks are zero-width" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0x0300)); // Combining Grave Accent + try std.testing.expectEqual(@as(usize, 0), charWidth(0x0301)); // Combining Acute Accent + try std.testing.expectEqual(@as(usize, 0), charWidth(0x036F)); // End of basic combining + try std.testing.expectEqual(@as(usize, 0), charWidth(0x20D0)); // Combining symbol marks + try std.testing.expectEqual(@as(usize, 0), charWidth(0xFE0F)); // Variation Selector-16 + try std.testing.expectEqual(@as(usize, 0), charWidth(0xFE00)); // Variation Selector-1 +} + +test "zero-width format characters" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0x200B)); // ZWSP + try std.testing.expectEqual(@as(usize, 0), charWidth(0x200C)); // ZWNJ + try std.testing.expectEqual(@as(usize, 0), charWidth(0x200D)); // ZWJ + try std.testing.expectEqual(@as(usize, 0), charWidth(0xFEFF)); // BOM + try std.testing.expectEqual(@as(usize, 0), charWidth(0x2060)); // Word Joiner +} + +test "CJK ideographs are wide" { + try std.testing.expectEqual(@as(usize, 2), charWidth(0x4E00)); // CJK Unified start + try std.testing.expectEqual(@as(usize, 2), charWidth(0x9FFF)); // CJK Unified + try std.testing.expectEqual(@as(usize, 2), charWidth(0x4E2D)); // 中 + try std.testing.expectEqual(@as(usize, 2), charWidth(0x6587)); // 文 +} + +test "Hangul syllables are wide" { + try std.testing.expectEqual(@as(usize, 2), charWidth(0xAC00)); // Hangul Syllable start + try std.testing.expectEqual(@as(usize, 2), charWidth(0xD7A3)); // Hangul Syllable end +} + +test "Hangul Jamo medials/finals are zero-width" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0x1160)); // Jamo medial start + try std.testing.expectEqual(@as(usize, 0), charWidth(0x11FF)); // Jamo final end +} + +test "fullwidth forms are wide" { + try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF01)); // Fullwidth ! + try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF21)); // Fullwidth A + try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF41)); // Fullwidth a +} + +test "halfwidth Katakana is normal width" { + try std.testing.expectEqual(@as(usize, 1), charWidth(0xFF61)); // Halfwidth Katakana start + try std.testing.expectEqual(@as(usize, 1), charWidth(0xFF9F)); // Halfwidth Katakana end +} + +test "emoji are wide" { + try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F600)); // Grinning face + try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F4A9)); // Pile of poo + try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F680)); // Rocket + try std.testing.expectEqual(@as(usize, 2), charWidth(0x2615)); // Hot beverage + try std.testing.expectEqual(@as(usize, 2), charWidth(0x231A)); // Watch +} + +test "variation selectors are zero-width" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0xE0100)); // VS17 + try std.testing.expectEqual(@as(usize, 0), charWidth(0xE01EF)); // VS256 +} + +test "strWidth with mixed content" { + try std.testing.expectEqual(@as(usize, 4), strWidth("中文")); // 2 wide chars + try std.testing.expectEqual(@as(usize, 5), strWidth("hello")); + try std.testing.expectEqual(@as(usize, 6), strWidth("hi中文")); // h=1 i=1 中=2 文=2 => 6 +} + +test "strWidth with combining characters" { + // e + combining acute accent = 1 display column + try std.testing.expectEqual(@as(usize, 1), strWidth("e\xcc\x81")); + // a + combining ring above = 1 + try std.testing.expectEqual(@as(usize, 1), strWidth("a\xcc\x8a")); +} + +test "CJK Extension B is wide" { + try std.testing.expectEqual(@as(usize, 2), charWidth(0x20000)); // Extension B start + try std.testing.expectEqual(@as(usize, 2), charWidth(0x2A6DF)); // Extension B range +} + +test "soft hyphen is zero-width" { + try std.testing.expectEqual(@as(usize, 0), charWidth(0x00AD)); +} From e1da21d6af3459f8947f30f20e174076576001e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 7 May 2026 07:32:59 +0000 Subject: [PATCH 06/10] chore: remove accidentally committed zig-pkg cache, add to .gitignore --- .gitignore | 1 + .../LICENSE | 21 - .../README.md | 1295 ----------- .../build.zig | 164 -- .../build.zig.zon | 14 - .../src/accessibility.zig | 169 -- .../src/components/bar_chart.zig | 289 --- .../src/components/braille_canvas.zig | 412 ---- .../src/components/breadcrumb.zig | 223 -- .../src/components/calendar.zig | 304 --- .../src/components/canvas.zig | 484 ----- .../src/components/chart.zig | 758 ------- .../src/components/charting.zig | 253 --- .../src/components/checkbox.zig | 434 ---- .../src/components/code_view.zig | 255 --- .../src/components/command_palette.zig | 422 ---- .../src/components/confirm.zig | 154 -- .../src/components/context_menu.zig | 392 ---- .../src/components/data_table.zig | 530 ----- .../src/components/diff_view.zig | 285 --- .../src/components/dropdown.zig | 719 ------- .../src/components/file_picker.zig | 419 ---- .../src/components/focus.zig | 553 ----- .../src/components/form.zig | 299 --- .../src/components/gauge.zig | 249 --- .../src/components/heatmap.zig | 250 --- .../src/components/help.zig | 238 -- .../src/components/keybinding.zig | 114 - .../src/components/list.zig | 490 ----- .../src/components/markdown.zig | 350 --- .../src/components/menu_bar.zig | 576 ----- .../src/components/modal.zig | 761 ------- .../src/components/notification.zig | 139 -- .../src/components/paginator.zig | 226 -- .../src/components/progress.zig | 264 --- .../src/components/radio_group.zig | 276 --- .../src/components/rich_log.zig | 422 ---- .../src/components/slider.zig | 291 --- .../src/components/sortable_table.zig | 321 --- .../src/components/sparkline.zig | 229 -- .../src/components/spinner.zig | 146 -- .../src/components/split_pane.zig | 246 --- .../src/components/status_bar.zig | 215 -- .../src/components/stepper.zig | 254 --- .../src/components/styled_list.zig | 169 -- .../src/components/tab_group.zig | 1066 --------- .../src/components/table.zig | 469 ---- .../src/components/text_area.zig | 1057 --------- .../src/components/text_input.zig | 462 ---- .../src/components/timer.zig | 223 -- .../src/components/toast.zig | 444 ---- .../src/components/tooltip.zig | 925 -------- .../src/components/tree.zig | 185 -- .../src/components/viewport.zig | 456 ---- .../src/components/virtual_list.zig | 216 -- .../src/core/action.zig | 410 ---- .../src/core/animation.zig | 185 -- .../src/core/async_task.zig | 108 - .../src/core/command.zig | 304 --- .../src/core/context.zig | 382 ---- .../src/core/dev_console.zig | 342 --- .../src/core/fuzzy.zig | 171 -- .../src/core/log.zig | 60 - .../src/core/message.zig | 90 - .../src/core/program.zig | 833 ------- .../src/core/screen_stack.zig | 393 ---- .../src/core/sub_program.zig | 87 - .../src/input/hitbox.zig | 128 -- .../src/input/keyboard.zig | 329 --- .../src/input/keys.zig | 191 -- .../src/input/mouse.zig | 164 -- .../src/layout/flex.zig | 473 ---- .../src/layout/join.zig | 225 -- .../src/layout/layer.zig | 156 -- .../src/layout/layout.zig | 41 - .../src/layout/measure.zig | 279 --- .../src/layout/place.zig | 388 ---- .../src/root.zig | 386 ---- .../src/style/border.zig | 303 --- .../src/style/color.zig | 310 --- .../src/style/compress.zig | 156 -- .../src/style/overflow.zig | 287 --- .../src/style/style.zig | 1060 --------- .../src/style/theme.zig | 481 ----- .../src/terminal/ansi.zig | 372 ---- .../src/terminal/platform/posix.zig | 204 -- .../src/terminal/platform/wasm.zig | 178 -- .../src/terminal/platform/windows.zig | 346 --- .../src/terminal/screen.zig | 306 --- .../src/terminal/terminal.zig | 1914 ----------------- .../src/testing/snapshot.zig | 232 -- .../src/unicode.zig | 96 - .../src/unicode/display_width.zig | 677 ------ 93 files changed, 1 insertion(+), 33624 deletions(-) delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig delete mode 100644 zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig diff --git a/.gitignore b/.gitignore index 3389c86..03cb27d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .zig-cache/ zig-out/ +zig-pkg/ diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE deleted file mode 100644 index ea076d3..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Matthew Meszaros - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md deleted file mode 100644 index 13ae4f6..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/README.md +++ /dev/null @@ -1,1295 +0,0 @@ -# ZigZag - -A delightful TUI framework for Zig, inspired by [Bubble Tea](https://github.com/charmbracelet/bubbletea) and [Lipgloss](https://github.com/charmbracelet/lipgloss). - -![Demo](assets/showcase.gif) - -## Features - -- **Elm Architecture** - Model-Update-View pattern for predictable state management -- **Rich Styling** - Comprehensive styling system with colors, borders, padding, margin backgrounds, per-side border colors, tab width control, style ranges, full style inheritance, text transforms, whitespace formatting controls, and unset methods -- **34+ Pre-built Components** - TextInput (with autocomplete/word movement), TextArea, List (fuzzy filtering), Table (interactive with row selection), SortableTable (column sorting, filtering), Viewport, VirtualList (lazy rendering for 100K+ items), Progress (color gradients), Gauge (bar, level meter, blocks with thresholds), Spinner, Tree, StyledList, Sparkline, Chart (linear, stepped, smoothed, area, scatter), BarChart, Heatmap (4 color scales), Canvas, Calendar/DatePicker, CodeView (syntax highlighting for 5 languages), DiffView (unified and side-by-side), Notification/Toast, Confirm dialog, Modal/Popup, Tooltip, Help, Paginator, Timer, FilePicker, TabGroup (multi-view routing), Form, Markdown, Dropdown, Checkbox/RadioGroup, Slider, MenuBar, ContextMenu -- **Focus Management** - `FocusGroup` with Tab/Shift+Tab cycling, comptime focusable protocol, `FocusStyle` for visual focus ring indicators -- **Keybinding Management** - Structured `KeyBinding`/`KeyMap` with matching, display formatting, and Help component integration -- **Color System** - ANSI 16, 256, and TrueColor with adaptive colors, color profile detection, and dark background detection -- **Command System** - Quit, tick, repeating tick (`every`), batch, sequence, suspend/resume, runtime terminal control (mouse, cursor, alt screen, title), print above program, comprehensive image rendering, AsyncRunner for background tasks -- **Sub-Programs** - Embed independent child models inside a parent with message routing and lifecycle management -- **Text Overflow** - Configurable overflow policies (hidden, ellipsis, word_wrap, char_wrap) integrated into the Style system -- **Image Rendering** - Kitty/iTerm2/Sixel with in-memory data, file paths, image caching (transmit once, display many), z-index layering, unicode placeholders for text reflow, protocol override, and file validation -- **Custom I/O** - Pipe-friendly with configurable input/output streams for testing and automation -- **Kitty Keyboard Protocol** - Modern keyboard handling with key release events and unambiguous key identification -- **Bracketed Paste** - Paste events delivered as a single message instead of individual keystrokes -- **Debug Logging** - File-based timestamped logging since stdout is owned by the renderer -- **Message Filtering** - Intercept and transform messages before they reach your model -- **ANSI Compression** - Reduce output overhead with diff-based style state tracking and redundant sequence elimination -- **Layout** - Horizontal/vertical joining, ANSI-aware measurement, 2D placement, float-based positioning, horizontal/vertical single-axis placement, overlay compositing, constraint-based Flexbox engine (fixed, percentage, min, max, ratio, fill), layer compositing with z-ordering -- **Cross-platform** - Works on macOS, Linux, and Windows -- **Zero Dependencies** - Pure Zig with no external dependencies - -## Installation - -Add ZigZag to your `build.zig.zon`: -```sh -zig fetch --save git+https://github.com/meszmate/zigzag#main -``` - -Then in your `build.zig`: - -```zig -const zigzag = b.dependency("zigzag", .{ - .target = target, - .optimize = optimize, -}); -exe.root_module.addImport("zigzag", zigzag.module("zigzag")); -``` - -## Quick Start - -```zig -const std = @import("std"); -const zz = @import("zigzag"); - -const Model = struct { - count: i32, - - pub const Msg = union(enum) { - key: zz.KeyEvent, - }; - - pub fn init(self: *Model, _: *zz.Context) zz.Cmd(Msg) { - self.* = .{ .count = 0 }; - return .none; - } - - pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { - switch (msg) { - .key => |k| switch (k.key) { - .char => |c| if (c == 'q') return .quit, - .up => self.count += 1, - .down => self.count -= 1, - else => {}, - }, - } - return .none; - } - - pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { - const style = (zz.Style{}).bold(true).fg(.cyan); - const text = std.fmt.allocPrint(ctx.allocator, "Count: {d}\n\nPress q to quit", .{self.count}) catch "Error"; - return style.render(ctx.allocator, text) catch text; - } -}; - -pub fn main(init: std.process.Init) !void { - var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); - defer program.deinit(); - try program.run(); -} -``` - -## Core Concepts - -### The Elm Architecture - -ZigZag uses the Elm Architecture (Model-Update-View): - -1. **Model** - Your application state -2. **Msg** - Messages that describe state changes -3. **init** - Initialize your model -4. **update** - Handle messages and update state -5. **view** - Render your model to a string - -### Commands - -Commands let you perform side effects: - -```zig -return .quit; // Quit the application -return .none; // Do nothing -return .{ .tick = ns }; // Request a tick after `ns` nanoseconds -return Cmd(Msg).everyMs(16); // Repeating tick every 16ms (~60fps) -return Cmd(Msg).tickMs(1000); // One-shot tick after 1 second -return .suspend_process; // Suspend (like Ctrl+Z) -return .enable_mouse; // Enable mouse tracking at runtime -return .disable_mouse; // Disable mouse tracking -return .show_cursor; // Show terminal cursor -return .hide_cursor; // Hide terminal cursor -return .{ .set_title = "My App" }; // Set terminal window title -return .{ .println = "Log message" }; // Print above the program output -return .{ .image_file = .{ // Draw image via Kitty/iTerm2/Sixel when available - .path = "assets/cat.png", - .width_cells = 40, - .height_cells = 20, - .placement = .center, // .cursor, .top_left, .top_center, .center - .row_offset = -6, // Negative = higher, positive = lower - .col_offset = 0, // Negative = left, positive = right - // .row = 2, .col = 10, // Optional absolute position override - .move_cursor = false, // Helpful for iTerm2 placement - .protocol = .auto, // .auto, .kitty, .iterm2, .sixel - .z_index = -1, // Kitty: render behind text - .unicode_placeholder = false, // Kitty: participate in text reflow -} }; -return .{ .image_data = .{ // Draw in-memory image data - .data = png_bytes, // Raw RGB, RGBA, or PNG bytes - .format = .png, // .rgb, .rgba, .png - .pixel_width = 100, // Required for RGB/RGBA - .pixel_height = 100, - .width_cells = 20, - .height_cells = 10, - .placement = .center, -} }; -return .{ .cache_image = .{ // Upload to Kitty cache (transmit once) - .source = .{ .file = "assets/logo.png" }, - .image_id = 1, -} }; -return .{ .place_cached_image = .{ // Display cached image (no re-upload) - .image_id = 1, - .placement = .center, - .width_cells = 20, - .height_cells = 10, -} }; -return .{ .delete_image = .{ .by_id = 1 } }; // Free cached image -return .{ .delete_image = .all }; // Free all cached images -``` - -### Styling - -The styling system is inspired by Lipgloss: - -```zig -const style = (zz.Style{}) - .bold(true) - .italic(true) - .fg(.cyan) - .bg(.black) - .paddingAll(1) - .marginAll(2) - .marginBackground(.gray(3)) - .borderAll(.rounded) - .borderForeground(.magenta) - .borderTopForeground(.cyan) // Per-side border colors - .borderBottomForeground(.green) - .tabWidth(4) - .width(40) - .alignH(.center); - -const output = try style.render(allocator, "Hello, World!"); -// render() does not append an implicit trailing '\n' - -// Text transforms -const upper_style = (zz.Style{}).transform(.uppercase); -const shouting = try upper_style.render(allocator, "hello"); // "HELLO" - -// Inline mode is useful when embedding block-styled output in a single line -const inline = (zz.Style{}).fg(.cyan).inline_style(true); - -// Whitespace formatting controls -const ws_style = (zz.Style{}) - .underline(true) - .setUnderlineSpaces(true) // Underline extends through spaces - .setColorWhitespace(false); // Don't apply bg color to whitespace - -// Unset individual properties -const derived = style.unsetBold().unsetPadding().unsetBorder(); - -// Style inheritance (unset values inherit from parent) -const child = (zz.Style{}).fg(.red).inherit(style); - -// Style ranges - apply different styles to byte ranges -const ranges = &[_]zz.StyleRange{ - .{ .start = 0, .end = 5, .s = (zz.Style{}).bold(true) }, -}; -const ranged = try zz.renderWithRanges(allocator, "Hello World", ranges); - -// Highlight specific positions (for fuzzy match results) -const highlighted = try zz.renderWithHighlights(allocator, "hello", &.{0, 2}, highlight_style, base_style); -``` - -### Colors - -```zig -// Basic ANSI colors -zz.Color.red -zz.Color.cyan -zz.Color.brightGreen - -// 256-color palette -zz.Color.color256(123) -zz.Color.gray(15) // 0-23 grayscale - -// True color (24-bit) -zz.Color.fromRgb(255, 128, 64) -zz.Color.hex("#FF8040") - -// Adaptive colors (change based on terminal capabilities) -const adaptive = zz.AdaptiveColor{ - .true_color = .hex("#FF8040"), - .color_256 = .color256(208), - .ansi = .red, -}; -const resolved = adaptive.resolve(ctx.true_color, ctx.color_256); - -// Color profile detection (automatic via context) -// ctx.color_profile: .ascii, .ansi, .ansi256, .true_color -// ctx.is_dark_background: bool - -// Color interpolation (for gradients) -const mid = zz.interpolateColor(.red, .green, 0.5); -``` - -### Borders - -```zig -zz.Border.normal // ┌─┐ -zz.Border.rounded // ╭─╮ -zz.Border.double // ╔═╗ -zz.Border.thick // ┏━┓ -zz.Border.ascii // +-+ -zz.Border.block // ███ -zz.Border.dashed // ┌╌┐ -zz.Border.dotted // ┌┈┐ -zz.Border.inner_half_block // ▗▄▖ -zz.Border.outer_half_block // ▛▀▜ -zz.Border.markdown // |-| -``` - -## Components - -### TextInput - -Single-line text input with cursor, validation, autocomplete, and word-level movement: - -```zig -var input = zz.TextInput.init(allocator); -input.setPlaceholder("Enter name..."); -input.setPrompt("> "); -input.setSuggestions(&.{ "hello", "help", "world" }); // Tab to accept -// Supports: Alt+Left/Right for word movement, Ctrl+W delete word -input.handleKey(key_event); -const view = try input.view(allocator); -``` - -### TextArea - -Multi-line text editor: - -```zig -var editor = zz.components.TextArea.init(allocator); -editor.setSize(80, 24); -editor.line_numbers = true; -editor.handleKey(key_event); -``` - -### List - -Selectable list with fuzzy filtering and status bar: - -```zig -var list = zz.List(MyItem).init(allocator); -list.multi_select = true; -list.show_item_count = true; // Shows "3/10 items" -try list.addItem(.init(item, "Item 1")); -// Fuzzy filtering: press / to filter, matches score by consecutive chars -list.handleKey(key_event); -``` - -### Viewport - -Scrollable content area with wrapping, horizontal scrolling, customizable scrollbar chars/styles, and built-in navigation keys (`j/k/h/l`, arrows, `PgUp/PgDn`, `g/G`, `d/u`): - -```zig -var viewport = zz.Viewport.init(allocator, 80, 24); -try viewport.setContent(long_text); -viewport.setWrap(true); -viewport.setScrollbarChars("·", "█"); -viewport.setScrollbarStyle( - (zz.Style{}).fg(.gray(8)).inline_style(true), - (zz.Style{}).fg(.cyan).inline_style(true), -); -viewport.handleKey(key_event); // Supports j/k, Page Up/Down, etc. -``` - -### Progress - -Progress bar with optional color gradients: - -```zig -var progress = zz.Progress.init(); -progress.setWidth(40); -progress.setGradient(.hex("#FF6B6B"), .hex("#4ECDC4")); -progress.setPercent(75); -const bar = try progress.view(allocator); -``` - -### Spinner - -Animated loading indicator: - -```zig -var spinner = zz.Spinner.init(); -spinner.update(elapsed_ns); -const view = try spinner.viewWithTitle(allocator, "Loading..."); -``` - -### Table - -Interactive tabular data display with row selection and navigation: - -```zig -var table = zz.Table(3).init(allocator); -table.setHeaders(.{ "Name", "Age", "City" }); -try table.addRow(.{ "Alice", "30", "NYC" }); -try table.addRow(.{ "Bob", "25", "LA" }); -table.focus(); // Enable interactive mode -table.show_row_borders = true; // Horizontal separators between rows -// Supports: j/k, up/down, pgup/pgdown, g/G for navigation -table.handleKey(key_event); -const selected = table.selectedRow(); // Get highlighted row index -``` - -### Tree - -Hierarchical tree view with customizable enumerators: - -```zig -var tree = zz.Tree(void).init(allocator); -const root = try tree.addRoot({}, "project/"); -const src = try tree.addChild(root, {}, "src/"); -_ = try tree.addChild(src, {}, "main.zig"); -const view = try tree.view(allocator); -// Output: -// project/ -// └── src/ -// └── main.zig -``` - -### StyledList - -Rendering list with enumerators (bullet, arabic, roman, alphabet): - -```zig -var list = zz.StyledList.init(allocator); -list.setEnumerator(.roman); -try list.addItem("First item"); -try list.addItem("Second item"); -try list.addItemNested("Sub-item", 1); -// Output: -// I. First item -// II. Second item -// I. Sub-item -``` - -### Sparkline - -Mini chart using Unicode block elements with configurable bucketing, ranges, and gradients: - -```zig -var spark = zz.Sparkline.init(allocator); -spark.setWidth(20); -spark.setSummary(.average); -spark.setGradient(.hex("#F97316"), .hex("#22C55E")); -try spark.push(10.0); -try spark.push(25.0); -try spark.push(15.0); -const chart = try spark.view(allocator); -``` - -### Chart - -Cartesian chart with multiple datasets, axes, grid lines, legends, selectable markers, and interpolation modes (`linear`, stepped, `catmull_rom`, `monotone_cubic`): - -Charts are passive views over your data. They do not animate on their own; they only change when your model updates the dataset. `zig build run-charts` and the `Charts` tab in `zig build run-showcase` demonstrate both static snapshot charts and slower sampled/live updates. The standalone `run-charts` demo now renders as a compact chart dashboard that fits like the other examples instead of behaving like a scrollable document. - -![Charts Example](assets/charts.jpg) - -```zig -var chart = zz.Chart.init(allocator); -chart.setSize(48, 16); -chart.setMarker(.braille); -chart.x_axis = .{ .title = "Time", .tick_count = 5, .show_grid = true }; -chart.y_axis = .{ .title = "CPU", .tick_count = 5, .show_grid = true }; - -var dataset = try zz.ChartDataset.init(allocator, "load"); -dataset.setStyle((zz.Style{}).fg(.cyan).bold(true)); -dataset.setShowPoints(true); -dataset.setInterpolation(.monotone_cubic); -dataset.setInterpolationSteps(10); -try dataset.setPoints(&.{ - .{ .x = 0, .y = 20 }, - .{ .x = 1, .y = 45 }, - .{ .x = 2, .y = 30 }, -}); -try chart.addDataset(dataset); - -const view = try chart.view(allocator); -``` - -### BarChart - -Vertical or horizontal bar chart with labels, values, and positive/negative baselines: - -```zig -var bars = zz.BarChart.init(allocator); -bars.setOrientation(.horizontal); -bars.show_values = true; -try bars.addBar(try .init(allocator, "api", 31)); -try bars.addBar(try .init(allocator, "db", -12)); -const view = try bars.view(allocator); -``` - -### Canvas - -Low-level plotting canvas for custom graphs, scatter plots, and braille-dot drawing: - -```zig -var canvas = zz.Canvas.init(allocator); -defer canvas.deinit(); - -canvas.setSize(24, 10); -canvas.setMarker(.braille); -canvas.setRanges(.{ .min = -1, .max = 1 }, .{ .min = -1, .max = 1 }); -try canvas.drawLineStyled(-1, -1, 1, 1, (zz.Style{}).fg(.yellow), null); -try canvas.drawPointStyled(0.25, 0.7, (zz.Style{}).fg(.cyan), null); -const view = try canvas.view(allocator); -``` - -### Notification/Toast - -Auto-dismissing timed messages with severity levels: - -```zig -var notifs = zz.Notification.init(allocator); -try notifs.push("Build complete!", .success, 3000, current_ns); -notifs.update(current_ns); // Removes expired notifications -const view = try notifs.view(allocator); -``` - -### Confirm - -Simple yes/no confirmation dialog: - -```zig -var confirm = zz.Confirm.init("Are you sure?"); -confirm.show(); -confirm.handleKey(key_event); // Left/Right, Enter, y/n -if (confirm.result()) |yes| { - if (yes) { /* confirmed */ } -} -``` - -### Modal - -Dialog overlay with buttons, backdrop, and focus support: - -```zig -var modal = zz.Modal.info("Notice", "Operation completed successfully."); -modal.show(); - -// In update: -modal.handleKey(key_event); -if (modal.getResult()) |res| { - switch (res) { - .button_pressed => |idx| { /* button at idx was pressed */ }, - .dismissed => { /* user pressed Escape */ }, - } -} - -// In view: -if (modal.isVisible()) { - return modal.viewWithBackdrop(allocator, ctx.width, ctx.height); -} -``` - -Presets: `Modal.info()`, `Modal.confirm()`, `Modal.warning()`, `Modal.err()`, or `Modal.init()` for full custom. - -### Tooltip - -Contextual hint positioned near a target element with cell-based overlay compositing: - -```zig -var tip = zz.Tooltip.init("Save the current document"); -tip.target_x = 10; -tip.target_y = 5; -tip.placement = .bottom; // .top, .bottom, .left, .right -tip.show(); - -// In view — overlays onto existing content: -if (tip.isVisible()) { - return tip.overlay(allocator, base_view, ctx.width, ctx.height); -} -``` - -Presets: `Tooltip.init(text)`, `Tooltip.titled(title, text)`, `Tooltip.help(text)`, `Tooltip.shortcut(label, key)`. Supports `border_bg`, `arrow_bg`, `content_bg`, and `inherit_bg` for full background control. - -### TabGroup - -Multi-screen tab navigation with fully customizable keymaps, styles, and optional per-tab route callbacks: - -```zig -var tabs = zz.TabGroup.init(allocator); -defer tabs.deinit(); - -tabs.show_numbers = true; -tabs.max_width = 60; // overflow-aware tab strip -tabs.overflow_mode = .scroll; // .none, .clip, .scroll -tabs.activate_on_focus = true; // set false for manual activation - -_ = try tabs.addTab(.{ .id = "home", .title = "Home" }); -_ = try tabs.addTab(.{ .id = "logs", .title = "Logs", .enabled = false }); -_ = try tabs.addTab(.{ .id = "settings", .title = "Settings" }); - -// In update: -const result = tabs.handleKey(key_event); // Left/Right, Home/End, 1..9 by default -_ = result.change; // optional active-tab change info - -// Optional: route unconsumed keys to active tab callback -const routed = tabs.handleKeyAndRoute(key_event).routed; -_ = routed; - -// In view: -const strip = try tabs.view(allocator); -const with_content = try tabs.viewWithContent(allocator, "No active tab"); -``` - -Per-tab route callback hooks: `render_fn`, `key_fn`, `on_enter_fn`, `on_leave_fn`. - -### Gauge - -Visual meter with bar, level meter, and block display styles: - -```zig -var gauge = zz.Gauge{}; -gauge.value = 73.5; -gauge.width = 40; -gauge.display_style = .bar; // .bar, .level_meter, .blocks -gauge.show_percent = true; -gauge.label = "CPU"; -gauge.full_char = "\xe2\x96\x88"; // Customizable fill character -gauge.empty_char = "\xe2\x96\x91"; // Customizable empty character -gauge.thresholds = &.{ - .{ .value = 80, .color = .yellow }, - .{ .value = 90, .color = .red }, -}; -const output = gauge.view(allocator); -``` - -### Heatmap - -2D data visualization with configurable color scales: - -```zig -var heatmap = zz.Heatmap.init(allocator); -heatmap.setData(7, 24, data); -heatmap.row_labels = &.{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; -heatmap.color_scale = .green_scale; // .green_scale, .cool_to_hot, .grayscale, .blue_red -heatmap.cell_width = 3; -heatmap.show_legend = true; -heatmap.show_values = true; -const output = heatmap.view(allocator); -``` - -### Calendar - -Month view date picker with keyboard navigation: - -```zig -var cal = zz.Calendar{}; -cal.year = 2026; -cal.month = 3; -cal.today_day = 30; -cal.today_month = 3; -cal.today_year = 2026; -cal.cell_width = 4; // Column width for alignment -cal.week_start_monday = true; -cal.day_headers_mon = .{ "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" }; // Customizable -cal.month_names = .{ "Jan", "Feb", ... }; // Customizable -cal.prev_symbol = "\xe2\x97\x80"; // Customizable nav symbols -cal.addMarkedDate(25, .red); -cal.update(key_event); // Arrows, Enter, PgUp/PgDn, Shift+L/R -const output = cal.view(allocator); -``` - -### VirtualList - -Efficient lazy-rendered list for large datasets (100K+ items): - -```zig -var vlist = zz.components.virtual_list.VirtualList(usize){}; -vlist.items = &huge_dataset; -vlist.viewport_height = 20; -vlist.render_fn = &myRenderFn; -vlist.wrap_around = true; // Cursor wraps at ends -vlist.empty_text = "No items"; // Custom empty state -vlist.cursor_symbol = "> "; // Customizable -vlist.show_scrollbar = true; -vlist.update(key_event); -const output = vlist.view(allocator); -``` - -### SortableTable - -Table with column sorting and text filtering: - -```zig -var table = zz.components.sortable_table.SortableTable(4).init(allocator); -table.setHeaders(.{ "Name", "Role", "City", "Score" }); -try table.addRow(.{ "Alice", "Engineer", "NYC", "95" }); -// Press 1-4 to sort by column, / to filter -table.update(key_event); -const output = table.view(allocator); -``` - -### CodeView - -Syntax-highlighted code display: - -```zig -var cv = zz.components.code_view.CodeView{}; -cv.source = source_code; -cv.language = .zig; // .zig, .python, .javascript, .go, .rust, .plain -cv.show_line_numbers = true; -cv.highlight_line = 5; // Highlight a specific line -cv.line_separator = "\xe2\x94\x82"; // Customizable separator -// All token styles are customizable: keyword_style, string_style, -// comment_style, number_style, type_style, builtin_style -const output = cv.view(allocator); -``` - -### DiffView - -Unified and side-by-side diff display: - -```zig -var dv = zz.components.diff_view.DiffView{}; -dv.old_text = old_source; -dv.new_text = new_source; -dv.old_label = "before"; -dv.new_label = "after"; -dv.mode = .unified; // .unified, .side_by_side -dv.side_width = 40; // Width per side in side-by-side mode -dv.add_prefix = "+"; // Customizable prefixes -dv.remove_prefix = "-"; -const output = dv.view(allocator); -``` - -### SubProgram - -Embed independent child models inside a parent: - -```zig -const Counter = struct { ... }; // Has Msg, init, update, view - -const Model = struct { - child: zz.SubProgram(Counter, Msg), - // ... - pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { - self.child = .{}; - _ = self.child.init(ctx); - } - pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) { - return self.child.update(.{ .key = k }, ctx); - } - pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { - return self.child.view(ctx); - } -}; -``` - -### AsyncRunner - -Spawn background tasks that deliver messages on completion: - -```zig -var runner = zz.AsyncRunner(Msg).init(allocator); -_ = runner.spawn(&myBackgroundTask); // Returns task ID -// Each frame: -const results = runner.poll(); // Collect completed messages -for (results) |msg| { /* process */ } -``` - -### Flexbox Layout - -Constraint-based layout engine: - -```zig -const areas = try zz.flex.layout(allocator, width, height, &.{ - .{ .constraint = .{ .fixed = 3 } }, // Header: 3 rows - .{ .constraint = .fill }, // Body: remaining space - .{ .constraint = .{ .percentage = 10 } }, // Footer: 10% -}, .{ .direction = .column, .gap = 1 }); -// areas[0].x, areas[0].y, areas[0].width, areas[0].height -``` - -Constraints: `fixed(n)`, `percentage(pct)`, `min(n)`, `max(n)`, `ratio(num, den)`, `fill`. Options: direction, gap, alignment, justify, wrap. - -### Layer Compositing - -Z-ordered overlay system for popups and modals: - -```zig -var stack = zz.layout.layer.LayerStack.init(allocator); -stack.setSize(width, height); -stack.push(.{ .content = background, .z = 0 }) catch {}; -stack.push(.{ .content = popup, .x = 10, .y = 5, .z = 10 }) catch {}; -const output = stack.render(allocator); -``` - -### Text Overflow - -Integrated into the Style system: - -```zig -var s = zz.Style{}; -s = s.width(40); -s = s.overflow(.ellipsis); // .visible, .hidden, .ellipsis, .word_wrap, .char_wrap -const output = try s.render(allocator, long_text); -``` - -### More Components - -- **Help** - Display key bindings with responsive truncation -- **Paginator** - Pagination controls -- **Timer** - Countdown/stopwatch with warning thresholds -- **FilePicker** - File system navigation - -### Keybinding Management - -Structured key binding definitions with matching and Help integration: - -```zig -var keymap = zz.KeyMap.init(allocator); -defer keymap.deinit(); - -try keymap.addChar('q', "Quit"); -try keymap.addCtrl('s', "Save"); -try keymap.add(.{ - .key_event = zz.KeyEvent{ .key = .up }, - .description = "Move up", - .short_desc = "up", -}); - -// Check if a key event matches any binding -if (keymap.match(key_event)) |binding| { - // Handle the matched binding - _ = binding.description; -} - -// Generate help text from keybindings -var help = try zz.components.Help.fromKeyMap(allocator, &keymap); -defer help.deinit(); -const help_view = try help.view(allocator); -``` - -### Focus Management - -Manage Tab/Shift+Tab cycling between interactive components with `FocusGroup`: - -```zig -const Model = struct { - name: zz.TextInput, - email: zz.TextInput, - focus: zz.FocusGroup(2), - focus_style: zz.FocusStyle, - - pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { - self.name = zz.TextInput.init(ctx.persistent_allocator); - self.email = zz.TextInput.init(ctx.persistent_allocator); - - self.focus = .{}; - self.focus.add(&self.name); // index 0 - self.focus.add(&self.email); // index 1 - self.focus.initFocus(); // focus first, blur rest - - self.focus_style = .{}; // cyan/gray borders by default - return .none; - } - - pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { - switch (msg) { - .key => |k| { - // Tab/Shift+Tab cycles focus (returns true if consumed) - if (self.focus.handleKey(k)) return .none; - // Forward to all — unfocused components auto-ignore - self.name.handleKey(k); - self.email.handleKey(k); - }, - } - return .none; - } - - pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { - // Apply focus ring (border color changes based on focus) - var style = zz.Style{}; - style = style.paddingAll(1); - const name_style = self.focus_style.apply(style, self.focus.isFocused(0)); - const email_style = self.focus_style.apply(style, self.focus.isFocused(1)); - // ... render with styled boxes ... - } -}; -``` - -Any component with `focused: bool`, `focus()`, and `blur()` methods works with `FocusGroup`. -Built-in focusable components: TextInput, TextArea, Table, List, Confirm, FilePicker. - -#### Custom navigation keys - -By default Tab moves forward and Shift+Tab moves backward. Add or replace bindings freely: - -```zig -// Add arrow keys and vim j/k alongside the default Tab -fg.addNextKey(.{ .key = .down }); // Down arrow -fg.addNextKey(.{ .key = .{ .char = 'j' } }); // vim j -fg.addPrevKey(.{ .key = .up }); // Up arrow -fg.addPrevKey(.{ .key = .{ .char = 'k' } }); // vim k - -// Or replace defaults entirely -fg.setNextKey(.{ .key = .down }); // Down only, Tab no longer works -fg.setPrevKey(.{ .key = .up }); // Up only - -// Clear all bindings (manual-only via focusNext/focusPrev) -fg.clearNextKeys(); -fg.clearPrevKeys(); - -// Modifier keys work too -fg.addNextKey(.{ .key = .{ .char = 'n' }, .modifiers = .{ .ctrl = true } }); // Ctrl+N -``` - -Up to 4 bindings per direction. Modifier matching is exact (Ctrl+Tab won't match a plain Tab binding). - -#### Additional API - -```zig -fg.focusAt(2); // Focus specific index -fg.focusNext(); // Manual next -fg.focusPrev(); // Manual prev -fg.blurAll(); // Remove focus from all -fg.focused(); // Get current index -fg.isFocused(1); // Check if index is focused -fg.len(); // Number of registered items - -// Disable wrapping (stop at ends instead of cycling) -var fg: zz.FocusGroup(3) = .{ .wrap = false }; - -// Custom focus ring colors -const fs = zz.FocusStyle{ - .focused_border_fg = .green, - .blurred_border_fg = .gray(8), - .border_chars = .double, -}; -``` - -## Options - -Configure the program with custom options: - -```zig -var program = try zz.Program(Model).initWithOptions(init.gpa, init.io, init.environ_map, .{ - .fps = 60, // Target frame rate - .alt_screen = true, // Use alternate screen buffer - .mouse = false, // Enable mouse tracking - .cursor = false, // Show cursor - .bracketed_paste = true, // Enable bracketed paste mode - .kitty_keyboard = false, // Enable Kitty keyboard protocol - .osc52 = .{ // OSC 52 clipboard defaults - .enabled = true, - .query_enabled = true, // Allow OSC 52 clipboard reads (query) - .target = .clipboard, // .primary, .secondary, .select, .cut_buffer, .raw - .terminator = .bel, // .bel or .st - .passthrough = .auto, // .auto, .none, .tmux, .dcs - .max_bytes = null, // Optional write payload limit - .query_timeout_ms = 180, - .max_read_bytes = null, // Optional decoded read limit - .strict_query_target = false, - }, - .unicode_width_strategy = null, // null=auto, .legacy_wcwidth, .unicode - .suspend_enabled = true, // Enable Ctrl+Z suspend/resume - .title = "My App", // Window title - .log_file = "debug.log", // Debug log file path - .input = custom_stdin, // Custom input (for testing/piping) - .output = custom_stdout, // Custom output (for testing/piping) -}); -``` - -Unicode width strategy can also be overridden per-process with `ZZ_UNICODE_WIDTH=auto|legacy|unicode`. -By default (`null`/`auto`), ZigZag: -- probes DEC mode `2027` and enables it when available, -- probes kitty text-sizing support, -- applies terminal/multiplexer heuristics (e.g. tmux/screen/zellij favor legacy width). - -### Allocator Lifetimes - -`ctx.allocator` is a frame allocator that is reset before each `tick()`. -Use it for temporary values (render strings, per-frame buffers). - -For model state that must live across frames, allocate with `ctx.persistent_allocator`. - -### Custom Event Loop - -For applications that need to do other work between frames (network polling, background processing, etc.), use `start()` + `tick()` instead of `run()`: - -```zig -var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); -defer program.deinit(); - -try program.start(); -while (program.isRunning()) { - try program.tick(); - // poll sockets, process jobs, etc. -} -``` - -### Debug Logging - -Since stdout is owned by the renderer, use file-based logging: - -```zig -// In your update function, log via context: -pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) { - ctx.log("received key: {s}", .{@tagName(msg)}); - // ... -} -``` - -### Message Filtering - -Intercept and transform messages before they reach your model: - -```zig -var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); -program.setFilter(&myFilter); - -fn myFilter(msg: Model.Msg) ?Model.Msg { - // Return null to drop the message, or modify it - return msg; -} -``` - -### Bracketed Paste - -Handle pasted text as a single event by adding a `paste` field to your Msg: - -```zig -pub const Msg = union(enum) { - key: zz.KeyEvent, - paste: []const u8, // Receives full pasted text -}; -``` - -### OSC 52 Clipboard (Copy + Query) - -Copy text/bytes to the system clipboard from your app: - -```zig -// Uses Program option defaults (.osc52) -_ = try ctx.setClipboard("Copied from ZigZag"); -``` - -Query clipboard bytes back from the terminal: - -```zig -if (try ctx.getClipboard(ctx.allocator)) |clip| { - // clip is decoded bytes from OSC 52 response -} -``` - -Per-call overrides for edge cases: - -```zig -_ = try ctx.setClipboardWithOptions("Primary selection", .{ - .target = .primary, - .terminator = .st, - .passthrough = .tmux, - .max_bytes = 64 * 1024, -}); - -if (try ctx.getClipboardWithOptions(ctx.allocator, .{ - .target = .clipboard, - .timeout_ms = 250, - .passthrough = .auto, - .strict_target = true, -})) |clip| { - _ = clip; -} -``` - -Advanced/extension example (non-standard selector string): - -```zig -_ = try ctx.setClipboardWithOptions("Custom selector", .{ - .target = .{ .raw = "c" }, -}); -``` - -Notes: -- Returns `false` when disabled (`.osc52.enabled = false`), blocked by guardrails (TTY/size), or unavailable in current output mode. -- Query returns `null` when disabled/blocked/timed out/no response/invalid payload. -- `.passthrough = .auto` detects tmux/screen-like environments and wraps OSC 52 in DCS passthrough when needed. -- Terminals differ in security policy and maximum accepted sequence length. Use `.max_bytes` to enforce an app-side ceiling if desired. -- The `run-clipboard_osc52` example also handles `Msg.paste` (bracketed paste input) to demonstrate inbound paste events. - -### Suspend/Resume - -Ctrl+Z support is enabled by default. Handle resume events by adding a `resumed` field: - -```zig -pub const Msg = union(enum) { - key: zz.KeyEvent, - resumed: void, // Sent after process resumes from Ctrl+Z -}; -``` - -### Images (Kitty + iTerm2 + Sixel) - -Image commands are automatically no-ops on unsupported terminals. All `draw*` functions return `bool` indicating success. - -#### Basic usage - -```zig -// Draw from file (auto-selects best protocol) -if (ctx.supportsImages()) { - _ = try ctx.drawImageFromFile("assets/cat.png", .{ - .width_cells = 40, - .height_cells = 20, - }); -} - -// Draw from file with specific protocol -_ = try ctx.drawImageFromFileWithProtocol("assets/cat.png", .{ - .width_cells = 40, - .z_index = -1, // Behind text (Kitty only) -}, .kitty); -``` - -#### In-memory image data - -Render raw pixels or PNG bytes directly from memory, without writing to disk: - -```zig -// Draw PNG bytes from memory -_ = try ctx.drawImageData(png_bytes, .{ - .format = .png, - .width_cells = 20, - .height_cells = 10, -}); - -// Draw raw RGBA pixels -_ = try ctx.drawImageData(rgba_pixels, .{ - .format = .rgba, - .pixel_width = 100, // Required for RGB/RGBA - .pixel_height = 100, - .width_cells = 20, -}); -``` - -#### Image caching (Kitty) - -Transmit an image once, display it many times without re-uploading: - -```zig -// Upload to cache (no display) -_ = try ctx.transmitKittyImageFromFile("assets/logo.png", .{ - .image_id = 1, -}); - -// Display cached image at different positions -_ = try ctx.placeKittyImage(.{ - .image_id = 1, - .width_cells = 10, - .height_cells = 5, -}); - -// Clean up when done -_ = try ctx.deleteKittyImage(.{ .by_id = 1 }); -_ = try ctx.deleteKittyImage(.all); // Delete everything -``` - -#### Z-index and unicode placeholders (Kitty) - -```zig -// Render image behind text -_ = try ctx.drawKittyImageFromFile("assets/bg.png", .{ - .z_index = -1, // Negative = behind text - .unicode_placeholder = true, // Image participates in text reflow/scrolling -}); -``` - -#### Protocol override - -Force a specific protocol instead of auto-selection (Kitty > iTerm2 > Sixel): - -```zig -_ = try ctx.drawImageFromFileWithProtocol("image.png", .{}, .iterm2); -_ = try ctx.drawImageDataWithProtocol(data, .{ .format = .png }, .sixel); -``` - -#### Querying capabilities - -```zig -const caps = ctx.getImageCapabilities(); -// caps.kitty_graphics: bool -// caps.iterm2_inline_image: bool -// caps.sixel: bool - -if (ctx.supportsKittyGraphics()) { /* ... */ } -if (ctx.supportsIterm2InlineImages()) { /* ... */ } -if (ctx.supportsSixel()) { /* ... */ } -``` - -#### Command-based API - -All image operations are also available as commands from `update()`: - -```zig -// File image with all options -return .{ .image_file = .{ - .path = "assets/cat.png", - .placement = .center, - .width_cells = 40, - .protocol = .auto, // .auto, .kitty, .iterm2, .sixel - .z_index = -1, // Behind text (Kitty) - .unicode_placeholder = true, // Text reflow (Kitty) -} }; - -// In-memory data -return .{ .image_data = .{ - .data = png_bytes, - .format = .png, // .rgb, .rgba, .png - .width_cells = 20, -} }; - -// Cache + place workflow -return .{ .batch = &.{ - .{ .cache_image = .{ .source = .{ .file = "logo.png" }, .image_id = 1 } }, - .{ .place_cached_image = .{ .image_id = 1, .placement = .center } }, -} }; - -// Delete cached images -return .{ .delete_image = .{ .by_id = 1 } }; -return .{ .delete_image = .all }; -``` - -#### Detection - -Detection combines runtime protocol probes with terminal feature/env hints: -- Kitty graphics: Kitty query command (`a=q`) for confirmation. -- iTerm2 inline images: `OSC 1337;Capabilities`/`TERM_FEATURES` when available. -- Sixel: iTerm/WezTerm `TERM_FEATURES` (`Sx`) and primary device attributes (`CSI c`, param `4`). - -Common terminals supported by default: -- Kitty and Ghostty via Kitty graphics protocol. -- iTerm2 and WezTerm via `OSC 1337` inline images. -- Sixel-capable terminals (for example xterm with Sixel, mlterm, contour). - -#### Notes - -- File paths are validated before sending; missing files return `false` instead of erroring. -- For iTerm2, large images (>750KB encoded) are sent with multipart `OSC 1337` sequences automatically. -- For Sixel, provide a `.sixel`/`.six` file or a regular image with `img2sixel` in `PATH`. Optional `-w`/`-h` pixel hints are passed through. -- Inside multiplexers (tmux/screen/zellij), image passthrough depends on multiplexer configuration. -- Image caching, z-index, and unicode placeholders are Kitty-specific features; they are silently ignored on other protocols. - -## Layout - -### Join - -Combine multiple strings: - -```zig -// Horizontal (side by side) -const row = try zz.joinHorizontal(allocator, &.{ left, middle, right }); - -// Vertical (stacked) -const col = try zz.joinVertical(allocator, &.{ top, middle, bottom }); -``` - -### Measure - -Get text dimensions (ANSI-aware): - -```zig -const w = zz.width("Hello"); // 5 -const h = zz.height("Line 1\nLine 2"); // 2 -``` - -### Place - -Position content in a bounding box: - -```zig -// 2D placement in a bounding box -const centered = try zz.place.place(allocator, 80, 24, .center, .middle, content); - -// Single-axis horizontal placement -const right_aligned = try zz.placeHorizontal(allocator, 80, .right, content); - -// Single-axis vertical placement -const bottom_aligned = try zz.placeVertical(allocator, 24, .bottom, content); - -// Float-based positioning (0.0 = left/top, 0.5 = center, 1.0 = right/bottom) -const placed = try zz.placeFloat(allocator, 80, 24, 0.75, 0.25, content); -``` - -## Examples - -Run the examples: - -```bash -zig build run-hello_world -zig build run-counter -zig build run-todo_list -zig build run-text_editor -zig build run-file_browser -zig build run-dashboard -zig build run-charts # Static snapshots plus slower sampled chart updates -zig build run-showcase # Multi-tab demo of all features -zig build run-focus_form # Focus management with Tab cycling -zig build run-tabs # TabGroup multi-screen routing -zig build run-clipboard_osc52 # OSC 52 clipboard output demo -zig build run-flex_layout # Flexbox constraint-based layout -zig build run-text_overflow # Overflow policies demo -zig build run-gauge # Gauge component styles -zig build run-heatmap # 2D data heatmap visualization -zig build run-calendar # Calendar date picker -zig build run-virtual_list # 100K item virtual scrolling -zig build run-layers # Z-ordered layer compositing -zig build run-sub_program # Nested sub-program models -zig build run-async_tasks # Background task execution -zig build run-sortable_table # Sortable/filterable table -zig build run-code_view # Syntax-highlighted code -zig build run-diff_view # Unified and side-by-side diff -``` - -## Building - -```bash -# Build the library -zig build - -# Run tests -zig build test - -# Build with optimizations -zig build -Doptimize=ReleaseFast -``` - -## Cross-compilation - -```bash -zig build -Dtarget=x86_64-linux -zig build -Dtarget=aarch64-macos -zig build -Dtarget=x86_64-windows -``` - -## Contributing - -Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. - -## License - -MIT License - see LICENSE file for details. - -## Acknowledgments - -- [Bubble Tea](https://github.com/charmbracelet/bubbletea) - The original Go TUI framework -- [Lipgloss](https://github.com/charmbracelet/lipgloss) - Style definitions for terminal applications -- [The Elm Architecture](https://guide.elm-lang.org/architecture/) - The pattern that inspired it all diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig deleted file mode 100644 index 24d73ee..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig +++ /dev/null @@ -1,164 +0,0 @@ -const std = @import("std"); - -pub fn build(b: *std.Build) void { - const target = b.standardTargetOptions(.{}); - const optimize = b.standardOptimizeOption(.{}); - - // Main library module - const zigzag_mod = b.addModule("zigzag", .{ - .root_source_file = b.path("src/root.zig"), - .target = target, - .optimize = optimize, - }); - - // Examples - const examples = [_][]const u8{ - "hello_world", - "counter", - "todo_list", - "text_editor", - "file_browser", - "dashboard", - "charts", - "showcase", - "focus_form", - "modal", - "tooltip", - "tabs", - "clipboard_osc52", - "theming", - "slider", - "menu_bar", - "checkbox_radio", - "dropdown", - "toast", - "context_menu", - "form", - "markdown", - "animation", - "mouse", - "accessibility", - "wasm_app", - "diff_view", - "code_view", - "sortable_table", - "text_overflow", - "async_tasks", - "sub_program", - "layers", - "virtual_list", - "calendar", - "heatmap", - "gauge", - "flex_layout", - "braille_canvas", - "rich_log", - "screen_stack", - "action_system", - "data_table", - "dev_console", - }; - - for (examples) |example_name| { - const example = b.addExecutable(.{ - .name = example_name, - .root_module = b.createModule(.{ - .root_source_file = b.path(b.fmt("examples/{s}.zig", .{example_name})), - .target = target, - .optimize = optimize, - .imports = &.{ - .{ .name = "zigzag", .module = zigzag_mod }, - }, - }), - }); - b.installArtifact(example); - - const run_cmd = b.addRunArtifact(example); - run_cmd.step.dependOn(b.getInstallStep()); - if (b.args) |args| { - run_cmd.addArgs(args); - } - - const run_step = b.step( - b.fmt("run-{s}", .{example_name}), - b.fmt("Run the {s} example", .{example_name}), - ); - run_step.dependOn(&run_cmd.step); - } - - // Tests - const test_files = [_][]const u8{ - "tests/style_tests.zig", - "tests/input_tests.zig", - "tests/layout_tests.zig", - "tests/unicode_tests.zig", - "tests/program_tests.zig", - "tests/focus_tests.zig", - "tests/modal_tests.zig", - "tests/tooltip_tests.zig", - "tests/tab_group_tests.zig", - "tests/chart_tests.zig", - "tests/viewport_tests.zig", - "tests/theme_tests.zig", - "tests/slider_tests.zig", - "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", - "tests/animation_tests.zig", - "tests/accessibility_tests.zig", - "tests/mouse_tests.zig", - }; - - const test_step = b.step("test", "Run unit tests"); - - for (test_files) |test_file| { - const unit_tests = b.addTest(.{ - .root_module = b.createModule(.{ - .root_source_file = b.path(test_file), - .target = target, - .optimize = optimize, - .imports = &.{ - .{ .name = "zigzag", .module = zigzag_mod }, - }, - }), - }); - - const run_unit_tests = b.addRunArtifact(unit_tests); - test_step.dependOn(&run_unit_tests.step); - } - - // Also run tests on the main library - const lib_tests = b.addTest(.{ - .root_module = b.createModule(.{ - .root_source_file = b.path("src/root.zig"), - .target = target, - .optimize = optimize, - }), - }); - const run_lib_tests = b.addRunArtifact(lib_tests); - test_step.dependOn(&run_lib_tests.step); - - // WASM library build (for browser-based terminals) - const wasm_step = b.step("wasm", "Build ZigZag as a WASM library"); - - const wasm_target = b.resolveTargetQuery(.{ - .cpu_arch = .wasm32, - .os_tag = .freestanding, - }); - - const wasm_lib = b.addLibrary(.{ - .name = "zigzag", - .root_module = b.createModule(.{ - .root_source_file = b.path("src/root.zig"), - .target = wasm_target, - .optimize = .ReleaseSmall, - }), - .linkage = .static, - }); - b.installArtifact(wasm_lib); - wasm_step.dependOn(&wasm_lib.step); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon deleted file mode 100644 index 473f6a5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/build.zig.zon +++ /dev/null @@ -1,14 +0,0 @@ -.{ - .name = .zigzag, - .version = "0.1.2", - .fingerprint = 0xdffe16194b187c61, - .minimum_zig_version = "0.16.0", - .paths = .{ - "build.zig", - "build.zig.zon", - "src", - "README.md", - "LICENSE", - }, - .dependencies = .{}, -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig deleted file mode 100644 index 04b7853..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/accessibility.zig +++ /dev/null @@ -1,169 +0,0 @@ -//! Accessibility utilities for ZigZag TUI applications. -//! Provides WCAG contrast checking, screen reader announcements, -//! and semantic role annotations for terminal UIs. - -const std = @import("std"); -const Writer = std.Io.Writer; -const Color = @import("style/color.zig").Color; - -/// WCAG 2.1 contrast ratio levels. -pub const ContrastLevel = enum { - /// Fails WCAG minimum requirements (< 3:1) - fail, - /// Passes large text / UI component requirement (>= 3:1) - aa_large, - /// Passes normal text requirement (>= 4.5:1) - aa, - /// Passes enhanced contrast for normal text (>= 7:1) - aaa, -}; - -/// Check the WCAG compliance level for a foreground/background color pair. -pub fn checkContrast(fg: Color, bg: Color) ContrastLevel { - const ratio = fg.contrastRatio(bg); - if (ratio >= 7.0) return .aaa; - if (ratio >= 4.5) return .aa; - if (ratio >= 3.0) return .aa_large; - return .fail; -} - -/// Returns true if the color pair meets WCAG AA for normal text (4.5:1). -pub fn meetsAA(fg: Color, bg: Color) bool { - return fg.contrastRatio(bg) >= 4.5; -} - -/// Returns true if the color pair meets WCAG AAA for normal text (7:1). -pub fn meetsAAA(fg: Color, bg: Color) bool { - return fg.contrastRatio(bg) >= 7.0; -} - -/// Suggest a foreground color (white or black) that has better contrast -/// against the given background. -pub fn suggestForeground(bg: Color) Color { - const white = Color.white; - const black = Color.black; - const white_ratio = white.contrastRatio(bg); - const black_ratio = black.contrastRatio(bg); - return if (white_ratio >= black_ratio) white else black; -} - -/// Semantic roles for UI components, useful for screen reader hints -/// and accessible descriptions. -pub const Role = enum { - button, - checkbox, - radio, - textbox, - listbox, - option, - menu, - menuitem, - dialog, - alert, - status, - progressbar, - slider, - tab, - tabpanel, - tree, - treeitem, - heading, - separator, - tooltip, - form, - list, - listitem, - link, - img, - none, - - /// Get a human-readable label for this role. - pub fn label(self: Role) []const u8 { - return switch (self) { - .button => "button", - .checkbox => "checkbox", - .radio => "radio button", - .textbox => "text field", - .listbox => "list box", - .option => "option", - .menu => "menu", - .menuitem => "menu item", - .dialog => "dialog", - .alert => "alert", - .status => "status", - .progressbar => "progress bar", - .slider => "slider", - .tab => "tab", - .tabpanel => "tab panel", - .tree => "tree", - .treeitem => "tree item", - .heading => "heading", - .separator => "separator", - .tooltip => "tooltip", - .form => "form", - .list => "list", - .listitem => "list item", - .link => "link", - .img => "image", - .none => "", - }; - } -}; - -/// An accessible label attached to a UI element. -pub const AccessibleLabel = struct { - role: Role = .none, - name: []const u8 = "", - description: []const u8 = "", - value: []const u8 = "", - state: []const u8 = "", - - /// Format an accessible description string for screen readers. - pub fn format(self: AccessibleLabel, allocator: std.mem.Allocator) ![]const u8 { - var parts: Writer.Allocating = .init(allocator); - const w = &parts.writer; - - if (self.role != .none) { - try w.writeAll(self.role.label()); - } - - if (self.name.len > 0) { - if (parts.writer.buffered().len > 0) try w.writeAll(": "); - try w.writeAll(self.name); - } - - if (self.value.len > 0) { - if (parts.writer.buffered().len > 0) try w.writeAll(", "); - try w.writeAll(self.value); - } - - if (self.state.len > 0) { - if (parts.writer.buffered().len > 0) try w.writeAll(", "); - try w.writeAll(self.state); - } - - if (self.description.len > 0) { - if (parts.writer.buffered().len > 0) try w.writeAll(" - "); - try w.writeAll(self.description); - } - - return parts.toOwnedSlice(); - } -}; - -/// Generate a terminal announcement using the window title (OSC 0). -/// Some screen readers pick up title changes as announcements. -pub fn announceViaTitle(allocator: std.mem.Allocator, message: []const u8) ![]const u8 { - return std.fmt.allocPrint(allocator, "\x1b]0;{s}\x07", .{message}); -} - -/// Generate a terminal bell (BEL) to alert the user audibly. -pub fn bell() []const u8 { - return "\x07"; -} - -/// Format a progress value as an accessible string. -pub fn progressDescription(allocator: std.mem.Allocator, value: f64, max: f64) ![]const u8 { - const pct = if (max > 0) (value / max) * 100.0 else 0.0; - return std.fmt.allocPrint(allocator, "{d:.0}% complete", .{pct}); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig deleted file mode 100644 index cd47f4d..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/bar_chart.zig +++ /dev/null @@ -1,289 +0,0 @@ -//! Bar chart widget with vertical and horizontal layouts. - -const std = @import("std"); -const charting = @import("charting.zig"); -const measure = @import("../layout/measure.zig"); -const join = @import("../layout/join.zig"); -const style_mod = @import("../style/style.zig"); - -pub const Style = style_mod.Style; -pub const DataRange = charting.DataRange; -pub const Orientation = charting.Orientation; -pub const ValueFormatter = charting.ValueFormatter; - -pub const Bar = struct { - allocator: std.mem.Allocator, - label: []const u8, - value: f64, - style: ?Style = null, - glyph: []const u8 = "█", - - pub fn init(allocator: std.mem.Allocator, label: []const u8, value: f64) !Bar { - return .{ - .allocator = allocator, - .label = try allocator.dupe(u8, label), - .value = value, - }; - } - - pub fn deinit(self: *Bar) void { - self.allocator.free(self.label); - } - - pub fn setStyle(self: *Bar, style: Style) void { - self.style = charting.inlineStyle(style); - } - - pub fn setGlyph(self: *Bar, glyph: []const u8) void { - self.glyph = glyph; - } -}; - -pub const BarChart = struct { - allocator: std.mem.Allocator, - width: u16, - height: u16, - orientation: Orientation, - bars: std.array_list.Managed(Bar), - bar_width: u16, - gap: u16, - domain: ?DataRange, - baseline: f64, - show_labels: bool, - show_values: bool, - axis_style: Style, - label_style: Style, - value_style: Style, - positive_style: Style, - negative_style: Style, - formatter: ?ValueFormatter, - - pub fn init(allocator: std.mem.Allocator) BarChart { - return .{ - .allocator = allocator, - .width = 40, - .height = 12, - .orientation = .vertical, - .bars = std.array_list.Managed(Bar).init(allocator), - .bar_width = 2, - .gap = 1, - .domain = null, - .baseline = 0, - .show_labels = true, - .show_values = false, - .axis_style = charting.inlineStyle(Style{}), - .label_style = charting.inlineStyle(Style{}), - .value_style = charting.inlineStyle(Style{}), - .positive_style = charting.inlineStyle(Style{}), - .negative_style = charting.inlineStyle(Style{}), - .formatter = null, - }; - } - - pub fn deinit(self: *BarChart) void { - for (self.bars.items) |*bar| bar.deinit(); - self.bars.deinit(); - } - - pub fn clear(self: *BarChart) void { - for (self.bars.items) |*bar| bar.deinit(); - self.bars.clearRetainingCapacity(); - } - - pub fn addBar(self: *BarChart, bar: Bar) !void { - try self.bars.append(bar); - } - - pub fn setSize(self: *BarChart, width: u16, height: u16) void { - self.width = @max(8, width); - self.height = @max(4, height); - } - - pub fn setOrientation(self: *BarChart, orientation: Orientation) void { - self.orientation = orientation; - } - - pub fn setBarWidth(self: *BarChart, bar_width: u16) void { - self.bar_width = @max(1, bar_width); - } - - pub fn setGap(self: *BarChart, gap: u16) void { - self.gap = gap; - } - - pub fn setDomain(self: *BarChart, domain: ?DataRange) void { - self.domain = if (domain) |d| d.normalized() else null; - } - - pub fn setBaseline(self: *BarChart, baseline: f64) void { - self.baseline = baseline; - } - - pub fn setFormatter(self: *BarChart, formatter: ?ValueFormatter) void { - self.formatter = formatter; - } - - pub fn view(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { - if (self.bars.items.len == 0) return try allocator.dupe(u8, ""); - - return switch (self.orientation) { - .vertical => self.renderVertical(allocator), - .horizontal => self.renderHorizontal(allocator), - }; - } - - fn resolvedDomain(self: *const BarChart) DataRange { - if (self.domain) |domain| return domain.normalized(); - - var min_value = self.baseline; - var max_value = self.baseline; - for (self.bars.items) |bar| { - min_value = @min(min_value, bar.value); - max_value = @max(max_value, bar.value); - } - - const range = DataRange{ .min = min_value, .max = max_value }; - return range.normalized(); - } - - fn renderVertical(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { - const domain = self.resolvedDomain(); - const label_rows: usize = if (self.show_labels) 1 else 0; - const plot_height = @max(@as(usize, 1), @as(usize, self.height) -| label_rows); - const total_slot_width = @as(usize, self.bar_width) + @as(usize, self.gap); - const plot_width = @max(@as(usize, self.width), self.bars.items.len * total_slot_width); - - var buffer = try charting.CellBuffer.init(allocator, plot_width, plot_height); - defer buffer.deinit(); - var owned_values = std.array_list.Managed([]const u8).init(allocator); - defer { - for (owned_values.items) |value| allocator.free(value); - owned_values.deinit(); - } - for (0..plot_height) |y| for (0..plot_width) |x| buffer.setSlice(x, y, " ", null); - - const baseline_row = charting.mapY(self.baseline, domain, plot_height); - for (0..plot_width) |x| buffer.setSlice(x, baseline_row, "─", self.axis_style); - - for (self.bars.items, 0..) |bar, index| { - const start_x = index * total_slot_width; - const end_x = @min(plot_width, start_x + @as(usize, self.bar_width)); - const target_row = charting.mapY(bar.value, domain, plot_height); - const top = @min(target_row, baseline_row); - const bottom = @max(target_row, baseline_row); - const bar_style = bar.style orelse if (bar.value >= self.baseline) self.positive_style else self.negative_style; - - for (top..bottom + 1) |y| { - for (start_x..end_x) |x| { - buffer.setSlice(x, y, bar.glyph, bar_style); - } - } - - if (self.show_values) { - const label = try self.formatValue(allocator, bar.value); - try owned_values.append(label); - const row = if (bar.value >= self.baseline) top -| 1 else @min(plot_height - 1, bottom + 1); - const start = start_x + ((end_x - start_x) -| measure.width(label)) / 2; - buffer.writeText(start, row, label, self.value_style); - } - } - - const plot = try buffer.render(allocator); - defer allocator.free(plot); - if (!self.show_labels) return try allocator.dupe(u8, plot); - - var label_row = try charting.CellBuffer.init(allocator, plot_width, 1); - defer label_row.deinit(); - var owned_labels = std.array_list.Managed([]const u8).init(allocator); - defer { - for (owned_labels.items) |label| allocator.free(label); - owned_labels.deinit(); - } - for (0..plot_width) |x| label_row.setSlice(x, 0, " ", null); - - for (self.bars.items, 0..) |bar, index| { - const start_x = index * total_slot_width; - const label_width = measure.width(bar.label); - const label_start = start_x + (@as(usize, self.bar_width) -| @min(label_width, @as(usize, self.bar_width))) / 2; - const clipped = try truncateLabel(allocator, bar.label, @as(usize, self.bar_width)); - try owned_labels.append(clipped); - label_row.writeText(label_start, 0, clipped, self.label_style); - } - - const labels = try label_row.render(allocator); - defer allocator.free(labels); - return try join.vertical(allocator, .left, &.{ plot, labels }); - } - - fn renderHorizontal(self: *const BarChart, allocator: std.mem.Allocator) ![]const u8 { - const domain = self.resolvedDomain(); - const label_width = if (self.show_labels) self.maxLabelWidth() else 0; - const label_offset: usize = label_width + (if (label_width > 0) @as(usize, 1) else 0); - const plot_width = @max(@as(usize, 1), @as(usize, self.width) -| label_offset); - const total_slot_height = @as(usize, self.bar_width) + @as(usize, self.gap); - const plot_height = @max(@as(usize, self.height), self.bars.items.len * total_slot_height); - - var buffer = try charting.CellBuffer.init(allocator, label_offset + plot_width, plot_height); - defer buffer.deinit(); - var owned_values = std.array_list.Managed([]const u8).init(allocator); - defer { - for (owned_values.items) |value| allocator.free(value); - owned_values.deinit(); - } - for (0..buffer.height) |y| for (0..buffer.width) |x| buffer.setSlice(x, y, " ", null); - - const offset = label_offset; - const baseline_col = offset + charting.mapX(self.baseline, domain, plot_width); - for (0..plot_height) |y| buffer.setSlice(baseline_col, y, "│", self.axis_style); - - for (self.bars.items, 0..) |bar, index| { - const start_y = index * total_slot_height; - const end_y = @min(plot_height, start_y + @as(usize, self.bar_width)); - const target_col = offset + charting.mapX(bar.value, domain, plot_width); - const left = @min(target_col, baseline_col); - const right = @max(target_col, baseline_col); - const bar_style = bar.style orelse if (bar.value >= self.baseline) self.positive_style else self.negative_style; - - for (start_y..end_y) |y| { - if (self.show_labels and y == start_y) { - buffer.writeText(0, y, bar.label, self.label_style); - } - - for (left..right + 1) |x| { - buffer.setSlice(x, y, bar.glyph, bar_style); - } - - if (self.show_values and y == start_y) { - const value_text = try self.formatValue(allocator, bar.value); - try owned_values.append(value_text); - const text_x = if (bar.value >= self.baseline) - @min(buffer.width - measure.width(value_text), right + 1) - else - @max(offset, left -| (measure.width(value_text) + 1)); - buffer.writeText(text_x, y, value_text, self.value_style); - } - } - } - - return try buffer.render(allocator); - } - - fn maxLabelWidth(self: *const BarChart) usize { - var max_width: usize = 0; - for (self.bars.items) |bar| { - max_width = @max(max_width, measure.width(bar.label)); - } - return max_width; - } - - fn formatValue(self: *const BarChart, allocator: std.mem.Allocator, value: f64) ![]const u8 { - const formatter = self.formatter orelse charting.defaultFormatter; - return try formatter(allocator, value); - } -}; - -fn truncateLabel(allocator: std.mem.Allocator, label: []const u8, width: usize) ![]const u8 { - if (width == 0) return try allocator.dupe(u8, ""); - if (measure.width(label) <= width) return try allocator.dupe(u8, label); - return try measure.truncate(allocator, label, width); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig deleted file mode 100644 index 1cfdc3d..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/braille_canvas.zig +++ /dev/null @@ -1,412 +0,0 @@ -//! Braille canvas with direct pixel-grid API. -//! -//! Each terminal cell holds 2x4 sub-cell "pixels" via Unicode braille -//! characters (U+2800..U+28FF). Pixel coordinates use (px, py) with origin at -//! top-left; cell coordinates use (col, row). -//! -//! For chart-style data plotting, see `Canvas`. This component is intended -//! for raw pixel work — world maps, scopes, simple bitmaps — where the -//! caller already knows pixel coordinates. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Style = style_mod.Style; - -const BRAILLE_BASE: u21 = 0x2800; - -/// Bit position within a braille cell for each (sub_x, sub_y) coordinate. -/// Layout matches Unicode braille: -/// 0 3 -/// 1 4 -/// 2 5 -/// 6 7 -const BRAILLE_BITS = [4][2]u8{ - .{ 0x01, 0x08 }, - .{ 0x02, 0x10 }, - .{ 0x04, 0x20 }, - .{ 0x40, 0x80 }, -}; - -const BrailleCell = struct { - bits: u8 = 0, - style: ?Style = null, -}; - -const TextOverlay = struct { - col: u16, - row: u16, - text: []const u8, - style: Style, -}; - -pub const BrailleCanvas = struct { - allocator: std.mem.Allocator, - /// Cell width (each cell = 2 pixels wide). - cell_width: u16, - /// Cell height (each cell = 4 pixels tall). - cell_height: u16, - - cells: []BrailleCell, - overlays: std.array_list.Managed(TextOverlay), - text_arena: std.heap.ArenaAllocator, - - default_style: Style, - background_glyph: []const u8, - - pub fn init(allocator: std.mem.Allocator, cell_width: u16, cell_height: u16) !BrailleCanvas { - const w = @max(@as(u16, 1), cell_width); - const h = @max(@as(u16, 1), cell_height); - const cells = try allocator.alloc(BrailleCell, @as(usize, w) * @as(usize, h)); - for (cells) |*c| c.* = .{}; - - var inline_style = Style{}; - inline_style = inline_style.inline_style(true); - - return .{ - .allocator = allocator, - .cell_width = w, - .cell_height = h, - .cells = cells, - .overlays = std.array_list.Managed(TextOverlay).init(allocator), - .text_arena = std.heap.ArenaAllocator.init(allocator), - .default_style = inline_style, - .background_glyph = " ", - }; - } - - pub fn deinit(self: *BrailleCanvas) void { - self.allocator.free(self.cells); - self.overlays.deinit(); - self.text_arena.deinit(); - } - - pub fn setSize(self: *BrailleCanvas, cell_width: u16, cell_height: u16) !void { - const w = @max(@as(u16, 1), cell_width); - const h = @max(@as(u16, 1), cell_height); - if (w == self.cell_width and h == self.cell_height) { - self.clear(); - return; - } - self.allocator.free(self.cells); - self.cells = try self.allocator.alloc(BrailleCell, @as(usize, w) * @as(usize, h)); - for (self.cells) |*c| c.* = .{}; - self.cell_width = w; - self.cell_height = h; - self.overlays.clearRetainingCapacity(); - _ = self.text_arena.reset(.retain_capacity); - } - - pub fn setStyle(self: *BrailleCanvas, style: Style) void { - var s = style; - s = s.inline_style(true); - self.default_style = s; - } - - pub fn setBackground(self: *BrailleCanvas, glyph: []const u8) void { - self.background_glyph = glyph; - } - - /// Pixel grid dimensions. - pub fn pixelWidth(self: *const BrailleCanvas) u16 { - return self.cell_width *| 2; - } - pub fn pixelHeight(self: *const BrailleCanvas) u16 { - return self.cell_height *| 4; - } - - pub fn clear(self: *BrailleCanvas) void { - for (self.cells) |*c| c.* = .{}; - self.overlays.clearRetainingCapacity(); - _ = self.text_arena.reset(.retain_capacity); - } - - pub fn setPixel(self: *BrailleCanvas, px: i32, py: i32) void { - self.setPixelStyled(px, py, self.default_style); - } - - pub fn setPixelStyled(self: *BrailleCanvas, px: i32, py: i32, style: Style) void { - if (px < 0 or py < 0) return; - const upx: u32 = @intCast(px); - const upy: u32 = @intCast(py); - if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return; - - const col: usize = upx / 2; - const row: usize = upy / 4; - const sx: usize = upx % 2; - const sy: usize = upy % 4; - - const idx = row * self.cell_width + col; - var cell = &self.cells[idx]; - cell.bits |= BRAILLE_BITS[sy][sx]; - var s = style; - s = s.inline_style(true); - cell.style = s; - } - - pub fn clearPixel(self: *BrailleCanvas, px: i32, py: i32) void { - if (px < 0 or py < 0) return; - const upx: u32 = @intCast(px); - const upy: u32 = @intCast(py); - if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return; - - const col: usize = upx / 2; - const row: usize = upy / 4; - const sx: usize = upx % 2; - const sy: usize = upy % 4; - - const idx = row * self.cell_width + col; - var cell = &self.cells[idx]; - cell.bits &= ~BRAILLE_BITS[sy][sx]; - if (cell.bits == 0) cell.style = null; - } - - pub fn togglePixel(self: *BrailleCanvas, px: i32, py: i32) void { - if (self.isPixelSet(px, py)) { - self.clearPixel(px, py); - } else { - self.setPixel(px, py); - } - } - - pub fn isPixelSet(self: *const BrailleCanvas, px: i32, py: i32) bool { - if (px < 0 or py < 0) return false; - const upx: u32 = @intCast(px); - const upy: u32 = @intCast(py); - if (upx >= self.pixelWidth() or upy >= self.pixelHeight()) return false; - const col: usize = upx / 2; - const row: usize = upy / 4; - const sx: usize = upx % 2; - const sy: usize = upy % 4; - const idx = row * self.cell_width + col; - return (self.cells[idx].bits & BRAILLE_BITS[sy][sx]) != 0; - } - - pub fn drawLine(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32) void { - self.drawLineStyled(x0, y0, x1, y1, self.default_style); - } - - pub fn drawLineStyled(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, style: Style) void { - // Bresenham. - var x = x0; - var y = y0; - const dx = @as(i32, @intCast(@abs(x1 - x0))); - const dy = -@as(i32, @intCast(@abs(y1 - y0))); - const sx: i32 = if (x0 < x1) 1 else -1; - const sy: i32 = if (y0 < y1) 1 else -1; - var err = dx + dy; - while (true) { - self.setPixelStyled(x, y, style); - if (x == x1 and y == y1) break; - const e2 = err * 2; - if (e2 >= dy) { - if (x == x1) break; - err += dy; - x += sx; - } - if (e2 <= dx) { - if (y == y1) break; - err += dx; - y += sy; - } - } - } - - pub fn drawRect(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, filled: bool) void { - self.drawRectStyled(x0, y0, x1, y1, filled, self.default_style); - } - - pub fn drawRectStyled(self: *BrailleCanvas, x0: i32, y0: i32, x1: i32, y1: i32, filled: bool, style: Style) void { - const lx = @min(x0, x1); - const hx = @max(x0, x1); - const ly = @min(y0, y1); - const hy = @max(y0, y1); - if (filled) { - var y = ly; - while (y <= hy) : (y += 1) { - var x = lx; - while (x <= hx) : (x += 1) { - self.setPixelStyled(x, y, style); - } - } - } else { - self.drawLineStyled(lx, ly, hx, ly, style); - self.drawLineStyled(lx, hy, hx, hy, style); - self.drawLineStyled(lx, ly, lx, hy, style); - self.drawLineStyled(hx, ly, hx, hy, style); - } - } - - pub fn drawCircle(self: *BrailleCanvas, cx: i32, cy: i32, radius: i32) void { - self.drawCircleStyled(cx, cy, radius, self.default_style); - } - - pub fn drawCircleStyled(self: *BrailleCanvas, cx: i32, cy: i32, radius: i32, style: Style) void { - if (radius <= 0) { - self.setPixelStyled(cx, cy, style); - return; - } - // Midpoint circle algorithm. - var x: i32 = radius; - var y: i32 = 0; - var err: i32 = 1 - radius; - while (x >= y) { - self.setPixelStyled(cx + x, cy + y, style); - self.setPixelStyled(cx + y, cy + x, style); - self.setPixelStyled(cx - y, cy + x, style); - self.setPixelStyled(cx - x, cy + y, style); - self.setPixelStyled(cx - x, cy - y, style); - self.setPixelStyled(cx - y, cy - x, style); - self.setPixelStyled(cx + y, cy - x, style); - self.setPixelStyled(cx + x, cy - y, style); - y += 1; - if (err < 0) { - err += 2 * y + 1; - } else { - x -= 1; - err += 2 * (y - x) + 1; - } - } - } - - /// Overlay text at cell coordinates, replacing the braille at those cells. - pub fn drawText(self: *BrailleCanvas, col: u16, row: u16, text: []const u8, style: Style) !void { - const owned = try self.text_arena.allocator().dupe(u8, text); - var s = style; - s = s.inline_style(true); - try self.overlays.append(.{ .col = col, .row = row, .text = owned, .style = s }); - } - - pub fn view(self: *const BrailleCanvas, allocator: std.mem.Allocator) ![]const u8 { - // Materialize each cell into a string (braille char or background), - // styled. Then apply text overlays. - const total_cells = @as(usize, self.cell_width) * @as(usize, self.cell_height); - var glyph_for_cell = try allocator.alloc(?[]const u8, total_cells); - defer allocator.free(glyph_for_cell); - for (glyph_for_cell) |*g| g.* = null; - - // Apply text overlays first so they take precedence. - for (self.overlays.items) |ov| { - if (ov.row >= self.cell_height) continue; - var col: u16 = ov.col; - var view_iter = std.unicode.Utf8View.init(ov.text) catch continue; - var iter = view_iter.iterator(); - while (iter.nextCodepointSlice()) |cp_slice| { - if (col >= self.cell_width) break; - const idx = @as(usize, ov.row) * self.cell_width + col; - glyph_for_cell[idx] = try ov.style.render(allocator, cp_slice); - col += 1; - } - } - - var result: Writer.Allocating = .init(allocator); - const w = &result.writer; - - var row: usize = 0; - while (row < self.cell_height) : (row += 1) { - if (row > 0) try w.writeByte('\n'); - var col: usize = 0; - while (col < self.cell_width) : (col += 1) { - const idx = row * self.cell_width + col; - if (glyph_for_cell[idx]) |overlay| { - try w.writeAll(overlay); - allocator.free(overlay); - continue; - } - - const cell = self.cells[idx]; - if (cell.bits == 0) { - try w.writeAll(self.background_glyph); - continue; - } - var buf: [4]u8 = undefined; - const cp: u21 = BRAILLE_BASE + @as(u21, cell.bits); - const len = std.unicode.utf8Encode(cp, &buf) catch { - try w.writeAll(self.background_glyph); - continue; - }; - const styled = try (cell.style orelse self.default_style).render(allocator, buf[0..len]); - defer allocator.free(styled); - try w.writeAll(styled); - } - } - - return result.toOwnedSlice(); - } -}; - -test "set and check pixel" { - var c = try BrailleCanvas.init(std.testing.allocator, 4, 4); - defer c.deinit(); - c.setPixel(0, 0); - try std.testing.expect(c.isPixelSet(0, 0)); - try std.testing.expect(!c.isPixelSet(1, 0)); - c.clearPixel(0, 0); - try std.testing.expect(!c.isPixelSet(0, 0)); -} - -test "out-of-bounds writes are ignored" { - var c = try BrailleCanvas.init(std.testing.allocator, 2, 2); - defer c.deinit(); - c.setPixel(-1, -1); - c.setPixel(100, 100); - // Nothing crashes; nothing set. - try std.testing.expect(!c.isPixelSet(0, 0)); -} - -test "drawLine sets endpoints" { - var c = try BrailleCanvas.init(std.testing.allocator, 8, 4); - defer c.deinit(); - c.drawLine(0, 0, 10, 10); - try std.testing.expect(c.isPixelSet(0, 0)); - try std.testing.expect(c.isPixelSet(10, 10)); -} - -test "drawCircle hits cardinal points" { - var c = try BrailleCanvas.init(std.testing.allocator, 16, 16); - defer c.deinit(); - c.drawCircle(10, 10, 5); - try std.testing.expect(c.isPixelSet(15, 10)); - try std.testing.expect(c.isPixelSet(5, 10)); - try std.testing.expect(c.isPixelSet(10, 15)); - try std.testing.expect(c.isPixelSet(10, 5)); -} - -test "view emits cell_height lines" { - const allocator = std.testing.allocator; - var c = try BrailleCanvas.init(allocator, 4, 3); - defer c.deinit(); - c.setPixel(0, 0); - c.setPixel(1, 1); - const out = try c.view(allocator); - defer allocator.free(out); - var newlines: usize = 0; - for (out) |b| if (b == '\n') { - newlines += 1; - }; - try std.testing.expectEqual(@as(usize, 2), newlines); -} - -test "drawText overlay replaces braille" { - const allocator = std.testing.allocator; - var c = try BrailleCanvas.init(allocator, 10, 2); - defer c.deinit(); - c.drawLine(0, 0, 19, 7); - try c.drawText(0, 0, "hi", Style{}); - const out = try c.view(allocator); - defer allocator.free(out); - // Both characters should appear somewhere; styling may sit between them. - try std.testing.expect(std.mem.indexOfScalar(u8, out, 'h') != null); - try std.testing.expect(std.mem.indexOfScalar(u8, out, 'i') != null); -} - -test "setSize resets cells" { - var c = try BrailleCanvas.init(std.testing.allocator, 2, 2); - defer c.deinit(); - c.setPixel(0, 0); - try c.setSize(4, 4); - try std.testing.expect(!c.isPixelSet(0, 0)); - try std.testing.expectEqual(@as(u16, 8), c.pixelWidth()); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig deleted file mode 100644 index d4464c2..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/breadcrumb.zig +++ /dev/null @@ -1,223 +0,0 @@ -//! 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 Writer = std.Io.Writer; -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(.gray(12)); - seg = seg.inline_style(true); - - var active = style_mod.Style{}; - active = active.fg(.cyan); - active = active.bold(true); - active = active.inline_style(true); - - var sep = style_mod.Style{}; - sep = sep.fg(.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: Writer.Allocating = .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: Writer.Allocating = .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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig deleted file mode 100644 index bcd8839..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/calendar.zig +++ /dev/null @@ -1,304 +0,0 @@ -//! Calendar/DatePicker component. -//! Displays a month view grid with date selection and navigation. -//! Fully customizable: styles, labels, symbols, layout. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const keys = @import("../input/keys.zig"); - -pub const Calendar = struct { - year: u16 = 2026, - month: u8 = 1, - selected_day: u8 = 1, - cursor_day: u8 = 1, - /// Day to highlight as today (0 = none). - today_day: u8 = 0, - today_month: u8 = 0, - today_year: u16 = 0, - /// Week starts on Monday (true) or Sunday (false). - week_start_monday: bool = true, - /// Marked dates with colors. - marked_days: [31]?Color = .{null} ** 31, - /// Focused state. - focused: bool = true, - - // Customizable labels - /// Month names (12 entries). - month_names: [12][]const u8 = .{ - "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December", - }, - /// Day-of-week headers when week starts Monday (7 entries). - day_headers_mon: [7][]const u8 = .{ "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" }, - /// Day-of-week headers when week starts Sunday (7 entries). - day_headers_sun: [7][]const u8 = .{ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }, - - // Navigation symbols - /// Previous month indicator in title. - prev_symbol: []const u8 = "<", - /// Next month indicator in title. - next_symbol: []const u8 = ">", - /// Title format: 0=prev_symbol, 1=month_name, 2=year, 3=next_symbol. - /// Set to "" to hide title. - title_prefix: []const u8 = " ", - title_suffix: []const u8 = " ", - - // Cell layout - /// Width of each day cell in characters (minimum 2). - cell_width: u8 = 4, - - // Styles - title_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - today_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - selected_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.blue); - s = s.inline_style(true); - break :blk s; - }, - cursor_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.bg(.blue); - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - weekend_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - header_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - normal_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - /// Style for the prev/next symbols in the title. - nav_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - /// Style for marked dates (applied when no custom color is set). - marked_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - - pub fn addMarkedDate(self: *Calendar, day: u8, c: Color) void { - if (day >= 1 and day <= 31) { - self.marked_days[day - 1] = c; - } - } - - pub fn clearMarkedDates(self: *Calendar) void { - self.marked_days = .{null} ** 31; - } - - pub fn update(self: *Calendar, key: keys.KeyEvent) void { - const dim = daysInMonth(self.year, self.month); - switch (key.key) { - .left => { - if (key.modifiers.shift) { - self.prevMonth(); - } else if (self.cursor_day > 1) { - self.cursor_day -= 1; - } - }, - .right => { - if (key.modifiers.shift) { - self.nextMonth(); - } else if (self.cursor_day < dim) { - self.cursor_day += 1; - } - }, - .up => { - if (self.cursor_day > 7) { - self.cursor_day -= 7; - } - }, - .down => { - if (self.cursor_day + 7 <= dim) { - self.cursor_day += 7; - } - }, - .char => |c| switch (c) { - 'h' => self.prevMonth(), - 'l' => self.nextMonth(), - else => {}, - }, - .enter => { - self.selected_day = self.cursor_day; - }, - .page_up => self.prevMonth(), - .page_down => self.nextMonth(), - else => {}, - } - } - - fn prevMonth(self: *Calendar) void { - if (self.month == 1) { - self.month = 12; - if (self.year > 1) self.year -= 1; - } else { - self.month -= 1; - } - const dim = daysInMonth(self.year, self.month); - if (self.cursor_day > dim) self.cursor_day = dim; - if (self.selected_day > dim) self.selected_day = dim; - } - - fn nextMonth(self: *Calendar) void { - if (self.month == 12) { - self.month = 1; - self.year += 1; - } else { - self.month += 1; - } - const dim = daysInMonth(self.year, self.month); - if (self.cursor_day > dim) self.cursor_day = dim; - if (self.selected_day > dim) self.selected_day = dim; - } - - pub fn view(self: *const Calendar, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const cw: usize = @max(2, self.cell_width); - - // Title: < month year > - const mname = if (self.month >= 1 and self.month <= 12) self.month_names[self.month - 1] else "?"; - const nav_prev = self.nav_style.render(allocator, self.prev_symbol) catch self.prev_symbol; - const nav_next = self.nav_style.render(allocator, self.next_symbol) catch self.next_symbol; - const title_text = std.fmt.allocPrint(allocator, "{s}{s}{s} {d}{s}{s}", .{ - self.title_prefix, nav_prev, mname, self.year, nav_next, self.title_suffix, - }) catch "?"; - writer.writeAll(self.title_style.render(allocator, title_text) catch title_text) catch {}; - writer.writeByte('\n') catch {}; - - // Day-of-week headers — aligned to cell_width columns - const headers = if (self.week_start_monday) &self.day_headers_mon else &self.day_headers_sun; - for (headers) |hdr| { - const padded = padCenter(allocator, hdr, cw); - writer.writeAll(self.header_style.render(allocator, padded) catch padded) catch {}; - } - writer.writeByte('\n') catch {}; - - // Calendar grid - const dim = daysInMonth(self.year, self.month); - var first_dow = dayOfWeek(self.year, self.month, 1); // 0=Monday - if (!self.week_start_monday) { - first_dow = (first_dow + 1) % 7; - } - - // Leading blanks — same cell width - for (0..first_dow) |_| { - for (0..cw) |_| writer.writeByte(' ') catch {}; - } - - var col = first_dow; - for (1..@as(usize, dim) + 1) |d| { - const day: u8 = @intCast(d); - const day_str = std.fmt.allocPrint(allocator, "{d}", .{day}) catch "??"; - - const is_today = (day == self.today_day and self.month == self.today_month and self.year == self.today_year); - const is_selected = (day == self.selected_day); - const is_cursor = (day == self.cursor_day and self.focused); - const is_weekend = if (self.week_start_monday) (col >= 5) else (col == 0 or col == 6); - - // Check marked - const marked_color: ?Color = if (day >= 1 and day <= 31) self.marked_days[day - 1] else null; - - var s: style_mod.Style = undefined; - if (is_cursor) { - s = self.cursor_style; - } else if (is_selected) { - s = self.selected_style; - } else if (is_today) { - s = self.today_style; - } else if (marked_color) |mc| { - var ms = self.marked_style; - ms = ms.fg(mc); - s = ms; - } else if (is_weekend) { - s = self.weekend_style; - } else { - s = self.normal_style; - } - - // Center the day number within cell_width - const padded = padCenter(allocator, day_str, cw); - writer.writeAll(s.render(allocator, padded) catch padded) catch {}; - - col += 1; - if (col >= 7) { - col = 0; - if (d < dim) writer.writeByte('\n') catch {}; - } - } - - return result.toArrayList().items; - } - - fn padCenter(allocator: std.mem.Allocator, text: []const u8, target: usize) []const u8 { - if (text.len >= target) return text[0..target]; - var buf = std.array_list.Managed(u8).init(allocator); - const pad = target - text.len; - const left = pad / 2; - const right = pad - left; - for (0..left) |_| buf.append(' ') catch {}; - buf.appendSlice(text) catch {}; - for (0..right) |_| buf.append(' ') catch {}; - return buf.items; - } - - // Calendar math - fn isLeapYear(y: u16) bool { - if (y % 400 == 0) return true; - if (y % 100 == 0) return false; - return y % 4 == 0; - } - - fn daysInMonth(y: u16, m: u8) u8 { - const days = [_]u8{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - if (m < 1 or m > 12) return 30; - if (m == 2 and isLeapYear(y)) return 29; - return days[m - 1]; - } - - /// Returns day of week: 0=Monday, 6=Sunday (Tomohiko Sakamoto's algorithm). - fn dayOfWeek(y_in: u16, m: u8, d: u8) u8 { - const t = [_]i8{ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; - var y: i32 = @intCast(y_in); - if (m < 3) y -= 1; - const mi: usize = @intCast(m - 1); - const r = @mod(y + @divTrunc(y, 4) - @divTrunc(y, 100) + @divTrunc(y, 400) + t[mi] + @as(i32, d), 7); - // r: 0=Sunday. Convert to 0=Monday. - return @intCast(@mod(r + 6, 7)); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig deleted file mode 100644 index 60cfa37..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/canvas.zig +++ /dev/null @@ -1,484 +0,0 @@ -//! Plotting canvas with braille and cell-based markers. - -const std = @import("std"); -const charting = @import("charting.zig"); -const style_mod = @import("../style/style.zig"); - -pub const Marker = charting.Marker; -pub const Point = charting.Point; -pub const DataRange = charting.DataRange; -pub const Style = style_mod.Style; - -pub const Canvas = struct { - allocator: std.mem.Allocator, - width: u16, - height: u16, - x_range: DataRange, - y_range: DataRange, - marker: Marker, - background_glyph: []const u8, - point_glyph: []const u8, - line_glyph: []const u8, - default_style: Style, - operations: std.array_list.Managed(Operation), - - const Operation = union(enum) { - point: PointOp, - line: LineOp, - rect: RectOp, - text: TextOp, - }; - - const PointOp = struct { - point: Point, - style: Style, - glyph: ?[]const u8 = null, - }; - - const LineOp = struct { - from: Point, - to: Point, - style: Style, - glyph: ?[]const u8 = null, - }; - - const RectOp = struct { - min: Point, - max: Point, - filled: bool, - style: Style, - glyph: ?[]const u8 = null, - }; - - const TextOp = struct { - origin: Point, - text: []const u8, - style: Style, - }; - - const BrailleCell = struct { - bits: u8 = 0, - style: ?Style = null, - }; - - pub fn init(allocator: std.mem.Allocator) Canvas { - return .{ - .allocator = allocator, - .width = 40, - .height = 12, - .x_range = .{ .min = 0, .max = 1 }, - .y_range = .{ .min = 0, .max = 1 }, - .marker = .braille, - .background_glyph = " ", - .point_glyph = "•", - .line_glyph = "█", - .default_style = charting.inlineStyle(Style{}), - .operations = std.array_list.Managed(Operation).init(allocator), - }; - } - - pub fn deinit(self: *Canvas) void { - self.operations.deinit(); - } - - pub fn clear(self: *Canvas) void { - self.operations.clearRetainingCapacity(); - } - - pub fn setSize(self: *Canvas, width: u16, height: u16) void { - self.width = @max(1, width); - self.height = @max(1, height); - } - - pub fn setRanges(self: *Canvas, x_range: DataRange, y_range: DataRange) void { - self.x_range = x_range.normalized(); - self.y_range = y_range.normalized(); - } - - pub fn setMarker(self: *Canvas, marker: Marker) void { - self.marker = marker; - } - - pub fn setStyle(self: *Canvas, style: Style) void { - self.default_style = charting.inlineStyle(style); - } - - pub fn setGlyphs(self: *Canvas, point_glyph: []const u8, line_glyph: []const u8) void { - self.point_glyph = point_glyph; - self.line_glyph = line_glyph; - } - - pub fn setBackground(self: *Canvas, glyph: []const u8) void { - self.background_glyph = glyph; - } - - pub fn drawPoint(self: *Canvas, x: f64, y: f64) !void { - try self.drawPointStyled(x, y, self.default_style, null); - } - - pub fn drawPointStyled(self: *Canvas, x: f64, y: f64, style: Style, glyph: ?[]const u8) !void { - try self.operations.append(.{ - .point = .{ - .point = .{ .x = x, .y = y }, - .style = charting.inlineStyle(style), - .glyph = glyph, - }, - }); - } - - pub fn drawLine(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64) !void { - try self.drawLineStyled(x0, y0, x1, y1, self.default_style, null); - } - - pub fn drawLineStyled(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64, style: Style, glyph: ?[]const u8) !void { - try self.operations.append(.{ - .line = .{ - .from = .{ .x = x0, .y = y0 }, - .to = .{ .x = x1, .y = y1 }, - .style = charting.inlineStyle(style), - .glyph = glyph, - }, - }); - } - - pub fn drawRect(self: *Canvas, x0: f64, y0: f64, x1: f64, y1: f64, filled: bool, style: Style, glyph: ?[]const u8) !void { - try self.operations.append(.{ - .rect = .{ - .min = .{ .x = @min(x0, x1), .y = @min(y0, y1) }, - .max = .{ .x = @max(x0, x1), .y = @max(y0, y1) }, - .filled = filled, - .style = charting.inlineStyle(style), - .glyph = glyph, - }, - }); - } - - pub fn drawText(self: *Canvas, x: f64, y: f64, text: []const u8, style: Style) !void { - try self.operations.append(.{ - .text = .{ - .origin = .{ .x = x, .y = y }, - .text = text, - .style = charting.inlineStyle(style), - }, - }); - } - - pub fn view(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { - return switch (self.marker) { - .braille => self.renderBraille(allocator), - .block, .dot, .ascii => self.renderCells(allocator), - }; - } - - pub fn drawIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { - switch (self.marker) { - .braille => self.drawBrailleIntoBuffer(buffer), - .block, .dot, .ascii => self.drawCellIntoBuffer(buffer), - } - } - - fn renderCells(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { - var buffer = try charting.CellBuffer.init(allocator, self.width, self.height); - defer buffer.deinit(); - - for (0..self.height) |y| { - for (0..self.width) |x| { - buffer.setSlice(x, y, self.background_glyph, null); - } - } - - self.drawCellIntoBuffer(&buffer); - - return try buffer.render(allocator); - } - - fn renderBraille(self: *const Canvas, allocator: std.mem.Allocator) ![]const u8 { - const cell_count = @as(usize, self.width) * @as(usize, self.height); - const braille_cells = try allocator.alloc(BrailleCell, cell_count); - defer allocator.free(braille_cells); - for (braille_cells) |*cell| cell.* = .{}; - - var overlay = try charting.CellBuffer.init(allocator, self.width, self.height); - defer overlay.deinit(); - - for (self.operations.items) |op| { - switch (op) { - .point => |point_op| { - const x = charting.mapX(point_op.point.x, self.x_range, @as(usize, self.width) * 2); - const y = charting.mapY(point_op.point.y, self.y_range, @as(usize, self.height) * 4); - setBraillePixel(braille_cells, self.width, x, y, point_op.style); - }, - .line => |line_op| { - const x0 = charting.mapX(line_op.from.x, self.x_range, @as(usize, self.width) * 2); - const y0 = charting.mapY(line_op.from.y, self.y_range, @as(usize, self.height) * 4); - const x1 = charting.mapX(line_op.to.x, self.x_range, @as(usize, self.width) * 2); - const y1 = charting.mapY(line_op.to.y, self.y_range, @as(usize, self.height) * 4); - drawBrailleLine(braille_cells, self.width, x0, y0, x1, y1, line_op.style); - }, - .rect => |rect_op| { - const min_x = charting.mapX(rect_op.min.x, self.x_range, @as(usize, self.width) * 2); - const min_y = charting.mapY(rect_op.max.y, self.y_range, @as(usize, self.height) * 4); - const max_x = charting.mapX(rect_op.max.x, self.x_range, @as(usize, self.width) * 2); - const max_y = charting.mapY(rect_op.min.y, self.y_range, @as(usize, self.height) * 4); - drawBrailleRect(braille_cells, self.width, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.style); - }, - .text => |text_op| { - const x = charting.mapX(text_op.origin.x, self.x_range, self.width); - const y = charting.mapY(text_op.origin.y, self.y_range, self.height); - overlay.writeText(x, y, text_op.text, text_op.style); - }, - } - } - - var final = try charting.CellBuffer.init(allocator, self.width, self.height); - defer final.deinit(); - - for (0..self.height) |y| { - for (0..self.width) |x| { - const cell = braille_cells[y * self.width + x]; - if (cell.bits == 0) { - final.setSlice(x, y, self.background_glyph, null); - } else { - final.setCodepoint(x, y, @as(u21, 0x2800) + cell.bits, cell.style); - } - } - } - - for (0..self.height) |y| { - for (0..self.width) |x| { - const cell = overlay.cells[y * self.width + x]; - if (glyphIsBlank(cell.glyph)) continue; - final.cells[y * self.width + x] = cell; - } - } - - return try final.render(allocator); - } - - fn drawCellIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { - for (self.operations.items) |op| { - switch (op) { - .point => |point_op| { - const x = charting.mapX(point_op.point.x, self.x_range, self.width); - const y = charting.mapY(point_op.point.y, self.y_range, self.height); - buffer.setSlice(x, y, point_op.glyph orelse self.defaultCellGlyph(), point_op.style); - }, - .line => |line_op| { - const x0 = charting.mapX(line_op.from.x, self.x_range, self.width); - const y0 = charting.mapY(line_op.from.y, self.y_range, self.height); - const x1 = charting.mapX(line_op.to.x, self.x_range, self.width); - const y1 = charting.mapY(line_op.to.y, self.y_range, self.height); - drawLineCells(buffer, x0, y0, x1, y1, line_op.glyph orelse self.lineCellGlyph(), line_op.style); - }, - .rect => |rect_op| { - const min_x = charting.mapX(rect_op.min.x, self.x_range, self.width); - const min_y = charting.mapY(rect_op.max.y, self.y_range, self.height); - const max_x = charting.mapX(rect_op.max.x, self.x_range, self.width); - const max_y = charting.mapY(rect_op.min.y, self.y_range, self.height); - drawRectCells(buffer, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.glyph orelse self.lineCellGlyph(), rect_op.style); - }, - .text => |text_op| { - const x = charting.mapX(text_op.origin.x, self.x_range, self.width); - const y = charting.mapY(text_op.origin.y, self.y_range, self.height); - buffer.writeText(x, y, text_op.text, text_op.style); - }, - } - } - } - - fn drawBrailleIntoBuffer(self: *const Canvas, buffer: *charting.CellBuffer) void { - const cell_count = @as(usize, self.width) * @as(usize, self.height); - const braille_cells = buffer.allocator.alloc(BrailleCell, cell_count) catch return; - defer buffer.allocator.free(braille_cells); - for (braille_cells) |*cell| cell.* = .{}; - - for (self.operations.items) |op| { - switch (op) { - .point => |point_op| { - const x = charting.mapX(point_op.point.x, self.x_range, @as(usize, self.width) * 2); - const y = charting.mapY(point_op.point.y, self.y_range, @as(usize, self.height) * 4); - setBraillePixel(braille_cells, self.width, x, y, point_op.style); - }, - .line => |line_op| { - const x0 = charting.mapX(line_op.from.x, self.x_range, @as(usize, self.width) * 2); - const y0 = charting.mapY(line_op.from.y, self.y_range, @as(usize, self.height) * 4); - const x1 = charting.mapX(line_op.to.x, self.x_range, @as(usize, self.width) * 2); - const y1 = charting.mapY(line_op.to.y, self.y_range, @as(usize, self.height) * 4); - drawBrailleLine(braille_cells, self.width, x0, y0, x1, y1, line_op.style); - }, - .rect => |rect_op| { - const min_x = charting.mapX(rect_op.min.x, self.x_range, @as(usize, self.width) * 2); - const min_y = charting.mapY(rect_op.max.y, self.y_range, @as(usize, self.height) * 4); - const max_x = charting.mapX(rect_op.max.x, self.x_range, @as(usize, self.width) * 2); - const max_y = charting.mapY(rect_op.min.y, self.y_range, @as(usize, self.height) * 4); - drawBrailleRect(braille_cells, self.width, min_x, min_y, max_x, max_y, rect_op.filled, rect_op.style); - }, - .text => |text_op| { - const x = charting.mapX(text_op.origin.x, self.x_range, self.width); - const y = charting.mapY(text_op.origin.y, self.y_range, self.height); - buffer.writeText(x, y, text_op.text, text_op.style); - }, - } - } - - for (0..self.height) |y| { - for (0..self.width) |x| { - const cell = braille_cells[y * self.width + x]; - if (cell.bits == 0) continue; - buffer.setCodepoint(x, y, @as(u21, 0x2800) + cell.bits, cell.style); - } - } - } - - fn defaultCellGlyph(self: *const Canvas) []const u8 { - return switch (self.marker) { - .braille => "•", - .block => if (self.point_glyph.len > 0) self.point_glyph else "█", - .dot => if (self.point_glyph.len > 0) self.point_glyph else "•", - .ascii => if (self.point_glyph.len > 0) self.point_glyph else "*", - }; - } - - fn lineCellGlyph(self: *const Canvas) []const u8 { - return switch (self.marker) { - .braille => "•", - .block => if (self.line_glyph.len > 0) self.line_glyph else "█", - .dot => if (self.line_glyph.len > 0) self.line_glyph else "•", - .ascii => if (self.line_glyph.len > 0) self.line_glyph else "*", - }; - } -}; - -fn glyphIsBlank(glyph: charting.Glyph) bool { - return switch (glyph) { - .slice => |slice| slice.len == 0 or std.mem.eql(u8, slice, " "), - .codepoint => |cp| cp == ' ' or cp == 0x2800, - }; -} - -fn drawLineCells(buffer: *charting.CellBuffer, x0: usize, y0: usize, x1: usize, y1: usize, glyph: []const u8, style: ?Style) void { - const dx = @as(isize, @intCast(x1)) - @as(isize, @intCast(x0)); - const dy = @as(isize, @intCast(y1)) - @as(isize, @intCast(y0)); - const steps = @max(@abs(dx), @abs(dy)); - if (steps == 0) { - buffer.setSlice(x0, y0, glyph, style); - return; - } - - const step_x = @as(f64, @floatFromInt(dx)) / @as(f64, @floatFromInt(steps)); - const step_y = @as(f64, @floatFromInt(dy)) / @as(f64, @floatFromInt(steps)); - - var x = @as(f64, @floatFromInt(x0)); - var y = @as(f64, @floatFromInt(y0)); - var i: usize = 0; - while (i <= @as(usize, @intCast(steps))) : (i += 1) { - buffer.setSlice( - @as(usize, @intFromFloat(@round(x))), - @as(usize, @intFromFloat(@round(y))), - glyph, - style, - ); - x += step_x; - y += step_y; - } -} - -fn drawRectCells(buffer: *charting.CellBuffer, min_x: usize, min_y: usize, max_x: usize, max_y: usize, filled: bool, glyph: []const u8, style: ?Style) void { - const left = @min(min_x, max_x); - const right = @max(min_x, max_x); - const top = @min(min_y, max_y); - const bottom = @max(min_y, max_y); - - if (filled) { - for (top..bottom + 1) |y| { - for (left..right + 1) |x| { - buffer.setSlice(x, y, glyph, style); - } - } - return; - } - - drawLineCells(buffer, left, top, right, top, glyph, style); - drawLineCells(buffer, left, bottom, right, bottom, glyph, style); - drawLineCells(buffer, left, top, left, bottom, glyph, style); - drawLineCells(buffer, right, top, right, bottom, glyph, style); -} - -fn setBraillePixel(cells: []Canvas.BrailleCell, width: u16, x: usize, y: usize, style: ?Style) void { - const cell_x = x / 2; - const cell_y = y / 4; - if (cell_x >= width) return; - const height = if (width == 0) 0 else cells.len / width; - if (cell_y >= height) return; - - const local_x = x % 2; - const local_y = y % 4; - - const bit = switch (local_x) { - 0 => switch (local_y) { - 0 => @as(u8, 0x01), - 1 => @as(u8, 0x02), - 2 => @as(u8, 0x04), - else => @as(u8, 0x40), - }, - else => switch (local_y) { - 0 => @as(u8, 0x08), - 1 => @as(u8, 0x10), - 2 => @as(u8, 0x20), - else => @as(u8, 0x80), - }, - }; - - const index = cell_y * width + cell_x; - cells[index].bits |= bit; - cells[index].style = style; -} - -fn drawBrailleLine(cells: []Canvas.BrailleCell, width: u16, x0: usize, y0: usize, x1: usize, y1: usize, style: ?Style) void { - const dx = @as(isize, @intCast(x1)) - @as(isize, @intCast(x0)); - const dy = @as(isize, @intCast(y1)) - @as(isize, @intCast(y0)); - const steps = @max(@abs(dx), @abs(dy)); - if (steps == 0) { - setBraillePixel(cells, width, x0, y0, style); - return; - } - - const step_x = @as(f64, @floatFromInt(dx)) / @as(f64, @floatFromInt(steps)); - const step_y = @as(f64, @floatFromInt(dy)) / @as(f64, @floatFromInt(steps)); - - var x = @as(f64, @floatFromInt(x0)); - var y = @as(f64, @floatFromInt(y0)); - var i: usize = 0; - while (i <= @as(usize, @intCast(steps))) : (i += 1) { - setBraillePixel( - cells, - width, - @as(usize, @intFromFloat(@round(x))), - @as(usize, @intFromFloat(@round(y))), - style, - ); - x += step_x; - y += step_y; - } -} - -fn drawBrailleRect(cells: []Canvas.BrailleCell, width: u16, min_x: usize, min_y: usize, max_x: usize, max_y: usize, filled: bool, style: ?Style) void { - const left = @min(min_x, max_x); - const right = @max(min_x, max_x); - const top = @min(min_y, max_y); - const bottom = @max(min_y, max_y); - - if (filled) { - for (top..bottom + 1) |y| { - for (left..right + 1) |x| { - setBraillePixel(cells, width, x, y, style); - } - } - return; - } - - drawBrailleLine(cells, width, left, top, right, top, style); - drawBrailleLine(cells, width, left, bottom, right, bottom, style); - drawBrailleLine(cells, width, left, top, left, bottom, style); - drawBrailleLine(cells, width, right, top, right, bottom, style); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig deleted file mode 100644 index 90eff91..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/chart.zig +++ /dev/null @@ -1,758 +0,0 @@ -//! Cartesian chart widget with axes, legend, and multiple datasets. - -const std = @import("std"); -const Writer = std.Io.Writer; -const charting = @import("charting.zig"); -const canvas_mod = @import("canvas.zig"); -const join = @import("../layout/join.zig"); -const measure = @import("../layout/measure.zig"); -const style_mod = @import("../style/style.zig"); - -pub const Style = style_mod.Style; -pub const AxisLabel = charting.AxisLabel; -pub const DataRange = charting.DataRange; -pub const GraphType = charting.GraphType; -pub const Interpolation = charting.Interpolation; -pub const LegendPosition = charting.LegendPosition; -pub const Marker = charting.Marker; -pub const Point = charting.Point; -pub const ValueFormatter = charting.ValueFormatter; - -pub const Axis = struct { - title: []const u8 = "", - bounds: ?DataRange = null, - labels: []const AxisLabel = &.{}, - tick_count: u8 = 5, - show_line: bool = true, - show_labels: bool = true, - show_grid: bool = false, - style: Style = charting.inlineStyle(Style{}), - label_style: Style = charting.inlineStyle(Style{}), - title_style: Style = charting.inlineStyle((Style{}).bold(true)), - grid_style: Style = charting.inlineStyle(Style{}), - formatter: ?ValueFormatter = null, -}; - -pub const Dataset = struct { - allocator: std.mem.Allocator, - label: []const u8, - points: std.array_list.Managed(Point), - style: Style, - graph_type: GraphType, - interpolation: Interpolation, - interpolation_steps: u8, - curve_tension: f64, - show_points: bool, - point_glyph: ?[]const u8, - fill_to: ?f64, - - pub fn init(allocator: std.mem.Allocator, label: []const u8) !Dataset { - return .{ - .allocator = allocator, - .label = try allocator.dupe(u8, label), - .points = std.array_list.Managed(Point).init(allocator), - .style = charting.inlineStyle(Style{}), - .graph_type = .line, - .interpolation = .linear, - .interpolation_steps = 8, - .curve_tension = 0.5, - .show_points = false, - .point_glyph = null, - .fill_to = null, - }; - } - - pub fn deinit(self: *Dataset) void { - self.allocator.free(self.label); - self.points.deinit(); - } - - pub fn setStyle(self: *Dataset, style: Style) void { - self.style = charting.inlineStyle(style); - } - - pub fn setGraphType(self: *Dataset, graph_type: GraphType) void { - self.graph_type = graph_type; - } - - pub fn setInterpolation(self: *Dataset, interpolation: Interpolation) void { - self.interpolation = interpolation; - } - - pub fn setInterpolationSteps(self: *Dataset, steps: u8) void { - self.interpolation_steps = @max(@as(u8, 1), steps); - } - - pub fn setCurveTension(self: *Dataset, tension: f64) void { - self.curve_tension = std.math.clamp(tension, 0.0, 1.0); - } - - pub fn setShowPoints(self: *Dataset, show_points: bool) void { - self.show_points = show_points; - } - - pub fn setPointGlyph(self: *Dataset, glyph: ?[]const u8) void { - self.point_glyph = glyph; - } - - pub fn setFillBaseline(self: *Dataset, baseline: ?f64) void { - self.fill_to = baseline; - } - - pub fn appendPoint(self: *Dataset, point: Point) !void { - try self.points.append(point); - } - - pub fn setPoints(self: *Dataset, points: []const Point) !void { - self.points.clearRetainingCapacity(); - try self.points.appendSlice(points); - } -}; - -pub const Chart = struct { - allocator: std.mem.Allocator, - width: u16, - height: u16, - marker: Marker, - x_axis: Axis, - y_axis: Axis, - datasets: std.array_list.Managed(Dataset), - legend_position: LegendPosition, - legend_style: Style, - plot_background: []const u8, - - pub fn init(allocator: std.mem.Allocator) Chart { - return .{ - .allocator = allocator, - .width = 60, - .height = 18, - .marker = .braille, - .x_axis = .{}, - .y_axis = .{}, - .datasets = std.array_list.Managed(Dataset).init(allocator), - .legend_position = .bottom, - .legend_style = charting.inlineStyle((Style{}).bold(true)), - .plot_background = " ", - }; - } - - pub fn deinit(self: *Chart) void { - for (self.datasets.items) |*dataset| dataset.deinit(); - self.datasets.deinit(); - } - - pub fn clearDatasets(self: *Chart) void { - for (self.datasets.items) |*dataset| dataset.deinit(); - self.datasets.clearRetainingCapacity(); - } - - pub fn setSize(self: *Chart, width: u16, height: u16) void { - self.width = @max(10, width); - self.height = @max(6, height); - } - - pub fn setMarker(self: *Chart, marker: Marker) void { - self.marker = marker; - } - - pub fn setLegendPosition(self: *Chart, position: LegendPosition) void { - self.legend_position = position; - } - - pub fn setPlotBackground(self: *Chart, glyph: []const u8) void { - self.plot_background = glyph; - } - - pub fn addDataset(self: *Chart, dataset: Dataset) !void { - try self.datasets.append(dataset); - } - - pub fn view(self: *const Chart, allocator: std.mem.Allocator) ![]const u8 { - const resolved_x = self.resolveRange(.x); - const resolved_y = self.resolveRange(.y); - - var x_ticks = try TickSet.init(allocator, self.x_axis, resolved_x); - defer x_ticks.deinit(); - var y_ticks = try TickSet.init(allocator, self.y_axis, resolved_y); - defer y_ticks.deinit(); - - const y_label_width = if (self.y_axis.show_labels) y_ticks.maxLabelWidth() else 0; - const y_axis_offset: usize = if (self.y_axis.show_line) - 2 - else if (y_label_width > 0) - 1 - else - 0; - const left_gutter = y_label_width + y_axis_offset; - const x_axis_line_rows: usize = if (self.x_axis.show_line) 1 else 0; - const x_label_rows: usize = if (self.x_axis.show_labels) 1 else 0; - const x_title_rows: usize = if (self.x_axis.title.len > 0) 1 else 0; - const y_title_rows: usize = if (self.y_axis.title.len > 0) 1 else 0; - - const plot_width = @max(@as(usize, 1), @as(usize, self.width) -| left_gutter); - const plot_height = @max(@as(usize, 1), @as(usize, self.height) -| (x_axis_line_rows + x_label_rows + x_title_rows + y_title_rows)); - - x_ticks.updatePositions(plot_width); - y_ticks.updatePositions(plot_height); - - const plot = try self.renderPlot(allocator, plot_width, plot_height, resolved_x, resolved_y, &x_ticks, &y_ticks); - defer allocator.free(plot); - - var rows = std.array_list.Managed([]const u8).init(allocator); - defer { - for (rows.items) |row| allocator.free(row); - rows.deinit(); - } - - if (self.y_axis.title.len > 0) { - const row = try self.renderYAxisTitleRow(allocator, y_label_width, plot_width); - try rows.append(row); - } - - var plot_lines = std.mem.splitScalar(u8, plot, '\n'); - var row_index: usize = 0; - while (plot_lines.next()) |plot_line| : (row_index += 1) { - const row = try self.renderPlotRow(allocator, row_index, plot_line, plot_height, y_label_width, &y_ticks); - try rows.append(row); - } - - if (self.x_axis.show_line) { - const axis_row = try self.renderXAxisLineRow(allocator, plot_width, y_label_width); - try rows.append(axis_row); - } - - if (self.x_axis.show_labels) { - const label_row = try self.renderXAxisLabelsRow(allocator, plot_width, y_label_width, &x_ticks); - try rows.append(label_row); - } - - if (self.x_axis.title.len > 0) { - const title_row = try self.renderXAxisTitleRow(allocator, plot_width, y_label_width); - try rows.append(title_row); - } - - const chart_body = try join.vertical(allocator, .left, rows.items); - defer allocator.free(chart_body); - - const legend = try self.renderLegend(allocator); - defer allocator.free(legend); - - return switch (self.legend_position) { - .hidden => try allocator.dupe(u8, chart_body), - .top => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.vertical(allocator, .left, &.{ legend, chart_body }), - .bottom => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.vertical(allocator, .left, &.{ chart_body, legend }), - .left => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.horizontal(allocator, .top, &.{ legend, " ", chart_body }), - .right => if (legend.len == 0) try allocator.dupe(u8, chart_body) else try join.horizontal(allocator, .top, &.{ chart_body, " ", legend }), - }; - } - - const AxisKind = enum { x, y }; - - fn resolveRange(self: *const Chart, axis_kind: AxisKind) DataRange { - const axis = switch (axis_kind) { - .x => self.x_axis, - .y => self.y_axis, - }; - if (axis.bounds) |bounds| return bounds.normalized(); - - var found = false; - var min_value: f64 = 0; - var max_value: f64 = 0; - - for (self.datasets.items) |dataset| { - for (dataset.points.items) |point| { - const value = switch (axis_kind) { - .x => point.x, - .y => point.y, - }; - if (!std.math.isFinite(value)) continue; - if (!found) { - min_value = value; - max_value = value; - found = true; - } else { - min_value = @min(min_value, value); - max_value = @max(max_value, value); - } - } - - if (axis_kind == .y and dataset.graph_type == .area) { - if (dataset.fill_to) |baseline| { - if (!found) { - min_value = baseline; - max_value = baseline; - found = true; - } else { - min_value = @min(min_value, baseline); - max_value = @max(max_value, baseline); - } - } - } - } - - if (!found) return .{ .min = 0, .max = 1 }; - const range = DataRange{ .min = min_value, .max = max_value }; - return range.normalized(); - } - - fn renderPlot(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, plot_height: usize, x_range: DataRange, y_range: DataRange, x_ticks: *const TickSet, y_ticks: *const TickSet) ![]const u8 { - var buffer = try charting.CellBuffer.init(allocator, plot_width, plot_height); - defer buffer.deinit(); - - for (0..plot_height) |y| { - for (0..plot_width) |x| { - buffer.setSlice(x, y, self.plot_background, null); - } - } - - if (self.y_axis.show_grid) { - for (y_ticks.positions.items) |y| { - if (y >= plot_height) continue; - for (0..plot_width) |x| { - setGridGlyph(&buffer, x, y, .horizontal, self.y_axis.grid_style); - } - } - } - - if (self.x_axis.show_grid) { - for (x_ticks.positions.items) |x| { - if (x >= plot_width) continue; - for (0..plot_height) |y| { - setGridGlyph(&buffer, x, y, .vertical, self.x_axis.grid_style); - } - } - } - - var plot = canvas_mod.Canvas.init(allocator); - defer plot.deinit(); - - plot.setSize(@intCast(plot_width), @intCast(plot_height)); - plot.setRanges(x_range, y_range); - plot.setMarker(self.marker); - - for (self.datasets.items) |dataset| { - var path = try sampledPath(allocator, &dataset); - defer path.deinit(); - - switch (dataset.graph_type) { - .line => { - if (dataset.points.items.len == 1) { - const point = dataset.points.items[0]; - try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); - } else if (path.items.len > 1) { - var i: usize = 1; - while (i < path.items.len) : (i += 1) { - const prev = path.items[i - 1]; - const point = path.items[i]; - try plot.drawLineStyled(prev.x, prev.y, point.x, point.y, dataset.style, null); - } - } - - if (dataset.show_points) { - for (dataset.points.items) |point| { - try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); - } - } - }, - .scatter => { - for (dataset.points.items) |point| { - try plot.drawPointStyled(point.x, point.y, dataset.style, dataset.point_glyph); - } - }, - .area => { - if (path.items.len > 1) { - var i: usize = 1; - while (i < path.items.len) : (i += 1) { - const prev = path.items[i - 1]; - const point = path.items[i]; - try plot.drawLineStyled(prev.x, prev.y, point.x, point.y, dataset.style, null); - } - } - - const baseline = dataset.fill_to orelse y_range.min; - for (path.items) |point| { - try plot.drawLineStyled(point.x, baseline, point.x, point.y, dataset.style, null); - } - }, - } - } - - plot.drawIntoBuffer(&buffer); - return try buffer.render(allocator); - } - - fn renderYAxisTitleRow(self: *const Chart, allocator: std.mem.Allocator, y_label_width: usize, plot_width: usize) ![]const u8 { - const prefix_width = leftPrefixWidth(self, y_label_width); - var row = try charting.CellBuffer.init(allocator, prefix_width + plot_width, 1); - defer row.deinit(); - - for (0..row.width) |x| row.setSlice(x, 0, " ", null); - row.writeText(prefix_width, 0, self.y_axis.title, self.y_axis.title_style); - return try row.render(allocator); - } - - fn renderPlotRow(self: *const Chart, allocator: std.mem.Allocator, row_index: usize, plot_line: []const u8, plot_height: usize, y_label_width: usize, y_ticks: *const TickSet) ![]const u8 { - _ = plot_height; - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (self.y_axis.show_labels) { - const label = y_ticks.labelForRow(row_index) orelse ""; - const padded = try renderPaddedLabel(allocator, label, y_label_width, self.y_axis.label_style); - defer allocator.free(padded); - try writer.writeAll(padded); - } - - if (self.y_axis.show_line) { - const axis_glyph = try self.y_axis.style.render(allocator, " │"); - defer allocator.free(axis_glyph); - try writer.writeAll(axis_glyph); - } else if (y_label_width > 0) { - try writer.writeByte(' '); - } - - try writer.writeAll(plot_line); - return try result.toOwnedSlice(); - } - - fn renderXAxisLineRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (self.y_axis.show_labels) { - for (0..y_label_width) |_| try writer.writeByte(' '); - } - - if (self.y_axis.show_line) { - const corner = try self.x_axis.style.render(allocator, " └"); - defer allocator.free(corner); - try writer.writeAll(corner); - } else if (y_label_width > 0) { - try writer.writeByte(' '); - } - - var axis_style = self.x_axis.style; - axis_style = charting.inlineStyle(axis_style); - const segment = try axis_style.render(allocator, "─"); - defer allocator.free(segment); - for (0..plot_width) |_| try writer.writeAll(segment); - - return try result.toOwnedSlice(); - } - - fn renderXAxisLabelsRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize, x_ticks: *const TickSet) ![]const u8 { - const offset = leftPrefixWidth(self, y_label_width); - var row = try charting.CellBuffer.init(allocator, offset + plot_width, 1); - defer row.deinit(); - - for (0..row.width) |x| row.setSlice(x, 0, " ", null); - - for (x_ticks.positions.items, x_ticks.labels.items) |x, label| { - const label_width = measure.width(label); - const start = offset + x -| (label_width / 2); - row.writeText(start, 0, label, self.x_axis.label_style); - } - - return try row.render(allocator); - } - - fn renderXAxisTitleRow(self: *const Chart, allocator: std.mem.Allocator, plot_width: usize, y_label_width: usize) ![]const u8 { - const offset = leftPrefixWidth(self, y_label_width); - var row = try charting.CellBuffer.init(allocator, offset + plot_width, 1); - defer row.deinit(); - - for (0..row.width) |x| row.setSlice(x, 0, " ", null); - - const title_width = measure.width(self.x_axis.title); - const start = offset + (plot_width -| title_width) / 2; - row.writeText(start, 0, self.x_axis.title, self.x_axis.title_style); - return try row.render(allocator); - } - - fn renderLegend(self: *const Chart, allocator: std.mem.Allocator) ![]const u8 { - if (self.legend_position == .hidden or self.datasets.items.len == 0) { - return try allocator.dupe(u8, ""); - } - - var pieces = std.array_list.Managed([]const u8).init(allocator); - defer { - for (pieces.items) |piece| allocator.free(piece); - pieces.deinit(); - } - - for (self.datasets.items) |dataset| { - const symbol_raw = switch (dataset.graph_type) { - .line => "──", - .scatter => dataset.point_glyph orelse "•", - .area => "██", - }; - const symbol = try dataset.style.render(allocator, symbol_raw); - defer allocator.free(symbol); - - const label = try self.legend_style.render(allocator, dataset.label); - defer allocator.free(label); - - const piece = try std.fmt.allocPrint(allocator, "{s} {s}", .{ symbol, label }); - try pieces.append(piece); - } - - return try join.horizontal(allocator, .top, pieces.items); - } -}; - -const TickSet = struct { - allocator: std.mem.Allocator, - range: DataRange, - values: std.array_list.Managed(f64), - positions: std.array_list.Managed(usize), - labels: std.array_list.Managed([]const u8), - - fn init(allocator: std.mem.Allocator, axis: Axis, range: DataRange) !TickSet { - var self = TickSet{ - .allocator = allocator, - .range = range, - .values = std.array_list.Managed(f64).init(allocator), - .positions = std.array_list.Managed(usize).init(allocator), - .labels = std.array_list.Managed([]const u8).init(allocator), - }; - - if (axis.labels.len > 0) { - for (axis.labels) |label| { - try self.values.append(label.value); - try self.positions.append(0); - try self.labels.append(try allocator.dupe(u8, label.text)); - } - return self; - } - - const tick_count = @max(@as(usize, 2), axis.tick_count); - var i: usize = 0; - while (i < tick_count) : (i += 1) { - const t = if (tick_count == 1) 0.0 else @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(tick_count - 1)); - const value = range.min + (range.max - range.min) * t; - try self.values.append(value); - try self.positions.append(0); - - const formatter = axis.formatter orelse charting.defaultFormatter; - const label = try formatter(allocator, value); - try self.labels.append(label); - } - - return self; - } - - fn updatePositions(self: *TickSet, span: usize) void { - const usable_span = @max(@as(usize, 1), span); - for (self.values.items, 0..) |value, index| { - self.positions.items[index] = charting.mapToResolution(value, self.range, usable_span); - } - } - - fn deinit(self: *TickSet) void { - for (self.labels.items) |label| self.allocator.free(label); - self.values.deinit(); - self.positions.deinit(); - self.labels.deinit(); - } - - fn maxLabelWidth(self: *const TickSet) usize { - var max_width: usize = 0; - for (self.labels.items) |label| { - max_width = @max(max_width, measure.width(label)); - } - return max_width; - } - - fn labelForRow(self: *const TickSet, row: usize) ?[]const u8 { - for (self.positions.items, self.labels.items) |tick_row, label| { - if (tick_row == row) return label; - } - return null; - } -}; - -const GridOrientation = enum { vertical, horizontal }; - -fn renderPaddedLabel(allocator: std.mem.Allocator, label: []const u8, width: usize, style: Style) ![]const u8 { - const label_width = measure.width(label); - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const padding = width -| label_width; - for (0..padding) |_| try writer.writeByte(' '); - - if (label.len > 0) { - const rendered = try style.render(allocator, label); - defer allocator.free(rendered); - try writer.writeAll(rendered); - } - - return try result.toOwnedSlice(); -} - -fn setGridGlyph(buffer: *charting.CellBuffer, x: usize, y: usize, orientation: GridOrientation, style: Style) void { - const current = buffer.cells[y * buffer.width + x]; - const next = switch (current.glyph) { - .slice => |slice| blk: { - if (orientation == .vertical and std.mem.eql(u8, slice, "─")) break :blk "┼"; - if (orientation == .horizontal and std.mem.eql(u8, slice, "│")) break :blk "┼"; - if (std.mem.eql(u8, slice, "┼")) break :blk "┼"; - break :blk if (orientation == .vertical) "│" else "─"; - }, - else => if (orientation == .vertical) "│" else "─", - }; - buffer.setSlice(x, y, next, style); -} - -fn leftPrefixWidth(self: *const Chart, y_label_width: usize) usize { - return y_label_width + (if (self.y_axis.show_line) - @as(usize, 2) - else if (y_label_width > 0) - @as(usize, 1) - else - @as(usize, 0)); -} - -fn sampledPath(allocator: std.mem.Allocator, dataset: *const Dataset) !std.array_list.Managed(Point) { - var path = std.array_list.Managed(Point).init(allocator); - if (dataset.points.items.len == 0) return path; - - switch (dataset.interpolation) { - .linear => try path.appendSlice(dataset.points.items), - .step_start => try appendSteppedPoints(&path, dataset.points.items, .step_start), - .step_center => try appendSteppedPoints(&path, dataset.points.items, .step_center), - .step_end => try appendSteppedPoints(&path, dataset.points.items, .step_end), - .catmull_rom => try appendCatmullRomPoints(&path, dataset.points.items, dataset.interpolation_steps, dataset.curve_tension), - .monotone_cubic => try appendMonotonePoints(allocator, &path, dataset.points.items, dataset.interpolation_steps), - } - - return path; -} - -fn appendSteppedPoints(path: *std.array_list.Managed(Point), points: []const Point, mode: Interpolation) !void { - if (points.len == 0) return; - try path.append(points[0]); - - for (points[1..], 1..) |point, index| { - const prev = points[index - 1]; - switch (mode) { - .step_start => { - try path.append(.{ .x = prev.x, .y = point.y }); - }, - .step_center => { - const mid_x = prev.x + (point.x - prev.x) / 2.0; - try path.append(.{ .x = mid_x, .y = prev.y }); - try path.append(.{ .x = mid_x, .y = point.y }); - }, - .step_end => { - try path.append(.{ .x = point.x, .y = prev.y }); - }, - else => unreachable, - } - try path.append(point); - } -} - -fn appendCatmullRomPoints(path: *std.array_list.Managed(Point), points: []const Point, steps: u8, tension: f64) !void { - if (points.len <= 2) { - try path.appendSlice(points); - return; - } - - const alpha = 1.0 - tension; - try path.append(points[0]); - - var i: usize = 0; - while (i + 1 < points.len) : (i += 1) { - const p0 = if (i == 0) points[i] else points[i - 1]; - const p1 = points[i]; - const p2 = points[i + 1]; - const p3 = if (i + 2 < points.len) points[i + 2] else points[i + 1]; - - var step: usize = 1; - while (step <= steps) : (step += 1) { - const t = @as(f64, @floatFromInt(step)) / @as(f64, @floatFromInt(steps)); - try path.append(catmullRomPoint(p0, p1, p2, p3, t, alpha)); - } - } -} - -fn catmullRomPoint(p0: Point, p1: Point, p2: Point, p3: Point, t: f64, alpha: f64) Point { - const t2 = t * t; - const t3 = t2 * t; - - const a0 = -alpha * t3 + 2.0 * alpha * t2 - alpha * t; - const a1 = (2.0 - alpha) * t3 + (alpha - 3.0) * t2 + 1.0; - const a2 = (alpha - 2.0) * t3 + (3.0 - 2.0 * alpha) * t2 + alpha * t; - const a3 = alpha * t3 - alpha * t2; - - return .{ - .x = a0 * p0.x + a1 * p1.x + a2 * p2.x + a3 * p3.x, - .y = a0 * p0.y + a1 * p1.y + a2 * p2.y + a3 * p3.y, - }; -} - -fn appendMonotonePoints(allocator: std.mem.Allocator, path: *std.array_list.Managed(Point), points: []const Point, steps: u8) !void { - if (points.len <= 2 or !strictlyIncreasingX(points)) { - try path.appendSlice(points); - return; - } - - const delta = try allocator.alloc(f64, points.len - 1); - defer allocator.free(delta); - const slopes = try allocator.alloc(f64, points.len); - defer allocator.free(slopes); - - for (0..points.len - 1) |i| { - const dx = points[i + 1].x - points[i].x; - if (dx <= 0) { - try path.appendSlice(points); - return; - } - delta[i] = (points[i + 1].y - points[i].y) / dx; - } - - slopes[0] = delta[0]; - slopes[points.len - 1] = delta[delta.len - 1]; - - for (1..points.len - 1) |i| { - if (delta[i - 1] == 0 or delta[i] == 0 or std.math.signbit(delta[i - 1]) != std.math.signbit(delta[i])) { - slopes[i] = 0; - } else { - const h0 = points[i].x - points[i - 1].x; - const h1 = points[i + 1].x - points[i].x; - const w1 = 2.0 * h1 + h0; - const w2 = h1 + 2.0 * h0; - slopes[i] = (w1 + w2) / (w1 / delta[i - 1] + w2 / delta[i]); - } - } - - try path.append(points[0]); - for (0..points.len - 1) |i| { - const p0 = points[i]; - const p1 = points[i + 1]; - const dx = p1.x - p0.x; - - var step: usize = 1; - while (step <= steps) : (step += 1) { - const t = @as(f64, @floatFromInt(step)) / @as(f64, @floatFromInt(steps)); - const t2 = t * t; - const t3 = t2 * t; - const h00 = 2.0 * t3 - 3.0 * t2 + 1.0; - const h10 = t3 - 2.0 * t2 + t; - const h01 = -2.0 * t3 + 3.0 * t2; - const h11 = t3 - t2; - try path.append(.{ - .x = p0.x + dx * t, - .y = h00 * p0.y + h10 * dx * slopes[i] + h01 * p1.y + h11 * dx * slopes[i + 1], - }); - } - } -} - -fn strictlyIncreasingX(points: []const Point) bool { - for (points[1..], 1..) |point, index| { - if (!(point.x > points[index - 1].x)) return false; - } - return true; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig deleted file mode 100644 index 0c2ac41..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/charting.zig +++ /dev/null @@ -1,253 +0,0 @@ -//! Shared plotting primitives for chart-like components. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("../layout/measure.zig"); -const style_mod = @import("../style/style.zig"); - -pub const Style = style_mod.Style; - -pub const Point = struct { - x: f64, - y: f64, -}; - -pub const DataRange = struct { - min: f64, - max: f64, - - pub fn normalized(self: DataRange) DataRange { - if (!std.math.isFinite(self.min) or !std.math.isFinite(self.max)) { - return .{ .min = 0, .max = 1 }; - } - - if (self.min == self.max) { - return .{ - .min = self.min - 0.5, - .max = self.max + 0.5, - }; - } - - if (self.min < self.max) return self; - - return .{ - .min = self.max, - .max = self.min, - }; - } - - pub fn span(self: DataRange) f64 { - const normalized_range = self.normalized(); - return normalized_range.max - normalized_range.min; - } -}; - -pub const Marker = enum { - braille, - block, - dot, - ascii, -}; - -pub const GraphType = enum { - line, - scatter, - area, -}; - -pub const Interpolation = enum { - linear, - step_start, - step_center, - step_end, - catmull_rom, - monotone_cubic, -}; - -pub const Orientation = enum { - vertical, - horizontal, -}; - -pub const Summary = enum { - last, - average, - minimum, - maximum, - sum, -}; - -pub const LegendPosition = enum { - hidden, - top, - bottom, - left, - right, -}; - -pub const AxisLabel = struct { - value: f64, - text: []const u8, -}; - -pub const ValueFormatter = *const fn (std.mem.Allocator, f64) anyerror![]const u8; - -pub const Glyph = union(enum) { - slice: []const u8, - codepoint: u21, -}; - -pub const Cell = struct { - glyph: Glyph = .{ .slice = " " }, - style: ?Style = null, -}; - -pub const CellBuffer = struct { - allocator: std.mem.Allocator, - width: usize, - height: usize, - cells: []Cell, - - pub fn init(allocator: std.mem.Allocator, width: usize, height: usize) !CellBuffer { - const cells = try allocator.alloc(Cell, width * height); - for (cells) |*cell| cell.* = .{}; - - return .{ - .allocator = allocator, - .width = width, - .height = height, - .cells = cells, - }; - } - - pub fn deinit(self: *CellBuffer) void { - self.allocator.free(self.cells); - } - - pub fn clear(self: *CellBuffer) void { - for (self.cells) |*cell| cell.* = .{}; - } - - fn index(self: *const CellBuffer, x: usize, y: usize) usize { - return y * self.width + x; - } - - pub fn setGlyph(self: *CellBuffer, x: usize, y: usize, glyph: Glyph, style: ?Style) void { - if (x >= self.width or y >= self.height) return; - self.cells[self.index(x, y)] = .{ - .glyph = glyph, - .style = style, - }; - } - - pub fn setSlice(self: *CellBuffer, x: usize, y: usize, glyph: []const u8, style: ?Style) void { - self.setGlyph(x, y, .{ .slice = glyph }, style); - } - - pub fn setCodepoint(self: *CellBuffer, x: usize, y: usize, codepoint: u21, style: ?Style) void { - self.setGlyph(x, y, .{ .codepoint = codepoint }, style); - } - - pub fn writeText(self: *CellBuffer, x: usize, y: usize, text: []const u8, style: ?Style) void { - if (y >= self.height) return; - - var col = x; - var i: usize = 0; - while (i < text.len and col < self.width) { - const byte_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; - const end = @min(text.len, i + byte_len); - const glyph = text[i..end]; - - var codepoint_width: usize = 1; - if (end <= text.len) { - const cp = std.unicode.utf8Decode(glyph) catch 0; - if (cp != 0) { - codepoint_width = @max(1, measure.charWidth(cp)); - } - } - - self.setSlice(col, y, glyph, style); - if (codepoint_width > 1) { - var extra: usize = 1; - while (extra < codepoint_width and col + extra < self.width) : (extra += 1) { - self.setSlice(col + extra, y, " ", style); - } - } - - col += codepoint_width; - i = end; - } - } - - pub fn render(self: *const CellBuffer, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var glyph_buf: [4]u8 = undefined; - - for (0..self.height) |y| { - if (y > 0) try writer.writeByte('\n'); - - for (0..self.width) |x| { - const cell = self.cells[self.index(x, y)]; - const glyph = switch (cell.glyph) { - .slice => |slice| slice, - .codepoint => |cp| blk: { - const len = try std.unicode.utf8Encode(cp, &glyph_buf); - break :blk glyph_buf[0..len]; - }, - }; - - if (cell.style) |base_style| { - var inline_style = base_style.inline_style(true); - const rendered = try inline_style.render(allocator, glyph); - defer allocator.free(rendered); - try writer.writeAll(rendered); - } else { - try writer.writeAll(glyph); - } - } - } - - return try result.toOwnedSlice(); - } -}; - -pub fn inlineStyle(style: Style) Style { - return style.inline_style(true); -} - -pub fn clampUnit(value: f64) f64 { - if (value < 0) return 0; - if (value > 1) return 1; - return value; -} - -pub fn mapToResolution(value: f64, range: DataRange, resolution: usize) usize { - if (resolution <= 1) return 0; - - const normalized = range.normalized(); - const span = normalized.max - normalized.min; - if (span <= 0) return 0; - - const unit = clampUnit((value - normalized.min) / span); - return @intFromFloat(@round(unit * @as(f64, @floatFromInt(resolution - 1)))); -} - -pub fn mapX(value: f64, range: DataRange, width: usize) usize { - return mapToResolution(value, range, width); -} - -pub fn mapY(value: f64, range: DataRange, height: usize) usize { - if (height <= 1) return 0; - const mapped = mapToResolution(value, range, height); - return (height - 1) - mapped; -} - -pub fn defaultFormatter(allocator: std.mem.Allocator, value: f64) ![]const u8 { - if (value == @trunc(value)) { - return try std.fmt.allocPrint(allocator, "{d}", .{@as(i64, @intFromFloat(value))}); - } - - return try std.fmt.allocPrint(allocator, "{d:.2}", .{value}); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig deleted file mode 100644 index 9cdb38a..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/checkbox.zig +++ /dev/null @@ -1,434 +0,0 @@ -//! Checkbox and CheckboxGroup components. -//! Standalone boolean toggle and multi-select checkbox group. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -/// Standalone checkbox - a single boolean toggle. -pub const Checkbox = struct { - label: []const u8, - checked: bool, - enabled: bool, - focused: bool, - - // Symbols - checked_symbol: []const u8, - unchecked_symbol: []const u8, - - // Styling - label_style: style_mod.Style, - checked_style: style_mod.Style, - unchecked_style: style_mod.Style, - focused_style: style_mod.Style, - disabled_style: style_mod.Style, - - pub fn init(label: []const u8) Checkbox { - return .{ - .label = label, - .checked = false, - .enabled = true, - .focused = true, - .checked_symbol = "[x] ", - .unchecked_symbol = "[ ] ", - .label_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .checked_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .unchecked_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .focused_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.magenta); - s = s.inline_style(true); - break :blk s; - }, - .disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn toggle(self: *Checkbox) void { - if (!self.enabled) return; - self.checked = !self.checked; - } - - pub fn setChecked(self: *Checkbox, value: bool) void { - self.checked = value; - } - - pub fn isChecked(self: *const Checkbox) bool { - return self.checked; - } - - pub fn focus(self: *Checkbox) void { - self.focused = true; - } - - pub fn blur(self: *Checkbox) void { - self.focused = false; - } - - pub fn handleKey(self: *Checkbox, key: keys.KeyEvent) void { - if (!self.focused or !self.enabled) return; - - switch (key.key) { - .space, .enter => self.toggle(), - else => {}, - } - } - - pub fn view(self: *const Checkbox, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const symbol = if (self.checked) self.checked_symbol else self.unchecked_symbol; - const sym_style = if (!self.enabled) - self.disabled_style - else if (self.checked) - self.checked_style - else - self.unchecked_style; - - const styled_symbol = try sym_style.render(allocator, symbol); - try writer.writeAll(styled_symbol); - - const lbl_style = if (!self.enabled) - self.disabled_style - else if (self.focused) - self.focused_style - else - self.label_style; - - const styled_label = try lbl_style.render(allocator, self.label); - try writer.writeAll(styled_label); - - return result.toOwnedSlice(); - } -}; - -/// Multi-select checkbox group. -pub fn CheckboxGroup(comptime T: type) type { - return struct { - allocator: std.mem.Allocator, - - // Items - items: std.array_list.Managed(Item), - - // Navigation - cursor: usize, - height: u16, - y_offset: usize, - - // Focus - focused: bool, - - // Constraints - min_selected: usize, - max_selected: ?usize, - - // Symbols - cursor_symbol: []const u8, - checked_symbol: []const u8, - unchecked_symbol: []const u8, - - // Styling - item_style: style_mod.Style, - checked_style: style_mod.Style, - cursor_style: style_mod.Style, - disabled_style: style_mod.Style, - - const Self = @This(); - - pub const Item = struct { - value: T, - label: []const u8, - description: []const u8, - enabled: bool, - checked: bool, - - pub fn init(value: T, label: []const u8) Item { - return .{ - .value = value, - .label = label, - .description = "", - .enabled = true, - .checked = false, - }; - } - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .items = std.array_list.Managed(Item).init(allocator), - .cursor = 0, - .height = 10, - .y_offset = 0, - .focused = true, - .min_selected = 0, - .max_selected = null, - .cursor_symbol = "> ", - .checked_symbol = "[x] ", - .unchecked_symbol = "[ ] ", - .item_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .checked_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.magenta); - s = s.inline_style(true); - break :blk s; - }, - .disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *Self) void { - self.items.deinit(); - } - - pub fn addItem(self: *Self, item: Item) !void { - try self.items.append(item); - } - - pub fn addItems(self: *Self, new_items: []const Item) !void { - try self.items.appendSlice(new_items); - } - - pub fn toggleCurrent(self: *Self) void { - if (self.cursor >= self.items.items.len) return; - const item = &self.items.items[self.cursor]; - if (!item.enabled) return; - - if (item.checked) { - // Check min constraint - if (self.checkedCount() <= self.min_selected) return; - item.checked = false; - } else { - // Check max constraint - if (self.max_selected) |max| { - if (self.checkedCount() >= max) return; - } - item.checked = true; - } - } - - pub fn selectAll(self: *Self) void { - for (self.items.items) |*item| { - if (item.enabled) item.checked = true; - } - } - - pub fn selectNone(self: *Self) void { - for (self.items.items) |*item| { - if (item.enabled) item.checked = false; - } - } - - pub fn invertSelection(self: *Self) void { - for (self.items.items) |*item| { - if (item.enabled) item.checked = !item.checked; - } - } - - pub fn checkedCount(self: *const Self) usize { - var count: usize = 0; - for (self.items.items) |item| { - if (item.checked) count += 1; - } - return count; - } - - pub fn checkedValues(self: *const Self, allocator: std.mem.Allocator) ![]const T { - var result = std.array_list.Managed(T).init(allocator); - for (self.items.items) |item| { - if (item.checked) try result.append(item.value); - } - return result.toOwnedSlice(); - } - - // Focus protocol - pub fn focus(self: *Self) void { - self.focused = true; - } - - pub fn blur(self: *Self) void { - self.focused = false; - } - - pub fn handleKey(self: *Self, key: keys.KeyEvent) void { - if (!self.focused) return; - - switch (key.key) { - .up => self.cursorUp(), - .down => self.cursorDown(), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoFirst(), - .end => self.gotoLast(), - .space => self.toggleCurrent(), - .char => |c| switch (c) { - 'j' => self.cursorDown(), - 'k' => self.cursorUp(), - 'g' => self.gotoFirst(), - 'G' => self.gotoLast(), - 'a' => self.selectAll(), - 'n' => self.selectNone(), - 'i' => self.invertSelection(), - else => {}, - }, - else => {}, - } - } - - fn cursorUp(self: *Self) void { - if (self.items.items.len == 0) return; - if (self.cursor > 0) { - self.cursor -= 1; - } else { - self.cursor = self.items.items.len - 1; - } - self.ensureVisible(); - } - - fn cursorDown(self: *Self) void { - if (self.items.items.len == 0) return; - if (self.cursor < self.items.items.len - 1) { - self.cursor += 1; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - fn pageUp(self: *Self) void { - if (self.cursor >= self.height) { - self.cursor -= self.height; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - fn pageDown(self: *Self) void { - if (self.cursor + self.height < self.items.items.len) { - self.cursor += self.height; - } else if (self.items.items.len > 0) { - self.cursor = self.items.items.len - 1; - } - self.ensureVisible(); - } - - fn gotoFirst(self: *Self) void { - self.cursor = 0; - self.y_offset = 0; - } - - fn gotoLast(self: *Self) void { - if (self.items.items.len > 0) { - self.cursor = self.items.items.len - 1; - self.ensureVisible(); - } - } - - fn ensureVisible(self: *Self) void { - if (self.cursor < self.y_offset) { - self.y_offset = self.cursor; - } else if (self.cursor >= self.y_offset + self.height) { - self.y_offset = self.cursor - self.height + 1; - } - } - - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var rendered: usize = 0; - while (rendered < self.height) : (rendered += 1) { - if (rendered > 0) try writer.writeByte('\n'); - - const idx = self.y_offset + rendered; - if (idx >= self.items.items.len) break; - - const item = self.items.items[idx]; - - // Cursor - if (idx == self.cursor and self.focused) { - const styled = try self.cursor_style.render(allocator, self.cursor_symbol); - try writer.writeAll(styled); - } else { - for (0..self.cursor_symbol.len) |_| { - try writer.writeByte(' '); - } - } - - // Check symbol - const check_sym = if (item.checked) self.checked_symbol else self.unchecked_symbol; - const check_s = if (!item.enabled) - self.disabled_style - else if (item.checked) - self.checked_style - else - self.item_style; - const styled_check = try check_s.render(allocator, check_sym); - try writer.writeAll(styled_check); - - // Label - const lbl_style = if (!item.enabled) - self.disabled_style - else if (idx == self.cursor and self.focused) - self.cursor_style - else if (item.checked) - self.checked_style - else - self.item_style; - const styled_label = try lbl_style.render(allocator, item.label); - try writer.writeAll(styled_label); - - // Description - if (item.description.len > 0) { - try writer.writeAll(" - "); - try writer.writeAll(item.description); - } - } - - return result.toOwnedSlice(); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig deleted file mode 100644 index 2798003..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/code_view.zig +++ /dev/null @@ -1,255 +0,0 @@ -//! Code viewer with syntax highlighting. -//! Provides keyword-based highlighting for common languages. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const CodeView = struct { - source: []const u8 = "", - language: Language = .zig, - show_line_numbers: bool = true, - start_line: usize = 1, - /// Highlight specific line (1-indexed, 0 = none). - highlight_line: usize = 0, - /// Line number width (number of digits, 0 = auto). - line_number_width: u8 = 4, - /// Separator between line numbers and code. - line_separator: []const u8 = "\xe2\x94\x82", - /// Tab display width. - tab_width: u8 = 4, - /// Operator style. - operator_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - - // Styles - keyword_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.magenta); - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - string_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - comment_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(10)); - s = s.italic(true); - s = s.inline_style(true); - break :blk s; - }, - number_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - type_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - builtin_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - line_number_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - highlight_bg: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bg(.fromRgb(40, 40, 60)); - s = s.inline_style(true); - break :blk s; - }, - - pub const Language = enum { - zig, - python, - javascript, - go, - rust, - plain, - }; - - pub fn view(self: *const CodeView, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var lines = std.mem.splitScalar(u8, self.source, '\n'); - var line_num: usize = self.start_line; - var first = true; - var in_multiline_comment = false; - - while (lines.next()) |line| { - if (!first) writer.writeByte('\n') catch {}; - first = false; - - // Line number - if (self.show_line_numbers) { - const num_str = std.fmt.allocPrint(allocator, "{d:>4} {s} ", .{ line_num, self.line_separator }) catch " ? | "; - writer.writeAll(self.line_number_style.render(allocator, num_str) catch num_str) catch {}; - } - - // Highlight line background - const is_highlighted = (self.highlight_line > 0 and line_num == self.highlight_line); - - // Syntax highlight the line - const highlighted = self.highlightLine(allocator, line, &in_multiline_comment); - if (is_highlighted) { - writer.writeAll(self.highlight_bg.render(allocator, highlighted) catch highlighted) catch {}; - } else { - writer.writeAll(highlighted) catch {}; - } - - line_num += 1; - } - - return result.toArrayList().items; - } - - fn highlightLine(self: *const CodeView, allocator: std.mem.Allocator, line: []const u8, in_multiline: *bool) []const u8 { - if (self.language == .plain) return line; - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var i: usize = 0; - while (i < line.len) { - // Multi-line comment continuation - if (in_multiline.*) { - if (i + 1 < line.len and line[i] == '*' and line[i + 1] == '/') { - writer.writeAll(self.comment_style.render(allocator, "*/") catch "*/") catch {}; - i += 2; - in_multiline.* = false; - continue; - } - writer.writeAll(self.comment_style.render(allocator, line[i .. i + 1]) catch line[i .. i + 1]) catch {}; - i += 1; - continue; - } - - // Line comments - if (isLineComment(self.language, line, i)) { - writer.writeAll(self.comment_style.render(allocator, line[i..]) catch line[i..]) catch {}; - break; - } - - // Multi-line comment start - if (i + 1 < line.len and line[i] == '/' and line[i + 1] == '*') { - in_multiline.* = true; - writer.writeAll(self.comment_style.render(allocator, "/*") catch "/*") catch {}; - i += 2; - continue; - } - - // Strings - if (line[i] == '"' or line[i] == '\'') { - const quote = line[i]; - const str_start = i; - i += 1; - while (i < line.len and line[i] != quote) { - if (line[i] == '\\') i += 1; // skip escape - i += 1; - } - if (i < line.len) i += 1; // closing quote - writer.writeAll(self.string_style.render(allocator, line[str_start..i]) catch line[str_start..i]) catch {}; - continue; - } - - // Builtins (Zig @-prefixed) - if (self.language == .zig and line[i] == '@' and i + 1 < line.len and std.ascii.isAlphabetic(line[i + 1])) { - const start = i; - i += 1; - while (i < line.len and (std.ascii.isAlphanumeric(line[i]) or line[i] == '_')) : (i += 1) {} - writer.writeAll(self.builtin_style.render(allocator, line[start..i]) catch line[start..i]) catch {}; - continue; - } - - // Numbers - if (std.ascii.isDigit(line[i])) { - const start = i; - while (i < line.len and (std.ascii.isDigit(line[i]) or line[i] == '.' or line[i] == 'x' or line[i] == '_')) : (i += 1) {} - writer.writeAll(self.number_style.render(allocator, line[start..i]) catch line[start..i]) catch {}; - continue; - } - - // Identifiers / keywords - if (std.ascii.isAlphabetic(line[i]) or line[i] == '_') { - const start = i; - while (i < line.len and (std.ascii.isAlphanumeric(line[i]) or line[i] == '_')) : (i += 1) {} - const word = line[start..i]; - - if (isKeyword(self.language, word)) { - writer.writeAll(self.keyword_style.render(allocator, word) catch word) catch {}; - } else if (isType(self.language, word)) { - writer.writeAll(self.type_style.render(allocator, word) catch word) catch {}; - } else { - writer.writeAll(word) catch {}; - } - continue; - } - - // Other characters - writer.writeByte(line[i]) catch {}; - i += 1; - } - - return result.toArrayList().items; - } - - fn isLineComment(lang: Language, line: []const u8, pos: usize) bool { - return switch (lang) { - .zig, .go, .rust, .javascript => pos + 1 < line.len and line[pos] == '/' and line[pos + 1] == '/', - .python => line[pos] == '#', - .plain => false, - }; - } - - fn isKeyword(lang: Language, word: []const u8) bool { - const keywords = switch (lang) { - .zig => &[_][]const u8{ "const", "var", "fn", "pub", "return", "if", "else", "while", "for", "switch", "break", "continue", "defer", "errdefer", "try", "catch", "comptime", "inline", "struct", "enum", "union", "error", "test", "unreachable", "undefined", "null", "true", "false", "and", "or", "orelse", "import" }, - .python => &[_][]const u8{ "def", "class", "if", "elif", "else", "for", "while", "return", "import", "from", "as", "try", "except", "finally", "with", "yield", "lambda", "pass", "break", "continue", "True", "False", "None", "and", "or", "not", "in", "is", "raise", "async", "await" }, - .javascript => &[_][]const u8{ "const", "let", "var", "function", "return", "if", "else", "for", "while", "switch", "case", "break", "continue", "class", "extends", "new", "this", "import", "export", "from", "async", "await", "try", "catch", "finally", "throw", "typeof", "instanceof", "true", "false", "null", "undefined" }, - .go => &[_][]const u8{ "func", "var", "const", "type", "struct", "interface", "return", "if", "else", "for", "switch", "case", "break", "continue", "defer", "go", "select", "chan", "map", "range", "import", "package", "true", "false", "nil" }, - .rust => &[_][]const u8{ "fn", "let", "mut", "const", "pub", "return", "if", "else", "for", "while", "loop", "match", "struct", "enum", "impl", "trait", "use", "mod", "crate", "self", "super", "move", "async", "await", "true", "false", "where" }, - .plain => &[_][]const u8{}, - }; - for (keywords) |kw| { - if (std.mem.eql(u8, word, kw)) return true; - } - return false; - } - - fn isType(lang: Language, word: []const u8) bool { - const types = switch (lang) { - .zig => &[_][]const u8{ "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "f32", "f64", "bool", "void", "usize", "isize", "type", "anytype", "anyerror", "noreturn" }, - .python => &[_][]const u8{ "int", "float", "str", "bool", "list", "dict", "tuple", "set", "bytes", "type", "object" }, - .javascript => &[_][]const u8{ "number", "string", "boolean", "object", "Array", "Promise", "Map", "Set" }, - .go => &[_][]const u8{ "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "string", "bool", "byte", "rune", "error" }, - .rust => &[_][]const u8{ "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "bool", "str", "String", "Vec", "Box", "Option", "Result", "usize", "isize" }, - .plain => &[_][]const u8{}, - }; - for (types) |t| { - if (std.mem.eql(u8, word, t)) return true; - } - return false; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig deleted file mode 100644 index 7c15e9e..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/command_palette.zig +++ /dev/null @@ -1,422 +0,0 @@ -//! 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 Writer = std.Io.Writer; -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"); -const action_mod = @import("../core/action.zig"); -const ActionRegistry = action_mod.ActionRegistry; - -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(.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(.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(.gray(10)); - desc_s = desc_s.inline_style(true); - - var shortcut_s = style_mod.Style{}; - shortcut_s = shortcut_s.fg(.gray(8)); - shortcut_s = shortcut_s.inline_style(true); - - var selected_s = style_mod.Style{}; - selected_s = selected_s.bg(.gray(4)); - selected_s = selected_s.inline_style(true); - - var selected_label_s = style_mod.Style{}; - selected_label_s = selected_label_s.bg(.gray(4)); - selected_label_s = selected_label_s.fg(.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(.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 = .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.freeAllCommandStrings(); - self.commands.deinit(); - self.filtered.deinit(); - self.query.deinit(); - } - - /// Add a command. The palette clones every string in `cmd` (id, label, - /// description, shortcut) so the caller is free to pass arena-allocated, - /// formatted, or otherwise short-lived strings — no lifetime tracking - /// required. - pub fn addCommand(self: *CommandPalette, cmd: Command) !void { - const owned = try self.cloneCommand(cmd); - errdefer self.freeCommand(owned); - try self.commands.append(owned); - try self.rebuildFilter(); - } - - /// Replace all commands. Each input command's strings are cloned. Old - /// commands are freed. - pub fn setCommands(self: *CommandPalette, cmds: []const Command) !void { - self.freeAllCommandStrings(); - self.commands.clearRetainingCapacity(); - for (cmds) |cmd| { - const owned = try self.cloneCommand(cmd); - errdefer self.freeCommand(owned); - try self.commands.append(owned); - } - try self.rebuildFilter(); - } - - /// Convenience: load every enabled action from a registry, formatting its - /// binding as the shortcut hint. Cleaner than building Command structs by - /// hand and avoids the need to manage shortcut-string lifetimes. - pub fn setFromRegistry(self: *CommandPalette, registry: *const ActionRegistry) !void { - self.freeAllCommandStrings(); - self.commands.clearRetainingCapacity(); - for (registry.actions.items) |a| { - if (!a.enabled) continue; - const shortcut = if (a.binding) |b| - try ActionRegistry.formatKey(self.allocator, b) - else - try self.allocator.dupe(u8, ""); - // shortcut is heap-owned; cloneCommand will dup again, so free - // the temporary after. - defer self.allocator.free(shortcut); - - const owned = try self.cloneCommand(.{ - .id = a.id, - .label = a.label, - .description = a.description, - .shortcut = shortcut, - }); - errdefer self.freeCommand(owned); - try self.commands.append(owned); - } - try self.rebuildFilter(); - } - - /// Reset the typed query and cursor without touching the command list. - pub fn clear(self: *CommandPalette) !void { - self.query.clearRetainingCapacity(); - self.cursor = 0; - try self.rebuildFilter(); - } - - fn cloneCommand(self: *CommandPalette, cmd: Command) !Command { - const id = try self.allocator.dupe(u8, cmd.id); - errdefer self.allocator.free(id); - const label = try self.allocator.dupe(u8, cmd.label); - errdefer self.allocator.free(label); - const description = try self.allocator.dupe(u8, cmd.description); - errdefer self.allocator.free(description); - const shortcut = try self.allocator.dupe(u8, cmd.shortcut); - return .{ - .id = id, - .label = label, - .description = description, - .shortcut = shortcut, - }; - } - - fn freeCommand(self: *CommandPalette, cmd: Command) void { - self.allocator.free(cmd.id); - self.allocator.free(cmd.label); - self.allocator.free(cmd.description); - self.allocator.free(cmd.shortcut); - } - - fn freeAllCommandStrings(self: *CommandPalette) void { - for (self.commands.items) |c| self.freeCommand(c); - } - - /// 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: Writer.Allocating = .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, 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: *Writer, - 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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig deleted file mode 100644 index 5dc5b9b..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/confirm.zig +++ /dev/null @@ -1,154 +0,0 @@ -//! Confirmation dialog component. -//! Simple yes/no prompt with keyboard navigation. - -const std = @import("std"); -const keys = @import("../input/keys.zig"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Confirm = struct { - prompt_text: []const u8, - selected: Selection, - confirmed: ?bool, - active: bool, - focused: bool, - - // Styling - prompt_style: style_mod.Style, - active_style: style_mod.Style, - inactive_style: style_mod.Style, - - pub const Selection = enum { - yes, - no, - }; - - pub fn init(prompt_text: []const u8) Confirm { - return .{ - .prompt_text = prompt_text, - .selected = .yes, - .confirmed = null, - .active = false, - .focused = true, - .prompt_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .active_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .inactive_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - /// Show the confirmation dialog - pub fn show(self: *Confirm) void { - self.active = true; - self.confirmed = null; - self.selected = .yes; - } - - /// Hide the dialog - pub fn hide(self: *Confirm) void { - self.active = false; - } - - /// Check if confirmed (returns true for yes, false for no, null if not yet confirmed) - pub fn result(self: *const Confirm) ?bool { - return self.confirmed; - } - - /// Set focused state (for use with FocusGroup). - pub fn focus(self: *Confirm) void { - self.focused = true; - } - - /// Clear focused state (for use with FocusGroup). - pub fn blur(self: *Confirm) void { - self.focused = false; - } - - /// Handle a key event - pub fn handleKey(self: *Confirm, key: keys.KeyEvent) void { - if (!self.active or !self.focused) return; - - switch (key.key) { - .left, .right, .tab => { - self.selected = if (self.selected == .yes) .no else .yes; - }, - .char => |c| switch (c) { - 'y', 'Y' => { - self.confirmed = true; - self.active = false; - }, - 'n', 'N' => { - self.confirmed = false; - self.active = false; - }, - 'h' => self.selected = .yes, - 'l' => self.selected = .no, - else => {}, - }, - .enter => { - self.confirmed = (self.selected == .yes); - self.active = false; - }, - .escape => { - self.confirmed = false; - self.active = false; - }, - else => {}, - } - } - - /// Render the confirmation dialog - pub fn view(self: *const Confirm, allocator: std.mem.Allocator) ![]const u8 { - if (!self.active) { - return try allocator.dupe(u8, ""); - } - - var result_buf: Writer.Allocating = .init(allocator); - const writer = &result_buf.writer; - - // Prompt - const styled_prompt = try self.prompt_style.render(allocator, self.prompt_text); - try writer.writeAll(styled_prompt); - try writer.writeAll(" "); - - // Yes option - const yes_style = if (self.selected == .yes) self.active_style else self.inactive_style; - if (self.selected == .yes) { - const styled = try yes_style.render(allocator, "[Yes]"); - try writer.writeAll(styled); - } else { - const styled = try yes_style.render(allocator, " Yes "); - try writer.writeAll(styled); - } - - try writer.writeAll(" "); - - // No option - const no_style = if (self.selected == .no) self.active_style else self.inactive_style; - if (self.selected == .no) { - const styled = try no_style.render(allocator, "[No]"); - try writer.writeAll(styled); - } else { - const styled = try no_style.render(allocator, " No "); - try writer.writeAll(styled); - } - - return result_buf.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig deleted file mode 100644 index 6dcaee5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/context_menu.zig +++ /dev/null @@ -1,392 +0,0 @@ -//! Context menu component. -//! Popup menu triggered by keyboard shortcut or mouse, positioned at a target location. - -const std = @import("std"); -const Writer = std.Io.Writer; -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"); - -pub fn ContextMenu(comptime Action: type) type { - return struct { - const max_items = 20; - - // Items - items: [max_items]?MenuItem, - item_count: usize, - - // State - visible: bool, - cursor: usize, - selected_action: ?Action, - - // Position - x: usize, - y: usize, - - // Styling - item_style: style_mod.Style, - active_style: style_mod.Style, - disabled_style: style_mod.Style, - separator_style: style_mod.Style, - shortcut_style: style_mod.Style, - border_chars: border_mod.BorderChars, - border_fg: Color, - - const Self = @This(); - - pub const MenuItem = union(enum) { - action: ActionItem, - separator: void, - }; - - pub const ActionItem = struct { - label: []const u8, - shortcut_display: []const u8, - action: Action, - enabled: bool, - }; - - pub fn init() Self { - return .{ - .items = [_]?MenuItem{null} ** max_items, - .item_count = 0, - .visible = false, - .cursor = 0, - .selected_action = null, - .x = 0, - .y = 0, - .item_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(18)); - s = s.inline_style(true); - break :blk s; - }, - .active_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.white); - s = s.bg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - .separator_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - .shortcut_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .border_chars = .rounded, - .border_fg = .gray(14), - }; - } - - /// Add an action item. - pub fn addItem(self: *Self, label: []const u8, shortcut: []const u8, action: Action) void { - if (self.item_count >= max_items) return; - self.items[self.item_count] = .{ .action = .{ - .label = label, - .shortcut_display = shortcut, - .action = action, - .enabled = true, - } }; - self.item_count += 1; - } - - /// Add a disabled item. - pub fn addDisabledItem(self: *Self, label: []const u8, action: Action) void { - if (self.item_count >= max_items) return; - self.items[self.item_count] = .{ .action = .{ - .label = label, - .shortcut_display = "", - .action = action, - .enabled = false, - } }; - self.item_count += 1; - } - - /// Add a separator. - pub fn addSeparator(self: *Self) void { - if (self.item_count >= max_items) return; - self.items[self.item_count] = .{ .separator = {} }; - self.item_count += 1; - } - - /// Show the menu at a position. - pub fn show(self: *Self, pos_x: usize, pos_y: usize) void { - self.visible = true; - self.cursor = 0; - self.selected_action = null; - self.x = pos_x; - self.y = pos_y; - self.skipToNextEnabled(); - } - - /// Show clamped to terminal bounds. - pub fn showClamped(self: *Self, pos_x: usize, pos_y: usize, term_width: usize, term_height: usize) void { - const menu_width = self.calcWidth() + 4; // borders + padding - const menu_height = self.item_count + 2; // borders - - const clamped_x = if (pos_x + menu_width > term_width) - term_width -| menu_width - else - pos_x; - - const clamped_y = if (pos_y + menu_height > term_height) - term_height -| menu_height - else - pos_y; - - self.show(clamped_x, clamped_y); - } - - /// Hide the menu. - pub fn hide(self: *Self) void { - self.visible = false; - } - - pub fn isVisible(self: *const Self) bool { - return self.visible; - } - - /// Get and consume the selected action. - pub fn getSelectedAction(self: *Self) ?Action { - const act = self.selected_action; - self.selected_action = null; - return act; - } - - /// Handle key events. Returns true if consumed. - pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { - if (!self.visible) return false; - - switch (key.key) { - .up => { - self.moveCursorUp(); - return true; - }, - .down => { - self.moveCursorDown(); - return true; - }, - .enter => { - self.selectCurrent(); - return true; - }, - .escape => { - self.hide(); - return true; - }, - .char => |c| { - switch (c) { - 'k' => { - self.moveCursorUp(); - return true; - }, - 'j' => { - self.moveCursorDown(); - return true; - }, - else => return false, - } - }, - else => return false, - } - } - - fn moveCursorUp(self: *Self) void { - if (self.item_count == 0) return; - var pos = self.cursor; - var attempts: usize = 0; - while (attempts < self.item_count) : (attempts += 1) { - if (pos == 0) { - pos = self.item_count - 1; - } else { - pos -= 1; - } - if (self.isSelectable(self.items[pos])) { - self.cursor = pos; - return; - } - } - } - - fn moveCursorDown(self: *Self) void { - if (self.item_count == 0) return; - var pos = self.cursor; - var attempts: usize = 0; - while (attempts < self.item_count) : (attempts += 1) { - pos = if (pos + 1 < self.item_count) pos + 1 else 0; - if (self.isSelectable(self.items[pos])) { - self.cursor = pos; - return; - } - } - } - - fn skipToNextEnabled(self: *Self) void { - if (self.item_count == 0) return; - if (self.isSelectable(self.items[self.cursor])) return; - self.moveCursorDown(); - } - - fn isSelectable(_: *const Self, maybe_item: ?MenuItem) bool { - const item = maybe_item orelse return false; - return switch (item) { - .action => |a| a.enabled, - .separator => false, - }; - } - - fn selectCurrent(self: *Self) void { - if (self.cursor >= self.item_count) return; - const item = self.items[self.cursor] orelse return; - switch (item) { - .action => |a| { - if (a.enabled) { - self.selected_action = a.action; - self.hide(); - } - }, - .separator => {}, - } - } - - fn calcWidth(self: *const Self) usize { - var max_label: usize = 0; - var max_shortcut: usize = 0; - for (self.items[0..self.item_count]) |maybe_item| { - const item = maybe_item orelse continue; - switch (item) { - .action => |a| { - const lw = measure.width(a.label); - if (lw > max_label) max_label = lw; - const sw = measure.width(a.shortcut_display); - if (sw > max_shortcut) max_shortcut = sw; - }, - .separator => {}, - } - } - return max_label + max_shortcut + 4; - } - - /// Render the context menu. - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - if (!self.visible) return try allocator.dupe(u8, ""); - - var result: Writer.Allocating = .init(allocator); - const w = &result.writer; - - const inner_width = self.calcWidth(); - - // Indent to x position - // Top border - try self.writeIndent(w, self.x); - try self.writeBorder(w, allocator, inner_width, .top); - try w.writeByte('\n'); - - // Items - for (self.items[0..self.item_count], 0..) |maybe_item, i| { - const item = maybe_item orelse continue; - - try self.writeIndent(w, self.x); - - switch (item) { - .separator => { - try self.writeBorder(w, allocator, inner_width, .middle); - }, - .action => |a| { - try self.writeBorderChar(w, allocator, .left); - - const is_active = (i == self.cursor); - const s = if (!a.enabled) self.disabled_style else if (is_active) self.active_style else self.item_style; - - var line: Writer.Allocating = .init(allocator); - const lw = &line.writer; - try lw.writeByte(' '); - try lw.writeAll(a.label); - - const label_w = measure.width(a.label); - const shortcut_w = measure.width(a.shortcut_display); - const gap = inner_width -| label_w -| shortcut_w -| 2; - for (0..gap) |_| try lw.writeByte(' '); - - if (a.shortcut_display.len > 0) { - try lw.writeAll(a.shortcut_display); - } - try lw.writeByte(' '); - - const line_text = try line.toOwnedSlice(); - const styled = try s.render(allocator, line_text); - try w.writeAll(styled); - - try self.writeBorderChar(w, allocator, .right); - }, - } - try w.writeByte('\n'); - } - - // Bottom border - try self.writeIndent(w, self.x); - try self.writeBorder(w, allocator, inner_width, .bottom); - - return result.toOwnedSlice(); - } - - const BorderPos = enum { top, middle, bottom }; - const BorderSide = enum { left, right }; - - fn writeIndent(_: *const Self, writer: *Writer, count: usize) !void { - for (0..count) |_| try writer.writeByte(' '); - } - - fn writeBorder(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { - var bs = style_mod.Style{}; - bs = bs.fg(self.border_fg); - bs = bs.inline_style(true); - - const bc = self.border_chars; - const cl = switch (pos) { - .top => bc.top_left, - .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, - .bottom => bc.bottom_left, - }; - const cr = switch (pos) { - .top => bc.top_right, - .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, - .bottom => bc.bottom_right, - }; - - try writer.writeAll(try bs.render(allocator, cl)); - for (0..width) |_| { - try writer.writeAll(try bs.render(allocator, bc.horizontal)); - } - try writer.writeAll(try bs.render(allocator, cr)); - } - - fn writeBorderChar(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { - var bs = style_mod.Style{}; - bs = bs.fg(self.border_fg); - bs = bs.inline_style(true); - const char = switch (side) { - .left, .right => self.border_chars.vertical, - }; - try writer.writeAll(try bs.render(allocator, char)); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig deleted file mode 100644 index 374416c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/data_table.zig +++ /dev/null @@ -1,530 +0,0 @@ -//! DataTable — table with cell-level cursor, frozen columns, and horizontal -//! scroll. -//! -//! Distinct from the existing `Table` (compile-time column count, row-only -//! cursor) and `SortableTable` (sorting and styling). DataTable targets the -//! "spreadsheet view" use case: many columns, navigable cell-by-cell, -//! leftmost columns pinned so they stay visible while the rest of the grid -//! scrolls horizontally. -//! -//! The column count is runtime, so it's a good fit for dynamic schemas -//! (database results, log fields, CSV files). - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const border_mod = @import("../style/border.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); - -pub const Align = enum { left, center, right }; - -pub const Column = struct { - header: []const u8, - /// Fixed display width in cells. Required (we don't auto-fit since the - /// row store may be huge or lazy-loaded). - width: u16, - @"align": Align = .left, -}; - -pub const DataTable = struct { - allocator: std.mem.Allocator, - - columns: std.array_list.Managed(Column), - /// Row store: each row is a slice of cell strings, length must match - /// columns.len. The DataTable does not own these strings; the caller - /// guarantees they live as long as the table is rendered. - rows: std.array_list.Managed([]const []const u8), - - cursor_row: usize, - cursor_col: usize, - /// Leftmost N columns never scroll out of view. - frozen_columns: usize, - - /// Display config. - width: u16, - height: u16, - show_header: bool, - show_borders: bool, - /// Horizontal scroll offset in *columns* (not cells), excluding frozen. - col_x_offset: usize, - /// Vertical scroll offset in rows. - y_offset: usize, - - /// Styling. - header_style: style_mod.Style, - cell_style: style_mod.Style, - cursor_cell_style: style_mod.Style, - cursor_row_style: style_mod.Style, - frozen_separator_style: style_mod.Style, - border_chars: border_mod.BorderChars, - - pub fn init(allocator: std.mem.Allocator) DataTable { - var header_s = style_mod.Style{}; - header_s = header_s.bold(true); - header_s = header_s.inline_style(true); - - var cell_s = style_mod.Style{}; - cell_s = cell_s.inline_style(true); - - var cursor_cell = style_mod.Style{}; - cursor_cell = cursor_cell.bg(.cyan); - cursor_cell = cursor_cell.fg(.black); - cursor_cell = cursor_cell.inline_style(true); - - var cursor_row = style_mod.Style{}; - cursor_row = cursor_row.bg(.gray(4)); - cursor_row = cursor_row.inline_style(true); - - var frozen_sep = style_mod.Style{}; - frozen_sep = frozen_sep.fg(.gray(8)); - frozen_sep = frozen_sep.inline_style(true); - - return .{ - .allocator = allocator, - .columns = std.array_list.Managed(Column).init(allocator), - .rows = std.array_list.Managed([]const []const u8).init(allocator), - .cursor_row = 0, - .cursor_col = 0, - .frozen_columns = 0, - .width = 80, - .height = 12, - .show_header = true, - .show_borders = false, - .col_x_offset = 0, - .y_offset = 0, - .header_style = header_s, - .cell_style = cell_s, - .cursor_cell_style = cursor_cell, - .cursor_row_style = cursor_row, - .frozen_separator_style = frozen_sep, - .border_chars = .normal, - }; - } - - pub fn deinit(self: *DataTable) void { - self.columns.deinit(); - self.rows.deinit(); - } - - pub fn setColumns(self: *DataTable, cols: []const Column) !void { - self.columns.clearRetainingCapacity(); - try self.columns.appendSlice(cols); - if (self.cursor_col >= self.columns.items.len) { - self.cursor_col = self.columns.items.len -| 1; - } - if (self.frozen_columns > self.columns.items.len) { - self.frozen_columns = self.columns.items.len; - } - } - - pub fn addRow(self: *DataTable, cells: []const []const u8) !void { - if (cells.len != self.columns.items.len) return error.ColumnCountMismatch; - try self.rows.append(cells); - } - - pub fn setRows(self: *DataTable, rows: []const []const []const u8) !void { - for (rows) |r| { - if (r.len != self.columns.items.len) return error.ColumnCountMismatch; - } - self.rows.clearRetainingCapacity(); - try self.rows.appendSlice(rows); - if (self.cursor_row >= self.rows.items.len) { - self.cursor_row = self.rows.items.len -| 1; - } - } - - pub fn setSize(self: *DataTable, w: u16, h: u16) void { - self.width = w; - self.height = h; - } - - pub fn setFrozenColumns(self: *DataTable, n: usize) void { - self.frozen_columns = @min(n, self.columns.items.len); - if (self.cursor_col < self.frozen_columns) { - // Frozen cells are still cursorable. - } - self.col_x_offset = 0; - } - - pub fn moveLeft(self: *DataTable) void { - if (self.cursor_col > 0) self.cursor_col -= 1; - self.ensureCursorVisible(); - } - - pub fn moveRight(self: *DataTable) void { - if (self.cursor_col + 1 < self.columns.items.len) self.cursor_col += 1; - self.ensureCursorVisible(); - } - - pub fn moveUp(self: *DataTable) void { - if (self.cursor_row > 0) self.cursor_row -= 1; - self.ensureCursorRowVisible(); - } - - pub fn moveDown(self: *DataTable) void { - if (self.cursor_row + 1 < self.rows.items.len) self.cursor_row += 1; - self.ensureCursorRowVisible(); - } - - pub fn pageUp(self: *DataTable) void { - const visible = self.dataRowsAvailable(); - self.cursor_row -|= visible; - self.ensureCursorRowVisible(); - } - - pub fn pageDown(self: *DataTable) void { - const visible = self.dataRowsAvailable(); - self.cursor_row = @min(self.cursor_row + visible, self.rows.items.len -| 1); - self.ensureCursorRowVisible(); - } - - pub fn gotoFirstRow(self: *DataTable) void { - self.cursor_row = 0; - self.y_offset = 0; - } - - pub fn gotoLastRow(self: *DataTable) void { - self.cursor_row = self.rows.items.len -| 1; - self.ensureCursorRowVisible(); - } - - pub fn gotoFirstColumn(self: *DataTable) void { - self.cursor_col = 0; - self.col_x_offset = 0; - } - - pub fn gotoLastColumn(self: *DataTable) void { - self.cursor_col = self.columns.items.len -| 1; - self.ensureCursorVisible(); - } - - pub fn handleKey(self: *DataTable, key: keys.KeyEvent) void { - switch (key.key) { - .left => self.moveLeft(), - .right => self.moveRight(), - .up => self.moveUp(), - .down => self.moveDown(), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoFirstColumn(), - .end => self.gotoLastColumn(), - .char => |c| switch (c) { - 'h' => self.moveLeft(), - 'l' => self.moveRight(), - 'k' => self.moveUp(), - 'j' => self.moveDown(), - 'g' => self.gotoFirstRow(), - 'G' => self.gotoLastRow(), - else => {}, - }, - else => {}, - } - } - - /// Number of data rows that fit in the viewport (excluding header). - fn dataRowsAvailable(self: *const DataTable) usize { - const header_lines: usize = if (self.show_header) 2 else 0; // header + separator - return @as(usize, self.height) -| header_lines; - } - - fn ensureCursorRowVisible(self: *DataTable) void { - const avail = self.dataRowsAvailable(); - if (avail == 0) return; - if (self.cursor_row < self.y_offset) { - self.y_offset = self.cursor_row; - } else if (self.cursor_row >= self.y_offset + avail) { - self.y_offset = self.cursor_row - avail + 1; - } - } - - fn ensureCursorVisible(self: *DataTable) void { - // Frozen cursors don't scroll. - if (self.cursor_col < self.frozen_columns) { - self.col_x_offset = 0; - return; - } - - // Compute non-frozen visible width. - const frozen_w = self.frozenWidth(); - const avail: usize = @as(usize, self.width) -| frozen_w; - - // Walk from col_x_offset to find which non-frozen columns fit. - const total_non_frozen = self.columns.items.len - self.frozen_columns; - const cursor_idx = self.cursor_col - self.frozen_columns; - - // First, scroll right if cursor is past visible. - var off = self.col_x_offset; - while (off < total_non_frozen) { - var used: usize = 0; - var i = off; - var found = false; - while (i < total_non_frozen) : (i += 1) { - const col_w = self.columns.items[self.frozen_columns + i].width; - if (used + col_w > avail) break; - used += col_w + 1; // 1 for column gap - if (i == cursor_idx) { - found = true; - break; - } - } - if (cursor_idx >= off and found) break; - if (cursor_idx < off) { - off = cursor_idx; - break; - } - off += 1; - } - self.col_x_offset = off; - } - - fn frozenWidth(self: *const DataTable) usize { - var sum: usize = 0; - for (self.columns.items[0..self.frozen_columns], 0..) |c, i| { - sum += c.width; - if (i + 1 < self.frozen_columns) sum += 1; - } - if (self.frozen_columns > 0 and self.frozen_columns < self.columns.items.len) { - sum += 2; // separator " │ " - } - return sum; - } - - pub fn view(self: *DataTable, allocator: std.mem.Allocator) ![]const u8 { - var out: Writer.Allocating = .init(allocator); - const w = &out.writer; - - const visible_cols = try self.computeVisibleColumns(allocator); - defer allocator.free(visible_cols); - - if (self.show_header) { - try self.renderRow(allocator, w, null, visible_cols, true); - try w.writeByte('\n'); - try self.renderHeaderSeparator(allocator, w, visible_cols); - try w.writeByte('\n'); - } - - const avail = self.dataRowsAvailable(); - const start = self.y_offset; - const end = @min(start + avail, self.rows.items.len); - var first = true; - for (start..end) |row_idx| { - if (!first) try w.writeByte('\n'); - first = false; - try self.renderRow(allocator, w, row_idx, visible_cols, false); - } - - return out.toOwnedSlice(); - } - - /// Indices of columns to render: all frozen + a slice of non-frozen - /// starting at col_x_offset that fits in the remaining width. - fn computeVisibleColumns(self: *const DataTable, allocator: std.mem.Allocator) ![]usize { - var list = std.array_list.Managed(usize).init(allocator); - errdefer list.deinit(); - - var i: usize = 0; - while (i < self.frozen_columns) : (i += 1) try list.append(i); - - const frozen_w = self.frozenWidth(); - const avail: usize = @as(usize, self.width) -| frozen_w; - var used: usize = 0; - i = self.frozen_columns + self.col_x_offset; - while (i < self.columns.items.len) : (i += 1) { - const c = self.columns.items[i]; - const need = c.width + (if (used > 0) @as(usize, 1) else 0); - if (used + need > avail) break; - used += need; - try list.append(i); - } - return list.toOwnedSlice(); - } - - fn renderRow(self: *const DataTable, allocator: std.mem.Allocator, writer: *Writer, row_idx: ?usize, visible_cols: []const usize, is_header: bool) !void { - for (visible_cols, 0..) |col_idx, i| { - // Frozen separator. - if (self.frozen_columns > 0 and i == self.frozen_columns) { - const sep = try self.frozen_separator_style.render(allocator, " │ "); - defer allocator.free(sep); - try writer.writeAll(sep); - } else if (i > 0) { - try writer.writeByte(' '); - } - - const col = self.columns.items[col_idx]; - const cell_text: []const u8 = if (is_header) - col.header - else - self.rows.items[row_idx.?][col_idx]; - - const formatted = try formatCell(allocator, cell_text, col.width, col.@"align"); - defer allocator.free(formatted); - - const is_cursor_cell = !is_header and row_idx.? == self.cursor_row and col_idx == self.cursor_col; - const is_cursor_row = !is_header and row_idx.? == self.cursor_row; - - const s = if (is_header) - self.header_style - else if (is_cursor_cell) - self.cursor_cell_style - else if (is_cursor_row) - self.cursor_row_style - else - self.cell_style; - - const styled = try s.render(allocator, formatted); - defer allocator.free(styled); - try writer.writeAll(styled); - } - } - - fn renderHeaderSeparator(self: *const DataTable, allocator: std.mem.Allocator, writer: *Writer, visible_cols: []const usize) !void { - for (visible_cols, 0..) |col_idx, i| { - if (self.frozen_columns > 0 and i == self.frozen_columns) { - const sep = try self.frozen_separator_style.render(allocator, "─┼─"); - defer allocator.free(sep); - try writer.writeAll(sep); - } else if (i > 0) { - try writer.writeAll("─"); - } - const col = self.columns.items[col_idx]; - const dashes = try allocator.alloc(u8, col.width * 3); // up to 3 bytes per UTF-8 dash - defer allocator.free(dashes); - const dash = "─"; - var written: usize = 0; - var k: usize = 0; - while (k < col.width) : (k += 1) { - @memcpy(dashes[written .. written + dash.len], dash); - written += dash.len; - } - const styled = try self.frozen_separator_style.render(allocator, dashes[0..written]); - defer allocator.free(styled); - try writer.writeAll(styled); - } - } -}; - -fn formatCell(allocator: std.mem.Allocator, text: []const u8, width: u16, align_: Align) ![]u8 { - const w = measure.width(text); - if (w == width) return allocator.dupe(u8, text); - if (w > width) { - const truncated = try measure.truncate(allocator, text, width); - // Always cast away const since we ultimately return `[]u8`. - return @constCast(truncated); - } - const padding = width - w; - return switch (align_) { - .left => @constCast(try measure.padRight(allocator, text, width)), - .right => @constCast(try measure.padLeft(allocator, text, width)), - .center => blk: { - const left = padding / 2; - const right = padding - left; - const out = try allocator.alloc(u8, left + text.len + right); - @memset(out[0..left], ' '); - @memcpy(out[left .. left + text.len], text); - @memset(out[left + text.len ..], ' '); - break :blk out; - }, - }; -} - -// `measure.padRight` and `padLeft` return `[]const u8`; cast for callers -// expecting `[]u8`. -fn padOwned(allocator: std.mem.Allocator, text: []const u8, w: usize, left: bool) ![]u8 { - const r = if (left) try measure.padLeft(allocator, text, w) else try measure.padRight(allocator, text, w); - return @constCast(r); -} - -// ── Tests ────────────────────────────────────────────────────────────── - -const testing = std.testing; - -test "moveRight clamps at last column" { - var t = DataTable.init(testing.allocator); - defer t.deinit(); - try t.setColumns(&.{ - .{ .header = "A", .width = 4 }, - .{ .header = "B", .width = 4 }, - }); - try t.addRow(&.{ "1", "2" }); - t.moveRight(); - try testing.expectEqual(@as(usize, 1), t.cursor_col); - t.moveRight(); - try testing.expectEqual(@as(usize, 1), t.cursor_col); -} - -test "moveDown advances cursor row" { - var t = DataTable.init(testing.allocator); - defer t.deinit(); - try t.setColumns(&.{.{ .header = "A", .width = 4 }}); - try t.addRow(&.{"1"}); - try t.addRow(&.{"2"}); - t.moveDown(); - try testing.expectEqual(@as(usize, 1), t.cursor_row); -} - -test "frozen columns stay at zero offset" { - var t = DataTable.init(testing.allocator); - defer t.deinit(); - try t.setColumns(&.{ - .{ .header = "id", .width = 4 }, - .{ .header = "name", .width = 6 }, - .{ .header = "x", .width = 4 }, - .{ .header = "y", .width = 4 }, - .{ .header = "z", .width = 4 }, - }); - try t.addRow(&.{ "1", "alice", "10", "20", "30" }); - t.setSize(20, 5); - t.setFrozenColumns(1); - t.cursor_col = 4; - t.moveLeft(); - t.moveLeft(); - t.moveLeft(); - t.moveLeft(); // back to col 0 (frozen) - try testing.expectEqual(@as(usize, 0), t.cursor_col); - try testing.expectEqual(@as(usize, 0), t.col_x_offset); -} - -test "view contains headers and data" { - const allocator = testing.allocator; - var t = DataTable.init(allocator); - defer t.deinit(); - try t.setColumns(&.{ - .{ .header = "id", .width = 4 }, - .{ .header = "name", .width = 6 }, - }); - try t.addRow(&.{ "42", "alice" }); - - const out = try t.view(allocator); - defer allocator.free(out); - try testing.expect(std.mem.indexOf(u8, out, "id") != null); - try testing.expect(std.mem.indexOf(u8, out, "alice") != null); - try testing.expect(std.mem.indexOf(u8, out, "42") != null); -} - -test "view renders frozen separator when columns are frozen" { - const allocator = testing.allocator; - var t = DataTable.init(allocator); - defer t.deinit(); - try t.setColumns(&.{ - .{ .header = "id", .width = 4 }, - .{ .header = "name", .width = 6 }, - .{ .header = "value", .width = 6 }, - }); - try t.addRow(&.{ "1", "alice", "10" }); - t.setFrozenColumns(1); - const out = try t.view(allocator); - defer allocator.free(out); - try testing.expect(std.mem.indexOf(u8, out, "│") != null); -} - -test "addRow rejects mismatched column count" { - var t = DataTable.init(testing.allocator); - defer t.deinit(); - try t.setColumns(&.{ - .{ .header = "A", .width = 4 }, - .{ .header = "B", .width = 4 }, - }); - try testing.expectError(error.ColumnCountMismatch, t.addRow(&.{"only one"})); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig deleted file mode 100644 index 2802284..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/diff_view.zig +++ /dev/null @@ -1,285 +0,0 @@ -//! Diff viewer component. -//! Displays unified or side-by-side text diffs with syntax coloring. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const DiffView = struct { - old_text: []const u8 = "", - new_text: []const u8 = "", - old_label: []const u8 = "old", - new_label: []const u8 = "new", - mode: Mode = .unified, - show_line_numbers: bool = true, - context_lines: usize = 3, - /// Width of each side in side-by-side mode. - side_width: usize = 38, - /// Separator character for side-by-side mode. - separator: []const u8 = "\xe2\x94\x82", - /// Add prefix symbol. - add_prefix: []const u8 = "+", - /// Remove prefix symbol. - remove_prefix: []const u8 = "-", - /// Context prefix symbol. - context_prefix: []const u8 = " ", - - // Styles - add_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - remove_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - context_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - header_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - line_num_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - separator_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(6)); - s = s.inline_style(true); - break :blk s; - }, - - pub const Mode = enum { - unified, - side_by_side, - }; - - pub fn view(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { - return switch (self.mode) { - .unified => self.renderUnified(allocator), - .side_by_side => self.renderSideBySide(allocator), - }; - } - - fn renderUnified(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Header - const hdr = std.fmt.allocPrint(allocator, "--- {s}\n+++ {s}", .{ self.old_label, self.new_label }) catch ""; - writer.writeAll(self.header_style.render(allocator, hdr) catch hdr) catch {}; - writer.writeByte('\n') catch {}; - - // Compute diff using LCS-based approach - const old_lines = splitLines(allocator, self.old_text); - const new_lines = splitLines(allocator, self.new_text); - const ops = computeDiff(allocator, old_lines, new_lines); - - var old_num: usize = 1; - var new_num: usize = 1; - - for (ops) |op| { - switch (op) { - .equal => |line| { - if (self.show_line_numbers) { - const nums = std.fmt.allocPrint(allocator, "{d:>4} {d:>4} ", .{ old_num, new_num }) catch ""; - writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; - } - writer.writeAll(self.context_style.render(allocator, " ") catch " ") catch {}; - writer.writeAll(self.context_style.render(allocator, line) catch line) catch {}; - writer.writeByte('\n') catch {}; - old_num += 1; - new_num += 1; - }, - .delete => |line| { - if (self.show_line_numbers) { - const nums = std.fmt.allocPrint(allocator, "{d:>4} ", .{old_num}) catch ""; - writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; - } - const prefixed = std.fmt.allocPrint(allocator, "-{s}", .{line}) catch line; - writer.writeAll(self.remove_style.render(allocator, prefixed) catch prefixed) catch {}; - writer.writeByte('\n') catch {}; - old_num += 1; - }, - .insert => |line| { - if (self.show_line_numbers) { - const nums = std.fmt.allocPrint(allocator, " {d:>4} ", .{new_num}) catch ""; - writer.writeAll(self.line_num_style.render(allocator, nums) catch nums) catch {}; - } - const prefixed = std.fmt.allocPrint(allocator, "+{s}", .{line}) catch line; - writer.writeAll(self.add_style.render(allocator, prefixed) catch prefixed) catch {}; - writer.writeByte('\n') catch {}; - new_num += 1; - }, - } - } - - // Trim trailing newline - var array = result.toArrayList(); - if (array.items.len > 0 and array.items[array.items.len - 1] == '\n') { - _ = array.pop(); - } - - return array.items; - } - - fn renderSideBySide(self: *const DiffView, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const old_lines = splitLines(allocator, self.old_text); - const new_lines = splitLines(allocator, self.new_text); - const ops = computeDiff(allocator, old_lines, new_lines); - - const half_width: usize = self.side_width; - - // Header - const old_hdr = padRight(allocator, self.old_label, half_width); - const new_hdr = self.new_label; - writer.writeAll(self.header_style.render(allocator, old_hdr) catch old_hdr) catch {}; - writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; - writer.writeAll(self.header_style.render(allocator, new_hdr) catch new_hdr) catch {}; - writer.writeByte('\n') catch {}; - - // Separator line - for (0..half_width) |_| writer.writeAll("\xe2\x94\x80") catch {}; - writer.writeAll("\xe2\x94\xbc") catch {}; - for (0..half_width + 2) |_| writer.writeAll("\xe2\x94\x80") catch {}; - writer.writeByte('\n') catch {}; - - for (ops) |op| { - switch (op) { - .equal => |line| { - const padded = padRight(allocator, line, half_width); - writer.writeAll(self.context_style.render(allocator, padded) catch padded) catch {}; - writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; - writer.writeAll(self.context_style.render(allocator, line) catch line) catch {}; - writer.writeByte('\n') catch {}; - }, - .delete => |line| { - const padded = padRight(allocator, line, half_width); - writer.writeAll(self.remove_style.render(allocator, padded) catch padded) catch {}; - writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; - writer.writeByte('\n') catch {}; - }, - .insert => |line| { - const blank = padRight(allocator, "", half_width); - writer.writeAll(blank) catch {}; - writer.writeAll(self.separator_style.render(allocator, " \xe2\x94\x82 ") catch " | ") catch {}; - writer.writeAll(self.add_style.render(allocator, line) catch line) catch {}; - writer.writeByte('\n') catch {}; - }, - } - } - - var array = result.toArrayList(); - if (array.items.len > 0 and array.items[array.items.len - 1] == '\n') { - _ = array.pop(); - } - - return array.items; - } - - fn padRight(allocator: std.mem.Allocator, text: []const u8, target: usize) []const u8 { - if (text.len >= target) return text[0..target]; - var buf = std.array_list.Managed(u8).init(allocator); - buf.appendSlice(text) catch {}; - for (0..target - text.len) |_| buf.append(' ') catch {}; - return buf.items; - } - - fn splitLines(allocator: std.mem.Allocator, text: []const u8) []const []const u8 { - var lines = std.array_list.Managed([]const u8).init(allocator); - var iter = std.mem.splitScalar(u8, text, '\n'); - while (iter.next()) |line| { - lines.append(line) catch {}; - } - return lines.items; - } -}; - -/// Diff operation. -const DiffOp = union(enum) { - equal: []const u8, - delete: []const u8, - insert: []const u8, -}; - -/// Simple Myers-like diff: compute edit operations between old and new line arrays. -fn computeDiff(allocator: std.mem.Allocator, old: []const []const u8, new: []const []const u8) []const DiffOp { - var ops = std.array_list.Managed(DiffOp).init(allocator); - - // Simple O(n*m) LCS-based diff - const m = old.len; - const n = new.len; - - if (m == 0) { - for (new) |line| ops.append(.{ .insert = line }) catch {}; - return ops.items; - } - if (n == 0) { - for (old) |line| ops.append(.{ .delete = line }) catch {}; - return ops.items; - } - - // Build LCS table - const table = allocator.alloc(usize, (m + 1) * (n + 1)) catch { - // Fallback: show all as delete + insert - for (old) |line| ops.append(.{ .delete = line }) catch {}; - for (new) |line| ops.append(.{ .insert = line }) catch {}; - return ops.items; - }; - for (0..m + 1) |i| { - for (0..n + 1) |j| { - if (i == 0 or j == 0) { - table[i * (n + 1) + j] = 0; - } else if (std.mem.eql(u8, old[i - 1], new[j - 1])) { - table[i * (n + 1) + j] = table[(i - 1) * (n + 1) + (j - 1)] + 1; - } else { - table[i * (n + 1) + j] = @max(table[(i - 1) * (n + 1) + j], table[i * (n + 1) + (j - 1)]); - } - } - } - - // Backtrack to produce ops - var rev_ops = std.array_list.Managed(DiffOp).init(allocator); - var i: usize = m; - var j: usize = n; - while (i > 0 or j > 0) { - if (i > 0 and j > 0 and std.mem.eql(u8, old[i - 1], new[j - 1])) { - rev_ops.append(.{ .equal = old[i - 1] }) catch {}; - i -= 1; - j -= 1; - } else if (j > 0 and (i == 0 or table[i * (n + 1) + (j - 1)] >= table[(i - 1) * (n + 1) + j])) { - rev_ops.append(.{ .insert = new[j - 1] }) catch {}; - j -= 1; - } else if (i > 0) { - rev_ops.append(.{ .delete = old[i - 1] }) catch {}; - i -= 1; - } - } - - // Reverse - var idx: usize = rev_ops.items.len; - while (idx > 0) { - idx -= 1; - ops.append(rev_ops.items[idx]) catch {}; - } - - return ops.items; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig deleted file mode 100644 index be6099f..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/dropdown.zig +++ /dev/null @@ -1,719 +0,0 @@ -//! Dropdown/Select component. -//! Collapsible list for selecting one or more options. - -const std = @import("std"); -const keys = @import("../input/keys.zig"); -const Writer = std.Io.Writer; -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 { - allocator: std.mem.Allocator, - - // Items - items: std.array_list.Managed(Item), - filtered_indices: std.array_list.Managed(usize), - - // State - expanded: bool, - cursor: usize, - selected_index: ?usize, - selected_indices: std.AutoHashMap(usize, void), - - // Filtering - filter_text: std.array_list.Managed(u8), - filter_active: bool, - - // Scrolling - y_offset: usize, - max_visible: u16, - - // Focus - focused: bool, - - // Behavior - multi_select: bool, - close_on_select: bool, - wrap_around: bool, - - // Labels - label: []const u8, - placeholder: []const u8, - - // Symbols - expand_symbol: []const u8, - cursor_symbol: []const u8, - checked_symbol: []const u8, - unchecked_symbol: []const u8, - scroll_up_symbol: []const u8, - scroll_down_symbol: []const u8, - - // Styling - label_style: style_mod.Style, - trigger_style: style_mod.Style, - trigger_focused_style: style_mod.Style, - item_style: style_mod.Style, - cursor_item_style: style_mod.Style, - selected_item_style: style_mod.Style, - disabled_style: style_mod.Style, - filter_style: style_mod.Style, - border_chars: border_mod.BorderChars, - border_fg: Color, - - const Self = @This(); - - pub const Item = struct { - value: T, - label: []const u8, - description: []const u8, - enabled: bool, - - pub fn init(value: T, label_text: []const u8) Item { - return .{ - .value = value, - .label = label_text, - .description = "", - .enabled = true, - }; - } - - pub fn withDescription(value: T, label_text: []const u8, desc: []const u8) Item { - return .{ - .value = value, - .label = label_text, - .description = desc, - .enabled = true, - }; - } - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .items = std.array_list.Managed(Item).init(allocator), - .filtered_indices = std.array_list.Managed(usize).init(allocator), - .expanded = false, - .cursor = 0, - .selected_index = null, - .selected_indices = std.AutoHashMap(usize, void).init(allocator), - .filter_text = std.array_list.Managed(u8).init(allocator), - .filter_active = false, - .y_offset = 0, - .max_visible = 6, - .focused = true, - .multi_select = false, - .close_on_select = true, - .wrap_around = false, - .label = "", - .placeholder = "Select...", - .expand_symbol = "▼", - .cursor_symbol = "> ", - .checked_symbol = "[x] ", - .unchecked_symbol = "[ ] ", - .scroll_up_symbol = "▲", - .scroll_down_symbol = "▼", - .label_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .trigger_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - .trigger_focused_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .item_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .cursor_item_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .selected_item_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - .disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - .filter_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .border_chars = .rounded, - .border_fg = .gray(14), - }; - } - - pub fn deinit(self: *Self) void { - self.items.deinit(); - self.filtered_indices.deinit(); - self.selected_indices.deinit(); - self.filter_text.deinit(); - } - - // ── Item management ───────────────────────────── - - pub fn addItem(self: *Self, item: Item) !void { - try self.items.append(item); - try self.rebuildFilter(); - } - - pub fn addItems(self: *Self, new_items: []const Item) !void { - try self.items.appendSlice(new_items); - try self.rebuildFilter(); - } - - pub fn setItems(self: *Self, new_items: []const Item) !void { - self.items.clearRetainingCapacity(); - try self.items.appendSlice(new_items); - self.cursor = 0; - self.y_offset = 0; - self.selected_index = null; - self.selected_indices.clearRetainingCapacity(); - try self.rebuildFilter(); - } - - // ── State ─────────────────────────────────────── - - pub fn open(self: *Self) void { - self.expanded = true; - self.filter_active = false; - self.filter_text.clearRetainingCapacity(); - self.rebuildFilter() catch {}; - // Position cursor at selected item if any - if (self.selected_index) |sel| { - for (self.filtered_indices.items, 0..) |idx, i| { - if (idx == sel) { - self.cursor = i; - self.ensureVisible(); - break; - } - } - } - } - - pub fn close(self: *Self) void { - self.expanded = false; - self.filter_active = false; - self.filter_text.clearRetainingCapacity(); - } - - pub fn toggle(self: *Self) void { - if (self.expanded) self.close() else self.open(); - } - - pub fn isExpanded(self: *const Self) bool { - return self.expanded; - } - - // ── Selection ─────────────────────────────────── - - pub fn selectedItem(self: *const Self) ?*const Item { - if (self.selected_index) |idx| { - if (idx < self.items.items.len) { - return &self.items.items[idx]; - } - } - return null; - } - - pub fn selectedValue(self: *const Self) ?T { - if (self.selectedItem()) |item| { - return item.value; - } - return null; - } - - pub fn selectedItems(self: *const Self, allocator: std.mem.Allocator) ![]const *const Item { - var result = std.array_list.Managed(*const Item).init(allocator); - var iter = self.selected_indices.keyIterator(); - while (iter.next()) |idx| { - if (idx.* < self.items.items.len) { - try result.append(&self.items.items[idx.*]); - } - } - return result.toOwnedSlice(); - } - - fn selectAtCursor(self: *Self) void { - const visible = self.filtered_indices.items; - if (self.cursor >= visible.len) return; - const idx = visible[self.cursor]; - if (!self.items.items[idx].enabled) return; - - if (self.multi_select) { - if (self.selected_indices.contains(idx)) { - _ = self.selected_indices.remove(idx); - } else { - self.selected_indices.put(idx, {}) catch {}; - } - } else { - self.selected_index = idx; - if (self.close_on_select) { - self.close(); - } - } - } - - // ── Focus protocol ────────────────────────────── - - pub fn focus(self: *Self) void { - self.focused = true; - } - - pub fn blur(self: *Self) void { - self.focused = false; - } - - // ── Input handling ────────────────────────────── - - pub fn handleKey(self: *Self, key: keys.KeyEvent) void { - if (!self.focused) return; - - // When filter is active, capture typed characters - if (self.expanded and self.filter_active and key.key == .char and !key.modifiers.ctrl) { - const c = key.key.char; - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch return; - self.filter_text.appendSlice(buf[0..len]) catch {}; - self.rebuildFilter() catch {}; - return; - } - - if (self.expanded and self.filter_active and key.key == .backspace) { - if (self.filter_text.items.len > 0) { - _ = self.filter_text.pop(); - self.rebuildFilter() catch {}; - } - return; - } - - if (!self.expanded) { - // Collapsed state - switch (key.key) { - .enter, .space => self.open(), - .down => self.open(), - else => {}, - } - return; - } - - // Expanded state - switch (key.key) { - .up => self.cursorUp(), - .down => self.cursorDown(), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoFirst(), - .end => self.gotoLast(), - .enter => self.selectAtCursor(), - .space => if (self.multi_select) self.selectAtCursor(), - .escape => { - if (self.filter_active) { - self.filter_active = false; - self.filter_text.clearRetainingCapacity(); - self.rebuildFilter() catch {}; - } else { - self.close(); - } - }, - .char => |c| switch (c) { - 'j' => self.cursorDown(), - 'k' => self.cursorUp(), - 'g' => self.gotoFirst(), - 'G' => self.gotoLast(), - '/' => { - self.filter_active = true; - self.filter_text.clearRetainingCapacity(); - }, - 'q' => self.close(), - else => {}, - }, - else => {}, - } - } - - // ── Navigation ────────────────────────────────── - - fn cursorUp(self: *Self) void { - const visible = self.filtered_indices.items; - if (visible.len == 0) return; - if (self.cursor > 0) { - self.cursor -= 1; - } else if (self.wrap_around) { - self.cursor = visible.len - 1; - } - self.skipDisabledUp(); - self.ensureVisible(); - } - - fn cursorDown(self: *Self) void { - const visible = self.filtered_indices.items; - if (visible.len == 0) return; - if (self.cursor < visible.len - 1) { - self.cursor += 1; - } else if (self.wrap_around) { - self.cursor = 0; - } - self.skipDisabledDown(); - self.ensureVisible(); - } - - fn pageUp(self: *Self) void { - if (self.cursor >= self.max_visible) { - self.cursor -= self.max_visible; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - fn pageDown(self: *Self) void { - const visible = self.filtered_indices.items; - if (self.cursor + self.max_visible < visible.len) { - self.cursor += self.max_visible; - } else if (visible.len > 0) { - self.cursor = visible.len - 1; - } - self.ensureVisible(); - } - - fn gotoFirst(self: *Self) void { - self.cursor = 0; - self.y_offset = 0; - } - - fn gotoLast(self: *Self) void { - const visible = self.filtered_indices.items; - if (visible.len > 0) { - self.cursor = visible.len - 1; - self.ensureVisible(); - } - } - - fn skipDisabledDown(self: *Self) void { - const visible = self.filtered_indices.items; - const start = self.cursor; - while (self.cursor < visible.len) { - if (self.items.items[visible[self.cursor]].enabled) return; - self.cursor += 1; - } - self.cursor = start; // no enabled item found, revert - } - - fn skipDisabledUp(self: *Self) void { - const visible = self.filtered_indices.items; - if (visible.len == 0) return; - const start = self.cursor; - while (true) { - if (self.items.items[visible[self.cursor]].enabled) return; - if (self.cursor == 0) break; - self.cursor -= 1; - } - self.cursor = start; // revert - } - - fn ensureVisible(self: *Self) void { - if (self.cursor < self.y_offset) { - self.y_offset = self.cursor; - } else if (self.cursor >= self.y_offset + self.max_visible) { - self.y_offset = self.cursor - self.max_visible + 1; - } - } - - // ── Filtering ────────────────────────────────── - - fn rebuildFilter(self: *Self) !void { - self.filtered_indices.clearRetainingCapacity(); - - if (self.filter_text.items.len == 0) { - for (0..self.items.items.len) |i| { - try self.filtered_indices.append(i); - } - } else { - var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); - defer scored.deinit(); - - for (self.items.items, 0..) |item, i| { - const s = fuzzy.scoreIgnoreCase(item.label, self.filter_text.items); - if (s > 0) try scored.append(.{ .index = i, .score = s }); - } - - 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); - - for (scored.items) |s| { - try self.filtered_indices.append(s.index); - } - } - - 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(); - } - - // ── Rendering ─────────────────────────────────── - - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Label - if (self.label.len > 0) { - const styled_label = try self.label_style.render(allocator, self.label); - try writer.writeAll(styled_label); - try writer.writeAll(" "); - } - - // Trigger line - const display_text = if (self.selectedItem()) |item| - item.label - else if (self.multi_select and self.selectedCount() > 0) - try std.fmt.allocPrint(allocator, "{d} selected", .{self.selectedCount()}) - else - self.placeholder; - - const trig_style = if (self.focused) self.trigger_focused_style else self.trigger_style; - const styled_trigger = try trig_style.render(allocator, display_text); - try writer.writeAll(styled_trigger); - try writer.writeAll(" "); - - const expand_str = if (self.expanded) "▲" else self.expand_symbol; - try writer.writeAll(expand_str); - - if (!self.expanded) { - return result.toOwnedSlice(); - } - - // Expanded dropdown - try writer.writeByte('\n'); - - // Compute dropdown width - var max_item_width: usize = 0; - for (self.items.items) |item| { - const w = measure.width(item.label) + self.cursor_symbol.len; - const extra: usize = if (self.multi_select) self.checked_symbol.len else 0; - if (w + extra > max_item_width) max_item_width = w + extra; - } - max_item_width = @max(max_item_width, 10); - const inner_width = max_item_width + 2; // padding - - // Top border - try self.writeBorderLine(writer, allocator, inner_width, .top); - try writer.writeByte('\n'); - - // Filter line - if (self.filter_active) { - try self.writeBorderSide(writer, allocator, .left); - const filter_line = try std.fmt.allocPrint(allocator, " / {s}_", .{self.filter_text.items}); - const styled = try self.filter_style.render(allocator, filter_line); - try writer.writeAll(styled); - const used = measure.width(filter_line); - if (used < inner_width) { - try self.writePadding(writer, inner_width - used); - } - try self.writeBorderSide(writer, allocator, .right); - try writer.writeByte('\n'); - - // Separator - try self.writeBorderLine(writer, allocator, inner_width, .middle); - try writer.writeByte('\n'); - } - - // Scroll indicator (top) - const visible = self.filtered_indices.items; - const has_above = self.y_offset > 0; - const end_idx = @min(self.y_offset + self.max_visible, visible.len); - const has_below = end_idx < visible.len; - - if (has_above) { - try self.writeBorderSide(writer, allocator, .left); - const up_str = try std.fmt.allocPrint(allocator, " {s}", .{self.scroll_up_symbol}); - try writer.writeAll(up_str); - const used = measure.width(up_str); - if (used < inner_width) { - try self.writePadding(writer, inner_width - used); - } - try self.writeBorderSide(writer, allocator, .right); - try writer.writeByte('\n'); - } - - // Items - var rendered: usize = 0; - while (rendered < self.max_visible) : (rendered += 1) { - const idx = self.y_offset + rendered; - if (idx >= visible.len) break; - - if (rendered > 0 or has_above) { - // already have newline from previous - } - - try self.writeBorderSide(writer, allocator, .left); - - const item_idx = visible[idx]; - const item = self.items.items[item_idx]; - var line: Writer.Allocating = .init(allocator); - const line_writer = &line.writer; - - try line_writer.writeByte(' '); - - // Cursor symbol - if (idx == self.cursor) { - try line_writer.writeAll(self.cursor_symbol); - } else { - for (0..self.cursor_symbol.len) |_| { - try line_writer.writeByte(' '); - } - } - - // Multi-select check - if (self.multi_select) { - if (self.selected_indices.contains(item_idx)) { - try line_writer.writeAll(self.checked_symbol); - } else { - try line_writer.writeAll(self.unchecked_symbol); - } - } - - // Label - try line_writer.writeAll(item.label); - - const line_text = try line.toOwnedSlice(); - const item_s = if (!item.enabled) - self.disabled_style - else if (idx == self.cursor) - self.cursor_item_style - else if (self.isItemSelected(item_idx)) - self.selected_item_style - else - self.item_style; - - const styled_line = try item_s.render(allocator, line_text); - try writer.writeAll(styled_line); - - // Pad to width - const used = measure.width(line_text); - if (used < inner_width) { - try self.writePadding(writer, inner_width - used); - } - - try self.writeBorderSide(writer, allocator, .right); - if (rendered + 1 < self.max_visible and idx + 1 < visible.len) { - try writer.writeByte('\n'); - } - } - - // Scroll indicator (bottom) - if (has_below) { - try writer.writeByte('\n'); - try self.writeBorderSide(writer, allocator, .left); - const down_str = try std.fmt.allocPrint(allocator, " {s}", .{self.scroll_down_symbol}); - try writer.writeAll(down_str); - const used = measure.width(down_str); - if (used < inner_width) { - try self.writePadding(writer, inner_width - used); - } - try self.writeBorderSide(writer, allocator, .right); - } - - // Bottom border - try writer.writeByte('\n'); - try self.writeBorderLine(writer, allocator, inner_width, .bottom); - - return result.toOwnedSlice(); - } - - fn isItemSelected(self: *const Self, idx: usize) bool { - if (self.multi_select) { - return self.selected_indices.contains(idx); - } - return self.selected_index != null and self.selected_index.? == idx; - } - - fn selectedCount(self: *const Self) usize { - return self.selected_indices.count(); - } - - const BorderPos = enum { top, middle, bottom }; - const BorderSide = enum { left, right }; - - fn writeBorderLine(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { - const bc = self.border_chars; - var border_style = style_mod.Style{}; - border_style = border_style.fg(self.border_fg); - border_style = border_style.inline_style(true); - - const corner_l = switch (pos) { - .top => bc.top_left, - .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, - .bottom => bc.bottom_left, - }; - const corner_r = switch (pos) { - .top => bc.top_right, - .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, - .bottom => bc.bottom_right, - }; - - const styled_l = try border_style.render(allocator, corner_l); - try writer.writeAll(styled_l); - - for (0..width) |_| { - const styled = try border_style.render(allocator, bc.horizontal); - try writer.writeAll(styled); - } - - const styled_r = try border_style.render(allocator, corner_r); - try writer.writeAll(styled_r); - } - - fn writeBorderSide(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { - var border_style = style_mod.Style{}; - border_style = border_style.fg(self.border_fg); - border_style = border_style.inline_style(true); - - const char = switch (side) { - .left => self.border_chars.vertical, - .right => self.border_chars.vertical, - }; - const styled = try border_style.render(allocator, char); - try writer.writeAll(styled); - } - - fn writePadding(_: *const Self, writer: *Writer, count: usize) !void { - for (0..count) |_| { - try writer.writeByte(' '); - } - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig deleted file mode 100644 index 56720ad..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/file_picker.zig +++ /dev/null @@ -1,419 +0,0 @@ -//! File picker component for file system navigation. -//! Allows browsing directories and selecting files. - -const std = @import("std"); -const Writer = std.Io.Writer; -const builtin = @import("builtin"); -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); -const Dir = std.Io.Dir; - -pub const FilePicker = struct { - allocator: std.mem.Allocator, - - // State - current_path: std.array_list.Managed(u8), - entries: std.array_list.Managed(Entry), - cursor: usize, - y_offset: usize, - - // Selection - selected_path: ?[]const u8, - - // Options - height: u16, - show_hidden: bool, - show_size: bool, - show_permissions: bool, - dir_only: bool, - file_only: bool, - allowed_extensions: ?[]const []const u8, - - // Styling - dir_style: style_mod.Style, - file_style: style_mod.Style, - cursor_style: style_mod.Style, - size_style: style_mod.Style, - path_style: style_mod.Style, - - // Focus - focused: bool, - - // Symbols - dir_icon: []const u8, - file_icon: []const u8, - link_icon: []const u8, - parent_icon: []const u8, - - pub const Entry = struct { - name: []const u8, - entry_type: EntryType, - size: u64, - is_hidden: bool, - - pub const EntryType = enum { - file, - directory, - symlink, - parent, - }; - }; - - pub fn init(allocator: std.mem.Allocator) FilePicker { - return .{ - .allocator = allocator, - .current_path = std.array_list.Managed(u8).init(allocator), - .entries = std.array_list.Managed(Entry).init(allocator), - .cursor = 0, - .y_offset = 0, - .selected_path = null, - .height = 15, - .show_hidden = false, - .show_size = true, - .show_permissions = false, - .dir_only = false, - .file_only = false, - .allowed_extensions = null, - .dir_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.blue); - s = s.inline_style(true); - break :blk s; - }, - .file_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .size_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .path_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .focused = true, - .dir_icon = "📁 ", - .file_icon = "📄 ", - .link_icon = "🔗 ", - .parent_icon = "📂 ", - }; - } - - pub fn deinit(self: *FilePicker) void { - self.current_path.deinit(); - for (self.entries.items) |entry| { - self.allocator.free(entry.name); - } - self.entries.deinit(); - if (self.selected_path) |path| { - self.allocator.free(path); - } - } - - /// Navigate to a directory - pub fn navigate(self: *FilePicker, io: std.Io, path: []const u8) !void { - // Update current path - self.current_path.clearRetainingCapacity(); - try self.current_path.appendSlice(path); - - // Clear old entries - for (self.entries.items) |entry| { - self.allocator.free(entry.name); - } - self.entries.clearRetainingCapacity(); - - // Add parent directory entry - if (!std.mem.eql(u8, path, "/")) { - const parent_name = try self.allocator.dupe(u8, ".."); - try self.entries.append(.{ - .name = parent_name, - .entry_type = .parent, - .size = 0, - .is_hidden = false, - }); - } - - // Read directory - var dir = Dir.openDirAbsolute(io, path, .{ .iterate = true }) catch { - return; - }; - defer dir.close(io); - - var iter = dir.iterate(); - while (iter.next(io) catch null) |entry| { - // Skip hidden files if not showing them - const is_hidden = entry.name.len > 0 and entry.name[0] == '.'; - if (is_hidden and !self.show_hidden) continue; - - // Skip files if dir_only - if (self.dir_only and entry.kind != .directory) continue; - - // Skip directories if file_only - if (self.file_only and entry.kind == .directory) continue; - - // Check extensions if specified - if (self.allowed_extensions) |exts| { - if (entry.kind != .directory) { - const ext = std.fs.path.extension(entry.name); - var found = false; - for (exts) |allowed_ext| { - if (std.mem.eql(u8, ext, allowed_ext)) { - found = true; - break; - } - } - if (!found) continue; - } - } - - // Get file size - var size: u64 = 0; - if (entry.kind == .file) { - const stat = dir.statFile(io, entry.name, .{}) catch null; - if (stat) |s| { - size = s.size; - } - } - - const name_copy = try self.allocator.dupe(u8, entry.name); - try self.entries.append(.{ - .name = name_copy, - .entry_type = switch (entry.kind) { - .directory => .directory, - .sym_link => .symlink, - else => .file, - }, - .size = size, - .is_hidden = is_hidden, - }); - } - - // Sort entries (directories first, then alphabetically) - std.mem.sort(Entry, self.entries.items, {}, struct { - fn lessThan(_: void, a: Entry, b: Entry) bool { - // Parent always first - if (a.entry_type == .parent) return true; - if (b.entry_type == .parent) return false; - - // Directories before files - if (a.entry_type == .directory and b.entry_type != .directory) return true; - if (b.entry_type == .directory and a.entry_type != .directory) return false; - - // Alphabetical - return std.mem.lessThan(u8, a.name, b.name); - } - }.lessThan); - - self.cursor = 0; - self.y_offset = 0; - } - - /// Navigate to home directory using the supplied environment. - pub fn navigateHome(self: *FilePicker, io: std.Io, environ_map: *const std.process.Environ.Map) !void { - if (comptime builtin.os.tag == .windows) { - const home = environ_map.get("USERPROFILE") orelse "C:\\"; - try self.navigate(io, home); - } else { - const home = environ_map.get("HOME") orelse "/"; - try self.navigate(io, home); - } - } - - /// Move cursor up - pub fn cursorUp(self: *FilePicker) void { - if (self.cursor > 0) { - self.cursor -= 1; - self.ensureVisible(); - } - } - - /// Move cursor down - pub fn cursorDown(self: *FilePicker) void { - if (self.cursor < self.entries.items.len -| 1) { - self.cursor += 1; - self.ensureVisible(); - } - } - - /// Select current entry - pub fn selectCurrent(self: *FilePicker, io: std.Io) !bool { - if (self.cursor >= self.entries.items.len) return false; - - const entry = self.entries.items[self.cursor]; - - if (entry.entry_type == .directory or entry.entry_type == .parent) { - // Navigate into directory - if (entry.entry_type == .parent) { - const parent = std.fs.path.dirname(self.current_path.items) orelse "/"; - const parent_copy = try self.allocator.dupe(u8, parent); - defer self.allocator.free(parent_copy); - try self.navigate(io, parent_copy); - } else { - const new_path = try std.fs.path.join(self.allocator, &.{ self.current_path.items, entry.name }); - defer self.allocator.free(new_path); - try self.navigate(io, new_path); - } - return false; - } else { - // Select file - if (self.selected_path) |path| { - self.allocator.free(path); - } - self.selected_path = try std.fs.path.join(self.allocator, &.{ self.current_path.items, entry.name }); - return true; - } - } - - /// Set focused state (for use with FocusGroup). - pub fn focus(self: *FilePicker) void { - self.focused = true; - } - - /// Clear focused state (for use with FocusGroup). - pub fn blur(self: *FilePicker) void { - self.focused = false; - } - - /// Handle key event - pub fn handleKey( - self: *FilePicker, - io: std.Io, - environ_map: *const std.process.Environ.Map, - key: keys.KeyEvent, - ) !bool { - if (!self.focused) return false; - switch (key.key) { - .up => self.cursorUp(), - .down => self.cursorDown(), - .enter => return try self.selectCurrent(io), - .backspace => { - const parent = std.fs.path.dirname(self.current_path.items) orelse "/"; - const parent_copy = try self.allocator.dupe(u8, parent); - defer self.allocator.free(parent_copy); - try self.navigate(io, parent_copy); - }, - .char => |c| { - switch (c) { - 'j' => self.cursorDown(), - 'k' => self.cursorUp(), - 'h' => self.showHidden(io), - '~' => try self.navigateHome(io, environ_map), - else => {}, - } - }, - else => {}, - } - return false; - } - - fn showHidden(self: *FilePicker, io: std.Io) void { - self.show_hidden = !self.show_hidden; - const path_copy = self.allocator.dupe(u8, self.current_path.items) catch return; - defer self.allocator.free(path_copy); - self.navigate(io, path_copy) catch {}; - } - - fn ensureVisible(self: *FilePicker) void { - if (self.cursor < self.y_offset) { - self.y_offset = self.cursor; - } else if (self.cursor >= self.y_offset + self.height) { - self.y_offset = self.cursor - self.height + 1; - } - } - - /// Get selected path - pub fn getSelected(self: *const FilePicker) ?[]const u8 { - return self.selected_path; - } - - /// Format file size for display - fn formatSize(self: *const FilePicker, allocator: std.mem.Allocator, size: u64) ![]const u8 { - _ = self; - if (size < 1024) { - return try std.fmt.allocPrint(allocator, "{d}B", .{size}); - } else if (size < 1024 * 1024) { - return try std.fmt.allocPrint(allocator, "{d:.1}K", .{@as(f64, @floatFromInt(size)) / 1024.0}); - } else if (size < 1024 * 1024 * 1024) { - return try std.fmt.allocPrint(allocator, "{d:.1}M", .{@as(f64, @floatFromInt(size)) / (1024.0 * 1024.0)}); - } else { - return try std.fmt.allocPrint(allocator, "{d:.1}G", .{@as(f64, @floatFromInt(size)) / (1024.0 * 1024.0 * 1024.0)}); - } - } - - /// Render the file picker - pub fn view(self: *const FilePicker, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Current path header - const path_styled = try self.path_style.render(allocator, self.current_path.items); - try writer.writeAll(path_styled); - try writer.writeByte('\n'); - try writer.writeByte('\n'); - - // Entries - var rendered: usize = 0; - while (rendered < self.height -| 2) : (rendered += 1) { - if (rendered > 0) try writer.writeByte('\n'); - - const idx = self.y_offset + rendered; - if (idx >= self.entries.items.len) continue; - - const entry = self.entries.items[idx]; - const is_selected = idx == self.cursor; - - // Cursor indicator - if (is_selected) { - try writer.writeAll("> "); - } else { - try writer.writeAll(" "); - } - - // Icon - const icon = switch (entry.entry_type) { - .directory => self.dir_icon, - .parent => self.parent_icon, - .symlink => self.link_icon, - .file => self.file_icon, - }; - try writer.writeAll(icon); - - // Name - const name_style = if (is_selected) - self.cursor_style - else switch (entry.entry_type) { - .directory, .parent => self.dir_style, - else => self.file_style, - }; - const name_styled = try name_style.render(allocator, entry.name); - try writer.writeAll(name_styled); - - // Size (for files) - if (self.show_size and entry.entry_type == .file) { - const size_str = try self.formatSize(allocator, entry.size); - try writer.writeAll(" "); - const size_styled = try self.size_style.render(allocator, size_str); - try writer.writeAll(size_styled); - } - } - - return result.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig deleted file mode 100644 index 9e66964..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/focus.zig +++ /dev/null @@ -1,553 +0,0 @@ -//! Focus management for ZigZag TUI applications. -//! Provides Tab/Shift+Tab cycling between focusable components and -//! focus-aware style helpers for rendering focus indicators. -//! -//! A component is "focusable" if it has: -//! - a `focused: bool` field -//! - a `pub fn focus(*Self) void` method -//! - a `pub fn blur(*Self) void` method -//! -//! TextInput, TextArea, Table, List, Confirm, and FilePicker all satisfy -//! this protocol out of the box. - -const std = @import("std"); -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const border_mod = @import("../style/border.zig"); -const Color = @import("../style/color.zig").Color; - -/// Comptime check: returns true if `T` satisfies the focusable protocol. -pub fn isFocusable(comptime T: type) bool { - return @hasField(T, "focused") and - @hasDecl(T, "focus") and - @hasDecl(T, "blur"); -} - -/// Maximum number of key bindings per action (next / prev). -const max_binds = 4; - -/// A key binding slot: a key plus optional modifiers. -pub const KeyBind = struct { - key: keys.Key, - modifiers: keys.Modifiers = .{}, - - /// Check if a KeyEvent matches this binding. - pub fn matches(self: KeyBind, event: keys.KeyEvent) bool { - return self.key.eql(event.key) and self.modifiers.eql(event.modifiers); - } -}; - -/// Default "next" bindings: Tab (no modifiers), Down arrow, 'j'. -pub const default_next_keys = [max_binds]?KeyBind{ - .{ .key = .tab }, - null, - null, - null, -}; - -/// Default "prev" bindings: Shift+Tab, Up arrow, 'k'. -pub const default_prev_keys = [max_binds]?KeyBind{ - .{ .key = .tab, .modifiers = .{ .shift = true } }, - null, - null, - null, -}; - -/// A group of focusable components with customizable key-driven cycling. -/// -/// `max_items` is the maximum number of components that can be registered. -/// The group uses a fixed-size array so it requires no allocation and can -/// be embedded directly in a Model struct. -/// -/// By default, Tab moves forward and Shift+Tab moves backward. -/// Override `next_keys` / `prev_keys` or call `addNextKey()` / `addPrevKey()` -/// to use any keys you want (arrows, vim j/k, etc.). -/// -/// Usage: -/// ``` -/// var fg: FocusGroup(3) = .{}; -/// fg.add(&self.input_a); -/// fg.add(&self.input_b); -/// fg.add(&self.table); -/// fg.initFocus(); // focus first, blur the rest -/// -/// // Optional: add extra navigation keys -/// fg.addNextKey(.{ .key = .down }); // Down arrow -/// fg.addNextKey(.{ .key = .{ .char = 'j' } }); // vim j -/// fg.addPrevKey(.{ .key = .up }); // Up arrow -/// fg.addPrevKey(.{ .key = .{ .char = 'k' } }); // vim k -/// ``` -pub fn FocusGroup(comptime max_items: usize) type { - return struct { - const Self = @This(); - - /// Type-erased handle to a focusable component. - pub const FocusItem = struct { - focus_fn: *const fn (*anyopaque) void, - blur_fn: *const fn (*anyopaque) void, - is_focused_fn: *const fn (*const anyopaque) bool, - ptr: *anyopaque, - }; - - items: [max_items]?FocusItem = [_]?FocusItem{null} ** max_items, - count: usize = 0, - active: usize = 0, - /// Whether cycling wraps from last to first (and vice versa). - wrap: bool = true, - /// Key bindings that trigger focusNext(). Up to 4 bindings. - next_keys: [max_binds]?KeyBind = default_next_keys, - /// Key bindings that trigger focusPrev(). Up to 4 bindings. - prev_keys: [max_binds]?KeyBind = default_prev_keys, - - /// Register a focusable component. - /// - /// The component must satisfy the focusable protocol - /// (`focused: bool`, `focus()`, `blur()`). A compile error is - /// emitted if the protocol is not satisfied. - /// - /// The pointer must remain valid for the lifetime of the FocusGroup - /// (which is naturally the case for fields in the same Model struct). - pub fn add(self: *Self, item_ptr: anytype) void { - const Ptr = @TypeOf(item_ptr); - const T = @typeInfo(Ptr).pointer.child; - - comptime { - if (!@hasField(T, "focused")) - @compileError("FocusGroup item must have a 'focused: bool' field. " ++ - "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); - if (!@hasDecl(T, "focus")) - @compileError("FocusGroup item must have a 'pub fn focus(*Self) void' method. " ++ - "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); - if (!@hasDecl(T, "blur")) - @compileError("FocusGroup item must have a 'pub fn blur(*Self) void' method. " ++ - "Type '" ++ @typeName(T) ++ "' does not satisfy the focusable protocol."); - } - - if (self.count >= max_items) return; - - self.items[self.count] = .{ - .focus_fn = @ptrCast(&struct { - fn call(raw_ptr: *anyopaque) void { - const ptr: *T = @ptrCast(@alignCast(raw_ptr)); - ptr.focus(); - } - }.call), - .blur_fn = @ptrCast(&struct { - fn call(raw_ptr: *anyopaque) void { - const ptr: *T = @ptrCast(@alignCast(raw_ptr)); - ptr.blur(); - } - }.call), - .is_focused_fn = @ptrCast(&struct { - fn call(raw_ptr: *const anyopaque) bool { - const ptr: *const T = @ptrCast(@alignCast(raw_ptr)); - return ptr.focused; - } - }.call), - .ptr = @ptrCast(item_ptr), - }; - self.count += 1; - } - - /// Focus the item at `index`, blurring all others. - /// Does nothing if `index` is out of range. - pub fn focusAt(self: *Self, index: usize) void { - if (index >= self.count) return; - for (0..self.count) |i| { - if (self.items[i]) |item| { - if (i == index) { - item.focus_fn(item.ptr); - } else { - item.blur_fn(item.ptr); - } - } - } - self.active = index; - } - - /// Move focus to the next item (Tab behavior). - pub fn focusNext(self: *Self) void { - if (self.count == 0) return; - if (self.active + 1 < self.count) { - self.focusAt(self.active + 1); - } else if (self.wrap) { - self.focusAt(0); - } - } - - /// Move focus to the previous item (Shift+Tab behavior). - pub fn focusPrev(self: *Self) void { - if (self.count == 0) return; - if (self.active > 0) { - self.focusAt(self.active - 1); - } else if (self.wrap) { - self.focusAt(self.count - 1); - } - } - - /// Handle a key event for focus cycling. - /// - /// Checks the event against `next_keys` and `prev_keys`. - /// Returns `true` if the key was consumed (matched a binding), - /// `false` if it should be forwarded to the active component. - pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { - for (self.next_keys) |maybe_bind| { - if (maybe_bind) |bind| { - if (bind.matches(key)) { - self.focusNext(); - return true; - } - } - } - for (self.prev_keys) |maybe_bind| { - if (maybe_bind) |bind| { - if (bind.matches(key)) { - self.focusPrev(); - return true; - } - } - } - return false; - } - - /// Add an extra key binding for "focus next". - /// Returns false if all 4 slots are full. - pub fn addNextKey(self: *Self, bind: KeyBind) bool { - for (&self.next_keys) |*slot| { - if (slot.* == null) { - slot.* = bind; - return true; - } - } - return false; - } - - /// Add an extra key binding for "focus prev". - /// Returns false if all 4 slots are full. - pub fn addPrevKey(self: *Self, bind: KeyBind) bool { - for (&self.prev_keys) |*slot| { - if (slot.* == null) { - slot.* = bind; - return true; - } - } - return false; - } - - /// Replace all "next" bindings with a single key. - pub fn setNextKey(self: *Self, bind: KeyBind) void { - self.next_keys = .{ bind, null, null, null }; - } - - /// Replace all "prev" bindings with a single key. - pub fn setPrevKey(self: *Self, bind: KeyBind) void { - self.prev_keys = .{ bind, null, null, null }; - } - - /// Clear all "next" key bindings. - pub fn clearNextKeys(self: *Self) void { - self.next_keys = .{ null, null, null, null }; - } - - /// Clear all "prev" key bindings. - pub fn clearPrevKeys(self: *Self) void { - self.prev_keys = .{ null, null, null, null }; - } - - /// Get the index of the currently focused item. - pub fn focused(self: *const Self) usize { - return self.active; - } - - /// Check if the item at `index` is the currently focused one. - pub fn isFocused(self: *const Self, index: usize) bool { - return self.active == index; - } - - /// Initialize focus: focuses the first item and blurs all others. - /// Call this after adding all components. - pub fn initFocus(self: *Self) void { - if (self.count > 0) { - self.focusAt(0); - } - } - - /// Blur all items (none focused). - pub fn blurAll(self: *Self) void { - for (0..self.count) |i| { - if (self.items[i]) |item| { - item.blur_fn(item.ptr); - } - } - } - - /// Returns the total number of registered items. - pub fn len(self: *const Self) usize { - return self.count; - } - }; -} - -/// Style helper for rendering focus-aware borders. -/// -/// Apply to a base `Style` in your `view()` function to get a border -/// that changes color depending on focus state. -/// -/// ``` -/// const fs = FocusStyle{}; -/// var style = zz.Style{}; -/// style = style.paddingAll(1); -/// style = fs.apply(style, is_focused); -/// const rendered = style.render(allocator, content); -/// ``` -pub const FocusStyle = struct { - /// Border color when focused (default: cyan). - focused_border_fg: Color = .cyan, - /// Border color when not focused (default: dark gray). - blurred_border_fg: Color = .gray(12), - /// Border character set (default: rounded). - border_chars: border_mod.BorderChars = .rounded, - - /// Apply focus-aware border styling to `base`. - /// Returns a new Style with the appropriate border and color. - pub fn apply(self: FocusStyle, base: style_mod.Style, is_focused: bool) style_mod.Style { - var s = base; - s = s.borderAll(self.border_chars); - if (is_focused) { - s = s.borderForeground(self.focused_border_fg); - } else { - s = s.borderForeground(self.blurred_border_fg); - } - return s; - } -}; - -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- - -test "isFocusable positive" { - const Focusable = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - try std.testing.expect(isFocusable(Focusable)); -} - -test "isFocusable negative — missing field" { - const NotFocusable = struct { - pub fn focus(_: *@This()) void {} - pub fn blur(_: *@This()) void {} - }; - try std.testing.expect(!isFocusable(NotFocusable)); -} - -test "isFocusable negative — missing method" { - const NotFocusable = struct { - focused: bool = false, - pub fn focus(_: *@This()) void {} - }; - try std.testing.expect(!isFocusable(NotFocusable)); -} - -test "FocusGroup — basic cycling" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - var c = Item{}; - - var fg: FocusGroup(3) = .{}; - fg.add(&a); - fg.add(&b); - fg.add(&c); - fg.initFocus(); - - // After init: first item focused - try std.testing.expect(a.focused); - try std.testing.expect(!b.focused); - try std.testing.expect(!c.focused); - try std.testing.expectEqual(@as(usize, 0), fg.focused()); - - // focusNext - fg.focusNext(); - try std.testing.expect(!a.focused); - try std.testing.expect(b.focused); - try std.testing.expect(!c.focused); - try std.testing.expectEqual(@as(usize, 1), fg.focused()); - - // focusNext again - fg.focusNext(); - try std.testing.expectEqual(@as(usize, 2), fg.focused()); - try std.testing.expect(c.focused); - - // focusNext wraps - fg.focusNext(); - try std.testing.expectEqual(@as(usize, 0), fg.focused()); - try std.testing.expect(a.focused); - try std.testing.expect(!c.focused); -} - -test "FocusGroup — prev cycling" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - - var fg: FocusGroup(2) = .{}; - fg.add(&a); - fg.add(&b); - fg.initFocus(); - - // focusPrev wraps from 0 to last - fg.focusPrev(); - try std.testing.expectEqual(@as(usize, 1), fg.focused()); - try std.testing.expect(b.focused); - try std.testing.expect(!a.focused); - - // focusPrev goes back - fg.focusPrev(); - try std.testing.expectEqual(@as(usize, 0), fg.focused()); - try std.testing.expect(a.focused); -} - -test "FocusGroup — no wrap" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - - var fg: FocusGroup(2) = .{ .wrap = false }; - fg.add(&a); - fg.add(&b); - fg.initFocus(); - - // At first item, prev should NOT wrap - fg.focusPrev(); - try std.testing.expectEqual(@as(usize, 0), fg.focused()); - - // At last item, next should NOT wrap - fg.focusAt(1); - fg.focusNext(); - try std.testing.expectEqual(@as(usize, 1), fg.focused()); -} - -test "FocusGroup — handleKey Tab" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - - var fg: FocusGroup(2) = .{}; - fg.add(&a); - fg.add(&b); - fg.initFocus(); - - // Tab moves forward - const tab_event = keys.KeyEvent{ .key = .tab, .modifiers = .{} }; - const consumed = fg.handleKey(tab_event); - try std.testing.expect(consumed); - try std.testing.expectEqual(@as(usize, 1), fg.focused()); - - // Shift+Tab moves backward - const shift_tab = keys.KeyEvent{ .key = .tab, .modifiers = .{ .shift = true } }; - const consumed2 = fg.handleKey(shift_tab); - try std.testing.expect(consumed2); - try std.testing.expectEqual(@as(usize, 0), fg.focused()); - - // Other keys not consumed - const other = keys.KeyEvent{ .key = .{ .char = 'a' }, .modifiers = .{} }; - const consumed3 = fg.handleKey(other); - try std.testing.expect(!consumed3); -} - -test "FocusGroup — focusAt and isFocused" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - var c = Item{}; - - var fg: FocusGroup(3) = .{}; - fg.add(&a); - fg.add(&b); - fg.add(&c); - - fg.focusAt(2); - try std.testing.expect(!fg.isFocused(0)); - try std.testing.expect(!fg.isFocused(1)); - try std.testing.expect(fg.isFocused(2)); - try std.testing.expect(!a.focused); - try std.testing.expect(!b.focused); - try std.testing.expect(c.focused); -} - -test "FocusGroup — blurAll" { - const Item = struct { - focused: bool = false, - pub fn focus(self: *@This()) void { - self.focused = true; - } - pub fn blur(self: *@This()) void { - self.focused = false; - } - }; - - var a = Item{}; - var b = Item{}; - - var fg: FocusGroup(2) = .{}; - fg.add(&a); - fg.add(&b); - fg.initFocus(); - try std.testing.expect(a.focused); - - fg.blurAll(); - try std.testing.expect(!a.focused); - try std.testing.expect(!b.focused); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig deleted file mode 100644 index d740943..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/form.zig +++ /dev/null @@ -1,299 +0,0 @@ -//! Form component. -//! Composes multiple input fields with focus management, labels, and validation. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const border_mod = @import("../style/border.zig"); -const focus_mod = @import("focus.zig"); - -/// Universally-supported submit bindings. Ctrl+S works in every terminal -/// (no encoding ambiguity). Ctrl+Enter is included for terminals that -/// implement the Kitty keyboard protocol — most don't (notably macOS -/// Terminal.app, basic xterm), so it's a bonus, not the primary binding. -const default_submit_keys = [_]keys.KeyEvent{ - keys.KeyEvent.ctrl('s'), - .{ .key = .enter, .modifiers = .{ .ctrl = true } }, -}; - -const default_cancel_keys = [_]keys.KeyEvent{ - .{ .key = .escape }, -}; - -pub fn Form(comptime max_fields: usize) type { - return struct { - // Fields - fields: [max_fields]?Field, - field_count: usize, - - // Focus - focus_group: focus_mod.FocusGroup(max_fields), - - // State - submitted: bool, - cancelled: bool, - - // Layout - label_width: u16, - spacing: u16, - show_required_marker: bool, - - // Submit bindings. Multiple keys can submit the form. Default - // includes Ctrl+S (works in every terminal) and Ctrl+Enter (only - // works in terminals that implement the Kitty keyboard protocol — - // Terminal.app and most basic xterms cannot tell Ctrl+Enter from - // plain Enter, so we don't rely on it). - submit_keys: []const keys.KeyEvent, - cancel_keys: []const keys.KeyEvent, - /// Human-readable description of submit/cancel bindings shown in the - /// footer hint. Override if you change submit_keys/cancel_keys. - hint_text: []const u8, - - // Styling - label_style: style_mod.Style, - required_style: style_mod.Style, - error_style: style_mod.Style, - border_chars: border_mod.BorderChars, - border_fg: Color, - border_focus_fg: Color, - title: []const u8, - title_style: style_mod.Style, - - const Self = @This(); - - pub const Field = struct { - label: []const u8, - required: bool, - error_msg: ?[]const u8, - // Type-erased component - ptr: *anyopaque, - view_fn: *const fn (*anyopaque, std.mem.Allocator) anyerror![]const u8, - handle_key_fn: *const fn (*anyopaque, keys.KeyEvent) void, - validate_fn: ?*const fn (*anyopaque) ?[]const u8, - }; - - pub fn init() Self { - return .{ - .fields = [_]?Field{null} ** max_fields, - .field_count = 0, - .focus_group = .{}, - .submitted = false, - .cancelled = false, - .label_width = 15, - .spacing = 1, - .show_required_marker = true, - .submit_keys = &default_submit_keys, - .cancel_keys = &default_cancel_keys, - .hint_text = "Tab: next field | Ctrl+S: submit | Esc: cancel", - .label_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .required_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - .error_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - .border_chars = .rounded, - .border_fg = .gray(10), - .border_focus_fg = .cyan, - .title = "", - .title_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - /// Add a focusable component as a form field. - pub fn addField(self: *Self, label: []const u8, component: anytype, options: struct { - required: bool = false, - validate_fn: ?*const fn (*anyopaque) ?[]const u8 = null, - }) void { - if (self.field_count >= max_fields) return; - - const Ptr = @TypeOf(component); - const T = @typeInfo(Ptr).pointer.child; - - self.fields[self.field_count] = .{ - .label = label, - .required = options.required, - .error_msg = null, - .ptr = @ptrCast(component), - .view_fn = @ptrCast(&struct { - fn call(raw_ptr: *anyopaque, allocator: std.mem.Allocator) anyerror![]const u8 { - const ptr: *T = @ptrCast(@alignCast(raw_ptr)); - return ptr.view(allocator); - } - }.call), - .handle_key_fn = @ptrCast(&struct { - fn call(raw_ptr: *anyopaque, key: keys.KeyEvent) void { - const ptr: *T = @ptrCast(@alignCast(raw_ptr)); - ptr.handleKey(key); - } - }.call), - .validate_fn = options.validate_fn, - }; - - self.focus_group.add(component); - self.field_count += 1; - } - - /// Initialize focus on first field. - pub fn initFocus(self: *Self) void { - self.focus_group.initFocus(); - } - - /// Check if form was submitted. - pub fn isSubmitted(self: *const Self) bool { - return self.submitted; - } - - /// Check if form was cancelled. - pub fn isCancelled(self: *const Self) bool { - return self.cancelled; - } - - /// Reset submission state. - pub fn reset(self: *Self) void { - self.submitted = false; - self.cancelled = false; - for (0..self.field_count) |i| { - if (self.fields[i]) |*field| { - field.error_msg = null; - } - } - } - - /// Validate all fields. Returns true if all pass. - pub fn validate(self: *Self) bool { - var all_valid = true; - for (0..self.field_count) |i| { - if (self.fields[i]) |*field| { - if (field.validate_fn) |vfn| { - field.error_msg = vfn(field.ptr); - if (field.error_msg != null) all_valid = false; - } - } - } - return all_valid; - } - - /// Get current focused field index. - pub fn focusedIndex(self: *const Self) usize { - return self.focus_group.focused(); - } - - /// Handle key events. - pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { - // Submit on any configured submit key. - for (self.submit_keys) |sk| { - if (sk.eql(key)) { - if (self.validate()) { - self.submitted = true; - } - return true; - } - } - - // Cancel on any configured cancel key. - for (self.cancel_keys) |ck| { - if (ck.eql(key)) { - self.cancelled = true; - return true; - } - } - - // Tab/Shift+Tab for focus cycling - if (self.focus_group.handleKey(key)) { - return true; - } - - // Forward to active field - const active = self.focus_group.focused(); - if (active < self.field_count) { - if (self.fields[active]) |field| { - field.handle_key_fn(field.ptr, key); - return true; - } - } - - return false; - } - - /// Render the form. - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Title - if (self.title.len > 0) { - const styled_title = try self.title_style.render(allocator, self.title); - try writer.writeAll(styled_title); - try writer.writeByte('\n'); - try writer.writeByte('\n'); - } - - // Fields - for (0..self.field_count) |i| { - const field = self.fields[i] orelse continue; - - if (i > 0) { - for (0..self.spacing) |_| try writer.writeByte('\n'); - } - - // Label - const label_text = if (field.required and self.show_required_marker) - try std.fmt.allocPrint(allocator, "{s} *", .{field.label}) - else - field.label; - - const is_focused = self.focus_group.isFocused(i); - const lbl_style = if (is_focused) blk: { - var s = self.label_style; - s = s.fg(self.border_focus_fg); - break :blk s; - } else self.label_style; - - const styled_label = try lbl_style.render(allocator, label_text); - try writer.writeAll(styled_label); - try writer.writeByte('\n'); - - // Component view - const component_view = field.view_fn(field.ptr, allocator) catch try allocator.dupe(u8, "render error"); - try writer.writeAll(component_view); - - // Error message - if (field.error_msg) |err_msg| { - try writer.writeByte('\n'); - const styled_err = try self.error_style.render(allocator, err_msg); - try writer.writeAll(styled_err); - } - } - - // Footer - try writer.writeAll("\n\n"); - var hint_style = style_mod.Style{}; - hint_style = hint_style.fg(.gray(12)); - hint_style = hint_style.inline_style(true); - const hint = try hint_style.render(allocator, self.hint_text); - try writer.writeAll(hint); - - return result.toOwnedSlice(); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig deleted file mode 100644 index 5fb67e3..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/gauge.zig +++ /dev/null @@ -1,249 +0,0 @@ -//! Gauge component for displaying a value within a range. -//! Supports bar, level meter, and block display styles with thresholds and gradients. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Gauge = struct { - /// Current value. - value: f64 = 0, - /// Minimum value. - min: f64 = 0, - /// Maximum value. - max: f64 = 100, - /// Display width in cells. - width: u16 = 40, - /// Display style. - display_style: DisplayStyle = .bar, - /// Show value label. - show_value: bool = true, - /// Show percentage. - show_percent: bool = false, - /// Label format (prefix text). - label: []const u8 = "", - /// Thresholds for color changes. - thresholds: []const Threshold = &.{}, - /// Base color (used when below all thresholds). - base_color: Color = .green, - /// Empty/background color. - empty_color: Color = .gray(6), - /// Label style. - label_style: style_mod.Style = .{}, - /// Value/percent label style. - value_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - /// Filled bar character. - full_char: []const u8 = "\xe2\x96\x88", - /// Empty bar character. - empty_char: []const u8 = "\xe2\x96\x91", - /// Level meter bracket left. - bracket_left: []const u8 = "[", - /// Level meter bracket right. - bracket_right: []const u8 = "]", - /// Number of segments in level meter. - level_segments: usize = 10, - /// Value format string prefix. - value_prefix: []const u8 = "", - /// Value format string suffix. - value_suffix: []const u8 = "", - - pub const DisplayStyle = enum { - /// Horizontal bar with fill characters. - bar, - /// Vertical level meter segments. - level_meter, - /// Block characters showing intensity. - blocks, - }; - - pub const Threshold = struct { - value: f64, - color: Color, - }; - - /// Set the gauge value clamped to min/max. - pub fn setValue(self: *Gauge, v: f64) void { - self.value = @max(self.min, @min(v, self.max)); - } - - /// Get the ratio (0.0 to 1.0). - pub fn ratio(self: *const Gauge) f64 { - const range = self.max - self.min; - if (range <= 0) return 0; - return (self.value - self.min) / range; - } - - /// Get the active color based on thresholds. - fn activeColor(self: *const Gauge) Color { - var result = self.base_color; - for (self.thresholds) |t| { - if (self.value >= t.value) result = t.color; - } - return result; - } - - /// Render the gauge. - pub fn view(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { - return switch (self.display_style) { - .bar => self.renderBar(allocator), - .level_meter => self.renderLevelMeter(allocator), - .blocks => self.renderBlocks(allocator), - }; - } - - fn renderBar(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { - const pct = self.ratio(); - const active_color = self.activeColor(); - const bar_width: usize = self.width; - const filled: usize = @intFromFloat(@as(f64, @floatFromInt(bar_width)) * pct); - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Label - if (self.label.len > 0) { - if (self.label_style.bold_attr != null or !self.label_style.foreground.isNone()) { - writer.writeAll(self.label_style.render(allocator, self.label) catch self.label) catch {}; - } else { - writer.writeAll(self.label) catch {}; - } - writer.writeByte(' ') catch {}; - } - - // Filled portion - var fill_style = style_mod.Style{}; - fill_style = fill_style.fg(active_color); - fill_style = fill_style.inline_style(true); - - var empty_style = style_mod.Style{}; - empty_style = empty_style.fg(self.empty_color); - empty_style = empty_style.inline_style(true); - - for (0..bar_width) |col| { - if (col < filled) { - writer.writeAll(fill_style.render(allocator, "\xe2\x96\x88") catch "\xe2\x96\x88") catch {}; - } else if (col == filled and pct > 0) { - // Partial fill using fractional blocks - const frac = (@as(f64, @floatFromInt(bar_width)) * pct) - @as(f64, @floatFromInt(filled)); - const block_idx: usize = @intFromFloat(frac * 8); - const partial_blocks = [_][]const u8{ - " ", - "\xe2\x96\x8f", // ▏ - "\xe2\x96\x8e", // ▎ - "\xe2\x96\x8d", // ▍ - "\xe2\x96\x8c", // ▌ - "\xe2\x96\x8b", // ▋ - "\xe2\x96\x8a", // ▊ - "\xe2\x96\x89", // ▉ - }; - const ch = if (block_idx < partial_blocks.len) partial_blocks[block_idx] else "\xe2\x96\x88"; - writer.writeAll(fill_style.render(allocator, ch) catch ch) catch {}; - } else { - writer.writeAll(empty_style.render(allocator, "\xe2\x96\x91") catch "\xe2\x96\x91") catch {}; - } - } - - // Value/percent label - if (self.show_value or self.show_percent) { - writer.writeByte(' ') catch {}; - if (self.show_percent) { - const pct_val = pct * 100; - writer.print("{d:.0}%", .{pct_val}) catch {}; - } else { - writer.print("{d:.1}/{d:.1}", .{ self.value, self.max }) catch {}; - } - } - - return result.toArrayList().items; - } - - fn renderLevelMeter(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { - const pct = self.ratio(); - const levels: usize = 10; - const filled: usize = @intFromFloat(@as(f64, @floatFromInt(levels)) * pct); - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (self.label.len > 0) { - writer.writeAll(self.label) catch {}; - writer.writeByte(' ') catch {}; - } - - writer.writeAll("[") catch {}; - for (0..levels) |lvl| { - const level_pct = @as(f64, @floatFromInt(lvl)) / @as(f64, @floatFromInt(levels)); - const c = self.colorForLevel(level_pct); - var s = style_mod.Style{}; - s = s.fg(c); - s = s.inline_style(true); - - if (lvl < filled) { - writer.writeAll(s.render(allocator, "\xe2\x96\x88") catch "\xe2\x96\x88") catch {}; - } else { - writer.writeAll("\xe2\x96\x91") catch {}; - } - } - writer.writeAll("]") catch {}; - - if (self.show_percent) { - writer.print(" {d:.0}%", .{pct * 100}) catch {}; - } - - return result.toArrayList().items; - } - - fn renderBlocks(self: *const Gauge, allocator: std.mem.Allocator) []const u8 { - const pct = self.ratio(); - const active_color = self.activeColor(); - const block_count: usize = self.width; - - // Use shade characters based on intensity - const shades = [_][]const u8{ " ", "\xe2\x96\x91", "\xe2\x96\x92", "\xe2\x96\x93", "\xe2\x96\x88" }; - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (self.label.len > 0) { - writer.writeAll(self.label) catch {}; - writer.writeByte(' ') catch {}; - } - - var s = style_mod.Style{}; - s = s.fg(active_color); - s = s.inline_style(true); - - for (0..block_count) |col| { - const col_pct = @as(f64, @floatFromInt(col)) / @as(f64, @floatFromInt(block_count)); - if (col_pct < pct) { - // Full block for cells well below the value - const local_pct = (pct - col_pct) * @as(f64, @floatFromInt(block_count)); - const shade_idx: usize = @intFromFloat(@min(local_pct, 4)); - const ch = if (shade_idx < shades.len) shades[shade_idx] else shades[4]; - writer.writeAll(s.render(allocator, ch) catch ch) catch {}; - } else { - writer.writeByte(' ') catch {}; - } - } - - if (self.show_percent) { - writer.print(" {d:.0}%", .{pct * 100}) catch {}; - } - - return result.toArrayList().items; - } - - fn colorForLevel(self: *const Gauge, level_pct: f64) Color { - const value = self.min + (self.max - self.min) * level_pct; - var result = self.base_color; - for (self.thresholds) |t| { - if (value >= t.value) result = t.color; - } - return result; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig deleted file mode 100644 index 766ff7d..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/heatmap.zig +++ /dev/null @@ -1,250 +0,0 @@ -//! Heatmap component for 2D data visualization. -//! Displays data as a colored grid with configurable color scales. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Heatmap = struct { - allocator: std.mem.Allocator, - /// 2D data stored row-major. - data: []const f64 = &.{}, - rows: usize = 0, - cols: usize = 0, - /// Row labels (optional). - row_labels: []const []const u8 = &.{}, - /// Column labels (optional). - col_labels: []const []const u8 = &.{}, - /// Color scale. - color_scale: ColorScale = .green_scale, - /// Cell width in characters. - cell_width: u8 = 2, - /// Manual min/max (auto-detect if null). - min_val: ?f64 = null, - max_val: ?f64 = null, - /// Show legend. - show_legend: bool = true, - /// Show values in cells. - show_values: bool = false, - /// Title. - title: []const u8 = "", - /// Cell height in rows (1 = single line). - cell_height: u8 = 1, - /// Title style. - title_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - /// Row label style. - row_label_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - /// Column label style. - col_label_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - /// Legend label style. - legend_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - /// Number of steps in the legend gradient. - legend_steps: usize = 10, - /// Empty cell character (used when value is zero/min). - empty_char: []const u8 = " ", - - pub const ColorScale = enum { - /// Dark green to bright green (GitHub contributions style). - green_scale, - /// Blue to cyan to green to yellow to red. - cool_to_hot, - /// Black to white. - grayscale, - /// Blue to red. - blue_red, - }; - - pub fn init(allocator: std.mem.Allocator) Heatmap { - return .{ .allocator = allocator }; - } - - /// Set data as a flat array with dimensions. - pub fn setData(self: *Heatmap, r: usize, c: usize, d: []const f64) void { - self.rows = r; - self.cols = c; - self.data = d; - } - - fn getMinMax(self: *const Heatmap) struct { min: f64, max: f64 } { - const mn = self.min_val orelse blk: { - var m: f64 = std.math.inf(f64); - for (self.data) |v| m = @min(m, v); - break :blk m; - }; - const mx = self.max_val orelse blk: { - var m: f64 = -std.math.inf(f64); - for (self.data) |v| m = @max(m, v); - break :blk m; - }; - return .{ .min = mn, .max = mx }; - } - - fn normalize(val: f64, mn: f64, mx: f64) f64 { - if (mx <= mn) return 0; - return @max(0, @min(1, (val - mn) / (mx - mn))); - } - - fn scaleColor(self: *const Heatmap, t: f64) Color { - return switch (self.color_scale) { - .green_scale => { - if (t < 0.01) return .gray(2); - const g: u8 = @intFromFloat(80 + 175 * t); - return .fromRgb(0, g, 0); - }, - .cool_to_hot => { - if (t < 0.25) { - const lt = t * 4; - return .fromRgb(0, @intFromFloat(lt * 255), 255); - } else if (t < 0.5) { - const lt = (t - 0.25) * 4; - return .fromRgb(0, 255, @intFromFloat(255 - lt * 255)); - } else if (t < 0.75) { - const lt = (t - 0.5) * 4; - return .fromRgb(@intFromFloat(lt * 255), 255, 0); - } else { - const lt = (t - 0.75) * 4; - return .fromRgb(255, @intFromFloat(255 - lt * 255), 0); - } - }, - .grayscale => { - const v: u8 = @intFromFloat(t * 255); - return .fromRgb(v, v, v); - }, - .blue_red => { - const r: u8 = @intFromFloat(t * 255); - const b: u8 = @intFromFloat((1 - t) * 255); - return .fromRgb(r, 0, b); - }, - }; - } - - pub fn view(self: *const Heatmap, allocator: std.mem.Allocator) []const u8 { - if (self.rows == 0 or self.cols == 0) return ""; - - const mm = self.getMinMax(); - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Title - if (self.title.len > 0) { - writer.writeAll(self.title_style.render(allocator, self.title) catch self.title) catch {}; - writer.writeByte('\n') catch {}; - } - - // Column labels - if (self.col_labels.len > 0) { - // Padding for row labels - const label_pad: usize = if (self.row_labels.len > 0) maxLabelWidth(self.row_labels) + 1 else 0; - for (0..label_pad) |_| writer.writeByte(' ') catch {}; - - for (self.col_labels, 0..) |label, ci| { - if (ci >= self.cols) break; - const cw = self.cell_width; - if (label.len >= cw) { - writer.writeAll(label[0..cw]) catch {}; - } else { - writer.writeAll(label) catch {}; - for (0..cw - label.len) |_| writer.writeByte(' ') catch {}; - } - } - writer.writeByte('\n') catch {}; - } - - // Data rows - for (0..self.rows) |r| { - // Row label - if (r < self.row_labels.len) { - const max_lw = maxLabelWidth(self.row_labels); - const label = self.row_labels[r]; - // Right-align - if (label.len < max_lw) { - for (0..max_lw - label.len) |_| writer.writeByte(' ') catch {}; - } - writer.writeAll(label) catch {}; - writer.writeByte(' ') catch {}; - } - - // Cells - for (0..self.cols) |c| { - const idx = r * self.cols + c; - const val = if (idx < self.data.len) self.data[idx] else 0; - const t = normalize(val, mm.min, mm.max); - const bg_color = self.scaleColor(t); - - var cs = style_mod.Style{}; - cs = cs.bg(bg_color); - cs = cs.inline_style(true); - - if (self.show_values and self.cell_width >= 3) { - const val_str = std.fmt.allocPrint(allocator, "{d:.0}", .{val}) catch " "; - const padded = padCenter(allocator, val_str, self.cell_width); - // Choose foreground for contrast - cs = cs.fg(if (t > 0.5) .black else .white); - writer.writeAll(cs.render(allocator, padded) catch padded) catch {}; - } else { - var cell_buf: [8]u8 = undefined; - const cw = @min(self.cell_width, 8); - for (0..cw) |i| cell_buf[i] = ' '; - writer.writeAll(cs.render(allocator, cell_buf[0..cw]) catch cell_buf[0..cw]) catch {}; - } - } - if (r < self.rows - 1) writer.writeByte('\n') catch {}; - } - - // Legend - if (self.show_legend) { - writer.writeAll("\n\n") catch {}; - const steps: usize = 10; - for (0..steps) |s| { - const t = @as(f64, @floatFromInt(s)) / @as(f64, @floatFromInt(steps - 1)); - const c = self.scaleColor(t); - var ls = style_mod.Style{}; - ls = ls.bg(c); - ls = ls.inline_style(true); - writer.writeAll(ls.render(allocator, " ") catch " ") catch {}; - } - const min_str = std.fmt.allocPrint(allocator, " {d:.0}", .{mm.min}) catch ""; - const max_str = std.fmt.allocPrint(allocator, " - {d:.0}", .{mm.max}) catch ""; - writer.writeAll(min_str) catch {}; - writer.writeAll(max_str) catch {}; - } - - return result.toArrayList().items; - } - - fn maxLabelWidth(labels: []const []const u8) usize { - var max: usize = 0; - for (labels) |l| max = @max(max, l.len); - return max; - } - - fn padCenter(allocator: std.mem.Allocator, text: []const u8, target_width: u8) []const u8 { - if (text.len >= target_width) return text[0..target_width]; - const total_pad = target_width - text.len; - const left_pad = total_pad / 2; - const right_pad = total_pad - left_pad; - var buf = std.array_list.Managed(u8).init(allocator); - for (0..left_pad) |_| buf.append(' ') catch {}; - buf.appendSlice(text) catch {}; - for (0..right_pad) |_| buf.append(' ') catch {}; - return buf.items; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig deleted file mode 100644 index fce7398..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/help.zig +++ /dev/null @@ -1,238 +0,0 @@ -//! Help component for displaying key bindings. -//! Shows keyboard shortcuts and their descriptions. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); -const join = @import("../layout/join.zig"); - -pub const Help = struct { - allocator: std.mem.Allocator, - - // Bindings - bindings: std.array_list.Managed(Binding), - - // Appearance - separator: []const u8, - ellipsis: []const u8, - max_width: ?u16, - short_mode: bool, - - // Styling - key_style: style_mod.Style, - desc_style: style_mod.Style, - sep_style: style_mod.Style, - - pub const Binding = struct { - key: []const u8, - description: []const u8, - short_desc: ?[]const u8, - }; - - pub fn init(allocator: std.mem.Allocator) Help { - return .{ - .allocator = allocator, - .bindings = std.array_list.Managed(Binding).init(allocator), - .separator = " • ", - .ellipsis = "...", - .max_width = null, - .short_mode = false, - .key_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .desc_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(18)); - s = s.inline_style(true); - break :blk s; - }, - .sep_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *Help) void { - self.bindings.deinit(); - } - - /// Create a Help component from a KeyMap - pub fn fromKeyMap(allocator: std.mem.Allocator, keymap: anytype) !Help { - var help = Help.init(allocator); - const bindings = try keymap.toHelpBindings(allocator); - try help.setBindings(bindings); - return help; - } - - /// Add a key binding - pub fn addBinding(self: *Help, key: []const u8, description: []const u8) !void { - try self.bindings.append(.{ - .key = key, - .description = description, - .short_desc = null, - }); - } - - /// Add a key binding with short description - pub fn addBindingShort(self: *Help, key: []const u8, description: []const u8, short_desc: []const u8) !void { - try self.bindings.append(.{ - .key = key, - .description = description, - .short_desc = short_desc, - }); - } - - /// Set bindings from a list - pub fn setBindings(self: *Help, bindings: []const Binding) !void { - self.bindings.clearRetainingCapacity(); - try self.bindings.appendSlice(bindings); - } - - /// Clear all bindings - pub fn clear(self: *Help) void { - self.bindings.clearRetainingCapacity(); - } - - /// Set max width (enables truncation) - pub fn setMaxWidth(self: *Help, width: u16) void { - self.max_width = width; - } - - /// Enable/disable short mode - pub fn setShortMode(self: *Help, short: bool) void { - self.short_mode = short; - } - - /// Render the help - pub fn view(self: *const Help, allocator: std.mem.Allocator) ![]const u8 { - if (self.bindings.items.len == 0) { - return try allocator.dupe(u8, ""); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var total_width: usize = 0; - - for (self.bindings.items, 0..) |binding, i| { - // Calculate this binding's width - const desc = if (self.short_mode and binding.short_desc != null) - binding.short_desc.? - else - binding.description; - - const binding_text = try std.fmt.allocPrint(allocator, "{s} {s}", .{ binding.key, desc }); - const binding_width = measure.width(binding_text); - - // Check if we need truncation - if (self.max_width) |max_w| { - const sep_width = if (i > 0) measure.width(self.separator) else 0; - if (total_width + sep_width + binding_width > max_w) { - // Add ellipsis and stop - if (i > 0) { - const sep_styled = try self.sep_style.render(allocator, self.separator); - try writer.writeAll(sep_styled); - } - try writer.writeAll(self.ellipsis); - break; - } - } - - // Add separator - if (i > 0) { - const sep_styled = try self.sep_style.render(allocator, self.separator); - try writer.writeAll(sep_styled); - total_width += measure.width(self.separator); - } - - // Add key - const key_styled = try self.key_style.render(allocator, binding.key); - try writer.writeAll(key_styled); - - // Add description - try writer.writeByte(' '); - const desc_styled = try self.desc_style.render(allocator, desc); - try writer.writeAll(desc_styled); - - total_width += binding_width; - } - - return result.toOwnedSlice(); - } - - /// Render as a vertical list - pub fn viewVertical(self: *const Help, allocator: std.mem.Allocator) ![]const u8 { - if (self.bindings.items.len == 0) { - return try allocator.dupe(u8, ""); - } - - // Find max key width - var max_key_width: usize = 0; - for (self.bindings.items) |binding| { - max_key_width = @max(max_key_width, measure.width(binding.key)); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (self.bindings.items, 0..) |binding, i| { - if (i > 0) try writer.writeByte('\n'); - - // Key with padding - const key_styled = try self.key_style.render(allocator, binding.key); - try writer.writeAll(key_styled); - - const key_width = measure.width(binding.key); - for (0..(max_key_width - key_width + 2)) |_| { - try writer.writeByte(' '); - } - - // Description - const desc = if (self.short_mode and binding.short_desc != null) - binding.short_desc.? - else - binding.description; - const desc_styled = try self.desc_style.render(allocator, desc); - try writer.writeAll(desc_styled); - } - - return result.toOwnedSlice(); - } -}; - -/// Common key binding sets -pub const CommonBindings = struct { - pub const navigation = [_]Help.Binding{ - .{ .key = "↑/k", .description = "Move up", .short_desc = "up" }, - .{ .key = "↓/j", .description = "Move down", .short_desc = "down" }, - .{ .key = "←/h", .description = "Move left", .short_desc = "left" }, - .{ .key = "→/l", .description = "Move right", .short_desc = "right" }, - }; - - pub const quit = Help.Binding{ - .key = "q", - .description = "Quit", - .short_desc = "quit", - }; - - pub const enter = Help.Binding{ - .key = "enter", - .description = "Select", - .short_desc = "select", - }; - - pub const escape = Help.Binding{ - .key = "esc", - .description = "Cancel", - .short_desc = "cancel", - }; -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig deleted file mode 100644 index e8bbfb7..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/keybinding.zig +++ /dev/null @@ -1,114 +0,0 @@ -//! Keybinding management component. -//! Provides structured key binding definitions with matching and help integration. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const Key = keys.Key; -const KeyEvent = keys.KeyEvent; -const Modifiers = keys.Modifiers; -const Help = @import("help.zig").Help; - -/// A single key binding with description and enabled state -pub const KeyBinding = struct { - key_event: KeyEvent, - description: []const u8, - short_desc: ?[]const u8 = null, - enabled: bool = true, - - /// Check if a key event matches this binding - pub fn matches(self: *const KeyBinding, event: KeyEvent) bool { - if (!self.enabled) return false; - return self.key_event.eql(event); - } - - /// Get a display string for the key - pub fn keyDisplay(self: *const KeyBinding, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (self.key_event.modifiers.ctrl) try writer.writeAll("ctrl+"); - if (self.key_event.modifiers.alt) try writer.writeAll("alt+"); - if (self.key_event.modifiers.shift) try writer.writeAll("shift+"); - if (self.key_event.modifiers.super) try writer.writeAll("super+"); - - switch (self.key_event.key) { - .char => |c| { - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch 0; - try writer.writeAll(buf[0..len]); - }, - else => try writer.writeAll(self.key_event.key.name()), - } - - return result.toOwnedSlice(); - } -}; - -/// A collection of key bindings with matching and management -pub const KeyMap = struct { - bindings: std.array_list.Managed(KeyBinding), - - pub fn init(allocator: std.mem.Allocator) KeyMap { - return .{ - .bindings = std.array_list.Managed(KeyBinding).init(allocator), - }; - } - - pub fn deinit(self: *KeyMap) void { - self.bindings.deinit(); - } - - /// Add a key binding - pub fn add(self: *KeyMap, binding: KeyBinding) !void { - try self.bindings.append(binding); - } - - /// Add a simple character binding - pub fn addChar(self: *KeyMap, c: u21, description: []const u8) !void { - try self.bindings.append(.{ - .key_event = KeyEvent.char(c), - .description = description, - }); - } - - /// Add a ctrl+character binding - pub fn addCtrl(self: *KeyMap, c: u21, description: []const u8) !void { - try self.bindings.append(.{ - .key_event = KeyEvent.ctrl(c), - .description = description, - }); - } - - /// Find the first matching binding for an event - pub fn match(self: *const KeyMap, event: KeyEvent) ?*const KeyBinding { - for (self.bindings.items) |*binding| { - if (binding.matches(event)) return binding; - } - return null; - } - - /// Enable or disable a binding by description - pub fn setEnabled(self: *KeyMap, description: []const u8, enabled: bool) void { - for (self.bindings.items) |*binding| { - if (std.mem.eql(u8, binding.description, description)) { - binding.enabled = enabled; - } - } - } - - /// Convert to Help.Binding format for use with Help component - pub fn toHelpBindings(self: *const KeyMap, allocator: std.mem.Allocator) ![]Help.Binding { - var result = std.array_list.Managed(Help.Binding).init(allocator); - for (self.bindings.items) |*binding| { - if (!binding.enabled) continue; - const key_str = try binding.keyDisplay(allocator); - try result.append(.{ - .key = key_str, - .description = binding.description, - .short_desc = binding.short_desc, - }); - } - return result.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig deleted file mode 100644 index 5cf72f5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/list.zig +++ /dev/null @@ -1,490 +0,0 @@ -//! Selectable list component. -//! Displays a list of items with selection and optional filtering. - -const std = @import("std"); -const Writer = std.Io.Writer; -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 { - allocator: std.mem.Allocator, - - // Items - items: std.array_list.Managed(Item), - filtered_indices: std.array_list.Managed(usize), - - // Selection - cursor: usize, - selected: std.AutoHashMap(usize, void), - - // Filtering - filter_text: std.array_list.Managed(u8), - filter_enabled: bool, - - // Appearance - height: u16, - y_offset: usize, - - // Styling - item_style: style_mod.Style, - selected_style: style_mod.Style, - cursor_style: style_mod.Style, - filter_style: style_mod.Style, - - // Symbols - cursor_symbol: []const u8, - selected_symbol: []const u8, - unselected_symbol: []const u8, - - // Focus - focused: bool, - - // Behavior - multi_select: bool, - wrap_around: bool, - - // Status - status_message: ?[]const u8, - show_item_count: bool, - - const Self = @This(); - - pub const Item = struct { - value: T, - title: []const u8, - description: []const u8, - enabled: bool, - - pub fn init(value: T, title: []const u8) Item { - return .{ - .value = value, - .title = title, - .description = "", - .enabled = true, - }; - } - - pub fn withDescription(value: T, title: []const u8, desc: []const u8) Item { - return .{ - .value = value, - .title = title, - .description = desc, - .enabled = true, - }; - } - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .items = std.array_list.Managed(Item).init(allocator), - .filtered_indices = std.array_list.Managed(usize).init(allocator), - .cursor = 0, - .selected = std.AutoHashMap(usize, void).init(allocator), - .filter_text = std.array_list.Managed(u8).init(allocator), - .filter_enabled = false, - .height = 10, - .y_offset = 0, - .item_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .selected_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.magenta); - s = s.inline_style(true); - break :blk s; - }, - .filter_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .cursor_symbol = "> ", - .selected_symbol = "[x] ", - .unselected_symbol = "[ ] ", - .focused = true, - .multi_select = false, - .wrap_around = true, - .status_message = null, - .show_item_count = false, - }; - } - - pub fn deinit(self: *Self) void { - self.items.deinit(); - self.filtered_indices.deinit(); - self.selected.deinit(); - self.filter_text.deinit(); - } - - /// Add an item to the list - pub fn addItem(self: *Self, item: Item) !void { - try self.items.append(item); - try self.updateFilter(); - } - - /// Add multiple items - pub fn addItems(self: *Self, items: []const Item) !void { - try self.items.appendSlice(items); - try self.updateFilter(); - } - - /// Set items (replaces all) - pub fn setItems(self: *Self, items: []const Item) !void { - self.items.clearRetainingCapacity(); - try self.items.appendSlice(items); - self.cursor = 0; - self.y_offset = 0; - try self.updateFilter(); - } - - /// Clear all items - pub fn clear(self: *Self) void { - self.items.clearRetainingCapacity(); - self.filtered_indices.clearRetainingCapacity(); - self.selected.clearRetainingCapacity(); - self.cursor = 0; - self.y_offset = 0; - } - - /// Get selected item - pub fn selectedItem(self: *const Self) ?*const Item { - const visible = self.visibleItems(); - if (self.cursor < visible.len) { - const idx = visible[self.cursor]; - return &self.items.items[idx]; - } - return null; - } - - /// Get selected value - pub fn selectedValue(self: *const Self) ?T { - if (self.selectedItem()) |item| { - return item.value; - } - return null; - } - - /// Get all selected items (for multi-select) - pub fn selectedItems(self: *const Self, allocator: std.mem.Allocator) ![]const *const Item { - var result = std.array_list.Managed(*const Item).init(allocator); - var iter = self.selected.keyIterator(); - while (iter.next()) |idx| { - if (idx.* < self.items.items.len) { - try result.append(&self.items.items[idx.*]); - } - } - return result.toOwnedSlice(); - } - - /// Move cursor up - pub fn cursorUp(self: *Self) void { - const visible = self.visibleItems(); - if (visible.len == 0) return; - - if (self.cursor > 0) { - self.cursor -= 1; - } else if (self.wrap_around) { - self.cursor = visible.len - 1; - } - - self.ensureVisible(); - } - - /// Move cursor down - pub fn cursorDown(self: *Self) void { - const visible = self.visibleItems(); - if (visible.len == 0) return; - - if (self.cursor < visible.len - 1) { - self.cursor += 1; - } else if (self.wrap_around) { - self.cursor = 0; - } - - self.ensureVisible(); - } - - /// Page up - pub fn pageUp(self: *Self) void { - if (self.cursor >= self.height) { - self.cursor -= self.height; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - /// Page down - pub fn pageDown(self: *Self) void { - const visible = self.visibleItems(); - if (self.cursor + self.height < visible.len) { - self.cursor += self.height; - } else if (visible.len > 0) { - self.cursor = visible.len - 1; - } - self.ensureVisible(); - } - - /// Go to first item - pub fn gotoFirst(self: *Self) void { - self.cursor = 0; - self.y_offset = 0; - } - - /// Go to last item - pub fn gotoLast(self: *Self) void { - const visible = self.visibleItems(); - if (visible.len > 0) { - self.cursor = visible.len - 1; - self.ensureVisible(); - } - } - - /// Toggle selection of current item - pub fn toggleSelection(self: *Self) void { - const visible = self.visibleItems(); - if (self.cursor >= visible.len) return; - - const idx = visible[self.cursor]; - - if (self.multi_select) { - if (self.selected.contains(idx)) { - _ = self.selected.remove(idx); - } else { - self.selected.put(idx, {}) catch {}; - } - } else { - self.selected.clearRetainingCapacity(); - self.selected.put(idx, {}) catch {}; - } - } - - /// Select current item - pub fn selectCurrent(self: *Self) void { - const visible = self.visibleItems(); - if (self.cursor >= visible.len) return; - - const idx = visible[self.cursor]; - if (!self.multi_select) { - self.selected.clearRetainingCapacity(); - } - self.selected.put(idx, {}) catch {}; - } - - /// Enable filtering - pub fn enableFilter(self: *Self) void { - self.filter_enabled = true; - } - - /// Disable filtering - pub fn disableFilter(self: *Self) void { - self.filter_enabled = false; - self.filter_text.clearRetainingCapacity(); - self.updateFilter() catch {}; - } - - /// Set filter text - pub fn setFilter(self: *Self, text: []const u8) !void { - self.filter_text.clearRetainingCapacity(); - try self.filter_text.appendSlice(text); - try self.updateFilter(); - } - - /// Set focused state (for use with FocusGroup). - pub fn focus(self: *Self) void { - self.focused = true; - } - - /// Clear focused state (for use with FocusGroup). - pub fn blur(self: *Self) void { - self.focused = false; - } - - /// Handle key event - pub fn handleKey(self: *Self, key: keys.KeyEvent) void { - if (!self.focused) return; - if (self.filter_enabled and key.key == .char and !key.modifiers.ctrl) { - // Add to filter - const c = key.key.char; - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch return; - self.filter_text.appendSlice(buf[0..len]) catch {}; - self.updateFilter() catch {}; - return; - } - - if (self.filter_enabled and key.key == .backspace) { - if (self.filter_text.items.len > 0) { - _ = self.filter_text.pop(); - self.updateFilter() catch {}; - } - return; - } - - switch (key.key) { - .up => self.cursorUp(), - .down => self.cursorDown(), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoFirst(), - .end => self.gotoLast(), - .space => if (self.multi_select) self.toggleSelection(), - .enter => self.selectCurrent(), - .char => |c| { - switch (c) { - 'j' => self.cursorDown(), - 'k' => self.cursorUp(), - 'g' => self.gotoFirst(), - 'G' => self.gotoLast(), - '/' => self.enableFilter(), - else => {}, - } - }, - .escape => if (self.filter_enabled) self.disableFilter(), - else => {}, - } - } - - fn visibleItems(self: *const Self) []const usize { - return self.filtered_indices.items; - } - - pub fn updateFilter(self: *Self) !void { - self.filtered_indices.clearRetainingCapacity(); - - if (self.filter_text.items.len == 0) { - for (0..self.items.items.len) |i| { - try self.filtered_indices.append(i); - } - } else { - var scored = std.array_list.Managed(fuzzy.Ranked).init(self.allocator); - defer scored.deinit(); - - for (self.items.items, 0..) |item, i| { - const s = fuzzy.scoreIgnoreCase(item.title, self.filter_text.items); - if (s > 0) try scored.append(.{ .index = i, .score = s }); - } - - 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); - - for (scored.items) |s| { - try self.filtered_indices.append(s.index); - } - } - - 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 ensureVisible(self: *Self) void { - if (self.cursor < self.y_offset) { - self.y_offset = self.cursor; - } else if (self.cursor >= self.y_offset + self.height) { - self.y_offset = self.cursor - self.height + 1; - } - } - - /// Render the list - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Filter line - if (self.filter_enabled) { - const filter_line = try std.fmt.allocPrint(allocator, "Filter: {s}", .{self.filter_text.items}); - const styled = try self.filter_style.render(allocator, filter_line); - try writer.writeAll(styled); - try writer.writeByte('\n'); - } - - const visible = self.visibleItems(); - - // Render visible items - var rendered: usize = 0; - while (rendered < self.height) : (rendered += 1) { - if (rendered > 0) try writer.writeByte('\n'); - - const idx = self.y_offset + rendered; - if (idx < visible.len) { - const item_idx = visible[idx]; - const item = self.items.items[item_idx]; - - // Cursor - if (idx == self.cursor) { - const cursor_styled = try self.cursor_style.render(allocator, self.cursor_symbol); - try writer.writeAll(cursor_styled); - } else { - for (0..self.cursor_symbol.len) |_| { - try writer.writeByte(' '); - } - } - - // Selection indicator (multi-select) - if (self.multi_select) { - if (self.selected.contains(item_idx)) { - const sel_styled = try self.selected_style.render(allocator, self.selected_symbol); - try writer.writeAll(sel_styled); - } else { - try writer.writeAll(self.unselected_symbol); - } - } - - // Item text - const item_rendered = if (idx == self.cursor) - try self.cursor_style.render(allocator, item.title) - else if (self.selected.contains(item_idx)) - try self.selected_style.render(allocator, item.title) - else - try self.item_style.render(allocator, item.title); - - try writer.writeAll(item_rendered); - - // Description - if (item.description.len > 0) { - try writer.writeAll(" - "); - try writer.writeAll(item.description); - } - } - } - - // Status bar - if (self.show_item_count or self.status_message != null) { - try writer.writeAll("\n"); - if (self.show_item_count) { - const count_str = try std.fmt.allocPrint(allocator, "{d}/{d} items", .{ - visible.len, - self.items.items.len, - }); - const count_styled = try self.filter_style.render(allocator, count_str); - try writer.writeAll(count_styled); - } - if (self.status_message) |msg| { - if (self.show_item_count) try writer.writeAll(" "); - try writer.writeAll(msg); - } - } - - return result.toOwnedSlice(); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig deleted file mode 100644 index e29ef6b..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/markdown.zig +++ /dev/null @@ -1,350 +0,0 @@ -//! Markdown renderer for terminal output. -//! Converts a subset of markdown to ANSI-styled text. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const border_mod = @import("../style/border.zig"); - -pub const Markdown = struct { - // Styling - h1_style: style_mod.Style, - h2_style: style_mod.Style, - h3_style: style_mod.Style, - bold_style: style_mod.Style, - italic_style: style_mod.Style, - code_style: style_mod.Style, - code_block_style: style_mod.Style, - code_block_border: style_mod.Style, - link_style: style_mod.Style, - blockquote_style: style_mod.Style, - blockquote_bar: style_mod.Style, - list_bullet_style: style_mod.Style, - hr_style: style_mod.Style, - text_style: style_mod.Style, - - // Layout - width: u16, - hr_char: []const u8, - - pub fn init() Markdown { - return .{ - .h1_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.magenta); - s = s.underline(true); - s = s.inline_style(true); - break :blk s; - }, - .h2_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .h3_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - .bold_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .italic_style = blk: { - var s = style_mod.Style{}; - s = s.italic(true); - s = s.inline_style(true); - break :blk s; - }, - .code_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.bg(.fromRgb(40, 40, 40)); - s = s.inline_style(true); - break :blk s; - }, - .code_block_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - .code_block_border = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - .link_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.underline(true); - s = s.inline_style(true); - break :blk s; - }, - .blockquote_style = blk: { - var s = style_mod.Style{}; - s = s.italic(true); - s = s.fg(.gray(14)); - s = s.inline_style(true); - break :blk s; - }, - .blockquote_bar = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - .list_bullet_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .hr_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - .text_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .width = 80, - .hr_char = "─", - }; - } - - /// Render markdown text to styled terminal output. - pub fn render(self: *const Markdown, allocator: std.mem.Allocator, source: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - errdefer result.deinit(); - const writer = &result.writer; - - // Intermediate styled spans get freed in bulk at end of render. - var arena = std.heap.ArenaAllocator.init(allocator); - defer arena.deinit(); - const tmp = arena.allocator(); - - var lines_iter = std.mem.splitScalar(u8, source, '\n'); - var in_code_block = false; - var first_line = true; - - while (lines_iter.next()) |line| { - if (!first_line) try writer.writeByte('\n'); - first_line = false; - - // Code block toggle - if (std.mem.startsWith(u8, std.mem.trimStart(u8, line, " "), "```")) { - in_code_block = !in_code_block; - if (in_code_block) { - // Opening fence - const bar = try self.code_block_border.render(tmp, "┌"); - try writer.writeAll(bar); - const dash = try self.code_block_border.render(tmp, "─"); - for (0..@min(self.width - 2, 40)) |_| { - try writer.writeAll(dash); - } - const end = try self.code_block_border.render(tmp, "┐"); - try writer.writeAll(end); - } else { - // Closing fence - const bar = try self.code_block_border.render(tmp, "└"); - try writer.writeAll(bar); - const dash = try self.code_block_border.render(tmp, "─"); - for (0..@min(self.width - 2, 40)) |_| { - try writer.writeAll(dash); - } - const end = try self.code_block_border.render(tmp, "┘"); - try writer.writeAll(end); - } - continue; - } - - if (in_code_block) { - const bar = try self.code_block_border.render(tmp, "│ "); - try writer.writeAll(bar); - const styled = try self.code_block_style.render(tmp, line); - try writer.writeAll(styled); - continue; - } - - const trimmed = std.mem.trimStart(u8, line, " "); - - // Horizontal rule - if (trimmed.len >= 3 and isAllChar(trimmed, '-')) { - const dash = try self.hr_style.render(tmp, self.hr_char); - for (0..@min(self.width, 60)) |_| { - try writer.writeAll(dash); - } - continue; - } - - if (trimmed.len >= 3 and isAllChar(trimmed, '*') and !std.mem.startsWith(u8, trimmed, "**")) { - const dash = try self.hr_style.render(tmp, self.hr_char); - for (0..@min(self.width, 60)) |_| { - try writer.writeAll(dash); - } - continue; - } - - // Headers - if (std.mem.startsWith(u8, trimmed, "### ")) { - const content = trimmed[4..]; - const styled = try self.h3_style.render(tmp, content); - try writer.writeAll(styled); - continue; - } - if (std.mem.startsWith(u8, trimmed, "## ")) { - const content = trimmed[3..]; - const styled = try self.h2_style.render(tmp, content); - try writer.writeAll(styled); - continue; - } - if (std.mem.startsWith(u8, trimmed, "# ")) { - const content = trimmed[2..]; - const styled = try self.h1_style.render(tmp, content); - try writer.writeAll(styled); - continue; - } - - // Blockquote - if (std.mem.startsWith(u8, trimmed, "> ")) { - const content = trimmed[2..]; - const bar = try self.blockquote_bar.render(tmp, "│ "); - try writer.writeAll(bar); - const styled = try self.blockquote_style.render(tmp, content); - try writer.writeAll(styled); - continue; - } - - // Unordered list - if (std.mem.startsWith(u8, trimmed, "- ") or std.mem.startsWith(u8, trimmed, "* ")) { - const indent = line.len - trimmed.len; - for (0..indent) |_| try writer.writeByte(' '); - const bullet = try self.list_bullet_style.render(tmp, "• "); - try writer.writeAll(bullet); - const content = trimmed[2..]; - const styled = try self.renderInline(tmp, content); - try writer.writeAll(styled); - continue; - } - - // Ordered list (simple: "1. ", "2. ", etc.) - if (trimmed.len >= 3 and trimmed[0] >= '0' and trimmed[0] <= '9') { - if (std.mem.indexOf(u8, trimmed[0..@min(4, trimmed.len)], ". ")) |dot_pos| { - const indent = line.len - trimmed.len; - for (0..indent) |_| try writer.writeByte(' '); - const num = try self.list_bullet_style.render(tmp, trimmed[0 .. dot_pos + 2]); - try writer.writeAll(num); - const content = trimmed[dot_pos + 2 ..]; - const styled = try self.renderInline(tmp, content); - try writer.writeAll(styled); - continue; - } - } - - // Empty line - if (trimmed.len == 0) { - continue; - } - - // Regular paragraph with inline formatting - const styled = try self.renderInline(tmp, line); - try writer.writeAll(styled); - } - - return result.toOwnedSlice(); - } - - /// Render inline formatting: **bold**, *italic*, `code`, [links](url) - /// `allocator` should be a short-lived/arena allocator: intermediate styled - /// spans are leaked into it (freed in bulk when the arena is reset). - fn renderInline(self: *const Markdown, allocator: std.mem.Allocator, text: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - errdefer result.deinit(); - const writer = &result.writer; - - var i: usize = 0; - while (i < text.len) { - // Bold: **text** - if (i + 1 < text.len and text[i] == '*' and text[i + 1] == '*') { - if (std.mem.indexOf(u8, text[i + 2 ..], "**")) |end| { - const content = text[i + 2 .. i + 2 + end]; - const styled = try self.bold_style.render(allocator, content); - try writer.writeAll(styled); - i += 4 + end; - continue; - } - } - - // Italic: *text* - if (text[i] == '*' and (i + 1 >= text.len or text[i + 1] != '*')) { - if (std.mem.indexOfScalar(u8, text[i + 1 ..], '*')) |end| { - const content = text[i + 1 .. i + 1 + end]; - const styled = try self.italic_style.render(allocator, content); - try writer.writeAll(styled); - i += 2 + end; - continue; - } - } - - // Inline code: `code` - if (text[i] == '`') { - if (std.mem.indexOfScalar(u8, text[i + 1 ..], '`')) |end| { - const content = text[i + 1 .. i + 1 + end]; - const styled = try self.code_style.render(allocator, content); - try writer.writeAll(styled); - i += 2 + end; - continue; - } - } - - // Link: [text](url) - if (text[i] == '[') { - if (std.mem.indexOfScalar(u8, text[i + 1 ..], ']')) |text_end| { - const link_text = text[i + 1 .. i + 1 + text_end]; - const after_bracket = i + 2 + text_end; - if (after_bracket < text.len and text[after_bracket] == '(') { - if (std.mem.indexOfScalar(u8, text[after_bracket + 1 ..], ')')) |url_end| { - const url = text[after_bracket + 1 .. after_bracket + 1 + url_end]; - const styled_text = try self.link_style.render(allocator, link_text); - try writer.writeAll(styled_text); - var dim = style_mod.Style{}; - dim = dim.fg(.gray(10)); - dim = dim.inline_style(true); - const url_str = try std.fmt.allocPrint(allocator, " ({s})", .{url}); - const styled_url = try dim.render(allocator, url_str); - try writer.writeAll(styled_url); - i = after_bracket + 2 + url_end; - continue; - } - } - } - } - - // Regular character - try writer.writeByte(text[i]); - i += 1; - } - - return result.toOwnedSlice(); - } - - fn isAllChar(s: []const u8, c: u8) bool { - for (s) |ch| { - if (ch != c and ch != ' ') return false; - } - return true; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig deleted file mode 100644 index ba34b01..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/menu_bar.zig +++ /dev/null @@ -1,576 +0,0 @@ -//! Menu bar component. -//! Horizontal menu bar with dropdown menus and keyboard navigation. - -const std = @import("std"); -const Writer = std.Io.Writer; -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"); - -pub fn MenuBar(comptime Action: type) type { - return struct { - const max_menus = 10; - const max_items = 20; - - // Menus - menus: [max_menus]?Menu, - menu_count: usize, - - // State - state: State, - active_menu: usize, - active_item: usize, - - // Result - selected_action: ?Action, - - // Styling - bar_style: style_mod.Style, - bar_item_style: style_mod.Style, - bar_active_style: style_mod.Style, - item_style: style_mod.Style, - item_active_style: style_mod.Style, - item_disabled_style: style_mod.Style, - separator_style: style_mod.Style, - shortcut_style: style_mod.Style, - border_chars: border_mod.BorderChars, - border_fg: Color, - - // Layout - gap: usize, - - const Self = @This(); - - pub const State = enum { - closed, - bar_focused, - dropdown_open, - }; - - pub const MenuItem = union(enum) { - action: ActionItem, - separator: void, - }; - - pub const ActionItem = struct { - label: []const u8, - shortcut_display: []const u8, - action: Action, - enabled: bool, - checked: ?bool, - }; - - pub const Menu = struct { - label: []const u8, - accelerator: ?u8, - items: [max_items]?MenuItem, - item_count: usize, - }; - - pub fn init() Self { - return .{ - .menus = [_]?Menu{null} ** max_menus, - .menu_count = 0, - .state = .closed, - .active_menu = 0, - .active_item = 0, - .selected_action = null, - .bar_style = blk: { - var s = style_mod.Style{}; - s = s.bg(.fromRgb(40, 40, 50)); - s = s.inline_style(true); - break :blk s; - }, - .bar_item_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(18)); - s = s.inline_style(true); - break :blk s; - }, - .bar_active_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.white); - s = s.bg(.fromRgb(60, 60, 80)); - s = s.inline_style(true); - break :blk s; - }, - .item_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(18)); - s = s.inline_style(true); - break :blk s; - }, - .item_active_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.white); - s = s.bg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .item_disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - .separator_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - .shortcut_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .border_chars = .normal, - .border_fg = .gray(14), - .gap = 2, - }; - } - - /// Add a menu to the bar. - pub fn addMenu(self: *Self, label: []const u8, accelerator: ?u8, items: []const MenuItem) void { - if (self.menu_count >= max_menus) return; - - var menu = Menu{ - .label = label, - .accelerator = accelerator, - .items = [_]?MenuItem{null} ** max_items, - .item_count = 0, - }; - - for (items) |item| { - if (menu.item_count >= max_items) break; - menu.items[menu.item_count] = item; - menu.item_count += 1; - } - - self.menus[self.menu_count] = menu; - self.menu_count += 1; - } - - /// Create an action menu item. - pub fn action(label: []const u8, shortcut: []const u8, act: Action) MenuItem { - return .{ .action = .{ - .label = label, - .shortcut_display = shortcut, - .action = act, - .enabled = true, - .checked = null, - } }; - } - - /// Create a disabled action menu item. - pub fn disabledAction(label: []const u8, shortcut: []const u8, act: Action) MenuItem { - return .{ .action = .{ - .label = label, - .shortcut_display = shortcut, - .action = act, - .enabled = false, - .checked = null, - } }; - } - - /// Create a checked action menu item. - pub fn checkedAction(label: []const u8, act: Action, is_checked: bool) MenuItem { - return .{ .action = .{ - .label = label, - .shortcut_display = "", - .action = act, - .enabled = true, - .checked = is_checked, - } }; - } - - /// Create a separator. - pub fn separator() MenuItem { - return .{ .separator = {} }; - } - - // ── State management ───────────────────────── - - pub fn isOpen(self: *const Self) bool { - return self.state != .closed; - } - - pub fn activate(self: *Self) void { - self.state = .bar_focused; - self.selected_action = null; - } - - pub fn deactivate(self: *Self) void { - self.state = .closed; - } - - pub fn getSelectedAction(self: *Self) ?Action { - const act = self.selected_action; - self.selected_action = null; - return act; - } - - // ── Input handling ─────────────────────────── - - pub fn handleKey(self: *Self, key: keys.KeyEvent) bool { - // Check for Alt+letter accelerators - if (key.modifiers.alt and key.key == .char) { - const c = key.key.char; - for (self.menus[0..self.menu_count], 0..) |maybe_menu, i| { - if (maybe_menu) |menu| { - if (menu.accelerator) |acc| { - if (toLowerChar(c) == toLowerChar(acc)) { - self.active_menu = i; - self.active_item = 0; - self.state = .dropdown_open; - self.skipToNextEnabled(); - return true; - } - } - } - } - } - - switch (self.state) { - .closed => return false, - .bar_focused => return self.handleBarKey(key), - .dropdown_open => return self.handleDropdownKey(key), - } - } - - fn handleBarKey(self: *Self, key: keys.KeyEvent) bool { - switch (key.key) { - .left => { - if (self.active_menu > 0) { - self.active_menu -= 1; - } else if (self.menu_count > 0) { - self.active_menu = self.menu_count - 1; - } - return true; - }, - .right => { - if (self.active_menu + 1 < self.menu_count) { - self.active_menu += 1; - } else { - self.active_menu = 0; - } - return true; - }, - .down, .enter => { - self.state = .dropdown_open; - self.active_item = 0; - self.skipToNextEnabled(); - return true; - }, - .escape => { - self.state = .closed; - return true; - }, - else => return false, - } - } - - fn handleDropdownKey(self: *Self, key: keys.KeyEvent) bool { - switch (key.key) { - .up => { - self.moveCursorUp(); - return true; - }, - .down => { - self.moveCursorDown(); - return true; - }, - .left => { - if (self.active_menu > 0) { - self.active_menu -= 1; - } else if (self.menu_count > 0) { - self.active_menu = self.menu_count - 1; - } - self.active_item = 0; - self.skipToNextEnabled(); - return true; - }, - .right => { - if (self.active_menu + 1 < self.menu_count) { - self.active_menu += 1; - } else { - self.active_menu = 0; - } - self.active_item = 0; - self.skipToNextEnabled(); - return true; - }, - .enter => { - self.selectCurrentItem(); - return true; - }, - .escape => { - self.state = .bar_focused; - return true; - }, - else => return false, - } - } - - fn moveCursorUp(self: *Self) void { - const menu = self.menus[self.active_menu] orelse return; - if (menu.item_count == 0) return; - - var pos = self.active_item; - var attempts: usize = 0; - while (attempts < menu.item_count) : (attempts += 1) { - if (pos == 0) { - pos = menu.item_count - 1; - } else { - pos -= 1; - } - if (self.isSelectableItem(menu.items[pos])) { - self.active_item = pos; - return; - } - } - } - - fn moveCursorDown(self: *Self) void { - const menu = self.menus[self.active_menu] orelse return; - if (menu.item_count == 0) return; - - var pos = self.active_item; - var attempts: usize = 0; - while (attempts < menu.item_count) : (attempts += 1) { - pos = if (pos + 1 < menu.item_count) pos + 1 else 0; - if (self.isSelectableItem(menu.items[pos])) { - self.active_item = pos; - return; - } - } - } - - fn skipToNextEnabled(self: *Self) void { - const menu = self.menus[self.active_menu] orelse return; - if (menu.item_count == 0) return; - - if (self.isSelectableItem(menu.items[self.active_item])) return; - self.moveCursorDown(); - } - - fn isSelectableItem(_: *const Self, maybe_item: ?MenuItem) bool { - const item = maybe_item orelse return false; - return switch (item) { - .action => |a| a.enabled, - .separator => false, - }; - } - - fn selectCurrentItem(self: *Self) void { - const menu = self.menus[self.active_menu] orelse return; - if (self.active_item >= menu.item_count) return; - - const item = menu.items[self.active_item] orelse return; - switch (item) { - .action => |a| { - if (a.enabled) { - self.selected_action = a.action; - self.state = .closed; - } - }, - .separator => {}, - } - } - - fn toLowerChar(c: u21) u21 { - return if (c >= 'A' and c <= 'Z') c + 32 else c; - } - - // ── Rendering ─────────────────────────────── - - pub fn view(self: *const Self, allocator: std.mem.Allocator, term_width: usize) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Render menu bar - var bar_content: Writer.Allocating = .init(allocator); - const bar_writer = &bar_content.writer; - - try bar_writer.writeAll(" "); - - for (self.menus[0..self.menu_count], 0..) |maybe_menu, i| { - const menu = maybe_menu orelse continue; - - if (i > 0) { - for (0..self.gap) |_| try bar_writer.writeByte(' '); - } - - const is_active = (self.state != .closed and self.active_menu == i); - const menu_style = if (is_active) self.bar_active_style else self.bar_item_style; - const padded = try std.fmt.allocPrint(allocator, " {s} ", .{menu.label}); - const styled = try menu_style.render(allocator, padded); - try bar_writer.writeAll(styled); - } - - // Pad bar to terminal width - const bar_text = try bar_content.toOwnedSlice(); - const bar_width = measure.width(bar_text); - try writer.writeAll(bar_text); - if (bar_width < term_width) { - const pad_text = try allocator.alloc(u8, term_width - bar_width); - @memset(pad_text, ' '); - const styled_pad = try self.bar_style.render(allocator, pad_text); - try writer.writeAll(styled_pad); - } - - // Render dropdown if open - if (self.state == .dropdown_open) { - if (self.menus[self.active_menu]) |menu| { - const dropdown = try self.renderDropdown(allocator, menu); - try writer.writeByte('\n'); - try writer.writeAll(dropdown); - } - } - - return result.toOwnedSlice(); - } - - fn renderDropdown(self: *const Self, allocator: std.mem.Allocator, menu: Menu) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const w = &result.writer; - - // Calculate width - var max_label_width: usize = 0; - var max_shortcut_width: usize = 0; - for (menu.items[0..menu.item_count]) |maybe_item| { - const item = maybe_item orelse continue; - switch (item) { - .action => |a| { - const lw = measure.width(a.label) + if (a.checked != null) @as(usize, 2) else 0; - if (lw > max_label_width) max_label_width = lw; - const sw = measure.width(a.shortcut_display); - if (sw > max_shortcut_width) max_shortcut_width = sw; - }, - .separator => {}, - } - } - - const inner_width = max_label_width + max_shortcut_width + 4; // padding + gap - - // Calculate x offset for dropdown - var x_offset: usize = 1; - for (self.menus[0..self.active_menu]) |maybe_menu| { - if (maybe_menu) |m| { - x_offset += measure.width(m.label) + 2 + self.gap; - } - } - // Indent dropdown to align with menu item - for (0..x_offset) |_| try w.writeByte(' '); - - // Top border - try self.writeBorder(w, allocator, inner_width, .top); - try w.writeByte('\n'); - - // Items - for (menu.items[0..menu.item_count], 0..) |maybe_item, i| { - const item = maybe_item orelse continue; - - for (0..x_offset) |_| try w.writeByte(' '); - - switch (item) { - .separator => { - try self.writeBorder(w, allocator, inner_width, .middle); - }, - .action => |a| { - try self.writeBorderChar(w, allocator, .left); - - const is_active = (i == self.active_item); - const s = if (!a.enabled) self.item_disabled_style else if (is_active) self.item_active_style else self.item_style; - - // Build line content - var line: Writer.Allocating = .init(allocator); - const lw = &line.writer; - - try lw.writeByte(' '); - - // Check mark - if (a.checked) |checked| { - if (checked) { - try lw.writeAll("\u{2713} "); - } else { - try lw.writeAll(" "); - } - } - - try lw.writeAll(a.label); - - // Pad between label and shortcut - const label_width = measure.width(a.label) + if (a.checked != null) @as(usize, 2) else @as(usize, 0); - const gap_needed = inner_width -| label_width -| measure.width(a.shortcut_display) -| 2; - for (0..gap_needed) |_| try lw.writeByte(' '); - - if (a.shortcut_display.len > 0) { - try lw.writeAll(a.shortcut_display); - } - - try lw.writeByte(' '); - - const line_text = try line.toOwnedSlice(); - const styled = try s.render(allocator, line_text); - try w.writeAll(styled); - - try self.writeBorderChar(w, allocator, .right); - }, - } - - try w.writeByte('\n'); - } - - // Bottom border - for (0..x_offset) |_| try w.writeByte(' '); - try self.writeBorder(w, allocator, inner_width, .bottom); - - return result.toOwnedSlice(); - } - - const BorderPos = enum { top, middle, bottom }; - const BorderSide = enum { left, right }; - - fn writeBorder(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, width: usize, pos: BorderPos) !void { - var bs = style_mod.Style{}; - bs = bs.fg(self.border_fg); - bs = bs.inline_style(true); - - const bc = self.border_chars; - const cl = switch (pos) { - .top => bc.top_left, - .middle => if (bc.middle_left.len > 0) bc.middle_left else bc.vertical, - .bottom => bc.bottom_left, - }; - const cr = switch (pos) { - .top => bc.top_right, - .middle => if (bc.middle_right.len > 0) bc.middle_right else bc.vertical, - .bottom => bc.bottom_right, - }; - - try writer.writeAll(try bs.render(allocator, cl)); - for (0..width) |_| { - try writer.writeAll(try bs.render(allocator, bc.horizontal)); - } - try writer.writeAll(try bs.render(allocator, cr)); - } - - fn writeBorderChar(self: *const Self, writer: *Writer, allocator: std.mem.Allocator, side: BorderSide) !void { - var bs = style_mod.Style{}; - bs = bs.fg(self.border_fg); - bs = bs.inline_style(true); - const char = switch (side) { - .left => self.border_chars.vertical, - .right => self.border_chars.vertical, - }; - try writer.writeAll(try bs.render(allocator, char)); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig deleted file mode 100644 index e8a3a23..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/modal.zig +++ /dev/null @@ -1,761 +0,0 @@ -//! Modal/Popup/Overlay component. -//! State-managed dialog that captures focus, renders on top, and returns a result. -//! Supports confirmation dialogs, input prompts, selection menus, error popups, -//! and fully custom content. -//! -//! ## Quick Start -//! -//! ```zig -//! // Create an info modal -//! var modal = Modal.info("Notice", "Operation completed successfully."); -//! modal.show(); -//! -//! // In your update function: -//! modal.handleKey(key_event); -//! if (modal.getResult()) |res| { -//! switch (res) { -//! .button_pressed => |idx| { /* button at idx was pressed */ }, -//! .dismissed => { /* user pressed Escape */ }, -//! } -//! } -//! -//! // In your view function: -//! if (modal.isVisible()) { -//! return modal.viewWithBackdrop(allocator, ctx.width, ctx.height); -//! } -//! ``` -//! -//! ## Presets -//! -//! - `Modal.info(title, body)` — informational dialog with OK button (cyan border) -//! - `Modal.confirm(title, body)` — yes/no confirmation (yellow border) -//! - `Modal.warning(title, body)` — warning with OK button (yellow border) -//! - `Modal.err(title, body)` — error with OK button (red border) -//! - `Modal.init()` — blank modal for full custom configuration -//! -//! ## Focus Protocol -//! -//! Modal satisfies the focusable protocol (`focused`, `focus()`, `blur()`) and -//! can be registered with a `FocusGroup`. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const border_mod = @import("../style/border.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); -const place = @import("../layout/place.zig"); - -const max_buttons = 8; - -pub const Modal = struct { - // ── State ────────────────────────────────────────────────────────── - - visible: bool = false, - focused: bool = false, - result: ?Result = null, - - // ── Content ──────────────────────────────────────────────────────── - - title: []const u8 = "", - body: []const u8 = "", - footer: ?[]const u8 = null, - - // ── Buttons ──────────────────────────────────────────────────────── - - buttons: [max_buttons]?Button = [_]?Button{null} ** max_buttons, - button_count: usize = 0, - selected_button: usize = 0, - - // ── Layout ───────────────────────────────────────────────────────── - - width: Size = .{ .percent = 0.5 }, - height: Size = .auto, - h_position: f32 = 0.5, - v_position: f32 = 0.5, - padding: Padding = .{ .top = 1, .right = 2, .bottom = 1, .left = 2 }, - button_align: ButtonAlign = .right, - - // ── Behavior ─────────────────────────────────────────────────────── - - close_on_escape: bool = true, - - // ── Styling ──────────────────────────────────────────────────────── - - border_chars: border_mod.BorderChars = .rounded, - border_fg: Color = .gray(18), - content_bg: Color = .none, - title_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white }), - body_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(20) }), - footer_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(12), .italic_v = true }), - button_active_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white, .bg_color = .cyan }), - button_inactive_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(14) }), - backdrop: ?Backdrop = null, - - // ── Types ────────────────────────────────────────────────────────── - - pub const Result = union(enum) { - button_pressed: usize, - dismissed: void, - }; - - pub const Button = struct { - label: []const u8, - shortcut: ?keys.Key = null, - }; - - pub const Size = union(enum) { - fixed: u16, - percent: f32, - auto: void, - }; - - pub const Padding = struct { - top: u16 = 0, - right: u16 = 0, - bottom: u16 = 0, - left: u16 = 0, - - pub fn all(n: u16) Padding { - return .{ .top = n, .right = n, .bottom = n, .left = n }; - } - - pub fn symmetric(vert: u16, horiz: u16) Padding { - return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; - } - }; - - pub const ButtonAlign = enum { left, center, right }; - - pub const Backdrop = struct { - /// Fill character (UTF-8 string, e.g. " ", "░", "▒", "▓", "█"). - char: []const u8 = " ", - /// Style applied to the backdrop fill. - style: style_mod.Style = makeStyle(.{ .bg_color = .gray(3) }), - - /// Dark semi-transparent backdrop (default). - pub const dark = Backdrop{}; - - /// Slightly lighter backdrop. - pub const medium = Backdrop{ - .style = makeStyle(.{ .bg_color = .gray(5) }), - }; - - /// Light backdrop. - pub const light = Backdrop{ - .style = makeStyle(.{ .bg_color = .gray(8) }), - }; - - /// Clear backdrop — uses the terminal's default background color. - pub const clear = Backdrop{ - .style = makeStyle(.{}), - }; - - /// Light shade fill character (░). - pub const shade_light = Backdrop{ - .char = "░", - .style = makeStyle(.{ .fg_color = .gray(5) }), - }; - - /// Medium shade fill character (▒). - pub const shade_medium = Backdrop{ - .char = "▒", - .style = makeStyle(.{ .fg_color = .gray(5) }), - }; - - /// Dense shade fill character (▓). - pub const shade_dense = Backdrop{ - .char = "▓", - .style = makeStyle(.{ .fg_color = .gray(4) }), - }; - - /// Create a solid-color backdrop. - pub fn solid(bg_color: Color) Backdrop { - return .{ .style = makeStyle(.{ .bg_color = bg_color }) }; - } - - /// Create a backdrop with a custom fill character and foreground color. - pub fn custom(char_str: []const u8, fg_color: Color, bg_color: Color) Backdrop { - return .{ - .char = char_str, - .style = makeStyle(.{ .fg_color = fg_color, .bg_color = bg_color }), - }; - } - }; - - // ── Preset Constructors ──────────────────────────────────────────── - - /// Informational dialog with a single OK button and cyan accent. - pub fn info(title: []const u8, body: []const u8) Modal { - var m: Modal = .{ - .title = title, - .body = body, - .border_fg = .cyan, - .title_style = makeStyle(.{ .bold_v = true, .fg_color = .cyan }), - }; - m.addButton("OK", .enter); - return m; - } - - /// Yes/No confirmation dialog with yellow accent. - pub fn confirm(title: []const u8, body: []const u8) Modal { - var m: Modal = .{ - .title = title, - .body = body, - .border_fg = .yellow, - .title_style = makeStyle(.{ .bold_v = true, .fg_color = .yellow }), - }; - m.addButton("Yes", .{ .char = 'y' }); - m.addButton("No", .{ .char = 'n' }); - return m; - } - - /// Warning dialog with a single OK button and yellow accent. - pub fn warning(title: []const u8, body: []const u8) Modal { - var m: Modal = .{ - .title = title, - .body = body, - .border_fg = .yellow, - .title_style = makeStyle(.{ .bold_v = true, .fg_color = .yellow }), - }; - m.addButton("OK", .enter); - return m; - } - - /// Error dialog with a single OK button and red accent. - pub fn err(title: []const u8, body: []const u8) Modal { - var m: Modal = .{ - .title = title, - .body = body, - .border_fg = .red, - .title_style = makeStyle(.{ .bold_v = true, .fg_color = .red }), - }; - m.addButton("OK", .enter); - return m; - } - - /// Blank modal with no preset content — configure everything yourself. - pub fn init() Modal { - return .{}; - } - - // ── Button Management ────────────────────────────────────────────── - - /// Add a button with an optional keyboard shortcut. - pub fn addButton(self: *Modal, label: []const u8, shortcut: ?keys.Key) void { - if (self.button_count >= max_buttons) return; - self.buttons[self.button_count] = .{ - .label = label, - .shortcut = shortcut, - }; - self.button_count += 1; - } - - /// Remove all buttons. - pub fn clearButtons(self: *Modal) void { - self.buttons = [_]?Button{null} ** max_buttons; - self.button_count = 0; - self.selected_button = 0; - } - - // ── State Management ─────────────────────────────────────────────── - - /// Show the modal and reset its result. - pub fn show(self: *Modal) void { - self.visible = true; - self.focused = true; - self.result = null; - self.selected_button = 0; - } - - /// Hide the modal without setting a result. - pub fn hide(self: *Modal) void { - self.visible = false; - self.focused = false; - } - - pub fn isVisible(self: *const Modal) bool { - return self.visible; - } - - /// Returns the result once the modal has been closed. - pub fn getResult(self: *const Modal) ?Result { - return self.result; - } - - /// Reset visibility, focus, and result. - pub fn reset(self: *Modal) void { - self.visible = false; - self.focused = false; - self.result = null; - self.selected_button = 0; - } - - // ── Focusable Protocol ───────────────────────────────────────────── - - pub fn focus(self: *Modal) void { - self.focused = true; - } - - pub fn blur(self: *Modal) void { - self.focused = false; - } - - // ── Input Handling ───────────────────────────────────────────────── - - /// Process a key event. Only acts when visible and focused. - pub fn handleKey(self: *Modal, key: keys.KeyEvent) void { - if (!self.visible or !self.focused) return; - - // Check button shortcuts first - for (self.buttons[0..self.button_count], 0..) |maybe_btn, i| { - if (maybe_btn) |btn| { - if (btn.shortcut) |sc| { - if (sc.eql(key.key)) { - self.result = .{ .button_pressed = i }; - self.visible = false; - return; - } - } - } - } - - switch (key.key) { - .escape => { - if (self.close_on_escape) { - self.result = .dismissed; - self.visible = false; - } - }, - .enter => { - if (self.button_count > 0) { - self.result = .{ .button_pressed = self.selected_button }; - self.visible = false; - } - }, - .tab => { - if (self.button_count > 1) { - if (key.modifiers.shift) { - self.selected_button = if (self.selected_button > 0) - self.selected_button - 1 - else - self.button_count - 1; - } else { - self.selected_button = if (self.selected_button + 1 < self.button_count) - self.selected_button + 1 - else - 0; - } - } - }, - .left => { - if (self.button_count > 1 and self.selected_button > 0) { - self.selected_button -= 1; - } - }, - .right => { - if (self.button_count > 1 and self.selected_button + 1 < self.button_count) { - self.selected_button += 1; - } - }, - else => {}, - } - } - - // ── Rendering ────────────────────────────────────────────────────── - - /// Render the modal box centered on a transparent (space-filled) canvas. - /// Returns empty string if not visible. - pub fn view(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { - if (!self.visible) return try allocator.dupe(u8, ""); - - const box = try self.renderBox(allocator, term_width, term_height); - return try place.placeFloat(allocator, term_width, term_height, self.h_position, self.v_position, box); - } - - /// Render the modal with a styled backdrop filling the entire terminal. - /// Returns empty string if not visible. - pub fn viewWithBackdrop(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { - if (!self.visible) return try allocator.dupe(u8, ""); - - const bd = self.backdrop orelse Backdrop{}; - const box = try self.renderBox(allocator, term_width, term_height); - const box_w = measure.maxLineWidth(box); - const box_h = measure.height(box); - - // Position - const h_space = if (term_width > box_w) term_width - box_w else 0; - const v_space = if (term_height > box_h) term_height - box_h else 0; - const modal_x: usize = @intFromFloat(@as(f32, @floatFromInt(h_space)) * clamp01(self.h_position)); - const modal_y: usize = @intFromFloat(@as(f32, @floatFromInt(v_space)) * clamp01(self.v_position)); - - // Collect modal lines - var modal_lines_list = std.array_list.Managed([]const u8).init(allocator); - defer modal_lines_list.deinit(); - var box_iter = std.mem.splitScalar(u8, box, '\n'); - while (box_iter.next()) |line| try modal_lines_list.append(line); - const modal_lines = modal_lines_list.items; - - // Build full-screen output - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (0..term_height) |row| { - if (row > 0) try writer.writeByte('\n'); - - const in_modal = row >= modal_y and row < modal_y + box_h; - if (in_modal) { - const mline_idx = row - modal_y; - if (mline_idx < modal_lines.len) { - // Left backdrop - if (modal_x > 0) { - try writer.writeAll(try renderBackdropSegment(allocator, bd, modal_x)); - } - // Modal line - try writer.writeAll(modal_lines[mline_idx]); - // Right backdrop - const mline_w = measure.width(modal_lines[mline_idx]); - const right_start = modal_x + mline_w; - if (right_start < term_width) { - try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width - right_start)); - } - } else { - try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width)); - } - } else { - try writer.writeAll(try renderBackdropSegment(allocator, bd, term_width)); - } - } - - return result.toOwnedSlice(); - } - - /// Render just the modal box (no positioning or backdrop). - pub fn renderBox(self: *const Modal, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { - const bc = self.border_chars; - const box_w = self.computeWidth(term_width); - const inner_w: usize = if (box_w >= 2) box_w - 2 else 0; - const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); - const content_w: usize = if (inner_w >= pad_h) inner_w - pad_h else 0; - - // Compute height constraints - const box_h = self.computeHeight(term_height, inner_w); - const extras = self.computeExtras(); - const max_body_lines: usize = if (box_h > extras) box_h - extras else 0; - - // Inline styles for border and padding segments - var bdr_s = style_mod.Style{}; - bdr_s = bdr_s.fg(self.border_fg).inline_style(true); - if (!self.content_bg.isNone()) bdr_s = bdr_s.bg(self.content_bg); - - var pad_s = style_mod.Style{}; - pad_s = pad_s.inline_style(true); - if (!self.content_bg.isNone()) pad_s = pad_s.bg(self.content_bg); - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // ── Top border ── - try writer.writeAll(try bdr_s.render(allocator, bc.top_left)); - if (self.title.len > 0) { - const title_w = measure.width(self.title); - // top + space + title + space + remaining top chars - const used: usize = 3 + title_w; // 1 top + 1 space + title + 1 space - const remaining: usize = if (inner_w > used) inner_w - used else 0; - - try writer.writeAll(try bdr_s.render(allocator, bc.horizontal)); - try writer.writeAll(try bdr_s.render(allocator, " ")); - try writer.writeAll(try self.title_style.inline_style(true).render(allocator, self.title)); - try writer.writeAll(try bdr_s.render(allocator, " ")); - try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, remaining)); - } else { - try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); - } - try writer.writeAll(try bdr_s.render(allocator, bc.top_right)); - - // Helpers for inner lines - const styled_left = try bdr_s.render(allocator, bc.vertical); - const styled_right = try bdr_s.render(allocator, bc.vertical); - - // ── Top padding ── - for (0..self.padding.top) |_| { - try writer.writeByte('\n'); - try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - } - - // ── Body lines ── - var body_iter = std.mem.splitScalar(u8, self.body, '\n'); - var body_line_count: usize = 0; - while (body_iter.next()) |line| { - if (body_line_count >= max_body_lines) break; - body_line_count += 1; - - try writer.writeByte('\n'); - try writer.writeAll(styled_left); - - // Left padding - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); - - // Body text - var merged_body = self.body_style.inline_style(true); - if (!self.content_bg.isNone() and merged_body.background.isNone()) { - merged_body = merged_body.bg(self.content_bg); - } - try writer.writeAll(try merged_body.render(allocator, line)); - - // Right fill - const line_w = measure.width(line); - const fill: usize = if (content_w > line_w) content_w - line_w else 0; - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); - - try writer.writeAll(styled_right); - } - - // Pad body if fixed/percent height has more room - while (body_line_count < max_body_lines) : (body_line_count += 1) { - try writer.writeByte('\n'); - try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - } - - // ── Footer ── - if (self.footer) |footer_text| { - // Separator line - try writer.writeByte('\n'); - try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - - try writer.writeByte('\n'); - try writer.writeAll(styled_left); - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); - - var merged_footer = self.footer_style.inline_style(true); - if (!self.content_bg.isNone() and merged_footer.background.isNone()) { - merged_footer = merged_footer.bg(self.content_bg); - } - try writer.writeAll(try merged_footer.render(allocator, footer_text)); - - const fw = measure.width(footer_text); - const fill: usize = if (content_w > fw) content_w - fw else 0; - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); - try writer.writeAll(styled_right); - } - - // ── Buttons ── - if (self.button_count > 0) { - // Separator - try writer.writeByte('\n'); - try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - - // Render button row content - var btn_buf: Writer.Allocating = .init(allocator); - const btn_writer = &btn_buf.writer; - - for (self.buttons[0..self.button_count], 0..) |maybe_btn, i| { - if (maybe_btn) |btn| { - if (i > 0) { - try btn_writer.writeAll(try pad_s.render(allocator, " ")); - } - const label = try std.fmt.allocPrint(allocator, " {s} ", .{btn.label}); - var btn_style = if (i == self.selected_button) self.button_active_style else self.button_inactive_style; - btn_style = btn_style.inline_style(true); - if (!self.content_bg.isNone() and i != self.selected_button and btn_style.background.isNone()) { - btn_style = btn_style.bg(self.content_bg); - } - try btn_writer.writeAll(try btn_style.render(allocator, label)); - } - } - const btn_row = try btn_buf.toOwnedSlice(); - const btn_row_w = measure.width(btn_row); - - try writer.writeByte('\n'); - try writer.writeAll(styled_left); - - // Align buttons within inner_w - const left_spaces: usize = switch (self.button_align) { - .left => self.padding.left, - .center => if (inner_w > btn_row_w) (inner_w - btn_row_w) / 2 else 0, - .right => if (inner_w > btn_row_w + self.padding.right) - inner_w - btn_row_w - self.padding.right - else - 0, - }; - const right_spaces: usize = if (inner_w > left_spaces + btn_row_w) - inner_w - left_spaces - btn_row_w - else - 0; - - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, left_spaces))); - try writer.writeAll(btn_row); - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, right_spaces))); - - try writer.writeAll(styled_right); - } - - // ── Bottom padding ── - for (0..self.padding.bottom) |_| { - try writer.writeByte('\n'); - try self.writeEmptyInnerLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - } - - // ── Bottom border ── - try writer.writeByte('\n'); - try writer.writeAll(try bdr_s.render(allocator, bc.bottom_left)); - try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); - try writer.writeAll(try bdr_s.render(allocator, bc.bottom_right)); - - return result.toOwnedSlice(); - } - - // ── Private Helpers ──────────────────────────────────────────────── - - fn writeEmptyInnerLine( - self: *const Modal, - allocator: std.mem.Allocator, - writer: *Writer, - styled_left: []const u8, - styled_right: []const u8, - pad_s: style_mod.Style, - inner_w: usize, - ) !void { - _ = self; - try writer.writeAll(styled_left); - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, inner_w))); - try writer.writeAll(styled_right); - } - - fn computeWidth(self: *const Modal, term_width: usize) usize { - return switch (self.width) { - .fixed => |w| @min(@as(usize, w), term_width), - .percent => |p| @intFromFloat(@as(f32, @floatFromInt(term_width)) * clamp01(p)), - .auto => blk: { - const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); - var max_inner: usize = 0; - - // Title (in border): needs title_w + 4 - if (self.title.len > 0) { - max_inner = @max(max_inner, measure.width(self.title) + 4); - } - - // Content-area items need content_w + padding_h - var max_content: usize = 0; - - var body_iter = std.mem.splitScalar(u8, self.body, '\n'); - while (body_iter.next()) |line| { - max_content = @max(max_content, measure.width(line)); - } - - if (self.footer) |ft| { - max_content = @max(max_content, measure.width(ft)); - } - - var btn_w: usize = 0; - for (self.buttons[0..self.button_count]) |maybe_btn| { - if (maybe_btn) |btn| { - if (btn_w > 0) btn_w += 2; // gap - btn_w += measure.width(btn.label) + 2; // " Label " - } - } - max_content = @max(max_content, btn_w); - - max_inner = @max(max_inner, max_content + pad_h); - break :blk @min(max_inner + 2, term_width); // +2 for borders - }, - }; - } - - fn computeHeight(self: *const Modal, term_height: usize, inner_w: usize) usize { - _ = inner_w; - return switch (self.height) { - .fixed => |h| @min(@as(usize, h), term_height), - .percent => |p| @intFromFloat(@as(f32, @floatFromInt(term_height)) * clamp01(p)), - .auto => blk: { - var h: usize = 2; // top + bottom border - h += self.padding.top; - h += self.padding.bottom; - - // Body lines - var body_lines: usize = 0; - var iter = std.mem.splitScalar(u8, self.body, '\n'); - while (iter.next()) |_| body_lines += 1; - h += body_lines; - - if (self.footer != null) h += 2; // separator + footer - if (self.button_count > 0) h += 2; // separator + button row - - break :blk @min(h, term_height); - }, - }; - } - - fn computeExtras(self: *const Modal) usize { - var e: usize = 2; // borders - e += self.padding.top; - e += self.padding.bottom; - if (self.footer != null) e += 2; - if (self.button_count > 0) e += 2; - return e; - } - - fn renderBackdropSegment(allocator: std.mem.Allocator, bd: Backdrop, count: usize) ![]const u8 { - if (count == 0) return try allocator.dupe(u8, ""); - const ch = bd.char; - if (ch.len == 0) return try allocator.dupe(u8, ""); - const buf = try allocator.alloc(u8, ch.len * count); - for (0..count) |i| { - @memcpy(buf[i * ch.len ..][0..ch.len], ch); - } - return try bd.style.inline_style(true).render(allocator, buf); - } - - fn repeatStr(allocator: std.mem.Allocator, s: style_mod.Style, str: []const u8, count: usize) ![]const u8 { - if (count == 0 or str.len == 0) return try allocator.dupe(u8, ""); - // Build repeated plain string, then style once - const buf = try allocator.alloc(u8, str.len * count); - for (0..count) |i| { - @memcpy(buf[i * str.len ..][0..str.len], str); - } - return try s.render(allocator, buf); - } - - fn nSpaces(allocator: std.mem.Allocator, count: anytype) ![]const u8 { - const n: usize = switch (@typeInfo(@TypeOf(count))) { - .int, .comptime_int => @intCast(count), - else => count, - }; - if (n == 0) return try allocator.dupe(u8, ""); - const buf = try allocator.alloc(u8, n); - @memset(buf, ' '); - return buf; - } - - fn nChars(allocator: std.mem.Allocator, ch: u8, count: usize) ![]const u8 { - if (count == 0) return try allocator.dupe(u8, ""); - const buf = try allocator.alloc(u8, count); - @memset(buf, ch); - return buf; - } - - fn clamp01(v: f32) f32 { - return @max(0.0, @min(1.0, v)); - } - - // Comptime style builder to avoid runtime block initialization - const StyleOpts = struct { - bold_v: ?bool = null, - dim_v: ?bool = null, - italic_v: ?bool = null, - fg_color: Color = .none, - bg_color: Color = .none, - }; - - fn makeStyle(opts: StyleOpts) style_mod.Style { - var s = style_mod.Style{}; - if (opts.bold_v) |v| s.bold_attr = v; - if (opts.dim_v) |v| s.dim_attr = v; - if (opts.italic_v) |v| s.italic_attr = v; - if (!opts.fg_color.isNone()) s.foreground = opts.fg_color; - if (!opts.bg_color.isNone()) s.background = opts.bg_color; - s.inline_mode = true; - return s; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig deleted file mode 100644 index f557161..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/notification.zig +++ /dev/null @@ -1,139 +0,0 @@ -//! Notification/Toast component for timed messages. -//! Displays auto-dismissing messages with severity levels. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Level = enum { - info, - success, - warning, - err, -}; - -pub const ToastMessage = struct { - text: []const u8, - level: Level, - created_ns: u64, - duration_ms: u64, -}; - -pub const Notification = struct { - allocator: std.mem.Allocator, - messages: std.array_list.Managed(ToastMessage), - max_visible: usize, - - // Styling per level - info_style: style_mod.Style, - success_style: style_mod.Style, - warning_style: style_mod.Style, - err_style: style_mod.Style, - - pub fn init(allocator: std.mem.Allocator) Notification { - return .{ - .allocator = allocator, - .messages = std.array_list.Managed(ToastMessage).init(allocator), - .max_visible = 5, - .info_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .success_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - .warning_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .err_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *Notification) void { - self.messages.deinit(); - } - - /// Push a new notification - pub fn push(self: *Notification, 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, - }); - } - - /// Remove expired notifications - pub fn update(self: *Notification, current_ns: u64) void { - var i: usize = 0; - while (i < self.messages.items.len) { - const msg = self.messages.items[i]; - 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 Notification) bool { - return self.messages.items.len > 0; - } - - /// Render notifications - pub fn view(self: *const Notification, allocator: std.mem.Allocator) ![]const u8 { - if (self.messages.items.len == 0) { - return try allocator.dupe(u8, ""); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const visible_count = @min(self.messages.items.len, self.max_visible); - const start = if (self.messages.items.len > self.max_visible) - self.messages.items.len - self.max_visible - else - 0; - - for (start..start + visible_count) |i| { - if (i > start) try writer.writeAll("\n"); - - const msg = self.messages.items[i]; - const icon = switch (msg.level) { - .info => "i ", - .success => "* ", - .warning => "! ", - .err => "x ", - }; - const active_style = switch (msg.level) { - .info => self.info_style, - .success => self.success_style, - .warning => self.warning_style, - .err => self.err_style, - }; - - const styled_icon = try active_style.render(allocator, icon); - try writer.writeAll(styled_icon); - const styled_text = try active_style.render(allocator, msg.text); - try writer.writeAll(styled_text); - } - - return result.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig deleted file mode 100644 index deefad3..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/paginator.zig +++ /dev/null @@ -1,226 +0,0 @@ -//! Paginator component for pagination controls. -//! Displays page indicators and handles navigation. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Paginator = struct { - // State - current_page: usize, - total_pages: usize, - per_page: usize, - total_items: usize, - - // Appearance - paginator_type: Type, - active_dot: []const u8, - inactive_dot: []const u8, - - // Styling - active_style: style_mod.Style, - inactive_style: style_mod.Style, - - pub const Type = enum { - dots, - arabic, // 1/5, 2/5, etc. - compact, // [1] 2 3 4 5 - }; - - pub fn init() Paginator { - return .{ - .current_page = 0, - .total_pages = 1, - .per_page = 10, - .total_items = 0, - .paginator_type = .dots, - .active_dot = "●", - .inactive_dot = "○", - .active_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .inactive_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - /// Set total items and calculate pages - pub fn setTotalItems(self: *Paginator, total: usize) void { - self.total_items = total; - self.total_pages = if (total == 0) 1 else (total + self.per_page - 1) / self.per_page; - self.current_page = @min(self.current_page, self.total_pages -| 1); - } - - /// Set items per page - pub fn setPerPage(self: *Paginator, per_page: usize) void { - self.per_page = @max(1, per_page); - self.setTotalItems(self.total_items); - } - - /// Set total pages directly - pub fn setTotalPages(self: *Paginator, pages: usize) void { - self.total_pages = @max(1, pages); - self.current_page = @min(self.current_page, self.total_pages - 1); - } - - /// Go to specific page - pub fn gotoPage(self: *Paginator, page: usize) void { - self.current_page = @min(page, self.total_pages -| 1); - } - - /// Go to next page - pub fn nextPage(self: *Paginator) void { - if (self.current_page < self.total_pages - 1) { - self.current_page += 1; - } - } - - /// Go to previous page - pub fn prevPage(self: *Paginator) void { - if (self.current_page > 0) { - self.current_page -= 1; - } - } - - /// Go to first page - pub fn firstPage(self: *Paginator) void { - self.current_page = 0; - } - - /// Go to last page - pub fn lastPage(self: *Paginator) void { - self.current_page = self.total_pages -| 1; - } - - /// Check if on first page - pub fn onFirstPage(self: *const Paginator) bool { - return self.current_page == 0; - } - - /// Check if on last page - pub fn onLastPage(self: *const Paginator) bool { - return self.current_page >= self.total_pages -| 1; - } - - /// Get start index for current page - pub fn startIndex(self: *const Paginator) usize { - return self.current_page * self.per_page; - } - - /// Get end index for current page (exclusive) - pub fn endIndex(self: *const Paginator) usize { - return @min(self.startIndex() + self.per_page, self.total_items); - } - - /// Get items on current page - pub fn itemsOnPage(self: *const Paginator) usize { - return self.endIndex() - self.startIndex(); - } - - /// Handle key event - pub fn handleKey(self: *Paginator, key: keys.KeyEvent) void { - switch (key.key) { - .left => self.prevPage(), - .right => self.nextPage(), - .home => self.firstPage(), - .end => self.lastPage(), - .char => |c| { - switch (c) { - 'h' => self.prevPage(), - 'l' => self.nextPage(), - else => {}, - } - }, - else => {}, - } - } - - /// Render the paginator - pub fn view(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { - return switch (self.paginator_type) { - .dots => self.viewDots(allocator), - .arabic => self.viewArabic(allocator), - .compact => self.viewCompact(allocator), - }; - } - - fn viewDots(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (0..self.total_pages) |i| { - if (i > 0) try writer.writeByte(' '); - - if (i == self.current_page) { - const styled = try self.active_style.render(allocator, self.active_dot); - try writer.writeAll(styled); - } else { - const styled = try self.inactive_style.render(allocator, self.inactive_dot); - try writer.writeAll(styled); - } - } - - return result.toOwnedSlice(); - } - - fn viewArabic(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { - const text = try std.fmt.allocPrint(allocator, "{d}/{d}", .{ self.current_page + 1, self.total_pages }); - return self.active_style.render(allocator, text); - } - - fn viewCompact(self: *const Paginator, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Show limited range of pages - const max_visible = 5; - var start: usize = 0; - var end = self.total_pages; - - if (self.total_pages > max_visible) { - const half = max_visible / 2; - if (self.current_page <= half) { - end = max_visible; - } else if (self.current_page >= self.total_pages - half) { - start = self.total_pages - max_visible; - } else { - start = self.current_page - half; - end = self.current_page + half + 1; - } - } - - // Previous indicator - if (start > 0) { - try writer.writeAll("< "); - } - - for (start..end) |i| { - if (i > start) try writer.writeByte(' '); - - const page_str = try std.fmt.allocPrint(allocator, "{d}", .{i + 1}); - if (i == self.current_page) { - const styled = try self.active_style.render(allocator, page_str); - try writer.writeAll(styled); - } else { - const styled = try self.inactive_style.render(allocator, page_str); - try writer.writeAll(styled); - } - } - - // Next indicator - if (end < self.total_pages) { - try writer.writeAll(" >"); - } - - return result.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig deleted file mode 100644 index 15ef751..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/progress.zig +++ /dev/null @@ -1,264 +0,0 @@ -//! Progress bar component. -//! Displays progress with customizable appearance. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Progress = struct { - // Progress state - current: f64, - total: f64, - - // Appearance - width: u16, - show_percent: bool, - show_count: bool, - - // Characters - full_char: []const u8, - empty_char: []const u8, - head_char: ?[]const u8, - - // Styling - full_style: style.Style, - empty_style: style.Style, - percent_style: style.Style, - - // Gradient - gradient_start: ?Color, - gradient_end: ?Color, - - pub fn init() Progress { - return .{ - .current = 0, - .total = 100, - .width = 40, - .show_percent = true, - .show_count = false, - .full_char = "█", - .empty_char = "░", - .head_char = null, - .full_style = blk: { - var s = style.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .empty_style = blk: { - var s = style.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - .percent_style = blk: { - var s = style.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .gradient_start = null, - .gradient_end = null, - }; - } - - /// Set progress value (0 to total) - pub fn setValue(self: *Progress, value: f64) void { - self.current = @max(0, @min(value, self.total)); - } - - /// Set progress percentage (0 to 100) - pub fn setPercent(self: *Progress, pct: f64) void { - self.current = (pct / 100.0) * self.total; - } - - /// Increment progress - pub fn increment(self: *Progress, amount: f64) void { - self.setValue(self.current + amount); - } - - /// Set total value - pub fn setTotal(self: *Progress, total: f64) void { - self.total = total; - } - - /// Set bar width - pub fn setWidth(self: *Progress, width: u16) void { - self.width = width; - } - - /// Get current percentage (0-100) - pub fn percent(self: *const Progress) f64 { - if (self.total == 0) return 0; - return (self.current / self.total) * 100.0; - } - - /// Check if complete - pub fn isComplete(self: *const Progress) bool { - return self.current >= self.total; - } - - /// Set bar characters - pub fn setChars(self: *Progress, full: []const u8, empty: []const u8, head: ?[]const u8) void { - self.full_char = full; - self.empty_char = empty; - self.head_char = head; - } - - /// Use gradient style - pub fn useGradient(self: *Progress) void { - self.full_char = "█"; - self.empty_char = "░"; - self.head_char = "▓"; - } - - /// Use simple ASCII style - pub fn useAscii(self: *Progress) void { - self.full_char = "#"; - self.empty_char = "-"; - self.head_char = ">"; - } - - /// Use block style - pub fn useBlock(self: *Progress) void { - self.full_char = "■"; - self.empty_char = "□"; - self.head_char = null; - } - - /// Set color gradient for the filled portion - pub fn setGradient(self: *Progress, start: Color, end: Color) void { - self.gradient_start = start; - self.gradient_end = end; - } - - /// Render the progress bar - pub fn view(self: *const Progress, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const ratio = if (self.total > 0) self.current / self.total else 0; - const filled_width = @as(usize, @intFromFloat(ratio * @as(f64, @floatFromInt(self.width)))); - const empty_width = self.width -| @as(u16, @intCast(filled_width)); - - // Filled portion - for (0..filled_width) |i| { - const char = if (self.head_char != null and i == filled_width - 1 and empty_width > 0) - self.head_char.? - else - self.full_char; - - // Apply gradient color if set - if (self.gradient_start != null and self.gradient_end != null and filled_width > 0) { - const t: f64 = @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(@max(1, filled_width - 1))); - const color = interpolateColor(self.gradient_start.?, self.gradient_end.?, t); - var grad_style = style.Style{}; - grad_style = grad_style.fg(color); - grad_style = grad_style.inline_style(true); - const grad_styled = try grad_style.render(allocator, char); - try writer.writeAll(grad_styled); - } else { - const full_styled = try self.full_style.render(allocator, char); - try writer.writeAll(full_styled); - } - } - - // Empty portion - for (0..empty_width) |_| { - const empty_styled = try self.empty_style.render(allocator, self.empty_char); - try writer.writeAll(empty_styled); - } - - // Percentage - if (self.show_percent) { - const pct = self.percent(); - const pct_str = try std.fmt.allocPrint(allocator, " {d:.0}%", .{pct}); - const pct_styled = try self.percent_style.render(allocator, pct_str); - try writer.writeAll(pct_styled); - } - - // Count - if (self.show_count) { - const count_str = try std.fmt.allocPrint(allocator, " ({d}/{d})", .{ - @as(i64, @intFromFloat(self.current)), - @as(i64, @intFromFloat(self.total)), - }); - try writer.writeAll(count_str); - } - - return result.toOwnedSlice(); - } - - /// Render with a label - pub fn viewWithLabel(self: *const Progress, allocator: std.mem.Allocator, label: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - try writer.writeAll(label); - try writer.writeAll(" "); - - const bar = try self.view(allocator); - try writer.writeAll(bar); - - return result.toOwnedSlice(); - } -}; - -/// Progress bar styles -pub const ProgressStyle = struct { - /// Default style with gradient characters - pub fn gradient() Progress { - var p = Progress.init(); - p.useGradient(); - return p; - } - - /// ASCII-only style - pub fn ascii() Progress { - var p = Progress.init(); - p.useAscii(); - return p; - } - - /// Block style - pub fn block() Progress { - var p = Progress.init(); - p.useBlock(); - return p; - } - - /// Simple line style - pub fn simple() Progress { - var p = Progress.init(); - p.full_char = "="; - p.empty_char = " "; - p.head_char = ">"; - return p; - } - - /// Colored style - pub fn colored() Progress { - var p = Progress.init(); - var full_s = style.Style{}; - full_s = full_s.fg(.green); - full_s = full_s.inline_style(true); - p.full_style = full_s; - var empty_s = style.Style{}; - empty_s = empty_s.fg(.red); - empty_s = empty_s.inline_style(true); - p.empty_style = empty_s; - return p; - } -}; - -/// Interpolate between two colors using RGB lerp -pub fn interpolateColor(start: Color, end: Color, t: f64) Color { - const start_rgb = start.toRgb() orelse return start; - const end_rgb = end.toRgb() orelse return end; - - const r: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.r)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.r)) * t); - const g: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.g)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.g)) * t); - const b: u8 = @intFromFloat(@as(f64, @floatFromInt(start_rgb.b)) * (1.0 - t) + @as(f64, @floatFromInt(end_rgb.b)) * t); - - return .fromRgb(r, g, b); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig deleted file mode 100644 index 7f754ab..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/radio_group.zig +++ /dev/null @@ -1,276 +0,0 @@ -//! RadioGroup component. -//! Single-select option group with radio button semantics. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub fn RadioGroup(comptime T: type) type { - return struct { - allocator: std.mem.Allocator, - - // Items - items: std.array_list.Managed(Item), - - // State - selected: ?usize, - cursor: usize, - height: u16, - y_offset: usize, - - // Focus - focused: bool, - - // Symbols - cursor_symbol: []const u8, - selected_symbol: []const u8, - unselected_symbol: []const u8, - - // Styling - item_style: style_mod.Style, - selected_style: style_mod.Style, - cursor_style: style_mod.Style, - disabled_style: style_mod.Style, - - const Self = @This(); - - pub const Item = struct { - value: T, - label: []const u8, - description: []const u8, - enabled: bool, - - pub fn init(value: T, label: []const u8) Item { - return .{ - .value = value, - .label = label, - .description = "", - .enabled = true, - }; - } - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .items = std.array_list.Managed(Item).init(allocator), - .selected = null, - .cursor = 0, - .height = 10, - .y_offset = 0, - .focused = true, - .cursor_symbol = "> ", - .selected_symbol = "(●) ", - .unselected_symbol = "( ) ", - .item_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .selected_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.magenta); - s = s.inline_style(true); - break :blk s; - }, - .disabled_style = blk: { - var s = style_mod.Style{}; - s = s.dim(true); - s = s.fg(.gray(10)); - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *Self) void { - self.items.deinit(); - } - - pub fn addOption(self: *Self, item: Item) !void { - try self.items.append(item); - } - - pub fn addOptions(self: *Self, new_items: []const Item) !void { - try self.items.appendSlice(new_items); - } - - pub fn selectCurrent(self: *Self) void { - if (self.cursor >= self.items.items.len) return; - if (!self.items.items[self.cursor].enabled) return; - self.selected = self.cursor; - } - - pub fn selectedItem(self: *const Self) ?*const Item { - if (self.selected) |idx| { - if (idx < self.items.items.len) { - return &self.items.items[idx]; - } - } - return null; - } - - pub fn selectedValue(self: *const Self) ?T { - if (self.selectedItem()) |item| { - return item.value; - } - return null; - } - - // Focus protocol - pub fn focus(self: *Self) void { - self.focused = true; - } - - pub fn blur(self: *Self) void { - self.focused = false; - } - - pub fn handleKey(self: *Self, key: keys.KeyEvent) void { - if (!self.focused) return; - - switch (key.key) { - .up => self.cursorUp(), - .down => self.cursorDown(), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoFirst(), - .end => self.gotoLast(), - .space, .enter => self.selectCurrent(), - .char => |c| switch (c) { - 'j' => self.cursorDown(), - 'k' => self.cursorUp(), - 'g' => self.gotoFirst(), - 'G' => self.gotoLast(), - else => {}, - }, - else => {}, - } - } - - fn cursorUp(self: *Self) void { - if (self.items.items.len == 0) return; - if (self.cursor > 0) { - self.cursor -= 1; - } else { - self.cursor = self.items.items.len - 1; - } - self.ensureVisible(); - } - - fn cursorDown(self: *Self) void { - if (self.items.items.len == 0) return; - if (self.cursor < self.items.items.len - 1) { - self.cursor += 1; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - fn pageUp(self: *Self) void { - if (self.cursor >= self.height) { - self.cursor -= self.height; - } else { - self.cursor = 0; - } - self.ensureVisible(); - } - - fn pageDown(self: *Self) void { - if (self.cursor + self.height < self.items.items.len) { - self.cursor += self.height; - } else if (self.items.items.len > 0) { - self.cursor = self.items.items.len - 1; - } - self.ensureVisible(); - } - - fn gotoFirst(self: *Self) void { - self.cursor = 0; - self.y_offset = 0; - } - - fn gotoLast(self: *Self) void { - if (self.items.items.len > 0) { - self.cursor = self.items.items.len - 1; - self.ensureVisible(); - } - } - - fn ensureVisible(self: *Self) void { - if (self.cursor < self.y_offset) { - self.y_offset = self.cursor; - } else if (self.cursor >= self.y_offset + self.height) { - self.y_offset = self.cursor - self.height + 1; - } - } - - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var rendered: usize = 0; - while (rendered < self.height) : (rendered += 1) { - if (rendered > 0) try writer.writeByte('\n'); - - const idx = self.y_offset + rendered; - if (idx >= self.items.items.len) break; - - const item = self.items.items[idx]; - const is_selected = self.selected != null and self.selected.? == idx; - - // Cursor - if (idx == self.cursor and self.focused) { - const styled = try self.cursor_style.render(allocator, self.cursor_symbol); - try writer.writeAll(styled); - } else { - for (0..self.cursor_symbol.len) |_| { - try writer.writeByte(' '); - } - } - - // Radio symbol - const radio_sym = if (is_selected) self.selected_symbol else self.unselected_symbol; - const radio_s = if (!item.enabled) - self.disabled_style - else if (is_selected) - self.selected_style - else - self.item_style; - const styled_radio = try radio_s.render(allocator, radio_sym); - try writer.writeAll(styled_radio); - - // Label - const lbl_style = if (!item.enabled) - self.disabled_style - else if (idx == self.cursor and self.focused) - self.cursor_style - else if (is_selected) - self.selected_style - else - self.item_style; - const styled_label = try lbl_style.render(allocator, item.label); - try writer.writeAll(styled_label); - - // Description - if (item.description.len > 0) { - try writer.writeAll(" - "); - try writer.writeAll(item.description); - } - } - - return result.toOwnedSlice(); - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig deleted file mode 100644 index 895c72f..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/rich_log.zig +++ /dev/null @@ -1,422 +0,0 @@ -//! Rich log widget — append-only, virtualized, level-aware. -//! -//! Stores a bounded ring buffer of log entries with severity levels and -//! optional timestamps. Renders only the visible window so cost stays O(rows) -//! regardless of buffer size. Supports follow-mode (auto-scroll to tail), -//! per-level styling, level filters, and substring search highlighting. -//! -//! Distinct from Viewport (raw text) and Toast (transient notification): this -//! is the right widget for a long-running app's persistent log/audit pane. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); - -pub const Style = style_mod.Style; - -pub const Level = enum { - trace, - debug, - info, - warn, - err, - - pub fn label(self: Level) []const u8 { - return switch (self) { - .trace => "TRACE", - .debug => "DEBUG", - .info => "INFO ", - .warn => "WARN ", - .err => "ERROR", - }; - } - - pub fn rank(self: Level) u8 { - return switch (self) { - .trace => 0, - .debug => 1, - .info => 2, - .warn => 3, - .err => 4, - }; - } -}; - -pub const Entry = struct { - level: Level, - /// Unix nanoseconds, populated by `append` from `std.Io.Timestamp.now(io, .real)`. - timestamp_ns: i128, - text: []u8, -}; - -pub const RichLog = struct { - allocator: std.mem.Allocator, - - /// Ring buffer of entries. - entries: std.array_list.Managed(Entry), - /// Maximum entries retained; older entries are dropped on append. - capacity: usize, - - /// Indices into `entries` after applying min_level + search filter. - /// Recomputed lazily. - visible: std.array_list.Managed(usize), - visible_dirty: bool, - - /// Display configuration. - width: u16, - height: u16, - y_offset: usize, - follow: bool, - - /// Filtering. - min_level: Level, - search_term: std.array_list.Managed(u8), - - /// Display options. - show_timestamps: bool, - show_level: bool, - - /// Styling. - timestamp_style: Style, - level_styles: [5]Style, - text_style: Style, - highlight_style: Style, - - pub fn init(allocator: std.mem.Allocator, capacity: usize) RichLog { - var ts = Style{}; - ts = ts.fg(.gray(8)); - ts = ts.inline_style(true); - - var trace_s = Style{}; - trace_s = trace_s.fg(.gray(6)); - trace_s = trace_s.inline_style(true); - var debug_s = Style{}; - debug_s = debug_s.fg(.gray(10)); - debug_s = debug_s.inline_style(true); - var info_s = Style{}; - info_s = info_s.fg(.cyan); - info_s = info_s.inline_style(true); - var warn_s = Style{}; - warn_s = warn_s.fg(.yellow); - warn_s = warn_s.inline_style(true); - var err_s = Style{}; - err_s = err_s.fg(.red); - err_s = err_s.bold(true); - err_s = err_s.inline_style(true); - - var text = Style{}; - text = text.inline_style(true); - - var hi = Style{}; - hi = hi.bg(.yellow); - hi = hi.fg(.black); - hi = hi.inline_style(true); - - return .{ - .allocator = allocator, - .entries = std.array_list.Managed(Entry).init(allocator), - .capacity = @max(capacity, 1), - .visible = std.array_list.Managed(usize).init(allocator), - .visible_dirty = true, - .width = 80, - .height = 10, - .y_offset = 0, - .follow = true, - .min_level = .trace, - .search_term = std.array_list.Managed(u8).init(allocator), - .show_timestamps = false, - .show_level = true, - .timestamp_style = ts, - .level_styles = .{ trace_s, debug_s, info_s, warn_s, err_s }, - .text_style = text, - .highlight_style = hi, - }; - } - - pub fn deinit(self: *RichLog) void { - for (self.entries.items) |e| self.allocator.free(e.text); - self.entries.deinit(); - self.visible.deinit(); - self.search_term.deinit(); - } - - pub fn setSize(self: *RichLog, w: u16, h: u16) void { - self.width = w; - self.height = h; - } - - pub fn setMinLevel(self: *RichLog, lvl: Level) void { - self.min_level = lvl; - self.visible_dirty = true; - } - - pub fn setSearch(self: *RichLog, term: []const u8) !void { - self.search_term.clearRetainingCapacity(); - try self.search_term.appendSlice(term); - self.visible_dirty = true; - } - - pub fn clearSearch(self: *RichLog) void { - self.search_term.clearRetainingCapacity(); - self.visible_dirty = true; - } - - /// Append an entry, dropping the oldest if at capacity. - pub fn append(self: *RichLog, io: std.Io, level: Level, text: []const u8) !void { - const owned = try self.allocator.dupe(u8, text); - if (self.entries.items.len >= self.capacity) { - const oldest = self.entries.orderedRemove(0); - self.allocator.free(oldest.text); - } - try self.entries.append(.{ - .level = level, - .timestamp_ns = std.Io.Timestamp.now(io, .real).toNanoseconds(), - .text = owned, - }); - self.visible_dirty = true; - if (self.follow) self.scrollToEnd(); - } - - /// Append using std.fmt-style formatting. - pub fn appendFmt(self: *RichLog, io: std.Io, level: Level, comptime fmt: []const u8, args: anytype) !void { - const formatted = try std.fmt.allocPrint(self.allocator, fmt, args); - defer self.allocator.free(formatted); - try self.append(io, level, formatted); - } - - pub fn clear(self: *RichLog) void { - for (self.entries.items) |e| self.allocator.free(e.text); - self.entries.clearRetainingCapacity(); - self.visible.clearRetainingCapacity(); - self.visible_dirty = false; - self.y_offset = 0; - } - - pub fn scrollUp(self: *RichLog, n: usize) void { - self.follow = false; - self.y_offset -|= n; - } - - pub fn scrollDown(self: *RichLog, n: usize) !void { - try self.refresh(); - const max_off = self.maxOffset(); - self.y_offset = @min(self.y_offset + n, max_off); - if (self.y_offset == max_off) self.follow = true; - } - - pub fn scrollToEnd(self: *RichLog) void { - self.refresh() catch return; - self.y_offset = self.maxOffset(); - self.follow = true; - } - - pub fn scrollToStart(self: *RichLog) void { - self.y_offset = 0; - self.follow = false; - } - - fn maxOffset(self: *const RichLog) usize { - const visible_count = self.visible.items.len; - if (visible_count <= self.height) return 0; - return visible_count - self.height; - } - - fn refresh(self: *RichLog) !void { - if (!self.visible_dirty) return; - self.visible.clearRetainingCapacity(); - for (self.entries.items, 0..) |e, i| { - if (e.level.rank() < self.min_level.rank()) continue; - if (self.search_term.items.len > 0 and - std.mem.indexOf(u8, e.text, self.search_term.items) == null) - { - continue; - } - try self.visible.append(i); - } - self.visible_dirty = false; - const max_off = self.maxOffset(); - if (self.y_offset > max_off) self.y_offset = max_off; - } - - pub fn handleKey(self: *RichLog, key: keys.KeyEvent) !void { - switch (key.key) { - .up => self.scrollUp(1), - .down => try self.scrollDown(1), - .page_up => self.scrollUp(self.height), - .page_down => try self.scrollDown(self.height), - .home => self.scrollToStart(), - .end => self.scrollToEnd(), - .char => |c| switch (c) { - 'g' => self.scrollToStart(), - 'G' => self.scrollToEnd(), - 'k' => self.scrollUp(1), - 'j' => try self.scrollDown(1), - else => {}, - }, - else => {}, - } - } - - pub fn view(self: *RichLog, allocator: std.mem.Allocator) ![]const u8 { - try self.refresh(); - - var out: Writer.Allocating = .init(allocator); - const w = &out.writer; - - const visible = self.visible.items; - if (visible.len == 0) { - return out.toOwnedSlice(); - } - - const start = self.y_offset; - const end = @min(start + self.height, visible.len); - - var first = true; - for (start..end) |row_idx| { - if (!first) try w.writeByte('\n'); - first = false; - const entry = self.entries.items[visible[row_idx]]; - try self.renderEntry(allocator, w, entry); - } - - return out.toOwnedSlice(); - } - - fn renderEntry(self: *const RichLog, allocator: std.mem.Allocator, w: *Writer, entry: Entry) !void { - if (self.show_timestamps) { - const ts = try formatTimestamp(allocator, entry.timestamp_ns); - defer allocator.free(ts); - const styled = try self.timestamp_style.render(allocator, ts); - defer allocator.free(styled); - try w.writeAll(styled); - try w.writeByte(' '); - } - - if (self.show_level) { - const lvl_style = self.level_styles[@intFromEnum(entry.level)]; - const styled = try lvl_style.render(allocator, entry.level.label()); - defer allocator.free(styled); - try w.writeAll(styled); - try w.writeByte(' '); - } - - // Render text with optional search highlighting. - if (self.search_term.items.len == 0) { - const styled = try self.text_style.render(allocator, entry.text); - defer allocator.free(styled); - try w.writeAll(styled); - } else { - try self.renderHighlighted(allocator, w, entry.text); - } - } - - fn renderHighlighted(self: *const RichLog, allocator: std.mem.Allocator, w: *Writer, text: []const u8) !void { - const term = self.search_term.items; - var rest = text; - while (std.mem.indexOf(u8, rest, term)) |pos| { - if (pos > 0) { - const before = try self.text_style.render(allocator, rest[0..pos]); - defer allocator.free(before); - try w.writeAll(before); - } - const hi = try self.highlight_style.render(allocator, rest[pos .. pos + term.len]); - defer allocator.free(hi); - try w.writeAll(hi); - rest = rest[pos + term.len ..]; - } - if (rest.len > 0) { - const tail = try self.text_style.render(allocator, rest); - defer allocator.free(tail); - try w.writeAll(tail); - } - } -}; - -fn formatTimestamp(allocator: std.mem.Allocator, ns: i128) ![]u8 { - const seconds_total: i64 = @intCast(@divTrunc(ns, std.time.ns_per_s)); - // HH:MM:SS in UTC. - const sec_in_day: u32 = @intCast(@mod(seconds_total, 86400)); - const hh = sec_in_day / 3600; - const mm = (sec_in_day % 3600) / 60; - const ss = sec_in_day % 60; - return std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hh, mm, ss }); -} - -test "append respects capacity" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 3); - defer log.deinit(); - try log.append(std.testing.io, .info, "a"); - try log.append(std.testing.io, .info, "b"); - try log.append(std.testing.io, .info, "c"); - try log.append(std.testing.io, .info, "d"); - try std.testing.expectEqual(@as(usize, 3), log.entries.items.len); - try std.testing.expectEqualStrings("b", log.entries.items[0].text); - try std.testing.expectEqualStrings("d", log.entries.items[2].text); -} - -test "min level filters entries" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 100); - defer log.deinit(); - try log.append(std.testing.io, .debug, "noise"); - try log.append(std.testing.io, .warn, "important"); - log.setMinLevel(.warn); - try log.refresh(); - try std.testing.expectEqual(@as(usize, 1), log.visible.items.len); -} - -test "search filter matches substring" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 10); - defer log.deinit(); - try log.append(std.testing.io, .info, "hello world"); - try log.append(std.testing.io, .info, "goodbye"); - try log.setSearch("hello"); - try log.refresh(); - try std.testing.expectEqual(@as(usize, 1), log.visible.items.len); -} - -test "follow mode auto-scrolls" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 100); - defer log.deinit(); - log.setSize(80, 2); - var i: usize = 0; - while (i < 5) : (i += 1) { - try log.appendFmt(std.testing.io, .info, "line {d}", .{i}); - } - try log.refresh(); - // Last two entries should fit; offset should be 3. - try std.testing.expectEqual(@as(usize, 3), log.y_offset); -} - -test "scrollUp disables follow" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 100); - defer log.deinit(); - try log.append(std.testing.io, .info, "a"); - log.scrollUp(1); - try std.testing.expect(!log.follow); -} - -test "view emits at most height lines" { - const allocator = std.testing.allocator; - var log = RichLog.init(allocator, 100); - defer log.deinit(); - log.setSize(80, 3); - var i: usize = 0; - while (i < 10) : (i += 1) { - try log.appendFmt(std.testing.io, .info, "line {d}", .{i}); - } - const out = try log.view(allocator); - defer allocator.free(out); - var newlines: usize = 0; - for (out) |b| if (b == '\n') { - newlines += 1; - }; - try std.testing.expect(newlines <= 2); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig deleted file mode 100644 index c38bb44..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/slider.zig +++ /dev/null @@ -1,291 +0,0 @@ -//! Slider component. -//! Interactive numeric range input with keyboard control. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const progress_mod = @import("progress.zig"); - -pub const Slider = struct { - // Value - value: f64, - min: f64, - max: f64, - step: f64, - large_step: f64, - - // Display - width: u16, - precision: u8, - show_value: bool, - show_bounds: bool, - show_percent: bool, - label: []const u8, - - // Characters - track_char: []const u8, - thumb_char: []const u8, - filled_char: []const u8, - - // Styling - track_style: style_mod.Style, - filled_style: style_mod.Style, - thumb_style: style_mod.Style, - label_style: style_mod.Style, - value_style: style_mod.Style, - - // Gradient - gradient_start: ?Color, - gradient_end: ?Color, - - // Focus - focused: bool, - - pub fn init(min: f64, max: f64) Slider { - return .{ - .value = min, - .min = min, - .max = max, - .step = 1, - .large_step = 10, - .width = 30, - .precision = 0, - .show_value = true, - .show_bounds = false, - .show_percent = false, - .label = "", - .track_char = "━", - .thumb_char = "●", - .filled_char = "━", - .track_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - .filled_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .thumb_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - .label_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .value_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .gradient_start = null, - .gradient_end = null, - .focused = true, - }; - } - - pub fn setValue(self: *Slider, val: f64) void { - self.value = @max(self.min, @min(val, self.max)); - } - - pub fn getValue(self: *const Slider) f64 { - return self.value; - } - - pub fn percent(self: *const Slider) f64 { - if (self.max == self.min) return 0; - return ((self.value - self.min) / (self.max - self.min)) * 100.0; - } - - pub fn setStep(self: *Slider, s: f64) void { - self.step = s; - } - - pub fn setLargeStep(self: *Slider, s: f64) void { - self.large_step = s; - } - - pub fn setWidth(self: *Slider, w: u16) void { - self.width = w; - } - - pub fn setPrecision(self: *Slider, p: u8) void { - self.precision = p; - } - - pub fn setGradient(self: *Slider, start: Color, end: Color) void { - self.gradient_start = start; - self.gradient_end = end; - } - - // Focus protocol - pub fn focus(self: *Slider) void { - self.focused = true; - } - - pub fn blur(self: *Slider) void { - self.focused = false; - } - - pub fn handleKey(self: *Slider, key: keys.KeyEvent) void { - if (!self.focused) return; - - switch (key.key) { - .left => self.decrement(self.step), - .right => self.increment(self.step), - .page_down => self.decrement(self.large_step), - .page_up => self.increment(self.large_step), - .home => self.setValue(self.min), - .end => self.setValue(self.max), - .char => |c| switch (c) { - 'h' => self.decrement(self.step), - 'l' => self.increment(self.step), - 'H' => self.decrement(self.large_step), - 'L' => self.increment(self.large_step), - '0' => self.setValue(self.min), - '$' => self.setValue(self.max), - else => {}, - }, - else => {}, - } - } - - fn increment(self: *Slider, amount: f64) void { - self.setValue(self.value + amount); - } - - fn decrement(self: *Slider, amount: f64) void { - self.setValue(self.value - amount); - } - - pub fn view(self: *const Slider, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Label - if (self.label.len > 0) { - const styled = try self.label_style.render(allocator, self.label); - try writer.writeAll(styled); - try writer.writeAll(" "); - } - - // Bounds (left) - if (self.show_bounds) { - const min_str = try self.formatValue(allocator, self.min); - try writer.writeAll(min_str); - try writer.writeAll(" "); - } - - // Track - const range = self.max - self.min; - const ratio: f64 = if (range > 0) (self.value - self.min) / range else 0; - const track_width = self.width; - const thumb_pos = @as(usize, @intFromFloat(ratio * @as(f64, @floatFromInt(track_width -| 1)))); - - for (0..track_width) |i| { - if (i == thumb_pos) { - // Thumb - const styled = try self.thumb_style.render(allocator, self.thumb_char); - try writer.writeAll(styled); - } else if (i < thumb_pos) { - // Filled portion - if (self.gradient_start != null and self.gradient_end != null and thumb_pos > 0) { - const t: f64 = @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(@max(1, thumb_pos))); - const col = progress_mod.interpolateColor(self.gradient_start.?, self.gradient_end.?, t); - var grad_style = style_mod.Style{}; - grad_style = grad_style.fg(col); - grad_style = grad_style.inline_style(true); - const styled = try grad_style.render(allocator, self.filled_char); - try writer.writeAll(styled); - } else { - const styled = try self.filled_style.render(allocator, self.filled_char); - try writer.writeAll(styled); - } - } else { - // Empty track - const styled = try self.track_style.render(allocator, self.track_char); - try writer.writeAll(styled); - } - } - - // Bounds (right) - if (self.show_bounds) { - try writer.writeAll(" "); - const max_str = try self.formatValue(allocator, self.max); - try writer.writeAll(max_str); - } - - // Value display - if (self.show_value) { - try writer.writeAll(" "); - const val_str = try self.formatValue(allocator, self.value); - const styled = try self.value_style.render(allocator, val_str); - try writer.writeAll(styled); - } - - // Percentage - if (self.show_percent) { - const pct = self.percent(); - const pct_str = try std.fmt.allocPrint(allocator, " ({d:.0}%)", .{pct}); - try writer.writeAll(pct_str); - } - - return result.toOwnedSlice(); - } - - fn formatValue(self: *const Slider, allocator: std.mem.Allocator, val: f64) ![]const u8 { - return switch (self.precision) { - 0 => std.fmt.allocPrint(allocator, "{d:.0}", .{val}), - 1 => std.fmt.allocPrint(allocator, "{d:.1}", .{val}), - 2 => std.fmt.allocPrint(allocator, "{d:.2}", .{val}), - else => std.fmt.allocPrint(allocator, "{d:.3}", .{val}), - }; - } -}; - -/// Slider style presets -pub const SliderStyle = struct { - pub fn block() Slider { - var s = Slider.init(0, 100); - s.filled_char = "█"; - s.track_char = "░"; - s.thumb_char = "▓"; - return s; - } - - pub fn ascii() Slider { - var s = Slider.init(0, 100); - s.filled_char = "="; - s.track_char = "-"; - s.thumb_char = ">"; - return s; - } - - pub fn thin() Slider { - var s = Slider.init(0, 100); - s.filled_char = "─"; - s.track_char = "─"; - s.thumb_char = "◆"; - return s; - } - - pub fn dots() Slider { - var s = Slider.init(0, 100); - s.filled_char = "•"; - s.track_char = "·"; - s.thumb_char = "◉"; - return s; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig deleted file mode 100644 index 58e7c75..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sortable_table.zig +++ /dev/null @@ -1,321 +0,0 @@ -//! Sortable and filterable table component. -//! Extends basic table with column sorting and text filtering. - -const std = @import("std"); -const Writer = std.Io.Writer; -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 keys = @import("../input/keys.zig"); - -pub fn SortableTable(comptime num_cols: usize) type { - return struct { - allocator: std.mem.Allocator, - headers: [num_cols][]const u8, - rows: std.array_list.Managed([num_cols][]const u8), - /// Indices into rows for display order (sorted/filtered view). - view_indices: std.array_list.Managed(usize), - - // Sort state - sort_column: ?usize = null, - sort_ascending: bool = true, - - // Filter - filter_text: std.array_list.Managed(u8), - filter_column: ?usize = null, // null = search all columns - filter_active: bool = false, - - // Display - col_widths: [num_cols]?u16 = .{null} ** num_cols, - col_aligns: [num_cols]Align = .{.left} ** num_cols, - show_header: bool = true, - show_border: bool = true, - border_chars: border_mod.BorderChars = .normal, - - // Interactive - cursor_row: usize = 0, - y_offset: usize = 0, - visible_rows: u16 = 20, - focused: bool = true, - - // Styling - header_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - cell_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - cursor_row_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bg(.blue); - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - sort_indicator_asc: []const u8 = " \xe2\x96\xb2", - sort_indicator_desc: []const u8 = " \xe2\x96\xbc", - - const Self = @This(); - - pub const Align = enum { left, center, right }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .headers = .{""} ** num_cols, - .rows = std.array_list.Managed([num_cols][]const u8).init(allocator), - .view_indices = std.array_list.Managed(usize).init(allocator), - .filter_text = std.array_list.Managed(u8).init(allocator), - }; - } - - pub fn deinit(self: *Self) void { - self.rows.deinit(); - self.view_indices.deinit(); - self.filter_text.deinit(); - } - - pub fn setHeaders(self: *Self, hdrs: [num_cols][]const u8) void { - self.headers = hdrs; - } - - pub fn addRow(self: *Self, row: [num_cols][]const u8) !void { - try self.rows.append(row); - try self.rebuildView(); - } - - pub fn update(self: *Self, key: keys.KeyEvent) void { - const total = self.view_indices.items.len; - switch (key.key) { - .up => { - if (self.cursor_row > 0) self.cursor_row -= 1; - self.ensureVisible(); - }, - .down => { - if (self.cursor_row + 1 < total) self.cursor_row += 1; - self.ensureVisible(); - }, - .char => |c| { - if (c >= '1' and c <= '9') { - const col: usize = c - '1'; - if (col < num_cols) self.toggleSort(col); - } else if (c == '/') { - self.filter_active = true; - } else if (self.filter_active) { - if (c < 128) { - self.filter_text.append(@intCast(c)) catch {}; - self.rebuildView() catch {}; - } - } - }, - .backspace => { - if (self.filter_active and self.filter_text.items.len > 0) { - _ = self.filter_text.pop(); - self.rebuildView() catch {}; - } - }, - .escape => { - if (self.filter_active) { - self.filter_active = false; - self.filter_text.clearRetainingCapacity(); - self.rebuildView() catch {}; - } - }, - .enter => { - if (self.filter_active) { - self.filter_active = false; - } - }, - else => {}, - } - } - - fn toggleSort(self: *Self, col: usize) void { - if (self.sort_column == col) { - self.sort_ascending = !self.sort_ascending; - } else { - self.sort_column = col; - self.sort_ascending = true; - } - self.rebuildView() catch {}; - } - - fn rebuildView(self: *Self) !void { - self.view_indices.clearRetainingCapacity(); - const filter = self.filter_text.items; - - for (0..self.rows.items.len) |i| { - if (filter.len > 0) { - var matches = false; - for (self.rows.items[i]) |cell| { - if (containsIgnoreCase(cell, filter)) { - matches = true; - break; - } - } - if (!matches) continue; - } - try self.view_indices.append(i); - } - - // Sort using bubble sort (simple, avoids comptime context issues) - if (self.sort_column) |col| { - const indices = self.view_indices.items; - const rws = self.rows.items; - const asc = self.sort_ascending; - var sorted = false; - while (!sorted) { - sorted = true; - for (0..indices.len -| 1) |i| { - const va = rws[indices[i]][col]; - const vb = rws[indices[i + 1]][col]; - const cmp = std.mem.order(u8, va, vb); - const should_swap = if (asc) cmp == .gt else cmp == .lt; - if (should_swap) { - const tmp = indices[i]; - indices[i] = indices[i + 1]; - indices[i + 1] = tmp; - sorted = false; - } - } - } - } - - if (self.cursor_row >= self.view_indices.items.len and self.view_indices.items.len > 0) { - self.cursor_row = self.view_indices.items.len - 1; - } - } - - fn ensureVisible(self: *Self) void { - if (self.cursor_row < self.y_offset) self.y_offset = self.cursor_row; - if (self.cursor_row >= self.y_offset + self.visible_rows) { - self.y_offset = self.cursor_row - self.visible_rows + 1; - } - } - - pub fn view(self: *const Self, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Compute column widths - var widths: [num_cols]usize = undefined; - for (0..num_cols) |c| { - widths[c] = if (self.col_widths[c]) |w| w else blk: { - var max_w: usize = self.headers[c].len + 2; // room for sort indicator - for (self.rows.items) |row| { - max_w = @max(max_w, row[c].len); - } - break :blk max_w; - }; - } - - // Header - if (self.show_header) { - for (0..num_cols) |c| { - if (c > 0) writer.writeAll(" \xe2\x94\x82 ") catch {}; - const hdr = self.headers[c]; - writer.writeAll(self.header_style.render(allocator, hdr) catch hdr) catch {}; - - // Sort indicator - if (self.sort_column == c) { - if (self.sort_ascending) { - writer.writeAll(self.sort_indicator_asc) catch {}; - } else { - writer.writeAll(self.sort_indicator_desc) catch {}; - } - const used = hdr.len + 2; - if (used < widths[c]) { - for (0..widths[c] - used) |_| writer.writeByte(' ') catch {}; - } - } else { - if (hdr.len < widths[c]) { - for (0..widths[c] - hdr.len) |_| writer.writeByte(' ') catch {}; - } - } - } - writer.writeByte('\n') catch {}; - - // Separator - for (0..num_cols) |c| { - if (c > 0) writer.writeAll("\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80") catch {}; - for (0..widths[c]) |_| writer.writeAll("\xe2\x94\x80") catch {}; - } - writer.writeByte('\n') catch {}; - } - - // Rows - const end = @min(self.y_offset + self.visible_rows, self.view_indices.items.len); - for (self.y_offset..end) |vi| { - if (vi > self.y_offset) writer.writeByte('\n') catch {}; - const ri = self.view_indices.items[vi]; - const row = self.rows.items[ri]; - const is_cursor = (vi == self.cursor_row and self.focused); - - for (0..num_cols) |c| { - if (c > 0) writer.writeAll(" \xe2\x94\x82 ") catch {}; - const cell = row[c]; - const s = if (is_cursor) self.cursor_row_style else self.cell_style; - const padded = padTo(allocator, cell, widths[c], self.col_aligns[c]); - writer.writeAll(s.render(allocator, padded) catch padded) catch {}; - } - } - - // Filter bar - if (self.filter_active or self.filter_text.items.len > 0) { - writer.writeAll("\n\nFilter: ") catch {}; - writer.writeAll(self.filter_text.items) catch {}; - if (self.filter_active) writer.writeByte('_') catch {}; - } - - // Count - writer.writeByte('\n') catch {}; - const count = std.fmt.allocPrint(allocator, " {d}/{d} rows", .{ self.view_indices.items.len, self.rows.items.len }) catch ""; - var cs = style_mod.Style{}; - cs = cs.fg(.gray(10)); - cs = cs.inline_style(true); - writer.writeAll(cs.render(allocator, count) catch count) catch {}; - - return result.toArrayList().items; - } - - fn padTo(allocator: std.mem.Allocator, text: []const u8, target: usize, alignment: Align) []const u8 { - if (text.len >= target) return text; - var buf = std.array_list.Managed(u8).init(allocator); - const pad = target - text.len; - switch (alignment) { - .left => { - buf.appendSlice(text) catch {}; - for (0..pad) |_| buf.append(' ') catch {}; - }, - .right => { - for (0..pad) |_| buf.append(' ') catch {}; - buf.appendSlice(text) catch {}; - }, - .center => { - const left = pad / 2; - for (0..left) |_| buf.append(' ') catch {}; - buf.appendSlice(text) catch {}; - for (0..pad - left) |_| buf.append(' ') catch {}; - }, - } - return buf.items; - } - - fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool { - if (needle.len > haystack.len) return false; - outer: for (0..haystack.len - needle.len + 1) |i| { - for (0..needle.len) |j| { - if (std.ascii.toLower(haystack[i + j]) != std.ascii.toLower(needle[j])) continue :outer; - } - return true; - } - return false; - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig deleted file mode 100644 index aeb4ed6..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/sparkline.zig +++ /dev/null @@ -1,229 +0,0 @@ -//! Sparkline component with configurable aggregation and styling. - -const std = @import("std"); -const Writer = std.Io.Writer; -const charting = @import("charting.zig"); -const progress = @import("progress.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Style = style_mod.Style; -pub const Summary = charting.Summary; -pub const DataRange = charting.DataRange; - -pub const Sparkline = struct { - allocator: std.mem.Allocator, - data: std.array_list.Managed(f64), - display_width: u16, - summary: Summary, - retention_limit: ?usize, - spark_style: Style, - empty_char: []const u8, - glyphs: []const []const u8, - fixed_range: ?DataRange, - gradient_start: ?Color, - gradient_end: ?Color, - - const default_glyphs = [_][]const u8{ " ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" }; - - pub fn init(allocator: std.mem.Allocator) Sparkline { - return .{ - .allocator = allocator, - .data = std.array_list.Managed(f64).init(allocator), - .display_width = 40, - .summary = .last, - .retention_limit = 40, - .spark_style = blk: { - var s = Style{}; - s = s.fg(.green); - break :blk charting.inlineStyle(s); - }, - .empty_char = " ", - .glyphs = default_glyphs[0..], - .fixed_range = null, - .gradient_start = null, - .gradient_end = null, - }; - } - - pub fn deinit(self: *Sparkline) void { - self.data.deinit(); - } - - pub fn push(self: *Sparkline, value: f64) !void { - try self.data.append(value); - self.enforceRetention(); - } - - pub fn setData(self: *Sparkline, data: []const f64) !void { - self.data.clearRetainingCapacity(); - try self.data.appendSlice(data); - self.enforceRetention(); - } - - pub fn clear(self: *Sparkline) void { - self.data.clearRetainingCapacity(); - } - - pub fn setWidth(self: *Sparkline, width: u16) void { - self.display_width = @max(1, width); - if (self.retention_limit) |limit| { - if (limit < self.display_width) { - self.retention_limit = self.display_width; - } - } - self.enforceRetention(); - } - - pub fn setSummary(self: *Sparkline, summary: Summary) void { - self.summary = summary; - } - - pub fn setRetentionLimit(self: *Sparkline, limit: ?usize) void { - self.retention_limit = if (limit) |value| @max(value, self.display_width) else null; - self.enforceRetention(); - } - - pub fn setStyle(self: *Sparkline, style: Style) void { - self.spark_style = charting.inlineStyle(style); - } - - pub fn setEmptyChar(self: *Sparkline, empty_char: []const u8) void { - self.empty_char = empty_char; - } - - pub fn setGlyphs(self: *Sparkline, glyphs: []const []const u8) void { - if (glyphs.len > 0) self.glyphs = glyphs; - } - - pub fn setRange(self: *Sparkline, range: ?DataRange) void { - self.fixed_range = if (range) |value| value.normalized() else null; - } - - pub fn setGradient(self: *Sparkline, start: ?Color, end: ?Color) void { - self.gradient_start = start; - self.gradient_end = end; - } - - pub fn view(self: *const Sparkline, allocator: std.mem.Allocator) ![]const u8 { - if (self.display_width == 0) return try allocator.dupe(u8, ""); - - var visible = try self.bucketValues(allocator); - defer visible.deinit(); - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - if (visible.items.len == 0) { - for (0..self.display_width) |_| try writer.writeAll(self.empty_char); - return try result.toOwnedSlice(); - } - - const range = self.fixed_range orelse self.computeRange(visible.items); - const glyph_count = self.glyphs.len; - const max_index = glyph_count - 1; - - for (visible.items, 0..) |value, index| { - const normalized = if (range.span() > 0) - charting.clampUnit((value - range.min) / range.span()) - else - 0.5; - - const glyph_index = @min(max_index, @as(usize, @intFromFloat(@round(normalized * @as(f64, @floatFromInt(max_index)))))); - const glyph = self.glyphs[glyph_index]; - - if (self.gradient_start != null and self.gradient_end != null) { - const t = if (visible.items.len <= 1) 0.0 else @as(f64, @floatFromInt(index)) / @as(f64, @floatFromInt(visible.items.len - 1)); - const color = progress.interpolateColor(self.gradient_start.?, self.gradient_end.?, t); - var style = self.spark_style.fg(color); - style = charting.inlineStyle(style); - const rendered = try style.render(allocator, glyph); - defer allocator.free(rendered); - try writer.writeAll(rendered); - } else { - const rendered = try self.spark_style.render(allocator, glyph); - defer allocator.free(rendered); - try writer.writeAll(rendered); - } - } - - if (visible.items.len < self.display_width) { - for (0..(@as(usize, self.display_width) - visible.items.len)) |_| { - try writer.writeAll(self.empty_char); - } - } - - return try result.toOwnedSlice(); - } - - fn enforceRetention(self: *Sparkline) void { - if (self.retention_limit) |limit| { - while (self.data.items.len > limit) { - _ = self.data.orderedRemove(0); - } - } - } - - fn bucketValues(self: *const Sparkline, allocator: std.mem.Allocator) !std.array_list.Managed(f64) { - var buckets = std.array_list.Managed(f64).init(allocator); - const width = @as(usize, self.display_width); - if (self.data.items.len == 0 or width == 0) return buckets; - - if (self.data.items.len <= width) { - try buckets.appendSlice(self.data.items); - return buckets; - } - - const data_len_f = @as(f64, @floatFromInt(self.data.items.len)); - const width_f = @as(f64, @floatFromInt(width)); - - for (0..width) |bucket_index| { - const start = @min(self.data.items.len, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(bucket_index)) * data_len_f / width_f)))); - const end = @min(self.data.items.len, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(bucket_index + 1)) * data_len_f / width_f)))); - const slice = if (end > start) self.data.items[start..end] else self.data.items[start..@min(self.data.items.len, start + 1)]; - try buckets.append(summarize(slice, self.summary)); - } - - return buckets; - } - - fn computeRange(self: *const Sparkline, values: []const f64) DataRange { - _ = self; - var min_value = values[0]; - var max_value = values[0]; - for (values[1..]) |value| { - min_value = @min(min_value, value); - max_value = @max(max_value, value); - } - const range = DataRange{ .min = min_value, .max = max_value }; - return range.normalized(); - } -}; - -fn summarize(values: []const f64, summary: Summary) f64 { - if (values.len == 0) return 0; - - return switch (summary) { - .last => values[values.len - 1], - .average => blk: { - var total: f64 = 0; - for (values) |value| total += value; - break :blk total / @as(f64, @floatFromInt(values.len)); - }, - .minimum => blk: { - var value = values[0]; - for (values[1..]) |item| value = @min(value, item); - break :blk value; - }, - .maximum => blk: { - var value = values[0]; - for (values[1..]) |item| value = @max(value, item); - break :blk value; - }, - .sum => blk: { - var total: f64 = 0; - for (values) |value| total += value; - break :blk total; - }, - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig deleted file mode 100644 index 1922b7e..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/spinner.zig +++ /dev/null @@ -1,146 +0,0 @@ -//! Animated loading spinner component. -//! Provides various spinner styles and customization options. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Spinner = struct { - // Spinner configuration - frames: []const []const u8, - frame_index: usize, - fps: u32, - - // Styling - spinner_style: style.Style, - - // State - last_tick: i64, - - /// Predefined spinner styles - pub const Styles = struct { - pub const line = &[_][]const u8{ "|", "/", "-", "\\" }; - pub const dots = &[_][]const u8{ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" }; - pub const dots2 = &[_][]const u8{ "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" }; - pub const dots3 = &[_][]const u8{ "⠋", "⠙", "⠚", "⠞", "⠖", "⠦", "⠴", "⠲", "⠳", "⠓" }; - pub const globe = &[_][]const u8{ "🌍", "🌎", "🌏" }; - pub const moon = &[_][]const u8{ "🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘" }; - pub const circle = &[_][]const u8{ "◐", "◓", "◑", "◒" }; - pub const square = &[_][]const u8{ "◰", "◳", "◲", "◱" }; - pub const arrow = &[_][]const u8{ "←", "↖", "↑", "↗", "→", "↘", "↓", "↙" }; - pub const bounce = &[_][]const u8{ "⠁", "⠂", "⠄", "⠂" }; - pub const box_bounce = &[_][]const u8{ "▖", "▘", "▝", "▗" }; - pub const triangle = &[_][]const u8{ "◢", "◣", "◤", "◥" }; - pub const arc = &[_][]const u8{ "◜", "◠", "◝", "◞", "◡", "◟" }; - pub const pipe = &[_][]const u8{ "┤", "┘", "┴", "└", "├", "┌", "┬", "┐" }; - pub const simple_dots = &[_][]const u8{ ". ", ".. ", "...", " ..", " .", " " }; - pub const pulse = &[_][]const u8{ "█", "▓", "▒", "░", "▒", "▓" }; - }; - - pub fn init() Spinner { - return .{ - .frames = Styles.dots, - .frame_index = 0, - .fps = 10, - .spinner_style = blk: { - var s = style.Style{}; - s = s.fg(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .last_tick = 0, - }; - } - - /// Set spinner frames - pub fn setFrames(self: *Spinner, frames: []const []const u8) void { - self.frames = frames; - self.frame_index = 0; - } - - /// Set spinner style - pub fn setStyle(self: *Spinner, s: style.Style) void { - self.spinner_style = s; - } - - /// Set frames per second - pub fn setFps(self: *Spinner, fps: u32) void { - self.fps = fps; - } - - /// Advance to next frame - pub fn tick(self: *Spinner) void { - self.frame_index = (self.frame_index + 1) % self.frames.len; - } - - /// Update based on elapsed time (in nanoseconds) - pub fn update(self: *Spinner, elapsed_ns: i64) bool { - const frame_ns = @as(i64, @intCast(std.time.ns_per_s / self.fps)); - - if (elapsed_ns - self.last_tick >= frame_ns) { - self.tick(); - self.last_tick = elapsed_ns; - return true; // Frame changed - } - return false; - } - - /// Get current frame - pub fn currentFrame(self: *const Spinner) []const u8 { - return self.frames[self.frame_index]; - } - - /// Render the spinner - pub fn view(self: *const Spinner, allocator: std.mem.Allocator) ![]const u8 { - return self.spinner_style.render(allocator, self.currentFrame()); - } - - /// Render spinner with title - pub fn viewWithTitle(self: *const Spinner, allocator: std.mem.Allocator, title: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const rendered_spinner = try self.view(allocator); - try writer.writeAll(rendered_spinner); - try writer.writeByte(' '); - try writer.writeAll(title); - - return result.toOwnedSlice(); - } -}; - -/// Create a spinner with the given style -pub fn newSpinner(frames: []const []const u8) Spinner { - var s = Spinner.init(); - s.setFrames(frames); - return s; -} - -/// Create a dots spinner -pub fn dots() Spinner { - return Spinner.init(); -} - -/// Create a line spinner -pub fn line() Spinner { - var s = Spinner.init(); - s.setFrames(Spinner.Styles.line); - return s; -} - -/// Create a globe spinner -pub fn globe() Spinner { - var s = Spinner.init(); - s.setFrames(Spinner.Styles.globe); - s.setFps(4); - return s; -} - -/// Create a moon spinner -pub fn moon() Spinner { - var s = Spinner.init(); - s.setFrames(Spinner.Styles.moon); - s.setFps(6); - return s; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig deleted file mode 100644 index 78e942c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/split_pane.zig +++ /dev/null @@ -1,246 +0,0 @@ -//! 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(.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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig deleted file mode 100644 index 7d64a2c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/status_bar.zig +++ /dev/null @@ -1,215 +0,0 @@ -//! 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 Writer = std.Io.Writer; -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(.gray(4)); - base = base.fg(.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: Writer.Allocating = .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, allocator, gap); - try writer.writeAll(center_str); - const consumed = lw + gap + cw; - const trailing = (self.width -| rw) -| consumed; - try self.writeGap(writer, allocator, trailing); - } else { - const gap = (self.width -| rw) -| lw; - try self.writeGap(writer, 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: Writer.Allocating = .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.Writer, 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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig deleted file mode 100644 index 1a3bafb..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/stepper.zig +++ /dev/null @@ -1,254 +0,0 @@ -//! 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 Writer = std.Io.Writer; -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(.green); - completed = completed.inline_style(true); - - var current = style_mod.Style{}; - current = current.fg(.cyan); - current = current.bold(true); - current = current.inline_style(true); - - var pending = style_mod.Style{}; - pending = pending.fg(.gray(8)); - pending = pending.inline_style(true); - - var connector = style_mod.Style{}; - connector = connector.fg(.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(.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: Writer.Allocating = .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: Writer.Allocating = .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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig deleted file mode 100644 index 8f9bec5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/styled_list.zig +++ /dev/null @@ -1,169 +0,0 @@ -//! Styled list component for rendering lists with various enumerators. -//! Non-interactive rendering-only list with bullet, numbered, roman, alphabet enumerators. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -/// Enumerator type for list items -pub const EnumeratorType = enum { - bullet, - arabic, - roman, - alphabet, - dash, - asterisk, - none, -}; - -pub const StyledList = struct { - allocator: std.mem.Allocator, - items: std.array_list.Managed(ListItem), - enumerator_type: EnumeratorType, - item_style: style_mod.Style, - enumerator_style: style_mod.Style, - - pub const ListItem = struct { - text: []const u8, - depth: usize, - style_override: ?style_mod.Style, - }; - - pub fn init(allocator: std.mem.Allocator) StyledList { - return .{ - .allocator = allocator, - .items = std.array_list.Managed(ListItem).init(allocator), - .enumerator_type = .bullet, - .item_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .enumerator_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *StyledList) void { - self.items.deinit(); - } - - /// Add an item at depth 0 - pub fn addItem(self: *StyledList, text: []const u8) !void { - try self.items.append(.{ - .text = text, - .depth = 0, - .style_override = null, - }); - } - - /// Add an item at specified depth - pub fn addItemNested(self: *StyledList, text: []const u8, depth: usize) !void { - try self.items.append(.{ - .text = text, - .depth = depth, - .style_override = null, - }); - } - - /// Set the enumerator type - pub fn setEnumerator(self: *StyledList, e: EnumeratorType) void { - self.enumerator_type = e; - } - - /// Render the list - pub fn view(self: *const StyledList, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Track counters per depth level - var counters: [16]usize = .{0} ** 16; - - for (self.items.items, 0..) |item, i| { - if (i > 0) try writer.writeAll("\n"); - - // Reset deeper counters when going to a shallower depth - const depth = @min(item.depth, 15); - for (depth + 1..16) |d| { - counters[d] = 0; - } - counters[depth] += 1; - - // Indent - for (0..depth) |_| { - try writer.writeAll(" "); - } - - // Enumerator - const enum_str = try self.formatEnumerator(allocator, counters[depth]); - const styled_enum = try self.enumerator_style.render(allocator, enum_str); - try writer.writeAll(styled_enum); - - // Item text - const active_style = item.style_override orelse self.item_style; - const styled_text = try active_style.render(allocator, item.text); - try writer.writeAll(styled_text); - } - - return result.toOwnedSlice(); - } - - fn formatEnumerator(self: *const StyledList, allocator: std.mem.Allocator, counter: usize) ![]const u8 { - return switch (self.enumerator_type) { - .bullet => try allocator.dupe(u8, "\u{2022} "), - .arabic => try std.fmt.allocPrint(allocator, "{d}. ", .{counter}), - .roman => blk: { - const roman = try toRoman(allocator, counter); - break :blk try std.fmt.allocPrint(allocator, "{s}. ", .{roman}); - }, - .alphabet => blk: { - const alpha = try toAlpha(allocator, counter); - break :blk try std.fmt.allocPrint(allocator, "{s}. ", .{alpha}); - }, - .dash => try allocator.dupe(u8, "- "), - .asterisk => try allocator.dupe(u8, "* "), - .none => try allocator.dupe(u8, ""), - }; - } -}; - -/// Convert number to Roman numerals -pub fn toRoman(allocator: std.mem.Allocator, n: usize) ![]const u8 { - if (n == 0) return try allocator.dupe(u8, "0"); - - var result: std.array_list.Managed(u8) = .init(allocator); - - const values = [_]usize{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; - const symbols = [_][]const u8{ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; - - var num = n; - for (values, symbols) |val, sym| { - while (num >= val) { - try result.appendSlice(sym); - num -= val; - } - } - - return result.toOwnedSlice(); -} - -/// Convert number to alphabetical representation (1=a, 2=b, ..., 26=z, 27=aa) -pub fn toAlpha(allocator: std.mem.Allocator, n: usize) ![]const u8 { - if (n == 0) return try allocator.dupe(u8, "?"); - - var result: std.array_list.Managed(u8) = .init(allocator); - var num = n - 1; - - while (true) { - const c: u8 = @intCast('a' + @as(u8, @intCast(num % 26))); - try result.insert(0, c); - if (num < 26) break; - num = num / 26 - 1; - } - - return result.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig deleted file mode 100644 index 0c9f23a..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tab_group.zig +++ /dev/null @@ -1,1066 +0,0 @@ -//! Tab group and multi-view routing component. -//! Provides tab-strip rendering, key-driven navigation, and optional -//! type-erased view routing for multi-screen applications. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const measure = @import("../layout/measure.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -/// Maximum number of key bindings tracked per action. -const max_binds = 8; - -/// A single key binding (key + optional modifiers). -pub const KeyBind = struct { - key: keys.Key, - modifiers: keys.Modifiers = .{}, - - pub fn matches(self: KeyBind, event: keys.KeyEvent) bool { - return self.key.eql(event.key) and self.modifiers.eql(event.modifiers); - } -}; - -/// Default next-tab bindings: Right, Tab. -pub const default_next_keys = [max_binds]?KeyBind{ - .{ .key = .right }, - .{ .key = .tab }, - null, - null, - null, - null, - null, - null, -}; - -/// Default previous-tab bindings: Left, Shift+Tab. -pub const default_prev_keys = [max_binds]?KeyBind{ - .{ .key = .left }, - .{ .key = .tab, .modifiers = .{ .shift = true } }, - null, - null, - null, - null, - null, - null, -}; - -/// Default "first tab" bindings: Home. -pub const default_first_keys = [max_binds]?KeyBind{ - .{ .key = .home }, - null, - null, - null, - null, - null, - null, - null, -}; - -/// Default "last tab" bindings: End. -pub const default_last_keys = [max_binds]?KeyBind{ - .{ .key = .end }, - null, - null, - null, - null, - null, - null, - null, -}; - -/// Default activation bindings (manual activation mode): Enter, Space. -pub const default_activate_keys = [max_binds]?KeyBind{ - .{ .key = .enter }, - .{ .key = .space }, - null, - null, - null, - null, - null, - null, -}; - -/// Why active tab changed. -pub const ChangeReason = enum { - init, - set_active, - next, - prev, - first, - last, - number_shortcut, - activate, - remove, - disable, - hide, - clear, -}; - -pub const Change = struct { - previous: ?usize, - current: ?usize, - reason: ChangeReason, -}; - -/// Result of handling a key event. -pub const KeyResult = struct { - consumed: bool = false, - change: ?Change = null, - routed: bool = false, -}; - -/// Tab label rendering context. -pub const LabelState = struct { - index: usize, - active: bool, - focused: bool, - enabled: bool, - visible: bool, -}; - -pub const OverflowMode = enum { - /// Render all tabs (no clipping). - none, - /// Render all tabs then truncate final output. - clip, - /// Keep active/focused tab visible and show scroll markers. - scroll, -}; - -pub const LabelRenderer = *const fn (ctx: *anyopaque, allocator: std.mem.Allocator, tab: Tab, state: LabelState) anyerror![]const u8; -pub const RouteRenderer = *const fn (ctx: *anyopaque, allocator: std.mem.Allocator) anyerror![]const u8; -pub const RouteKeyHandler = *const fn (ctx: *anyopaque, event: keys.KeyEvent) bool; -pub const RouteHook = *const fn (ctx: *anyopaque) void; - -/// Optional route callbacks attached to a tab. -pub const Route = struct { - ctx: *anyopaque, - render_fn: RouteRenderer, - key_fn: ?RouteKeyHandler = null, - on_enter_fn: ?RouteHook = null, - on_leave_fn: ?RouteHook = null, -}; - -pub const Tab = struct { - id: []const u8, - title: []const u8, - short_title: ?[]const u8 = null, - enabled: bool = true, - visible: bool = true, - closable: bool = false, - route: ?Route = null, - user_data: ?*anyopaque = null, -}; - -/// Tab strip + multi-view routing container. -pub const TabGroup = struct { - allocator: std.mem.Allocator, - tabs: std.array_list.Managed(Tab), - - active_index: ?usize, - focus_index: ?usize, - - // Focus protocol compatibility - focused: bool = true, - - // Navigation behavior - wrap: bool = true, - activate_on_focus: bool = true, - number_shortcuts: bool = true, - focus_disabled_tabs: bool = false, - - // Key maps - next_keys: [max_binds]?KeyBind = default_next_keys, - prev_keys: [max_binds]?KeyBind = default_prev_keys, - first_keys: [max_binds]?KeyBind = default_first_keys, - last_keys: [max_binds]?KeyBind = default_last_keys, - activate_keys: [max_binds]?KeyBind = default_activate_keys, - - // Rendering options - bar_style: style_mod.Style, - tab_style: style_mod.Style, - active_tab_style: style_mod.Style, - focused_tab_style: style_mod.Style, - disabled_tab_style: style_mod.Style, - separator_style: style_mod.Style, - overflow_style: style_mod.Style, - - separator: []const u8 = " ", - tab_prefix: []const u8 = " ", - tab_suffix: []const u8 = " ", - show_numbers: bool = false, - number_separator: []const u8 = ":", - - max_width: ?usize = null, - overflow_mode: OverflowMode = .scroll, - overflow_left: []const u8 = "… ", - overflow_right: []const u8 = " …", - - label_renderer: ?LabelRenderer = null, - label_renderer_ctx: ?*anyopaque = null, - - const Self = @This(); - - pub fn init(allocator: std.mem.Allocator) Self { - var tab_style = style_mod.Style{}; - tab_style = tab_style.fg(.gray(15)); - tab_style = tab_style.inline_style(true); - - var active_style = style_mod.Style{}; - active_style = active_style.fg(.cyan); - active_style = active_style.bold(true); - active_style = active_style.inline_style(true); - - var focused_style = style_mod.Style{}; - focused_style = focused_style.fg(.yellow); - focused_style = focused_style.bold(true); - focused_style = focused_style.inline_style(true); - - var disabled_style = style_mod.Style{}; - disabled_style = disabled_style.fg(.gray(9)); - disabled_style = disabled_style.dim(true); - disabled_style = disabled_style.inline_style(true); - - var sep_style = style_mod.Style{}; - sep_style = sep_style.fg(.gray(11)); - sep_style = sep_style.inline_style(true); - - var overflow_style = style_mod.Style{}; - overflow_style = overflow_style.fg(.gray(12)); - overflow_style = overflow_style.inline_style(true); - - return .{ - .allocator = allocator, - .tabs = std.array_list.Managed(Tab).init(allocator), - .active_index = null, - .focus_index = null, - .bar_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .tab_style = tab_style, - .active_tab_style = active_style, - .focused_tab_style = focused_style, - .disabled_tab_style = disabled_style, - .separator_style = sep_style, - .overflow_style = overflow_style, - }; - } - - pub fn deinit(self: *Self) void { - self.tabs.deinit(); - } - - pub fn focus(self: *Self) void { - self.focused = true; - } - - pub fn blur(self: *Self) void { - self.focused = false; - } - - pub fn len(self: *const Self) usize { - return self.tabs.items.len; - } - - pub fn hasTabs(self: *const Self) bool { - return self.tabs.items.len > 0; - } - - pub fn clear(self: *Self) ?Change { - const prev = self.active_index; - self.leaveActiveRoute(); - self.tabs.clearRetainingCapacity(); - self.active_index = null; - self.focus_index = null; - if (prev == null) return null; - return .{ - .previous = prev, - .current = null, - .reason = .clear, - }; - } - - pub fn addTab(self: *Self, tab: Tab) !usize { - try self.tabs.append(tab); - const idx = self.tabs.items.len - 1; - - if (self.focus_index == null) self.focus_index = idx; - - if (self.active_index == null and self.isActivatableIndex(idx)) { - _ = self.setActive(idx, .init); - } - - return idx; - } - - pub fn insertTab(self: *Self, index: usize, tab: Tab) !void { - const idx = @min(index, self.tabs.items.len); - try self.tabs.insert(idx, tab); - - if (self.active_index) |active| { - if (active >= idx) self.active_index = active + 1; - } - if (self.focus_index) |focus_idx| { - if (focus_idx >= idx) self.focus_index = focus_idx + 1; - } - - if (self.focus_index == null) self.focus_index = idx; - if (self.active_index == null and self.isActivatableIndex(idx)) { - _ = self.setActive(idx, .init); - } - } - - pub fn removeTabAt(self: *Self, index: usize) ?Change { - if (index >= self.tabs.items.len) return null; - - const prev_active = self.active_index; - const removed_was_active = prev_active != null and prev_active.? == index; - - if (removed_was_active) { - self.leaveActiveRoute(); - self.active_index = null; - } - - _ = self.tabs.orderedRemove(index); - - if (self.tabs.items.len == 0) { - self.active_index = null; - self.focus_index = null; - if (prev_active == null) return null; - return .{ - .previous = prev_active, - .current = null, - .reason = .remove, - }; - } - - if (self.active_index) |active_idx| { - if (active_idx > index) self.active_index = active_idx - 1; - } - if (self.focus_index) |focus_idx| { - if (focus_idx > index) { - self.focus_index = focus_idx - 1; - } else if (focus_idx == index) { - self.focus_index = self.pickFallbackFocusIndex(index); - } - } else { - self.focus_index = self.firstVisibleIndex() orelse self.firstIndex(); - } - - if (removed_was_active) { - const fallback = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); - if (fallback) |new_active| { - return self.setActive(new_active, .remove); - } - self.active_index = null; - return .{ - .previous = prev_active, - .current = null, - .reason = .remove, - }; - } - - self.ensureValidSelection(); - return null; - } - - pub fn removeTabById(self: *Self, id: []const u8) ?Change { - const idx = self.indexOf(id) orelse return null; - return self.removeTabAt(idx); - } - - pub fn indexOf(self: *const Self, id: []const u8) ?usize { - for (self.tabs.items, 0..) |tab, i| { - if (std.mem.eql(u8, tab.id, id)) return i; - } - return null; - } - - pub fn getTab(self: *Self, index: usize) ?*Tab { - if (index >= self.tabs.items.len) return null; - return &self.tabs.items[index]; - } - - pub fn getTabConst(self: *const Self, index: usize) ?*const Tab { - if (index >= self.tabs.items.len) return null; - return &self.tabs.items[index]; - } - - pub fn activeIndex(self: *const Self) ?usize { - return self.active_index; - } - - pub fn focusedIndex(self: *const Self) ?usize { - return self.focus_index; - } - - pub fn activeTab(self: *const Self) ?*const Tab { - const idx = self.active_index orelse return null; - return &self.tabs.items[idx]; - } - - pub fn activeRoute(self: *const Self) ?Route { - const idx = self.active_index orelse return null; - return self.tabs.items[idx].route; - } - - pub fn isActive(self: *const Self, index: usize) bool { - return self.active_index != null and self.active_index.? == index; - } - - pub fn isFocused(self: *const Self, index: usize) bool { - return self.focus_index != null and self.focus_index.? == index; - } - - pub fn setLabelRenderer(self: *Self, ctx: *anyopaque, renderer: LabelRenderer) void { - self.label_renderer_ctx = ctx; - self.label_renderer = renderer; - } - - pub fn clearLabelRenderer(self: *Self) void { - self.label_renderer_ctx = null; - self.label_renderer = null; - } - - pub fn setRoute(self: *Self, index: usize, route: ?Route) void { - if (index >= self.tabs.items.len) return; - self.tabs.items[index].route = route; - } - - pub fn setEnabled(self: *Self, index: usize, enabled: bool) ?Change { - if (index >= self.tabs.items.len) return null; - self.tabs.items[index].enabled = enabled; - if (enabled) { - if (self.active_index == null and self.isActivatableIndex(index)) { - return self.setActive(index, .set_active); - } - return null; - } - - const was_active = self.active_index != null and self.active_index.? == index; - if (!was_active) return null; - - const next_idx = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); - if (next_idx) |i| { - return self.setActive(i, .disable); - } - - const prev = self.active_index; - self.leaveActiveRoute(); - self.active_index = null; - return .{ - .previous = prev, - .current = null, - .reason = .disable, - }; - } - - pub fn setVisible(self: *Self, index: usize, visible: bool) ?Change { - if (index >= self.tabs.items.len) return null; - self.tabs.items[index].visible = visible; - - if (!visible) { - const was_active = self.active_index != null and self.active_index.? == index; - if (was_active) { - const fallback = self.pickFallbackActiveIndex(index) orelse self.firstActivatableIndex(); - if (fallback) |i| { - return self.setActive(i, .hide); - } - const prev = self.active_index; - self.leaveActiveRoute(); - self.active_index = null; - return .{ - .previous = prev, - .current = null, - .reason = .hide, - }; - } - - if (self.focus_index != null and self.focus_index.? == index) { - self.focus_index = self.pickFallbackFocusIndex(index) orelse self.firstVisibleIndex(); - } - } else if (self.focus_index == null) { - self.focus_index = index; - } - - self.ensureValidSelection(); - return null; - } - - pub fn setActive(self: *Self, index: usize, reason: ChangeReason) ?Change { - if (!self.isActivatableIndex(index)) return null; - - const prev = self.active_index; - if (prev != null and prev.? == index) { - self.focus_index = index; - return null; - } - - self.leaveRoute(prev); - self.active_index = index; - self.focus_index = index; - self.enterRoute(index); - - return .{ - .previous = prev, - .current = index, - .reason = reason, - }; - } - - pub fn setActiveById(self: *Self, id: []const u8, reason: ChangeReason) ?Change { - const idx = self.indexOf(id) orelse return null; - return self.setActive(idx, reason); - } - - pub fn focusTab(self: *Self, index: usize) bool { - if (index >= self.tabs.items.len) return false; - if (!self.tabs.items[index].visible) return false; - if (!self.focus_disabled_tabs and !self.tabs.items[index].enabled) return false; - self.focus_index = index; - return true; - } - - pub fn focusFirst(self: *Self) bool { - const idx = self.firstFocusableIndex() orelse return false; - self.focus_index = idx; - if (self.activate_on_focus) _ = self.setActive(idx, .first); - return true; - } - - pub fn focusLast(self: *Self) bool { - const idx = self.lastFocusableIndex() orelse return false; - self.focus_index = idx; - if (self.activate_on_focus) _ = self.setActive(idx, .last); - return true; - } - - pub fn focusNext(self: *Self) bool { - const start = self.focus_index orelse self.active_index orelse return self.focusFirst(); - const idx = self.findNextFocusable(start) orelse return false; - self.focus_index = idx; - if (self.activate_on_focus) _ = self.setActive(idx, .next); - return true; - } - - pub fn focusPrev(self: *Self) bool { - const start = self.focus_index orelse self.active_index orelse return self.focusLast(); - const idx = self.findPrevFocusable(start) orelse return false; - self.focus_index = idx; - if (self.activate_on_focus) _ = self.setActive(idx, .prev); - return true; - } - - pub fn activateFocused(self: *Self) ?Change { - const idx = self.focus_index orelse return null; - return self.setActive(idx, .activate); - } - - pub fn handleKey(self: *Self, event: keys.KeyEvent) KeyResult { - if (!self.focused) return .{}; - - if (self.matchAny(event, self.next_keys)) { - const prev = self.active_index; - if (self.focusNext()) { - return .{ - .consumed = true, - .change = self.diffChange(prev, .next), - }; - } - return .{ .consumed = true }; - } - if (self.matchAny(event, self.prev_keys)) { - const prev = self.active_index; - if (self.focusPrev()) { - return .{ - .consumed = true, - .change = self.diffChange(prev, .prev), - }; - } - return .{ .consumed = true }; - } - if (self.matchAny(event, self.first_keys)) { - const prev = self.active_index; - if (self.focusFirst()) { - return .{ - .consumed = true, - .change = self.diffChange(prev, .first), - }; - } - return .{ .consumed = true }; - } - if (self.matchAny(event, self.last_keys)) { - const prev = self.active_index; - if (self.focusLast()) { - return .{ - .consumed = true, - .change = self.diffChange(prev, .last), - }; - } - return .{ .consumed = true }; - } - - if (!self.activate_on_focus and self.matchAny(event, self.activate_keys)) { - return .{ - .consumed = true, - .change = self.activateFocused(), - }; - } - - if (self.number_shortcuts and !event.modifiers.any()) { - if (event.key == .char) { - const c = event.key.char; - if (c >= '1' and c <= '9') { - const ordinal: usize = @intCast(c - '1'); - if (self.setActiveByVisibleOrdinal(ordinal)) |chg| { - return .{ - .consumed = true, - .change = chg, - }; - } - return .{ .consumed = true }; - } - } - } - - return .{}; - } - - /// Handle tab navigation keys; if not consumed, forward key to active route. - pub fn handleKeyAndRoute(self: *Self, event: keys.KeyEvent) KeyResult { - var res = self.handleKey(event); - if (!res.consumed) { - res.routed = self.routeKey(event); - res.consumed = res.routed; - } - return res; - } - - /// Route a key event to active tab route (if it has a key handler). - pub fn routeKey(self: *Self, event: keys.KeyEvent) bool { - const idx = self.active_index orelse return false; - const route = self.tabs.items[idx].route orelse return false; - const key_fn = route.key_fn orelse return false; - return key_fn(route.ctx, event); - } - - /// Render only the tab strip. - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - return self.renderStrip(allocator); - } - - /// Render only the active route content (if any). - pub fn viewActiveContent(self: *const Self, allocator: std.mem.Allocator) !?[]const u8 { - const idx = self.active_index orelse return null; - const route = self.tabs.items[idx].route orelse return null; - return try route.render_fn(route.ctx, allocator); - } - - /// Render `tabs + content`, with optional fallback content when route is missing. - pub fn viewWithContent(self: *const Self, allocator: std.mem.Allocator, fallback_content: ?[]const u8) ![]const u8 { - const tabs = try self.renderStrip(allocator); - const content = (try self.viewActiveContent(allocator)) orelse fallback_content orelse ""; - - if (content.len == 0) return tabs; - return std.fmt.allocPrint(allocator, "{s}\n{s}", .{ tabs, content }); - } - - fn renderStrip(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var pieces = std.array_list.Managed([]const u8).init(allocator); - defer pieces.deinit(); - - var visible_indices = std.array_list.Managed(usize).init(allocator); - defer visible_indices.deinit(); - - for (self.tabs.items, 0..) |tab, i| { - if (tab.visible) try visible_indices.append(i); - } - - if (visible_indices.items.len == 0) return allocator.dupe(u8, ""); - - for (visible_indices.items) |tab_idx| { - const piece = try self.renderTabLabel(allocator, tab_idx); - try pieces.append(piece); - } - - const sep = try self.separator_style.render(allocator, self.separator); - - const strip = switch (self.overflow_mode) { - .none => try joinPieces(allocator, pieces.items, sep), - .clip => blk: { - const raw = try joinPieces(allocator, pieces.items, sep); - if (self.max_width) |w| { - break :blk try measure.truncate(allocator, raw, w); - } - break :blk raw; - }, - .scroll => try self.renderScrolledStrip(allocator, pieces.items, visible_indices.items, sep), - }; - - return self.bar_style.render(allocator, strip); - } - - fn renderScrolledStrip(self: *const Self, allocator: std.mem.Allocator, pieces: []const []const u8, visible_indices: []const usize, sep: []const u8) ![]const u8 { - const max_w = self.max_width orelse return joinPieces(allocator, pieces, sep); - - const total_w = joinedWidth(pieces, sep); - if (total_w <= max_w) return joinPieces(allocator, pieces, sep); - - const left_marker = try self.overflow_style.render(allocator, self.overflow_left); - const right_marker = try self.overflow_style.render(allocator, self.overflow_right); - const left_w = measure.width(left_marker); - const right_w = measure.width(right_marker); - - const target_tab_idx = self.focus_index orelse self.active_index orelse visible_indices[0]; - var target_pos: usize = 0; - for (visible_indices, 0..) |idx, i| { - if (idx == target_tab_idx) { - target_pos = i; - break; - } - } - - var start = target_pos; - var end = target_pos + 1; - - while (true) { - var grew = false; - - if (start > 0) { - const cand_start = start - 1; - const width = rangeWidthWithMarkers(pieces, sep, cand_start, end, left_w, right_w, cand_start > 0, end < pieces.len); - if (width <= max_w) { - start = cand_start; - grew = true; - } - } - - if (end < pieces.len) { - const cand_end = end + 1; - const width = rangeWidthWithMarkers(pieces, sep, start, cand_end, left_w, right_w, start > 0, cand_end < pieces.len); - if (width <= max_w) { - end = cand_end; - grew = true; - } - } - - if (!grew) break; - } - - var truncated_single: ?[]const u8 = null; - - // Degenerate case: marker + single tab still wider than max. - const single_range_w = rangeWidthWithMarkers(pieces, sep, start, end, left_w, right_w, start > 0, end < pieces.len); - if (single_range_w > max_w and end == start + 1) { - const reserved = (if (start > 0) left_w else 0) + (if (end < pieces.len) right_w else 0); - if (reserved < max_w) { - const allow = max_w - reserved; - truncated_single = try measure.truncate(allocator, pieces[start], allow); - } - } - - var out: Writer.Allocating = .init(allocator); - const writer = &out.writer; - - if (start > 0) try writer.writeAll(left_marker); - for (start..end) |i| { - if (i > start) try writer.writeAll(sep); - if (truncated_single != null and i == start) { - try writer.writeAll(truncated_single.?); - } else { - try writer.writeAll(pieces[i]); - } - } - if (end < pieces.len) try writer.writeAll(right_marker); - - return out.toOwnedSlice(); - } - - fn renderTabLabel(self: *const Self, allocator: std.mem.Allocator, tab_index: usize) ![]const u8 { - const tab = self.tabs.items[tab_index]; - const state = LabelState{ - .index = tab_index, - .active = self.isActive(tab_index), - .focused = self.isFocused(tab_index), - .enabled = tab.enabled, - .visible = tab.visible, - }; - - if (self.label_renderer) |renderer| { - const ctx = self.label_renderer_ctx orelse return error.MissingLabelRendererContext; - return renderer(ctx, allocator, tab, state); - } - - var base: Writer.Allocating = .init(allocator); - const writer = &base.writer; - - try writer.writeAll(self.tab_prefix); - if (self.show_numbers) { - const number = try std.fmt.allocPrint(allocator, "{d}{s}", .{ self.visibleOrdinal(tab_index) + 1, self.number_separator }); - try writer.writeAll(number); - } - try writer.writeAll(tab.title); - try writer.writeAll(self.tab_suffix); - - const raw = try base.toOwnedSlice(); - - if (!tab.enabled) return self.disabled_tab_style.render(allocator, raw); - if (state.active) return self.active_tab_style.render(allocator, raw); - if (!self.activate_on_focus and state.focused) return self.focused_tab_style.render(allocator, raw); - return self.tab_style.render(allocator, raw); - } - - fn setActiveByVisibleOrdinal(self: *Self, ordinal: usize) ?Change { - var seen: usize = 0; - for (self.tabs.items, 0..) |tab, i| { - if (!tab.visible or !tab.enabled) continue; - if (seen == ordinal) { - return self.setActive(i, .number_shortcut); - } - seen += 1; - } - return null; - } - - fn visibleOrdinal(self: *const Self, index: usize) usize { - var ordinal: usize = 0; - for (self.tabs.items, 0..) |tab, i| { - if (!tab.visible) continue; - if (i == index) return ordinal; - ordinal += 1; - } - return ordinal; - } - - fn ensureValidSelection(self: *Self) void { - if (self.tabs.items.len == 0) { - self.active_index = null; - self.focus_index = null; - return; - } - - if (self.active_index) |idx| { - if (!self.isActivatableIndex(idx)) { - const fallback = self.pickFallbackActiveIndex(idx) orelse self.firstActivatableIndex(); - if (fallback) |new_idx| { - _ = self.setActive(new_idx, .set_active); - } else { - self.active_index = null; - } - } - } else if (self.firstActivatableIndex()) |idx| { - _ = self.setActive(idx, .init); - } - - if (self.focus_index) |idx| { - if (!self.isFocusableIndex(idx)) { - self.focus_index = self.firstFocusableIndex() orelse self.firstVisibleIndex() orelse self.firstIndex(); - } - } else { - self.focus_index = self.firstFocusableIndex() orelse self.firstVisibleIndex() orelse self.firstIndex(); - } - } - - fn firstIndex(self: *const Self) ?usize { - if (self.tabs.items.len == 0) return null; - return 0; - } - - fn firstVisibleIndex(self: *const Self) ?usize { - for (self.tabs.items, 0..) |tab, i| { - if (tab.visible) return i; - } - return null; - } - - fn firstActivatableIndex(self: *const Self) ?usize { - for (self.tabs.items, 0..) |tab, i| { - if (tab.visible and tab.enabled) return i; - } - return null; - } - - fn firstFocusableIndex(self: *const Self) ?usize { - for (self.tabs.items, 0..) |tab, i| { - if (!tab.visible) continue; - if (!self.focus_disabled_tabs and !tab.enabled) continue; - return i; - } - return null; - } - - fn lastFocusableIndex(self: *const Self) ?usize { - if (self.tabs.items.len == 0) return null; - var i = self.tabs.items.len; - while (i > 0) { - i -= 1; - const tab = self.tabs.items[i]; - if (!tab.visible) continue; - if (!self.focus_disabled_tabs and !tab.enabled) continue; - return i; - } - return null; - } - - fn isActivatableIndex(self: *const Self, index: usize) bool { - if (index >= self.tabs.items.len) return false; - const tab = self.tabs.items[index]; - return tab.visible and tab.enabled; - } - - fn isFocusableIndex(self: *const Self, index: usize) bool { - if (index >= self.tabs.items.len) return false; - const tab = self.tabs.items[index]; - if (!tab.visible) return false; - if (!self.focus_disabled_tabs and !tab.enabled) return false; - return true; - } - - fn pickFallbackActiveIndex(self: *const Self, removed_index: usize) ?usize { - if (self.tabs.items.len == 0) return null; - - var i = removed_index; - while (i < self.tabs.items.len) : (i += 1) { - if (self.isActivatableIndex(i)) return i; - } - - i = removed_index; - while (i > 0) { - i -= 1; - if (self.isActivatableIndex(i)) return i; - } - - return null; - } - - fn pickFallbackFocusIndex(self: *const Self, removed_index: usize) ?usize { - if (self.tabs.items.len == 0) return null; - - var i = removed_index; - while (i < self.tabs.items.len) : (i += 1) { - if (self.isFocusableIndex(i)) return i; - } - - i = removed_index; - while (i > 0) { - i -= 1; - if (self.isFocusableIndex(i)) return i; - } - - return self.firstVisibleIndex(); - } - - fn findNextFocusable(self: *const Self, start: usize) ?usize { - if (self.tabs.items.len == 0) return null; - - var i = start + 1; - while (i < self.tabs.items.len) : (i += 1) { - if (self.isFocusableIndex(i)) return i; - } - - if (!self.wrap) return null; - - i = 0; - while (i <= start and i < self.tabs.items.len) : (i += 1) { - if (self.isFocusableIndex(i)) return i; - } - - return null; - } - - fn findPrevFocusable(self: *const Self, start: usize) ?usize { - if (self.tabs.items.len == 0) return null; - if (start > self.tabs.items.len - 1) return self.lastFocusableIndex(); - - var i = start; - while (i > 0) { - i -= 1; - if (self.isFocusableIndex(i)) return i; - } - - if (!self.wrap) return null; - - i = self.tabs.items.len; - while (i > start + 1) { - i -= 1; - if (self.isFocusableIndex(i)) return i; - } - - return null; - } - - fn diffChange(self: *Self, previous_active: ?usize, reason: ChangeReason) ?Change { - if (previous_active == self.active_index) return null; - return .{ - .previous = previous_active, - .current = self.active_index, - .reason = reason, - }; - } - - fn matchAny(_: *Self, event: keys.KeyEvent, binds: [max_binds]?KeyBind) bool { - for (binds) |maybe_bind| { - if (maybe_bind) |bind| { - if (bind.matches(event)) return true; - } - } - return false; - } - - fn leaveActiveRoute(self: *const Self) void { - self.leaveRoute(self.active_index); - } - - fn leaveRoute(self: *const Self, idx: ?usize) void { - if (idx) |i| { - if (i < self.tabs.items.len) { - if (self.tabs.items[i].route) |route| { - if (route.on_leave_fn) |f| f(route.ctx); - } - } - } - } - - fn enterRoute(self: *const Self, idx: usize) void { - if (idx >= self.tabs.items.len) return; - if (self.tabs.items[idx].route) |route| { - if (route.on_enter_fn) |f| f(route.ctx); - } - } -}; - -fn joinedWidth(parts: []const []const u8, separator: []const u8) usize { - if (parts.len == 0) return 0; - - const sep_w = measure.width(separator); - var w: usize = 0; - for (parts, 0..) |part, i| { - if (i > 0) w += sep_w; - w += measure.width(part); - } - return w; -} - -fn rangeWidthWithMarkers(parts: []const []const u8, separator: []const u8, start: usize, end: usize, left_marker_w: usize, right_marker_w: usize, show_left: bool, show_right: bool) usize { - const slice = parts[start..end]; - var w = joinedWidth(slice, separator); - if (show_left) w += left_marker_w; - if (show_right) w += right_marker_w; - return w; -} - -fn joinPieces(allocator: std.mem.Allocator, parts: []const []const u8, separator: []const u8) ![]const u8 { - if (parts.len == 0) return allocator.dupe(u8, ""); - - var out: Writer.Allocating = .init(allocator); - const writer = &out.writer; - for (parts, 0..) |part, i| { - if (i > 0) try writer.writeAll(separator); - try writer.writeAll(part); - } - return out.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig deleted file mode 100644 index c65a196..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/table.zig +++ /dev/null @@ -1,469 +0,0 @@ -//! Table component for displaying tabular data. -//! Supports column headers, alignment, and styling. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const border_mod = @import("../style/border.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); -const keys = @import("../input/keys.zig"); - -pub fn Table(comptime num_cols: usize) type { - return struct { - allocator: std.mem.Allocator, - - // Data - headers: [num_cols][]const u8, - rows: std.array_list.Managed([num_cols][]const u8), - - // Appearance - col_widths: [num_cols]?u16, - col_aligns: [num_cols]Align, - border_chars: border_mod.BorderChars, - show_header: bool, - show_border: bool, - - // Styling - header_style: style_mod.Style, - cell_style: style_mod.Style, - border_style: style_mod.Style, - alt_row_style: ?style_mod.Style, - cursor_row_style: style_mod.Style, - - // Interactive state - cursor_row: usize, - focused: bool, - y_offset: usize, - visible_rows: u16, - - // Row borders - show_row_borders: bool, - - // Per-cell styling callback - style_func: ?*const fn (usize, usize) ?style_mod.Style, - - const Self = @This(); - - pub const Align = enum { - left, - center, - right, - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .headers = .{""} ** num_cols, - .rows = std.array_list.Managed([num_cols][]const u8).init(allocator), - .col_widths = .{null} ** num_cols, - .col_aligns = .{.left} ** num_cols, - .border_chars = .normal, - .show_header = true, - .show_border = true, - .header_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .cell_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .border_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .alt_row_style = null, - .cursor_row_style = blk2: { - var s2 = style_mod.Style{}; - s2 = s2.bold(true); - s2 = s2.reverse(true); - s2 = s2.inline_style(true); - break :blk2 s2; - }, - .cursor_row = 0, - .focused = false, - .y_offset = 0, - .visible_rows = 10, - .show_row_borders = false, - .style_func = null, - }; - } - - pub fn deinit(self: *Self) void { - self.rows.deinit(); - } - - /// Set column headers - pub fn setHeaders(self: *Self, headers: [num_cols][]const u8) void { - self.headers = headers; - } - - /// Add a row - pub fn addRow(self: *Self, row: [num_cols][]const u8) !void { - try self.rows.append(row); - } - - /// Add multiple rows - pub fn addRows(self: *Self, rows: []const [num_cols][]const u8) !void { - try self.rows.appendSlice(rows); - } - - /// Clear all rows - pub fn clearRows(self: *Self) void { - self.rows.clearRetainingCapacity(); - } - - /// Set column width - pub fn setColumnWidth(self: *Self, col: usize, width: u16) void { - if (col < num_cols) { - self.col_widths[col] = width; - } - } - - /// Set column alignment - pub fn setColumnAlign(self: *Self, col: usize, align_val: Align) void { - if (col < num_cols) { - self.col_aligns[col] = align_val; - } - } - - /// Set border style - pub fn setBorder(self: *Self, border: border_mod.BorderChars) void { - self.border_chars = border; - } - - /// Focus the table for interactive mode - pub fn focus(self: *Self) void { - self.focused = true; - } - - /// Blur the table - pub fn blur(self: *Self) void { - self.focused = false; - } - - /// Get the currently selected row index - pub fn selectedRow(self: *const Self) usize { - return self.cursor_row; - } - - /// Handle key event for navigation - pub fn handleKey(self: *Self, key: keys.KeyEvent) void { - if (!self.focused) return; - - switch (key.key) { - .up => { - if (self.cursor_row > 0) self.cursor_row -= 1; - self.ensureRowVisible(); - }, - .down => { - if (self.rows.items.len > 0 and self.cursor_row < self.rows.items.len - 1) { - self.cursor_row += 1; - } - self.ensureRowVisible(); - }, - .page_up => { - if (self.cursor_row >= self.visible_rows) { - self.cursor_row -= self.visible_rows; - } else { - self.cursor_row = 0; - } - self.ensureRowVisible(); - }, - .page_down => { - self.cursor_row += self.visible_rows; - if (self.rows.items.len > 0 and self.cursor_row >= self.rows.items.len) { - self.cursor_row = self.rows.items.len - 1; - } - self.ensureRowVisible(); - }, - .home => { - self.cursor_row = 0; - self.y_offset = 0; - }, - .end => { - if (self.rows.items.len > 0) { - self.cursor_row = self.rows.items.len - 1; - } - self.ensureRowVisible(); - }, - .char => |c| switch (c) { - 'j' => { - if (self.rows.items.len > 0 and self.cursor_row < self.rows.items.len - 1) { - self.cursor_row += 1; - } - self.ensureRowVisible(); - }, - 'k' => { - if (self.cursor_row > 0) self.cursor_row -= 1; - self.ensureRowVisible(); - }, - 'g' => { - self.cursor_row = 0; - self.y_offset = 0; - }, - 'G' => { - if (self.rows.items.len > 0) { - self.cursor_row = self.rows.items.len - 1; - } - self.ensureRowVisible(); - }, - else => {}, - }, - else => {}, - } - } - - fn ensureRowVisible(self: *Self) void { - if (self.cursor_row < self.y_offset) { - self.y_offset = self.cursor_row; - } else if (self.cursor_row >= self.y_offset + self.visible_rows) { - self.y_offset = self.cursor_row - self.visible_rows + 1; - } - } - - /// Calculate actual column widths - fn calculateWidths(self: *const Self) [num_cols]usize { - var widths: [num_cols]usize = .{0} ** num_cols; - - // Check headers - for (0..num_cols) |i| { - if (self.col_widths[i]) |w| { - widths[i] = w; - } else { - widths[i] = @max(widths[i], measure.width(self.headers[i])); - } - } - - // Check rows - for (self.rows.items) |row| { - for (0..num_cols) |i| { - if (self.col_widths[i] == null) { - widths[i] = @max(widths[i], measure.width(row[i])); - } - } - } - - return widths; - } - - /// Render the table - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const widths = self.calculateWidths(); - - // Top border - if (self.show_border) { - try self.writeBorderLine(writer, allocator, widths, .top); - try writer.writeByte('\n'); - } - - // Header - if (self.show_header) { - try self.writeRow(writer, allocator, self.headers, widths, self.header_style); - try writer.writeByte('\n'); - - // Header separator - if (self.show_border) { - try self.writeBorderLine(writer, allocator, widths, .middle); - try writer.writeByte('\n'); - } - } - - // Data rows (with viewport if focused) - const start_row = if (self.focused) self.y_offset else 0; - const end_row = if (self.focused) - @min(start_row + self.visible_rows, self.rows.items.len) - else - self.rows.items.len; - - for (start_row..end_row) |row_idx| { - const row = self.rows.items[row_idx]; - const row_style = if (self.focused and row_idx == self.cursor_row) - self.cursor_row_style - else if (self.style_func) |func| blk: { - if (func(row_idx, 0)) |s| { - break :blk s; - } - break :blk if (self.alt_row_style != null and row_idx % 2 == 1) - self.alt_row_style.? - else - self.cell_style; - } else if (self.alt_row_style != null and row_idx % 2 == 1) - self.alt_row_style.? - else - self.cell_style; - - try self.writeRow(writer, allocator, row, widths, row_style); - if (row_idx < end_row - 1 or self.show_border) { - try writer.writeByte('\n'); - } - - // Row borders between data rows - if (self.show_row_borders and row_idx < end_row - 1) { - try self.writeBorderLine(writer, allocator, widths, .middle); - try writer.writeByte('\n'); - } - } - - // Bottom border - if (self.show_border) { - try self.writeBorderLine(writer, allocator, widths, .bottom); - } - - return result.toOwnedSlice(); - } - - fn writeRow( - self: *const Self, - writer: *Writer, - allocator: std.mem.Allocator, - row: [num_cols][]const u8, - widths: [num_cols]usize, - row_style: style_mod.Style, - ) !void { - if (self.show_border) { - const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); - try writer.writeAll(border_rendered); - } - - for (0..num_cols) |i| { - if (i > 0 and self.show_border) { - const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); - try writer.writeAll(border_rendered); - } - - try writer.writeByte(' '); - - const cell = row[i]; - const width = widths[i]; - const cell_width = measure.width(cell); - const padding = if (width > cell_width) width - cell_width else 0; - - switch (self.col_aligns[i]) { - .left => { - const styled = try row_style.render(allocator, cell); - try writer.writeAll(styled); - for (0..padding) |_| try writer.writeByte(' '); - }, - .center => { - const left_pad = padding / 2; - const right_pad = padding - left_pad; - for (0..left_pad) |_| try writer.writeByte(' '); - const styled = try row_style.render(allocator, cell); - try writer.writeAll(styled); - for (0..right_pad) |_| try writer.writeByte(' '); - }, - .right => { - for (0..padding) |_| try writer.writeByte(' '); - const styled = try row_style.render(allocator, cell); - try writer.writeAll(styled); - }, - } - - try writer.writeByte(' '); - } - - if (self.show_border) { - const border_rendered = try self.border_style.render(allocator, self.border_chars.vertical); - try writer.writeAll(border_rendered); - } - } - - const BorderPosition = enum { top, middle, bottom }; - - fn writeBorderLine( - self: *const Self, - writer: *Writer, - allocator: std.mem.Allocator, - widths: [num_cols]usize, - pos: BorderPosition, - ) !void { - const left = switch (pos) { - .top => self.border_chars.top_left, - .middle => self.border_chars.middle_left, - .bottom => self.border_chars.bottom_left, - }; - const mid = switch (pos) { - .top => self.border_chars.middle_top, - .middle => self.border_chars.cross, - .bottom => self.border_chars.middle_bottom, - }; - const right = switch (pos) { - .top => self.border_chars.top_right, - .middle => self.border_chars.middle_right, - .bottom => self.border_chars.bottom_right, - }; - - const left_styled = try self.border_style.render(allocator, left); - try writer.writeAll(left_styled); - - for (0..num_cols) |i| { - if (i > 0) { - const mid_styled = try self.border_style.render(allocator, mid); - try writer.writeAll(mid_styled); - } - - const h_styled = try self.border_style.render(allocator, self.border_chars.horizontal); - for (0..widths[i] + 2) |_| { - try writer.writeAll(h_styled); - } - } - - const right_styled = try self.border_style.render(allocator, right); - try writer.writeAll(right_styled); - } - }; -} - -/// Create a table with dynamic column count -pub fn DynamicTable(allocator: std.mem.Allocator) DynamicTableType { - return DynamicTableType.init(allocator); -} - -pub const DynamicTableType = struct { - allocator: std.mem.Allocator, - headers: std.array_list.Managed([]const u8), - rows: std.array_list.Managed(std.array_list.Managed([]const u8)), - border_chars: border_mod.BorderChars, - show_header: bool, - show_border: bool, - - pub fn init(allocator: std.mem.Allocator) DynamicTableType { - return .{ - .allocator = allocator, - .headers = std.array_list.Managed([]const u8).init(allocator), - .rows = std.array_list.Managed(std.array_list.Managed([]const u8)).init(allocator), - .border_chars = .normal, - .show_header = true, - .show_border = true, - }; - } - - pub fn deinit(self: *DynamicTableType) void { - self.headers.deinit(); - for (self.rows.items) |*row| { - row.deinit(); - } - self.rows.deinit(); - } - - pub fn setHeaders(self: *DynamicTableType, headers: []const []const u8) !void { - self.headers.clearRetainingCapacity(); - try self.headers.appendSlice(headers); - } - - pub fn addRow(self: *DynamicTableType, cells: []const []const u8) !void { - var row = std.array_list.Managed([]const u8).init(self.allocator); - try row.appendSlice(cells); - try self.rows.append(row); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig deleted file mode 100644 index 1e969b8..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_area.zig +++ /dev/null @@ -1,1057 +0,0 @@ -//! Multi-line text area component. -//! Provides text editing with multiple lines, cursor navigation, and scrolling. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const unicode = @import("../unicode.zig"); - -pub const TextArea = struct { - allocator: std.mem.Allocator, - - // Content - lines: std.array_list.Managed(std.array_list.Managed(u8)), - - // Cursor position - cursor_row: usize, - cursor_col: usize, - - // Viewport - viewport_row: usize, - viewport_col: usize, - width: u16, - height: u16, - - // Appearance - placeholder: []const u8, - line_numbers: bool, - word_wrap: bool, - - // Styling - text_style: style_mod.Style, - cursor_style: style_mod.Style, - line_number_style: style_mod.Style, - placeholder_style: style_mod.Style, - - // State - focused: bool, - - // Limits - max_lines: ?usize, - max_cols: ?usize, - char_limit: ?usize, - - const WrappedSegment = struct { - start: usize, - end: usize, - is_last: bool, - }; - - const WrappedRow = struct { - line_idx: usize, - start: usize, - end: usize, - is_first_segment: bool, - }; - - const CursorWrappedSegment = struct { - current_start: usize, - current_end: usize, - prev_start: ?usize, - is_last: bool, - }; - - pub fn init(allocator: std.mem.Allocator) TextArea { - var lines = std.array_list.Managed(std.array_list.Managed(u8)).init(allocator); - lines.append(std.array_list.Managed(u8).init(allocator)) catch {}; - - return .{ - .allocator = allocator, - .lines = lines, - .cursor_row = 0, - .cursor_col = 0, - .viewport_row = 0, - .viewport_col = 0, - .width = 80, - .height = 10, - .placeholder = "", - .line_numbers = false, - .word_wrap = false, - .text_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style_mod.Style{}; - s = s.reverse(true); - s = s.inline_style(true); - break :blk s; - }, - .line_number_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .placeholder_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .focused = true, - .max_lines = null, - .max_cols = null, - .char_limit = null, - }; - } - - pub fn deinit(self: *TextArea) void { - for (self.lines.items) |*line| { - line.deinit(); - } - self.lines.deinit(); - } - - /// Set the content - pub fn setValue(self: *TextArea, text: []const u8) !void { - // Clear existing lines - for (self.lines.items) |*line| { - line.deinit(); - } - self.lines.clearRetainingCapacity(); - - // Parse lines - var iter = std.mem.splitScalar(u8, text, '\n'); - while (iter.next()) |line_text| { - var line = std.array_list.Managed(u8).init(self.allocator); - try line.appendSlice(line_text); - try self.lines.append(line); - } - - if (self.lines.items.len == 0) { - try self.lines.append(std.array_list.Managed(u8).init(self.allocator)); - } - - // Reset cursor - self.cursor_row = 0; - self.cursor_col = 0; - self.viewport_row = 0; - } - - /// Get the content as a string - pub fn getValue(self: *const TextArea, allocator: std.mem.Allocator) ![]const u8 { - var result: std.array_list.Managed(u8) = .init(allocator); - - for (self.lines.items, 0..) |line, i| { - if (i > 0) try result.append('\n'); - try result.appendSlice(line.items); - } - - return result.toOwnedSlice(); - } - - /// Get total character count - pub fn charCount(self: *const TextArea) usize { - var count: usize = 0; - for (self.lines.items, 0..) |line, i| { - if (i > 0) count += 1; // Newline - count += line.items.len; - } - return count; - } - - /// Get line count - pub fn lineCount(self: *const TextArea) usize { - return self.lines.items.len; - } - - /// Set dimensions - pub fn setSize(self: *TextArea, width: u16, height: u16) void { - self.width = width; - self.height = height; - self.ensureVisible(); - } - - /// Focus the text area - pub fn focus(self: *TextArea) void { - self.focused = true; - } - - /// Blur the text area - pub fn blur(self: *TextArea) void { - self.focused = false; - } - - /// Handle key event - pub fn handleKey(self: *TextArea, key: keys.KeyEvent) void { - if (!self.focused) return; - - if (key.modifiers.ctrl) { - switch (key.key) { - .char => |c| switch (c) { - 'a' => self.cursor_col = 0, // Home - 'e' => self.cursor_col = self.currentLine().items.len, // End - 'k' => self.killToEndOfLine(), // Kill line - 'u' => self.killToStartOfLine(), // Kill to start - 'd' => self.deleteLine(), // Delete line - else => {}, - }, - else => {}, - } - return; - } - - switch (key.key) { - .char => |c| self.insertChar(c), - .paste => |text| self.insertText(text), - .enter => self.insertNewline(), - .backspace => self.deleteBackward(), - .delete => self.deleteForward(), - .up => self.moveCursorUp(), - .down => self.moveCursorDown(), - .left => self.moveCursorLeft(), - .right => self.moveCursorRight(), - .home => self.cursor_col = 0, - .end => self.cursor_col = self.currentLine().items.len, - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .tab => self.insertTab(), - else => {}, - } - - self.ensureVisible(); - } - - fn currentLine(self: *TextArea) *std.array_list.Managed(u8) { - return &self.lines.items[self.cursor_row]; - } - - fn insertChar(self: *TextArea, c: u21) void { - // Check char limit - if (self.char_limit) |limit| { - if (self.charCount() >= limit) return; - } - - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch return; - - const line = self.currentLine(); - const pos = @min(self.cursor_col, line.items.len); - line.insertSlice(pos, buf[0..len]) catch return; - self.cursor_col = pos + len; - } - - fn insertText(self: *TextArea, text: []const u8) void { - var i: usize = 0; - while (i < text.len) { - if (text[i] == '\r') { - self.insertNewline(); - if (i + 1 < text.len and text[i + 1] == '\n') i += 1; - i += 1; - continue; - } - if (text[i] == '\n') { - self.insertNewline(); - i += 1; - continue; - } - - const len = std.unicode.utf8ByteSequenceLength(text[i]) catch { - self.insertChar(text[i]); - i += 1; - continue; - }; - if (i + len > text.len) { - self.insertChar(text[i]); - i += 1; - continue; - } - - const codepoint = std.unicode.utf8Decode(text[i .. i + len]) catch { - self.insertChar(text[i]); - i += 1; - continue; - }; - self.insertChar(codepoint); - i += len; - } - } - - fn insertNewline(self: *TextArea) void { - if (self.max_lines) |max| { - if (self.lines.items.len >= max) return; - } - - self.clampCursorToLineBoundary(); - const line = self.currentLine(); - const rest = line.items[self.cursor_col..]; - - // Create new line with rest of content - var new_line = std.array_list.Managed(u8).init(self.allocator); - new_line.appendSlice(rest) catch return; - - // Truncate current line - line.shrinkRetainingCapacity(self.cursor_col); - - // Insert new line - self.lines.insert(self.cursor_row + 1, new_line) catch return; - - self.cursor_row += 1; - self.cursor_col = 0; - } - - fn insertTab(self: *TextArea) void { - // Insert spaces for tab - for (0..4) |_| { - self.insertChar(' '); - } - } - - fn deleteBackward(self: *TextArea) void { - if (self.cursor_col > 0) { - // Delete character before cursor - const line = self.currentLine(); - var pos = self.cursor_col - 1; - - // Find start of UTF-8 sequence - while (pos > 0 and (line.items[pos] & 0xC0) == 0x80) { - pos -= 1; - } - - const len = self.cursor_col - pos; - for (0..len) |_| { - _ = line.orderedRemove(pos); - } - self.cursor_col = pos; - } else if (self.cursor_row > 0) { - // Join with previous line - const current = self.lines.orderedRemove(self.cursor_row); - self.cursor_row -= 1; - const prev_line = self.currentLine(); - self.cursor_col = prev_line.items.len; - prev_line.appendSlice(current.items) catch {}; - @constCast(¤t).deinit(); - } - } - - fn deleteForward(self: *TextArea) void { - const line = self.currentLine(); - self.clampCursorToLineBoundary(); - if (self.cursor_col < line.items.len) { - // Delete character at cursor - const byte_len = std.unicode.utf8ByteSequenceLength(line.items[self.cursor_col]) catch 1; - for (0..byte_len) |_| { - if (self.cursor_col < line.items.len) { - _ = line.orderedRemove(self.cursor_col); - } - } - } else if (self.cursor_row < self.lines.items.len - 1) { - // Join with next line - const next = self.lines.orderedRemove(self.cursor_row + 1); - line.appendSlice(next.items) catch {}; - @constCast(&next).deinit(); - } - } - - fn killToEndOfLine(self: *TextArea) void { - self.clampCursorToLineBoundary(); - const line = self.currentLine(); - line.shrinkRetainingCapacity(self.cursor_col); - } - - fn killToStartOfLine(self: *TextArea) void { - self.clampCursorToLineBoundary(); - const line = self.currentLine(); - std.mem.copyForwards(u8, line.items[0..], line.items[self.cursor_col..]); - line.shrinkRetainingCapacity(line.items.len - self.cursor_col); - self.cursor_col = 0; - } - - fn deleteLine(self: *TextArea) void { - if (self.lines.items.len > 1) { - var removed = self.lines.orderedRemove(self.cursor_row); - removed.deinit(); - if (self.cursor_row >= self.lines.items.len) { - self.cursor_row = self.lines.items.len - 1; - } - self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); - self.clampCursorToLineBoundary(); - } else { - self.currentLine().clearRetainingCapacity(); - self.cursor_col = 0; - } - } - - fn moveCursorUp(self: *TextArea) void { - if (self.word_wrap) { - const max_width = self.textWidth(); - const line = self.currentLine().items; - const segment = self.findCursorWrappedSegment(line, max_width); - const target_col = displayWidthInRange(line, segment.current_start, self.cursor_col, max_width); - - if (segment.prev_start) |prev_start| { - const prev = wrappedSegmentAt(line, max_width, prev_start); - self.cursor_col = byteOffsetForDisplayCol(line, prev.start, prev.end, target_col, max_width); - return; - } - - if (self.cursor_row > 0) { - self.cursor_row -= 1; - const prev_line = self.currentLine().items; - const prev_start = lastWrappedSegmentStart(prev_line, max_width); - const prev = wrappedSegmentAt(prev_line, max_width, prev_start); - self.cursor_col = byteOffsetForDisplayCol(prev_line, prev.start, prev.end, target_col, max_width); - } - return; - } - - if (self.cursor_row > 0) { - self.cursor_row -= 1; - self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); - self.clampCursorToLineBoundary(); - } - } - - fn moveCursorDown(self: *TextArea) void { - if (self.word_wrap) { - const max_width = self.textWidth(); - const line = self.currentLine().items; - const segment = self.findCursorWrappedSegment(line, max_width); - const target_col = displayWidthInRange(line, segment.current_start, self.cursor_col, max_width); - - if (!segment.is_last) { - const next = wrappedSegmentAt(line, max_width, segment.current_end); - self.cursor_col = byteOffsetForDisplayCol(line, next.start, next.end, target_col, max_width); - return; - } - - if (self.cursor_row < self.lines.items.len - 1) { - self.cursor_row += 1; - const next_line = self.currentLine().items; - const next = wrappedSegmentAt(next_line, max_width, 0); - self.cursor_col = byteOffsetForDisplayCol(next_line, next.start, next.end, target_col, max_width); - } - return; - } - - if (self.cursor_row < self.lines.items.len - 1) { - self.cursor_row += 1; - self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); - self.clampCursorToLineBoundary(); - } - } - - fn moveCursorLeft(self: *TextArea) void { - self.clampCursorToLineBoundary(); - if (self.cursor_col > 0) { - self.cursor_col -= 1; - // Handle UTF-8 continuation bytes - const line = self.currentLine(); - while (self.cursor_col > 0 and (line.items[self.cursor_col] & 0xC0) == 0x80) { - self.cursor_col -= 1; - } - } else if (self.cursor_row > 0) { - self.cursor_row -= 1; - self.cursor_col = self.currentLine().items.len; - } - } - - fn moveCursorRight(self: *TextArea) void { - const line = self.currentLine(); - self.clampCursorToLineBoundary(); - if (self.cursor_col < line.items.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(line.items[self.cursor_col]) catch 1; - self.cursor_col = @min(self.cursor_col + byte_len, line.items.len); - } else if (self.cursor_row < self.lines.items.len - 1) { - self.cursor_row += 1; - self.cursor_col = 0; - } - } - - fn pageUp(self: *TextArea) void { - if (self.word_wrap) { - for (0..@max(@as(usize, 1), @as(usize, self.height))) |_| { - self.moveCursorUp(); - } - return; - } - - if (self.cursor_row >= self.height) { - self.cursor_row -= self.height; - } else { - self.cursor_row = 0; - } - self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); - self.clampCursorToLineBoundary(); - } - - fn pageDown(self: *TextArea) void { - if (self.word_wrap) { - for (0..@max(@as(usize, 1), @as(usize, self.height))) |_| { - self.moveCursorDown(); - } - return; - } - - if (self.cursor_row + self.height < self.lines.items.len) { - self.cursor_row += self.height; - } else { - self.cursor_row = self.lines.items.len - 1; - } - self.cursor_col = @min(self.cursor_col, self.currentLine().items.len); - self.clampCursorToLineBoundary(); - } - - fn ensureVisible(self: *TextArea) void { - const visible_rows: usize = @max(@as(usize, 1), @as(usize, self.height)); - - if (self.word_wrap) { - const cursor_visual_row = self.cursorVisualRow(self.textWidth()); - if (cursor_visual_row < self.viewport_row) { - self.viewport_row = cursor_visual_row; - } else if (cursor_visual_row >= self.viewport_row + visible_rows) { - self.viewport_row = cursor_visual_row - visible_rows + 1; - } - self.viewport_col = 0; - return; - } - - // Vertical scrolling - if (self.cursor_row < self.viewport_row) { - self.viewport_row = self.cursor_row; - } else if (self.cursor_row >= self.viewport_row + visible_rows) { - self.viewport_row = self.cursor_row - visible_rows + 1; - } - - // Horizontal scrolling using display columns - const effective_width = self.width -| (if (self.line_numbers) @as(u16, 5) else 0); - const display_col = self.cursorDisplayCol(); - if (display_col < self.viewport_col) { - self.viewport_col = display_col; - } else if (display_col >= self.viewport_col + effective_width) { - self.viewport_col = display_col - effective_width + 1; - } - } - - /// Cursor column in terminal cells (display width), 0-indexed. - pub fn cursorDisplayColumn(self: *const TextArea) usize { - return self.cursorDisplayCol(); - } - - /// Render the text area - pub fn view(self: *const TextArea, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const line_num_width: usize = if (self.line_numbers) 5 else 0; - const text_width = self.width -| @as(u16, @intCast(line_num_width)); - - // Check for empty content - const is_empty = self.lines.items.len == 1 and self.lines.items[0].items.len == 0; - - if (self.word_wrap) { - for (0..self.height) |row| { - if (row > 0) try writer.writeByte('\n'); - - const visual_row = self.viewport_row + row; - const wrapped_row = self.wrappedRowAt(visual_row, text_width); - - // Line numbers (only on first wrapped segment of a physical line) - if (self.line_numbers) { - if (wrapped_row) |r| { - if (r.is_first_segment) { - const num_str = try std.fmt.allocPrint(allocator, "{d:>4} ", .{r.line_idx + 1}); - defer allocator.free(num_str); - const styled = try self.line_number_style.render(allocator, num_str); - defer allocator.free(styled); - try writer.writeAll(styled); - } else { - try writer.writeAll(" "); - } - } else { - try writer.writeAll(" "); - } - } - - if (wrapped_row) |r| { - const line = self.lines.items[r.line_idx]; - - // Show placeholder on first empty line - if (is_empty and r.line_idx == 0 and r.is_first_segment and self.placeholder.len > 0) { - try self.renderPlaceholder(writer, allocator, text_width); - continue; - } - - try self.renderWrappedLineSegment( - writer, - allocator, - line.items, - r.line_idx, - r.start, - r.end, - text_width, - ); - } else { - for (0..text_width) |_| { - try writer.writeByte(' '); - } - } - } - - return result.toOwnedSlice(); - } - - for (0..self.height) |row| { - if (row > 0) try writer.writeByte('\n'); - - const line_idx = self.viewport_row + row; - - // Line numbers - if (self.line_numbers) { - if (line_idx < self.lines.items.len) { - const num_str = try std.fmt.allocPrint(allocator, "{d:>4} ", .{line_idx + 1}); - defer allocator.free(num_str); - const styled = try self.line_number_style.render(allocator, num_str); - defer allocator.free(styled); - try writer.writeAll(styled); - } else { - try writer.writeAll(" "); - } - } - - if (line_idx < self.lines.items.len) { - const line = self.lines.items[line_idx]; - - // Show placeholder on first empty line - if (is_empty and line_idx == 0 and self.placeholder.len > 0) { - try self.renderPlaceholder(writer, allocator, text_width); - continue; - } - - // Render line content with cursor - try self.renderLine(writer, allocator, line.items, line_idx, text_width); - } else { - // Pad empty rows to full width - var i: usize = 0; - while (i < text_width) : (i += 1) { - try writer.writeByte(' '); - } - } - } - - return result.toOwnedSlice(); - } - - fn renderPlaceholder(self: *const TextArea, writer: *Writer, allocator: std.mem.Allocator, max_width: u16) !void { - const width_limit: usize = max_width; - if (width_limit == 0) return; - - var rendered_width: usize = 0; - var byte_idx: usize = 0; - while (byte_idx < self.placeholder.len and rendered_width < width_limit) { - const byte_len = std.unicode.utf8ByteSequenceLength(self.placeholder[byte_idx]) catch 1; - if (byte_idx + byte_len > self.placeholder.len) break; - const char_slice = self.placeholder[byte_idx..][0..byte_len]; - - const cp = std.unicode.utf8Decode(char_slice) catch { - byte_idx += 1; - rendered_width += 1; - continue; - }; - const cw = wrapDisplayWidth(unicode.charWidth(cp), width_limit); - if (rendered_width + cw > width_limit) break; - - const styled = try self.placeholder_style.render(allocator, char_slice); - defer allocator.free(styled); - try writer.writeAll(styled); - byte_idx += byte_len; - rendered_width += cw; - } - - while (rendered_width < width_limit) { - try writer.writeByte(' '); - rendered_width += 1; - } - } - - fn renderWrappedLineSegment( - self: *const TextArea, - writer: *Writer, - allocator: std.mem.Allocator, - line: []const u8, - line_idx: usize, - start: usize, - end: usize, - max_width: u16, - ) !void { - const is_cursor_line = line_idx == self.cursor_row; - const width_limit: usize = max_width; - - if (width_limit == 0) return; - - var rendered_width: usize = 0; - var byte_idx = start; - while (byte_idx < end and rendered_width < width_limit) { - const is_cursor = is_cursor_line and self.focused and byte_idx == self.cursor_col; - - const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; - if (byte_idx + byte_len > line.len) break; - const char_slice = line[byte_idx..][0..byte_len]; - - const cp = std.unicode.utf8Decode(char_slice) catch { - byte_idx += 1; - rendered_width += 1; - continue; - }; - const cw = wrapDisplayWidth(unicode.charWidth(cp), width_limit); - if (rendered_width + cw > width_limit) break; - - if (is_cursor) { - const styled = try self.cursor_style.render(allocator, char_slice); - defer allocator.free(styled); - try writer.writeAll(styled); - } else { - const styled = try self.text_style.render(allocator, char_slice); - defer allocator.free(styled); - try writer.writeAll(styled); - } - - byte_idx += byte_len; - rendered_width += cw; - } - - // Cursor at segment end - if (is_cursor_line and self.focused and self.cursor_col == end and end == line.len and rendered_width < width_limit) { - const styled = try self.cursor_style.render(allocator, " "); - defer allocator.free(styled); - try writer.writeAll(styled); - rendered_width += 1; - } - - while (rendered_width < width_limit) { - try writer.writeByte(' '); - rendered_width += 1; - } - } - - fn renderLine(self: *const TextArea, writer: *Writer, allocator: std.mem.Allocator, line: []const u8, line_idx: usize, max_width: u16) !void { - const is_cursor_line = line_idx == self.cursor_row; - - // Apply horizontal scroll - var col: usize = 0; - var byte_idx: usize = 0; - - // Skip to viewport_col (using display columns) - while (col < self.viewport_col and byte_idx < line.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; - if (byte_idx + byte_len <= line.len) { - const cp = std.unicode.utf8Decode(line[byte_idx..][0..byte_len]) catch { - byte_idx += 1; - col += 1; - continue; - }; - col += unicode.charWidth(cp); - } - byte_idx += byte_len; - } - - // Render visible portion - var rendered_width: usize = 0; - while (byte_idx < line.len and rendered_width < max_width) { - const is_cursor = is_cursor_line and self.focused and byte_idx == self.cursor_col; - - const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_idx]) catch 1; - if (byte_idx + byte_len > line.len) break; - const char_slice = line[byte_idx..][0..byte_len]; - - const cp = std.unicode.utf8Decode(line[byte_idx..][0..byte_len]) catch { - byte_idx += 1; - rendered_width += 1; - continue; - }; - const cw = unicode.charWidth(cp); - - // Wide char won't fit — stop - if (rendered_width + cw > max_width) break; - - if (is_cursor) { - const styled = try self.cursor_style.render(allocator, char_slice); - defer allocator.free(styled); - try writer.writeAll(styled); - } else { - const styled = try self.text_style.render(allocator, char_slice); - defer allocator.free(styled); - try writer.writeAll(styled); - } - - byte_idx += byte_len; - col += cw; - rendered_width += cw; - } - - // Cursor at end of line - if (is_cursor_line and self.focused and byte_idx == self.cursor_col and rendered_width < max_width) { - const styled = try self.cursor_style.render(allocator, " "); - defer allocator.free(styled); - try writer.writeAll(styled); - rendered_width += 1; - } - - // Pad remaining width - while (rendered_width < max_width) { - try writer.writeByte(' '); - rendered_width += 1; - } - } - - /// Convert byte-offset cursor_col to display column width. - fn cursorDisplayCol(self: *const TextArea) usize { - const line = self.lines.items[self.cursor_row]; - var display_col: usize = 0; - var byte_idx: usize = 0; - while (byte_idx < self.cursor_col and byte_idx < line.items.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(line.items[byte_idx]) catch 1; - if (byte_idx + byte_len <= line.items.len) { - const cp = std.unicode.utf8Decode(line.items[byte_idx..][0..byte_len]) catch { - byte_idx += 1; - display_col += 1; - continue; - }; - display_col += unicode.charWidth(cp); - } - byte_idx += byte_len; - } - return display_col; - } - - fn textWidth(self: *const TextArea) usize { - const line_num_width: usize = if (self.line_numbers) 5 else 0; - return self.width -| @as(u16, @intCast(line_num_width)); - } - - fn cursorVisualRow(self: *const TextArea, max_width: usize) usize { - var row: usize = 0; - for (0..self.cursor_row) |idx| { - row += wrappedRowCount(self.lines.items[idx].items, max_width); - } - row += wrappedRowIndexForCursor(self.lines.items[self.cursor_row].items, self.cursor_col, max_width); - return row; - } - - fn wrappedRowAt(self: *const TextArea, visual_row: usize, max_width: u16) ?WrappedRow { - var row_index: usize = 0; - const width: usize = max_width; - - for (self.lines.items, 0..) |line, line_idx| { - const line_bytes = line.items; - if (line_bytes.len == 0) { - if (row_index == visual_row) { - return .{ - .line_idx = line_idx, - .start = 0, - .end = 0, - .is_first_segment = true, - }; - } - row_index += 1; - continue; - } - - var segment_start: usize = 0; - var first = true; - while (true) { - const segment = wrappedSegmentAt(line_bytes, width, segment_start); - if (row_index == visual_row) { - return .{ - .line_idx = line_idx, - .start = segment.start, - .end = segment.end, - .is_first_segment = first, - }; - } - - row_index += 1; - if (segment.is_last) break; - segment_start = segment.end; - first = false; - } - } - return null; - } - - fn findCursorWrappedSegment(self: *const TextArea, line: []const u8, max_width: usize) CursorWrappedSegment { - const clamped_cursor = clampToUtf8Boundary(line, self.cursor_col); - var segment_start: usize = 0; - var prev_start: ?usize = null; - while (true) { - const segment = wrappedSegmentAt(line, max_width, segment_start); - if (clamped_cursor < segment.end or segment.is_last) { - return .{ - .current_start = segment.start, - .current_end = segment.end, - .prev_start = prev_start, - .is_last = segment.is_last, - }; - } - - if (segment.is_last) break; - prev_start = segment_start; - segment_start = segment.end; - } - - return .{ - .current_start = 0, - .current_end = line.len, - .prev_start = null, - .is_last = true, - }; - } - - fn wrappedRowCount(line: []const u8, max_width: usize) usize { - if (line.len == 0) return 1; - if (max_width == 0) return 1; - - var count: usize = 0; - var segment_start: usize = 0; - while (true) { - const segment = wrappedSegmentAt(line, max_width, segment_start); - count += 1; - if (segment.is_last) break; - segment_start = segment.end; - } - return count; - } - - fn wrappedRowIndexForCursor(line: []const u8, cursor_col: usize, max_width: usize) usize { - if (line.len == 0) return 0; - if (max_width == 0) return 0; - - const clamped_cursor = clampToUtf8Boundary(line, cursor_col); - var index: usize = 0; - var segment_start: usize = 0; - while (true) { - const segment = wrappedSegmentAt(line, max_width, segment_start); - if (clamped_cursor < segment.end or segment.is_last) return index; - if (segment.is_last) return index; - index += 1; - segment_start = segment.end; - } - } - - fn lastWrappedSegmentStart(line: []const u8, max_width: usize) usize { - if (line.len == 0 or max_width == 0) return 0; - var segment_start: usize = 0; - while (true) { - const segment = wrappedSegmentAt(line, max_width, segment_start); - if (segment.is_last) return segment_start; - segment_start = segment.end; - } - } - - fn wrappedSegmentAt(line: []const u8, max_width: usize, start: usize) WrappedSegment { - if (line.len == 0 or max_width == 0 or start >= line.len) { - return .{ - .start = @min(start, line.len), - .end = @min(start, line.len), - .is_last = true, - }; - } - - var i = start; - var segment_width: usize = 0; - - while (i < line.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; - if (i + byte_len > line.len) break; - - const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { - if (segment_width > 0 and segment_width + 1 > max_width) break; - segment_width += 1; - i += 1; - continue; - }; - - const char_width = wrapDisplayWidth(unicode.charWidth(cp), max_width); - if (segment_width > 0 and segment_width + char_width > max_width) break; - - segment_width += char_width; - i += byte_len; - } - - return .{ - .start = start, - .end = i, - .is_last = i >= line.len, - }; - } - - fn displayWidthInRange(line: []const u8, start: usize, end: usize, max_width: usize) usize { - if (max_width == 0) return 0; - const clamped_end = clampToUtf8Boundary(line, @min(end, line.len)); - var width: usize = 0; - var i = @min(start, clamped_end); - while (i < clamped_end) { - const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; - if (i + byte_len > line.len) break; - const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { - width += 1; - i += 1; - continue; - }; - width += wrapDisplayWidth(unicode.charWidth(cp), max_width); - i += byte_len; - } - return width; - } - - fn byteOffsetForDisplayCol(line: []const u8, start: usize, end: usize, target_col: usize, max_width: usize) usize { - if (max_width == 0) return @min(start, line.len); - - const clamped_start = clampToUtf8Boundary(line, @min(start, line.len)); - const clamped_end = clampToUtf8Boundary(line, @min(end, line.len)); - var col: usize = 0; - var i = clamped_start; - while (i < clamped_end) { - if (col >= target_col) return i; - - const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; - if (i + byte_len > line.len) break; - const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { - if (col + 1 > target_col) return i; - col += 1; - i += 1; - continue; - }; - - const char_width = wrapDisplayWidth(unicode.charWidth(cp), max_width); - if (col + char_width > target_col) return i; - - col += char_width; - i += byte_len; - } - return clamped_end; - } - - fn wrapDisplayWidth(char_width: usize, max_width: usize) usize { - if (max_width == 0) return 0; - if (char_width == 0) return 0; - return @min(char_width, max_width); - } - - fn clampCursorToLineBoundary(self: *TextArea) void { - const line = self.currentLine(); - self.cursor_col = clampToUtf8Boundary(line.items, self.cursor_col); - } - - fn clampToUtf8Boundary(line: []const u8, pos: usize) usize { - var clamped = @min(pos, line.len); - while (clamped > 0 and clamped < line.len and (line[clamped] & 0xC0) == 0x80) { - clamped -= 1; - } - return clamped; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig deleted file mode 100644 index 5bd0fb8..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/text_input.zig +++ /dev/null @@ -1,462 +0,0 @@ -//! Single-line text input component. -//! Provides cursor navigation, text editing, and optional validation. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const style = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const TextInput = struct { - allocator: std.mem.Allocator, - - // Content - value: std.array_list.Managed(u8), - cursor: usize, - - // Appearance - placeholder: []const u8, - prompt: []const u8, - width: ?u16, - char_limit: ?usize, - echo_mode: EchoMode, - - // Styling - text_style: style.Style, - placeholder_style: style.Style, - cursor_style: style.Style, - prompt_style: style.Style, - - // State - focused: bool, - - // Validation - validate_fn: ?*const fn ([]const u8) bool, - - // Suggestions/autocomplete - suggestions: []const []const u8, - current_suggestion_idx: usize, - show_suggestions: bool, - suggestion_style: style.Style, - - pub const EchoMode = enum { - normal, - password, - none, - }; - - pub fn init(allocator: std.mem.Allocator) TextInput { - return .{ - .allocator = allocator, - .value = std.array_list.Managed(u8).init(allocator), - .cursor = 0, - .placeholder = "", - .prompt = "", - .width = null, - .char_limit = null, - .echo_mode = .normal, - .text_style = blk: { - var s = style.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .placeholder_style = blk: { - var s = style.Style{}; - s = s.fg(.gray(12)); - s = s.inline_style(true); - break :blk s; - }, - .cursor_style = blk: { - var s = style.Style{}; - s = s.reverse(true); - s = s.inline_style(true); - break :blk s; - }, - .prompt_style = blk: { - var s = style.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .focused = true, - .validate_fn = null, - .suggestions = &.{}, - .current_suggestion_idx = 0, - .show_suggestions = true, - .suggestion_style = blk2: { - var s2 = style.Style{}; - s2 = s2.dim(true); - s2 = s2.inline_style(true); - break :blk2 s2; - }, - }; - } - - pub fn deinit(self: *TextInput) void { - self.value.deinit(); - } - - /// Set the input value - pub fn setValue(self: *TextInput, text: []const u8) !void { - self.value.clearRetainingCapacity(); - try self.value.appendSlice(text); - self.cursor = @min(self.cursor, self.value.items.len); - } - - /// Get the current value - pub fn getValue(self: *const TextInput) []const u8 { - return self.value.items; - } - - /// Set placeholder text - pub fn setPlaceholder(self: *TextInput, text: []const u8) void { - self.placeholder = text; - } - - /// Set prompt text - pub fn setPrompt(self: *TextInput, text: []const u8) void { - self.prompt = text; - } - - /// Set width limit - pub fn setWidth(self: *TextInput, w: u16) void { - self.width = w; - } - - /// Set character limit - pub fn setCharLimit(self: *TextInput, limit: usize) void { - self.char_limit = limit; - } - - /// Set echo mode - pub fn setEchoMode(self: *TextInput, mode: EchoMode) void { - self.echo_mode = mode; - } - - /// Set validation function - pub fn setValidation(self: *TextInput, validate: *const fn ([]const u8) bool) void { - self.validate_fn = validate; - } - - /// Focus the input - pub fn focus(self: *TextInput) void { - self.focused = true; - } - - /// Blur the input - pub fn blur(self: *TextInput) void { - self.focused = false; - } - - /// Check if input is valid - pub fn isValid(self: *const TextInput) bool { - if (self.validate_fn) |validate| { - return validate(self.value.items); - } - return true; - } - - /// Set suggestion list - pub fn setSuggestions(self: *TextInput, list: []const []const u8) void { - self.suggestions = list; - self.current_suggestion_idx = 0; - } - - /// Get current matching suggestion - pub fn currentSuggestion(self: *const TextInput) ?[]const u8 { - if (self.suggestions.len == 0 or self.value.items.len == 0) return null; - const val = self.value.items; - var match_count: usize = 0; - for (self.suggestions) |s| { - if (s.len > val.len and std.mem.startsWith(u8, s, val)) { - if (match_count == self.current_suggestion_idx) { - return s; - } - match_count += 1; - } - } - return null; - } - - /// Handle a key event - pub fn handleKey(self: *TextInput, key: keys.KeyEvent) void { - if (!self.focused) return; - - // Alt+arrow for word movement - if (key.modifiers.alt) { - switch (key.key) { - .left => { - self.moveCursorWordLeft(); - return; - }, - .right => { - self.moveCursorWordRight(); - return; - }, - else => {}, - } - } - - if (key.modifiers.ctrl) { - switch (key.key) { - .char => |c| switch (c) { - 'a' => self.cursor = 0, // Home - 'e' => self.cursor = self.value.items.len, // End - 'k' => self.value.shrinkRetainingCapacity(self.cursor), // Kill to end - 'u' => { // Kill to start - std.mem.copyForwards(u8, self.value.items[0..], self.value.items[self.cursor..]); - self.value.shrinkRetainingCapacity(self.value.items.len - self.cursor); - self.cursor = 0; - }, - 'w' => self.deleteWordBackward(), // Delete word backward - else => {}, - }, - else => {}, - } - return; - } - - switch (key.key) { - .char => |c| self.insertChar(c), - .paste => |text| self.insertText(text), - .backspace => self.deleteBackward(), - .delete => self.deleteForward(), - .left => self.moveCursorLeft(), - .right => self.moveCursorRight(), - .home => self.cursor = 0, - .end => self.cursor = self.value.items.len, - .tab => { - // Accept current suggestion - if (self.currentSuggestion()) |suggestion| { - self.value.clearRetainingCapacity(); - self.value.appendSlice(suggestion) catch {}; - self.cursor = self.value.items.len; - } - }, - else => {}, - } - } - - fn insertChar(self: *TextInput, c: u21) void { - // Check char limit - if (self.char_limit) |limit| { - if (self.charCount() >= limit) return; - } - - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch return; - - // Insert at cursor position - self.value.insertSlice(self.cursor, buf[0..len]) catch return; - self.cursor += len; - } - - fn insertText(self: *TextInput, text: []const u8) void { - var i: usize = 0; - while (i < text.len) { - if (text[i] == '\r' or text[i] == '\n') { - i += 1; - continue; - } - - const len = std.unicode.utf8ByteSequenceLength(text[i]) catch { - self.insertChar(text[i]); - i += 1; - continue; - }; - if (i + len > text.len) { - self.insertChar(text[i]); - i += 1; - continue; - } - - const codepoint = std.unicode.utf8Decode(text[i .. i + len]) catch { - self.insertChar(text[i]); - i += 1; - continue; - }; - self.insertChar(codepoint); - i += len; - } - } - - fn deleteBackward(self: *TextInput) void { - if (self.cursor == 0) return; - - // Find start of previous character - var start = self.cursor - 1; - while (start > 0 and (self.value.items[start] & 0xC0) == 0x80) { - start -= 1; - } - - const len = self.cursor - start; - _ = self.value.orderedRemove(start); - for (1..len) |_| { - if (start < self.value.items.len) { - _ = self.value.orderedRemove(start); - } - } - self.cursor = start; - } - - fn deleteForward(self: *TextInput) void { - if (self.cursor >= self.value.items.len) return; - - // Find length of current character - const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; - - for (0..byte_len) |_| { - if (self.cursor < self.value.items.len) { - _ = self.value.orderedRemove(self.cursor); - } - } - } - - fn deleteWordBackward(self: *TextInput) void { - if (self.cursor == 0) return; - - // Skip trailing spaces - while (self.cursor > 0 and self.value.items[self.cursor - 1] == ' ') { - self.deleteBackward(); - } - - // Delete until space or start - while (self.cursor > 0 and self.value.items[self.cursor - 1] != ' ') { - self.deleteBackward(); - } - } - - fn moveCursorLeft(self: *TextInput) void { - if (self.cursor == 0) return; - - self.cursor -= 1; - while (self.cursor > 0 and (self.value.items[self.cursor] & 0xC0) == 0x80) { - self.cursor -= 1; - } - } - - fn moveCursorRight(self: *TextInput) void { - if (self.cursor >= self.value.items.len) return; - - const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; - self.cursor = @min(self.cursor + byte_len, self.value.items.len); - } - - fn moveCursorWordLeft(self: *TextInput) void { - if (self.cursor == 0) return; - // Skip whitespace - while (self.cursor > 0 and self.value.items[self.cursor - 1] == ' ') { - self.cursor -= 1; - } - // Skip word chars - while (self.cursor > 0 and self.value.items[self.cursor - 1] != ' ') { - self.cursor -= 1; - } - } - - fn moveCursorWordRight(self: *TextInput) void { - if (self.cursor >= self.value.items.len) return; - // Skip word chars - while (self.cursor < self.value.items.len and self.value.items[self.cursor] != ' ') { - self.cursor += 1; - } - // Skip whitespace - while (self.cursor < self.value.items.len and self.value.items[self.cursor] == ' ') { - self.cursor += 1; - } - } - - fn charCount(self: *const TextInput) usize { - var count: usize = 0; - var i: usize = 0; - while (i < self.value.items.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[i]) catch 1; - i += byte_len; - count += 1; - } - return count; - } - - /// Render the input to a string - pub fn view(self: *const TextInput, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Write prompt - if (self.prompt.len > 0) { - const rendered_prompt = try self.prompt_style.render(allocator, self.prompt); - try writer.writeAll(rendered_prompt); - } - - // Get display text - if (self.value.items.len == 0) { - // Show placeholder - if (self.placeholder.len > 0) { - const rendered = try self.placeholder_style.render(allocator, self.placeholder); - try writer.writeAll(rendered); - } - } else { - // Show value (possibly masked) - switch (self.echo_mode) { - .normal => { - // Render with cursor - if (self.focused) { - try self.renderWithCursor(writer, allocator); - } else { - const rendered = try self.text_style.render(allocator, self.value.items); - try writer.writeAll(rendered); - } - }, - .password => { - // Show asterisks - const char_count = self.charCount(); - const masked = try allocator.alloc(u8, char_count); - @memset(masked, '*'); - const rendered = try self.text_style.render(allocator, masked); - try writer.writeAll(rendered); - }, - .none => { - // Show nothing - }, - } - } - - return result.toOwnedSlice(); - } - - fn renderWithCursor(self: *const TextInput, writer: *Writer, allocator: std.mem.Allocator) !void { - // Text before cursor - if (self.cursor > 0) { - const before = try self.text_style.render(allocator, self.value.items[0..self.cursor]); - try writer.writeAll(before); - } - - // Cursor character - if (self.cursor < self.value.items.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(self.value.items[self.cursor]) catch 1; - const cursor_char = self.value.items[self.cursor..][0..byte_len]; - const cursor_rendered = try self.cursor_style.render(allocator, cursor_char); - try writer.writeAll(cursor_rendered); - - // Text after cursor - if (self.cursor + byte_len < self.value.items.len) { - const after = try self.text_style.render(allocator, self.value.items[self.cursor + byte_len ..]); - try writer.writeAll(after); - } - } else { - // Cursor at end - show cursor on space - const cursor_rendered = try self.cursor_style.render(allocator, " "); - try writer.writeAll(cursor_rendered); - } - - // Show ghost text for current suggestion - if (self.show_suggestions) { - if (self.currentSuggestion()) |suggestion| { - if (suggestion.len > self.value.items.len) { - const ghost = suggestion[self.value.items.len..]; - const ghost_rendered = try self.suggestion_style.render(allocator, ghost); - try writer.writeAll(ghost_rendered); - } - } - } - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig deleted file mode 100644 index ca708f5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/timer.zig +++ /dev/null @@ -1,223 +0,0 @@ -//! Timer component for countdowns and elapsed time. -//! Displays time in various formats. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -pub const Timer = struct { - // State - duration_ns: i128, - elapsed_ns: i128, - running: bool, - direction: Direction, - - // Display - format: Format, - show_milliseconds: bool, - - // Styling - timer_style: style_mod.Style, - warning_style: style_mod.Style, - danger_style: style_mod.Style, - - // Thresholds for countdown warnings (in seconds) - warning_threshold: ?u64, - danger_threshold: ?u64, - - pub const Direction = enum { - up, // Counts up (stopwatch) - down, // Counts down (timer) - }; - - pub const Format = enum { - compact, // 1:23 - long, // 01:23 - full, // 00:01:23 - verbose, // 1m 23s - }; - - pub fn init() Timer { - return .{ - .duration_ns = 0, - .elapsed_ns = 0, - .running = false, - .direction = .up, - .format = .long, - .show_milliseconds = false, - .timer_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.inline_style(true); - break :blk s; - }, - .warning_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .danger_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - .warning_threshold = 30, - .danger_threshold = 10, - }; - } - - /// Create a countdown timer - pub fn countdown(seconds: u64) Timer { - var t = init(); - t.direction = .down; - t.duration_ns = @as(i128, seconds) * std.time.ns_per_s; - return t; - } - - /// Create a stopwatch - pub fn stopwatch() Timer { - var t = init(); - t.direction = .up; - return t; - } - - /// Start the timer - pub fn start(self: *Timer) void { - self.running = true; - } - - /// Stop the timer - pub fn stop(self: *Timer) void { - self.running = false; - } - - /// Toggle running state - pub fn toggle(self: *Timer) void { - self.running = !self.running; - } - - /// Reset the timer - pub fn reset(self: *Timer) void { - self.elapsed_ns = 0; - } - - /// Set duration for countdown (in seconds) - pub fn setDuration(self: *Timer, seconds: u64) void { - self.duration_ns = @as(i128, seconds) * std.time.ns_per_s; - } - - /// Update timer with delta time (in nanoseconds) - pub fn update(self: *Timer, delta_ns: u64) void { - if (!self.running) return; - self.elapsed_ns += delta_ns; - } - - /// Get remaining time for countdown (in nanoseconds) - pub fn remaining(self: *const Timer) i128 { - if (self.direction == .down) { - return @max(0, self.duration_ns - self.elapsed_ns); - } - return self.elapsed_ns; - } - - /// Get elapsed time in seconds - pub fn elapsedSeconds(self: *const Timer) u64 { - return @intCast(@divFloor(self.elapsed_ns, std.time.ns_per_s)); - } - - /// Get remaining time in seconds (for countdown) - pub fn remainingSeconds(self: *const Timer) u64 { - return @intCast(@divFloor(self.remaining(), std.time.ns_per_s)); - } - - /// Check if countdown is finished - pub fn isFinished(self: *const Timer) bool { - if (self.direction == .down) { - return self.elapsed_ns >= self.duration_ns; - } - return false; - } - - /// Check if in warning state - pub fn isWarning(self: *const Timer) bool { - if (self.direction == .down and self.warning_threshold != null) { - const remaining_s = self.remainingSeconds(); - return remaining_s <= self.warning_threshold.? and remaining_s > (self.danger_threshold orelse 0); - } - return false; - } - - /// Check if in danger state - pub fn isDanger(self: *const Timer) bool { - if (self.direction == .down and self.danger_threshold != null) { - return self.remainingSeconds() <= self.danger_threshold.?; - } - return false; - } - - /// Render the timer - pub fn view(self: *const Timer, allocator: std.mem.Allocator) ![]const u8 { - const display_ns = if (self.direction == .down) self.remaining() else self.elapsed_ns; - - const total_seconds: u64 = @intCast(@divFloor(display_ns, std.time.ns_per_s)); - const milliseconds: u64 = @intCast(@mod(@divFloor(display_ns, std.time.ns_per_ms), 1000)); - - const hours = total_seconds / 3600; - const minutes = (total_seconds % 3600) / 60; - const seconds = total_seconds % 60; - - const time_str = switch (self.format) { - .compact => blk: { - if (hours > 0) { - break :blk try std.fmt.allocPrint(allocator, "{d}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }); - } else { - break :blk try std.fmt.allocPrint(allocator, "{d}:{d:0>2}", .{ minutes, seconds }); - } - }, - .long => blk: { - if (hours > 0) { - break :blk try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }); - } else { - break :blk try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}", .{ minutes, seconds }); - } - }, - .full => try std.fmt.allocPrint(allocator, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds }), - .verbose => blk: { - if (hours > 0) { - break :blk try std.fmt.allocPrint(allocator, "{d}h {d}m {d}s", .{ hours, minutes, seconds }); - } else if (minutes > 0) { - break :blk try std.fmt.allocPrint(allocator, "{d}m {d}s", .{ minutes, seconds }); - } else { - break :blk try std.fmt.allocPrint(allocator, "{d}s", .{seconds}); - } - }, - }; - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Choose style based on state - const active_style = if (self.isDanger()) - self.danger_style - else if (self.isWarning()) - self.warning_style - else - self.timer_style; - - const styled = try active_style.render(allocator, time_str); - try writer.writeAll(styled); - - // Add milliseconds if enabled - if (self.show_milliseconds) { - const ms_str = try std.fmt.allocPrint(allocator, ".{d:0>3}", .{milliseconds}); - try writer.writeAll(ms_str); - } - - return result.toOwnedSlice(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig deleted file mode 100644 index 0ff9612..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/toast.zig +++ /dev/null @@ -1,444 +0,0 @@ -//! Enhanced Toast/Snackbar notification system. -//! Supports positioning, stacking, icons, borders, and auto-dismiss with countdown. - -const std = @import("std"); -const Writer = std.Io.Writer; -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 = .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(.cyan); - s = s.inline_style(true); - break :blk s; - }, - .success_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - .warning_style = blk: { - var s = style_mod.Style{}; - s = s.fg(.yellow); - s = s.inline_style(true); - break :blk s; - }, - .err_style = blk: { - var s = style_mod.Style{}; - s = s.bold(true); - s = s.fg(.red); - s = s.inline_style(true); - break :blk s; - }, - .info_border_fg = .cyan, - .success_border_fg = .green, - .warning_border_fg = .yellow, - .err_border_fg = .red, - }; - } - - pub fn deinit(self: *Toast) void { - self.dismissAll(); - self.messages.deinit(); - } - - /// Push a notification. - pub fn push(self: *Toast, text: []const u8, level: Level, duration_ms: u64, current_ns: u64) !void { - const owned_text = try self.allocator.dupe(u8, text); - errdefer self.allocator.free(owned_text); - - try self.messages.append(.{ - .text = owned_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 { - const owned_text = try self.allocator.dupe(u8, text); - errdefer self.allocator.free(owned_text); - - try self.messages.append(.{ - .text = owned_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) { - const msg = self.messages.pop().?; - self.freeMessage(msg); - } - } - - /// Dismiss the oldest notification. - pub fn dismissOldest(self: *Toast) void { - if (self.messages.items.len > 0) { - self.removeAt(0); - } - } - - /// Dismiss all notifications. - pub fn dismissAll(self: *Toast) void { - for (self.messages.items) |msg| { - self.freeMessage(msg); - } - 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.removeAt(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: Writer.Allocating = .init(allocator); - errdefer result.deinit(); - const writer = &result.writer; - - const visible_count = @min(self.messages.items.len, self.max_visible); - - const total = self.messages.items.len; - for (0..visible_count) |render_idx| { - if (render_idx > 0) try writer.writeByte('\n'); - - const idx = switch (self.stack_order) { - .newest_first => total - 1 - render_idx, - .oldest_first => blk: { - const start = if (total > self.max_visible) total - self.max_visible else 0; - break :blk start + render_idx; - }, - }; - const msg = self.messages.items[idx]; - const toast_str = try self.renderSingleToast(allocator, msg, current_ns); - defer allocator.free(toast_str); - 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}); - defer allocator.free(overflow_text); - var dim_style = style_mod.Style{}; - dim_style = dim_style.fg(.gray(10)); - dim_style = dim_style.inline_style(true); - const styled = try dim_style.render(allocator, overflow_text); - defer allocator.free(styled); - 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; - defer allocator.free(toast_content); - - const place_mod = @import("../layout/place.zig"); - const line_alignment: style_mod.Align = switch (self.position) { - .top_left, .bottom_left => .left, - .top_center, .bottom_center => .center, - .top_right, .bottom_right => .right, - }; - const aligned_content = try alignLines(allocator, toast_content, line_alignment); - defer allocator.free(aligned_content); - - 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, - }; - - return place_mod.placeFloat(allocator, term_width, term_height, hpos, vpos, aligned_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: Writer.Allocating = .init(allocator); - errdefer line.deinit(); - const lw = &line.writer; - - const icon = if (self.show_icons) switch (msg.level) { - .info => self.info_icon, - .success => self.success_icon, - .warning => self.warning_icon, - .err => self.err_icon, - } else ""; - const icon_width = measure.width(icon); - - var countdown_text: []const u8 = ""; - var countdown_width: usize = 0; - 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; - countdown_text = try std.fmt.allocPrint(allocator, " ({d}s)", .{remaining_sec}); - countdown_width = measure.width(countdown_text); - } - defer if (countdown_text.len > 0) allocator.free(countdown_text); - - const max_inner_width = @max(self.minInnerWidth(), self.maxInnerWidth()); - const prefix_suffix_width = icon_width + countdown_width; - const available_text_width = max_inner_width -| prefix_suffix_width; - const display_text = if (measure.width(msg.text) > available_text_width) - try measure.truncate(allocator, msg.text, available_text_width) - else - try allocator.dupe(u8, msg.text); - defer allocator.free(display_text); - - // Icon - if (self.show_icons) { - const styled_icon = try active_style.render(allocator, icon); - defer allocator.free(styled_icon); - try lw.writeAll(styled_icon); - } - - // Text - const styled_text = try active_style.render(allocator, display_text); - defer allocator.free(styled_text); - try lw.writeAll(styled_text); - - // Countdown - if (countdown_text.len > 0) { - var dim_style = style_mod.Style{}; - dim_style = dim_style.fg(.gray(10)); - dim_style = dim_style.inline_style(true); - const styled_cd = try dim_style.render(allocator, countdown_text); - defer allocator.free(styled_cd); - try lw.writeAll(styled_cd); - } - - const line_content = try line.toOwnedSlice(); - - if (!self.show_border) { - return line_content; - } - - const target_inner_width = @max(self.minInnerWidth(), measure.width(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.width(@intCast(target_inner_width)); - box_style = box_style.inline_style(false); - - defer allocator.free(line_content); - 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, - }; - } - - fn freeMessage(self: *Toast, msg: ToastMessage) void { - self.allocator.free(msg.text); - } - - fn removeAt(self: *Toast, idx: usize) void { - const msg = self.messages.orderedRemove(idx); - self.freeMessage(msg); - } - - fn toastChromeWidth(self: *const Toast) usize { - if (!self.show_border) return 0; - return 4; // 2 border columns + 2 horizontal padding columns - } - - fn minInnerWidth(self: *const Toast) usize { - const min_total = @as(usize, self.min_width); - return if (min_total > self.toastChromeWidth()) - min_total - self.toastChromeWidth() - else - 0; - } - - fn maxInnerWidth(self: *const Toast) usize { - const min_inner = self.minInnerWidth(); - const max_total = @as(usize, self.max_width); - const max_inner = if (max_total > self.toastChromeWidth()) - max_total - self.toastChromeWidth() - else - 0; - return @max(min_inner, max_inner); - } -}; - -fn alignLines(allocator: std.mem.Allocator, content: []const u8, alignment: style_mod.Align) ![]const u8 { - const target_width = measure.maxLineWidth(content); - var result: Writer.Allocating = .init(allocator); - errdefer result.deinit(); - const writer = &result.writer; - - var lines = std.mem.splitScalar(u8, content, '\n'); - var first = true; - while (lines.next()) |line| { - if (!first) try writer.writeByte('\n'); - first = false; - - const line_width = measure.width(line); - const padding = target_width -| line_width; - const left_padding: usize = switch (alignment) { - .left => 0, - .center => padding / 2, - .right => padding, - }; - const right_padding: usize = switch (alignment) { - .left => padding, - .center => padding - left_padding, - .right => 0, - }; - - for (0..left_padding) |_| { - try writer.writeByte(' '); - } - try writer.writeAll(line); - for (0..right_padding) |_| { - try writer.writeByte(' '); - } - } - - return result.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig deleted file mode 100644 index b5d52fb..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tooltip.zig +++ /dev/null @@ -1,925 +0,0 @@ -//! Tooltip component for displaying contextual hints near a target position. -//! -//! ## Quick Start -//! -//! ```zig -//! // Create a tooltip -//! var tip = Tooltip.init("Save the current document"); -//! -//! // Position it relative to a target -//! tip.target_x = 10; -//! tip.target_y = 5; -//! tip.placement = .bottom; -//! tip.show(); -//! -//! // In your view function: -//! const output = try tip.render(allocator, term_width, term_height); -//! ``` -//! -//! ## Placements -//! -//! - `.top` — above the target, arrow pointing down -//! - `.bottom` — below the target, arrow pointing up -//! - `.left` — to the left of the target, arrow pointing right -//! - `.right` — to the right of the target, arrow pointing left -//! -//! ## Presets -//! -//! - `Tooltip.init(text)` — simple tooltip with default style -//! - `Tooltip.titled(title, text)` — tooltip with a bold title line -//! - `Tooltip.help(text)` — dim, italic help-style tooltip -//! - `Tooltip.shortcut(label, key)` — "Label Ctrl+S" style tooltip - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const border_mod = @import("../style/border.zig"); -const Color = @import("../style/color.zig").Color; -const AnsiColor = @import("../style/color.zig").AnsiColor; -const measure = @import("../layout/measure.zig"); -const unicode = @import("../unicode.zig"); - -pub const Tooltip = struct { - // ── State ────────────────────────────────────────────────────────── - - visible: bool = false, - - // ── Content ──────────────────────────────────────────────────────── - - text: []const u8 = "", - title: ?[]const u8 = null, - - // ── Position ────────────────────────────────────────────────────── - - /// X coordinate of the target element (display column). - target_x: usize = 0, - /// Y coordinate of the target element (display row). - target_y: usize = 0, - /// Width of the target element (used for centering arrows). - target_width: usize = 1, - /// Where to place the tooltip relative to the target. - placement: Placement = .bottom, - /// Gap between tooltip and target (in cells). - gap: usize = 0, - - // ── Sizing ───────────────────────────────────────────────────────── - - /// Maximum width of the tooltip content area (excluding border/padding). - max_width: usize = 40, - /// Padding inside the tooltip box. - padding: Padding = .{ .top = 0, .right = 1, .bottom = 0, .left = 1 }, - - // ── Styling ──────────────────────────────────────────────────────── - - border_chars: border_mod.BorderChars = .rounded, - border_fg: Color = .gray(14), - /// Background for the content area (padding + text) inside the border. - content_bg: Color = .none, - /// Background for border characters. Three-state via `?Color`: - /// - `null` (default) — falls back to `content_bg` (same bg everywhere). - /// - `.none` — explicitly no bg; with `inherit_bg` the base shows through. - /// - any color — use that color for borders only. - border_bg: ?Color = null, - text_style: style_mod.Style = makeStyle(.{ .fg_color = .gray(20) }), - title_style: style_mod.Style = makeStyle(.{ .bold_v = true, .fg_color = .white }), - - /// Show an arrow pointing from tooltip toward the target. - show_arrow: bool = true, - /// Color of the arrow character. - arrow_fg: Color = .gray(14), - /// Background for the arrow character. Three-state via `?Color`: - /// - `null` (default) — no bg; with `inherit_bg` the base shows through. - /// - `.none` — explicitly no bg, even when `inherit_bg` is on. - /// - any color — use that color. - arrow_bg: ?Color = null, - /// Custom arrow characters per direction (what's shown when the tooltip - /// is placed in that direction). Set to "" to hide a specific arrow. - arrow_up: []const u8 = "▲", - arrow_down: []const u8 = "▼", - arrow_left: []const u8 = "◀", - arrow_right: []const u8 = "▶", - - /// When true in overlay mode, tooltip elements (arrow, border) inherit - /// the background color from the underlying base content. - inherit_bg: bool = true, - - // ── Types ────────────────────────────────────────────────────────── - - pub const Placement = enum { top, bottom, left, right }; - - pub const Padding = struct { - top: u16 = 0, - right: u16 = 0, - bottom: u16 = 0, - left: u16 = 0, - - pub fn all(n: u16) Padding { - return .{ .top = n, .right = n, .bottom = n, .left = n }; - } - - pub fn symmetric(vert: u16, horiz: u16) Padding { - return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; - } - }; - - // ── Preset Constructors ──────────────────────────────────────────── - - /// Simple tooltip with text content. - pub fn init(text: []const u8) Tooltip { - return .{ .text = text }; - } - - /// Tooltip with a bold title line above the text. - pub fn titled(title_text: []const u8, body: []const u8) Tooltip { - return .{ - .text = body, - .title = title_text, - }; - } - - /// Help-style tooltip with dim italic text. - pub fn help(text: []const u8) Tooltip { - return .{ - .text = text, - .text_style = makeStyle(.{ .dim_v = true, .italic_v = true, .fg_color = .gray(16) }), - .border_fg = .gray(10), - .arrow_fg = .gray(10), - }; - } - - /// Shortcut tooltip showing "Label Key". - pub fn shortcut(label: []const u8, key: []const u8) Tooltip { - return .{ - .text = key, - .title = label, - .title_style = makeStyle(.{ .fg_color = .gray(18) }), - .text_style = makeStyle(.{ .bold_v = true, .fg_color = .cyan }), - }; - } - - // ── State Management ─────────────────────────────────────────────── - - pub fn show(self: *Tooltip) void { - self.visible = true; - } - - pub fn hide(self: *Tooltip) void { - self.visible = false; - } - - pub fn toggle(self: *Tooltip) void { - self.visible = !self.visible; - } - - pub fn isVisible(self: *const Tooltip) bool { - return self.visible; - } - - // ── Rendering ────────────────────────────────────────────────────── - - /// Render the tooltip box (no positioning). Returns the box string. - pub fn renderBox(self: *const Tooltip, allocator: std.mem.Allocator) ![]const u8 { - const bc = self.border_chars; - - // Compute content lines - var content_lines = std.array_list.Managed([]const u8).init(allocator); - defer content_lines.deinit(); - - if (self.title) |t| { - try content_lines.append(t); - } - - var text_iter = std.mem.splitScalar(u8, self.text, '\n'); - while (text_iter.next()) |line| { - try content_lines.append(line); - } - - // Compute inner width - var max_content_w: usize = 0; - for (content_lines.items) |line| { - max_content_w = @max(max_content_w, measure.width(line)); - } - max_content_w = @min(max_content_w, self.max_width); - - const pad_h: usize = @as(usize, self.padding.left) + @as(usize, self.padding.right); - const inner_w: usize = max_content_w + pad_h; - - // Inline styles - // border_bg: null → fall back to content_bg (backward compat) - // .none → explicitly no bg (transparent) - // color → use that color - const effective_border_bg = if (self.border_bg) |b| b else self.content_bg; - var bdr_s = style_mod.Style{}; - bdr_s = bdr_s.fg(self.border_fg).inline_style(true); - if (!effective_border_bg.isNone()) bdr_s = bdr_s.bg(effective_border_bg); - - var pad_s = style_mod.Style{}; - pad_s = pad_s.inline_style(true); - if (!self.content_bg.isNone()) pad_s = pad_s.bg(self.content_bg); - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // ── Top border ── - try writer.writeAll(try bdr_s.render(allocator, bc.top_left)); - try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); - try writer.writeAll(try bdr_s.render(allocator, bc.top_right)); - - const styled_left = try bdr_s.render(allocator, bc.vertical); - const styled_right = try bdr_s.render(allocator, bc.vertical); - - // ── Top padding ── - for (0..self.padding.top) |_| { - try writer.writeByte('\n'); - try writeEmptyLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - } - - // ── Content lines ── - for (content_lines.items, 0..) |line, idx| { - try writer.writeByte('\n'); - try writer.writeAll(styled_left); - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, self.padding.left))); - - // Pick style: title or body - const is_title_line = self.title != null and idx == 0; - var line_style = if (is_title_line) self.title_style else self.text_style; - line_style = line_style.inline_style(true); - if (!self.content_bg.isNone() and line_style.background.isNone()) { - line_style = line_style.bg(self.content_bg); - } - try writer.writeAll(try line_style.render(allocator, line)); - - const line_w = measure.width(line); - const fill: usize = if (max_content_w > line_w) max_content_w - line_w else 0; - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, fill + self.padding.right))); - try writer.writeAll(styled_right); - } - - // ── Bottom padding ── - for (0..self.padding.bottom) |_| { - try writer.writeByte('\n'); - try writeEmptyLine(allocator, writer, styled_left, styled_right, pad_s, inner_w); - } - - // ── Bottom border ── - try writer.writeByte('\n'); - try writer.writeAll(try bdr_s.render(allocator, bc.bottom_left)); - try writer.writeAll(try repeatStr(allocator, bdr_s, bc.horizontal, inner_w)); - try writer.writeAll(try bdr_s.render(allocator, bc.bottom_right)); - - return result.toOwnedSlice(); - } - - /// Render the tooltip positioned on a full-screen canvas. - /// Returns empty string if not visible. - pub fn render(self: *const Tooltip, allocator: std.mem.Allocator, term_width: usize, term_height: usize) ![]const u8 { - if (!self.visible) return try allocator.dupe(u8, ""); - - const box = try self.renderBox(allocator); - const box_w = measure.maxLineWidth(box); - const box_h = measure.height(box); - - // Compute arrow position and tooltip position - const pos = self.computePosition(box_w, box_h, term_width, term_height); - - // Build full-screen output line by line - var result: Writer.Allocating = .init(allocator); - const wr = &result.writer; - - // Collect box lines - var box_lines = std.array_list.Managed([]const u8).init(allocator); - defer box_lines.deinit(); - var box_iter = std.mem.splitScalar(u8, box, '\n'); - while (box_iter.next()) |line| try box_lines.append(line); - - const is_horizontal = self.placement == .left or self.placement == .right; - - for (0..term_height) |row| { - if (row > 0) try wr.writeByte('\n'); - - const in_box = row >= pos.box_y and row < pos.box_y + box_h; - const is_arrow_row = self.show_arrow and row == pos.arrow_y; - - if (in_box) { - const box_line_idx = row - pos.box_y; - const box_line = if (box_line_idx < box_lines.items.len) box_lines.items[box_line_idx] else ""; - // For left/right placement, include arrow on the same row as the box - if (is_arrow_row and is_horizontal) { - try self.writeBoxRowWithSideArrow(allocator, wr, pos, box_line, term_width); - } else { - try wr.writeAll(try nSpaces(allocator, pos.box_x)); - try wr.writeAll(box_line); - const right = pos.box_x + measure.width(box_line); - if (right < term_width) try wr.writeAll(try nSpaces(allocator, term_width - right)); - } - } else if (is_arrow_row) { - // Top/bottom arrow on its own row - try self.writeArrowOnlyRow(allocator, wr, pos, term_width); - } else { - try wr.writeAll(try nSpaces(allocator, term_width)); - } - } - - return result.toOwnedSlice(); - } - - /// Render the tooltip composited onto the given base content. - /// - /// Uses **cell-based compositing** (like Ratatui, Textual, Cursive): - /// both base and tooltip are parsed into a cell grid, tooltip cells are - /// painted on top, then the grid is serialized back to an ANSI string. - /// This completely avoids ANSI-splice style bleeding. - pub fn overlay(self: *const Tooltip, allocator: std.mem.Allocator, base: []const u8, term_width: usize, term_height: usize) ![]const u8 { - if (!self.visible) return try allocator.dupe(u8, base); - - const box = try self.renderBox(allocator); - const box_w = measure.maxLineWidth(box); - const box_h = measure.height(box); - const pos = self.computePosition(box_w, box_h, term_width, term_height); - - // 1. Parse base content into cell grid - var grid = try CellGrid.parse(allocator, base, term_width, term_height); - - // 2. Parse tooltip box into cell grid - var box_grid = try CellGrid.parse(allocator, box, box_w, box_h); - - // 3. Paint tooltip box cells onto base grid - for (0..box_h) |r| { - const dst_r = pos.box_y + r; - if (dst_r >= term_height) break; - var c: usize = 0; - while (c < box_w) { - const dst_c = pos.box_x + c; - if (dst_c >= term_width) break; - - const src_cell = box_grid.get(r, c); - if (self.inherit_bg and src_cell.style.bg.eql(.none)) { - // Tooltip cell has no bg → inherit from base - var merged = src_cell; - merged.style.bg = grid.get(dst_r, dst_c).style.bg; - grid.set(dst_r, dst_c, merged); - } else { - grid.set(dst_r, dst_c, src_cell); - } - - // Skip continuation cells of wide characters - const w = if (src_cell.width > 1) src_cell.width else 1; - c += w; - } - } - - // 4. Paint arrow cell - if (self.show_arrow) { - const arrow_ch = self.arrowChar(); - if (arrow_ch.len > 0 and pos.arrow_y < term_height and pos.arrow_x < term_width) { - const aw = self.arrowDisplayWidth(); - var arrow_style = CellStyle{}; - arrow_style.fg = colorToCellColor(self.arrow_fg); - if (self.arrow_bg) |abg| { - // Explicitly set → use it (even .none = explicitly no bg) - if (!abg.isNone()) arrow_style.bg = colorToCellColor(abg); - } else if (self.inherit_bg) { - // Not specified → inherit from base when enabled - arrow_style.bg = grid.get(pos.arrow_y, pos.arrow_x).style.bg; - } - grid.set(pos.arrow_y, pos.arrow_x, .{ - .char = arrow_ch, - .style = arrow_style, - .width = @intCast(aw), - }); - // Clear continuation cells for wide arrow - for (1..aw) |dx| { - if (pos.arrow_x + dx < term_width) { - grid.set(pos.arrow_y, pos.arrow_x + dx, .{ - .char = "", - .style = arrow_style, - .width = 0, - }); - } - } - } - } - - // 5. Serialize cell grid back to ANSI string - return grid.render(allocator); - } - - // ── Position Computation ────────────────────────────────────────── - - const Position = struct { - box_x: usize, - box_y: usize, - arrow_x: usize, - arrow_y: usize, - }; - - fn computePosition(self: *const Tooltip, box_w: usize, box_h: usize, tw: usize, th: usize) Position { - var pos: Position = .{ .box_x = 0, .box_y = 0, .arrow_x = 0, .arrow_y = 0 }; - - const arrow_offset: usize = if (self.show_arrow) 1 else 0; - - switch (self.placement) { - .bottom => { - // Box below target - pos.arrow_y = self.target_y + 1 + self.gap; - pos.box_y = pos.arrow_y + arrow_offset; - // Center horizontally on target - const target_center = self.target_x + self.target_width / 2; - pos.box_x = if (target_center >= box_w / 2) target_center - box_w / 2 else 0; - pos.arrow_x = target_center; - }, - .top => { - // Box above target - const total_h = box_h + arrow_offset; - pos.box_y = if (self.target_y >= total_h + self.gap) self.target_y - total_h - self.gap else 0; - pos.arrow_y = pos.box_y + box_h; - const target_center = self.target_x + self.target_width / 2; - pos.box_x = if (target_center >= box_w / 2) target_center - box_w / 2 else 0; - pos.arrow_x = target_center; - }, - .right => { - // Box to the right of target - pos.box_x = self.target_x + self.target_width + self.gap + arrow_offset; - pos.arrow_x = self.target_x + self.target_width + self.gap; - // Center vertically on target - pos.box_y = if (self.target_y >= box_h / 2) self.target_y - box_h / 2 else 0; - pos.arrow_y = self.target_y; - }, - .left => { - // Box to the left of target - const total_w = box_w + arrow_offset; - pos.box_x = if (self.target_x >= total_w + self.gap) self.target_x - total_w - self.gap else 0; - pos.arrow_x = pos.box_x + box_w; - pos.box_y = if (self.target_y >= box_h / 2) self.target_y - box_h / 2 else 0; - pos.arrow_y = self.target_y; - }, - } - - // Clamp to terminal bounds - if (pos.box_x + box_w > tw) pos.box_x = if (tw >= box_w) tw - box_w else 0; - if (pos.box_y + box_h > th) pos.box_y = if (th >= box_h) th - box_h else 0; - if (pos.arrow_x >= tw) pos.arrow_x = tw -| 1; - if (pos.arrow_y >= th) pos.arrow_y = th -| 1; - - return pos; - } - - fn arrowChar(self: *const Tooltip) []const u8 { - return switch (self.placement) { - .bottom => self.arrow_up, - .top => self.arrow_down, - .left => self.arrow_right, - .right => self.arrow_left, - }; - } - - fn renderStyledArrow(self: *const Tooltip, allocator: std.mem.Allocator) ![]const u8 { - const ch = self.arrowChar(); - if (ch.len == 0) return try allocator.dupe(u8, ""); - var arrow_s = style_mod.Style{}; - arrow_s = arrow_s.fg(self.arrow_fg).inline_style(true); - return try arrow_s.render(allocator, ch); - } - - fn arrowDisplayWidth(self: *const Tooltip) usize { - const ch = self.arrowChar(); - if (ch.len == 0) return 0; - return measure.width(ch); - } - - // ── Render helpers (full-screen canvas) ──────────────────────────── - - /// Arrow on its own row (top/bottom placement). - fn writeArrowOnlyRow(self: *const Tooltip, allocator: std.mem.Allocator, writer: *Writer, pos: Position, tw: usize) !void { - try writer.writeAll(try nSpaces(allocator, pos.arrow_x)); - try writer.writeAll(try self.renderStyledArrow(allocator)); - const aw = self.arrowDisplayWidth(); - const used = pos.arrow_x + aw; - if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); - } - - /// Box row that also has a side arrow (left/right placement). - fn writeBoxRowWithSideArrow(self: *const Tooltip, allocator: std.mem.Allocator, writer: *Writer, pos: Position, box_line: []const u8, tw: usize) !void { - const box_line_w = measure.width(box_line); - const aw = self.arrowDisplayWidth(); - const styled_arrow = try self.renderStyledArrow(allocator); - - if (self.placement == .right) { - // Layout: [spaces] [arrow] [box_line] [spaces] - try writer.writeAll(try nSpaces(allocator, pos.arrow_x)); - try writer.writeAll(styled_arrow); - const gap_between = if (pos.box_x > pos.arrow_x + aw) pos.box_x - pos.arrow_x - aw else 0; - try writer.writeAll(try nSpaces(allocator, gap_between)); - try writer.writeAll(box_line); - const used = pos.arrow_x + aw + gap_between + box_line_w; - if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); - } else { - // .left — Layout: [spaces] [box_line] [arrow] [spaces] - try writer.writeAll(try nSpaces(allocator, pos.box_x)); - try writer.writeAll(box_line); - const gap_between = if (pos.arrow_x > pos.box_x + box_line_w) pos.arrow_x - pos.box_x - box_line_w else 0; - try writer.writeAll(try nSpaces(allocator, gap_between)); - try writer.writeAll(styled_arrow); - const used = pos.box_x + box_line_w + gap_between + aw; - if (used < tw) try writer.writeAll(try nSpaces(allocator, tw - used)); - } - } - - // ── Private Helpers ─────────────────────────────────────────────── - - fn writeEmptyLine(allocator: std.mem.Allocator, writer: *Writer, styled_left: []const u8, styled_right: []const u8, pad_s: style_mod.Style, inner_w: usize) !void { - try writer.writeAll(styled_left); - try writer.writeAll(try pad_s.render(allocator, try nSpaces(allocator, inner_w))); - try writer.writeAll(styled_right); - } - - fn repeatStr(allocator: std.mem.Allocator, s: style_mod.Style, str: []const u8, count: usize) ![]const u8 { - if (count == 0 or str.len == 0) return try allocator.dupe(u8, ""); - const buf = try allocator.alloc(u8, str.len * count); - for (0..count) |i| { - @memcpy(buf[i * str.len ..][0..str.len], str); - } - return try s.render(allocator, buf); - } - - fn nSpaces(allocator: std.mem.Allocator, count: anytype) ![]const u8 { - const n: usize = switch (@typeInfo(@TypeOf(count))) { - .int, .comptime_int => @intCast(count), - else => count, - }; - if (n == 0) return try allocator.dupe(u8, ""); - const buf = try allocator.alloc(u8, n); - @memset(buf, ' '); - return buf; - } - - // Comptime style builder - const StyleOpts = struct { - bold_v: ?bool = null, - dim_v: ?bool = null, - italic_v: ?bool = null, - fg_color: Color = .none, - bg_color: Color = .none, - }; - - fn makeStyle(opts: StyleOpts) style_mod.Style { - var s = style_mod.Style{}; - if (opts.bold_v) |v| s.bold_attr = v; - if (opts.dim_v) |v| s.dim_attr = v; - if (opts.italic_v) |v| s.italic_attr = v; - if (!opts.fg_color.isNone()) s.foreground = opts.fg_color; - if (!opts.bg_color.isNone()) s.background = opts.bg_color; - s.inline_mode = true; - return s; - } - - /// Convert a framework Color to a CellColor for cell-based compositing. - fn colorToCellColor(c: Color) CellColor { - return switch (c) { - .none => .none, - .ansi => |a| .{ .ansi = a }, - .ansi256 => |n| .{ .ansi256 = n }, - .rgb => |v| .{ .rgb = .{ v.r, v.g, v.b } }, - }; - } -}; - -// ═══════════════════════════════════════════════════════════════════════ -// Cell-based compositing types (à la Ratatui Buffer / Textual Segment) -// ═══════════════════════════════════════════════════════════════════════ - -/// Color as parsed from raw ANSI SGR — independent of the framework Color type. -const CellColor = union(enum) { - none, - ansi: AnsiColor, - ansi256: u8, - rgb: [3]u8, - - fn eql(a: CellColor, b: CellColor) bool { - const tag_a = @intFromEnum(std.meta.activeTag(a)); - const tag_b = @intFromEnum(std.meta.activeTag(b)); - if (tag_a != tag_b) return false; - return switch (a) { - .none => true, - .ansi => |va| va == b.ansi, - .ansi256 => |va| va == b.ansi256, - .rgb => |va| va[0] == b.rgb[0] and va[1] == b.rgb[1] and va[2] == b.rgb[2], - }; - } - - fn writeFg(self: CellColor, wr: anytype) !void { - switch (self) { - .none => try wr.writeAll("\x1b[39m"), - .ansi => |a| try wr.print("\x1b[{d}m", .{a.fgCode()}), - .ansi256 => |n| try wr.print("\x1b[38;5;{d}m", .{n}), - .rgb => |c| try wr.print("\x1b[38;2;{d};{d};{d}m", .{ c[0], c[1], c[2] }), - } - } - - fn writeBg(self: CellColor, wr: anytype) !void { - switch (self) { - .none => try wr.writeAll("\x1b[49m"), - .ansi => |a| try wr.print("\x1b[{d}m", .{a.bgCode()}), - .ansi256 => |n| try wr.print("\x1b[48;5;{d}m", .{n}), - .rgb => |c| try wr.print("\x1b[48;2;{d};{d};{d}m", .{ c[0], c[1], c[2] }), - } - } -}; - -/// Per-cell style parsed from ANSI SGR sequences. -const CellStyle = struct { - fg: CellColor = .none, - bg: CellColor = .none, - bold: bool = false, - dim: bool = false, - italic: bool = false, - underline: bool = false, - strikethrough: bool = false, - - fn eql(a: CellStyle, b: CellStyle) bool { - return a.fg.eql(b.fg) and a.bg.eql(b.bg) and - a.bold == b.bold and a.dim == b.dim and - a.italic == b.italic and a.underline == b.underline and - a.strikethrough == b.strikethrough; - } -}; - -/// A single terminal cell. -const Cell = struct { - char: []const u8 = " ", - style: CellStyle = .{}, - width: u8 = 1, // display width; 0 = continuation cell of wide char -}; - -/// 2D grid of cells — the intermediate buffer for compositing. -const CellGrid = struct { - cells: []Cell, - w: usize, - h: usize, - - fn get(self: *const CellGrid, row: usize, col: usize) Cell { - if (row >= self.h or col >= self.w) return Cell{}; - return self.cells[row * self.w + col]; - } - - fn set(self: *CellGrid, row: usize, col: usize, cell: Cell) void { - if (row >= self.h or col >= self.w) return; - self.cells[row * self.w + col] = cell; - } - - /// Parse an ANSI-encoded string into a cell grid. - fn parse(allocator: std.mem.Allocator, str: []const u8, width: usize, height: usize) !CellGrid { - const total = width * height; - const cells = try allocator.alloc(Cell, total); - for (cells) |*c| c.* = Cell{}; - - var cur_style = CellStyle{}; - var row: usize = 0; - var col: usize = 0; - var i: usize = 0; - - while (i < str.len) { - const c = str[i]; - - // Newline → next row - if (c == '\n') { - row += 1; - col = 0; - i += 1; - continue; - } - - // ESC sequence - if (c == 0x1b and i + 1 < str.len and str[i + 1] == '[') { - i += 2; // skip ESC [ - const params_start = i; - // Scan to final byte (letter) - while (i < str.len and !isCSIFinal(str[i])) : (i += 1) {} - if (i < str.len) { - const final = str[i]; - i += 1; - if (final == 'm') { - // SGR — update current style - const params = str[params_start .. i - 1]; - applySgr(&cur_style, params); - } - // Other CSI sequences are silently consumed - } - continue; - } - - // Bare ESC (non-CSI) - if (c == 0x1b) { - i += 1; - continue; - } - - // Control chars (except newline handled above) - if (c < 0x20) { - i += 1; - continue; - } - - // Visible character - if (row >= height) { - i += 1; - continue; - } - - const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; - const end = @min(i + byte_len, str.len); - const ch_slice = str[i..end]; - - var cw: usize = 1; - if (i + byte_len <= str.len) { - if (std.unicode.utf8Decode(str[i..][0..byte_len])) |cp| { - cw = unicode.charWidth(cp); - } else |_| {} - } - - if (col < width) { - cells[row * width + col] = .{ - .char = ch_slice, - .style = cur_style, - .width = @intCast(cw), - }; - // Mark continuation cells for wide characters - for (1..cw) |dx| { - if (col + dx < width) { - cells[row * width + col + dx] = .{ - .char = "", - .style = cur_style, - .width = 0, - }; - } - } - col += cw; - } - - i = end; - } - - return .{ .cells = cells, .w = width, .h = height }; - } - - /// Serialize the cell grid back to an ANSI string. - /// Emits SGR sequences only when the style changes between cells - /// (like Ratatui's Buffer::diff), producing minimal output. - fn render(self: *const CellGrid, allocator: std.mem.Allocator) ![]const u8 { - var buf: Writer.Allocating = .init(allocator); - const wr = &buf.writer; - - var prev_style = CellStyle{}; - - for (0..self.h) |row| { - if (row > 0) try wr.writeByte('\n'); - - // Track trailing spaces to avoid emitting them - for (0..self.w) |col| { - const cell = self.cells[row * self.w + col]; - - // Skip continuation cells - if (cell.width == 0) continue; - - // Emit style change if needed - if (!cell.style.eql(prev_style)) { - try emitStyleDiff(wr, prev_style, cell.style); - prev_style = cell.style; - } - - // Emit character - if (cell.char.len > 0) { - try wr.writeAll(cell.char); - } - } - } - - // Final reset - try wr.writeAll("\x1b[0m"); - - return buf.toOwnedSlice(); - } -}; - -/// Check if a byte is a CSI final byte (letter). -fn isCSIFinal(c: u8) bool { - return (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'); -} - -/// Apply an SGR parameter string to a CellStyle. -fn applySgr(style: *CellStyle, params: []const u8) void { - // Empty params = reset - if (params.len == 0) { - style.* = CellStyle{}; - return; - } - - var iter = std.mem.splitScalar(u8, params, ';'); - while (iter.next()) |param| { - const n = std.fmt.parseInt(u32, param, 10) catch continue; - switch (n) { - 0 => style.* = CellStyle{}, - 1 => style.bold = true, - 2 => style.dim = true, - 3 => style.italic = true, - 4 => style.underline = true, - 9 => style.strikethrough = true, - 22 => { - style.bold = false; - style.dim = false; - }, - 23 => style.italic = false, - 24 => style.underline = false, - 29 => style.strikethrough = false, - // Foreground basic colors - 30...37 => { - style.fg = .{ .ansi = @enumFromInt(n - 30) }; - }, - 39 => style.fg = .none, - // Background basic colors - 40...47 => { - style.bg = .{ .ansi = @enumFromInt(n - 40) }; - }, - 49 => style.bg = .none, - // Extended foreground - 38 => { - const sub_str = iter.next() orelse return; - const sub = std.fmt.parseInt(u32, sub_str, 10) catch return; - if (sub == 5) { - const ci_str = iter.next() orelse return; - const ci = std.fmt.parseInt(u8, ci_str, 10) catch return; - style.fg = .{ .ansi256 = ci }; - } else if (sub == 2) { - const r = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - const g = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - const b = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - style.fg = .{ .rgb = .{ r, g, b } }; - } - }, - // Extended background - 48 => { - const sub_str = iter.next() orelse return; - const sub = std.fmt.parseInt(u32, sub_str, 10) catch return; - if (sub == 5) { - const ci_str = iter.next() orelse return; - const ci = std.fmt.parseInt(u8, ci_str, 10) catch return; - style.bg = .{ .ansi256 = ci }; - } else if (sub == 2) { - const r = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - const g = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - const b = std.fmt.parseInt(u8, iter.next() orelse return, 10) catch return; - style.bg = .{ .rgb = .{ r, g, b } }; - } - }, - // Bright foreground - 90...97 => { - style.fg = .{ .ansi = @enumFromInt(n - 90 + 8) }; - }, - // Bright background - 100...107 => { - style.bg = .{ .ansi = @enumFromInt(n - 100 + 8) }; - }, - else => {}, - } - } -} - -/// Emit the minimal SGR diff to transition from one style to another. -fn emitStyleDiff(wr: anytype, prev: CellStyle, next: CellStyle) !void { - // If the new style is default, just reset - const default_style = CellStyle{}; - if (next.eql(default_style)) { - try wr.writeAll("\x1b[0m"); - return; - } - - // If any attribute was turned off (true→false), we need a reset first - // since SGR doesn't have individual "off" codes for all attributes reliably. - const needs_reset = (prev.bold and !next.bold) or - (prev.dim and !next.dim) or - (prev.italic and !next.italic) or - (prev.underline and !next.underline) or - (prev.strikethrough and !next.strikethrough); - - if (needs_reset) { - try wr.writeAll("\x1b[0m"); - // After reset, emit all attributes of the new style - if (next.bold) try wr.writeAll("\x1b[1m"); - if (next.dim) try wr.writeAll("\x1b[2m"); - if (next.italic) try wr.writeAll("\x1b[3m"); - if (next.underline) try wr.writeAll("\x1b[4m"); - if (next.strikethrough) try wr.writeAll("\x1b[9m"); - if (!next.fg.eql(.none)) try next.fg.writeFg(wr); - if (!next.bg.eql(.none)) try next.bg.writeBg(wr); - return; - } - - // Otherwise, emit only what changed - if (!prev.fg.eql(next.fg)) try next.fg.writeFg(wr); - if (!prev.bg.eql(next.bg)) try next.bg.writeBg(wr); - if (!prev.bold and next.bold) try wr.writeAll("\x1b[1m"); - if (!prev.dim and next.dim) try wr.writeAll("\x1b[2m"); - if (!prev.italic and next.italic) try wr.writeAll("\x1b[3m"); - if (!prev.underline and next.underline) try wr.writeAll("\x1b[4m"); - if (!prev.strikethrough and next.strikethrough) try wr.writeAll("\x1b[9m"); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig deleted file mode 100644 index 1b46f3c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/tree.zig +++ /dev/null @@ -1,185 +0,0 @@ -//! Tree component for displaying hierarchical data. -//! Renders a tree structure with expandable nodes and customizable enumerators. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; - -/// Enumerator defines the prefix characters for tree rendering -pub const Enumerator = struct { - item_prefix: []const u8, - last_prefix: []const u8, - indent_prefix: []const u8, - empty_prefix: []const u8, -}; - -/// Default tree enumerator with box-drawing characters -pub const DefaultEnumerator = Enumerator{ - .item_prefix = "├── ", - .last_prefix = "└── ", - .indent_prefix = "│ ", - .empty_prefix = " ", -}; - -/// Rounded tree enumerator -pub const RoundedEnumerator = Enumerator{ - .item_prefix = "├── ", - .last_prefix = "╰── ", - .indent_prefix = "│ ", - .empty_prefix = " ", -}; - -pub fn Tree(comptime T: type) type { - return struct { - allocator: std.mem.Allocator, - nodes: std.array_list.Managed(Node), - root_indices: std.array_list.Managed(usize), - enumerator: Enumerator, - node_style: style_mod.Style, - label_style: style_mod.Style, - - const Self = @This(); - - pub const Node = struct { - value: T, - label: []const u8, - children: std.array_list.Managed(usize), - expanded: bool, - style_override: ?style_mod.Style, - - pub fn deinit(self: *Node) void { - self.children.deinit(); - } - }; - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .nodes = std.array_list.Managed(Node).init(allocator), - .root_indices = std.array_list.Managed(usize).init(allocator), - .enumerator = DefaultEnumerator, - .node_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - .label_style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - }; - } - - pub fn deinit(self: *Self) void { - for (self.nodes.items) |*node| { - node.deinit(); - } - self.nodes.deinit(); - self.root_indices.deinit(); - } - - /// Add a root node, returns its index - pub fn addRoot(self: *Self, value: T, label: []const u8) !usize { - const idx = self.nodes.items.len; - try self.nodes.append(.{ - .value = value, - .label = label, - .children = std.array_list.Managed(usize).init(self.allocator), - .expanded = true, - .style_override = null, - }); - try self.root_indices.append(idx); - return idx; - } - - /// Add a child node to a parent, returns child index - pub fn addChild(self: *Self, parent: usize, value: T, label: []const u8) !usize { - const idx = self.nodes.items.len; - try self.nodes.append(.{ - .value = value, - .label = label, - .children = std.array_list.Managed(usize).init(self.allocator), - .expanded = true, - .style_override = null, - }); - try self.nodes.items[parent].children.append(idx); - return idx; - } - - /// Toggle expand/collapse of a node - pub fn toggleNode(self: *Self, idx: usize) void { - if (idx < self.nodes.items.len) { - self.nodes.items[idx].expanded = !self.nodes.items[idx].expanded; - } - } - - /// Set enumerator style - pub fn setEnumerator(self: *Self, e: Enumerator) void { - self.enumerator = e; - } - - /// Render the tree - pub fn view(self: *const Self, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (self.root_indices.items, 0..) |root_idx, i| { - if (i > 0) try writer.writeAll("\n"); - try self.renderNode(writer, allocator, root_idx, "", true); - } - - return result.toOwnedSlice(); - } - - fn renderNode( - self: *const Self, - writer: *Writer, - allocator: std.mem.Allocator, - node_idx: usize, - prefix: []const u8, - is_root: bool, - ) !void { - const node = self.nodes.items[node_idx]; - const active_style = node.style_override orelse self.label_style; - - // Write prefix - try writer.writeAll(prefix); - - // Write label - const styled_label = try active_style.render(allocator, node.label); - try writer.writeAll(styled_label); - - // Render children if expanded - if (node.expanded and node.children.items.len > 0) { - const children = node.children.items; - for (children, 0..) |child_idx, ci| { - try writer.writeAll("\n"); - const is_last = (ci == children.len - 1); - const connector = if (is_last) self.enumerator.last_prefix else self.enumerator.item_prefix; - const child_prefix = if (is_last) self.enumerator.empty_prefix else self.enumerator.indent_prefix; - - // Build new prefix for children - var new_prefix = std.array_list.Managed(u8).init(allocator); - if (!is_root) { - try new_prefix.appendSlice(prefix); - } - try new_prefix.appendSlice(child_prefix); - const new_prefix_str = try new_prefix.toOwnedSlice(); - - // Write connector and recurse - var connector_prefix = std.array_list.Managed(u8).init(allocator); - if (!is_root) { - try connector_prefix.appendSlice(prefix); - } - try connector_prefix.appendSlice(connector); - const connector_str = try connector_prefix.toOwnedSlice(); - - try self.renderNode(writer, allocator, child_idx, connector_str, false); - _ = new_prefix_str; - } - } - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig deleted file mode 100644 index 69085e5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/viewport.zig +++ /dev/null @@ -1,456 +0,0 @@ -//! Scrollable content viewport component. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const measure = @import("../layout/measure.zig"); -const style = @import("../style/style.zig"); -const ansi = @import("../terminal/ansi.zig"); -const unicode = @import("../unicode.zig"); - -pub const Viewport = struct { - allocator: std.mem.Allocator, - - // Content - content: []const u8, - owned_content: ?[]u8, - lines: std.array_list.Managed([]const u8), - - // Dimensions - width: u16, - height: u16, - - // Scroll position (visual rows, display columns) - y_offset: usize, - x_offset: usize, - - // Styling - viewport_style: style.Style, - scrollbar_track_style: style.Style, - scrollbar_thumb_style: style.Style, - - // Options - wrap: bool, - show_scrollbar: bool, - empty_char: []const u8, - scrollbar_track_char: []const u8, - scrollbar_thumb_char: []const u8, - - pub fn init(allocator: std.mem.Allocator, width: u16, height: u16) Viewport { - return .{ - .allocator = allocator, - .content = "", - .owned_content = null, - .lines = std.array_list.Managed([]const u8).init(allocator), - .width = width, - .height = height, - .y_offset = 0, - .x_offset = 0, - .viewport_style = blk: { - var s = style.Style{}; - break :blk s.inline_style(true); - }, - .scrollbar_track_style = blk: { - var s = style.Style{}; - break :blk s.inline_style(true); - }, - .scrollbar_thumb_style = blk: { - var s = style.Style{}; - break :blk s.inline_style(true); - }, - .wrap = false, - .show_scrollbar = true, - .empty_char = " ", - .scrollbar_track_char = "░", - .scrollbar_thumb_char = "█", - }; - } - - pub fn deinit(self: *Viewport) void { - if (self.owned_content) |content| self.allocator.free(content); - self.lines.deinit(); - } - - pub fn setContent(self: *Viewport, content: []const u8) !void { - if (self.owned_content) |existing| self.allocator.free(existing); - const owned = try self.allocator.dupe(u8, content); - self.owned_content = owned; - self.content = owned; - self.lines.clearRetainingCapacity(); - - var iter = std.mem.splitScalar(u8, self.content, '\n'); - while (iter.next()) |line| { - try self.lines.append(line); - } - - self.clampScroll(); - } - - pub fn setSize(self: *Viewport, width: u16, height: u16) void { - self.width = width; - self.height = height; - self.clampScroll(); - } - - pub fn setWrap(self: *Viewport, wrap: bool) void { - self.wrap = wrap; - if (wrap) self.x_offset = 0; - self.clampScroll(); - } - - pub fn setShowScrollbar(self: *Viewport, show_scrollbar: bool) void { - self.show_scrollbar = show_scrollbar; - self.clampScroll(); - } - - pub fn setStyle(self: *Viewport, viewport_style: style.Style) void { - self.viewport_style = viewport_style.inline_style(true); - } - - pub fn setScrollbarStyle(self: *Viewport, track_style: style.Style, thumb_style: style.Style) void { - self.scrollbar_track_style = track_style.inline_style(true); - self.scrollbar_thumb_style = thumb_style.inline_style(true); - } - - pub fn setScrollbarChars(self: *Viewport, track_char: []const u8, thumb_char: []const u8) void { - self.scrollbar_track_char = track_char; - self.scrollbar_thumb_char = thumb_char; - } - - pub fn setEmptyChar(self: *Viewport, empty_char: []const u8) void { - self.empty_char = empty_char; - } - - pub fn scrollDown(self: *Viewport, n: usize) void { - self.y_offset += n; - self.clampScroll(); - } - - pub fn scrollUp(self: *Viewport, n: usize) void { - self.y_offset -|= n; - } - - pub fn scrollRight(self: *Viewport, n: usize) void { - if (self.wrap) return; - self.x_offset += n; - self.clampScroll(); - } - - pub fn scrollLeft(self: *Viewport, n: usize) void { - self.x_offset -|= n; - } - - pub fn scrollTo(self: *Viewport, y_offset: usize, x_offset: usize) void { - self.y_offset = y_offset; - self.x_offset = if (self.wrap) 0 else x_offset; - self.clampScroll(); - } - - pub fn gotoTop(self: *Viewport) void { - self.y_offset = 0; - } - - pub fn gotoBottom(self: *Viewport) void { - const total = self.totalVisualLines(); - if (total > self.height) { - self.y_offset = total - self.height; - } else { - self.y_offset = 0; - } - } - - pub fn pageDown(self: *Viewport) void { - self.scrollDown(self.height); - } - - pub fn pageUp(self: *Viewport) void { - self.scrollUp(self.height); - } - - pub fn halfPageDown(self: *Viewport) void { - self.scrollDown(self.height / 2); - } - - pub fn halfPageUp(self: *Viewport) void { - self.scrollUp(self.height / 2); - } - - pub fn scrollPercent(self: *const Viewport) u8 { - const total = self.totalVisualLines(); - if (total <= self.height) return 100; - const max_offset = total - self.height; - return @intCast(@min(100, (self.y_offset * 100) / max_offset)); - } - - pub fn atTop(self: *const Viewport) bool { - return self.y_offset == 0; - } - - pub fn atBottom(self: *const Viewport) bool { - const total = self.totalVisualLines(); - if (total <= self.height) return true; - return self.y_offset >= total - self.height; - } - - pub fn totalLines(self: *const Viewport) usize { - return self.lines.items.len; - } - - pub fn totalVisualLines(self: *const Viewport) usize { - return self.totalVisualLinesForWidth(self.visibleWidth()); - } - - fn totalVisualLinesForWidth(self: *const Viewport, visible_width: usize) usize { - if (self.lines.items.len == 0) return 0; - if (visible_width == 0) return 0; - - if (!self.wrap) return self.lines.items.len; - - var total: usize = 0; - for (self.lines.items) |line| { - const line_width = measure.width(line); - total += @max(@as(usize, 1), std.math.divCeil(usize, line_width, visible_width) catch 1); - } - return total; - } - - pub fn contentWidth(self: *const Viewport) usize { - var max_width: usize = 0; - for (self.lines.items) |line| { - max_width = @max(max_width, measure.width(line)); - } - return max_width; - } - - pub fn handleKey(self: *Viewport, key: keys.KeyEvent) void { - switch (key.key) { - .up => self.scrollUp(1), - .down => self.scrollDown(1), - .left => self.scrollLeft(1), - .right => self.scrollRight(1), - .page_up => self.pageUp(), - .page_down => self.pageDown(), - .home => self.gotoTop(), - .end => self.gotoBottom(), - .char => |c| switch (c) { - 'j' => self.scrollDown(1), - 'k' => self.scrollUp(1), - 'h' => self.scrollLeft(1), - 'l' => self.scrollRight(1), - 'g' => self.gotoTop(), - 'G' => self.gotoBottom(), - 'd' => self.halfPageDown(), - 'u' => self.halfPageUp(), - else => {}, - }, - else => {}, - } - } - - fn clampScroll(self: *Viewport) void { - const total_visual_lines = self.totalVisualLines(); - if (total_visual_lines > self.height) { - self.y_offset = @min(self.y_offset, total_visual_lines - self.height); - } else { - self.y_offset = 0; - } - - if (self.wrap) { - self.x_offset = 0; - return; - } - - const visible_width = self.visibleWidth(); - const total_width = self.contentWidth(); - if (total_width > visible_width) { - self.x_offset = @min(self.x_offset, total_width - visible_width); - } else { - self.x_offset = 0; - } - } - - pub fn view(self: *const Viewport, allocator: std.mem.Allocator) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const visible_width = self.visibleWidth(); - - var row: usize = 0; - while (row < self.height) : (row += 1) { - if (row > 0) try writer.writeByte('\n'); - - const line_text = try self.lineForVisualRow(allocator, self.y_offset + row, visible_width); - defer allocator.free(line_text); - - const padded = try self.padLine(allocator, line_text, visible_width); - defer allocator.free(padded); - - const rendered = try self.viewport_style.render(allocator, padded); - defer allocator.free(rendered); - try writer.writeAll(rendered); - - if (self.show_scrollbar and self.totalVisualLines() > self.height) { - const scrollbar = try self.renderScrollbar(allocator, row); - defer allocator.free(scrollbar); - try writer.writeAll(scrollbar); - } - } - - return result.toOwnedSlice(); - } - - fn visibleWidth(self: *const Viewport) usize { - if (!self.show_scrollbar) return self.width; - const with_scrollbar = self.width -| 1; - if (self.totalVisualLinesForWidth(@max(@as(usize, 1), with_scrollbar)) > self.height) { - return with_scrollbar; - } - return self.width; - } - - fn lineForVisualRow(self: *const Viewport, allocator: std.mem.Allocator, visual_row: usize, visible_width: usize) ![]const u8 { - if (visible_width == 0 or self.lines.items.len == 0) { - return try allocator.dupe(u8, ""); - } - - if (!self.wrap) { - if (visual_row >= self.lines.items.len) return try allocator.dupe(u8, ""); - const line = self.lines.items[visual_row]; - if (self.x_offset >= measure.width(line)) return try allocator.dupe(u8, ""); - return try self.getSubstring(allocator, line, self.x_offset, visible_width); - } - - var remaining = visual_row; - for (self.lines.items) |line| { - const line_width = measure.width(line); - const segments = @max(@as(usize, 1), std.math.divCeil(usize, line_width, visible_width) catch 1); - if (remaining < segments) { - return try self.getSubstring(allocator, line, remaining * visible_width, visible_width); - } - remaining -= segments; - } - - return try allocator.dupe(u8, ""); - } - - fn padLine(self: *const Viewport, allocator: std.mem.Allocator, line: []const u8, visible_width: usize) ![]const u8 { - const current_width = measure.width(line); - if (current_width >= visible_width) return try allocator.dupe(u8, line); - - var out = std.array_list.Managed(u8).init(allocator); - try out.appendSlice(line); - for (0..(visible_width - current_width)) |_| { - try out.appendSlice(self.empty_char); - } - return out.toOwnedSlice(); - } - - fn getSubstring(self: *const Viewport, allocator: std.mem.Allocator, line: []const u8, start_col: usize, max_width: usize) ![]const u8 { - _ = self; - var result: std.array_list.Managed(u8) = .init(allocator); - - var col: usize = 0; - var i: usize = 0; - var wrote_escape = false; - - while (i < line.len and col < start_col) { - if (line[i] == 0x1b) { - const seq_end = ansiSequenceEnd(line, i); - if (seq_end > i) { - try result.appendSlice(line[i..seq_end]); - wrote_escape = true; - i = seq_end; - continue; - } - } - - const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; - if (i + byte_len <= line.len) { - const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { - i += 1; - col += 1; - continue; - }; - col += unicode.charWidth(cp); - } - i += byte_len; - } - - var output_width: usize = 0; - while (i < line.len and output_width < max_width) { - if (line[i] == 0x1b) { - const seq_end = ansiSequenceEnd(line, i); - if (seq_end > i) { - try result.appendSlice(line[i..seq_end]); - wrote_escape = true; - i = seq_end; - continue; - } - } - - const byte_len = std.unicode.utf8ByteSequenceLength(line[i]) catch 1; - if (i + byte_len <= line.len) { - const cp = std.unicode.utf8Decode(line[i..][0..byte_len]) catch { - try result.append(line[i]); - i += 1; - output_width += 1; - continue; - }; - const cw = unicode.charWidth(cp); - if (output_width + cw > max_width) break; - try result.appendSlice(line[i..][0..byte_len]); - output_width += cw; - } - i += byte_len; - } - - if (wrote_escape and !std.mem.endsWith(u8, result.items, ansi.reset)) { - try result.appendSlice(ansi.reset); - } - - return result.toOwnedSlice(); - } - - fn renderScrollbar(self: *const Viewport, allocator: std.mem.Allocator, row: usize) ![]const u8 { - const total = self.totalVisualLines(); - const visible = self.height; - - if (total <= visible) return try allocator.dupe(u8, ""); - - const scrollbar_height = @max(1, (visible * visible) / total); - const max_offset = total - visible; - const scrollbar_pos = if (max_offset == 0) 0 else (self.y_offset * (visible - scrollbar_height)) / max_offset; - - const glyph = if (row >= scrollbar_pos and row < scrollbar_pos + scrollbar_height) - try self.scrollbar_thumb_style.render(allocator, self.scrollbar_thumb_char) - else - try self.scrollbar_track_style.render(allocator, self.scrollbar_track_char); - - return glyph; - } -}; - -fn ansiSequenceEnd(line: []const u8, start: usize) usize { - if (start >= line.len or line[start] != 0x1b or start + 1 >= line.len) return start; - - const second = line[start + 1]; - if (second == '[') { - var i = start + 2; - while (i < line.len) : (i += 1) { - const c = line[i]; - if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) return i + 1; - } - return line.len; - } - - if (second == ']') { - var i = start + 2; - while (i < line.len) : (i += 1) { - if (line[i] == 0x07) return i + 1; - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '\\') return i + 2; - } - return line.len; - } - - return @min(line.len, start + 2); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig deleted file mode 100644 index cfaadda..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/components/virtual_list.zig +++ /dev/null @@ -1,216 +0,0 @@ -//! Virtual list component for efficiently rendering large datasets. -//! Only renders items visible in the viewport. - -const std = @import("std"); -const Writer = std.Io.Writer; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const keys = @import("../input/keys.zig"); -const measure = @import("../layout/measure.zig"); - -pub fn VirtualList(comptime T: type) type { - return struct { - /// All items (not copied — references the original slice). - items: []const T = &.{}, - /// Number of visible rows. - viewport_height: u16 = 20, - /// Current cursor position (absolute index). - cursor: usize = 0, - /// Scroll offset (first visible item index). - offset: usize = 0, - /// Selection set. - selected: ?std.AutoHashMap(usize, void) = null, - /// Multi-select mode. - multi_select: bool = false, - /// Focused state. - focused: bool = true, - /// Render function: called for each visible item. - render_fn: ?*const fn (item: T, index: usize, selected: bool, allocator: std.mem.Allocator) []const u8 = null, - /// Wrap cursor around list ends. - wrap_around: bool = false, - /// Text shown when list is empty. - empty_text: []const u8 = "(empty)", - /// Width for each row (0 = no padding). - row_width: u16 = 0, - - // Styling - cursor_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.bg(.blue); - s = s.fg(.white); - s = s.inline_style(true); - break :blk s; - }, - item_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.inline_style(true); - break :blk s; - }, - selected_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.green); - s = s.inline_style(true); - break :blk s; - }, - scrollbar_style: style_mod.Style = blk: { - var s = style_mod.Style{}; - s = s.fg(.gray(8)); - s = s.inline_style(true); - break :blk s; - }, - /// Cursor prefix. - cursor_symbol: []const u8 = "> ", - /// Normal prefix. - normal_symbol: []const u8 = " ", - /// Show scrollbar. - show_scrollbar: bool = true, - /// Show item count. - show_count: bool = true, - - const Self = @This(); - - pub fn setItems(self: *Self, items: []const T) void { - self.items = items; - if (self.cursor >= items.len and items.len > 0) { - self.cursor = items.len - 1; - } - self.ensureVisible(); - } - - pub fn update(self: *Self, key: keys.KeyEvent) void { - const total = self.items.len; - if (total == 0) return; - - switch (key.key) { - .up => { - if (self.cursor > 0) { - self.cursor -= 1; - } else if (self.wrap_around and total > 0) { - self.cursor = total - 1; - } - self.ensureVisible(); - }, - .down => { - if (self.cursor + 1 < total) { - self.cursor += 1; - } else if (self.wrap_around) { - self.cursor = 0; - } - self.ensureVisible(); - }, - .page_up => { - if (self.cursor >= self.viewport_height) { - self.cursor -= self.viewport_height; - } else { - self.cursor = 0; - } - self.ensureVisible(); - }, - .page_down => { - self.cursor += self.viewport_height; - if (self.cursor >= total) self.cursor = total - 1; - self.ensureVisible(); - }, - .home => { - self.cursor = 0; - self.ensureVisible(); - }, - .end => { - if (total > 0) self.cursor = total - 1; - self.ensureVisible(); - }, - .char => |c| { - if (c == ' ' and self.multi_select) { - self.toggleSelection(self.cursor); - } - }, - .enter => { - self.toggleSelection(self.cursor); - }, - else => {}, - } - } - - fn toggleSelection(self: *Self, index: usize) void { - _ = self; - _ = index; - // Selection is managed externally; this is a placeholder for signaling - } - - fn ensureVisible(self: *Self) void { - if (self.cursor < self.offset) { - self.offset = self.cursor; - } - if (self.cursor >= self.offset + self.viewport_height) { - self.offset = self.cursor - self.viewport_height + 1; - } - } - - pub fn view(self: *const Self, allocator: std.mem.Allocator) []const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - const total = self.items.len; - const vh: usize = self.viewport_height; - - if (total == 0) { - writer.writeAll(self.empty_text) catch {}; - return result.toArrayList().items; - } - - const end = @min(self.offset + vh, total); - - for (self.offset..end) |i| { - if (i > self.offset) writer.writeByte('\n') catch {}; - - const is_cursor = (i == self.cursor and self.focused); - const is_selected = false; // Could check selection map - - // Get item text - const item_text = if (self.render_fn) |rf| - rf(self.items[i], i, is_selected, allocator) - else - defaultRender(self.items[i], i, allocator); - - // Apply style - const prefix = if (is_cursor) self.cursor_symbol else self.normal_symbol; - const s = if (is_cursor) self.cursor_style else if (is_selected) self.selected_style else self.item_style; - - const line = std.fmt.allocPrint(allocator, "{s}{s}", .{ prefix, item_text }) catch item_text; - writer.writeAll(s.render(allocator, line) catch line) catch {}; - - // Scrollbar - if (self.show_scrollbar and total > vh) { - const row = i - self.offset; - const thumb_start = (self.offset * vh) / total; - const thumb_size = @max(1, (vh * vh) / total); - const is_thumb = row >= thumb_start and row < thumb_start + thumb_size; - const sb_char: []const u8 = if (is_thumb) "\xe2\x96\x88" else "\xe2\x96\x91"; - writer.writeByte(' ') catch {}; - writer.writeAll(self.scrollbar_style.render(allocator, sb_char) catch sb_char) catch {}; - } - } - - // Item count - if (self.show_count) { - writer.writeByte('\n') catch {}; - const count_str = std.fmt.allocPrint(allocator, " {d}/{d}", .{ self.cursor + 1, total }) catch ""; - var cs = style_mod.Style{}; - cs = cs.fg(.gray(10)); - cs = cs.inline_style(true); - writer.writeAll(cs.render(allocator, count_str) catch count_str) catch {}; - } - - return result.toArrayList().items; - } - - fn defaultRender(item: T, index: usize, allocator: std.mem.Allocator) []const u8 { - if (comptime @typeInfo(T) == .pointer) { - if (comptime @typeInfo(std.meta.Child(T)) == .int) { - // T is []const u8 - return item; - } - } - return std.fmt.allocPrint(allocator, "Item {d}", .{index}) catch "?"; - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig deleted file mode 100644 index 2728a74..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/action.zig +++ /dev/null @@ -1,410 +0,0 @@ -//! Action / command registry — central source of truth for app actions. -//! -//! Inspired by Textual's action system. An `Action` couples a stable string -//! ID, a human label, an optional key binding, and an optional category to a -//! single registry. The same registry feeds: -//! -//! * the keybinding matcher (key event → action id) -//! * the auto-footer (one-line key hint bar) -//! * the command palette (filterable list of all actions) -//! * the help screen -//! -//! The user's `update` function looks up the matching action by id, eg.: -//! -//! if (registry.matchKey(key_event)) |action| { -//! return self.dispatch(action.id); -//! } -//! -//! and a `dispatch` switch on `action.id` calls the right handler. Optional -//! `handler` callbacks are also supported for fire-and-forget actions. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("../input/keys.zig"); -const KeyEvent = keys.KeyEvent; -const style_mod = @import("../style/style.zig"); -const Color = @import("../style/color.zig").Color; -const measure = @import("../layout/measure.zig"); -const fuzzy = @import("fuzzy.zig"); - -/// Optional callback shape. Receives the user-supplied context pointer the -/// registry was created with — typically the app model. -pub const Handler = *const fn (user_ctx: ?*anyopaque) void; - -pub const Action = struct { - /// Stable string identifier, eg. "app.quit", "file.save". - id: []const u8, - /// User-facing label, eg. "Quit", "Save File". - label: []const u8, - /// Longer description for palette / help. - description: []const u8 = "", - /// Optional category for grouping in help / palette, eg. "File", "Edit". - category: []const u8 = "", - /// Optional primary key binding. Other bindings can be added via - /// `addBinding` if you want chord-style or aliases. - binding: ?KeyEvent = null, - /// Whether this action shows up in match/footer/palette. - enabled: bool = true, - /// Whether this action is shown in the auto-footer hint bar. - show_in_footer: bool = false, - /// Optional fire-and-forget callback. The registry calls this when the - /// matching key fires, in addition to returning the action so the user's - /// update function can switch on the id. - handler: ?Handler = null, -}; - -pub const ActionRegistry = struct { - allocator: std.mem.Allocator, - actions: std.array_list.Managed(Action), - /// Optional aliases: extra key events that map to the same action. - aliases: std.array_list.Managed(Alias), - /// Pointer passed to `Handler` callbacks. Typically the app model. - user_ctx: ?*anyopaque, - - pub const Alias = struct { - id: []const u8, - binding: KeyEvent, - }; - - pub fn init(allocator: std.mem.Allocator) ActionRegistry { - return .{ - .allocator = allocator, - .actions = std.array_list.Managed(Action).init(allocator), - .aliases = std.array_list.Managed(Alias).init(allocator), - .user_ctx = null, - }; - } - - pub fn deinit(self: *ActionRegistry) void { - self.actions.deinit(); - self.aliases.deinit(); - } - - pub fn setUserContext(self: *ActionRegistry, ctx: *anyopaque) void { - self.user_ctx = ctx; - } - - pub fn register(self: *ActionRegistry, action: Action) !void { - // Detect duplicate ids early — registry is a "single source of truth". - for (self.actions.items) |existing| { - if (std.mem.eql(u8, existing.id, action.id)) return error.DuplicateActionId; - } - try self.actions.append(action); - } - - /// Replace an action's binding by id. Returns true if the action existed. - pub fn rebind(self: *ActionRegistry, id: []const u8, binding: ?KeyEvent) bool { - for (self.actions.items) |*a| { - if (std.mem.eql(u8, a.id, id)) { - a.binding = binding; - return true; - } - } - return false; - } - - pub fn setEnabled(self: *ActionRegistry, id: []const u8, enabled: bool) bool { - for (self.actions.items) |*a| { - if (std.mem.eql(u8, a.id, id)) { - a.enabled = enabled; - return true; - } - } - return false; - } - - /// Add an additional key alias for an existing action. - pub fn addAlias(self: *ActionRegistry, id: []const u8, binding: KeyEvent) !void { - // Validate the action exists. - for (self.actions.items) |a| { - if (std.mem.eql(u8, a.id, id)) { - try self.aliases.append(.{ .id = id, .binding = binding }); - return; - } - } - return error.UnknownAction; - } - - pub fn get(self: *const ActionRegistry, id: []const u8) ?*const Action { - for (self.actions.items) |*a| { - if (std.mem.eql(u8, a.id, id)) return a; - } - return null; - } - - /// Look up the action matching `event`. Returns null when no enabled - /// action is bound. Calls the action's handler if present. - pub fn matchKey(self: *const ActionRegistry, event: KeyEvent) ?*const Action { - for (self.actions.items) |*a| { - if (!a.enabled) continue; - if (a.binding) |b| { - if (b.eql(event)) { - if (a.handler) |h| h(self.user_ctx); - return a; - } - } - } - for (self.aliases.items) |alias| { - if (alias.binding.eql(event)) { - const a = self.get(alias.id) orelse continue; - if (!a.enabled) continue; - if (a.handler) |h| h(self.user_ctx); - return a; - } - } - return null; - } - - /// Invoke the action's handler explicitly (eg. selected from the palette). - /// Returns true if the action exists and is enabled. - pub fn invoke(self: *const ActionRegistry, id: []const u8) bool { - const a = self.get(id) orelse return false; - if (!a.enabled) return false; - if (a.handler) |h| h(self.user_ctx); - return true; - } - - /// Iterate enabled actions matching a fuzzy query. Caller owns the - /// returned slice. Useful for feeding a CommandPalette. - pub fn filter(self: *const ActionRegistry, allocator: std.mem.Allocator, query: []const u8) ![]const *const Action { - var out = std.array_list.Managed(*const Action).init(allocator); - errdefer out.deinit(); - if (query.len == 0) { - for (self.actions.items) |*a| { - if (a.enabled) try out.append(a); - } - return out.toOwnedSlice(); - } - - const Scored = struct { ptr: *const Action, score: i32 }; - var scored = std.array_list.Managed(Scored).init(allocator); - defer scored.deinit(); - - for (self.actions.items) |*a| { - if (!a.enabled) continue; - const s = fuzzy.scoreIgnoreCase(a.label, query); - if (s > 0) try scored.append(.{ .ptr = a, .score = s }); - } - - std.mem.sort(Scored, scored.items, {}, struct { - fn lt(_: void, l: Scored, r: Scored) bool { - return l.score > r.score; - } - }.lt); - - for (scored.items) |s| try out.append(s.ptr); - return out.toOwnedSlice(); - } - - /// Format a key event for display: "ctrl+s", "esc", "enter", etc. - pub fn formatKey(allocator: std.mem.Allocator, event: KeyEvent) ![]u8 { - var out: Writer.Allocating = .init(allocator); - const w = &out.writer; - if (event.modifiers.ctrl) try w.writeAll("ctrl+"); - if (event.modifiers.alt) try w.writeAll("alt+"); - if (event.modifiers.shift) try w.writeAll("shift+"); - if (event.modifiers.super) try w.writeAll("super+"); - switch (event.key) { - .char => |c| { - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch 0; - try w.writeAll(buf[0..len]); - }, - .escape => try w.writeAll("esc"), - .enter => try w.writeAll("⏎"), - .space => try w.writeAll("space"), - .tab => try w.writeAll("⇥"), - .left => try w.writeAll("←"), - .right => try w.writeAll("→"), - .up => try w.writeAll("↑"), - .down => try w.writeAll("↓"), - else => try w.writeAll(event.key.name()), - } - return out.toOwnedSlice(); - } -}; - -/// Auto-rendered single-line footer that shows the bindings for actions -/// flagged with `show_in_footer = true`. Useful as a persistent key hint -/// bar at the bottom of the screen, kept in sync with the registry. -pub const Footer = struct { - registry: *const ActionRegistry, - width: u16 = 80, - separator: []const u8 = " ", - key_style: style_mod.Style, - label_style: style_mod.Style, - base_style: style_mod.Style, - - pub fn init(registry: *const ActionRegistry) Footer { - var key_s = style_mod.Style{}; - key_s = key_s.fg(.cyan); - key_s = key_s.bold(true); - key_s = key_s.inline_style(true); - var label_s = style_mod.Style{}; - label_s = label_s.fg(.gray(12)); - label_s = label_s.inline_style(true); - var base = style_mod.Style{}; - base = base.bg(.gray(3)); - base = base.inline_style(true); - return .{ - .registry = registry, - .key_style = key_s, - .label_style = label_s, - .base_style = base, - }; - } - - pub fn setWidth(self: *Footer, w: u16) void { - self.width = w; - } - - pub fn view(self: *const Footer, allocator: std.mem.Allocator) ![]const u8 { - var inner: Writer.Allocating = .init(allocator); - defer inner.deinit(); - const w = &inner.writer; - - var first = true; - for (self.registry.actions.items) |a| { - if (!a.enabled or !a.show_in_footer) continue; - const binding = a.binding orelse continue; - if (!first) try w.writeAll(self.separator); - first = false; - const key_str = try ActionRegistry.formatKey(allocator, binding); - defer allocator.free(key_str); - const styled_key = try self.key_style.render(allocator, key_str); - defer allocator.free(styled_key); - try w.writeAll(styled_key); - try w.writeByte(' '); - const styled_label = try self.label_style.render(allocator, a.label); - defer allocator.free(styled_label); - try w.writeAll(styled_label); - } - - // Pad / truncate to width and apply base background. - const text = try inner.toOwnedSlice(); - defer allocator.free(text); - const text_w = measure.width(text); - - var out: Writer.Allocating = .init(allocator); - const ow = &out.writer; - try ow.writeAll(text); - if (text_w < self.width) { - const pad = self.width - text_w; - const spaces = try allocator.alloc(u8, pad); - defer allocator.free(spaces); - @memset(spaces, ' '); - const styled_pad = try self.base_style.render(allocator, spaces); - defer allocator.free(styled_pad); - try ow.writeAll(styled_pad); - } - return out.toOwnedSlice(); - } -}; - -// ── Tests ────────────────────────────────────────────────────────────── - -const testing = std.testing; - -test "register and lookup by id" { - var reg = ActionRegistry.init(testing.allocator); - defer reg.deinit(); - - try reg.register(.{ .id = "app.quit", .label = "Quit" }); - const a = reg.get("app.quit").?; - try testing.expectEqualStrings("Quit", a.label); -} - -test "duplicate id rejected" { - var reg = ActionRegistry.init(testing.allocator); - defer reg.deinit(); - try reg.register(.{ .id = "x", .label = "X" }); - const r = reg.register(.{ .id = "x", .label = "X again" }); - try testing.expectError(error.DuplicateActionId, r); -} - -test "matchKey routes by binding" { - var reg = ActionRegistry.init(testing.allocator); - defer reg.deinit(); - try reg.register(.{ - .id = "file.save", - .label = "Save", - .binding = .{ .key = .{ .char = 's' }, .modifiers = .{ .ctrl = true } }, - }); - const event: KeyEvent = .{ .key = .{ .char = 's' }, .modifiers = .{ .ctrl = true } }; - const a = reg.matchKey(event).?; - try testing.expectEqualStrings("file.save", a.id); -} - -test "matchKey returns null for unbound" { - var reg = ActionRegistry.init(testing.allocator); - defer reg.deinit(); - try reg.register(.{ .id = "noop", .label = "Noop" }); - const ev: KeyEvent = .{ .key = .{ .char = 'q' } }; - try testing.expectEqual(@as(?*const Action, null), reg.matchKey(ev)); -} - -test "alias matches same action" { - var reg = ActionRegistry.init(testing.allocator); - defer reg.deinit(); - try reg.register(.{ - .id = "view.toggle", - .label = "Toggle", - .binding = .{ .key = .{ .char = 't' } }, - }); - try reg.addAlias("view.toggle", .{ .key = .f5 }); - const a = reg.matchKey(.{ .key = .f5 }).?; - try testing.expectEqualStrings("view.toggle", a.id); -} - -test "filter ranks by fuzzy match" { - const allocator = testing.allocator; - var reg = ActionRegistry.init(allocator); - defer reg.deinit(); - try reg.register(.{ .id = "open", .label = "Open File" }); - try reg.register(.{ .id = "save", .label = "Save File" }); - try reg.register(.{ .id = "close", .label = "Close Window" }); - - const matches = try reg.filter(allocator, "of"); - defer allocator.free(matches); - try testing.expect(matches.len >= 1); - try testing.expectEqualStrings("open", matches[0].id); -} - -test "footer shows only flagged actions" { - const allocator = testing.allocator; - var reg = ActionRegistry.init(allocator); - defer reg.deinit(); - try reg.register(.{ - .id = "app.quit", - .label = "Quit", - .binding = .{ .key = .{ .char = 'q' } }, - .show_in_footer = true, - }); - try reg.register(.{ - .id = "internal", - .label = "Hidden", - .binding = .{ .key = .{ .char = 'h' } }, - .show_in_footer = false, - }); - - const footer = Footer.init(®); - const out = try footer.view(allocator); - defer allocator.free(out); - - try testing.expect(std.mem.indexOf(u8, out, "Quit") != null); - try testing.expect(std.mem.indexOf(u8, out, "Hidden") == null); -} - -test "formatKey produces readable strings" { - const allocator = testing.allocator; - const ctrl_s = try ActionRegistry.formatKey(allocator, .{ - .key = .{ .char = 's' }, - .modifiers = .{ .ctrl = true }, - }); - defer allocator.free(ctrl_s); - try testing.expectEqualStrings("ctrl+s", ctrl_s); - - const escape = try ActionRegistry.formatKey(allocator, .{ .key = .escape }); - defer allocator.free(escape); - try testing.expectEqualStrings("esc", escape); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig deleted file mode 100644 index 3296928..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/animation.zig +++ /dev/null @@ -1,185 +0,0 @@ -//! Animation and tween system. -//! Provides easing functions and a Tween for interpolating values over time. - -const std = @import("std"); -const Color = @import("../style/color.zig").Color; -const progress_mod = @import("../components/progress.zig"); - -/// Easing functions that map t in [0,1] to an output in [0,1]. -pub const Easing = enum { - linear, - ease_in, - ease_out, - ease_in_out, - ease_in_cubic, - ease_out_cubic, - ease_in_out_cubic, - bounce, - elastic, - - pub fn apply(self: Easing, t: f64) f64 { - const clamped = @max(0.0, @min(1.0, t)); - return switch (self) { - .linear => clamped, - .ease_in => clamped * clamped, - .ease_out => 1.0 - (1.0 - clamped) * (1.0 - clamped), - .ease_in_out => if (clamped < 0.5) - 2.0 * clamped * clamped - else - 1.0 - std.math.pow(f64, -2.0 * clamped + 2.0, 2) / 2.0, - .ease_in_cubic => clamped * clamped * clamped, - .ease_out_cubic => 1.0 - std.math.pow(f64, 1.0 - clamped, 3), - .ease_in_out_cubic => if (clamped < 0.5) - 4.0 * clamped * clamped * clamped - else - 1.0 - std.math.pow(f64, -2.0 * clamped + 2.0, 3) / 2.0, - .bounce => blk: { - var b = 1.0 - clamped; - if (b < 1.0 / 2.75) { - break :blk 1.0 - (7.5625 * b * b); - } else if (b < 2.0 / 2.75) { - b -= 1.5 / 2.75; - break :blk 1.0 - (7.5625 * b * b + 0.75); - } else if (b < 2.5 / 2.75) { - b -= 2.25 / 2.75; - break :blk 1.0 - (7.5625 * b * b + 0.9375); - } else { - b -= 2.625 / 2.75; - break :blk 1.0 - (7.5625 * b * b + 0.984375); - } - }, - .elastic => if (clamped == 0.0 or clamped == 1.0) - clamped - else - -std.math.pow(f64, 2.0, 10.0 * clamped - 10.0) * - @sin((clamped * 10.0 - 10.75) * (2.0 * std.math.pi / 3.0)), - }; - } -}; - -/// A tween that interpolates a f64 value from `start` to `end` over `duration_ns`. -pub const Tween = struct { - start_val: f64, - end_val: f64, - duration_ns: u64, - elapsed_ns: u64, - easing: Easing, - state: State, - loop_mode: LoopMode, - - pub const State = enum { - idle, - running, - finished, - }; - - pub const LoopMode = enum { - once, - loop, - ping_pong, - }; - - /// Create a new tween. - pub fn init(from: f64, to: f64, duration_ms: u64) Tween { - return .{ - .start_val = from, - .end_val = to, - .duration_ns = duration_ms * std.time.ns_per_ms, - .elapsed_ns = 0, - .easing = .linear, - .state = .idle, - .loop_mode = .once, - }; - } - - /// Set easing function. - pub fn setEasing(self: *Tween, easing: Easing) void { - self.easing = easing; - } - - /// Set loop mode. - pub fn setLoop(self: *Tween, mode: LoopMode) void { - self.loop_mode = mode; - } - - /// Start the tween. - pub fn start(self: *Tween) void { - self.state = .running; - self.elapsed_ns = 0; - } - - /// Reset to beginning. - pub fn reset(self: *Tween) void { - self.elapsed_ns = 0; - self.state = .idle; - } - - /// Update with delta time in nanoseconds. - pub fn update(self: *Tween, delta_ns: u64) void { - if (self.state != .running) return; - - self.elapsed_ns += delta_ns; - - if (self.elapsed_ns >= self.duration_ns) { - switch (self.loop_mode) { - .once => { - self.elapsed_ns = self.duration_ns; - self.state = .finished; - }, - .loop => { - self.elapsed_ns = self.elapsed_ns % self.duration_ns; - }, - .ping_pong => { - self.elapsed_ns = self.elapsed_ns % (self.duration_ns * 2); - }, - } - } - } - - /// Get the current interpolated value. - pub fn value(self: *const Tween) f64 { - if (self.duration_ns == 0) return self.end_val; - - var t: f64 = @as(f64, @floatFromInt(self.elapsed_ns)) / @as(f64, @floatFromInt(self.duration_ns)); - - // Ping-pong: reverse in second half - if (self.loop_mode == .ping_pong and t > 1.0) { - t = 2.0 - t; - } - - t = @max(0.0, @min(1.0, t)); - const eased = self.easing.apply(t); - return self.start_val + (self.end_val - self.start_val) * eased; - } - - /// Get value as integer. - pub fn intValue(self: *const Tween) i64 { - return @intFromFloat(self.value()); - } - - /// Check if finished (only relevant for .once mode). - pub fn isFinished(self: *const Tween) bool { - return self.state == .finished; - } - - /// Check if running. - pub fn isRunning(self: *const Tween) bool { - return self.state == .running; - } - - /// Get normalized progress [0, 1]. - pub fn progress(self: *const Tween) f64 { - if (self.duration_ns == 0) return 1.0; - return @min(1.0, @as(f64, @floatFromInt(self.elapsed_ns)) / @as(f64, @floatFromInt(self.duration_ns))); - } -}; - -/// Interpolate between two colors using a tween. -pub fn tweenColor(start: Color, end: Color, t: f64) Color { - return progress_mod.interpolateColor(start, end, @max(0.0, @min(1.0, t))); -} - -/// Convenience: lerp between two f64 values. -pub fn lerp(a: f64, b: f64, t: f64) f64 { - return a + (b - a) * @max(0.0, @min(1.0, t)); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig deleted file mode 100644 index f4e1dd9..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/async_task.zig +++ /dev/null @@ -1,108 +0,0 @@ -//! Async task runner for background work in ZigZag. -//! Spawns threads that execute functions and queue result messages. - -const std = @import("std"); - -/// Thread-safe result queue for async tasks. -pub fn AsyncRunner(comptime Msg: type) type { - return struct { - allocator: std.mem.Allocator, - results: ResultQueue, - next_id: u32 = 1, - - const Self = @This(); - const ResultQueue = std.array_list.Managed(?Msg); - - pub fn init(allocator: std.mem.Allocator) Self { - return .{ - .allocator = allocator, - .results = ResultQueue.init(allocator), - }; - } - - pub fn deinit(self: *Self) void { - self.results.deinit(); - } - - /// Spawn a background task. The function runs on a new thread and - /// its return value is queued as a message for the next frame. - pub fn spawn(self: *Self, func: *const fn () ?Msg) u32 { - const id = self.next_id; - self.next_id += 1; - - const ctx = self.allocator.create(SpawnContext) catch return 0; - ctx.* = .{ .func = func, .runner = self }; - - _ = std.Thread.spawn(.{}, runTask, .{ctx}) catch { - self.allocator.destroy(ctx); - return 0; - }; - - return id; - } - - /// Spawn with a context argument. - pub fn spawnWithArg(self: *Self, comptime ArgT: type, arg: ArgT, func: *const fn (ArgT) ?Msg) u32 { - const id = self.next_id; - self.next_id += 1; - - const Closure = struct { - arg_val: ArgT, - func_ptr: *const fn (ArgT) ?Msg, - runner_ptr: *Self, - - fn execute(closure: *@This()) void { - const result = closure.func_ptr(closure.arg_val); - if (result) |m| { - closure.runner_ptr.pushResult(m); - } - } - }; - - const closure = self.allocator.create(Closure) catch return 0; - closure.* = .{ .arg_val = arg, .func_ptr = func, .runner_ptr = self }; - - _ = std.Thread.spawn(.{}, struct { - fn run(c: *Closure) void { - c.execute(); - } - }.run, .{closure}) catch { - self.allocator.destroy(closure); - return 0; - }; - - return id; - } - - /// Poll for completed results. Returns messages from finished tasks. - /// Call this each frame to collect async results. - pub fn poll(self: *Self) []Msg { - if (self.results.items.len == 0) return &.{}; - - var msgs = std.array_list.Managed(Msg).init(self.allocator); - for (self.results.items) |maybe_msg| { - if (maybe_msg) |m| { - msgs.append(m) catch {}; - } - } - self.results.clearRetainingCapacity(); - return msgs.items; - } - - fn pushResult(self: *Self, m: Msg) void { - self.results.append(m) catch {}; - } - - const SpawnContext = struct { - func: *const fn () ?Msg, - runner: *Self, - }; - - fn runTask(ctx: *SpawnContext) void { - const result = ctx.func(); - if (result) |m| { - ctx.runner.pushResult(m); - } - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig deleted file mode 100644 index bb504aa..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/command.zig +++ /dev/null @@ -1,304 +0,0 @@ -//! Command system for the ZigZag TUI framework. -//! Commands represent side effects and actions to be performed. - -const std = @import("std"); - -/// Parameters for image rendering by file path. -pub const ImagePlacement = enum { - /// Use the current cursor position. - cursor, - /// Draw from top-left corner. - top_left, - /// Draw from top-center using width hint. - top_center, - /// Center using provided width/height cell hints. - center, -}; - -/// Preferred image protocol for rendering. -pub const ImageProtocol = enum { - /// Auto-select best available (Kitty > iTerm2 > Sixel). - auto, - /// Force Kitty graphics protocol. - kitty, - /// Force iTerm2 inline image protocol. - iterm2, - /// Force Sixel graphics protocol. - sixel, -}; - -/// Pixel format for in-memory image data. -pub const ImageFormat = enum(u16) { - rgb = 24, - rgba = 32, - png = 100, -}; - -/// Parameters for image rendering by file path. -pub const ImageFile = struct { - path: []const u8, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - placement: ImagePlacement = .top_left, - /// Optional absolute row (0-indexed). Overrides anchor row when provided. - row: ?u16 = null, - /// Optional absolute column (0-indexed). Overrides anchor column when provided. - col: ?u16 = null, - /// Signed row offset (in terminal cells) applied after anchor/absolute position. - row_offset: i16 = 0, - /// Signed column offset (in terminal cells) applied after anchor/absolute position. - col_offset: i16 = 0, - preserve_aspect_ratio: bool = true, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - /// Preferred protocol (default: auto-select). - protocol: ImageProtocol = .auto, - /// Z-index for layering (Kitty only). Negative = behind text. - z_index: ?i32 = null, - /// Enable unicode placeholders (Kitty only). Images participate in text reflow. - unicode_placeholder: bool = false, -}; - -/// Parameters for rendering in-memory image data. -pub const ImageData = struct { - /// Raw pixel data (RGB, RGBA, or PNG bytes). - data: []const u8, - /// Pixel format of the data. - format: ImageFormat = .png, - /// Pixel width of the image (required for RGB/RGBA). - pixel_width: ?u32 = null, - /// Pixel height of the image (required for RGB/RGBA). - pixel_height: ?u32 = null, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - placement: ImagePlacement = .top_left, - row: ?u16 = null, - col: ?u16 = null, - row_offset: i16 = 0, - col_offset: i16 = 0, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - protocol: ImageProtocol = .auto, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// Transmit an image to the terminal without displaying it (Kitty cache). -pub const CacheImage = struct { - /// File path or in-memory data source. - source: ImageSource, - /// Unique image ID for later reference. Required. - image_id: u32, - /// Pixel format (only for in-memory data). - format: ImageFormat = .png, - /// Pixel width (required for RGB/RGBA in-memory data). - pixel_width: ?u32 = null, - /// Pixel height (required for RGB/RGBA in-memory data). - pixel_height: ?u32 = null, - quiet: bool = true, -}; - -/// Source for an image: file path or in-memory bytes. -pub const ImageSource = union(enum) { - file: []const u8, - data: []const u8, -}; - -/// Display a previously cached image by ID (Kitty virtual placement). -pub const PlaceCachedImage = struct { - /// Image ID from a previous cache_image command. - image_id: u32, - placement_id: ?u32 = null, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - placement: ImagePlacement = .top_left, - row: ?u16 = null, - col: ?u16 = null, - row_offset: i16 = 0, - col_offset: i16 = 0, - move_cursor: bool = true, - quiet: bool = true, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// Delete a cached image or placement (Kitty). -pub const DeleteImage = union(enum) { - /// Delete all placements of a specific image ID. - by_id: u32, - /// Delete a specific placement of an image. - by_placement: struct { image_id: u32, placement_id: u32 }, - /// Delete all images and placements. - all, -}; - -/// Backward-compatible alias for existing Kitty-only APIs. -pub const KittyImageFile = ImageFile; - -/// Command type parameterized by the user's message type -pub fn Cmd(comptime Msg: type) type { - return union(enum) { - /// No operation - none, - - /// Quit the application - quit, - - /// Request a tick after the specified duration (nanoseconds) - tick: u64, - - /// Request repeating tick at interval (nanoseconds) - every: u64, - - /// Execute a batch of commands - batch: []const Cmd(Msg), - - /// Execute commands in sequence (wait for each to complete) - sequence: []const Cmd(Msg), - - /// Send a message to the update function - msg: Msg, - - /// Execute a custom function that produces a message - perform: *const fn () ?Msg, - - /// Suspend the program (Ctrl+Z behavior) - suspend_process, - - /// Runtime terminal commands - enable_mouse, - disable_mouse, - show_cursor, - hide_cursor, - enter_alt_screen, - exit_alt_screen, - set_title: []const u8, - - /// Print a line above the program output - println: []const u8, - - /// Draw an image file using the best available protocol (Kitty, iTerm2, Sixel) - image_file: ImageFile, - - /// Draw an image file via Kitty graphics protocol (no-op if unsupported) - kitty_image_file: KittyImageFile, - - /// Draw in-memory image data (RGB, RGBA, or PNG bytes) - image_data: ImageData, - - /// Transmit an image to the terminal cache without displaying (Kitty) - cache_image: CacheImage, - - /// Display a previously cached image (Kitty virtual placement) - place_cached_image: PlaceCachedImage, - - /// Delete a cached image or placement (Kitty) - delete_image: DeleteImage, - - const Self = @This(); - - /// Create a none command - pub fn none_cmd() Self { - return .none; - } - - /// Create a quit command - pub fn quit_cmd() Self { - return .quit; - } - - /// Request a tick after milliseconds - pub fn tickMs(ms: u64) Self { - return .{ .tick = ms * std.time.ns_per_ms }; - } - - /// Request a tick after seconds - pub fn tickSec(sec: u64) Self { - return .{ .tick = sec * std.time.ns_per_s }; - } - - /// Request a repeating tick every `ms` milliseconds - pub fn everyMs(ms: u64) Self { - return .{ .every = ms * std.time.ns_per_ms }; - } - - /// Request a repeating tick every `sec` seconds - pub fn everySec(sec: u64) Self { - return .{ .every = sec * std.time.ns_per_s }; - } - - /// Create a batch of commands - pub fn batchOf(cmds: []const Self) Self { - return .{ .batch = cmds }; - } - - /// Create a sequence of commands - pub fn sequenceOf(cmds: []const Self) Self { - return .{ .sequence = cmds }; - } - - /// Send a message - pub fn send(message: Msg) Self { - return .{ .msg = message }; - } - - /// Execute a function to get a message - pub fn performFn(func: *const fn () ?Msg) Self { - return .{ .perform = func }; - } - - /// Check if command is none - pub fn isNone(self: Self) bool { - return self == .none; - } - - /// Check if command is quit - pub fn isQuit(self: Self) bool { - return self == .quit; - } - }; -} - -/// Standard commands without message type -pub const StandardCmd = union(enum) { - none, - quit, - tick: u64, - set_title: []const u8, - enable_mouse, - disable_mouse, - show_cursor, - hide_cursor, - enter_alt_screen, - exit_alt_screen, - image_file: ImageFile, - kitty_image_file: KittyImageFile, - image_data: ImageData, - cache_image: CacheImage, - place_cached_image: PlaceCachedImage, - delete_image: DeleteImage, -}; - -/// Combine multiple commands into a batch -pub fn batch(comptime Msg: type, cmds: []const Cmd(Msg)) Cmd(Msg) { - return .{ .batch = cmds }; -} - -/// Combine multiple commands into a sequence -pub fn sequence(comptime Msg: type, cmds: []const Cmd(Msg)) Cmd(Msg) { - return .{ .sequence = cmds }; -} - -/// Create a tick command with millisecond duration -pub fn tick(comptime Msg: type, ms: u64) Cmd(Msg) { - return Cmd(Msg).tickMs(ms); -} - -/// Create a tick command that fires every frame -pub fn everyFrame(comptime Msg: type) Cmd(Msg) { - return Cmd(Msg).tickMs(16); // ~60fps -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig deleted file mode 100644 index 608fb53..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/context.zig +++ /dev/null @@ -1,382 +0,0 @@ -//! Runtime context for ZigZag applications. -//! Provides access to terminal state and resources. - -const std = @import("std"); -const terminal_mod = @import("../terminal/terminal.zig"); -const Terminal = terminal_mod.Terminal; -const ImageCapabilities = terminal_mod.ImageCapabilities; -const color_mod = @import("../style/color.zig"); -const unicode_mod = @import("../unicode.zig"); -const Logger = @import("log.zig").Logger; -const theme_mod = @import("../style/theme.zig"); - -/// Runtime context passed to init, update, and view functions -pub const Context = struct { - /// Allocator for temporary allocations (reset each frame) - allocator: std.mem.Allocator, - - /// Persistent allocator for model state (not reset between frames) - persistent_allocator: std.mem.Allocator, - - /// Process environment for env-driven detection (color, multiplexer, locale). - environ_map: *const std.process.Environ.Map, - - /// Asynchronous I/O facilities (file, network, time, sleep). - io: std.Io, - - /// Terminal width in columns - width: u16, - - /// Terminal height in rows - height: u16, - - /// Current frame number - frame: u64, - - /// Time since program start (nanoseconds) - elapsed: u64, - - /// Delta time since last frame (nanoseconds) - delta: u64, - - /// Whether the terminal supports true color - true_color: bool, - - /// Whether the terminal supports 256 colors - color_256: bool, - - /// Color profile of the terminal - color_profile: color_mod.ColorProfile, - - /// Whether the terminal has a dark background - is_dark_background: bool, - - /// Active Unicode width strategy for text measurement - unicode_width_strategy: unicode_mod.WidthStrategy, - - /// Whether DEC mode 2027 was successfully negotiated - terminal_mode_2027: bool, - - /// Whether kitty text sizing support was detected - kitty_text_sizing: bool, - - /// Active theme for the application - theme: theme_mod.Theme = theme_mod.Theme.fromPalette(theme_mod.Palette.default_dark), - - /// Access to internal state (for advanced use) - _terminal: ?*Terminal, - - /// Logger for debug output - _logger: ?*Logger = null, - - /// Log a debug message (writes to log file if configured) - pub fn log(self: *const Context, comptime fmt: []const u8, args: anytype) void { - if (self._logger) |logger| { - logger.log(fmt, args); - } - } - - pub fn init( - allocator: std.mem.Allocator, - persistent_allocator: std.mem.Allocator, - io: std.Io, - environ_map: *const std.process.Environ.Map, - ) Context { - const profile = color_mod.ColorProfile.detect(environ_map); - return .{ - .allocator = allocator, - .persistent_allocator = persistent_allocator, - .io = io, - .environ_map = environ_map, - .width = 80, - .height = 24, - .frame = 0, - .elapsed = 0, - .delta = 0, - .true_color = profile.supportsTrueColor(), - .color_256 = profile.supports256(), - .color_profile = profile, - .is_dark_background = color_mod.hasDarkBackground(environ_map), - .unicode_width_strategy = unicode_mod.getWidthStrategy(), - .terminal_mode_2027 = false, - .kitty_text_sizing = false, - ._terminal = null, - }; - } - - /// Set the active theme from a palette. - pub fn setTheme(self: *Context, p: theme_mod.Palette) void { - self.theme = theme_mod.Theme.fromPalette(p); - } - - /// Get the current palette. - pub fn getPalette(self: *const Context) theme_mod.Palette { - return self.theme.palette; - } - - /// Get the aspect ratio (width / height) - pub fn aspectRatio(self: *const Context) f32 { - if (self.height == 0) return 1.0; - return @as(f32, @floatFromInt(self.width)) / @as(f32, @floatFromInt(self.height)); - } - - /// Get center coordinates - pub fn center(self: *const Context) struct { x: u16, y: u16 } { - return .{ - .x = self.width / 2, - .y = self.height / 2, - }; - } - - /// Check if a position is within bounds - pub fn inBounds(self: *const Context, x: u16, y: u16) bool { - return x < self.width and y < self.height; - } - - /// Get elapsed time in seconds (floating point) - pub fn elapsedSec(self: *const Context) f64 { - return @as(f64, @floatFromInt(self.elapsed)) / @as(f64, @floatFromInt(std.time.ns_per_s)); - } - - /// Get delta time in seconds (floating point) - pub fn deltaSec(self: *const Context) f64 { - return @as(f64, @floatFromInt(self.delta)) / @as(f64, @floatFromInt(std.time.ns_per_s)); - } - - /// Get frames per second (based on delta) - pub fn fps(self: *const Context) f64 { - if (self.delta == 0) return 0.0; - return @as(f64, @floatFromInt(std.time.ns_per_s)) / @as(f64, @floatFromInt(self.delta)); - } - - /// Clamp a value to screen bounds - pub fn clampX(self: *const Context, x: i32) u16 { - if (x < 0) return 0; - if (x >= self.width) return self.width -| 1; - return @intCast(x); - } - - pub fn clampY(self: *const Context, y: i32) u16 { - if (y < 0) return 0; - if (y >= self.height) return self.height -| 1; - return @intCast(y); - } - - /// Returns whether Kitty graphics protocol is available. - pub fn supportsKittyGraphics(self: *const Context) bool { - if (self._terminal) |term| { - return term.supportsKittyGraphics(); - } - return false; - } - - /// Returns whether iTerm2 inline images are available. - pub fn supportsIterm2InlineImages(self: *const Context) bool { - if (self._terminal) |term| { - return term.supportsIterm2InlineImages(); - } - return false; - } - - /// Returns whether Sixel graphics are available. - pub fn supportsSixel(self: *const Context) bool { - if (self._terminal) |term| { - return term.supportsSixel(); - } - return false; - } - - /// Returns whether any inline image protocol is available. - pub fn supportsImages(self: *const Context) bool { - if (self._terminal) |term| { - return term.supportsImages(); - } - return false; - } - - /// Copy bytes to the system clipboard via OSC 52 using terminal defaults. - /// Returns false when clipboard output is unavailable or disabled. - pub fn setClipboard(self: *Context, bytes: []const u8) !bool { - if (self._terminal) |term| { - return term.setClipboard(bytes); - } - return false; - } - - /// Copy bytes to the system clipboard via OSC 52 with per-call overrides. - pub fn setClipboardWithOptions(self: *Context, bytes: []const u8, options: terminal_mod.Osc52WriteOptions) !bool { - if (self._terminal) |term| { - return term.setClipboardWithOptions(bytes, options); - } - return false; - } - - /// Query clipboard bytes via OSC 52 using terminal defaults. - /// Returns null when unavailable, blocked, or timed out. - pub fn getClipboard(self: *Context, allocator: std.mem.Allocator) !?[]u8 { - if (self._terminal) |term| { - return term.getClipboard(allocator); - } - return null; - } - - /// Query clipboard bytes via OSC 52 with per-call overrides. - /// Returns null when unavailable, blocked, or timed out. - pub fn getClipboardWithOptions(self: *Context, allocator: std.mem.Allocator, options: terminal_mod.Osc52ReadOptions) !?[]u8 { - if (self._terminal) |term| { - return term.getClipboardWithOptions(allocator, options); - } - return null; - } - - /// Draw a PNG image file via Kitty graphics protocol (`t=f`). - /// Returns false when unsupported or path is empty. - pub fn drawKittyImageFromFile(self: *Context, path: []const u8, options: Terminal.KittyImageFileOptions) !bool { - if (self._terminal) |term| { - return term.drawKittyImageFromFile(path, options); - } - return false; - } - - /// Draw in-memory image data via Kitty graphics protocol (`t=d`). - /// Returns false when unsupported or data is empty. - pub fn drawKittyImage(self: *Context, data: []const u8, options: Terminal.KittyImageOptions) !bool { - if (self._terminal) |term| { - return term.drawKittyImage(data, options); - } - return false; - } - - /// Transmit an image to the Kitty cache without displaying. - /// Use `placeCachedImage` later to display by ID. - pub fn transmitKittyImage(self: *Context, payload: []const u8, options: Terminal.KittyTransmitOptions) !bool { - if (self._terminal) |term| { - return term.transmitKittyImage(payload, options); - } - return false; - } - - /// Transmit a file to the Kitty cache without displaying. - pub fn transmitKittyImageFromFile(self: *Context, path: []const u8, options: Terminal.KittyTransmitOptions) !bool { - if (self._terminal) |term| { - return term.transmitKittyImageFromFile(path, options); - } - return false; - } - - /// Display a previously cached Kitty image by ID. - pub fn placeKittyImage(self: *Context, options: Terminal.KittyPlaceOptions) !bool { - if (self._terminal) |term| { - return term.placeKittyImage(options); - } - return false; - } - - /// Delete cached Kitty images/placements. - pub fn deleteKittyImage(self: *Context, target: Terminal.KittyDeleteTarget) !bool { - if (self._terminal) |term| { - return term.deleteKittyImage(target); - } - return false; - } - - /// Draw a Sixel image from file (or convert via `img2sixel` when available). - /// Returns false when unsupported or path is empty. - pub fn drawSixelFromFile(self: *Context, path: []const u8, options: Terminal.SixelImageFileOptions) !bool { - if (self._terminal) |term| { - return term.drawSixelFromFile(path, options); - } - return false; - } - - /// Draw an image file using the best available protocol. - /// Returns false when unsupported or path is empty. - pub fn drawImageFromFile(self: *Context, path: []const u8, options: Terminal.ImageFileOptions) !bool { - if (self._terminal) |term| { - return term.drawImageFromFile(path, options); - } - return false; - } - - /// Draw an image file using a specific protocol. - pub fn drawImageFromFileWithProtocol(self: *Context, path: []const u8, options: Terminal.ImageFileOptions, protocol: Terminal.ImageProtocol) !bool { - if (self._terminal) |term| { - return term.drawImageFromFileWithProtocol(path, options, protocol); - } - return false; - } - - /// Draw in-memory image data using the best available protocol. - pub fn drawImageData(self: *Context, data: []const u8, options: Terminal.ImageDataOptions) !bool { - if (self._terminal) |term| { - return term.drawImageData(data, options); - } - return false; - } - - /// Draw in-memory image data using a specific protocol. - pub fn drawImageDataWithProtocol(self: *Context, data: []const u8, options: Terminal.ImageDataOptions, protocol: Terminal.ImageProtocol) !bool { - if (self._terminal) |term| { - return term.drawImageDataWithProtocol(data, options, protocol); - } - return false; - } - - /// Draw in-memory image data via iTerm2 inline image protocol. - pub fn drawIterm2ImageData(self: *Context, data: []const u8, options: Terminal.Iterm2ImageDataOptions) !bool { - if (self._terminal) |term| { - return term.drawIterm2ImageData(data, options); - } - return false; - } - - /// Get the current image capabilities of the terminal. - pub fn getImageCapabilities(self: *const Context) ImageCapabilities { - if (self._terminal) |term| { - return term.getImageCapabilities(); - } - return .{}; - } -}; - -/// Options that can be modified during runtime -pub const Options = struct { - /// Target frame rate (frames per second) - fps: u32 = 60, - - /// Enable mouse tracking - mouse: bool = false, - - /// Show cursor - cursor: bool = false, - - /// Use alternate screen buffer - alt_screen: bool = true, - - /// Enable bracketed paste mode - bracketed_paste: bool = true, - - /// Window title - title: ?[]const u8 = null, - - /// Custom input file (default: stdin) - input: ?std.Io.File = null, - - /// Custom output file (default: stdout) - output: ?std.Io.File = null, - - /// Log file path for debug output - log_file: ?[]const u8 = null, - - /// Enable Kitty keyboard protocol - kitty_keyboard: bool = false, - - /// OSC 52 clipboard configuration - osc52: terminal_mod.Osc52Config = .{}, - - /// Force Unicode width strategy (`null` = auto-detect) - unicode_width_strategy: ?unicode_mod.WidthStrategy = null, - - /// Enable suspend/resume with Ctrl+Z - suspend_enabled: bool = true, -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig deleted file mode 100644 index 1167c9b..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/dev_console.zig +++ /dev/null @@ -1,342 +0,0 @@ -//! Dev console — log streamer to a separate viewer. -//! -//! Solves a fundamental TUI debugging problem: stdout is owned by the -//! renderer, so `std.debug.print` would garble the screen. This module -//! routes structured log events to a separate sink so a developer can run -//! the TUI in one terminal and `tail -f` (or `nc`) the log stream in -//! another. -//! -//! Sinks supported: -//! -//! * `.file` — append to a log file. Pair with `tail -f path.log`. -//! * `.tcp` — listen on a TCP port. Pair with `nc localhost 9999`. -//! * `.stderr` — write to stderr. Useful when stderr is redirected. -//! * `.multi` — fan-out to several sinks at once. -//! -//! Each event has a level (trace/debug/info/warn/err) and a timestamp. -//! The console is safe to call from any thread; writes are mutex-guarded. - -const std = @import("std"); -const Writer = std.Io.Writer; - -pub const Level = enum { - trace, - debug, - info, - warn, - err, - - pub fn label(self: Level) []const u8 { - return switch (self) { - .trace => "TRACE", - .debug => "DEBUG", - .info => "INFO ", - .warn => "WARN ", - .err => "ERROR", - }; - } - - pub fn rank(self: Level) u8 { - return switch (self) { - .trace => 0, - .debug => 1, - .info => 2, - .warn => 3, - .err => 4, - }; - } -}; - -pub const SinkConfig = union(enum) { - /// Append-mode log file at this path. - file: []const u8, - /// TCP listener on the given host:port. The dev console writes to *all* - /// currently-connected clients; new connections receive future events. - tcp: struct { - host: []const u8 = "127.0.0.1", - port: u16, - }, - /// Write to stderr (file descriptor 2). - stderr, -}; - -pub const DevConsole = struct { - allocator: std.mem.Allocator, - io: std.Io, - sinks: std.array_list.Managed(Sink), - mutex: std.Io.Mutex, - /// Filter: events below this level are dropped. - min_level: Level, - /// Whether to prefix each line with a timestamp. - show_timestamps: bool, - - const Sink = union(enum) { - file: struct { - file: std.Io.File, - /// Append cursor. Only advanced after a successful flush — a failed - /// write leaves it pointing at the truncated record's start, so the - /// next entry overwrites the partial one. Not safe under concurrent - /// writers to the same file. - end_pos: u64, - }, - tcp: *TcpSink, - stderr, - }; - - const TcpSink = struct { - io: std.Io, - allocator: std.mem.Allocator, - listen_address: std.Io.net.IpAddress, - server: std.Io.net.Server, - thread: std.Thread, - connections: std.array_list.Managed(std.Io.net.Stream), - mutex: std.Io.Mutex, - /// Set to true to signal the accept thread to stop. - stopping: std.atomic.Value(bool), - }; - - pub fn init(allocator: std.mem.Allocator, io: std.Io) DevConsole { - return .{ - .allocator = allocator, - .io = io, - .sinks = std.array_list.Managed(Sink).init(allocator), - .mutex = .init, - .min_level = .trace, - .show_timestamps = true, - }; - } - - pub fn deinit(self: *DevConsole) void { - const io = self.io; - for (self.sinks.items) |*sink| { - switch (sink.*) { - .file => |*f| f.file.close(io), - .tcp => |tcp| { - tcp.stopping.store(true, .seq_cst); - // Wake the listener by connecting once. - if (tcp.listen_address.connect(io, .{ .mode = .stream })) |conn| { - conn.close(io); - } else |_| {} - tcp.thread.join(); - tcp.server.deinit(io); - for (tcp.connections.items) |*c| c.close(io); - tcp.connections.deinit(); - self.allocator.destroy(tcp); - }, - .stderr => {}, - } - } - self.sinks.deinit(); - } - - pub fn setMinLevel(self: *DevConsole, lvl: Level) void { - self.min_level = lvl; - } - - pub fn addSink(self: *DevConsole, cfg: SinkConfig) !void { - const io = self.io; - switch (cfg) { - .file => |path| { - const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = false }); - const end_pos = std.Io.File.length(file, io) catch 0; - try self.sinks.append(.{ .file = .{ .file = file, .end_pos = end_pos } }); - }, - .stderr => { - try self.sinks.append(.stderr); - }, - .tcp => |t| { - const addr = try std.Io.net.IpAddress.parse(t.host, t.port); - var server = try addr.listen(io, .{ .reuse_address = true }); - errdefer server.deinit(io); - - const tcp_ptr = try self.allocator.create(TcpSink); - errdefer self.allocator.destroy(tcp_ptr); - tcp_ptr.* = .{ - .io = io, - .allocator = self.allocator, - .listen_address = addr, - .server = server, - .thread = undefined, - .connections = std.array_list.Managed(std.Io.net.Stream).init(self.allocator), - .mutex = .init, - .stopping = std.atomic.Value(bool).init(false), - }; - - tcp_ptr.thread = try std.Thread.spawn(.{}, acceptLoop, .{tcp_ptr}); - try self.sinks.append(.{ .tcp = tcp_ptr }); - }, - } - } - - fn acceptLoop(tcp: *TcpSink) void { - const io = tcp.io; - while (!tcp.stopping.load(.seq_cst)) { - const conn = tcp.server.accept(io) catch break; - if (tcp.stopping.load(.seq_cst)) { - conn.close(io); - break; - } - tcp.mutex.lockUncancelable(io); - tcp.connections.append(conn) catch { - conn.close(io); - tcp.mutex.unlock(io); - continue; - }; - tcp.mutex.unlock(io); - } - } - - pub fn log(self: *DevConsole, level: Level, comptime fmt: []const u8, args: anytype) void { - if (level.rank() < self.min_level.rank()) return; - - // Build the line in a stack buffer (or heap-fall-back) once. - var stack_buf: [4096]u8 = undefined; - const line = self.format(stack_buf[0..], level, fmt, args) catch return; - - const io = self.io; - self.mutex.lockUncancelable(io); - defer self.mutex.unlock(io); - - for (self.sinks.items) |*sink| { - switch (sink.*) { - .file => |*f| { - var write_buf: [1024]u8 = undefined; - var w = f.file.writer(io, &write_buf); - w.seekTo(f.end_pos) catch continue; - w.interface.writeAll(line) catch continue; - w.interface.flush() catch continue; - f.end_pos = w.logicalPos(); - }, - .stderr => { - std.debug.print("{s}", .{line}); - }, - .tcp => |tcp| { - var keep = std.array_list.Managed(std.Io.net.Stream).init(self.allocator); - defer keep.deinit(); - - tcp.mutex.lockUncancelable(io); - defer tcp.mutex.unlock(io); - for (tcp.connections.items) |conn| { - var write_buf: [1024]u8 = undefined; - var w = conn.writer(io, &write_buf); - if (w.interface.writeAll(line)) |_| { - if (w.interface.flush()) |_| { - keep.append(conn) catch continue; - } else |_| {} - } else |_| {} - } - // Drop dead connections. - if (keep.items.len != tcp.connections.items.len) { - for (tcp.connections.items) |conn| { - var still_alive = false; - for (keep.items) |k| { - if (k.socket.handle == conn.socket.handle) { - still_alive = true; - break; - } - } - if (!still_alive) conn.close(io); - } - tcp.connections.clearRetainingCapacity(); - tcp.connections.appendSlice(keep.items) catch {}; - } - }, - } - } - } - - fn format(self: *const DevConsole, buf: []u8, level: Level, comptime fmt: []const u8, args: anytype) ![]u8 { - var writer: Writer = .fixed(buf); - if (self.show_timestamps) { - const now = std.Io.Timestamp.now(self.io, .real).toSeconds(); - const epoch = std.time.epoch.EpochSeconds{ .secs = @intCast(now) }; - const day = epoch.getDaySeconds(); - try writer.print("[{d:0>2}:{d:0>2}:{d:0>2}] ", .{ - day.getHoursIntoDay(), - day.getMinutesIntoHour(), - day.getSecondsIntoMinute(), - }); - } - try writer.print("{s} ", .{level.label()}); - try writer.print(fmt, args); - try writer.writeByte('\n'); - return writer.buffered(); - } - - // Convenience wrappers. - pub fn trace(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { - self.log(.trace, fmt, args); - } - pub fn debug(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { - self.log(.debug, fmt, args); - } - pub fn info(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { - self.log(.info, fmt, args); - } - pub fn warn(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { - self.log(.warn, fmt, args); - } - pub fn err(self: *DevConsole, comptime fmt: []const u8, args: anytype) void { - self.log(.err, fmt, args); - } -}; - -// ── Tests ────────────────────────────────────────────────────────────── - -const testing = std.testing; - -test "file sink writes formatted log lines" { - const allocator = testing.allocator; - const io = testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - - var orig = try std.Io.Dir.cwd().openDir(io, ".", .{}); - defer orig.close(io); - try std.process.setCurrentDir(io, tmp.dir); - defer std.process.setCurrentDir(io, orig) catch {}; - - var console = DevConsole.init(allocator, io); - defer console.deinit(); - try console.addSink(.{ .file = "console.log" }); - - console.info("hello {s}", .{"world"}); - console.warn("careful", .{}); - - var buf: [4096]u8 = undefined; - const contents = try std.Io.Dir.cwd().readFile(io, "console.log", &buf); - - try testing.expect(std.mem.indexOf(u8, contents, "hello world") != null); - try testing.expect(std.mem.indexOf(u8, contents, "INFO") != null); - try testing.expect(std.mem.indexOf(u8, contents, "WARN") != null); -} - -test "min level filter" { - const allocator = testing.allocator; - const io = testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - - var orig = try std.Io.Dir.cwd().openDir(io, ".", .{}); - defer orig.close(io); - try std.process.setCurrentDir(io, tmp.dir); - defer std.process.setCurrentDir(io, orig) catch {}; - - var console = DevConsole.init(allocator, io); - defer console.deinit(); - try console.addSink(.{ .file = "filtered.log" }); - console.setMinLevel(.warn); - - console.debug("hidden", .{}); - console.warn("visible", .{}); - - var buf: [4096]u8 = undefined; - const contents = try std.Io.Dir.cwd().readFile(io, "filtered.log", &buf); - try testing.expect(std.mem.indexOf(u8, contents, "hidden") == null); - try testing.expect(std.mem.indexOf(u8, contents, "visible") != null); -} - -test "level rank ordering" { - try testing.expect(Level.trace.rank() < Level.err.rank()); - try testing.expect(Level.warn.rank() < Level.err.rank()); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig deleted file mode 100644 index 296e227..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/fuzzy.zig +++ /dev/null @@ -1,171 +0,0 @@ -//! 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/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig deleted file mode 100644 index 3c2b607..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/log.zig +++ /dev/null @@ -1,60 +0,0 @@ -//! Debug file logging for ZigZag applications. -//! Since stdout is owned by the renderer, this provides file-based logging. - -const std = @import("std"); - -/// Logger that writes timestamped messages to a file -pub const Logger = struct { - io: std.Io, - file: std.Io.File, - /// Append cursor. Only advanced after a successful flush — a failed write - /// leaves it pointing at where the truncated record started, so the next - /// log line will overwrite the partial one. Acceptable for a debug logger; - /// not safe under concurrent writers to the same file. - end_pos: u64, - mutex: std.Io.Mutex, - - /// Initialize a logger that writes to the given file path - pub fn init(io: std.Io, path: []const u8) !Logger { - const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = false }); - // Capture current length so subsequent writes append. - const end_pos = std.Io.File.length(file, io) catch 0; - return .{ - .io = io, - .file = file, - .end_pos = end_pos, - .mutex = .init, - }; - } - - /// Close the log file - pub fn deinit(self: *Logger) void { - self.file.close(self.io); - } - - /// Write a log message with timestamp prefix - pub fn log(self: *Logger, comptime fmt: []const u8, args: anytype) void { - self.mutex.lockUncancelable(self.io); - defer self.mutex.unlock(self.io); - - var buf: [1024]u8 = undefined; - var w = self.file.writer(self.io, &buf); - w.seekTo(self.end_pos) catch return; - - const now = std.Io.Timestamp.now(self.io, .real).toSeconds(); - const epoch_seconds = std.time.epoch.EpochSeconds{ .secs = @intCast(now) }; - const day_seconds = epoch_seconds.getDaySeconds(); - - w.interface.print("[{d:0>2}:{d:0>2}:{d:0>2}] ", .{ - day_seconds.getHoursIntoDay(), - day_seconds.getMinutesIntoHour(), - day_seconds.getSecondsIntoMinute(), - }) catch return; - - w.interface.print(fmt, args) catch return; - w.interface.writeByte('\n') catch return; - w.interface.flush() catch return; - - self.end_pos = w.logicalPos(); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig deleted file mode 100644 index e230a42..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/message.zig +++ /dev/null @@ -1,90 +0,0 @@ -//! Message types for the ZigZag TUI framework. -//! Messages represent events that can occur in the application. - -const std = @import("std"); -const keyboard = @import("../input/keyboard.zig"); -const mouse = @import("../input/mouse.zig"); - -/// Key event message -pub const Key = keyboard.KeyEvent; - -/// Mouse event message -pub const Mouse = mouse.MouseEvent; - -/// Window size change message -pub const WindowSize = struct { - width: u16, - height: u16, -}; - -/// Tick message for timer-based updates -pub const Tick = struct { - /// Monotonic timestamp in nanoseconds since program start. - timestamp: i64, - delta: u64, // nanoseconds since last tick -}; - -/// Focus change message -pub const Focus = enum { - gained, - lost, -}; - -/// Batch of messages -pub const Batch = struct { - messages: []const SystemMsg, -}; - -/// System messages that the framework generates -pub const SystemMsg = union(enum) { - /// Keyboard input - key: Key, - /// Mouse input - mouse: Mouse, - /// Window was resized - window_size: WindowSize, - /// Timer tick - tick: Tick, - /// Focus change - focus: Focus, - /// Batch of messages - batch: Batch, - /// No message - none, - - pub fn isQuit(self: SystemMsg) bool { - return switch (self) { - .key => |k| k.key == .{ .char = 'c' } and k.modifiers.ctrl, - else => false, - }; - } -}; - -/// Convert a key to a character if possible -pub fn keyToChar(key: Key) ?u21 { - return key.key.toChar(); -} - -/// Check if a key matches a specific character -pub fn isChar(key: Key, c: u21) bool { - return switch (key.key) { - .char => |ch| ch == c and !key.modifiers.any(), - else => false, - }; -} - -/// Check if a key is a specific character with ctrl modifier -pub fn isCtrl(key: Key, c: u21) bool { - return switch (key.key) { - .char => |ch| ch == c and key.modifiers.ctrl and !key.modifiers.alt and !key.modifiers.shift, - else => false, - }; -} - -/// Check if a key is a specific character with alt modifier -pub fn isAlt(key: Key, c: u21) bool { - return switch (key.key) { - .char => |ch| ch == c and key.modifiers.alt and !key.modifiers.ctrl and !key.modifiers.shift, - else => false, - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig deleted file mode 100644 index 7195d34..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/program.zig +++ /dev/null @@ -1,833 +0,0 @@ -//! Program runtime for the ZigZag TUI framework. -//! Implements the Model-Update-View pattern with an event loop. - -const std = @import("std"); -const builtin = @import("builtin"); -const Terminal = @import("../terminal/terminal.zig").Terminal; -const ansi = @import("../terminal/ansi.zig"); -const keyboard = @import("../input/keyboard.zig"); -const Context = @import("context.zig").Context; -const Options = @import("context.zig").Options; -const message = @import("message.zig"); -const command = @import("command.zig"); -const Logger = @import("log.zig").Logger; -const unicode = @import("../unicode.zig"); - -pub const Cmd = command.Cmd; -pub const Msg = message; - -const PendingImage = union(enum) { - auto: command.ImageFile, - kitty: command.KittyImageFile, - data: command.ImageData, - place_cached: command.PlaceCachedImage, -}; - -/// Program runtime that manages the application lifecycle -pub fn Program(comptime Model: type) type { - // Ensure Model has required declarations - comptime { - if (!@hasDecl(Model, "Msg")) { - @compileError("Model must have a 'Msg' type declaration"); - } - if (!@hasDecl(Model, "init")) { - @compileError("Model must have an 'init' function"); - } - if (!@hasDecl(Model, "update")) { - @compileError("Model must have an 'update' function"); - } - if (!@hasDecl(Model, "view")) { - @compileError("Model must have a 'view' function"); - } - } - - const UserMsg = Model.Msg; - const UserCmd = Cmd(UserMsg); - - return struct { - allocator: std.mem.Allocator, - io: std.Io, - environ_map: *const std.process.Environ.Map, - arena: std.heap.ArenaAllocator, - model: Model, - terminal: ?Terminal, - context: Context, - options: Options, - running: bool, - /// Boot-clock epoch from which `last_frame_time` and `context.elapsed` are measured. - /// `.boot` includes time the system was suspended, giving a monotonic reading - /// without gaps on resume. - clock_epoch: std.Io.Clock.Timestamp, - last_frame_time: u64, - pending_tick: ?u64, - every_interval: ?u64, - last_every_tick: u64, - last_view_hash: u64, - last_line_count: usize, - pending_image: ?PendingImage, - logger: ?Logger, - - /// Message filter function - filter: ?*const fn (UserMsg) ?UserMsg, - - const Self = @This(); - - /// Initialize the program - pub fn init( - allocator: std.mem.Allocator, - io: std.Io, - environ_map: *const std.process.Environ.Map, - ) !Self { - return initWithOptions(allocator, io, environ_map, .{}); - } - - /// Initialize with custom options - pub fn initWithOptions( - allocator: std.mem.Allocator, - io: std.Io, - environ_map: *const std.process.Environ.Map, - options: Options, - ) !Self { - const arena = std.heap.ArenaAllocator.init(allocator); - const clock_epoch = std.Io.Clock.Timestamp.now(io, .boot); - const self = Self{ - .allocator = allocator, - .io = io, - .environ_map = environ_map, - .arena = arena, - .model = undefined, - .terminal = null, - // `self` is returned by value, so don't capture an arena allocator here. - // It would point at this function's stack copy and dangle after return. - .context = Context.init(allocator, allocator, io, environ_map), - .options = options, - .running = false, - .clock_epoch = clock_epoch, - .last_frame_time = 0, - .pending_tick = null, - .every_interval = null, - .last_every_tick = 0, - .last_view_hash = 0, - .last_line_count = 0, - .pending_image = null, - .logger = null, - .filter = null, - }; - - return self; - } - - /// Clean up resources - pub fn deinit(self: *Self) void { - if (self.terminal) |*term| { - term.deinit(); - } - if (self.logger) |*l| { - l.deinit(); - } - self.arena.deinit(); - - // Call model's deinit if it exists - if (@hasDecl(Model, "deinit")) { - self.model.deinit(); - } - } - - /// Set a message filter function - pub fn setFilter(self: *Self, f: ?*const fn (UserMsg) ?UserMsg) void { - self.filter = f; - } - - /// Run the program with the built-in event loop. - /// For custom event loops, use `start()` + `tick()` instead. - pub fn run(self: *Self) !void { - try self.start(); - - // Main event loop - while (self.running) { - try self.tick(); - } - } - - /// Initialize the terminal and model without entering the event loop. - /// After calling this, drive the program manually by calling `tick()` - /// in your own loop. Check `isRunning()` to know when to stop. - /// - /// Example: - /// ``` - /// try program.start(); - /// while (program.isRunning()) { - /// try program.tick(); - /// // ... do other work between frames ... - /// } - /// ``` - pub fn start(self: *Self) !void { - // Initialize logger if configured - if (self.options.log_file) |log_path| { - self.logger = Logger.init(self.io, log_path) catch null; - if (self.logger != null) { - self.context._logger = &self.logger.?; - } - } - - // Initialize terminal - self.terminal = try Terminal.init(self.io, self.environ_map, .{ - .alt_screen = self.options.alt_screen, - .hide_cursor = !self.options.cursor, - .mouse = self.options.mouse, - .bracketed_paste = self.options.bracketed_paste, - .input = self.options.input, - .output = self.options.output, - .kitty_keyboard = self.options.kitty_keyboard, - .osc52 = self.options.osc52, - }); - - // Set title if provided - if (self.options.title) |title| { - try self.terminal.?.setTitle(title); - } - - // Get initial size - const size = try self.terminal.?.getSize(); - self.context.width = size.cols; - self.context.height = size.rows; - self.context._terminal = &self.terminal.?; - - const width_caps = self.terminal.?.getUnicodeWidthCapabilities(); - const effective_width_strategy = self.resolveUnicodeWidthStrategy(width_caps.strategy); - self.context.unicode_width_strategy = effective_width_strategy; - self.context.terminal_mode_2027 = width_caps.mode_2027; - self.context.kitty_text_sizing = width_caps.kitty_text_sizing; - unicode.setWidthStrategy(effective_width_strategy); - - self.clock_epoch = std.Io.Clock.Timestamp.now(self.io, .boot); - self.last_frame_time = 0; - self.context.elapsed = 0; - self.context.delta = 0; - self.context.frame = 0; - - self.resetFrameAllocator(); - - // Initialize the model - const init_cmd = self.model.init(&self.context); - try self.processCommand(init_cmd); - - self.running = true; - } - - /// Returns true if the program is still running. - pub fn isRunning(self: *const Self) bool { - return self.running; - } - - /// Execute a single frame: poll input, process events, render. - pub fn tick(self: *Self) !void { - const now = self.elapsedNs(); - const delta = now - self.last_frame_time; - - // Enforce framerate limit - const min_frame_time_ns: u64 = if (self.options.fps > 0) - @divFloor(std.time.ns_per_s, self.options.fps) - else - 16_666_666; // ~60fps default - - if (delta < min_frame_time_ns) { - sleepNs(self.io, min_frame_time_ns - delta); - } - - const frame_time = self.elapsedNs(); - const actual_delta = frame_time - self.last_frame_time; - self.last_frame_time = frame_time; - - self.context.delta = actual_delta; - self.context.elapsed = frame_time; - self.context.frame += 1; - - self.resetFrameAllocator(); - - // Check for resize - if (self.terminal.?.checkResize()) { - const size = try self.terminal.?.getSize(); - self.context.width = size.cols; - self.context.height = size.rows; - - // Only send window_size message if the user model supports it - if (@hasField(UserMsg, "window_size")) { - const cmd = self.dispatchToModel(.{ .window_size = .{ - .width = size.cols, - .height = size.rows, - } }); - try self.processCommand(cmd); - } - } - - // Read input - var input_buf: [256]u8 = undefined; - const bytes_read = try self.terminal.?.readInput(&input_buf, 16); - - if (bytes_read > 0) { - const events = try keyboard.parseAll(self.context.allocator, input_buf[0..bytes_read]); - for (events) |event| { - const user_cmd = switch (event) { - .key => |k| self.processKeyEvent(k), - .mouse => |m| self.processMouseEvent(m), - .none => null, - }; - if (user_cmd) |cmd| { - try self.processCommand(cmd); - } - } - } - - // Handle pending tick - if (self.pending_tick) |tick_ns| { - if (self.context.elapsed >= tick_ns) { - self.pending_tick = null; - // Deliver tick to user's update if Model.Msg has a tick variant - if (@hasField(UserMsg, "tick")) { - const user_msg = UserMsg{ .tick = .{ - .timestamp = @intCast(frame_time), - .delta = actual_delta, - } }; - const cmd = self.dispatchToModel(user_msg); - try self.processCommand(cmd); - } - } - } - - // Handle repeating tick - if (self.every_interval) |interval| { - if (self.context.elapsed - self.last_every_tick >= interval) { - self.last_every_tick = self.context.elapsed; - if (@hasField(UserMsg, "tick")) { - const user_msg = UserMsg{ .tick = .{ - .timestamp = @intCast(frame_time), - .delta = actual_delta, - } }; - const cmd = self.dispatchToModel(user_msg); - try self.processCommand(cmd); - } - } - } - - // Render - try self.render(); - try self.flushPendingImage(); - } - - /// Dispatch a message to the model, applying the filter if set - fn dispatchToModel(self: *Self, user_msg: UserMsg) UserCmd { - if (self.filter) |f| { - if (f(user_msg)) |filtered_msg| { - return self.model.update(filtered_msg, &self.context); - } - return .none; - } - return self.model.update(user_msg, &self.context); - } - - fn processKeyEvent(self: *Self, key: keyboard.KeyEvent) ?UserCmd { - // Check for Ctrl+C to quit - if (key.modifiers.ctrl) { - switch (key.key) { - .char => |c| { - if (c == 'c') { - self.running = false; - return null; - } - // Handle Ctrl+Z for suspend - if (c == 'z' and self.options.suspend_enabled) { - self.performSuspend(); - return null; - } - }, - else => {}, - } - } - - // Handle paste events - if (key.key == .paste) { - if (@hasField(UserMsg, "paste")) { - const user_msg = UserMsg{ .paste = key.key.paste }; - return self.dispatchToModel(user_msg); - } - // If model doesn't handle paste, send as individual key events - if (@hasField(UserMsg, "key")) { - const user_msg = UserMsg{ .key = key }; - return self.dispatchToModel(user_msg); - } - return null; - } - - // Convert to user message if Model.Msg has a key variant - if (@hasField(UserMsg, "key")) { - const user_msg = UserMsg{ .key = key }; - return self.dispatchToModel(user_msg); - } - - return null; - } - - fn resolveUnicodeWidthStrategy(self: *const Self, detected: unicode.WidthStrategy) unicode.WidthStrategy { - if (self.options.unicode_width_strategy) |forced| { - return forced; - } - if (envUnicodeWidthOverride(self.environ_map)) |from_env| { - return from_env; - } - return detected; - } - - fn envUnicodeWidthOverride(environ_map: *const std.process.Environ.Map) ?unicode.WidthStrategy { - const raw = environ_map.get("ZZ_UNICODE_WIDTH") orelse return null; - if (std.ascii.eqlIgnoreCase(raw, "unicode")) return .unicode; - if (std.ascii.eqlIgnoreCase(raw, "legacy")) return .legacy_wcwidth; - if (std.ascii.eqlIgnoreCase(raw, "auto")) return null; - return null; - } - - fn processMouseEvent(self: *Self, mouse_event: keyboard.MouseEvent) ?UserCmd { - if (@hasField(UserMsg, "mouse")) { - const user_msg = UserMsg{ .mouse = mouse_event }; - return self.dispatchToModel(user_msg); - } - - return null; - } - - /// Perform suspend (Ctrl+Z) — POSIX only - fn performSuspend(self: *Self) void { - if (builtin.os.tag == .windows) return; - - // Cleanup terminal - if (self.terminal) |*term| { - term.cleanup(); - } - - // Raise SIGTSTP to suspend process - if (builtin.os.tag != .windows) { - const posix = std.posix; - _ = posix.raise(posix.SIG.TSTP) catch {}; - } - - // When we resume (after `fg`), re-setup terminal - if (self.terminal) |*term| { - term.setup() catch {}; - } - - // Avoid a large post-resume frame delta. - self.last_frame_time = self.elapsedNs(); - - // Force re-render - self.last_view_hash = 0; - - // Dispatch resumed message if model supports it - if (@hasField(UserMsg, "resumed")) { - const cmd = self.dispatchToModel(.{ .resumed = {} }); - self.processCommand(cmd) catch {}; - } - } - - fn processCommand(self: *Self, cmd: UserCmd) !void { - switch (cmd) { - .none => {}, - .quit => { - self.running = false; - }, - .tick => |ns| { - self.pending_tick = self.context.elapsed + ns; - }, - .every => |ns| { - self.every_interval = ns; - self.last_every_tick = self.context.elapsed; - }, - .batch => |cmds| { - for (cmds) |c| { - try self.processCommand(c); - } - }, - .sequence => |cmds| { - for (cmds) |c| { - try self.processCommand(c); - } - }, - .msg => |m| { - const new_cmd = self.dispatchToModel(m); - try self.processCommand(new_cmd); - }, - .perform => |func| { - if (func()) |m| { - const new_cmd = self.dispatchToModel(m); - try self.processCommand(new_cmd); - } - }, - .suspend_process => { - self.performSuspend(); - }, - .enable_mouse => { - if (self.terminal) |*term| { - try term.enableMouse(); - } - }, - .disable_mouse => { - if (self.terminal) |*term| { - try term.disableMouse(); - } - }, - .show_cursor => { - if (self.terminal) |*term| { - const writer = term.writer(); - try writer.writeAll(ansi.cursor_show); - try term.flush(); - } - }, - .hide_cursor => { - if (self.terminal) |*term| { - const writer = term.writer(); - try writer.writeAll(ansi.cursor_hide); - try term.flush(); - } - }, - .enter_alt_screen => { - if (self.terminal) |*term| { - const writer = term.writer(); - try writer.writeAll(ansi.alt_screen_enter); - try term.flush(); - } - }, - .exit_alt_screen => { - if (self.terminal) |*term| { - const writer = term.writer(); - try writer.writeAll(ansi.alt_screen_exit); - try term.flush(); - } - }, - .set_title => |title| { - if (self.terminal) |*term| { - try term.setTitle(title); - } - }, - .println => |line| { - if (self.terminal) |*term| { - const writer = term.writer(); - try writer.writeAll(ansi.cursor_save); - try writer.writeAll(ansi.cursor_home); - try writer.writeAll(line); - try writer.writeAll("\n"); - try writer.writeAll(ansi.cursor_restore); - try term.flush(); - } - }, - .image_file => |image| { - self.pending_image = .{ .auto = image }; - }, - .kitty_image_file => |image| { - self.pending_image = .{ .kitty = image }; - }, - .image_data => |image| { - self.pending_image = .{ .data = image }; - }, - .cache_image => |cache| { - if (self.terminal) |*term| { - switch (cache.source) { - .file => |path| { - _ = term.transmitKittyImageFromFile(path, .{ - .image_id = cache.image_id, - .format = @enumFromInt(@intFromEnum(cache.format)), - .quiet = cache.quiet, - .pixel_width = cache.pixel_width, - .pixel_height = cache.pixel_height, - }) catch {}; - }, - .data => |data| { - _ = term.transmitKittyImage(data, .{ - .image_id = cache.image_id, - .format = @enumFromInt(@intFromEnum(cache.format)), - .quiet = cache.quiet, - .pixel_width = cache.pixel_width, - .pixel_height = cache.pixel_height, - }) catch {}; - }, - } - term.flush() catch {}; - } - }, - .place_cached_image => |place| { - self.pending_image = .{ .place_cached = place }; - }, - .delete_image => |del| { - if (self.terminal) |*term| { - const target: @import("../terminal/terminal.zig").KittyDeleteTarget = switch (del) { - .by_id => |id| .{ .by_id = id }, - .by_placement => |bp| .{ .by_placement = .{ .image_id = bp.image_id, .placement_id = bp.placement_id } }, - .all => .all, - }; - _ = term.deleteKittyImage(target) catch {}; - term.flush() catch {}; - } - }, - } - } - - fn flushPendingImage(self: *Self) !void { - const TerminalMod = @import("../terminal/terminal.zig"); - const pending = self.pending_image orelse return; - self.pending_image = null; - if (self.terminal) |*term| { - switch (pending) { - .auto => |image| { - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_save); - } - try self.positionPendingImage(term, image); - const protocol: TerminalMod.ImageProtocol = switch (image.protocol) { - .auto => .auto, - .kitty => .kitty, - .iterm2 => .iterm2, - .sixel => .sixel, - }; - _ = try term.drawImageFromFileWithProtocol(image.path, .{ - .width_cells = image.width_cells, - .height_cells = image.height_cells, - .preserve_aspect_ratio = image.preserve_aspect_ratio, - .image_id = image.image_id, - .placement_id = image.placement_id, - .move_cursor = image.move_cursor, - .quiet = image.quiet, - .z_index = image.z_index, - .unicode_placeholder = image.unicode_placeholder, - }, protocol); - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_restore); - } - }, - .kitty => |image| { - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_save); - } - try self.positionPendingImage(term, image); - _ = try term.drawKittyImageFromFile(image.path, .{ - .width_cells = image.width_cells, - .height_cells = image.height_cells, - .image_id = image.image_id, - .placement_id = image.placement_id, - .move_cursor = image.move_cursor, - .quiet = image.quiet, - .z_index = image.z_index, - .unicode_placeholder = image.unicode_placeholder, - }); - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_restore); - } - }, - .data => |image| { - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_save); - } - try self.positionPendingImageData(term, image); - const protocol: TerminalMod.ImageProtocol = switch (image.protocol) { - .auto => .auto, - .kitty => .kitty, - .iterm2 => .iterm2, - .sixel => .sixel, - }; - _ = try term.drawImageDataWithProtocol(image.data, .{ - .format = @enumFromInt(@intFromEnum(image.format)), - .pixel_width = image.pixel_width, - .pixel_height = image.pixel_height, - .width_cells = image.width_cells, - .height_cells = image.height_cells, - .image_id = image.image_id, - .placement_id = image.placement_id, - .move_cursor = image.move_cursor, - .quiet = image.quiet, - .z_index = image.z_index, - .unicode_placeholder = image.unicode_placeholder, - }, protocol); - if (!image.move_cursor) { - try term.writer().writeAll(ansi.cursor_restore); - } - }, - .place_cached => |place| { - if (!place.move_cursor) { - try term.writer().writeAll(ansi.cursor_save); - } - try self.positionPendingCachedImage(term, place); - _ = try term.placeKittyImage(.{ - .image_id = place.image_id, - .placement_id = place.placement_id, - .width_cells = place.width_cells, - .height_cells = place.height_cells, - .move_cursor = place.move_cursor, - .quiet = place.quiet, - .z_index = place.z_index, - .unicode_placeholder = place.unicode_placeholder, - }); - if (!place.move_cursor) { - try term.writer().writeAll(ansi.cursor_restore); - } - }, - } - try term.flush(); - } - } - - fn positionPendingImage(self: *Self, term: *Terminal, image: command.ImageFile) !void { - try self.positionByPlacement(term, image.placement, image.width_cells, image.height_cells, image.row, image.col, image.row_offset, image.col_offset); - } - - fn positionPendingImageData(self: *Self, term: *Terminal, image: command.ImageData) !void { - try self.positionByPlacement(term, image.placement, image.width_cells, image.height_cells, image.row, image.col, image.row_offset, image.col_offset); - } - - fn positionPendingCachedImage(self: *Self, term: *Terminal, place: command.PlaceCachedImage) !void { - try self.positionByPlacement(term, place.placement, place.width_cells, place.height_cells, place.row, place.col, place.row_offset, place.col_offset); - } - - fn positionByPlacement( - self: *Self, - term: *Terminal, - placement: command.ImagePlacement, - width_cells: ?u16, - height_cells: ?u16, - opt_row: ?u16, - opt_col: ?u16, - row_offset: i16, - col_offset: i16, - ) !void { - var row: u16 = 0; - var col: u16 = 0; - - switch (placement) { - .cursor => return, - .top_left => { - row = 0; - col = 0; - }, - .top_center => { - if (width_cells) |w_cells| { - const term_width = @as(usize, self.context.width); - const image_width = @as(usize, w_cells); - if (term_width > image_width) { - col = @intCast((term_width - image_width) / 2); - } - } - row = 0; - }, - .center => { - if (width_cells) |w_cells| { - const term_width = @as(usize, self.context.width); - const image_width = @as(usize, w_cells); - if (term_width > image_width) { - col = @intCast((term_width - image_width) / 2); - } - } - if (height_cells) |h_cells| { - const term_height = @as(usize, self.context.height); - const image_height = @as(usize, h_cells); - if (term_height > image_height) { - row = @intCast((term_height - image_height) / 2); - } - } - }, - } - - if (opt_row) |r| row = r; - if (opt_col) |c| col = c; - - const max_row = if (height_cells) |h| self.context.height -| h else self.context.height -| 1; - const max_col = if (width_cells) |w| self.context.width -| w else self.context.width -| 1; - row = applySignedOffsetClamped(row, row_offset, max_row); - col = applySignedOffsetClamped(col, col_offset, max_col); - - try term.moveTo(row, col); - } - - fn applySignedOffsetClamped(base: u16, offset: i16, max: u16) u16 { - const base_i32 = @as(i32, @intCast(base)); - const offset_i32 = @as(i32, offset); - const max_i32 = @as(i32, @intCast(max)); - var value = base_i32 + offset_i32; - if (value < 0) value = 0; - if (value > max_i32) value = max_i32; - return @intCast(value); - } - - /// Nanoseconds elapsed on the boot clock since `clock_epoch`. - fn elapsedNs(self: *const Self) u64 { - const dur = self.clock_epoch.untilNow(self.io); - const ns = dur.raw.nanoseconds; - if (ns <= 0) return 0; - return @intCast(ns); - } - - fn sleepNs(io: std.Io, nanoseconds: u64) void { - if (nanoseconds == 0) return; - std.Io.sleep(io, .fromNanoseconds(nanoseconds), .boot) catch unreachable; - } - - fn resetFrameAllocator(self: *Self) void { - _ = self.arena.reset(.retain_capacity); - self.context.allocator = self.arena.allocator(); - } - - fn render(self: *Self) !void { - const view_output = self.model.view(&self.context); - - // Compute hash of view output - const view_hash = std.hash.Wyhash.hash(0, view_output); - - // Only redraw if view changed - if (view_hash != self.last_view_hash) { - const writer = self.terminal.?.writer(); - - // Start synchronized output (prevents tearing on supporting terminals) - try writer.writeAll(ansi.sync_start); - - // Move cursor home (don't clear entire screen to reduce flicker) - try writer.writeAll(ansi.cursor_home); - - // Write each line, clearing to end of line - var lines = std.mem.splitScalar(u8, view_output, '\n'); - var first = true; - var line_count: usize = 0; - while (lines.next()) |line| { - if (!first) try writer.writeAll("\r\n"); - first = false; - try writer.writeAll(line); - try writer.writeAll(ansi.line_clear_right); - line_count += 1; - } - - // Clear remaining lines if previous content was taller - if (self.last_line_count > line_count) { - var remaining = self.last_line_count - line_count; - while (remaining > 0) : (remaining -= 1) { - try writer.writeAll("\r\n"); - try writer.writeAll(ansi.line_clear); - } - } - self.last_line_count = line_count; - - // End synchronized output - try writer.writeAll(ansi.sync_end); - - try self.terminal.?.flush(); - - // Save hash for comparison - self.last_view_hash = view_hash; - } - } - - /// Send a message to the model - pub fn send(self: *Self, m: UserMsg) !void { - const cmd = self.dispatchToModel(m); - try self.processCommand(cmd); - } - - /// Stop the program - pub fn quit(self: *Self) void { - self.running = false; - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig deleted file mode 100644 index acbd197..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/screen_stack.zig +++ /dev/null @@ -1,393 +0,0 @@ -//! Screen stack / router. -//! -//! Manages a stack of independent screens (each with its own state, key -//! handler, and view), letting an app push/pop modal or full-screen layers -//! the way a browser navigates pages. Distinct from `SubProgram` which is a -//! static-typed wrapper for one child model: a `ScreenStack` holds a runtime -//! stack of heterogeneous screens via a small vtable interface. -//! -//! Usage outline: -//! -//! var stack = zz.ScreenStack.init(allocator); -//! defer stack.deinit(); -//! try stack.push(login_screen); -//! // In your top-level update: -//! switch (try stack.handleKey(key, ctx)) { -//! .none => {}, -//! .quit => return .quit, -//! .pushed, .popped, .replaced => {}, -//! } -//! // In your top-level view: -//! return try stack.view(ctx, allocator); -//! -//! Screens marked `modal = true` render layered on top of the screen below, -//! so the previous screen stays visible behind a centered overlay (commonly -//! used for confirm dialogs or command palettes). - -const std = @import("std"); -const Writer = std.Io.Writer; -const Context = @import("context.zig").Context; -const keys = @import("../input/keys.zig"); -const measure = @import("../layout/measure.zig"); -const join = @import("../layout/join.zig"); - -/// Result of a key handler. Tells the stack how to mutate itself. -pub const Action = union(enum) { - /// Do nothing. - none, - /// Pop this screen off the top. - pop, - /// Pop this screen and push another. - replace: Screen, - /// Push a new screen on top of this one. - push: Screen, - /// Quit the whole program. - quit, -}; - -/// Outcome of a `handleKey` call to the stack — useful when the parent wants -/// to react to navigation. -pub const HandleResult = enum { none, pushed, popped, replaced, quit }; - -/// A single screen owned by the stack. Implemented via a tiny vtable so the -/// stack can hold heterogeneous screen types. -pub const Screen = struct { - ptr: *anyopaque, - vtable: *const VTable, - /// Title shown in breadcrumbs/diagnostics. Optional. - title: []const u8 = "", - /// If true, the screen behind this one is rendered first and this view - /// is overlaid (centered horizontally + vertically). - modal: bool = false, - - pub const VTable = struct { - update: *const fn (ctx: *anyopaque, msg_ctx: *Context, key: keys.KeyEvent) Action, - view: *const fn (ctx: *anyopaque, msg_ctx: *const Context, allocator: std.mem.Allocator) anyerror![]const u8, - /// Called by the stack when the screen is removed (pop or replace). - /// Use this to free per-screen resources. May be null. - deinit: ?*const fn (ctx: *anyopaque, allocator: std.mem.Allocator) void = null, - /// Called when the screen is pushed onto the stack. May be null. - on_enter: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, - /// Called when another screen is pushed on top, so this one is - /// covered. May be null. - on_suspend: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, - /// Called when this screen becomes the top again after a pop. - on_resume: ?*const fn (ctx: *anyopaque, msg_ctx: *Context) void = null, - }; -}; - -pub const ScreenStack = struct { - allocator: std.mem.Allocator, - stack: std.array_list.Managed(Screen), - - pub fn init(allocator: std.mem.Allocator) ScreenStack { - return .{ - .allocator = allocator, - .stack = std.array_list.Managed(Screen).init(allocator), - }; - } - - pub fn deinit(self: *ScreenStack) void { - // Tear down in reverse order so on_suspend semantics make sense. - while (self.stack.pop()) |s| { - if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); - } - self.stack.deinit(); - } - - pub fn depth(self: *const ScreenStack) usize { - return self.stack.items.len; - } - - pub fn isEmpty(self: *const ScreenStack) bool { - return self.stack.items.len == 0; - } - - /// The currently-active (top-of-stack) screen, or null. - pub fn top(self: *const ScreenStack) ?Screen { - if (self.stack.items.len == 0) return null; - return self.stack.items[self.stack.items.len - 1]; - } - - pub fn push(self: *ScreenStack, screen: Screen) !void { - if (self.top()) |prev| { - if (prev.vtable.on_suspend) |fn_ptr| fn_ptr(prev.ptr, undefined); - } - try self.stack.append(screen); - if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, undefined); - } - - pub fn pushWithCtx(self: *ScreenStack, screen: Screen, ctx: *Context) !void { - if (self.top()) |prev| { - if (prev.vtable.on_suspend) |fn_ptr| fn_ptr(prev.ptr, ctx); - } - try self.stack.append(screen); - if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, ctx); - } - - pub fn pop(self: *ScreenStack) void { - if (self.stack.pop()) |s| { - if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); - if (self.top()) |new_top| { - if (new_top.vtable.on_resume) |fn_ptr| fn_ptr(new_top.ptr, undefined); - } - } - } - - pub fn popWithCtx(self: *ScreenStack, ctx: *Context) void { - if (self.stack.pop()) |s| { - if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); - if (self.top()) |new_top| { - if (new_top.vtable.on_resume) |fn_ptr| fn_ptr(new_top.ptr, ctx); - } - } - } - - pub fn replace(self: *ScreenStack, screen: Screen) !void { - if (self.stack.pop()) |s| { - if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); - } - try self.stack.append(screen); - if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, undefined); - } - - /// Forward a key event to the top screen and apply the returned action. - pub fn handleKey(self: *ScreenStack, ctx: *Context, key: keys.KeyEvent) !HandleResult { - const current = self.top() orelse return .none; - const action = current.vtable.update(current.ptr, ctx, key); - return self.applyAction(action, ctx); - } - - fn applyAction(self: *ScreenStack, action: Action, ctx: *Context) !HandleResult { - switch (action) { - .none => return .none, - .quit => return .quit, - .pop => { - self.popWithCtx(ctx); - return .popped; - }, - .push => |screen| { - try self.pushWithCtx(screen, ctx); - return .pushed; - }, - .replace => |screen| { - if (self.stack.pop()) |s| { - if (s.vtable.deinit) |fn_ptr| fn_ptr(s.ptr, self.allocator); - } - try self.stack.append(screen); - if (screen.vtable.on_enter) |fn_ptr| fn_ptr(screen.ptr, ctx); - return .replaced; - }, - } - } - - /// Render the visible screens. Walks down from the top to find the - /// nearest non-modal "background" screen, then layers each modal on top. - pub fn view(self: *const ScreenStack, ctx: *const Context, allocator: std.mem.Allocator) ![]const u8 { - if (self.stack.items.len == 0) return try allocator.dupe(u8, ""); - - // Find the deepest screen we need to render: walk back until we hit - // a non-modal screen, that's our background. - var background_idx: usize = self.stack.items.len - 1; - while (background_idx > 0 and self.stack.items[background_idx].modal) { - background_idx -= 1; - } - - var current = try self.stack.items[background_idx].vtable.view( - self.stack.items[background_idx].ptr, - ctx, - allocator, - ); - - var i = background_idx + 1; - while (i < self.stack.items.len) : (i += 1) { - const overlay = try self.stack.items[i].vtable.view( - self.stack.items[i].ptr, - ctx, - allocator, - ); - defer allocator.free(overlay); - const composed = try compose(allocator, current, overlay); - allocator.free(current); - current = composed; - } - - return current; - } -}; - -/// Place `overlay` centered on top of `background`. The overlay's lines -/// replace the corresponding lines in the background; lines that don't -/// extend through the overlay region are kept as-is. The result has the -/// dimensions of the larger of the two. -fn compose(allocator: std.mem.Allocator, background: []const u8, overlay: []const u8) ![]const u8 { - const bg_w = measure.maxLineWidth(background); - const bg_h = measure.height(background); - const ov_w = measure.maxLineWidth(overlay); - const ov_h = measure.height(overlay); - - if (ov_w == 0 or ov_h == 0) return allocator.dupe(u8, background); - if (bg_w == 0 or bg_h == 0) return allocator.dupe(u8, overlay); - - // Vertical centering: place overlay starting at row (bg_h - ov_h) / 2. - const top: usize = if (bg_h > ov_h) (bg_h - ov_h) / 2 else 0; - const left: usize = if (bg_w > ov_w) (bg_w - ov_w) / 2 else 0; - - var bg_lines = std.array_list.Managed([]const u8).init(allocator); - defer bg_lines.deinit(); - { - var iter = std.mem.splitScalar(u8, background, '\n'); - while (iter.next()) |line| try bg_lines.append(line); - } - - var ov_lines = std.array_list.Managed([]const u8).init(allocator); - defer ov_lines.deinit(); - { - var iter = std.mem.splitScalar(u8, overlay, '\n'); - while (iter.next()) |line| try ov_lines.append(line); - } - - var result: Writer.Allocating = .init(allocator); - const w = &result.writer; - - var row: usize = 0; - while (row < bg_lines.items.len) : (row += 1) { - if (row > 0) try w.writeByte('\n'); - const ov_row_idx = if (row >= top) row - top else null; - if (ov_row_idx) |oidx| { - if (oidx < ov_lines.items.len) { - // Background prefix + overlay + background suffix. - const bg_line = bg_lines.items[row]; - const padded = try padOrTrim(allocator, bg_line, left); - defer allocator.free(padded); - try w.writeAll(padded); - try w.writeAll(ov_lines.items[oidx]); - continue; - } - } - try w.writeAll(bg_lines.items[row]); - } - - return result.toOwnedSlice(); -} - -fn padOrTrim(allocator: std.mem.Allocator, line: []const u8, target: usize) ![]u8 { - const w = measure.width(line); - if (w == target) return allocator.dupe(u8, line); - if (w < target) { - const pad = target - w; - const out = try allocator.alloc(u8, line.len + pad); - @memcpy(out[0..line.len], line); - @memset(out[line.len..], ' '); - return out; - } - // w > target: truncate visible width while preserving escapes. Best-effort. - const trimmed = try measure.truncate(allocator, line, target); - return @constCast(trimmed); -} - -// ── Tests ────────────────────────────────────────────────────────────── - -const testing = std.testing; - -const TestScreen = struct { - name: []const u8, - pop_on_q: bool = true, - quit_on_x: bool = false, - pub var enter_count: usize = 0; - pub var leave_count: usize = 0; - - fn update(ptr: *anyopaque, _: *Context, key: keys.KeyEvent) Action { - const self: *TestScreen = @ptrCast(@alignCast(ptr)); - switch (key.key) { - .char => |c| { - if (self.pop_on_q and c == 'q') return .pop; - if (self.quit_on_x and c == 'x') return .quit; - }, - else => {}, - } - return .none; - } - - fn view(ptr: *anyopaque, _: *const Context, allocator: std.mem.Allocator) ![]const u8 { - const self: *TestScreen = @ptrCast(@alignCast(ptr)); - return allocator.dupe(u8, self.name); - } - - fn onEnter(_: *anyopaque, _: *Context) void { - enter_count += 1; - } - - fn onSuspend(_: *anyopaque, _: *Context) void { - leave_count += 1; - } - - pub const vtable = Screen.VTable{ - .update = update, - .view = view, - .on_enter = onEnter, - .on_suspend = onSuspend, - }; -}; - -test "push and pop" { - var stack = ScreenStack.init(testing.allocator); - defer stack.deinit(); - - var s1 = TestScreen{ .name = "first" }; - var s2 = TestScreen{ .name = "second" }; - - try stack.push(.{ .ptr = &s1, .vtable = &TestScreen.vtable, .title = "first" }); - try testing.expectEqual(@as(usize, 1), stack.depth()); - try stack.push(.{ .ptr = &s2, .vtable = &TestScreen.vtable, .title = "second" }); - try testing.expectEqual(@as(usize, 2), stack.depth()); - - stack.pop(); - try testing.expectEqual(@as(usize, 1), stack.depth()); - const t = stack.top().?; - try testing.expectEqualStrings("first", t.title); -} - -test "handleKey processes pop action" { - var stack = ScreenStack.init(testing.allocator); - defer stack.deinit(); - - var s = TestScreen{ .name = "screen" }; - try stack.push(.{ .ptr = &s, .vtable = &TestScreen.vtable }); - - var ctx: Context = undefined; - const result = try stack.handleKey(&ctx, .{ .key = .{ .char = 'q' } }); - try testing.expectEqual(HandleResult.popped, result); - try testing.expect(stack.isEmpty()); -} - -test "quit action propagates" { - var stack = ScreenStack.init(testing.allocator); - defer stack.deinit(); - - var s = TestScreen{ .name = "screen", .quit_on_x = true }; - try stack.push(.{ .ptr = &s, .vtable = &TestScreen.vtable }); - - var ctx: Context = undefined; - const result = try stack.handleKey(&ctx, .{ .key = .{ .char = 'x' } }); - try testing.expectEqual(HandleResult.quit, result); -} - -test "modal screen overlays previous screen" { - var stack = ScreenStack.init(testing.allocator); - defer stack.deinit(); - - var bg = TestScreen{ .name = "background background background background\nbackground background background background\nbackground background background background\nbackground background background background" }; - var modal = TestScreen{ .name = "MODAL" }; - - try stack.push(.{ .ptr = &bg, .vtable = &TestScreen.vtable }); - try stack.push(.{ .ptr = &modal, .vtable = &TestScreen.vtable, .modal = true }); - - var ctx: Context = undefined; - const out = try stack.view(&ctx, testing.allocator); - defer testing.allocator.free(out); - - // Both background and modal should appear in output. - try testing.expect(std.mem.indexOf(u8, out, "background") != null); - try testing.expect(std.mem.indexOf(u8, out, "MODAL") != null); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig deleted file mode 100644 index 7a0e1a2..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/core/sub_program.zig +++ /dev/null @@ -1,87 +0,0 @@ -//! Sub-program support for embedding child models inside a parent. -//! Allows composing independent Model-Update-View units with message routing. - -const std = @import("std"); -const Context = @import("context.zig").Context; -const command = @import("command.zig"); - -/// A wrapper that embeds a child Model inside a parent, with message mapping. -/// -/// - `ChildModel` must have `Msg`, `init`, `update`, `view` like a top-level model. -/// - `ParentMsg` is the parent's message type. -/// - The child's `.quit` command is converted to an optional parent message via `quit_msg`. -pub fn SubProgram(comptime ChildModel: type, comptime ParentMsg: type) type { - comptime { - if (!@hasDecl(ChildModel, "Msg")) @compileError("ChildModel must have a 'Msg' type"); - if (!@hasDecl(ChildModel, "init")) @compileError("ChildModel must have an 'init' function"); - if (!@hasDecl(ChildModel, "update")) @compileError("ChildModel must have an 'update' function"); - if (!@hasDecl(ChildModel, "view")) @compileError("ChildModel must have a 'view' function"); - } - - const ChildMsg = ChildModel.Msg; - const ChildCmd = command.Cmd(ChildMsg); - const ParentCmd = command.Cmd(ParentMsg); - - return struct { - model: ChildModel = undefined, - initialized: bool = false, - /// Optional message to send to parent when child issues .quit. - quit_msg: ?ParentMsg = null, - - const Self = @This(); - - /// Initialize the child model. - pub fn init(self: *Self, ctx: *Context) ParentCmd { - const child_cmd = self.model.init(ctx); - self.initialized = true; - return self.translateCmd(child_cmd); - } - - /// Forward a child message to the child's update, returning a parent command. - pub fn update(self: *Self, child_msg: ChildMsg, ctx: *Context) ParentCmd { - if (!self.initialized) return .none; - const child_cmd = self.model.update(child_msg, ctx); - return self.translateCmd(child_cmd); - } - - /// Render the child model. - pub fn view(self: *const Self, ctx: *const Context) []const u8 { - if (!self.initialized) return ""; - return self.model.view(ctx); - } - - /// Translate a child command into a parent command. - fn translateCmd(self: *const Self, cmd: ChildCmd) ParentCmd { - return switch (cmd) { - .none => .none, - .quit => if (self.quit_msg) |m| .{ .msg = m } else .none, - .tick => |ns| .{ .tick = ns }, - .every => |ns| .{ .every = ns }, - .msg => |child_msg| blk: { - // Child-internal messages: re-dispatch is not possible at parent level, - // so we drop them. The parent should call sub.update() with child messages. - _ = child_msg; - break :blk .none; - }, - .perform => .none, // Can't translate perform functions across types - .suspend_process => .suspend_process, - .enable_mouse => .enable_mouse, - .disable_mouse => .disable_mouse, - .show_cursor => .show_cursor, - .hide_cursor => .hide_cursor, - .enter_alt_screen => .enter_alt_screen, - .exit_alt_screen => .exit_alt_screen, - .set_title => |t| .{ .set_title = t }, - .println => |l| .{ .println = l }, - .batch => .none, // Complex: would need recursive translation - .sequence => .none, - .image_file => |img| .{ .image_file = img }, - .kitty_image_file => |img| .{ .kitty_image_file = img }, - .image_data => |img| .{ .image_data = img }, - .cache_image => |c| .{ .cache_image = c }, - .place_cached_image => |p| .{ .place_cached_image = p }, - .delete_image => |d| .{ .delete_image = d }, - }; - } - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig deleted file mode 100644 index 49ccd5c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/hitbox.zig +++ /dev/null @@ -1,128 +0,0 @@ -//! Hit testing utilities for mouse interactions. -//! Provides rectangular region hit detection for UI components. - -const mouse = @import("mouse.zig"); -const MouseEvent = mouse.MouseEvent; - -/// A rectangular region for mouse hit testing. -pub const HitBox = struct { - x: u16, - y: u16, - width: u16, - height: u16, - - /// Create a hit box at the given position and size. - pub fn init(x: u16, y: u16, w: u16, h: u16) HitBox { - return .{ .x = x, .y = y, .width = w, .height = h }; - } - - /// Check whether a mouse event falls within this region. - pub fn contains(self: HitBox, event: MouseEvent) bool { - return event.x >= self.x and - event.x < self.x +| self.width and - event.y >= self.y and - event.y < self.y +| self.height; - } - - /// Check whether a coordinate falls within this region. - pub fn containsPoint(self: HitBox, x: u16, y: u16) bool { - return x >= self.x and - x < self.x +| self.width and - y >= self.y and - y < self.y +| self.height; - } - - /// Check if a click event (press with left button) occurred in this region. - pub fn clicked(self: HitBox, event: MouseEvent) bool { - return event.button == .left and - event.event_type == .press and - self.contains(event); - } - - /// Check if a right-click occurred in this region. - pub fn rightClicked(self: HitBox, event: MouseEvent) bool { - return event.button == .right and - event.event_type == .press and - self.contains(event); - } - - /// Get local coordinates relative to the hit box origin. - /// Returns null if the event is outside the region. - pub fn localCoords(self: HitBox, event: MouseEvent) ?struct { x: u16, y: u16 } { - if (!self.contains(event)) return null; - return .{ - .x = event.x - self.x, - .y = event.y - self.y, - }; - } - - /// Expand the hit box by a padding amount on all sides. - pub fn expand(self: HitBox, padding: u16) HitBox { - return .{ - .x = self.x -| padding, - .y = self.y -| padding, - .width = self.width +| padding *| 2, - .height = self.height +| padding *| 2, - }; - } - - /// Check if two hit boxes overlap. - pub fn overlaps(self: HitBox, other: HitBox) bool { - return self.x < other.x +| other.width and - self.x +| self.width > other.x and - self.y < other.y +| other.height and - self.y +| self.height > other.y; - } -}; - -/// Track mouse state across frames (hover, pressed, etc.) -pub const MouseState = struct { - hover: bool = false, - pressed: bool = false, - last_x: u16 = 0, - last_y: u16 = 0, - - /// Update state from a mouse event against a hit box. - /// Returns which interaction occurred. - pub fn update(self: *MouseState, hitbox: HitBox, event: MouseEvent) Interaction { - self.last_x = event.x; - self.last_y = event.y; - - const inside = hitbox.contains(event); - const was_hover = self.hover; - self.hover = inside; - - if (event.event_type == .press and event.button == .left and inside) { - self.pressed = true; - return .press; - } - - if (event.event_type == .release and event.button == .left) { - if (self.pressed and inside) { - self.pressed = false; - return .click; - } - self.pressed = false; - } - - if (inside and !was_hover) return .enter; - if (!inside and was_hover) return .leave; - if (inside and event.event_type == .move) return .hover; - - if (event.button == .wheel_up and inside) return .scroll_up; - if (event.button == .wheel_down and inside) return .scroll_down; - - return .none; - } -}; - -pub const Interaction = enum { - none, - press, - click, - enter, - leave, - hover, - scroll_up, - scroll_down, -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig deleted file mode 100644 index f59c19c..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keyboard.zig +++ /dev/null @@ -1,329 +0,0 @@ -//! Keyboard input parsing for terminal applications. -//! Parses ANSI escape sequences into structured key events. - -const std = @import("std"); -const keys = @import("keys.zig"); -const mouse = @import("mouse.zig"); - -pub const Key = keys.Key; -pub const KeyEvent = keys.KeyEvent; -pub const Modifiers = keys.Modifiers; -pub const MouseEvent = mouse.MouseEvent; - -/// Result of parsing input data -pub const ParseResult = union(enum) { - key: KeyEvent, - mouse: MouseEvent, - none, -}; - -/// Return type for parse functions -pub const ParseReturn = struct { result: ParseResult, consumed: usize }; - -/// Parse a single input event from raw terminal data -pub fn parse(data: []const u8) ParseReturn { - if (data.len == 0) return .{ .result = .none, .consumed = 0 }; - - // Check for escape sequence - if (data[0] == 0x1b) { - if (data.len == 1) { - // Just escape key - return .{ .result = .{ .key = .{ .key = .escape } }, .consumed = 1 }; - } - - // CSI sequence - if (data.len >= 2 and data[1] == '[') { - if (parseCsi(data)) |result| { - return result; - } - } - - // SS3 sequence (F1-F4 on some terminals) - if (data.len >= 2 and data[1] == 'O') { - if (parseSs3(data)) |result| { - return result; - } - } - - // Alt + key - if (data.len >= 2 and data[1] != '[' and data[1] != 'O') { - const inner = parse(data[1..]); - if (inner.result == .key) { - var key_event = inner.result.key; - key_event.modifiers.alt = true; - return .{ .result = .{ .key = key_event }, .consumed = 1 + inner.consumed }; - } - } - - return .{ .result = .{ .key = .{ .key = .escape } }, .consumed = 1 }; - } - - // Control characters - if (data[0] < 32) { - const key_event = parseControl(data[0]); - return .{ .result = .{ .key = key_event }, .consumed = 1 }; - } - - // DEL character - if (data[0] == 127) { - return .{ .result = .{ .key = .{ .key = .backspace } }, .consumed = 1 }; - } - - // UTF-8 character - const len = std.unicode.utf8ByteSequenceLength(data[0]) catch 1; - if (len <= data.len) { - const codepoint = std.unicode.utf8Decode(data[0..len]) catch data[0]; - return .{ .result = .{ .key = .{ .key = .{ .char = codepoint } } }, .consumed = len }; - } - - return .{ .result = .{ .key = .{ .key = .{ .char = data[0] } } }, .consumed = 1 }; -} - -fn parseControl(c: u8) KeyEvent { - return switch (c) { - 0 => .{ .key = .null_key, .modifiers = .{ .ctrl = true } }, - 9 => .{ .key = .tab }, - // In raw mode 0x0a is sent by the terminal itself - // Some editor-integrated terminals (Zed, possibly VSCode) use this - // historical CR/LF split to encode Shift+Enter without a richer - // keyboard protocol -- plain Enter sends 0x0d, Shift+Enter sends - // 0x0a. Mapping LF onto Enter+Shift recovers the modifier, ensuring - // consistent behavior to other TUI applications / libraries. - 10 => .{ .key = .enter, .modifiers = .{ .shift = true } }, - 13 => .{ .key = .enter }, - 27 => .{ .key = .escape }, - 1...8, 11, 12, 14...26 => .{ - .key = .{ .char = 'a' + c - 1 }, - .modifiers = .{ .ctrl = true }, - }, - else => .{ .key = .{ .char = c } }, - }; -} - -fn parseCsi(data: []const u8) ?ParseReturn { - if (data.len < 3) return null; - if (data[0] != 0x1b or data[1] != '[') return null; - - // Check for bracketed paste start: ESC[200~ - if (data.len >= 6 and std.mem.startsWith(u8, data[2..], "200~")) { - return parseBracketedPaste(data); - } - - // Check for mouse SGR sequence - if (data.len >= 3 and data[2] == '<') { - if (mouse.parseSgr(data)) |m| { - return .{ .result = .{ .mouse = m.event }, .consumed = m.consumed }; - } - } - - var idx: usize = 2; - var params: [8]u16 = .{0} ** 8; - var param_count: usize = 0; - var has_colon = false; - var sub_params: [8]u16 = .{0} ** 8; - - // Parse parameters (supports both ; and : separators for Kitty protocol) - while (idx < data.len and param_count < params.len) { - const c = data[idx]; - if (c >= '0' and c <= '9') { - params[param_count] = params[param_count] * 10 + @as(u16, @intCast(c - '0')); - idx += 1; - } else if (c == ';') { - param_count += 1; - idx += 1; - } else if (c == ':') { - // Kitty protocol uses : for sub-parameters (e.g., modifiers:event_type) - has_colon = true; - sub_params[param_count] = 0; - idx += 1; - // Parse the sub-parameter value - while (idx < data.len and data[idx] >= '0' and data[idx] <= '9') { - sub_params[param_count] = sub_params[param_count] * 10 + @as(u16, @intCast(data[idx] - '0')); - idx += 1; - } - } else { - break; - } - } - param_count += 1; - - if (idx >= data.len) return null; - - const final_byte = data[idx]; - idx += 1; - - // Kitty keyboard protocol: final byte 'u' - if (final_byte == 'u') { - return parseKittyCsi(params[0..param_count], sub_params[0..param_count], has_colon, idx); - } - - // Determine modifiers from parameter - var modifiers = Modifiers{}; - if (param_count >= 2 and params[1] > 1) { - const mod_param = params[1] - 1; - modifiers.shift = (mod_param & 1) != 0; - modifiers.alt = (mod_param & 2) != 0; - modifiers.ctrl = (mod_param & 4) != 0; - } - - const key: Key = switch (final_byte) { - 'A' => .up, - 'B' => .down, - 'C' => .right, - 'D' => .left, - 'H' => .home, - 'F' => .end, - 'Z' => { - modifiers.shift = true; - return .{ .result = .{ .key = .{ .key = .tab, .modifiers = modifiers } }, .consumed = idx }; - }, - '~' => switch (params[0]) { - 1 => .home, - 2 => .insert, - 3 => .delete, - 4 => .end, - 5 => .page_up, - 6 => .page_down, - 7 => .home, - 8 => .end, - 11 => .f1, - 12 => .f2, - 13 => .f3, - 14 => .f4, - 15 => .f5, - 17 => .f6, - 18 => .f7, - 19 => .f8, - 20 => .f9, - 21 => .f10, - 23 => .f11, - 24 => .f12, - else => return null, - }, - else => return null, - }; - - return .{ .result = .{ .key = .{ .key = key, .modifiers = modifiers } }, .consumed = idx }; -} - -/// Parse Kitty keyboard protocol CSI sequence: CSI keycode;modifiers:event_type u -fn parseKittyCsi(params: []const u16, sub_params: []const u16, has_colon: bool, consumed: usize) ?ParseReturn { - if (params.len == 0) return null; - - const keycode = params[0]; - - // Determine modifiers - var modifiers = Modifiers{}; - if (params.len >= 2 and params[1] > 1) { - const mod_param = params[1] - 1; - modifiers.shift = (mod_param & 1) != 0; - modifiers.alt = (mod_param & 2) != 0; - modifiers.ctrl = (mod_param & 4) != 0; - modifiers.super = (mod_param & 8) != 0; - } - - // Determine event type from sub-parameter - var event_type: keys.KeyEventType = .press; - if (has_colon and params.len >= 2) { - event_type = switch (sub_params[1]) { - 2 => .repeat, - 3 => .release, - else => .press, - }; - } - - // Map keycode to Key - const key: Key = switch (keycode) { - 9 => .tab, - 13 => .enter, - 27 => .escape, - 32 => .space, - 127 => .backspace, - 57358 => .{ .char = 0 }, // caps_lock etc - map to null - else => blk: { - if (keycode >= 32 and keycode < 127) { - break :blk .{ .char = @intCast(keycode) }; - } - if (keycode > 127 and keycode <= 0x10FFFF) { - break :blk .{ .char = @intCast(keycode) }; - } - break :blk .null_key; - }, - }; - - return .{ - .result = .{ .key = .{ - .key = key, - .modifiers = modifiers, - .event_type = event_type, - } }, - .consumed = consumed, - }; -} - -/// Parse bracketed paste: ESC[200~ ... ESC[201~ -fn parseBracketedPaste(data: []const u8) ?ParseReturn { - // data starts with ESC[200~ - const paste_start = 6; // length of ESC[200~ - const end_marker = "\x1b[201~"; - - if (std.mem.indexOf(u8, data[paste_start..], end_marker)) |end_offset| { - const paste_content = data[paste_start .. paste_start + end_offset]; - const total_consumed = paste_start + end_offset + end_marker.len; - return .{ - .result = .{ .key = .{ - .key = .{ .paste = paste_content }, - } }, - .consumed = total_consumed, - }; - } - - // End marker not found — consume all available data as paste - // (paste may span multiple reads) - return .{ - .result = .{ .key = .{ - .key = .{ .paste = data[paste_start..] }, - } }, - .consumed = data.len, - }; -} - -fn parseSs3(data: []const u8) ?ParseReturn { - if (data.len < 3) return null; - if (data[0] != 0x1b or data[1] != 'O') return null; - - const key: Key = switch (data[2]) { - 'P' => .f1, - 'Q' => .f2, - 'R' => .f3, - 'S' => .f4, - 'A' => .up, - 'B' => .down, - 'C' => .right, - 'D' => .left, - 'H' => .home, - 'F' => .end, - else => return null, - }; - - return .{ .result = .{ .key = .{ .key = key } }, .consumed = 3 }; -} - -/// Parse all available input events from a buffer -pub fn parseAll(allocator: std.mem.Allocator, data: []const u8) ![]ParseResult { - var results = std.array_list.Managed(ParseResult).init(allocator); - errdefer results.deinit(); - - var offset: usize = 0; - while (offset < data.len) { - const parsed = parse(data[offset..]); - if (parsed.consumed == 0) break; - - if (parsed.result != .none) { - try results.append(parsed.result); - } - offset += parsed.consumed; - } - - return results.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig deleted file mode 100644 index b858fa2..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/keys.zig +++ /dev/null @@ -1,191 +0,0 @@ -//! Key definitions for keyboard input handling. -//! Provides a comprehensive set of key types for terminal input. - -const std = @import("std"); -const Writer = std.Io.Writer; - -/// Modifier keys that can be combined with other keys -pub const Modifiers = packed struct { - shift: bool = false, - alt: bool = false, - ctrl: bool = false, - super: bool = false, - - pub const none = Modifiers{}; - - pub fn eql(self: Modifiers, other: Modifiers) bool { - return self.shift == other.shift and - self.alt == other.alt and - self.ctrl == other.ctrl and - self.super == other.super; - } - - pub fn any(self: Modifiers) bool { - return self.shift or self.alt or self.ctrl or self.super; - } -}; - -/// Represents a keyboard key -pub const Key = union(enum) { - // Character keys - char: u21, - - // Function keys - f1, - f2, - f3, - f4, - f5, - f6, - f7, - f8, - f9, - f10, - f11, - f12, - - // Navigation keys - up, - down, - left, - right, - home, - end, - page_up, - page_down, - - // Editing keys - insert, - delete, - backspace, - - // Control keys - enter, - tab, - escape, - space, - - // Paste (bracketed paste content) - paste: []const u8, - - // Special - null_key, - unknown: []const u8, - - pub fn eql(self: Key, other: Key) bool { - const self_tag = std.meta.activeTag(self); - const other_tag = std.meta.activeTag(other); - if (self_tag != other_tag) return false; - - return switch (self) { - .char => |c| c == other.char, - .paste => |s| std.mem.eql(u8, s, other.paste), - .unknown => |s| std.mem.eql(u8, s, other.unknown), - else => true, - }; - } - - /// Returns the character if this is a char key, null otherwise - pub fn toChar(self: Key) ?u21 { - return switch (self) { - .char => |c| c, - .space => ' ', - .enter => '\n', - .tab => '\t', - else => null, - }; - } - - /// Returns a human-readable string for the key - pub fn name(self: Key) []const u8 { - return switch (self) { - .char => "char", - .f1 => "f1", - .f2 => "f2", - .f3 => "f3", - .f4 => "f4", - .f5 => "f5", - .f6 => "f6", - .f7 => "f7", - .f8 => "f8", - .f9 => "f9", - .f10 => "f10", - .f11 => "f11", - .f12 => "f12", - .up => "up", - .down => "down", - .left => "left", - .right => "right", - .home => "home", - .end => "end", - .page_up => "page_up", - .page_down => "page_down", - .insert => "insert", - .delete => "delete", - .backspace => "backspace", - .enter => "enter", - .tab => "tab", - .escape => "escape", - .space => "space", - .paste => "paste", - .null_key => "null", - .unknown => "unknown", - }; - } -}; - -/// Key event type (for Kitty keyboard protocol) -pub const KeyEventType = enum { - press, - repeat, - release, -}; - -/// A key event with modifiers -pub const KeyEvent = struct { - key: Key, - modifiers: Modifiers = .{}, - event_type: KeyEventType = .press, - - pub fn eql(self: KeyEvent, other: KeyEvent) bool { - return self.key.eql(other.key) and self.modifiers.eql(other.modifiers); - } - - /// Create a key event from a character - pub fn char(c: u21) KeyEvent { - return .{ .key = .{ .char = c } }; - } - - /// Create a key event with ctrl modifier - pub fn ctrl(c: u21) KeyEvent { - return .{ - .key = .{ .char = c }, - .modifiers = .{ .ctrl = true }, - }; - } - - /// Create a key event with alt modifier - pub fn alt(c: u21) KeyEvent { - return .{ - .key = .{ .char = c }, - .modifiers = .{ .alt = true }, - }; - } - - /// Format the key event for display - pub fn format(self: KeyEvent, writer: *Writer) Writer.Error!void { - if (self.modifiers.ctrl) try writer.writeAll("ctrl+"); - if (self.modifiers.alt) try writer.writeAll("alt+"); - if (self.modifiers.shift) try writer.writeAll("shift+"); - if (self.modifiers.super) try writer.writeAll("super+"); - - switch (self.key) { - .char => |c| { - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(c, &buf) catch 0; - try writer.writeAll(buf[0..len]); - }, - else => try writer.writeAll(self.key.name()), - } - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig deleted file mode 100644 index 795c66f..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/input/mouse.zig +++ /dev/null @@ -1,164 +0,0 @@ -//! Mouse event handling for terminal applications. -//! Supports standard terminal mouse protocols. - -const std = @import("std"); -const Writer = std.Io.Writer; -const keys = @import("keys.zig"); - -/// Mouse button types -pub const Button = enum { - left, - middle, - right, - wheel_up, - wheel_down, - wheel_left, - wheel_right, - button_8, - button_9, - button_10, - button_11, - none, -}; - -/// Mouse event types -pub const EventType = enum { - press, - release, - drag, - move, -}; - -/// A mouse event -pub const MouseEvent = struct { - x: u16, - y: u16, - button: Button, - event_type: EventType, - modifiers: keys.Modifiers = .{}, - - pub fn format(self: MouseEvent, writer: *Writer) Writer.Error!void { - try writer.print("{s} {s} at ({d}, {d})", .{ - @tagName(self.event_type), - @tagName(self.button), - self.x, - self.y, - }); - - if (self.modifiers.any()) { - try writer.writeAll(" with "); - if (self.modifiers.ctrl) try writer.writeAll("ctrl "); - if (self.modifiers.alt) try writer.writeAll("alt "); - if (self.modifiers.shift) try writer.writeAll("shift "); - } - } -}; - -/// Mouse tracking modes -pub const TrackingMode = enum { - /// No mouse tracking - none, - /// Report button press events only - normal, - /// Report button press and release events - button, - /// Report all mouse events including motion - all, -}; - -/// Generate ANSI sequence to enable mouse tracking -pub fn enableSequence(mode: TrackingMode) []const u8 { - return switch (mode) { - .none => "", - .normal => "\x1b[?1000h\x1b[?1006h", - .button => "\x1b[?1002h\x1b[?1006h", - .all => "\x1b[?1003h\x1b[?1006h", - }; -} - -/// Generate ANSI sequence to disable mouse tracking -pub fn disableSequence(mode: TrackingMode) []const u8 { - return switch (mode) { - .none => "", - .normal => "\x1b[?1006l\x1b[?1000l", - .button => "\x1b[?1006l\x1b[?1002l", - .all => "\x1b[?1006l\x1b[?1003l", - }; -} - -/// Parse SGR mouse event (\x1b[<...M or \x1b[<...m) -pub fn parseSgr(data: []const u8) ?struct { event: MouseEvent, consumed: usize } { - // Format: \x1b[= '0' and c <= '9') { - params[param_idx] = params[param_idx] * 10 + @as(u16, @intCast(c - '0')); - idx += 1; - } else if (c == ';') { - param_idx += 1; - idx += 1; - } else if (c == 'M' or c == 'm') { - idx += 1; - break; - } else { - return null; - } - } - - if (param_idx < 2) return null; - if (idx == 0 or (data[idx - 1] != 'M' and data[idx - 1] != 'm')) return null; - - const cb = params[0]; - const is_release = data[idx - 1] == 'm'; - - var modifiers = keys.Modifiers{}; - if (cb & 4 != 0) modifiers.shift = true; - if (cb & 8 != 0) modifiers.alt = true; - if (cb & 16 != 0) modifiers.ctrl = true; - - const button_bits = cb & 0b11000011; - const is_motion = cb & 32 != 0; - - const button: Button = switch (button_bits) { - 0 => .left, - 1 => .middle, - 2 => .right, - 3 => .none, - 64 => .wheel_up, - 65 => .wheel_down, - 66 => .wheel_left, - 67 => .wheel_right, - 128 => .button_8, - 129 => .button_9, - 130 => .button_10, - 131 => .button_11, - else => .none, - }; - - const event_type: EventType = if (is_release) - .release - else if (is_motion and button == .none) - .move - else if (is_motion) - .drag - else - .press; - - return .{ - .event = .{ - .x = if (params[1] > 0) params[1] - 1 else 0, - .y = if (params[2] > 0) params[2] - 1 else 0, - .button = button, - .event_type = event_type, - .modifiers = modifiers, - }, - .consumed = idx, - }; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig deleted file mode 100644 index fca1d49..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/flex.zig +++ /dev/null @@ -1,473 +0,0 @@ -//! Constraint-based Flexbox layout engine for ZigZag TUI. -//! -//! Resolves sizing constraints and computes rectangular areas -//! for a list of flex items along a main axis (row or column), -//! with support for gaps, cross-axis alignment, main-axis -//! justification, and line wrapping. -//! -//! ## Example -//! -//! ```zig -//! const areas = try flex.layout(allocator, 80, 24, &.{ -//! .{ .constraint = .{ .percentage = 30 } }, -//! .{ .constraint = .{ .min = 10 } }, -//! .{ .constraint = .fill }, -//! }, .{ .direction = .row, .gap = 1 }); -//! ``` - -const std = @import("std"); - -// --------------------------------------------------------------------------- -// Public types -// --------------------------------------------------------------------------- - -/// A sizing constraint for one flex item. -pub const Constraint = union(enum) { - /// Exactly `n` cells. - fixed: u16, - /// A percentage of total available space (0-100). - percentage: u8, - /// At least `n` cells (can grow to fill). - min: u16, - /// At most `n` cells (can shrink to fit). - max: u16, - /// Ratio: `num / den` of available space. - ratio: struct { num: u16, den: u16 }, - /// Take all remaining space after fixed/percentage items. - fill, -}; - -/// Main-axis direction. -pub const Direction = enum { - row, - column, -}; - -/// Cross-axis alignment. -pub const Alignment = enum { - start, - center, - end, - stretch, -}; - -/// Main-axis content distribution. -pub const Justify = enum { - start, - center, - end, - space_between, - space_around, - space_evenly, -}; - -/// Describes a single flex child. -pub const Item = struct { - constraint: Constraint = .fill, -}; - -/// Layout options. -pub const FlexOptions = struct { - direction: Direction = .row, - gap: u16 = 0, - alignment: Alignment = .stretch, - justify: Justify = .start, - wrap: bool = false, -}; - -/// An output rectangle (in cell coordinates). -pub const Rect = struct { - x: u16, - y: u16, - width: u16, - height: u16, -}; - -// --------------------------------------------------------------------------- -// Core layout algorithm -// --------------------------------------------------------------------------- - -/// Compute layout rectangles for `items` inside a container of -/// `total_width` x `total_height` cells. -/// -/// Returns a slice of `Rect` allocated with `allocator`. -pub fn layout( - allocator: std.mem.Allocator, - total_width: u16, - total_height: u16, - items: []const Item, - options: FlexOptions, -) ![]Rect { - if (items.len == 0) { - return try allocator.alloc(Rect, 0); - } - - if (options.wrap) { - return layoutWrapped(allocator, total_width, total_height, items, options); - } - - return layoutLine(allocator, total_width, total_height, items, options, 0, 0); -} - -/// Layout a single line of items (no wrapping). -fn layoutLine( - allocator: std.mem.Allocator, - total_width: u16, - total_height: u16, - items: []const Item, - options: FlexOptions, - origin_x: u16, - origin_y: u16, -) ![]Rect { - const n = items.len; - const is_row = options.direction == .row; - const main_total: u16 = if (is_row) total_width else total_height; - const cross_total: u16 = if (is_row) total_height else total_width; - - // Total gap space - const gap_count: u16 = if (n > 1) @intCast(n - 1) else 0; - const total_gap: u16 = gap_count * options.gap; - const avail: u16 = if (main_total > total_gap) main_total - total_gap else 0; - - // -- Phase 1: resolve constraints to sizes -------------------------------- - var sizes = try allocator.alloc(u16, n); - defer allocator.free(sizes); - - var fill_count: u16 = 0; - var used: u32 = 0; - - for (items, 0..) |item, i| { - switch (item.constraint) { - .fixed => |v| { - sizes[i] = v; - used += v; - }, - .percentage => |pct| { - const clamped: u32 = @min(pct, 100); - const sz: u16 = @intCast((@as(u32, avail) * clamped) / 100); - sizes[i] = sz; - used += sz; - }, - .min => |v| { - sizes[i] = v; - used += v; - }, - .max => |v| { - sizes[i] = v; - used += v; - }, - .ratio => |r| { - const sz: u16 = if (r.den == 0) 0 else @intCast((@as(u32, avail) * r.num) / r.den); - sizes[i] = sz; - used += sz; - }, - .fill => { - sizes[i] = 0; - fill_count += 1; - }, - } - } - - // -- Phase 2: distribute remaining space among fill items ----------------- - const remaining: u16 = if (avail > @as(u16, @intCast(@min(used, avail)))) avail - @as(u16, @intCast(@min(used, avail))) else 0; - if (fill_count > 0 and remaining > 0) { - const per_fill: u16 = remaining / fill_count; - var leftover: u16 = remaining - per_fill * fill_count; - for (items, 0..) |item, i| { - if (item.constraint == .fill) { - sizes[i] = per_fill; - if (leftover > 0) { - sizes[i] += 1; - leftover -= 1; - } - } - } - } - - // Grow `min` items if there is leftover space - if (fill_count == 0 and remaining > 0) { - var min_count: u16 = 0; - for (items) |item| { - if (item.constraint == .min) min_count += 1; - } - if (min_count > 0) { - const per_min: u16 = remaining / min_count; - var leftover: u16 = remaining - per_min * min_count; - for (items, 0..) |item, i| { - if (item.constraint == .min) { - sizes[i] += per_min; - if (leftover > 0) { - sizes[i] += 1; - leftover -= 1; - } - } - } - } - } - - // Shrink `max` items so they don't exceed their cap - for (items, 0..) |item, i| { - if (item.constraint == .max) { - const cap = item.constraint.max; - if (sizes[i] > cap) sizes[i] = cap; - } - } - - // Clamp all sizes so total doesn't exceed available space - { - var sum: u32 = 0; - for (sizes) |s| sum += s; - if (sum > avail) { - const scale_num: u32 = avail; - const scale_den: u32 = sum; - for (sizes, 0..) |_, i| { - sizes[i] = @intCast((@as(u32, sizes[i]) * scale_num) / scale_den); - } - } - } - - // -- Phase 3: compute positions using justification ---------------------- - var positions = try allocator.alloc(u16, n); - defer allocator.free(positions); - - { - var total_sizes: u32 = 0; - for (sizes) |s| total_sizes += s; - const total_content: u32 = total_sizes + total_gap; - const free_space: u16 = if (main_total > @as(u16, @intCast(@min(total_content, main_total)))) main_total - @as(u16, @intCast(total_content)) else 0; - - var cursor: u16 = switch (options.justify) { - .start => 0, - .center => free_space / 2, - .end => free_space, - .space_between => 0, - .space_around => 0, - .space_evenly => 0, - }; - - // Compute per-item extra spacing for space_* modes - var between_extra: u16 = 0; - var before_first: u16 = 0; - - switch (options.justify) { - .space_between => { - if (n > 1) { - between_extra = free_space / @as(u16, @intCast(n - 1)); - } - }, - .space_around => { - const slot: u16 = free_space / @as(u16, @intCast(n)); - before_first = slot / 2; - between_extra = slot; - cursor = before_first; - }, - .space_evenly => { - const slot: u16 = free_space / @as(u16, @intCast(n + 1)); - before_first = slot; - between_extra = slot; - cursor = before_first; - }, - else => {}, - } - - for (0..n) |i| { - positions[i] = cursor; - cursor += sizes[i]; - if (i < n - 1) { - cursor += options.gap + between_extra; - } - } - } - - // -- Phase 4: build output Rects ----------------------------------------- - var rects = try allocator.alloc(Rect, n); - - for (0..n) |i| { - const main_pos = positions[i]; - const main_size = sizes[i]; - - const cross_pos: u16 = 0; - const cross_size: u16 = cross_total; - - if (is_row) { - rects[i] = .{ - .x = origin_x + main_pos, - .y = origin_y + cross_pos, - .width = main_size, - .height = cross_size, - }; - } else { - rects[i] = .{ - .x = origin_x + cross_pos, - .y = origin_y + main_pos, - .width = cross_size, - .height = main_size, - }; - } - } - - return rects; -} - -// --------------------------------------------------------------------------- -// Wrapped layout -// --------------------------------------------------------------------------- - -fn layoutWrapped( - allocator: std.mem.Allocator, - total_width: u16, - total_height: u16, - items: []const Item, - options: FlexOptions, -) ![]Rect { - const is_row = options.direction == .row; - const main_total: u16 = if (is_row) total_width else total_height; - - // First pass: figure out which items go on which line - var lines = std.array_list.Managed(LineRange).init(allocator); - defer lines.deinit(); - - var line_start: usize = 0; - var line_used: u32 = 0; - - for (items, 0..) |item, i| { - const item_size = estimateSize(item.constraint, main_total); - const gap_needed: u32 = if (i > line_start) options.gap else 0; - - if (line_used + gap_needed + item_size > main_total and i > line_start) { - try lines.append(.{ .start = line_start, .end = i }); - line_start = i; - line_used = item_size; - } else { - line_used += gap_needed + item_size; - } - } - // Last line - if (line_start < items.len) { - try lines.append(.{ .start = line_start, .end = items.len }); - } - - const num_lines = lines.items.len; - if (num_lines == 0) { - return try allocator.alloc(Rect, 0); - } - - const cross_total: u16 = if (is_row) total_height else total_width; - const per_line: u16 = if (num_lines > 0) cross_total / @as(u16, @intCast(num_lines)) else cross_total; - - var rects = try allocator.alloc(Rect, items.len); - - var cross_cursor: u16 = 0; - for (lines.items) |line| { - const line_items = items[line.start..line.end]; - const line_main: u16 = if (is_row) total_width else per_line; - const line_cross: u16 = per_line; - const line_w: u16 = if (is_row) line_main else line_cross; - const line_h: u16 = if (is_row) line_cross else line_main; - const ox: u16 = if (is_row) 0 else cross_cursor; - const oy: u16 = if (is_row) cross_cursor else 0; - - const line_rects = try layoutLine(allocator, line_w, line_h, line_items, options, ox, oy); - defer allocator.free(line_rects); - - @memcpy(rects[line.start..line.end], line_rects); - cross_cursor += per_line; - } - - return rects; -} - -const LineRange = struct { - start: usize, - end: usize, -}; - -fn estimateSize(constraint: Constraint, total: u16) u32 { - return switch (constraint) { - .fixed => |v| v, - .percentage => |pct| (@as(u32, total) * @as(u32, @min(pct, 100))) / 100, - .min => |v| v, - .max => |v| v, - .ratio => |r| if (r.den == 0) 0 else (@as(u32, total) * r.num) / r.den, - .fill => 1, // minimum estimate for wrapping purposes - }; -} - -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- - -test "basic row layout" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 100, 24, &.{ - .{ .constraint = .{ .fixed = 20 } }, - .{ .constraint = .fill }, - .{ .constraint = .{ .fixed = 30 } }, - }, .{ .direction = .row }); - defer allocator.free(rects); - - try std.testing.expectEqual(@as(usize, 3), rects.len); - try std.testing.expectEqual(@as(u16, 20), rects[0].width); - try std.testing.expectEqual(@as(u16, 30), rects[2].width); - try std.testing.expectEqual(@as(u16, 50), rects[1].width); - try std.testing.expectEqual(@as(u16, 0), rects[0].x); - try std.testing.expectEqual(@as(u16, 20), rects[1].x); - try std.testing.expectEqual(@as(u16, 70), rects[2].x); -} - -test "column layout" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 80, 40, &.{ - .{ .constraint = .{ .fixed = 3 } }, - .{ .constraint = .fill }, - .{ .constraint = .{ .fixed = 1 } }, - }, .{ .direction = .column }); - defer allocator.free(rects); - - try std.testing.expectEqual(@as(u16, 3), rects[0].height); - try std.testing.expectEqual(@as(u16, 36), rects[1].height); - try std.testing.expectEqual(@as(u16, 1), rects[2].height); -} - -test "percentage constraint" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 100, 10, &.{ - .{ .constraint = .{ .percentage = 30 } }, - .{ .constraint = .{ .percentage = 70 } }, - }, .{ .direction = .row }); - defer allocator.free(rects); - - try std.testing.expectEqual(@as(u16, 30), rects[0].width); - try std.testing.expectEqual(@as(u16, 70), rects[1].width); -} - -test "gap spacing" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 100, 10, &.{ - .{ .constraint = .{ .fixed = 20 } }, - .{ .constraint = .{ .fixed = 20 } }, - }, .{ .direction = .row, .gap = 5 }); - defer allocator.free(rects); - - try std.testing.expectEqual(@as(u16, 0), rects[0].x); - try std.testing.expectEqual(@as(u16, 25), rects[1].x); -} - -test "ratio constraint" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 90, 10, &.{ - .{ .constraint = .{ .ratio = .{ .num = 1, .den = 3 } } }, - .{ .constraint = .{ .ratio = .{ .num = 2, .den = 3 } } }, - }, .{ .direction = .row }); - defer allocator.free(rects); - - try std.testing.expectEqual(@as(u16, 30), rects[0].width); - try std.testing.expectEqual(@as(u16, 60), rects[1].width); -} - -test "empty items" { - const allocator = std.testing.allocator; - const rects = try layout(allocator, 80, 24, &.{}, .{}); - defer allocator.free(rects); - try std.testing.expectEqual(@as(usize, 0), rects.len); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig deleted file mode 100644 index 0a2b3d5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/join.zig +++ /dev/null @@ -1,225 +0,0 @@ -//! Layout joining utilities for combining multiple text blocks. -//! Provides horizontal and vertical joining with alignment options. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("measure.zig"); - -/// Vertical alignment for horizontal joins -pub const VAlign = enum { - top, - middle, - bottom, -}; - -/// Horizontal alignment for vertical joins -pub const HAlign = enum { - left, - center, - right, -}; - -/// Join multiple strings horizontally (side by side) -pub fn horizontal(allocator: std.mem.Allocator, valign: VAlign, parts: []const []const u8) ![]const u8 { - if (parts.len == 0) return try allocator.dupe(u8, ""); - if (parts.len == 1) return try allocator.dupe(u8, parts[0]); - - // Calculate dimensions - var max_height: usize = 0; - var widths = try allocator.alloc(usize, parts.len); - defer allocator.free(widths); - - for (parts, 0..) |part, i| { - widths[i] = measure.maxLineWidth(part); - max_height = @max(max_height, measure.height(part)); - } - - if (max_height == 0) max_height = 1; - - // Split all parts into lines - var all_lines = try allocator.alloc([][]const u8, parts.len); - defer { - for (all_lines) |lines| { - allocator.free(lines); - } - allocator.free(all_lines); - } - - for (parts, 0..) |part, i| { - var lines_list = std.array_list.Managed([]const u8).init(allocator); - var iter = std.mem.splitScalar(u8, part, '\n'); - while (iter.next()) |line| { - try lines_list.append(line); - } - all_lines[i] = try lines_list.toOwnedSlice(); - } - - // Build result - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (0..max_height) |row| { - if (row > 0) try writer.writeByte('\n'); - - for (parts, 0..) |_, part_idx| { - const lines = all_lines[part_idx]; - const part_height = lines.len; - const w = widths[part_idx]; - - // Calculate offset based on alignment - const offset: usize = switch (valign) { - .top => 0, - .middle => (max_height - part_height) / 2, - .bottom => max_height - part_height, - }; - - const line_idx = if (row >= offset and row < offset + part_height) - row - offset - else - null; - - if (line_idx) |idx| { - const line = lines[idx]; - try writer.writeAll(line); - // Pad to width - const line_width = measure.width(line); - if (line_width < w) { - for (0..(w - line_width)) |_| { - try writer.writeByte(' '); - } - } - } else { - // Empty line - for (0..w) |_| { - try writer.writeByte(' '); - } - } - } - } - - return result.toOwnedSlice(); -} - -/// Join multiple strings vertically (stacked) -pub fn vertical(allocator: std.mem.Allocator, halign: HAlign, parts: []const []const u8) ![]const u8 { - if (parts.len == 0) return try allocator.dupe(u8, ""); - if (parts.len == 1) return try allocator.dupe(u8, parts[0]); - - // Calculate max width - var max_width: usize = 0; - for (parts) |part| { - max_width = @max(max_width, measure.maxLineWidth(part)); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (parts, 0..) |part, part_idx| { - if (part_idx > 0) try writer.writeByte('\n'); - - var lines = std.mem.splitScalar(u8, part, '\n'); - var first_line = true; - - while (lines.next()) |line| { - if (!first_line) try writer.writeByte('\n'); - first_line = false; - - const line_width = measure.width(line); - const padding = if (max_width > line_width) max_width - line_width else 0; - - switch (halign) { - .left => { - try writer.writeAll(line); - for (0..padding) |_| { - try writer.writeByte(' '); - } - }, - .center => { - const left_pad = padding / 2; - const right_pad = padding - left_pad; - for (0..left_pad) |_| { - try writer.writeByte(' '); - } - try writer.writeAll(line); - for (0..right_pad) |_| { - try writer.writeByte(' '); - } - }, - .right => { - for (0..padding) |_| { - try writer.writeByte(' '); - } - try writer.writeAll(line); - }, - } - } - } - - return result.toOwnedSlice(); -} - -/// Join with a separator -pub fn horizontalSep( - allocator: std.mem.Allocator, - valign: VAlign, - separator: []const u8, - parts: []const []const u8, -) ![]const u8 { - if (parts.len == 0) return try allocator.dupe(u8, ""); - if (parts.len == 1) return try allocator.dupe(u8, parts[0]); - - // Create new parts array with separators - var with_seps = try allocator.alloc([]const u8, parts.len * 2 - 1); - defer allocator.free(with_seps); - - for (parts, 0..) |part, i| { - with_seps[i * 2] = part; - if (i < parts.len - 1) { - with_seps[i * 2 + 1] = separator; - } - } - - return horizontal(allocator, valign, with_seps[0 .. parts.len * 2 - 1]); -} - -/// Join with a separator -pub fn verticalSep( - allocator: std.mem.Allocator, - halign: HAlign, - separator: []const u8, - parts: []const []const u8, -) ![]const u8 { - if (parts.len == 0) return try allocator.dupe(u8, ""); - if (parts.len == 1) return try allocator.dupe(u8, parts[0]); - - // Create new parts array with separators - var with_seps = try allocator.alloc([]const u8, parts.len * 2 - 1); - defer allocator.free(with_seps); - - for (parts, 0..) |part, i| { - with_seps[i * 2] = part; - if (i < parts.len - 1) { - with_seps[i * 2 + 1] = separator; - } - } - - return vertical(allocator, halign, with_seps[0 .. parts.len * 2 - 1]); -} - -test "horizontal join" { - const testing = std.testing; - const alloc = testing.allocator; - - const result = try horizontal(alloc, .top, &[_][]const u8{ "A", "B", "C" }); - defer alloc.free(result); - try testing.expectEqualStrings("ABC", result); -} - -test "vertical join" { - const testing = std.testing; - const alloc = testing.allocator; - - const result = try vertical(alloc, .left, &[_][]const u8{ "A", "B", "C" }); - defer alloc.free(result); - try testing.expectEqualStrings("A\nB\nC", result); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig deleted file mode 100644 index 0232c2b..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layer.zig +++ /dev/null @@ -1,156 +0,0 @@ -//! Layer compositing system for z-ordered UI overlays. -//! Manages a stack of rendered text layers and composites them -//! into a single output with proper z-ordering and transparency. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("measure.zig"); - -/// A single layer in the stack. -pub const Layer = struct { - /// Rendered content string. - content: []const u8, - /// X position (column offset). - x: u16 = 0, - /// Y position (row offset). - y: u16 = 0, - /// Z-index for ordering. Higher = on top. - z: i16 = 0, - /// If true, space characters are transparent (show layer below). - transparent: bool = true, -}; - -/// Composites multiple layers into a single rendered output. -pub const LayerStack = struct { - allocator: std.mem.Allocator, - layers: std.array_list.Managed(Layer), - width: u16 = 80, - height: u16 = 24, - /// Background character for empty cells. - background: u8 = ' ', - - pub fn init(allocator: std.mem.Allocator) LayerStack { - return .{ - .allocator = allocator, - .layers = std.array_list.Managed(Layer).init(allocator), - }; - } - - pub fn deinit(self: *LayerStack) void { - self.layers.deinit(); - } - - pub fn setSize(self: *LayerStack, w: u16, h: u16) void { - self.width = w; - self.height = h; - } - - pub fn push(self: *LayerStack, layer: Layer) !void { - try self.layers.append(layer); - } - - pub fn clear(self: *LayerStack) void { - self.layers.clearRetainingCapacity(); - } - - /// Composite all layers and return the final rendered string. - pub fn render(self: *const LayerStack, allocator: std.mem.Allocator) []const u8 { - const w: usize = self.width; - const h: usize = self.height; - - // Create cell buffer: each cell stores a byte slice (content) and ANSI state - // For simplicity, we use a 2D grid of cells that stores display characters - const grid = allocator.alloc(Cell, w * h) catch return ""; - - // Fill with background - for (grid) |*cell| { - cell.* = .{ .char = self.background, .ansi_prefix = "" }; - } - - // Sort layers by z-index - const sorted = allocator.alloc(Layer, self.layers.items.len) catch return ""; - @memcpy(sorted, self.layers.items); - std.mem.sort(Layer, sorted, {}, struct { - fn lessThan(_: void, a: Layer, b: Layer) bool { - return a.z < b.z; - } - }.lessThan); - - // Paint each layer onto the grid - for (sorted) |layer| { - self.paintLayer(grid, w, h, layer); - } - - // Render grid to string - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (0..h) |row| { - if (row > 0) writer.writeByte('\n') catch {}; - for (0..w) |col| { - const cell = grid[row * w + col]; - if (cell.ansi_prefix.len > 0) { - writer.writeAll(cell.ansi_prefix) catch {}; - writer.writeByte(cell.char) catch {}; - writer.writeAll("\x1b[0m") catch {}; - } else { - writer.writeByte(cell.char) catch {}; - } - } - } - - return result.toArrayList().items; - } - - fn paintLayer(self: *const LayerStack, grid: []Cell, w: usize, h: usize, layer: Layer) void { - _ = self; - const content = layer.content; - var row: usize = layer.y; - var col: usize = layer.x; - var i: usize = 0; - var current_ansi: []const u8 = ""; - - while (i < content.len and row < h) { - if (content[i] == '\n') { - row += 1; - col = layer.x; - i += 1; - continue; - } - - // Detect ANSI escape sequence - if (content[i] == 0x1b and i + 1 < content.len and content[i + 1] == '[') { - const seq_start = i; - i += 2; - while (i < content.len and content[i] != 'm' and content[i] != 'H' and content[i] != 'J' and content[i] != 'K') : (i += 1) {} - if (i < content.len) { - i += 1; - // Check if it's a reset sequence - if (content[seq_start + 2 .. i - 1].len == 1 and content[seq_start + 2] == '0') { - current_ansi = ""; - } else { - current_ansi = content[seq_start..i]; - } - } - continue; - } - - if (col < w) { - const is_transparent = layer.transparent and content[i] == ' ' and current_ansi.len == 0; - if (!is_transparent) { - grid[row * w + col] = .{ - .char = content[i], - .ansi_prefix = current_ansi, - }; - } - col += 1; - } - i += 1; - } - } -}; - -const Cell = struct { - char: u8 = ' ', - ansi_prefix: []const u8 = "", -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig deleted file mode 100644 index 70530a4..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/layout.zig +++ /dev/null @@ -1,41 +0,0 @@ -//! Layout module entry point. -//! Re-exports layout utilities for convenience. - -pub const measure = @import("measure.zig"); -pub const join = @import("join.zig"); -pub const place = @import("place.zig"); -pub const layer = @import("layer.zig"); -pub const flex = @import("flex.zig"); - -// Re-export common types -pub const VAlign = join.VAlign; -pub const HAlign = join.HAlign; -pub const HPosition = place.HPosition; -pub const VPosition = place.VPosition; - -// Convenience functions - -/// Calculate visible width of text -pub fn width(str: []const u8) usize { - return measure.width(str); -} - -/// Calculate height (line count) of text -pub fn height(str: []const u8) usize { - return measure.height(str); -} - -/// Join strings horizontally with top alignment -pub fn joinHorizontal(allocator: @import("std").mem.Allocator, parts: []const []const u8) ![]const u8 { - return join.horizontal(allocator, .top, parts); -} - -/// Join strings vertically with left alignment -pub fn joinVertical(allocator: @import("std").mem.Allocator, parts: []const []const u8) ![]const u8 { - return join.vertical(allocator, .left, parts); -} - -/// Place content centered in a box -pub fn placeCenter(allocator: @import("std").mem.Allocator, w: usize, h: usize, content: []const u8) ![]const u8 { - return place.place(allocator, w, h, .center, .middle, content); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig deleted file mode 100644 index d71d31d..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/measure.zig +++ /dev/null @@ -1,279 +0,0 @@ -//! Text measurement utilities for ANSI-aware width and height calculation. -//! Properly handles ANSI escape sequences and Unicode characters. - -const std = @import("std"); -const Writer = std.Io.Writer; -const unicode = @import("../unicode.zig"); - -/// Calculate the visible width of a string (excluding ANSI escape sequences) -pub fn width(str: []const u8) usize { - var w: usize = 0; - var max_width: usize = 0; - var in_escape = false; - var escape_bracket = false; - - var i: usize = 0; - while (i < str.len) { - const c = str[i]; - - if (c == 0x1b) { - in_escape = true; - escape_bracket = false; - i += 1; - continue; - } - - if (in_escape) { - if (c == '[') { - escape_bracket = true; - } else if (escape_bracket) { - // CSI sequence ends with letter - if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) { - in_escape = false; - escape_bracket = false; - } - } else if (c == ']') { - // OSC sequence - skip until BEL or ST - i += 1; - while (i < str.len and str[i] != 0x07) { - if (str[i] == 0x1b and i + 1 < str.len and str[i + 1] == '\\') { - i += 1; - break; - } - i += 1; - } - in_escape = false; - } else { - // Single-character escape - in_escape = false; - } - i += 1; - continue; - } - - if (c == '\n') { - max_width = @max(max_width, w); - w = 0; - i += 1; - continue; - } - - if (c == '\r' or c == '\t') { - if (c == '\t') { - w += 8 - (w % 8); // Tab stops every 8 characters - } - i += 1; - continue; - } - - // Handle UTF-8 characters - const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; - if (i + byte_len <= str.len) { - const codepoint = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { - w += 1; - i += 1; - continue; - }; - - w += unicode.charWidth(codepoint); - i += byte_len; - } else { - w += 1; - i += 1; - } - } - - return @max(max_width, w); -} - -/// Calculate the height of a string (number of lines) -pub fn height(str: []const u8) usize { - if (str.len == 0) return 0; - - var h: usize = 1; - for (str) |c| { - if (c == '\n') h += 1; - } - return h; -} - -/// Calculate both width and height -pub fn size(str: []const u8) struct { width: usize, height: usize } { - return .{ - .width = width(str), - .height = height(str), - }; -} - -/// Get the display width of a Unicode codepoint using full Unicode tables. -pub fn charWidth(codepoint: u21) usize { - return unicode.charWidth(codepoint); -} - -/// Get the width of a specific line -pub fn lineWidth(str: []const u8, line_num: usize) usize { - var lines = std.mem.splitScalar(u8, str, '\n'); - var current: usize = 0; - - while (lines.next()) |line| { - if (current == line_num) { - return width(line); - } - current += 1; - } - - return 0; -} - -/// Get the maximum line width -pub fn maxLineWidth(str: []const u8) usize { - var max_w: usize = 0; - var lines = std.mem.splitScalar(u8, str, '\n'); - - while (lines.next()) |line| { - max_w = @max(max_w, width(line)); - } - - return max_w; -} - -/// Pad a string to a specific width -pub fn padRight(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { - const current_width = width(str); - if (current_width >= target_width) return try allocator.dupe(u8, str); - - var result: std.array_list.Managed(u8) = .init(allocator); - try result.appendSlice(str); - - for (0..(target_width - current_width)) |_| { - try result.append(' '); - } - - return result.toOwnedSlice(); -} - -/// Pad a string on the left to a specific width -pub fn padLeft(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { - const current_width = width(str); - if (current_width >= target_width) return try allocator.dupe(u8, str); - - var result: std.array_list.Managed(u8) = .init(allocator); - - for (0..(target_width - current_width)) |_| { - try result.append(' '); - } - try result.appendSlice(str); - - return result.toOwnedSlice(); -} - -/// Center a string within a specific width -pub fn center(allocator: std.mem.Allocator, str: []const u8, target_width: usize) ![]const u8 { - const current_width = width(str); - if (current_width >= target_width) return try allocator.dupe(u8, str); - - const total_padding = target_width - current_width; - const left_padding = total_padding / 2; - const right_padding = total_padding - left_padding; - - var result: std.array_list.Managed(u8) = .init(allocator); - - for (0..left_padding) |_| { - try result.append(' '); - } - try result.appendSlice(str); - for (0..right_padding) |_| { - try result.append(' '); - } - - return result.toOwnedSlice(); -} - -/// Truncate string to fit within max width, adding ellipsis if needed -pub fn truncate(allocator: std.mem.Allocator, str: []const u8, max_width: usize) ![]const u8 { - if (max_width == 0) return try allocator.dupe(u8, ""); - if (width(str) <= max_width) return try allocator.dupe(u8, str); - - if (max_width <= 3) { - const result = try allocator.alloc(u8, max_width); - @memset(result, '.'); - return result; - } - - var result: std.array_list.Managed(u8) = .init(allocator); - var w: usize = 0; - var i: usize = 0; - var in_escape = false; - - const target = max_width - 3; // Leave room for "..." - - while (i < str.len and w < target) { - const c = str[i]; - - if (c == 0x1b) { - in_escape = true; - const start = i; - i += 1; - // Copy escape sequence - while (i < str.len) { - if (str[i] == '[') { - i += 1; - while (i < str.len and !((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z'))) { - i += 1; - } - if (i < str.len) i += 1; - break; - } else { - i += 1; - break; - } - } - try result.appendSlice(str[start..i]); - in_escape = false; - continue; - } - - // Regular character - const byte_len = std.unicode.utf8ByteSequenceLength(c) catch 1; - if (i + byte_len <= str.len) { - const codepoint = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { - try result.append(c); - w += 1; - i += 1; - continue; - }; - const cw = unicode.charWidth(codepoint); - // Wide char would exceed target — stop here - if (w + cw > target) break; - try result.appendSlice(str[i..][0..byte_len]); - w += cw; - i += byte_len; - } else { - try result.append(c); - w += 1; - i += 1; - } - } - - try result.appendSlice("..."); - return result.toOwnedSlice(); -} - -test "width calculation" { - const testing = std.testing; - - try testing.expectEqual(@as(usize, 5), width("hello")); - try testing.expectEqual(@as(usize, 5), width("hello\n")); - try testing.expectEqual(@as(usize, 5), width("hello\nworld")); - try testing.expectEqual(@as(usize, 0), width("")); - try testing.expectEqual(@as(usize, 5), width("\x1b[31mhello\x1b[0m")); -} - -test "height calculation" { - const testing = std.testing; - - try testing.expectEqual(@as(usize, 1), height("hello")); - try testing.expectEqual(@as(usize, 2), height("hello\n")); - try testing.expectEqual(@as(usize, 2), height("hello\nworld")); - try testing.expectEqual(@as(usize, 0), height("")); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig deleted file mode 100644 index 249e657..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/layout/place.zig +++ /dev/null @@ -1,388 +0,0 @@ -//! Positioning utilities for placing content within a bounding box. -//! Provides 2D positioning with horizontal and vertical alignment. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("measure.zig"); -const unicode = @import("../unicode.zig"); - -/// Horizontal position -pub const HPosition = enum { - left, - center, - right, -}; - -/// Vertical position -pub const VPosition = enum { - top, - middle, - bottom, -}; - -/// Position content within a bounding box -pub fn place( - allocator: std.mem.Allocator, - width: usize, - height: usize, - hpos: HPosition, - vpos: VPosition, - content: []const u8, -) ![]const u8 { - const content_width = measure.maxLineWidth(content); - const content_height = measure.height(content); - - // If content is larger than box, just return it - if (content_width >= width and content_height >= height) { - return try allocator.dupe(u8, content); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Calculate vertical offset - const v_padding = if (height > content_height) height - content_height else 0; - const top_padding: usize = switch (vpos) { - .top => 0, - .middle => v_padding / 2, - .bottom => v_padding, - }; - const bottom_padding = v_padding - top_padding; - - // Calculate horizontal offset - const h_padding = if (width > content_width) width - content_width else 0; - const left_padding: usize = switch (hpos) { - .left => 0, - .center => h_padding / 2, - .right => h_padding, - }; - - // Write top padding - for (0..top_padding) |_| { - for (0..width) |_| { - try writer.writeByte(' '); - } - try writer.writeByte('\n'); - } - - // Write content lines - var lines = std.mem.splitScalar(u8, content, '\n'); - var first_line = true; - while (lines.next()) |line| { - if (!first_line) try writer.writeByte('\n'); - first_line = false; - - // Left padding - for (0..left_padding) |_| { - try writer.writeByte(' '); - } - - // Content - try writer.writeAll(line); - - // Right padding - const line_width = measure.width(line); - const right_pad = if (width > left_padding + line_width) - width - left_padding - line_width - else - 0; - for (0..right_pad) |_| { - try writer.writeByte(' '); - } - } - - // Write bottom padding - for (0..bottom_padding) |_| { - try writer.writeByte('\n'); - for (0..width) |_| { - try writer.writeByte(' '); - } - } - - return result.toOwnedSlice(); -} - -/// Place content at absolute coordinates -pub fn placeAt( - allocator: std.mem.Allocator, - canvas_width: usize, - canvas_height: usize, - x: usize, - y: usize, - content: []const u8, -) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var lines = std.mem.splitScalar(u8, content, '\n'); - var content_lines = std.array_list.Managed([]const u8).init(allocator); - defer content_lines.deinit(); - - while (lines.next()) |line| { - try content_lines.append(line); - } - - for (0..canvas_height) |row| { - if (row > 0) try writer.writeByte('\n'); - - for (0..canvas_width) |col| { - // Check if this position is within the content - if (row >= y and col >= x) { - const content_row = row - y; - const content_col = col - x; - - if (content_row < content_lines.items.len) { - const line = content_lines.items[content_row]; - if (content_col < measure.width(line)) { - // Find the byte position for this display column - var byte_pos: usize = 0; - var current_col: usize = 0; - while (byte_pos < line.len and current_col < content_col) { - const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_pos]) catch 1; - if (byte_pos + byte_len <= line.len) { - const cp = std.unicode.utf8Decode(line[byte_pos..][0..byte_len]) catch { - byte_pos += 1; - current_col += 1; - continue; - }; - current_col += unicode.charWidth(cp); - } - byte_pos += byte_len; - } - - // If we landed inside a wide character, emit space - if (current_col > content_col) { - try writer.writeByte(' '); - continue; - } - - if (byte_pos < line.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(line[byte_pos]) catch 1; - try writer.writeAll(line[byte_pos..][0..byte_len]); - continue; - } - } - } - } - try writer.writeByte(' '); - } - } - - return result.toOwnedSlice(); -} - -/// Overlay content on top of a base, preserving transparency (spaces in content show base) -pub fn overlay( - allocator: std.mem.Allocator, - base: []const u8, - content: []const u8, - x: usize, - y: usize, -) ![]const u8 { - const base_width = measure.maxLineWidth(base); - const base_height = measure.height(base); - - var base_lines = std.array_list.Managed([]const u8).init(allocator); - defer base_lines.deinit(); - var base_iter = std.mem.splitScalar(u8, base, '\n'); - while (base_iter.next()) |line| { - try base_lines.append(line); - } - - var content_lines = std.array_list.Managed([]const u8).init(allocator); - defer content_lines.deinit(); - var content_iter = std.mem.splitScalar(u8, content, '\n'); - while (content_iter.next()) |line| { - try content_lines.append(line); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - for (0..base_height) |row| { - if (row > 0) try writer.writeByte('\n'); - - const base_line = if (row < base_lines.items.len) base_lines.items[row] else ""; - const content_row = if (row >= y) row - y else base_height; - const content_line = if (content_row < content_lines.items.len) - content_lines.items[content_row] - else - ""; - - for (0..base_width) |col| { - const content_col = if (col >= x) col - x else base_width; - - // Try to get content character - var used_content = false; - if (content_col < measure.width(content_line)) { - // Find byte at display column - var byte_pos: usize = 0; - var current_col: usize = 0; - while (byte_pos < content_line.len and current_col < content_col) { - const byte_len = std.unicode.utf8ByteSequenceLength(content_line[byte_pos]) catch 1; - if (byte_pos + byte_len <= content_line.len) { - const cp = std.unicode.utf8Decode(content_line[byte_pos..][0..byte_len]) catch { - byte_pos += 1; - current_col += 1; - continue; - }; - current_col += unicode.charWidth(cp); - } - byte_pos += byte_len; - } - - // If we landed inside a wide character, emit space - if (current_col > content_col) { - try writer.writeByte(' '); - used_content = true; - } else if (byte_pos < content_line.len and content_line[byte_pos] != ' ') { - const byte_len = std.unicode.utf8ByteSequenceLength(content_line[byte_pos]) catch 1; - try writer.writeAll(content_line[byte_pos..][0..byte_len]); - used_content = true; - } - } - - if (!used_content) { - // Use base character - if (col < measure.width(base_line)) { - var byte_pos: usize = 0; - var current_col: usize = 0; - while (byte_pos < base_line.len and current_col < col) { - const byte_len = std.unicode.utf8ByteSequenceLength(base_line[byte_pos]) catch 1; - if (byte_pos + byte_len <= base_line.len) { - const cp = std.unicode.utf8Decode(base_line[byte_pos..][0..byte_len]) catch { - byte_pos += 1; - current_col += 1; - continue; - }; - current_col += unicode.charWidth(cp); - } - byte_pos += byte_len; - } - - if (current_col > col) { - try writer.writeByte(' '); - } else if (byte_pos < base_line.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(base_line[byte_pos]) catch 1; - try writer.writeAll(base_line[byte_pos..][0..byte_len]); - } else { - try writer.writeByte(' '); - } - } else { - try writer.writeByte(' '); - } - } - } - } - - return result.toOwnedSlice(); -} - -/// Place content with horizontal positioning only (height inferred from content) -pub fn placeHorizontal( - allocator: std.mem.Allocator, - width: usize, - hpos: HPosition, - content: []const u8, -) ![]const u8 { - const content_height = measure.height(content); - return place(allocator, width, content_height, hpos, .top, content); -} - -/// Place content with vertical positioning only (width inferred from content) -pub fn placeVertical( - allocator: std.mem.Allocator, - height: usize, - vpos: VPosition, - content: []const u8, -) ![]const u8 { - const content_width = measure.maxLineWidth(content); - return place(allocator, content_width, height, .left, vpos, content); -} - -/// Position content using float coordinates (0.0 = left/top, 0.5 = center, 1.0 = right/bottom) -pub fn placeFloat( - allocator: std.mem.Allocator, - width: usize, - height: usize, - hpos: f32, - vpos: f32, - content: []const u8, -) ![]const u8 { - const content_width = measure.maxLineWidth(content); - const content_height = measure.height(content); - - // If content is larger than box, just return it - if (content_width >= width and content_height >= height) { - return try allocator.dupe(u8, content); - } - - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - // Calculate offsets from float positions - const h_space = if (width > content_width) width - content_width else 0; - const v_space = if (height > content_height) height - content_height else 0; - - const clamped_h = @max(0.0, @min(1.0, hpos)); - const clamped_v = @max(0.0, @min(1.0, vpos)); - - const left_padding: usize = @intFromFloat(@as(f32, @floatFromInt(h_space)) * clamped_h); - const top_padding: usize = @intFromFloat(@as(f32, @floatFromInt(v_space)) * clamped_v); - const bottom_padding = v_space - top_padding; - - // Write top padding - for (0..top_padding) |_| { - for (0..width) |_| { - try writer.writeByte(' '); - } - try writer.writeByte('\n'); - } - - // Write content lines - var lines = std.mem.splitScalar(u8, content, '\n'); - var first_line = true; - while (lines.next()) |line| { - if (!first_line) try writer.writeByte('\n'); - first_line = false; - - // Left padding - for (0..left_padding) |_| { - try writer.writeByte(' '); - } - - // Content - try writer.writeAll(line); - - // Right padding - const line_width = measure.width(line); - const right_pad = if (width > left_padding + line_width) - width - left_padding - line_width - else - 0; - for (0..right_pad) |_| { - try writer.writeByte(' '); - } - } - - // Write bottom padding - for (0..bottom_padding) |_| { - try writer.writeByte('\n'); - for (0..width) |_| { - try writer.writeByte(' '); - } - } - - return result.toOwnedSlice(); -} - -test "place center" { - const testing = std.testing; - const alloc = testing.allocator; - - const result = try place(alloc, 5, 3, .center, .middle, "X"); - defer alloc.free(result); - - // Expected: 5x3 grid with X in center - try testing.expect(result.len > 0); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig deleted file mode 100644 index 7c96f94..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/root.zig +++ /dev/null @@ -1,386 +0,0 @@ -//! ZigZag - A TUI library for Zig inspired by Bubble Tea and Lipgloss -//! -//! ZigZag provides a framework for building terminal user interfaces using -//! the Elm architecture (Model-Update-View pattern). -//! -//! ## Quick Start -//! -//! ```zig -//! const std = @import("std"); -//! const zz = @import("zigzag"); -//! -//! const Model = struct { -//! count: i32, -//! -//! pub const Msg = union(enum) { -//! key: zz.KeyEvent, -//! }; -//! -//! pub fn init(self: *Model, _: *zz.Context) zz.Cmd(Msg) { -//! self.* = .{ .count = 0 }; -//! return .none; -//! } -//! -//! pub fn update(self: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { -//! switch (msg) { -//! .key => |k| switch (k.key) { -//! .char => |c| if (c == 'q') return .quit, -//! .up => self.count += 1, -//! .down => self.count -= 1, -//! else => {}, -//! }, -//! } -//! return .none; -//! } -//! -//! pub fn view(self: *const Model, ctx: *const zz.Context) []const u8 { -//! return std.fmt.allocPrint(ctx.allocator, "Count: {d}\n\nPress q to quit", .{self.count}) catch "Error"; -//! } -//! }; -//! -//! pub fn main(init: std.process.Init) !void { -//! var program = try zz.Program(Model).init(init.gpa, init.io, init.environ_map); -//! defer program.deinit(); -//! try program.run(); -//! } -//! ``` - -const std = @import("std"); - -// Core -pub const program = @import("core/program.zig"); -pub const Program = program.Program; -pub const Cmd = program.Cmd; -pub const command = @import("core/command.zig"); -pub const async_task = @import("core/async_task.zig"); -pub const AsyncRunner = async_task.AsyncRunner; -pub const SubProgram = @import("core/sub_program.zig").SubProgram; -pub const screen_stack = @import("core/screen_stack.zig"); -pub const ScreenStack = screen_stack.ScreenStack; -pub const Screen = screen_stack.Screen; -pub const ScreenAction = screen_stack.Action; -pub const ScreenHandleResult = screen_stack.HandleResult; -pub const Context = @import("core/context.zig").Context; -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 dev_console = @import("core/dev_console.zig"); -pub const DevConsole = dev_console.DevConsole; -pub const DevConsoleLevel = dev_console.Level; -pub const DevConsoleSink = dev_console.SinkConfig; -pub const fuzzy = @import("core/fuzzy.zig"); -pub const action = @import("core/action.zig"); -pub const Action = action.Action; -pub const ActionRegistry = action.ActionRegistry; -pub const ActionFooter = action.Footer; -pub const animation = @import("core/animation.zig"); -pub const Tween = animation.Tween; -pub const Easing = animation.Easing; -pub const tweenColor = animation.tweenColor; -pub const lerp = animation.lerp; - -// Terminal -pub const terminal = @import("terminal/terminal.zig"); -pub const Terminal = terminal.Terminal; -pub const ansi = terminal.ansi; -pub const screen = terminal.screen; - -// Input -pub const input = struct { - pub const keyboard = @import("input/keyboard.zig"); - pub const mouse = @import("input/mouse.zig"); - pub const keys = @import("input/keys.zig"); -}; -pub const Key = input.keys.Key; -pub const KeyEvent = input.keys.KeyEvent; -pub const Modifiers = input.keys.Modifiers; -pub const MouseEvent = input.mouse.MouseEvent; -pub const MouseButton = input.mouse.Button; -pub const MouseEventType = input.mouse.EventType; -pub const hitbox = @import("input/hitbox.zig"); -pub const HitBox = hitbox.HitBox; -pub const MouseState = hitbox.MouseState; -pub const MouseInteraction = hitbox.Interaction; - -// Style -pub const style = @import("style/style.zig"); -pub const Style = style.Style; -pub const color = @import("style/color.zig"); -pub const Color = color.Color; -pub const border = @import("style/border.zig"); -pub const Border = border.BorderChars; -pub const theme = @import("style/theme.zig"); -pub const Theme = theme.Theme; -pub const Palette = theme.Palette; -pub const AdaptivePalette = theme.AdaptivePalette; -pub const ThemeManager = theme.ThemeManager; - -// Layout -pub const layout = @import("layout/layout.zig"); -pub const measure = @import("layout/measure.zig"); -pub const join = @import("layout/join.zig"); -pub const place = @import("layout/place.zig"); -pub const flex = @import("layout/flex.zig"); -pub const Flex = flex; -pub const FlexConstraint = flex.Constraint; -pub const FlexItem = flex.Item; -pub const FlexOptions = flex.FlexOptions; -pub const FlexRect = flex.Rect; - -// Accessibility -pub const accessibility = @import("accessibility.zig"); -pub const a11y = accessibility; -pub const ContrastLevel = accessibility.ContrastLevel; -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; - pub const TextArea = @import("components/text_area.zig").TextArea; - pub const List = @import("components/list.zig").List; - pub const Viewport = @import("components/viewport.zig").Viewport; - pub const Progress = @import("components/progress.zig").Progress; - pub const Spinner = @import("components/spinner.zig").Spinner; - pub const Table = @import("components/table.zig").Table; - pub const data_table = @import("components/data_table.zig"); - pub const DataTable = data_table.DataTable; - pub const DataColumn = data_table.Column; - pub const DataAlign = data_table.Align; - pub const Paginator = @import("components/paginator.zig").Paginator; - pub const Help = @import("components/help.zig").Help; - pub const Timer = @import("components/timer.zig").Timer; - pub const FilePicker = @import("components/file_picker.zig").FilePicker; - pub const Tree = @import("components/tree.zig").Tree; - pub const StyledList = @import("components/styled_list.zig").StyledList; - pub const Sparkline = @import("components/sparkline.zig").Sparkline; - pub const charting = @import("components/charting.zig"); - pub const canvas = @import("components/canvas.zig"); - pub const Canvas = canvas.Canvas; - pub const braille_canvas = @import("components/braille_canvas.zig"); - pub const BrailleCanvas = braille_canvas.BrailleCanvas; - pub const chart = @import("components/chart.zig"); - pub const Chart = chart.Chart; - pub const BarChart = @import("components/bar_chart.zig").BarChart; - pub const notification = @import("components/notification.zig"); - pub const Notification = notification.Notification; - pub const Confirm = @import("components/confirm.zig").Confirm; - pub const modal = @import("components/modal.zig"); - pub const Modal = modal.Modal; - pub const tooltip = @import("components/tooltip.zig"); - pub const Tooltip = tooltip.Tooltip; - pub const focus = @import("components/focus.zig"); - pub const tab_group = @import("components/tab_group.zig"); - pub const TabGroup = tab_group.TabGroup; - pub const slider = @import("components/slider.zig"); - pub const Slider = slider.Slider; - pub const SliderStyle = slider.SliderStyle; - pub const MenuBar = @import("components/menu_bar.zig").MenuBar; - pub const checkbox = @import("components/checkbox.zig"); - pub const Checkbox = checkbox.Checkbox; - 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; - pub const diff_view = @import("components/diff_view.zig"); - pub const DiffView = diff_view.DiffView; - pub const code_view = @import("components/code_view.zig"); - pub const CodeView = code_view.CodeView; - pub const sortable_table = @import("components/sortable_table.zig"); - pub const SortableTable = sortable_table.SortableTable; - pub const virtual_list = @import("components/virtual_list.zig"); - pub const VirtualList = virtual_list.VirtualList; - pub const Calendar = @import("components/calendar.zig").Calendar; - 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; - 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; - 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; - 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; - pub const rich_log = @import("components/rich_log.zig"); - pub const RichLog = rich_log.RichLog; - pub const RichLogLevel = rich_log.Level; - pub const RichLogEntry = rich_log.Entry; -}; - -// Re-export commonly used components at top level -pub const TextInput = components.TextInput; -pub const TextArea = components.TextArea; -pub const List = components.List; -pub const Viewport = components.Viewport; -pub const Progress = components.Progress; -pub const Spinner = components.Spinner; -pub const Table = components.Table; -pub const DataTable = components.DataTable; -pub const DataColumn = components.DataColumn; -pub const Tree = components.Tree; -pub const StyledList = components.StyledList; -pub const Sparkline = components.Sparkline; -pub const Canvas = components.Canvas; -pub const BrailleCanvas = components.BrailleCanvas; -pub const Chart = components.Chart; -pub const BarChart = components.BarChart; -pub const Notification = components.Notification; -pub const Confirm = components.Confirm; -pub const Modal = components.Modal; -pub const Tooltip = components.Tooltip; -pub const TabGroup = components.TabGroup; -pub const Slider = components.Slider; -pub const SliderStyle = components.SliderStyle; -pub const MenuBar = components.MenuBar; -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; -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; -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; -pub const SplitPane = components.SplitPane; -pub const CommandPalette = components.CommandPalette; -pub const RichLog = components.RichLog; -pub const RichLogLevel = components.RichLogLevel; -pub const Command = components.Command; - -// Focus management -pub const FocusGroup = components.focus.FocusGroup; -pub const FocusStyle = components.focus.FocusStyle; -pub const KeyBind = components.focus.KeyBind; -pub const isFocusable = components.focus.isFocusable; -pub const TabChange = components.tab_group.Change; -pub const TabChangeReason = components.tab_group.ChangeReason; -pub const TabKeyResult = components.tab_group.KeyResult; -pub const TabKeyBind = components.tab_group.KeyBind; - -// Keybinding management -pub const keybinding = @import("components/keybinding.zig"); -pub const KeyBinding = keybinding.KeyBinding; -pub const KeyMap = keybinding.KeyMap; - -// Utility functions -pub fn joinHorizontal(allocator: std.mem.Allocator, parts: []const []const u8) ![]const u8 { - return join.horizontal(allocator, .top, parts); -} - -pub fn joinVertical(allocator: std.mem.Allocator, parts: []const []const u8) ![]const u8 { - return join.vertical(allocator, .left, parts); -} - -pub fn width(str: []const u8) usize { - return measure.width(str); -} - -pub fn height(str: []const u8) usize { - return measure.height(str); -} - -pub fn placeHorizontal(allocator: std.mem.Allocator, w: usize, hpos: place.HPosition, content: []const u8) ![]const u8 { - return place.placeHorizontal(allocator, w, hpos, content); -} - -pub fn placeVertical(allocator: std.mem.Allocator, h: usize, vpos: place.VPosition, content: []const u8) ![]const u8 { - return place.placeVertical(allocator, h, vpos, content); -} - -pub fn placeFloat(allocator: std.mem.Allocator, w: usize, h: usize, hpos: f32, vpos: f32, content: []const u8) ![]const u8 { - return place.placeFloat(allocator, w, h, hpos, vpos, content); -} - -// Image types -pub const ImageFile = command.ImageFile; -pub const ImageData = command.ImageData; -pub const ImagePlacement = command.ImagePlacement; -pub const ImageProtocol = command.ImageProtocol; -pub const ImageFormat = command.ImageFormat; -pub const ImageSource = command.ImageSource; -pub const CacheImage = command.CacheImage; -pub const PlaceCachedImage = command.PlaceCachedImage; -pub const DeleteImage = command.DeleteImage; -pub const ImageCapabilities = terminal.ImageCapabilities; -pub const Osc52Target = terminal.Osc52Target; -pub const Osc52Passthrough = terminal.Osc52Passthrough; -pub const Osc52Config = terminal.Osc52Config; -pub const Osc52WriteOptions = terminal.Osc52WriteOptions; -pub const Osc52ReadOptions = terminal.Osc52ReadOptions; -pub const OscTerminator = terminal.ansi.OscTerminator; - -// Color utilities -pub const ColorProfile = color.ColorProfile; -pub const AdaptiveColor = color.AdaptiveColor; -pub const CompleteColor = color.CompleteColor; -pub const CompleteAdaptiveColor = color.CompleteAdaptiveColor; - -// Overflow -pub const Overflow = style.Overflow; - -// Style utilities -pub const StyleRange = style.StyleRange; -pub const renderWithRanges = style.renderWithRanges; -pub const renderWithHighlights = style.renderWithHighlights; -pub const transforms = style.transforms; -pub const compress = @import("style/compress.zig"); -pub const StyleState = compress.StyleState; -pub const compressAnsi = compress.compressAnsi; - -// Progress helpers -pub const interpolateColor = @import("components/progress.zig").interpolateColor; -pub const PlotPoint = components.charting.Point; -pub const PlotRange = components.charting.DataRange; -pub const PlotMarker = components.charting.Marker; -pub const GraphType = components.chart.GraphType; -pub const ChartInterpolation = components.chart.Interpolation; -pub const Axis = components.chart.Axis; -pub const AxisLabel = components.chart.AxisLabel; -pub const ChartDataset = components.chart.Dataset; -pub const LegendPosition = components.chart.LegendPosition; -pub const Bar = @import("components/bar_chart.zig").Bar; -pub const ChartOrientation = components.charting.Orientation; -pub const SparkSummary = @import("components/sparkline.zig").Summary; - -test { - std.testing.refAllDecls(@This()); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig deleted file mode 100644 index e55c292..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/border.zig +++ /dev/null @@ -1,303 +0,0 @@ -//! Border styles for terminal UI elements. -//! Provides various border character sets and drawing functions. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("../layout/measure.zig"); - -/// Border character set -pub const BorderChars = struct { - top_left: []const u8, - top_right: []const u8, - bottom_left: []const u8, - bottom_right: []const u8, - horizontal: []const u8, - vertical: []const u8, - middle_left: []const u8, - middle_right: []const u8, - middle_top: []const u8, - middle_bottom: []const u8, - cross: []const u8, - - /// No border - pub const none = BorderChars{ - .top_left = "", - .top_right = "", - .bottom_left = "", - .bottom_right = "", - .horizontal = "", - .vertical = "", - .middle_left = "", - .middle_right = "", - .middle_top = "", - .middle_bottom = "", - .cross = "", - }; - - /// Normal single-line border - pub const normal = BorderChars{ - .top_left = "┌", - .top_right = "┐", - .bottom_left = "└", - .bottom_right = "┘", - .horizontal = "─", - .vertical = "│", - .middle_left = "├", - .middle_right = "┤", - .middle_top = "┬", - .middle_bottom = "┴", - .cross = "┼", - }; - - /// Rounded corners - pub const rounded = BorderChars{ - .top_left = "╭", - .top_right = "╮", - .bottom_left = "╰", - .bottom_right = "╯", - .horizontal = "─", - .vertical = "│", - .middle_left = "├", - .middle_right = "┤", - .middle_top = "┬", - .middle_bottom = "┴", - .cross = "┼", - }; - - /// Double-line border - pub const double = BorderChars{ - .top_left = "╔", - .top_right = "╗", - .bottom_left = "╚", - .bottom_right = "╝", - .horizontal = "═", - .vertical = "║", - .middle_left = "╠", - .middle_right = "╣", - .middle_top = "╦", - .middle_bottom = "╩", - .cross = "╬", - }; - - /// Thick/bold border - pub const thick = BorderChars{ - .top_left = "┏", - .top_right = "┓", - .bottom_left = "┗", - .bottom_right = "┛", - .horizontal = "━", - .vertical = "┃", - .middle_left = "┣", - .middle_right = "┫", - .middle_top = "┳", - .middle_bottom = "┻", - .cross = "╋", - }; - - /// ASCII-only border (compatible with all terminals) - pub const ascii = BorderChars{ - .top_left = "+", - .top_right = "+", - .bottom_left = "+", - .bottom_right = "+", - .horizontal = "-", - .vertical = "|", - .middle_left = "+", - .middle_right = "+", - .middle_top = "+", - .middle_bottom = "+", - .cross = "+", - }; - - /// Block border using full block characters - pub const block = BorderChars{ - .top_left = "█", - .top_right = "█", - .bottom_left = "█", - .bottom_right = "█", - .horizontal = "█", - .vertical = "█", - .middle_left = "█", - .middle_right = "█", - .middle_top = "█", - .middle_bottom = "█", - .cross = "█", - }; - - /// Hidden border (uses spaces) - pub const hidden = BorderChars{ - .top_left = " ", - .top_right = " ", - .bottom_left = " ", - .bottom_right = " ", - .horizontal = " ", - .vertical = " ", - .middle_left = " ", - .middle_right = " ", - .middle_top = " ", - .middle_bottom = " ", - .cross = " ", - }; - - /// Dashed border - pub const dashed = BorderChars{ - .top_left = "┌", - .top_right = "┐", - .bottom_left = "└", - .bottom_right = "┘", - .horizontal = "╌", - .vertical = "╎", - .middle_left = "├", - .middle_right = "┤", - .middle_top = "┬", - .middle_bottom = "┴", - .cross = "┼", - }; - - /// Dotted border - pub const dotted = BorderChars{ - .top_left = "┌", - .top_right = "┐", - .bottom_left = "└", - .bottom_right = "┘", - .horizontal = "┈", - .vertical = "┊", - .middle_left = "├", - .middle_right = "┤", - .middle_top = "┬", - .middle_bottom = "┴", - .cross = "┼", - }; - - /// Inner half block border (uses inner half-block characters) - pub const inner_half_block = BorderChars{ - .top_left = "▗", - .top_right = "▖", - .bottom_left = "▝", - .bottom_right = "▘", - .horizontal = "▄", - .vertical = "▐", - .middle_left = "▐", - .middle_right = "▌", - .middle_top = "▄", - .middle_bottom = "▀", - .cross = "█", - }; - - /// Outer half block border (uses outer half-block characters) - pub const outer_half_block = BorderChars{ - .top_left = "▛", - .top_right = "▜", - .bottom_left = "▙", - .bottom_right = "▟", - .horizontal = "▀", - .vertical = "▌", - .middle_left = "▌", - .middle_right = "▐", - .middle_top = "▀", - .middle_bottom = "▄", - .cross = "█", - }; - - /// Markdown-style border (uses pipe and dashes) - pub const markdown = BorderChars{ - .top_left = "|", - .top_right = "|", - .bottom_left = "|", - .bottom_right = "|", - .horizontal = "-", - .vertical = "|", - .middle_left = "|", - .middle_right = "|", - .middle_top = "|", - .middle_bottom = "|", - .cross = "|", - }; -}; - -/// Sides specification for borders -pub const Sides = struct { - top: bool = true, - right: bool = true, - bottom: bool = true, - left: bool = true, - - pub const all = Sides{}; - pub const horizontal_only = Sides{ .left = false, .right = false }; - pub const vertical_only = Sides{ .top = false, .bottom = false }; - pub const top_only = Sides{ .right = false, .bottom = false, .left = false }; - pub const bottom_only = Sides{ .top = false, .right = false, .left = false }; - pub const left_only = Sides{ .top = false, .right = false, .bottom = false }; - pub const right_only = Sides{ .top = false, .bottom = false, .left = false }; - pub const none = Sides{ .top = false, .right = false, .bottom = false, .left = false }; -}; - -/// Draw a border around content -pub fn drawBorder( - allocator: std.mem.Allocator, - content: []const u8, - chars: BorderChars, - sides: Sides, - width: usize, - height: usize, -) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - const inner_width = if (sides.left and sides.right) width -| 2 else if (sides.left or sides.right) width -| 1 else width; - - // Top border - if (sides.top) { - if (sides.left) try writer.writeAll(chars.top_left); - for (0..inner_width) |_| { - try writer.writeAll(chars.horizontal); - } - if (sides.right) try writer.writeAll(chars.top_right); - try writer.writeByte('\n'); - } - - // Content lines with side borders - var lines = std.mem.splitScalar(u8, content, '\n'); - var line_count: usize = 0; - while (lines.next()) |line| : (line_count += 1) { - if (sides.left) try writer.writeAll(chars.vertical); - - // Write the line, padding to inner_width - const visible_width = visibleWidth(line); - try writer.writeAll(line); - if (visible_width < inner_width) { - for (0..(inner_width - visible_width)) |_| { - try writer.writeByte(' '); - } - } - - if (sides.right) try writer.writeAll(chars.vertical); - try writer.writeByte('\n'); - } - - // Pad remaining lines if needed - while (line_count < height -| (if (sides.top) @as(usize, 1) else 0) -| (if (sides.bottom) @as(usize, 1) else 0)) : (line_count += 1) { - if (sides.left) try writer.writeAll(chars.vertical); - for (0..inner_width) |_| { - try writer.writeByte(' '); - } - if (sides.right) try writer.writeAll(chars.vertical); - try writer.writeByte('\n'); - } - - // Bottom border - if (sides.bottom) { - if (sides.left) try writer.writeAll(chars.bottom_left); - for (0..inner_width) |_| { - try writer.writeAll(chars.horizontal); - } - if (sides.right) try writer.writeAll(chars.bottom_right); - } - - return result.toOwnedSlice(); -} - -/// Calculate visible width (excluding ANSI sequences), with proper Unicode width. -fn visibleWidth(str: []const u8) usize { - return measure.width(str); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig deleted file mode 100644 index 5ad9eb5..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/color.zig +++ /dev/null @@ -1,310 +0,0 @@ -//! Color types for terminal styling. -//! Supports ANSI 16, 256, and TrueColor (24-bit) colors. - -const std = @import("std"); -const Writer = std.Io.Writer; -const builtin = @import("builtin"); -const ansi = @import("../terminal/ansi.zig"); - -/// Color representation supporting multiple color modes -pub const Color = union(enum) { - /// No color (use terminal default) - none, - - /// Basic ANSI colors (0-15) - ansi: AnsiColor, - - /// 256-color palette (0-255) - ansi256: u8, - - /// True color (24-bit RGB) - rgb: RGB, - - pub const RGB = struct { - r: u8, - g: u8, - b: u8, - }; - - // Basic ANSI colors - pub const black: Color = .{ .ansi = .black }; - pub const red: Color = .{ .ansi = .red }; - pub const green: Color = .{ .ansi = .green }; - pub const yellow: Color = .{ .ansi = .yellow }; - pub const blue: Color = .{ .ansi = .blue }; - pub const magenta: Color = .{ .ansi = .magenta }; - pub const cyan: Color = .{ .ansi = .cyan }; - pub const white: Color = .{ .ansi = .white }; - - // Bright ANSI colors - pub const brightBlack: Color = .{ .ansi = .bright_black }; - pub const brightRed: Color = .{ .ansi = .bright_red }; - pub const brightGreen: Color = .{ .ansi = .bright_green }; - pub const brightYellow: Color = .{ .ansi = .bright_yellow }; - pub const brightBlue: Color = .{ .ansi = .bright_blue }; - pub const brightMagenta: Color = .{ .ansi = .bright_magenta }; - pub const brightCyan: Color = .{ .ansi = .bright_cyan }; - pub const brightWhite: Color = .{ .ansi = .bright_white }; - - /// Create a color from RGB values - pub fn fromRgb(r: u8, g: u8, b: u8) Color { - return .{ .rgb = .{ .r = r, .g = g, .b = b } }; - } - - /// Create a color from a hex string (e.g., "#FF5733" or "FF5733") - pub fn hex(str: []const u8) Color { - const s = if (str.len > 0 and str[0] == '#') str[1..] else str; - - if (s.len != 6) return .none; - - const r = std.fmt.parseInt(u8, s[0..2], 16) catch return .none; - const g = std.fmt.parseInt(u8, s[2..4], 16) catch return .none; - const b = std.fmt.parseInt(u8, s[4..6], 16) catch return .none; - - return .{ .rgb = .{ .r = r, .g = g, .b = b } }; - } - - /// Create a color from the 256-color palette - pub fn color256(n: u8) Color { - return .{ .ansi256 = n }; - } - - /// Create a grayscale color (0-23, where 0 is dark and 23 is light) - pub fn gray(level: u8) Color { - if (level > 23) return .{ .ansi256 = 255 }; - return .{ .ansi256 = 232 + level }; - } - - /// Check if this is a "no color" value - pub fn isNone(self: Color) bool { - return self == .none; - } - - /// Convert to RGB (approximating ANSI colors) - pub fn toRgb(self: Color) ?RGB { - return switch (self) { - .none => null, - .rgb => |c| c, - .ansi => |c| c.toRgb(), - .ansi256 => |n| ansi256ToRgb(n), - }; - } - - /// Write foreground color ANSI sequence - pub fn writeFg(self: Color, writer: *Writer) !void { - switch (self) { - .none => {}, - .ansi => |c| try writer.print(ansi.CSI ++ "{d}m", .{c.fgCode()}), - .ansi256 => |n| try ansi.fg256(writer, n), - .rgb => |c| try ansi.fgRgb(writer, c.r, c.g, c.b), - } - } - - /// Write background color ANSI sequence - pub fn writeBg(self: Color, writer: *Writer) !void { - switch (self) { - .none => {}, - .ansi => |c| try writer.print(ansi.CSI ++ "{d}m", .{c.bgCode()}), - .ansi256 => |n| try ansi.bg256(writer, n), - .rgb => |c| try ansi.bgRgb(writer, c.r, c.g, c.b), - } - } - - /// Calculate contrast ratio with another color - pub fn contrastRatio(self: Color, other: Color) f32 { - const rgb1 = self.toRgb() orelse return 1.0; - const rgb2 = other.toRgb() orelse return 1.0; - - const l1 = relativeLuminance(rgb1); - const l2 = relativeLuminance(rgb2); - - const lighter = @max(l1, l2); - const darker = @min(l1, l2); - - return (lighter + 0.05) / (darker + 0.05); - } - - fn relativeLuminance(c: RGB) f32 { - const r = gammaCorrect(@as(f32, @floatFromInt(c.r)) / 255.0); - const g = gammaCorrect(@as(f32, @floatFromInt(c.g)) / 255.0); - const b = gammaCorrect(@as(f32, @floatFromInt(c.b)) / 255.0); - return 0.2126 * r + 0.7152 * g + 0.0722 * b; - } - - fn gammaCorrect(v: f32) f32 { - return if (v <= 0.03928) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4); - } -}; - -/// Basic ANSI colors -pub const AnsiColor = enum(u8) { - black = 0, - red = 1, - green = 2, - yellow = 3, - blue = 4, - magenta = 5, - cyan = 6, - white = 7, - bright_black = 8, - bright_red = 9, - bright_green = 10, - bright_yellow = 11, - bright_blue = 12, - bright_magenta = 13, - bright_cyan = 14, - bright_white = 15, - - pub fn fgCode(self: AnsiColor) u8 { - const base: u8 = @intFromEnum(self); - return if (base < 8) 30 + base else 90 + base - 8; - } - - pub fn bgCode(self: AnsiColor) u8 { - const base: u8 = @intFromEnum(self); - return if (base < 8) 40 + base else 100 + base - 8; - } - - pub fn toRgb(self: AnsiColor) Color.RGB { - return switch (self) { - .black => .{ .r = 0, .g = 0, .b = 0 }, - .red => .{ .r = 128, .g = 0, .b = 0 }, - .green => .{ .r = 0, .g = 128, .b = 0 }, - .yellow => .{ .r = 128, .g = 128, .b = 0 }, - .blue => .{ .r = 0, .g = 0, .b = 128 }, - .magenta => .{ .r = 128, .g = 0, .b = 128 }, - .cyan => .{ .r = 0, .g = 128, .b = 128 }, - .white => .{ .r = 192, .g = 192, .b = 192 }, - .bright_black => .{ .r = 128, .g = 128, .b = 128 }, - .bright_red => .{ .r = 255, .g = 0, .b = 0 }, - .bright_green => .{ .r = 0, .g = 255, .b = 0 }, - .bright_yellow => .{ .r = 255, .g = 255, .b = 0 }, - .bright_blue => .{ .r = 0, .g = 0, .b = 255 }, - .bright_magenta => .{ .r = 255, .g = 0, .b = 255 }, - .bright_cyan => .{ .r = 0, .g = 255, .b = 255 }, - .bright_white => .{ .r = 255, .g = 255, .b = 255 }, - }; - } -}; - -/// Convert 256-color index to RGB -fn ansi256ToRgb(n: u8) Color.RGB { - if (n < 16) { - // Standard colors - return @as(AnsiColor, @enumFromInt(n)).toRgb(); - } else if (n < 232) { - // 6x6x6 color cube - const idx = n - 16; - const r: u8 = @intCast((idx / 36) % 6); - const g: u8 = @intCast((idx / 6) % 6); - const b: u8 = @intCast(idx % 6); - return .{ - .r = if (r == 0) 0 else r * 40 + 55, - .g = if (g == 0) 0 else g * 40 + 55, - .b = if (b == 0) 0 else b * 40 + 55, - }; - } else { - // Grayscale - const gray: u8 = (n - 232) * 10 + 8; - return .{ .r = gray, .g = gray, .b = gray }; - } -} - -/// Adaptive color that changes based on terminal capabilities -pub const AdaptiveColor = struct { - /// Color for terminals with true color support - true_color: Color, - /// Fallback for 256-color terminals - color_256: Color, - /// Fallback for basic 16-color terminals - ansi: Color, - - pub fn resolve(self: AdaptiveColor, supports_true_color: bool, supports_256: bool) Color { - if (supports_true_color) return self.true_color; - if (supports_256) return self.color_256; - return self.ansi; - } -}; - -/// Complete color for foreground and background -pub const CompleteColor = struct { - fg: Color = .none, - bg: Color = .none, -}; - -/// Complete adaptive color that changes based on terminal background -pub const CompleteAdaptiveColor = struct { - light: CompleteColor, - dark: CompleteColor, - - pub fn resolve(self: CompleteAdaptiveColor, is_dark: bool) CompleteColor { - return if (is_dark) self.dark else self.light; - } -}; - -/// Color profile representing terminal color capabilities -pub const ColorProfile = enum { - ascii, - ansi, - ansi256, - true_color, - - /// Detect terminal color profile from the supplied environment. - pub fn detect(environ_map: *const std.process.Environ.Map) ColorProfile { - if (comptime builtin.os.tag == .windows) { - // Windows Terminal supports true color VT sequences - return .true_color; - } - - if (environ_map.get("NO_COLOR")) |_| { - return .ascii; - } - - if (environ_map.get("COLORTERM")) |ct| { - if (std.mem.eql(u8, ct, "truecolor") or std.mem.eql(u8, ct, "24bit")) { - return .true_color; - } - } - - if (environ_map.get("TERM")) |term| { - if (std.mem.indexOf(u8, term, "256color") != null) { - return .ansi256; - } - } - - return .ansi; - } - - /// Check if this profile supports true color - pub fn supportsTrueColor(self: ColorProfile) bool { - return self == .true_color; - } - - /// Check if this profile supports 256 colors - pub fn supports256(self: ColorProfile) bool { - return self == .true_color or self == .ansi256; - } - - /// Check if this profile supports any color - pub fn supportsColor(self: ColorProfile) bool { - return self != .ascii; - } -}; - -/// Detect if terminal has a dark background using the supplied environment. -pub fn hasDarkBackground(environ_map: *const std.process.Environ.Map) bool { - if (comptime builtin.os.tag == .windows) { - return true; - } - - if (environ_map.get("COLORFGBG")) |val| { - // Format: "foreground;background" - if (std.mem.lastIndexOfScalar(u8, val, ';')) |idx| { - const bg_str = val[idx + 1 ..]; - const bg_num = std.fmt.parseInt(u8, bg_str, 10) catch return true; - // Low numbers typically mean dark background - return bg_num < 8; - } - } - return true; // Default to dark -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig deleted file mode 100644 index 7a3ec97..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/compress.zig +++ /dev/null @@ -1,156 +0,0 @@ -//! ANSI output compression utilities. -//! Reduces ANSI escape sequence overhead by tracking terminal state and emitting only diffs. - -const std = @import("std"); -const Writer = std.Io.Writer; -const ansi = @import("../terminal/ansi.zig"); - -/// Tracks the current terminal style state for efficient transitions -pub const StyleState = struct { - bold: bool = false, - dim: bool = false, - italic: bool = false, - underline: bool = false, - blink: bool = false, - reverse: bool = false, - strikethrough: bool = false, - fg_set: bool = false, - bg_set: bool = false, - fg_r: u8 = 0, - fg_g: u8 = 0, - fg_b: u8 = 0, - bg_r: u8 = 0, - bg_g: u8 = 0, - bg_b: u8 = 0, - fg_ansi: ?u8 = null, - bg_ansi: ?u8 = null, - - /// Reset to default state - pub fn reset(self: *StyleState) void { - self.* = .{}; - } - - /// Emit only the ANSI escape sequences needed to transition to the target state - pub fn transitionTo(self: *StyleState, writer: *Writer, target: StyleState) !void { - // If target is fully default, just emit reset - if (!target.bold and !target.dim and !target.italic and !target.underline and - !target.blink and !target.reverse and !target.strikethrough and - !target.fg_set and !target.bg_set) - { - if (self.bold or self.dim or self.italic or self.underline or - self.blink or self.reverse or self.strikethrough or - self.fg_set or self.bg_set) - { - try writer.writeAll(ansi.reset); - self.reset(); - } - return; - } - - // Check if we need a full reset first (any attribute going from on to off) - const needs_reset = (self.bold and !target.bold) or - (self.dim and !target.dim) or - (self.italic and !target.italic) or - (self.underline and !target.underline) or - (self.blink and !target.blink) or - (self.reverse and !target.reverse) or - (self.strikethrough and !target.strikethrough); - - if (needs_reset) { - try writer.writeAll(ansi.reset); - self.reset(); - } - - // Now emit only the attributes that need to be turned on - if (target.bold and !self.bold) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); - if (target.dim and !self.dim) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); - if (target.italic and !self.italic) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); - if (target.underline and !self.underline) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - if (target.blink and !self.blink) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); - if (target.reverse and !self.reverse) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); - if (target.strikethrough and !self.strikethrough) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - - // Foreground color - if (target.fg_set) { - const fg_changed = !self.fg_set or - self.fg_r != target.fg_r or self.fg_g != target.fg_g or self.fg_b != target.fg_b or - (self.fg_ansi != target.fg_ansi); - if (fg_changed) { - if (target.fg_ansi) |a| { - try writer.print(ansi.CSI ++ "{d}m", .{a}); - } else { - try writer.print(ansi.CSI ++ "38;2;{d};{d};{d}m", .{ target.fg_r, target.fg_g, target.fg_b }); - } - } - } else if (self.fg_set) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.fg_default}); - } - - // Background color - if (target.bg_set) { - const bg_changed = !self.bg_set or - self.bg_r != target.bg_r or self.bg_g != target.bg_g or self.bg_b != target.bg_b or - (self.bg_ansi != target.bg_ansi); - if (bg_changed) { - if (target.bg_ansi) |a| { - try writer.print(ansi.CSI ++ "{d}m", .{a}); - } else { - try writer.print(ansi.CSI ++ "48;2;{d};{d};{d}m", .{ target.bg_r, target.bg_g, target.bg_b }); - } - } - } else if (self.bg_set) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bg_default}); - } - - // Update state - self.* = target; - } -}; - -/// Post-process an ANSI string to remove redundant escape sequences. -/// Strips consecutive resets and duplicate attribute settings. -pub fn compressAnsi(allocator: std.mem.Allocator, input: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var i: usize = 0; - var last_was_reset = false; - - while (i < input.len) { - // Check for ESC[ - if (i + 1 < input.len and input[i] == 0x1b and input[i + 1] == '[') { - // Find the end of the CSI sequence - var seq_end = i + 2; - while (seq_end < input.len) { - const c = input[seq_end]; - if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) { - seq_end += 1; - break; - } - seq_end += 1; - } - - const seq = input[i..seq_end]; - - // Check for reset sequence - if (std.mem.eql(u8, seq, ansi.reset)) { - if (!last_was_reset) { - try writer.writeAll(seq); - last_was_reset = true; - } - // Skip duplicate resets - } else { - try writer.writeAll(seq); - last_was_reset = false; - } - - i = seq_end; - } else { - try writer.writeByte(input[i]); - last_was_reset = false; - i += 1; - } - } - - return result.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig deleted file mode 100644 index 179a98a..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/overflow.zig +++ /dev/null @@ -1,287 +0,0 @@ -//! Text overflow handling for the ZigZag TUI framework. -//! Provides configurable overflow policies: clip, ellipsis, word-wrap, char-wrap. - -const std = @import("std"); -const Writer = std.Io.Writer; -const measure = @import("../layout/measure.zig"); - -/// Overflow policy for text that exceeds width constraints. -pub const Overflow = enum { - /// No overflow handling (default). - visible, - /// Clip text without indicator. - hidden, - /// Truncate with ellipsis character. - ellipsis, - /// Wrap at word boundaries. - word_wrap, - /// Wrap at character boundaries. - char_wrap, -}; - -/// Apply an overflow policy to text with a given max width. -/// Handles each line independently. ANSI-aware. -pub fn applyOverflow( - allocator: std.mem.Allocator, - text: []const u8, - max_width: u16, - policy: Overflow, -) ![]const u8 { - if (policy == .visible or max_width == 0) return text; - - var result: std.array_list.Managed(u8) = .init(allocator); - - var lines = std.mem.splitScalar(u8, text, '\n'); - var first_line = true; - while (lines.next()) |line| { - if (!first_line) try result.append('\n'); - first_line = false; - - switch (policy) { - .hidden => try applyClip(&result, line, max_width), - .ellipsis => try applyEllipsis(&result, line, max_width), - .word_wrap => try applyWordWrap(&result, line, max_width), - .char_wrap => try applyCharWrap(&result, line, max_width), - .visible => unreachable, - } - } - - return result.toOwnedSlice(); -} - -fn applyClip(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { - var visible_width: usize = 0; - var i: usize = 0; - while (i < line.len) { - // Skip ANSI escape sequences - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { - const seq_start = i; - i += 2; - while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} - if (i < line.len) i += 1; - try result.appendSlice(line[seq_start..i]); - continue; - } - - const char_width = charDisplayWidth(line, i); - if (visible_width + char_width > max_width) break; - - const byte_len = charByteLen(line[i]); - try result.appendSlice(line[i .. i + byte_len]); - visible_width += char_width; - i += byte_len; - } -} - -fn applyEllipsis(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { - const line_width = measure.width(line); - if (line_width <= max_width) { - try result.appendSlice(line); - return; - } - - if (max_width <= 1) { - if (max_width == 1) try result.appendSlice("\xe2\x80\xa6"); // … - return; - } - - // Truncate to max_width - 1 and add ellipsis - var visible_width: usize = 0; - var i: usize = 0; - const target_width = max_width - 1; - while (i < line.len) { - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { - const seq_start = i; - i += 2; - while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} - if (i < line.len) i += 1; - try result.appendSlice(line[seq_start..i]); - continue; - } - - const char_width = charDisplayWidth(line, i); - if (visible_width + char_width > target_width) break; - - const byte_len = charByteLen(line[i]); - try result.appendSlice(line[i .. i + byte_len]); - visible_width += char_width; - i += byte_len; - } - - try result.appendSlice("\xe2\x80\xa6"); // … -} - -fn applyWordWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { - if (measure.width(line) <= max_width) { - try result.appendSlice(line); - return; - } - - // Split line into words and re-flow them - var visible_width: usize = 0; - var i: usize = 0; - var line_start = true; - - while (i < line.len) { - // Skip ANSI sequences - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { - const seq_start = i; - i += 2; - while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} - if (i < line.len) i += 1; - try result.appendSlice(line[seq_start..i]); - continue; - } - - // Collect a word (non-space run) - if (line[i] == ' ') { - // Space: emit if it fits, otherwise start new line - if (visible_width + 1 > max_width) { - try result.append('\n'); - visible_width = 0; - line_start = true; - i += 1; - // Skip consecutive spaces at wrap point - while (i < line.len and line[i] == ' ') : (i += 1) {} - continue; - } - if (!line_start) { - try result.append(' '); - visible_width += 1; - } - i += 1; - continue; - } - - // Measure the next word - const word_start = i; - var word_width: usize = 0; - while (i < line.len and line[i] != ' ') { - // Skip ANSI inside word - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { - i += 2; - while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} - if (i < line.len) i += 1; - continue; - } - word_width += charDisplayWidth(line, i); - i += charByteLen(line[i]); - } - const word = line[word_start..i]; - - // If word doesn't fit on current line, wrap - if (!line_start and visible_width + word_width > max_width) { - try result.append('\n'); - visible_width = 0; - line_start = true; - } - - // If single word is wider than max, just emit it (char-wrap fallback) - try result.appendSlice(word); - visible_width += word_width; - line_start = false; - } -} - -fn applyCharWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { - if (measure.width(line) <= max_width) { - try result.appendSlice(line); - return; - } - - var visible_width: usize = 0; - var i: usize = 0; - var first_on_line = true; - - while (i < line.len) { - // Skip ANSI sequences - if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { - const seq_start = i; - i += 2; - while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} - if (i < line.len) i += 1; - try result.appendSlice(line[seq_start..i]); - continue; - } - - const char_width = charDisplayWidth(line, i); - if (visible_width + char_width > max_width and !first_on_line) { - try result.append('\n'); - visible_width = 0; - first_on_line = true; - } - - const byte_len = charByteLen(line[i]); - try result.appendSlice(line[i .. i + byte_len]); - visible_width += char_width; - first_on_line = false; - i += byte_len; - } -} - -fn charDisplayWidth(text: []const u8, pos: usize) usize { - const byte = text[pos]; - if (byte < 0x80) return 1; - // Simple heuristic: CJK characters are 2-wide, others 1-wide - // Full-width ranges: U+1100-U+115F, U+2E80-U+A4CF, U+AC00-U+D7A3, etc. - const byte_len = charByteLen(byte); - if (byte_len >= 3 and pos + byte_len <= text.len) { - const cp = std.unicode.utf8Decode(text[pos..][0..byte_len]) catch return 1; - if (isWideCodepoint(cp)) return 2; - } - return 1; -} - -fn isWideCodepoint(cp: u21) bool { - return (cp >= 0x1100 and cp <= 0x115F) or - (cp >= 0x2E80 and cp <= 0x303E) or - (cp >= 0x3041 and cp <= 0x33BF) or - (cp >= 0x3400 and cp <= 0x4DBF) or - (cp >= 0x4E00 and cp <= 0xA4CF) or - (cp >= 0xAC00 and cp <= 0xD7A3) or - (cp >= 0xF900 and cp <= 0xFAFF) or - (cp >= 0xFE30 and cp <= 0xFE6F) or - (cp >= 0xFF01 and cp <= 0xFF60) or - (cp >= 0xFFE0 and cp <= 0xFFE6) or - (cp >= 0x20000 and cp <= 0x2FFFD) or - (cp >= 0x30000 and cp <= 0x3FFFD); -} - -fn charByteLen(first_byte: u8) usize { - if (first_byte < 0x80) return 1; - if (first_byte & 0xE0 == 0xC0) return 2; - if (first_byte & 0xF0 == 0xE0) return 3; - if (first_byte & 0xF8 == 0xF0) return 4; - return 1; -} - -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- - -test "clip truncates at max width" { - const allocator = std.testing.allocator; - const result = try applyOverflow(allocator, "Hello, World!", 5, .hidden); - defer allocator.free(result); - try std.testing.expectEqualStrings("Hello", result); -} - -test "ellipsis adds character" { - const allocator = std.testing.allocator; - const result = try applyOverflow(allocator, "Hello, World!", 6, .ellipsis); - defer allocator.free(result); - try std.testing.expectEqualStrings("Hello\xe2\x80\xa6", result); -} - -test "visible returns original" { - const allocator = std.testing.allocator; - const result = try applyOverflow(allocator, "Hello", 3, .visible); - try std.testing.expectEqualStrings("Hello", result); -} - -test "short text unchanged with ellipsis" { - const allocator = std.testing.allocator; - const result = try applyOverflow(allocator, "Hi", 10, .ellipsis); - defer allocator.free(result); - try std.testing.expectEqualStrings("Hi", result); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig deleted file mode 100644 index 22b16e2..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/style.zig +++ /dev/null @@ -1,1060 +0,0 @@ -//! Style struct for terminal text styling (Lipgloss equivalent). -//! Provides a builder pattern for composing styles. - -const std = @import("std"); -const Writer = std.Io.Writer; -const color_mod = @import("color.zig"); -const border_mod = @import("border.zig"); -const ansi = @import("../terminal/ansi.zig"); -const measure = @import("../layout/measure.zig"); -const overflow_mod = @import("overflow.zig"); -pub const Overflow = overflow_mod.Overflow; - -pub const Color = color_mod.Color; -pub const BorderChars = border_mod.BorderChars; -pub const Sides = border_mod.Sides; - -/// Padding/Margin specification -pub const Spacing = struct { - top: u16 = 0, - right: u16 = 0, - bottom: u16 = 0, - left: u16 = 0, - - pub fn all(n: u16) Spacing { - return .{ .top = n, .right = n, .bottom = n, .left = n }; - } - - pub fn symmetric(vert: u16, horiz: u16) Spacing { - return .{ .top = vert, .right = horiz, .bottom = vert, .left = horiz }; - } - - pub fn horizontal(n: u16) Spacing { - return .{ .left = n, .right = n }; - } - - pub fn vertical(n: u16) Spacing { - return .{ .top = n, .bottom = n }; - } -}; - -/// Text alignment -pub const Align = enum { - left, - center, - right, -}; - -/// Vertical alignment -pub const VAlign = enum { - top, - middle, - bottom, -}; - -/// Built-in text transform functions -pub const transforms = struct { - pub fn uppercase(allocator: std.mem.Allocator, text: []const u8) []const u8 { - const result = allocator.alloc(u8, text.len) catch return text; - for (text, 0..) |c, i| { - result[i] = std.ascii.toUpper(c); - } - return result; - } - - pub fn lowercase(allocator: std.mem.Allocator, text: []const u8) []const u8 { - const result = allocator.alloc(u8, text.len) catch return text; - for (text, 0..) |c, i| { - result[i] = std.ascii.toLower(c); - } - return result; - } -}; - -/// Style definition with builder pattern -pub const Style = struct { - // Colors - foreground: Color = .none, - background: Color = .none, - - // Text attributes (nullable for unset semantics) - bold_attr: ?bool = null, - dim_attr: ?bool = null, - italic_attr: ?bool = null, - underline_attr: ?bool = null, - blink_attr: ?bool = null, - reverse_attr: ?bool = null, - strikethrough_attr: ?bool = null, - - // Spacing - padding_val: Spacing = .{}, - margin_val: Spacing = .{}, - - // Border - border_style: BorderChars = .none, - border_sides: Sides = .none, - border_fg: Color = .none, - border_bg: Color = .none, - - // Per-side border colors - border_top_fg: Color = .none, - border_top_bg: Color = .none, - border_right_fg: Color = .none, - border_right_bg: Color = .none, - border_bottom_fg: Color = .none, - border_bottom_bg: Color = .none, - border_left_fg: Color = .none, - border_left_bg: Color = .none, - - // Margin background - margin_bg: Color = .none, - - // Tab width - tab_width_val: ?u8 = null, - - // Size constraints - width_val: ?u16 = null, - height_val: ?u16 = null, - max_width_val: ?u16 = null, - max_height_val: ?u16 = null, - - // Alignment - align_horizontal: Align = .left, - align_vertical: VAlign = .top, - - // Inline (no newlines) - inline_mode: bool = false, - - // Transform function - transform_fn: ?*const fn (std.mem.Allocator, []const u8) []const u8 = null, - - // Text overflow - overflow_mode: Overflow = .visible, - - // Whitespace formatting controls - underline_spaces: bool = false, - strikethrough_spaces: bool = false, - color_whitespace: bool = true, - - const Self = @This(); - - // Color setters - pub fn foreground_color(self: Self, c: Color) Self { - var s = self; - s.foreground = c; - return s; - } - - pub fn background_color(self: Self, c: Color) Self { - var s = self; - s.background = c; - return s; - } - - pub fn fg(self: Self, c: Color) Self { - return self.foreground_color(c); - } - - pub fn bg(self: Self, c: Color) Self { - return self.background_color(c); - } - - // Text attribute setters - pub fn bold(self: Self, v: bool) Self { - var s = self; - s.bold_attr = v; - return s; - } - - pub fn dim(self: Self, v: bool) Self { - var s = self; - s.dim_attr = v; - return s; - } - - pub fn italic(self: Self, v: bool) Self { - var s = self; - s.italic_attr = v; - return s; - } - - pub fn underline(self: Self, v: bool) Self { - var s = self; - s.underline_attr = v; - return s; - } - - pub fn blink(self: Self, v: bool) Self { - var s = self; - s.blink_attr = v; - return s; - } - - pub fn reverse(self: Self, v: bool) Self { - var s = self; - s.reverse_attr = v; - return s; - } - - pub fn strikethrough(self: Self, v: bool) Self { - var s = self; - s.strikethrough_attr = v; - return s; - } - - // Unset methods - pub fn unsetBold(self: Self) Self { - var s = self; - s.bold_attr = null; - return s; - } - - pub fn unsetDim(self: Self) Self { - var s = self; - s.dim_attr = null; - return s; - } - - pub fn unsetItalic(self: Self) Self { - var s = self; - s.italic_attr = null; - return s; - } - - pub fn unsetUnderline(self: Self) Self { - var s = self; - s.underline_attr = null; - return s; - } - - pub fn unsetBlink(self: Self) Self { - var s = self; - s.blink_attr = null; - return s; - } - - pub fn unsetReverse(self: Self) Self { - var s = self; - s.reverse_attr = null; - return s; - } - - pub fn unsetStrikethrough(self: Self) Self { - var s = self; - s.strikethrough_attr = null; - return s; - } - - pub fn unsetFg(self: Self) Self { - var s = self; - s.foreground = .none; - return s; - } - - pub fn unsetBg(self: Self) Self { - var s = self; - s.background = .none; - return s; - } - - pub fn unsetPadding(self: Self) Self { - var s = self; - s.padding_val = .{}; - return s; - } - - pub fn unsetMargin(self: Self) Self { - var s = self; - s.margin_val = .{}; - return s; - } - - pub fn unsetBorder(self: Self) Self { - var s = self; - s.border_style = .none; - s.border_sides = .none; - s.border_fg = .none; - s.border_bg = .none; - s.border_top_fg = .none; - s.border_top_bg = .none; - s.border_right_fg = .none; - s.border_right_bg = .none; - s.border_bottom_fg = .none; - s.border_bottom_bg = .none; - s.border_left_fg = .none; - s.border_left_bg = .none; - return s; - } - - pub fn unsetWidth(self: Self) Self { - var s = self; - s.width_val = null; - return s; - } - - pub fn unsetHeight(self: Self) Self { - var s = self; - s.height_val = null; - return s; - } - - pub fn unsetMaxWidth(self: Self) Self { - var s = self; - s.max_width_val = null; - return s; - } - - pub fn unsetMaxHeight(self: Self) Self { - var s = self; - s.max_height_val = null; - return s; - } - - // Spacing setters - pub fn padding(self: Self, p: Spacing) Self { - var s = self; - s.padding_val = p; - return s; - } - - pub fn paddingAll(self: Self, n: u16) Self { - return self.padding(.all(n)); - } - - pub fn paddingLeft(self: Self, n: u16) Self { - var s = self; - s.padding_val.left = n; - return s; - } - - pub fn paddingRight(self: Self, n: u16) Self { - var s = self; - s.padding_val.right = n; - return s; - } - - pub fn paddingTop(self: Self, n: u16) Self { - var s = self; - s.padding_val.top = n; - return s; - } - - pub fn paddingBottom(self: Self, n: u16) Self { - var s = self; - s.padding_val.bottom = n; - return s; - } - - pub fn margin(self: Self, m: Spacing) Self { - var s = self; - s.margin_val = m; - return s; - } - - pub fn marginAll(self: Self, n: u16) Self { - return self.margin(.all(n)); - } - - pub fn marginLeft(self: Self, n: u16) Self { - var s = self; - s.margin_val.left = n; - return s; - } - - pub fn marginRight(self: Self, n: u16) Self { - var s = self; - s.margin_val.right = n; - return s; - } - - pub fn marginTop(self: Self, n: u16) Self { - var s = self; - s.margin_val.top = n; - return s; - } - - pub fn marginBottom(self: Self, n: u16) Self { - var s = self; - s.margin_val.bottom = n; - return s; - } - - // Border setters - pub fn border(self: Self, chars: BorderChars, sides: Sides) Self { - var s = self; - s.border_style = chars; - s.border_sides = sides; - return s; - } - - pub fn borderAll(self: Self, chars: BorderChars) Self { - return self.border(chars, .all); - } - - pub fn borderForeground(self: Self, c: Color) Self { - var s = self; - s.border_fg = c; - return s; - } - - pub fn borderBackground(self: Self, c: Color) Self { - var s = self; - s.border_bg = c; - return s; - } - - pub fn borderTopForeground(self: Self, c: Color) Self { - var s = self; - s.border_top_fg = c; - return s; - } - - pub fn borderTopBackground(self: Self, c: Color) Self { - var s = self; - s.border_top_bg = c; - return s; - } - - pub fn borderRightForeground(self: Self, c: Color) Self { - var s = self; - s.border_right_fg = c; - return s; - } - - pub fn borderRightBackground(self: Self, c: Color) Self { - var s = self; - s.border_right_bg = c; - return s; - } - - pub fn borderBottomForeground(self: Self, c: Color) Self { - var s = self; - s.border_bottom_fg = c; - return s; - } - - pub fn borderBottomBackground(self: Self, c: Color) Self { - var s = self; - s.border_bottom_bg = c; - return s; - } - - pub fn borderLeftForeground(self: Self, c: Color) Self { - var s = self; - s.border_left_fg = c; - return s; - } - - pub fn borderLeftBackground(self: Self, c: Color) Self { - var s = self; - s.border_left_bg = c; - return s; - } - - pub fn marginBackground(self: Self, c: Color) Self { - var s = self; - s.margin_bg = c; - return s; - } - - pub fn tabWidth(self: Self, n: u8) Self { - var s = self; - s.tab_width_val = n; - return s; - } - - // Size setters - pub fn width(self: Self, w: u16) Self { - var s = self; - s.width_val = w; - return s; - } - - pub fn height(self: Self, h: u16) Self { - var s = self; - s.height_val = h; - return s; - } - - pub fn maxWidth(self: Self, w: u16) Self { - var s = self; - s.max_width_val = w; - return s; - } - - pub fn maxHeight(self: Self, h: u16) Self { - var s = self; - s.max_height_val = h; - return s; - } - - // Overflow setter - pub fn overflow(self: Self, mode: Overflow) Self { - var s = self; - s.overflow_mode = mode; - return s; - } - - // Alignment setters - pub fn alignH(self: Self, a: Align) Self { - var s = self; - s.align_horizontal = a; - return s; - } - - pub fn valign(self: Self, a: VAlign) Self { - var s = self; - s.align_vertical = a; - return s; - } - - // Inline mode - pub fn inline_style(self: Self, v: bool) Self { - var s = self; - s.inline_mode = v; - return s; - } - - // Transform setter - pub fn transform(self: Self, func: *const fn (std.mem.Allocator, []const u8) []const u8) Self { - var s = self; - s.transform_fn = func; - return s; - } - - // Whitespace formatting control setters - pub fn setUnderlineSpaces(self: Self, v: bool) Self { - var s = self; - s.underline_spaces = v; - return s; - } - - pub fn setStrikethroughSpaces(self: Self, v: bool) Self { - var s = self; - s.strikethrough_spaces = v; - return s; - } - - pub fn setColorWhitespace(self: Self, v: bool) Self { - var s = self; - s.color_whitespace = v; - return s; - } - - /// Inherit unset values from another style - pub fn inherit(self: Self, other: Self) Self { - var s = self; - if (s.foreground == .none) s.foreground = other.foreground; - if (s.background == .none) s.background = other.background; - if (s.bold_attr == null) s.bold_attr = other.bold_attr; - if (s.dim_attr == null) s.dim_attr = other.dim_attr; - if (s.italic_attr == null) s.italic_attr = other.italic_attr; - if (s.underline_attr == null) s.underline_attr = other.underline_attr; - if (s.blink_attr == null) s.blink_attr = other.blink_attr; - if (s.reverse_attr == null) s.reverse_attr = other.reverse_attr; - if (s.strikethrough_attr == null) s.strikethrough_attr = other.strikethrough_attr; - if (s.padding_val.top == 0 and s.padding_val.bottom == 0 and s.padding_val.left == 0 and s.padding_val.right == 0) { - s.padding_val = other.padding_val; - } - if (s.margin_val.top == 0 and s.margin_val.bottom == 0 and s.margin_val.left == 0 and s.margin_val.right == 0) { - s.margin_val = other.margin_val; - } - if (s.border_fg == .none) s.border_fg = other.border_fg; - if (s.border_bg == .none) s.border_bg = other.border_bg; - if (s.width_val == null) s.width_val = other.width_val; - if (s.height_val == null) s.height_val = other.height_val; - if (s.max_width_val == null) s.max_width_val = other.max_width_val; - if (s.max_height_val == null) s.max_height_val = other.max_height_val; - if (s.margin_bg == .none) s.margin_bg = other.margin_bg; - if (s.tab_width_val == null) s.tab_width_val = other.tab_width_val; - if (s.transform_fn == null) s.transform_fn = other.transform_fn; - return s; - } - - /// Render styled text - pub fn render(self: Self, allocator: std.mem.Allocator, text: []const u8) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - defer result.deinit(); - - // Preprocess tabs if tab_width is set. Only allocate the scratch - // buffer when expansion is actually needed. - var processed_text = text; - if (self.tab_width_val) |tw| { - var buf: Writer.Allocating = .init(allocator); - defer buf.deinit(); - for (text) |c| { - if (c == '\t') { - for (0..tw) |_| { - try buf.writer.writeByte(' '); - } - } else { - try buf.writer.writeByte(c); - } - } - processed_text = try buf.toOwnedSlice(); - } - - // Apply transform function - if (self.transform_fn) |tf| { - processed_text = tf(allocator, processed_text); - } - - // Apply overflow policy before dimension calculation - if (self.overflow_mode != .visible) { - const ow = self.width_val orelse (self.max_width_val orelse 0); - if (ow > 0) { - processed_text = overflow_mod.applyOverflow(allocator, processed_text, ow, self.overflow_mode) catch processed_text; - } - } - - // Calculate content dimensions - const content_width = measure.width(processed_text); - const content_height = measure.height(processed_text); - - // Apply size constraints - var target_width = content_width; - var target_height = content_height; - - if (self.width_val) |w| target_width = w; - if (self.height_val) |h| target_height = h; - if (self.max_width_val) |mw| target_width = @min(target_width, mw); - if (self.max_height_val) |mh| target_height = @min(target_height, mh); - - // Add padding to target dimensions - target_width += self.padding_val.left + self.padding_val.right; - target_height += self.padding_val.top + self.padding_val.bottom; - - // Add border width - if (self.border_sides.left) target_width += 1; - if (self.border_sides.right) target_width += 1; - if (self.border_sides.top) target_height += 1; - if (self.border_sides.bottom) target_height += 1; - - // Write margin top - for (0..self.margin_val.top) |_| { - try self.writeMarginLeft(&result.writer); - if (!self.margin_bg.isNone()) { - try self.margin_bg.writeBg(&result.writer); - for (0..target_width) |_| { - try result.writer.writeByte(' '); - } - try self.writeMarginRight(&result.writer, target_width); - try result.writer.writeAll(ansi.reset); - } - try result.writer.writeByte('\n'); - } - - // Build styled content - try self.writeStyledContent(&result.writer, processed_text, target_width, target_height); - - // Write margin bottom - for (0..self.margin_val.bottom) |_| { - try result.writer.writeByte('\n'); - try self.writeMarginLeft(&result.writer); - if (!self.margin_bg.isNone()) { - try self.margin_bg.writeBg(&result.writer); - for (0..target_width) |_| { - try result.writer.writeByte(' '); - } - try self.writeMarginRight(&result.writer, target_width); - try result.writer.writeAll(ansi.reset); - } - } - - var array = result.toArrayList(); - if (!self.inline_mode and - array.items.len > 0 and - array.items[array.items.len - 1] == '\n') - _ = array.pop(); - - return array.toOwnedSlice(allocator); - } - - fn writeStyledContent(self: Self, writer: *Writer, text: []const u8, target_width: usize, target_height: usize) !void { - const inner_width = target_width -| - self.padding_val.left -| self.padding_val.right -| - @as(usize, if (self.border_sides.left) 1 else 0) -| - @as(usize, if (self.border_sides.right) 1 else 0); - - const inner_height = target_height -| - self.padding_val.top -| self.padding_val.bottom -| - @as(usize, if (self.border_sides.top) 1 else 0) -| - @as(usize, if (self.border_sides.bottom) 1 else 0); - - _ = inner_height; - - // Start style - try self.writeStyleStart(writer); - - // Top border - if (self.border_sides.top) { - try self.writeMarginLeft(writer); - try self.writeBorderColorSide(writer, .top); - if (self.border_sides.left) try writer.writeAll(self.border_style.top_left); - for (0..inner_width + self.padding_val.left + self.padding_val.right) |_| { - try writer.writeAll(self.border_style.horizontal); - } - if (self.border_sides.right) try writer.writeAll(self.border_style.top_right); - try writer.writeAll(ansi.reset); - try self.writeMarginRight(writer, target_width); - if (!self.inline_mode) try writer.writeByte('\n'); - } - - // Padding top - for (0..self.padding_val.top) |_| { - try self.writeContentLine(writer, "", inner_width); - } - - // Content lines - var lines = std.mem.splitScalar(u8, text, '\n'); - while (lines.next()) |line| { - try self.writeContentLine(writer, line, inner_width); - } - - // Padding bottom - for (0..self.padding_val.bottom) |_| { - try self.writeContentLine(writer, "", inner_width); - } - - // Bottom border - if (self.border_sides.bottom) { - try self.writeMarginLeft(writer); - try self.writeBorderColorSide(writer, .bottom); - if (self.border_sides.left) try writer.writeAll(self.border_style.bottom_left); - for (0..inner_width + self.padding_val.left + self.padding_val.right) |_| { - try writer.writeAll(self.border_style.horizontal); - } - if (self.border_sides.right) try writer.writeAll(self.border_style.bottom_right); - try writer.writeAll(ansi.reset); - try self.writeMarginRight(writer, target_width); - } - } - - /// Check if whitespace-aware rendering is needed - fn needsWhitespaceAwareRendering(self: Self) bool { - return (!self.color_whitespace and !self.background.isNone()) or - (self.underline_spaces and (self.underline_attr orelse false)) or - (self.strikethrough_spaces and (self.strikethrough_attr orelse false)); - } - - fn writeContentLine(self: Self, writer: *Writer, line: []const u8, inner_width: usize) !void { - try self.writeMarginLeft(writer); - - // Left border - if (self.border_sides.left) { - try self.writeBorderColorSide(writer, .left); - try writer.writeAll(self.border_style.vertical); - try writer.writeAll(ansi.reset); - } - - // Start content style - try self.writeStyleStart(writer); - - // Left padding - for (0..self.padding_val.left) |_| { - try writer.writeByte(' '); - } - - // Content with alignment - const line_width = measure.width(line); - const content_pad = if (inner_width > line_width) inner_width - line_width else 0; - - if (self.needsWhitespaceAwareRendering()) { - // Whitespace-aware rendering: toggle attributes around spaces - switch (self.align_horizontal) { - .left => { - try self.writeWithWhitespaceControl(writer, line); - try self.writeSpacesWithControl(writer, content_pad); - }, - .center => { - const left_pad = content_pad / 2; - const right_pad = content_pad - left_pad; - try self.writeSpacesWithControl(writer, left_pad); - try self.writeWithWhitespaceControl(writer, line); - try self.writeSpacesWithControl(writer, right_pad); - }, - .right => { - try self.writeSpacesWithControl(writer, content_pad); - try self.writeWithWhitespaceControl(writer, line); - }, - } - } else { - switch (self.align_horizontal) { - .left => { - try writer.writeAll(line); - for (0..content_pad) |_| { - try writer.writeByte(' '); - } - }, - .center => { - const left_pad = content_pad / 2; - const right_pad = content_pad - left_pad; - for (0..left_pad) |_| { - try writer.writeByte(' '); - } - try writer.writeAll(line); - for (0..right_pad) |_| { - try writer.writeByte(' '); - } - }, - .right => { - for (0..content_pad) |_| { - try writer.writeByte(' '); - } - try writer.writeAll(line); - }, - } - } - - // Right padding - for (0..self.padding_val.right) |_| { - try writer.writeByte(' '); - } - - // Reset style - try writer.writeAll(ansi.reset); - - // Right border - if (self.border_sides.right) { - try self.writeBorderColorSide(writer, .right); - try writer.writeAll(self.border_style.vertical); - try writer.writeAll(ansi.reset); - } - - // Right margin - const total_content_width = inner_width + self.padding_val.left + self.padding_val.right + - @as(usize, if (self.border_sides.left) 1 else 0) + - @as(usize, if (self.border_sides.right) 1 else 0); - try self.writeMarginRight(writer, total_content_width); - - if (!self.inline_mode) try writer.writeByte('\n'); - } - - /// Write text with per-character whitespace attribute control - fn writeWithWhitespaceControl(self: Self, writer: *Writer, text: []const u8) !void { - var i: usize = 0; - while (i < text.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; - const end = @min(i + byte_len, text.len); - const ch = text[i..end]; - const is_space = ch.len == 1 and ch[0] == ' '; - - if (is_space) { - // For spaces: conditionally disable/enable attributes - if (!self.color_whitespace and !self.background.isNone()) { - try writer.writeAll(ansi.reset); - // Re-emit attributes that should apply to spaces - if (self.underline_spaces and (self.underline_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - } - if (self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - } - try writer.writeByte(' '); - // Restore full style - try self.writeStyleStart(writer); - } else { - // Color whitespace is on, but check underline/strikethrough - if (!self.underline_spaces and (self.underline_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.no_underline}); - } - if (!self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.no_strikethrough}); - } - try writer.writeByte(' '); - // Restore - if (!self.underline_spaces and (self.underline_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - } - if (!self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - } - } - } else { - try writer.writeAll(ch); - } - - i = end; - } - } - - /// Write N spaces with whitespace control - fn writeSpacesWithControl(self: Self, writer: *Writer, count: usize) !void { - if (count == 0) return; - if (!self.color_whitespace and !self.background.isNone()) { - try writer.writeAll(ansi.reset); - if (self.underline_spaces and (self.underline_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - } - if (self.strikethrough_spaces and (self.strikethrough_attr orelse false)) { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - } - for (0..count) |_| { - try writer.writeByte(' '); - } - try self.writeStyleStart(writer); - } else { - for (0..count) |_| { - try writer.writeByte(' '); - } - } - } - - fn writeMarginLeft(self: Self, writer: *Writer) !void { - if (!self.margin_bg.isNone() and self.margin_val.left > 0) { - try self.margin_bg.writeBg(writer); - } - for (0..self.margin_val.left) |_| { - try writer.writeByte(' '); - } - if (!self.margin_bg.isNone() and self.margin_val.left > 0) { - try writer.writeAll(ansi.reset); - } - } - - fn writeMarginRight(self: Self, writer: *Writer, content_width: usize) !void { - _ = content_width; - if (self.margin_val.right > 0) { - if (!self.margin_bg.isNone()) { - try self.margin_bg.writeBg(writer); - } - for (0..self.margin_val.right) |_| { - try writer.writeByte(' '); - } - if (!self.margin_bg.isNone()) { - try writer.writeAll(ansi.reset); - } - } - } - - fn writeStyleStart(self: Self, writer: *Writer) !void { - if (self.bold_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); - if (self.dim_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); - if (self.italic_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); - if (self.underline_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - if (self.blink_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); - if (self.reverse_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); - if (self.strikethrough_attr orelse false) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - - try self.foreground.writeFg(writer); - try self.background.writeBg(writer); - } - - const BorderSide = enum { top, right, bottom, left }; - - fn writeBorderColorSide(self: Self, writer: *Writer, side: BorderSide) !void { - const side_fg = switch (side) { - .top => self.border_top_fg, - .right => self.border_right_fg, - .bottom => self.border_bottom_fg, - .left => self.border_left_fg, - }; - const side_bg = switch (side) { - .top => self.border_top_bg, - .right => self.border_right_bg, - .bottom => self.border_bottom_bg, - .left => self.border_left_bg, - }; - const resolved_fg = if (!side_fg.isNone()) side_fg else self.border_fg; - const resolved_bg = if (!side_bg.isNone()) side_bg else self.border_bg; - try resolved_fg.writeFg(writer); - try resolved_bg.writeBg(writer); - } - - fn writeBorderColor(self: Self, writer: *Writer) !void { - try self.border_fg.writeFg(writer); - try self.border_bg.writeBg(writer); - } - - /// Copy style - pub fn copy(self: Self) Self { - return self; - } -}; - -/// Style range for applying different styles to byte ranges -pub const StyleRange = struct { - start: usize, - end: usize, - s: Style, -}; - -/// Render text with different styles applied to specific byte ranges -pub fn renderWithRanges(allocator: std.mem.Allocator, text: []const u8, ranges: []const StyleRange) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var pos: usize = 0; - while (pos < text.len) { - // Find if this position is in a range - var found_range: ?StyleRange = null; - for (ranges) |r| { - if (pos >= r.start and pos < r.end) { - found_range = r; - break; - } - } - - if (found_range) |r| { - const end = @min(r.end, text.len); - const chunk = text[pos..end]; - const styled = try r.s.render(allocator, chunk); - try writer.writeAll(styled); - pos = end; - } else { - // Find next range start or end of text - var next_start: usize = text.len; - for (ranges) |r| { - if (r.start > pos and r.start < next_start) { - next_start = r.start; - } - } - try writer.writeAll(text[pos..next_start]); - pos = next_start; - } - } - - return result.toOwnedSlice(); -} - -/// Render text with specific byte positions highlighted -pub fn renderWithHighlights( - allocator: std.mem.Allocator, - text: []const u8, - positions: []const usize, - highlight_style: Style, - base_style: Style, -) ![]const u8 { - var result: Writer.Allocating = .init(allocator); - const writer = &result.writer; - - var pos: usize = 0; - var pi: usize = 0; // position index - - while (pos < text.len) { - if (pi < positions.len and pos == positions[pi]) { - // Highlighted character - const byte_len = std.unicode.utf8ByteSequenceLength(text[pos]) catch 1; - const end = @min(pos + byte_len, text.len); - const ch = text[pos..end]; - const styled = try highlight_style.render(allocator, ch); - try writer.writeAll(styled); - pos = end; - pi += 1; - } else { - // Find next highlight position or end of text - var next_pos: usize = text.len; - if (pi < positions.len) { - next_pos = @min(positions[pi], text.len); - } - const chunk = text[pos..next_pos]; - if (chunk.len > 0) { - const styled = try base_style.render(allocator, chunk); - try writer.writeAll(styled); - } - pos = next_pos; - } - } - - return result.toOwnedSlice(); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig deleted file mode 100644 index 4657e38..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/style/theme.zig +++ /dev/null @@ -1,481 +0,0 @@ -//! Theming system for ZigZag. -//! Provides centralized color palettes and component-specific themes. - -const std = @import("std"); -const Color = @import("color.zig").Color; -const style_mod = @import("style.zig"); - -/// Semantic color palette. Defines named colors for a theme. -pub const Palette = struct { - // Primary colors - primary: Color, - secondary: Color, - accent: Color, - - // Surfaces - background: Color, - surface: Color, - overlay: Color, - - // Text - foreground: Color, - muted: Color, - subtle: Color, - - // Feedback - success: Color, - warning: Color, - danger: Color, - info: Color, - - // Borders - border_color: Color, - border_focus: Color, - - // Highlight - highlight: Color, - highlight_text: Color, - - // ── Built-in presets ────────────────────────────── - - pub const default_dark = Palette{ - .primary = .cyan, - .secondary = .magenta, - .accent = .yellow, - .background = .fromRgb(24, 24, 32), - .surface = .fromRgb(32, 32, 42), - .overlay = .fromRgb(40, 40, 52), - .foreground = .white, - .muted = .gray(14), - .subtle = .gray(10), - .success = .green, - .warning = .yellow, - .danger = .red, - .info = .cyan, - .border_color = .gray(12), - .border_focus = .cyan, - .highlight = .fromRgb(60, 60, 80), - .highlight_text = .white, - }; - - pub const default_light = Palette{ - .primary = .fromRgb(0, 120, 180), - .secondary = .fromRgb(140, 60, 160), - .accent = .fromRgb(180, 120, 0), - .background = .fromRgb(250, 250, 250), - .surface = .fromRgb(240, 240, 240), - .overlay = .fromRgb(230, 230, 230), - .foreground = .fromRgb(30, 30, 30), - .muted = .fromRgb(100, 100, 100), - .subtle = .fromRgb(160, 160, 160), - .success = .fromRgb(40, 160, 40), - .warning = .fromRgb(200, 150, 0), - .danger = .fromRgb(200, 40, 40), - .info = .fromRgb(0, 120, 180), - .border_color = .fromRgb(180, 180, 180), - .border_focus = .fromRgb(0, 120, 180), - .highlight = .fromRgb(200, 220, 240), - .highlight_text = .fromRgb(30, 30, 30), - }; - - pub const catppuccin_mocha = Palette{ - .primary = .fromRgb(137, 180, 250), // blue - .secondary = .fromRgb(203, 166, 247), // mauve - .accent = .fromRgb(249, 226, 175), // yellow - .background = .fromRgb(30, 30, 46), // base - .surface = .fromRgb(49, 50, 68), // surface0 - .overlay = .fromRgb(69, 71, 90), // surface1 - .foreground = .fromRgb(205, 214, 244), // text - .muted = .fromRgb(166, 173, 200), // subtext0 - .subtle = .fromRgb(127, 132, 156), // overlay1 - .success = .fromRgb(166, 227, 161), // green - .warning = .fromRgb(249, 226, 175), // yellow - .danger = .fromRgb(243, 139, 168), // red - .info = .fromRgb(137, 180, 250), // blue - .border_color = .fromRgb(88, 91, 112), // overlay0 - .border_focus = .fromRgb(137, 180, 250), // blue - .highlight = .fromRgb(49, 50, 68), // surface0 - .highlight_text = .fromRgb(205, 214, 244), // text - }; - - pub const catppuccin_latte = Palette{ - .primary = .fromRgb(30, 102, 245), // blue - .secondary = .fromRgb(136, 57, 239), // mauve - .accent = .fromRgb(223, 142, 29), // yellow - .background = .fromRgb(239, 241, 245), // base - .surface = .fromRgb(204, 208, 218), // surface0 - .overlay = .fromRgb(188, 192, 204), // surface1 - .foreground = .fromRgb(76, 79, 105), // text - .muted = .fromRgb(108, 111, 133), // subtext0 - .subtle = .fromRgb(140, 143, 161), // overlay1 - .success = .fromRgb(64, 160, 43), // green - .warning = .fromRgb(223, 142, 29), // yellow - .danger = .fromRgb(210, 15, 57), // red - .info = .fromRgb(30, 102, 245), // blue - .border_color = .fromRgb(156, 160, 176), // overlay0 - .border_focus = .fromRgb(30, 102, 245), // blue - .highlight = .fromRgb(204, 208, 218), // surface0 - .highlight_text = .fromRgb(76, 79, 105), // text - }; - - pub const dracula = Palette{ - .primary = .fromRgb(189, 147, 249), // purple - .secondary = .fromRgb(255, 121, 198), // pink - .accent = .fromRgb(241, 250, 140), // yellow - .background = .fromRgb(40, 42, 54), // background - .surface = .fromRgb(68, 71, 90), // current line - .overlay = .fromRgb(68, 71, 90), // current line - .foreground = .fromRgb(248, 248, 242), // foreground - .muted = .fromRgb(98, 114, 164), // comment - .subtle = .fromRgb(98, 114, 164), // comment - .success = .fromRgb(80, 250, 123), // green - .warning = .fromRgb(255, 184, 108), // orange - .danger = .fromRgb(255, 85, 85), // red - .info = .fromRgb(139, 233, 253), // cyan - .border_color = .fromRgb(98, 114, 164), // comment - .border_focus = .fromRgb(189, 147, 249), // purple - .highlight = .fromRgb(68, 71, 90), // current line - .highlight_text = .fromRgb(248, 248, 242), // foreground - }; - - pub const nord = Palette{ - .primary = .fromRgb(136, 192, 208), // nord8 frost - .secondary = .fromRgb(129, 161, 193), // nord9 - .accent = .fromRgb(235, 203, 139), // nord13 aurora yellow - .background = .fromRgb(46, 52, 64), // nord0 polar night - .surface = .fromRgb(59, 66, 82), // nord1 - .overlay = .fromRgb(67, 76, 94), // nord2 - .foreground = .fromRgb(236, 239, 244), // nord6 snow storm - .muted = .fromRgb(216, 222, 233), // nord4 - .subtle = .fromRgb(76, 86, 106), // nord3 - .success = .fromRgb(163, 190, 140), // nord14 aurora green - .warning = .fromRgb(235, 203, 139), // nord13 - .danger = .fromRgb(191, 97, 106), // nord11 aurora red - .info = .fromRgb(136, 192, 208), // nord8 - .border_color = .fromRgb(76, 86, 106), // nord3 - .border_focus = .fromRgb(136, 192, 208), // nord8 - .highlight = .fromRgb(59, 66, 82), // nord1 - .highlight_text = .fromRgb(236, 239, 244), // nord6 - }; - - pub const high_contrast = Palette{ - .primary = .fromRgb(0, 200, 255), - .secondary = .fromRgb(255, 100, 255), - .accent = .fromRgb(255, 255, 0), - .background = .fromRgb(0, 0, 0), - .surface = .fromRgb(20, 20, 20), - .overlay = .fromRgb(40, 40, 40), - .foreground = .fromRgb(255, 255, 255), - .muted = .fromRgb(200, 200, 200), - .subtle = .fromRgb(150, 150, 150), - .success = .fromRgb(0, 255, 0), - .warning = .fromRgb(255, 255, 0), - .danger = .fromRgb(255, 0, 0), - .info = .fromRgb(0, 200, 255), - .border_color = .fromRgb(200, 200, 200), - .border_focus = .fromRgb(0, 200, 255), - .highlight = .fromRgb(0, 80, 120), - .highlight_text = .fromRgb(255, 255, 255), - }; - - pub const tokyo_night = Palette{ - .primary = .fromRgb(122, 162, 247), // blue - .secondary = .fromRgb(187, 154, 247), // purple - .accent = .fromRgb(224, 175, 104), // yellow - .background = .fromRgb(26, 27, 38), // bg - .surface = .fromRgb(36, 40, 59), // bg_highlight - .overlay = .fromRgb(41, 46, 66), // terminal_black - .foreground = .fromRgb(192, 202, 245), // fg - .muted = .fromRgb(144, 153, 191), // comment - .subtle = .fromRgb(86, 95, 137), // dark5 - .success = .fromRgb(158, 206, 106), // green - .warning = .fromRgb(224, 175, 104), // yellow - .danger = .fromRgb(247, 118, 142), // red - .info = .fromRgb(125, 207, 255), // cyan - .border_color = .fromRgb(41, 46, 66), - .border_focus = .fromRgb(122, 162, 247), - .highlight = .fromRgb(41, 46, 66), - .highlight_text = .fromRgb(192, 202, 245), - }; - - pub const gruvbox_dark = Palette{ - .primary = .fromRgb(131, 165, 152), // aqua - .secondary = .fromRgb(211, 134, 155), // purple - .accent = .fromRgb(250, 189, 47), // yellow - .background = .fromRgb(40, 40, 40), // bg - .surface = .fromRgb(60, 56, 54), // bg1 - .overlay = .fromRgb(80, 73, 69), // bg2 - .foreground = .fromRgb(235, 219, 178), // fg - .muted = .fromRgb(168, 153, 132), // gray - .subtle = .fromRgb(124, 111, 100), // bg4 - .success = .fromRgb(184, 187, 38), // green - .warning = .fromRgb(250, 189, 47), // yellow - .danger = .fromRgb(251, 73, 52), // red - .info = .fromRgb(131, 165, 152), // aqua - .border_color = .fromRgb(80, 73, 69), - .border_focus = .fromRgb(131, 165, 152), - .highlight = .fromRgb(80, 73, 69), - .highlight_text = .fromRgb(235, 219, 178), - }; - - pub const solarized_dark = Palette{ - .primary = .fromRgb(38, 139, 210), // blue - .secondary = .fromRgb(108, 113, 196), // violet - .accent = .fromRgb(181, 137, 0), // yellow - .background = .fromRgb(0, 43, 54), // base03 - .surface = .fromRgb(7, 54, 66), // base02 - .overlay = .fromRgb(88, 110, 117), // base01 - .foreground = .fromRgb(131, 148, 150), // base0 - .muted = .fromRgb(101, 123, 131), // base00 - .subtle = .fromRgb(88, 110, 117), // base01 - .success = .fromRgb(133, 153, 0), // green - .warning = .fromRgb(181, 137, 0), // yellow - .danger = .fromRgb(220, 50, 47), // red - .info = .fromRgb(42, 161, 152), // cyan - .border_color = .fromRgb(88, 110, 117), - .border_focus = .fromRgb(38, 139, 210), - .highlight = .fromRgb(7, 54, 66), - .highlight_text = .fromRgb(147, 161, 161), - }; - - pub const solarized_light = Palette{ - .primary = .fromRgb(38, 139, 210), // blue - .secondary = .fromRgb(108, 113, 196), // violet - .accent = .fromRgb(181, 137, 0), // yellow - .background = .fromRgb(253, 246, 227), // base3 - .surface = .fromRgb(238, 232, 213), // base2 - .overlay = .fromRgb(147, 161, 161), // base1 - .foreground = .fromRgb(101, 123, 131), // base00 - .muted = .fromRgb(131, 148, 150), // base0 - .subtle = .fromRgb(147, 161, 161), // base1 - .success = .fromRgb(133, 153, 0), // green - .warning = .fromRgb(181, 137, 0), // yellow - .danger = .fromRgb(220, 50, 47), // red - .info = .fromRgb(42, 161, 152), // cyan - .border_color = .fromRgb(147, 161, 161), - .border_focus = .fromRgb(38, 139, 210), - .highlight = .fromRgb(238, 232, 213), - .highlight_text = .fromRgb(88, 110, 117), - }; - - /// List of all built-in palette names for iteration. - pub const builtins = [_]struct { name: []const u8, palette: Palette }{ - .{ .name = "Default Dark", .palette = default_dark }, - .{ .name = "Default Light", .palette = default_light }, - .{ .name = "Catppuccin Mocha", .palette = catppuccin_mocha }, - .{ .name = "Catppuccin Latte", .palette = catppuccin_latte }, - .{ .name = "Dracula", .palette = dracula }, - .{ .name = "Nord", .palette = nord }, - .{ .name = "Tokyo Night", .palette = tokyo_night }, - .{ .name = "Gruvbox Dark", .palette = gruvbox_dark }, - .{ .name = "Solarized Dark", .palette = solarized_dark }, - .{ .name = "Solarized Light", .palette = solarized_light }, - .{ .name = "High Contrast", .palette = high_contrast }, - }; -}; - -/// Adaptive palette that resolves based on dark/light background. -pub const AdaptivePalette = struct { - light: Palette, - dark: Palette, - - pub fn resolve(self: AdaptivePalette, is_dark: bool) Palette { - return if (is_dark) self.dark else self.light; - } - - pub const catppuccin = AdaptivePalette{ - .light = .catppuccin_latte, - .dark = .catppuccin_mocha, - }; - - pub const default = AdaptivePalette{ - .light = .default_light, - .dark = .default_dark, - }; - - pub const solarized = AdaptivePalette{ - .light = .solarized_light, - .dark = .solarized_dark, - }; -}; - -/// Manages the active theme at runtime. -/// Holds a current theme and provides methods to switch between palettes. -pub const ThemeManager = struct { - current: Theme, - is_dark: bool, - palette_index: usize, - - /// Initialize with dark/light background detected from `environ_map`. - pub fn init(environ_map: *const std.process.Environ.Map) ThemeManager { - const is_dark = @import("color.zig").hasDarkBackground(environ_map); - const palette = AdaptivePalette.default.resolve(is_dark); - return .{ - .current = .fromPalette(palette), - .is_dark = is_dark, - .palette_index = 0, - }; - } - - /// Initialize with a specific palette and `environ_map`-detected dark/light hint. - pub fn initWithPalette(environ_map: *const std.process.Environ.Map, palette: Palette) ThemeManager { - const is_dark = @import("color.zig").hasDarkBackground(environ_map); - return .{ - .current = .fromPalette(palette), - .is_dark = is_dark, - .palette_index = 0, - }; - } - - /// Switch to a specific palette. - pub fn setPalette(self: *ThemeManager, palette: Palette) void { - self.current = .fromPalette(palette); - } - - /// Switch to a named built-in palette by index. - pub fn setBuiltinByIndex(self: *ThemeManager, index: usize) void { - if (index < Palette.builtins.len) { - self.palette_index = index; - self.current = .fromPalette(Palette.builtins[index].palette); - } - } - - /// Cycle to the next built-in palette. - pub fn nextBuiltin(self: *ThemeManager) void { - self.palette_index = (self.palette_index + 1) % Palette.builtins.len; - self.current = .fromPalette(Palette.builtins[self.palette_index].palette); - } - - /// Cycle to the previous built-in palette. - pub fn prevBuiltin(self: *ThemeManager) void { - self.palette_index = if (self.palette_index == 0) Palette.builtins.len - 1 else self.palette_index - 1; - self.current = .fromPalette(Palette.builtins[self.palette_index].palette); - } - - /// Get the name of the current built-in palette. - pub fn currentName(self: *const ThemeManager) []const u8 { - return Palette.builtins[self.palette_index].name; - } - - /// Get the total number of built-in palettes. - pub fn builtinCount() usize { - return Palette.builtins.len; - } -}; - -/// Theme contains a palette and derived component styles. -pub const Theme = struct { - palette: Palette, - - // Derived styles for components - text: TextTheme, - list: ListTheme, - progress: ProgressTheme, - modal: ModalTheme, - notification: NotificationTheme, - tab: TabTheme, - - pub const TextTheme = struct { - text_fg: Color, - placeholder_fg: Color, - prompt_fg: Color, - border_fg: Color, - border_focus_fg: Color, - }; - - pub const ListTheme = struct { - item_fg: Color, - selected_fg: Color, - cursor_fg: Color, - filter_fg: Color, - }; - - pub const ProgressTheme = struct { - filled_fg: Color, - empty_fg: Color, - percent_fg: Color, - }; - - pub const ModalTheme = struct { - border_fg: Color, - title_fg: Color, - body_fg: Color, - button_fg: Color, - button_active_bg: Color, - }; - - pub const NotificationTheme = struct { - info_fg: Color, - success_fg: Color, - warning_fg: Color, - err_fg: Color, - }; - - pub const TabTheme = struct { - bar_fg: Color, - active_fg: Color, - active_bg: Color, - inactive_fg: Color, - }; - - /// Create a Theme from a Palette with sensible defaults. - pub fn fromPalette(p: Palette) Theme { - return .{ - .palette = p, - .text = .{ - .text_fg = p.foreground, - .placeholder_fg = p.subtle, - .prompt_fg = p.primary, - .border_fg = p.border_color, - .border_focus_fg = p.border_focus, - }, - .list = .{ - .item_fg = p.foreground, - .selected_fg = p.primary, - .cursor_fg = p.secondary, - .filter_fg = p.accent, - }, - .progress = .{ - .filled_fg = p.primary, - .empty_fg = p.subtle, - .percent_fg = p.foreground, - }, - .modal = .{ - .border_fg = p.border_color, - .title_fg = p.foreground, - .body_fg = p.muted, - .button_fg = p.foreground, - .button_active_bg = p.primary, - }, - .notification = .{ - .info_fg = p.info, - .success_fg = p.success, - .warning_fg = p.warning, - .err_fg = p.danger, - }, - .tab = .{ - .bar_fg = p.muted, - .active_fg = p.foreground, - .active_bg = p.primary, - .inactive_fg = p.subtle, - }, - }; - } - - /// Helper to create a Style with foreground color from the theme. - pub fn styleWith(fg: Color) style_mod.Style { - var s = style_mod.Style{}; - s = s.fg(fg); - s = s.inline_style(true); - return s; - } - - /// Helper to create a bold Style with foreground color. - pub fn boldStyleWith(fg: Color) style_mod.Style { - var s = style_mod.Style{}; - s = s.fg(fg); - s = s.bold(true); - s = s.inline_style(true); - return s; - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig deleted file mode 100644 index 5030d03..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/ansi.zig +++ /dev/null @@ -1,372 +0,0 @@ -//! ANSI escape sequence generation for terminal control. -//! Provides functions to generate standard terminal control sequences. - -const std = @import("std"); -const Writer = std.Io.Writer; - -/// ANSI escape codes -pub const ESC = "\x1b"; -pub const CSI = ESC ++ "["; -pub const OSC = ESC ++ "]"; -pub const DCS = ESC ++ "P"; -pub const APC = ESC ++ "_"; -pub const ST = ESC ++ "\\"; - -pub const OscTerminator = enum { - bel, - st, -}; - -pub const Osc52Passthrough = enum { - none, - tmux, - dcs, -}; - -// Cursor control -pub const cursor_hide = CSI ++ "?25l"; -pub const cursor_show = CSI ++ "?25h"; -pub const cursor_save = CSI ++ "s"; -pub const cursor_restore = CSI ++ "u"; -pub const cursor_home = CSI ++ "H"; - -// Screen control -pub const screen_clear = CSI ++ "2J"; -pub const screen_clear_below = CSI ++ "J"; -pub const screen_clear_above = CSI ++ "1J"; -pub const line_clear = CSI ++ "2K"; -pub const line_clear_right = CSI ++ "K"; -pub const line_clear_left = CSI ++ "1K"; - -// Alternate screen buffer -pub const alt_screen_enter = CSI ++ "?1049h"; -pub const alt_screen_exit = CSI ++ "?1049l"; - -// Text attributes reset -pub const reset = CSI ++ "0m"; - -// Bracketed paste mode -pub const bracketed_paste_enable = CSI ++ "?2004h"; -pub const bracketed_paste_disable = CSI ++ "?2004l"; - -// Synchronized output (prevents tearing) -pub const sync_start = CSI ++ "?2026h"; -pub const sync_end = CSI ++ "?2026l"; - -// Unicode width mode (DECRQM/DECSET private mode 2027) -pub const unicode_width_mode_query = CSI ++ "?2027$p"; -pub const unicode_width_mode_enable = CSI ++ "?2027h"; -pub const unicode_width_mode_disable = CSI ++ "?2027l"; - -// Kitty keyboard protocol -pub const kitty_keyboard_enable = CSI ++ ">1u"; -pub const kitty_keyboard_disable = CSI ++ " 0) try writer.print(CSI ++ "{d}A", .{n}); -} - -/// Move cursor down -pub fn cursorDown(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}B", .{n}); -} - -/// Move cursor forward (right) -pub fn cursorForward(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}C", .{n}); -} - -/// Move cursor backward (left) -pub fn cursorBack(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}D", .{n}); -} - -/// Move cursor to column (1-indexed) -pub fn cursorToCol(writer: *Writer, col: u16) !void { - try writer.print(CSI ++ "{d}G", .{col}); -} - -/// Move cursor to column (0-indexed) -pub fn cursorToCol0(writer: *Writer, col: u16) !void { - try writer.print(CSI ++ "{d}G", .{col + 1}); -} - -/// Request cursor position (response: ESC[row;colR) -pub fn requestCursorPos(writer: *Writer) !void { - try writer.writeAll(CSI ++ "6n"); -} - -/// Set scrolling region -pub fn setScrollRegion(writer: *Writer, top: u16, bottom: u16) !void { - try writer.print(CSI ++ "{d};{d}r", .{ top, bottom }); -} - -/// Reset scrolling region -pub fn resetScrollRegion(writer: *Writer) !void { - try writer.writeAll(CSI ++ "r"); -} - -/// Scroll up (content moves up, blank lines at bottom) -pub fn scrollUp(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}S", .{n}); -} - -/// Scroll down (content moves down, blank lines at top) -pub fn scrollDown(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}T", .{n}); -} - -/// Erase n characters from cursor position -pub fn eraseChars(writer: *Writer, n: u16) !void { - try writer.print(CSI ++ "{d}X", .{n}); -} - -/// Insert n blank lines at cursor position -pub fn insertLines(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}L", .{n}); -} - -/// Delete n lines at cursor position -pub fn deleteLines(writer: *Writer, n: u16) !void { - if (n > 0) try writer.print(CSI ++ "{d}M", .{n}); -} - -/// Set window title -pub fn setTitle(writer: *Writer, title: []const u8) !void { - try writer.print(OSC ++ "0;{s}\x07", .{title}); -} - -fn writeOscTerminator(writer: *Writer, terminator: OscTerminator) !void { - switch (terminator) { - .bel => try writer.writeAll("\x07"), - .st => try writer.writeAll(ST), - } -} - -fn writeEscapedForDcs(writer: *Writer, bytes: []const u8) !void { - var start: usize = 0; - for (bytes, 0..) |byte, idx| { - if (byte != 0x1b) continue; - - if (idx > start) { - try writer.writeAll(bytes[start..idx]); - } - try writer.writeAll(ESC ++ ESC); - start = idx + 1; - } - - if (start < bytes.len) { - try writer.writeAll(bytes[start..]); - } -} - -/// Start an OSC 52 sequence and write the fixed header: -/// `OSC 52 ; ;` -pub fn osc52Start( - writer: *Writer, - target: []const u8, - passthrough: Osc52Passthrough, -) !void { - switch (passthrough) { - .none => { - try writer.writeAll(OSC ++ "52;"); - try writer.writeAll(target); - try writer.writeAll(";"); - }, - .tmux => { - try writer.writeAll(DCS ++ "tmux;"); - try writeEscapedForDcs(writer, OSC ++ "52;"); - try writeEscapedForDcs(writer, target); - try writeEscapedForDcs(writer, ";"); - }, - .dcs => { - try writer.writeAll(DCS); - try writeEscapedForDcs(writer, OSC ++ "52;"); - try writeEscapedForDcs(writer, target); - try writeEscapedForDcs(writer, ";"); - }, - } -} - -/// Finish an OSC 52 sequence started by `osc52Start`. -pub fn osc52End(writer: *Writer, terminator: OscTerminator, passthrough: Osc52Passthrough) !void { - switch (passthrough) { - .none => try writeOscTerminator(writer, terminator), - .tmux, .dcs => { - switch (terminator) { - .bel => try writer.writeAll("\x07"), - .st => try writer.writeAll(ESC ++ ESC ++ "\\"), - } - try writer.writeAll(ST); - }, - } -} - -/// Write a complete OSC 52 sequence with a pre-encoded base64 payload. -pub fn osc52Encoded( - writer: *Writer, - target: []const u8, - payload_b64: []const u8, - terminator: OscTerminator, - passthrough: Osc52Passthrough, -) !void { - try osc52Start(writer, target, passthrough); - try writer.writeAll(payload_b64); - try osc52End(writer, terminator, passthrough); -} - -/// SGR (Select Graphic Rendition) codes -pub const SGR = struct { - pub const reset = 0; - pub const bold = 1; - pub const dim = 2; - pub const italic = 3; - pub const underline = 4; - pub const blink = 5; - pub const blink_rapid = 6; - pub const reverse = 7; - pub const hidden = 8; - pub const strikethrough = 9; - - pub const no_bold = 22; - pub const no_italic = 23; - pub const no_underline = 24; - pub const no_blink = 25; - pub const no_reverse = 27; - pub const no_hidden = 28; - pub const no_strikethrough = 29; - - // Foreground colors - pub const fg_black = 30; - pub const fg_red = 31; - pub const fg_green = 32; - pub const fg_yellow = 33; - pub const fg_blue = 34; - pub const fg_magenta = 35; - pub const fg_cyan = 36; - pub const fg_white = 37; - pub const fg_default = 39; - - // Background colors - pub const bg_black = 40; - pub const bg_red = 41; - pub const bg_green = 42; - pub const bg_yellow = 43; - pub const bg_blue = 44; - pub const bg_magenta = 45; - pub const bg_cyan = 46; - pub const bg_white = 47; - pub const bg_default = 49; - - // Bright foreground colors - pub const fg_bright_black = 90; - pub const fg_bright_red = 91; - pub const fg_bright_green = 92; - pub const fg_bright_yellow = 93; - pub const fg_bright_blue = 94; - pub const fg_bright_magenta = 95; - pub const fg_bright_cyan = 96; - pub const fg_bright_white = 97; - - // Bright background colors - pub const bg_bright_black = 100; - pub const bg_bright_red = 101; - pub const bg_bright_green = 102; - pub const bg_bright_yellow = 103; - pub const bg_bright_blue = 104; - pub const bg_bright_magenta = 105; - pub const bg_bright_cyan = 106; - pub const bg_bright_white = 107; -}; - -/// Generate SGR sequence -pub fn sgr(writer: *Writer, codes: []const u8) !void { - try writer.writeAll(CSI); - for (codes, 0..) |code, i| { - if (i > 0) try writer.writeByte(';'); - try writer.print("{d}", .{code}); - } - try writer.writeByte('m'); -} - -/// Generate 256-color foreground -pub fn fg256(writer: *Writer, color: u8) !void { - try writer.print(CSI ++ "38;5;{d}m", .{color}); -} - -/// Generate 256-color background -pub fn bg256(writer: *Writer, color: u8) !void { - try writer.print(CSI ++ "48;5;{d}m", .{color}); -} - -/// Generate true color (24-bit) foreground -pub fn fgRgb(writer: *Writer, r: u8, g: u8, b: u8) !void { - try writer.print(CSI ++ "38;2;{d};{d};{d}m", .{ r, g, b }); -} - -/// Generate true color (24-bit) background -pub fn bgRgb(writer: *Writer, r: u8, g: u8, b: u8) !void { - try writer.print(CSI ++ "48;2;{d};{d};{d}m", .{ r, g, b }); -} - -/// Hyperlink (OSC 8) -pub fn hyperlink(writer: *Writer, url: []const u8, text: []const u8) !void { - try writer.print(OSC ++ "8;;{s}\x07{s}" ++ OSC ++ "8;;\x07", .{ url, text }); -} - -/// Kitty graphics protocol command (APC G ... ST) -pub fn kittyGraphics(writer: *Writer, params: []const u8, payload: []const u8) !void { - try writer.writeAll(APC ++ "G"); - try writer.writeAll(params); - try writer.writeAll(";"); - try writer.writeAll(payload); - try writer.writeAll(ST); -} - -/// iTerm2 inline image command (OSC 1337;File=...:... BEL) -pub fn iterm2InlineImage(writer: *Writer, params: []const u8, payload: []const u8) !void { - try writer.writeAll(OSC ++ "1337;File="); - try writer.writeAll(params); - try writer.writeAll(":"); - try writer.writeAll(payload); - try writer.writeAll("\x07"); -} - -test "osc52Encoded direct BEL" { - var buf: [128]u8 = undefined; - var writer: Writer = .fixed(&buf); - try osc52Encoded(&writer, "c", "YQ==", .bel, .none); - try std.testing.expectEqualStrings("\x1b]52;c;YQ==\x07", writer.buffered()); -} - -test "osc52Encoded direct ST" { - var buf: [128]u8 = undefined; - var writer: Writer = .fixed(&buf); - try osc52Encoded(&writer, "c", "YQ==", .st, .none); - try std.testing.expectEqualStrings("\x1b]52;c;YQ==\x1b\\", writer.buffered()); -} - -test "osc52Encoded tmux passthrough BEL" { - var buf: [256]u8 = undefined; - var writer: Writer = .fixed(&buf); - try osc52Encoded(&writer, "c", "YQ==", .bel, .tmux); - try std.testing.expectEqualStrings("\x1bPtmux;\x1b\x1b]52;c;YQ==\x07\x1b\\", writer.buffered()); -} - -test "osc52Encoded tmux passthrough ST" { - var buf: [256]u8 = undefined; - var writer: Writer = .fixed(&buf); - try osc52Encoded(&writer, "c", "YQ==", .st, .tmux); - try std.testing.expectEqualStrings("\x1bPtmux;\x1b\x1b]52;c;YQ==\x1b\x1b\\\x1b\\", writer.buffered()); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig deleted file mode 100644 index b1261bb..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/posix.zig +++ /dev/null @@ -1,204 +0,0 @@ -//! POSIX terminal implementation for Unix-like systems. -//! Handles raw mode, terminal size, and signal handling. - -const std = @import("std"); -const Writer = std.Io.Writer; -const posix = std.posix; -const ansi = @import("../ansi.zig"); - -pub const TerminalError = error{ - NotATty, - GetAttrFailed, - SetAttrFailed, - IoctlFailed, - PipeFailed, - SignalSetupFailed, -}; - -/// Terminal size -pub const Size = struct { - rows: u16, - cols: u16, -}; - -/// Original terminal state for restoration -pub const State = struct { - original_termios: ?posix.termios = null, - in_raw_mode: bool = false, - in_alt_screen: bool = false, - mouse_enabled: bool = false, - stdin_fd: posix.fd_t, - stdout_fd: posix.fd_t, - - pub fn init() State { - return .{ - .stdin_fd = posix.STDIN_FILENO, - .stdout_fd = posix.STDOUT_FILENO, - }; - } -}; - -/// Check if a file descriptor is a TTY by probing for terminal window size. -/// Replaces `posix.isatty`, which was removed in Zig 0.16; a successful -/// `TIOCGWINSZ` ioctl is only granted to terminal devices. -pub fn isTty(fd: posix.fd_t) bool { - var wsz: posix.winsize = undefined; - return posix.system.ioctl(fd, posix.T.IOCGWINSZ, @intFromPtr(&wsz)) == 0; -} - -/// Get terminal size using ioctl (falls back to 80x24 for non-TTY) -pub fn getSize(fd: posix.fd_t) !Size { - var wsz: posix.winsize = undefined; - const result = posix.system.ioctl(fd, posix.T.IOCGWINSZ, @intFromPtr(&wsz)); - if (result != 0) { - // Fallback to default size for non-TTY (e.g. pipes) - if (!isTty(fd)) { - return .{ .rows = 24, .cols = 80 }; - } - return TerminalError.IoctlFailed; - } - return .{ - .rows = wsz.row, - .cols = wsz.col, - }; -} - -/// Enable raw mode on the terminal -pub fn enableRawMode(state: *State) !void { - if (state.in_raw_mode) return; - - if (!isTty(state.stdin_fd)) { - // Non-TTY (e.g. pipe) — skip raw mode setup but mark as active - state.in_raw_mode = true; - return; - } - - // Save original settings - state.original_termios = posix.tcgetattr(state.stdin_fd) catch { - return TerminalError.GetAttrFailed; - }; - - var raw = state.original_termios.?; - - // Input flags: disable various input processing - raw.iflag.BRKINT = false; - raw.iflag.ICRNL = false; - raw.iflag.INPCK = false; - raw.iflag.ISTRIP = false; - raw.iflag.IXON = false; - - // Output flags: disable output processing - raw.oflag.OPOST = false; - - // Control flags: set 8-bit characters - raw.cflag.CSIZE = .CS8; - - // Local flags: disable echo, canonical mode, signals, extended input - raw.lflag.ECHO = false; - raw.lflag.ICANON = false; - raw.lflag.IEXTEN = false; - raw.lflag.ISIG = false; - - // Control characters: set read timeout - raw.cc[@intFromEnum(posix.V.MIN)] = 0; - raw.cc[@intFromEnum(posix.V.TIME)] = 1; // 0.1 seconds - - posix.tcsetattr(state.stdin_fd, .FLUSH, raw) catch { - return TerminalError.SetAttrFailed; - }; - - state.in_raw_mode = true; -} - -/// Disable raw mode and restore original settings -pub fn disableRawMode(state: *State) void { - if (!state.in_raw_mode) return; - - if (state.original_termios) |termios| { - posix.tcsetattr(state.stdin_fd, .FLUSH, termios) catch {}; - } - - state.in_raw_mode = false; -} - -/// Enter alternate screen buffer -pub fn enterAltScreen(state: *State, writer: *Writer) !void { - if (state.in_alt_screen) return; - - try writer.writeAll(ansi.alt_screen_enter); - state.in_alt_screen = true; -} - -/// Exit alternate screen buffer -pub fn exitAltScreen(state: *State, writer: *Writer) !void { - if (!state.in_alt_screen) return; - - try writer.writeAll(ansi.alt_screen_exit); - state.in_alt_screen = false; -} - -/// Enable mouse tracking -pub fn enableMouse(state: *State, writer: *Writer) !void { - if (state.mouse_enabled) return; - - // Enable SGR mouse mode with all motion tracking - try writer.writeAll("\x1b[?1003h\x1b[?1006h"); - state.mouse_enabled = true; -} - -/// Disable mouse tracking -pub fn disableMouse(state: *State, writer: *Writer) !void { - if (!state.mouse_enabled) return; - - try writer.writeAll("\x1b[?1006l\x1b[?1003l"); - state.mouse_enabled = false; -} - -/// Read available input with timeout -pub fn readInput(state: *State, buffer: []u8, timeout_ms: i32) !usize { - var pollfds = [_]posix.pollfd{ - .{ - .fd = state.stdin_fd, - .events = posix.POLL.IN, - .revents = 0, - }, - }; - - const result = posix.poll(&pollfds, timeout_ms) catch return 0; - - if (result > 0 and (pollfds[0].revents & posix.POLL.IN) != 0) { - return posix.read(state.stdin_fd, buffer) catch 0; - } - - return 0; -} - -/// Flush output -pub fn flush(fd: posix.fd_t) void { - _ = posix.system.fsync(fd); -} - -/// Signal handler state (for SIGWINCH) -var resize_signaled: std.atomic.Value(bool) = std.atomic.Value(bool).init(false); - -/// Setup signal handlers -pub fn setupSignals() !void { - const handler = posix.Sigaction{ - .handler = .{ - .handler = struct { - fn handle(_: posix.SIG) callconv(.c) void { - resize_signaled.store(true, .release); - } - }.handle, - }, - .mask = posix.sigemptyset(), - .flags = 0, - }; - - posix.sigaction(posix.SIG.WINCH, &handler, null); -} - -/// Check if resize was signaled -pub fn checkResize() bool { - return resize_signaled.swap(false, .acquire); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig deleted file mode 100644 index 8fdf695..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/wasm.zig +++ /dev/null @@ -1,178 +0,0 @@ -//! WebAssembly terminal implementation. -//! Communicates with a JavaScript host via imported/exported functions. -//! The JS host is responsible for rendering output to an xterm.js terminal -//! or similar browser-based terminal emulator. - -const std = @import("std"); -const Writer = std.Io.Writer; -const ansi = @import("../ansi.zig"); - -pub const TerminalError = error{ - NotATty, - GetAttrFailed, - SetAttrFailed, -}; - -/// Terminal size -pub const Size = struct { - rows: u16, - cols: u16, -}; - -// ── JS host imports ────────────────────────────────────────────────── -// The JavaScript host must provide these functions. - -extern "zigzag" fn jsWrite(ptr: [*]const u8, len: usize) void; -extern "zigzag" fn jsReadInput(ptr: [*]u8, max_len: usize) usize; -extern "zigzag" fn jsGetWidth() u16; -extern "zigzag" fn jsGetHeight() u16; -extern "zigzag" fn jsSetTitle(ptr: [*]const u8, len: usize) void; - -/// Terminal state for WASM -pub const State = struct { - in_raw_mode: bool = false, - in_alt_screen: bool = false, - mouse_enabled: bool = false, - width: u16 = 80, - height: u16 = 24, - /// Buffer for batching writes before flush. - output_buf: std.array_list.Managed(u8) = undefined, - output_buf_initialized: bool = false, - - pub fn init() State { - return .{}; - } -}; - -/// WASM is always considered a TTY (the JS host provides the terminal). -pub fn isTty(_: anytype) bool { - return true; -} - -/// Get terminal size from the JS host. -pub fn getSize(_: anytype) !Size { - return .{ - .rows = jsGetHeight(), - .cols = jsGetWidth(), - }; -} - -/// Enable raw mode (no-op for WASM, the JS host handles input modes). -pub fn enableRawMode(state: *State) !void { - state.in_raw_mode = true; -} - -/// Disable raw mode. -pub fn disableRawMode(state: *State) void { - state.in_raw_mode = false; -} - -/// Enter alternate screen buffer. -pub fn enterAltScreen(state: *State, writer: *Writer) !void { - if (state.in_alt_screen) return; - try writer.writeAll(ansi.alt_screen_enter); - state.in_alt_screen = true; -} - -/// Exit alternate screen buffer. -pub fn exitAltScreen(state: *State, writer: *Writer) !void { - if (!state.in_alt_screen) return; - try writer.writeAll(ansi.alt_screen_exit); - state.in_alt_screen = false; -} - -/// Enable mouse tracking. -pub fn enableMouse(state: *State, writer: *Writer) !void { - if (state.mouse_enabled) return; - try writer.writeAll("\x1b[?1003h\x1b[?1006h"); - state.mouse_enabled = true; -} - -/// Disable mouse tracking. -pub fn disableMouse(state: *State, writer: *Writer) !void { - if (!state.mouse_enabled) return; - try writer.writeAll("\x1b[?1006l\x1b[?1003l"); - state.mouse_enabled = false; -} - -/// Read available input from the JS host. -pub fn readInput(_: *State, buffer: []u8, _: i32) !usize { - return jsReadInput(buffer.ptr, buffer.len); -} - -/// Flush output to the JS host. -pub fn flush(_: anytype) void { - // Flushing is handled by the writer calling jsWrite directly. -} - -/// Setup signal handlers (no-op for WASM). -pub fn setupSignals() !void {} - -/// Check if resize was signaled. -/// The JS host should call the exported `zigzagResize` to signal this. -var resize_signaled: bool = false; - -pub fn checkResize() bool { - if (@atomicLoad(bool, &resize_signaled, .monotonic)) { - @atomicStore(bool, &resize_signaled, false, .monotonic); - return true; - } - return false; -} - -// ── Exported functions for the JS host to call ────────────────────── - -/// Called by JS when the terminal is resized. -export fn zigzagResize() void { - @atomicStore(bool, &resize_signaled, true, .monotonic); -} - -/// Called by JS to get a pointer to a write buffer. -/// The JS host writes input bytes here, then calls `jsReadInput` to report count. -var input_ring: [4096]u8 = undefined; -var input_write_pos: usize = 0; - -export fn zigzagInputBuffer() [*]u8 { - return &input_ring; -} - -export fn zigzagInputBufferLen() usize { - return input_ring.len; -} - -export fn zigzagPushInput(len: usize) void { - input_write_pos = @min(len, input_ring.len); -} - -/// Unbuffered `std.Io.Writer` adapter that drains bytes to the JS host. -pub const WasmWriter = struct { - writer: Writer, - - const vtable: Writer.VTable = .{ .drain = drain }; - - pub fn init() WasmWriter { - return .{ .writer = .{ .vtable = &vtable, .buffer = &.{} } }; - } - - fn drain(_: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { - // Empty data == pure flush; the splat pattern lives at the last - // element so we must early-return before indexing. - if (data.len == 0) return 0; - - var consumed: usize = 0; - if (data.len > 1) for (data[0 .. data.len - 1]) |chunk| { - if (chunk.len == 0) continue; - jsWrite(chunk.ptr, chunk.len); - consumed += chunk.len; - }; - const pattern = data[data.len - 1]; - if (pattern.len > 0 and splat > 0) { - var i: usize = 0; - while (i < splat) : (i += 1) jsWrite(pattern.ptr, pattern.len); - consumed += pattern.len * splat; - } - return consumed; - } -}; - -pub var wasm_writer_instance: WasmWriter = .init(); diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig deleted file mode 100644 index d370a20..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/platform/windows.zig +++ /dev/null @@ -1,346 +0,0 @@ -//! Windows terminal implementation using Console API. -//! Provides terminal control for Windows systems. - -const std = @import("std"); -const Writer = std.Io.Writer; -const windows = std.os.windows; -const ansi = @import("../ansi.zig"); - -pub const TerminalError = error{ - NotATty, - GetAttrFailed, - SetAttrFailed, - GetConsoleFailed, - SetConsoleFailed, - InvalidHandle, -}; - -/// Terminal size -pub const Size = struct { - rows: u16, - cols: u16, -}; - -/// Console mode flags -const ENABLE_VIRTUAL_TERMINAL_PROCESSING: windows.DWORD = 0x0004; -const ENABLE_VIRTUAL_TERMINAL_INPUT: windows.DWORD = 0x0200; -const ENABLE_PROCESSED_INPUT: windows.DWORD = 0x0001; -const ENABLE_LINE_INPUT: windows.DWORD = 0x0002; -const ENABLE_ECHO_INPUT: windows.DWORD = 0x0004; -const ENABLE_MOUSE_INPUT: windows.DWORD = 0x0010; -const ENABLE_WINDOW_INPUT: windows.DWORD = 0x0008; -const ENABLE_EXTENDED_FLAGS: windows.DWORD = 0x0080; -const ENABLE_QUICK_EDIT_MODE: windows.DWORD = 0x0040; -const FILE_TYPE_CHAR: windows.DWORD = 0x0002; -const FILE_TYPE_PIPE: windows.DWORD = 0x0003; -const KEY_EVENT: windows.WORD = 0x0001; -const MOUSE_EVENT: windows.WORD = 0x0002; -const INFINITE: windows.DWORD = 0xFFFFFFFF; -const WAIT_OBJECT_0: windows.DWORD = 0x00000000; -const CP_UTF8: windows.UINT = 65001; - -/// Terminal state for Windows -pub const State = struct { - original_input_mode: windows.DWORD = 0, - original_output_mode: windows.DWORD = 0, - original_output_cp: windows.UINT = 0, - original_input_cp: windows.UINT = 0, - in_raw_mode: bool = false, - in_alt_screen: bool = false, - mouse_enabled: bool = false, - stdin_handle: windows.HANDLE, - stdout_handle: windows.HANDLE, - - pub fn init() State { - return .{ - .stdin_handle = std.Io.File.stdin().handle, - .stdout_handle = std.Io.File.stdout().handle, - }; - } -}; - -/// External Windows API declarations -extern "kernel32" fn GetConsoleMode(hConsole: windows.HANDLE, lpMode: *windows.DWORD) callconv(.winapi) windows.BOOL; -extern "kernel32" fn SetConsoleMode(hConsole: windows.HANDLE, dwMode: windows.DWORD) callconv(.winapi) windows.BOOL; -extern "kernel32" fn GetConsoleScreenBufferInfo(hConsole: windows.HANDLE, lpInfo: *CONSOLE_SCREEN_BUFFER_INFO) callconv(.winapi) windows.BOOL; -extern "kernel32" fn GetFileType(hFile: windows.HANDLE) callconv(.winapi) windows.DWORD; -extern "kernel32" fn PeekNamedPipe( - hNamedPipe: windows.HANDLE, - lpBuffer: ?*anyopaque, - nBufferSize: windows.DWORD, - lpBytesRead: ?*windows.DWORD, - lpTotalBytesAvail: ?*windows.DWORD, - lpBytesLeftThisMessage: ?*windows.DWORD, -) callconv(.winapi) windows.BOOL; -extern "kernel32" fn GetNumberOfConsoleInputEvents( - hConsoleInput: windows.HANDLE, - lpcNumberOfEvents: *windows.DWORD, -) callconv(.winapi) windows.BOOL; -extern "kernel32" fn PeekConsoleInputW( - hConsoleInput: windows.HANDLE, - lpBuffer: [*]INPUT_RECORD, - nLength: windows.DWORD, - lpNumberOfEventsRead: *windows.DWORD, -) callconv(.winapi) windows.BOOL; -extern "kernel32" fn ReadConsoleInputW( - hConsoleInput: windows.HANDLE, - lpBuffer: [*]INPUT_RECORD, - nLength: windows.DWORD, - lpNumberOfEventsRead: *windows.DWORD, -) callconv(.winapi) windows.BOOL; -extern "kernel32" fn WaitForSingleObject( - hHandle: windows.HANDLE, - dwMilliseconds: windows.DWORD, -) callconv(.winapi) windows.DWORD; -extern "kernel32" fn ReadFile( - hFile: windows.HANDLE, - lpBuffer: [*]u8, - nNumberOfBytesToRead: windows.DWORD, - lpNumberOfBytesRead: ?*windows.DWORD, - lpOverlapped: ?*anyopaque, -) callconv(.winapi) windows.BOOL; -extern "kernel32" fn GetConsoleOutputCP() callconv(.winapi) windows.UINT; -extern "kernel32" fn SetConsoleOutputCP(wCodePageID: windows.UINT) callconv(.winapi) windows.BOOL; -extern "kernel32" fn GetConsoleCP() callconv(.winapi) windows.UINT; -extern "kernel32" fn SetConsoleCP(wCodePageID: windows.UINT) callconv(.winapi) windows.BOOL; - -const CONSOLE_SCREEN_BUFFER_INFO = extern struct { - dwSize: COORD, - dwCursorPosition: COORD, - wAttributes: windows.WORD, - srWindow: SMALL_RECT, - dwMaximumWindowSize: COORD, -}; - -const COORD = extern struct { - X: windows.SHORT, - Y: windows.SHORT, -}; - -const SMALL_RECT = extern struct { - Left: windows.SHORT, - Top: windows.SHORT, - Right: windows.SHORT, - Bottom: windows.SHORT, -}; - -const INPUT_RECORD = extern struct { - EventType: windows.WORD, - Event: INPUT_EVENT, -}; - -const INPUT_EVENT = extern union { - KeyEvent: KEY_EVENT_RECORD, - MouseEvent: [16]u8, - WindowBufferSizeEvent: [4]u8, - MenuEvent: [4]u8, - FocusEvent: [4]u8, -}; - -const KEY_EVENT_RECORD = extern struct { - bKeyDown: windows.BOOL, - wRepeatCount: windows.WORD, - wVirtualKeyCode: windows.WORD, - wVirtualScanCode: windows.WORD, - uChar: extern union { - UnicodeChar: windows.WCHAR, - AsciiChar: windows.CHAR, - }, - dwControlKeyState: windows.DWORD, -}; - -/// Check if a handle is valid -pub fn isTty(handle: windows.HANDLE) bool { - if (handle == windows.INVALID_HANDLE_VALUE) return false; - var mode: windows.DWORD = 0; - return GetConsoleMode(handle, &mode).toBool(); -} - -/// Get terminal size -pub fn getSize(handle: windows.HANDLE) !Size { - var info: CONSOLE_SCREEN_BUFFER_INFO = undefined; - if (!GetConsoleScreenBufferInfo(handle, &info).toBool()) { - return TerminalError.GetConsoleFailed; - } - return .{ - .rows = @intCast(info.srWindow.Bottom - info.srWindow.Top + 1), - .cols = @intCast(info.srWindow.Right - info.srWindow.Left + 1), - }; -} - -/// Enable raw mode -pub fn enableRawMode(state: *State) !void { - if (state.in_raw_mode) return; - - if (state.stdin_handle == windows.INVALID_HANDLE_VALUE or - state.stdout_handle == windows.INVALID_HANDLE_VALUE) - { - return TerminalError.InvalidHandle; - } - - // Save original modes - if (!GetConsoleMode(state.stdin_handle, &state.original_input_mode).toBool()) { - return TerminalError.GetConsoleFailed; - } - if (!GetConsoleMode(state.stdout_handle, &state.original_output_mode).toBool()) { - return TerminalError.GetConsoleFailed; - } - - // Set input mode for raw input with VT processing. - // Avoid WINDOW_INPUT because it can signal wait handles without producing bytes for ReadFile. - const input_mode: windows.DWORD = ENABLE_VIRTUAL_TERMINAL_INPUT; - if (!SetConsoleMode(state.stdin_handle, input_mode).toBool()) { - return TerminalError.SetConsoleFailed; - } - - // Enable VT processing on output - const output_mode: windows.DWORD = state.original_output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING; - if (!SetConsoleMode(state.stdout_handle, output_mode).toBool()) { - // Restore input mode and fail - _ = SetConsoleMode(state.stdin_handle, state.original_input_mode); - return TerminalError.SetConsoleFailed; - } - - // Switch the console code pages to UTF-8 so multi-byte sequences (box-drawing, - // emoji, etc.) emitted by the renderer aren't reinterpreted as the OEM codepage. - state.original_output_cp = GetConsoleOutputCP(); - state.original_input_cp = GetConsoleCP(); - _ = SetConsoleOutputCP(CP_UTF8); - _ = SetConsoleCP(CP_UTF8); - - state.in_raw_mode = true; -} - -/// Disable raw mode -pub fn disableRawMode(state: *State) void { - if (!state.in_raw_mode) return; - - _ = SetConsoleMode(state.stdin_handle, state.original_input_mode); - _ = SetConsoleMode(state.stdout_handle, state.original_output_mode); - if (state.original_output_cp != 0) _ = SetConsoleOutputCP(state.original_output_cp); - if (state.original_input_cp != 0) _ = SetConsoleCP(state.original_input_cp); - - state.in_raw_mode = false; -} - -/// Enter alternate screen buffer -pub fn enterAltScreen(state: *State, writer: *Writer) !void { - if (state.in_alt_screen) return; - - try writer.writeAll(ansi.alt_screen_enter); - state.in_alt_screen = true; -} - -/// Exit alternate screen buffer -pub fn exitAltScreen(state: *State, writer: *Writer) !void { - if (!state.in_alt_screen) return; - - try writer.writeAll(ansi.alt_screen_exit); - state.in_alt_screen = false; -} - -/// Enable mouse tracking -pub fn enableMouse(state: *State, writer: *Writer) !void { - if (state.mouse_enabled) return; - - // Enable mouse input in console mode - if (state.stdin_handle != windows.INVALID_HANDLE_VALUE) { - var mode: windows.DWORD = 0; - if (GetConsoleMode(state.stdin_handle, &mode).toBool()) { - _ = SetConsoleMode(state.stdin_handle, mode | ENABLE_MOUSE_INPUT); - } - } - - // Also send ANSI sequences for VT mode - try writer.writeAll("\x1b[?1003h\x1b[?1006h"); - state.mouse_enabled = true; -} - -/// Disable mouse tracking -pub fn disableMouse(state: *State, writer: *Writer) !void { - if (!state.mouse_enabled) return; - - try writer.writeAll("\x1b[?1006l\x1b[?1003l"); - state.mouse_enabled = false; -} - -/// Read available input (Windows uses std.Io) -pub fn readInput(state: *State, buffer: []u8, timeout_ms: i32) !usize { - if (state.stdin_handle == windows.INVALID_HANDLE_VALUE) return 0; - - // Match POSIX behavior: wait up to timeout_ms for input, then return 0. - const wait_ms: windows.DWORD = if (timeout_ms < 0) - INFINITE - else - @intCast(timeout_ms); - - if (WaitForSingleObject(state.stdin_handle, wait_ms) != WAIT_OBJECT_0) return 0; - - const file_type = GetFileType(state.stdin_handle); - - // ConPTY/Windows Terminal can expose stdin as a pipe. Ensure there are bytes before reading. - if (file_type == FILE_TYPE_PIPE) { - var available: windows.DWORD = 0; - if (!PeekNamedPipe(state.stdin_handle, null, 0, null, &available, null).toBool() or available == 0) { - return 0; - } - } - - // Console handles may wake due non-byte events (focus/menu/window-size). Drain those first. - if (file_type == FILE_TYPE_CHAR and !hasReadableConsoleInput(state.stdin_handle)) { - return 0; - } - - // Read from the configured stdin handle after it is signaled as readable. - var bytes_read: windows.DWORD = 0; - if (!ReadFile(state.stdin_handle, buffer.ptr, @intCast(buffer.len), &bytes_read, null).toBool()) return 0; - return bytes_read; -} - -fn hasReadableConsoleInput(handle: windows.HANDLE) bool { - var record_buf: [1]INPUT_RECORD = undefined; - - while (true) { - var event_count: windows.DWORD = 0; - if (!GetNumberOfConsoleInputEvents(handle, &event_count).toBool() or event_count == 0) { - return false; - } - - var peeked: windows.DWORD = 0; - if (!PeekConsoleInputW(handle, &record_buf, 1, &peeked).toBool() or peeked == 0) { - return false; - } - - const record = record_buf[0]; - switch (record.EventType) { - KEY_EVENT => { - if (record.Event.KeyEvent.bKeyDown.toBool()) return true; - }, - MOUSE_EVENT => return true, - else => {}, - } - - var consumed: windows.DWORD = 0; - if (!ReadConsoleInputW(handle, &record_buf, 1, &consumed).toBool() or consumed == 0) { - return false; - } - } -} - -/// Flush output -pub fn flush(handle: windows.HANDLE) void { - _ = handle; - // Windows typically auto-flushes -} - -/// Setup signal handlers (Windows uses console events differently) -pub fn setupSignals() !void { - // Windows handles resize through WINDOW_BUFFER_SIZE_EVENT - // This is handled in the input loop -} - -/// Check if resize was signaled -pub fn checkResize() bool { - // On Windows, resize is handled through console events - return false; -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig deleted file mode 100644 index e877467..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/screen.zig +++ /dev/null @@ -1,306 +0,0 @@ -//! Screen buffer management for efficient terminal rendering. -//! Provides double-buffering to minimize flickering and optimize updates. - -const std = @import("std"); -const Writer = std.Io.Writer; -const ansi = @import("ansi.zig"); -const unicode = @import("../unicode.zig"); - -/// A cell in the screen buffer -pub const Cell = struct { - char: u21 = ' ', - fg: ?Color = null, - bg: ?Color = null, - bold: bool = false, - dim: bool = false, - italic: bool = false, - underline: bool = false, - blink: bool = false, - reverse: bool = false, - strikethrough: bool = false, - /// True if this cell is the continuation (right half) of a wide character. - wide: bool = false, - - pub fn eql(self: Cell, other: Cell) bool { - return self.char == other.char and - eqlOptColor(self.fg, other.fg) and - eqlOptColor(self.bg, other.bg) and - self.bold == other.bold and - self.dim == other.dim and - self.italic == other.italic and - self.underline == other.underline and - self.blink == other.blink and - self.reverse == other.reverse and - self.strikethrough == other.strikethrough and - self.wide == other.wide; - } - - fn eqlOptColor(a: ?Color, b: ?Color) bool { - if (a == null and b == null) return true; - if (a == null or b == null) return false; - return a.?.eql(b.?); - } -}; - -/// Color representation -pub const Color = struct { - r: u8, - g: u8, - b: u8, - - pub fn eql(self: Color, other: Color) bool { - return self.r == other.r and self.g == other.g and self.b == other.b; - } -}; - -/// Screen buffer for rendering -pub const Screen = struct { - allocator: std.mem.Allocator, - cells: []Cell, - width: u16, - height: u16, - - pub fn init(allocator: std.mem.Allocator, width: u16, height: u16) !Screen { - const size = @as(usize, width) * @as(usize, height); - const cells = try allocator.alloc(Cell, size); - @memset(cells, Cell{}); - - return .{ - .allocator = allocator, - .cells = cells, - .width = width, - .height = height, - }; - } - - pub fn deinit(self: *Screen) void { - self.allocator.free(self.cells); - } - - pub fn resize(self: *Screen, new_width: u16, new_height: u16) !void { - const new_size = @as(usize, new_width) * @as(usize, new_height); - const new_cells = try self.allocator.alloc(Cell, new_size); - @memset(new_cells, Cell{}); - - // Copy existing content - const copy_height = @min(self.height, new_height); - const copy_width = @min(self.width, new_width); - - for (0..copy_height) |y| { - const old_row_start = y * self.width; - const new_row_start = y * new_width; - @memcpy( - new_cells[new_row_start..][0..copy_width], - self.cells[old_row_start..][0..copy_width], - ); - } - - self.allocator.free(self.cells); - self.cells = new_cells; - self.width = new_width; - self.height = new_height; - } - - pub fn clear(self: *Screen) void { - @memset(self.cells, Cell{}); - } - - pub fn getCell(self: *const Screen, x: u16, y: u16) ?*const Cell { - if (x >= self.width or y >= self.height) return null; - return &self.cells[@as(usize, y) * self.width + x]; - } - - pub fn setCell(self: *Screen, x: u16, y: u16, cell: Cell) void { - if (x >= self.width or y >= self.height) return; - const idx = @as(usize, y) * self.width + x; - - // If we're overwriting a wide-char continuation cell, clear the left half - if (self.cells[idx].wide and x > 0) { - self.cells[idx - 1] = Cell{}; - } - // If we're overwriting the left half of a wide char, clear the continuation - if (!self.cells[idx].wide and x + 1 < self.width and self.cells[idx + 1].wide) { - self.cells[idx + 1] = Cell{}; - } - - self.cells[idx] = cell; - - // If this is a wide character, set the continuation cell - const cw = unicode.charWidth(cell.char); - if (cw == 2 and x + 1 < self.width) { - var cont = Cell{}; - cont.wide = true; - cont.fg = cell.fg; - cont.bg = cell.bg; - self.cells[idx + 1] = cont; - } - } - - pub fn setChar(self: *Screen, x: u16, y: u16, char: u21) void { - if (x >= self.width or y >= self.height) return; - var cell = self.cells[@as(usize, y) * self.width + x]; - cell.char = char; - cell.wide = false; - self.setCell(x, y, cell); - } - - /// Write a string to the screen at the given position - pub fn writeString(self: *Screen, x: u16, y: u16, str: []const u8) u16 { - var col = x; - var utf8 = std.unicode.Utf8View.init(str) catch return 0; - var iter = utf8.iterator(); - - while (iter.nextCodepoint()) |cp| { - const cw = unicode.charWidth(cp); - if (cw == 0) continue; // Skip zero-width characters - if (col + cw > self.width) break; // Wide char won't fit - self.setChar(col, y, cp); - col += @intCast(cw); - } - - return col - x; - } - - /// Render screen differences to the writer - pub fn renderDiff(self: *const Screen, prev: *const Screen, writer: *Writer) !void { - var last_x: u16 = 0; - var last_y: u16 = 0; - var need_move = true; - var current_cell = Cell{}; - - for (0..self.height) |y_usize| { - const y: u16 = @intCast(y_usize); - var x_usize: usize = 0; - while (x_usize < self.width) { - const x: u16 = @intCast(x_usize); - const idx = y_usize * self.width + x_usize; - const cell = self.cells[idx]; - - // Skip wide continuation cells - if (cell.wide) { - x_usize += 1; - need_move = true; - continue; - } - - const prev_cell = if (idx < prev.cells.len) prev.cells[idx] else Cell{}; - - if (!cell.eql(prev_cell)) { - // Need to update this cell - if (need_move or x != last_x + 1 or y != last_y) { - try ansi.cursorTo0(writer, y, x); - need_move = false; - } - - // Apply style changes - try applyStyle(writer, ¤t_cell, cell); - current_cell = cell; - - // Write character - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(cell.char, &buf) catch 1; - try writer.writeAll(buf[0..len]); - - const cw = unicode.charWidth(cell.char); - last_x = if (cw == 2) x + 1 else x; - last_y = y; - x_usize += cw; - } else { - x_usize += 1; - } - } - } - - // Reset styles at the end - try writer.writeAll(ansi.reset); - } - - /// Render entire screen to writer - pub fn render(self: *const Screen, writer: *Writer) !void { - try writer.writeAll(ansi.cursor_home); - try writer.writeAll(ansi.reset); - - var current_cell = Cell{}; - - for (0..self.height) |y_usize| { - if (y_usize > 0) { - try writer.writeAll("\r\n"); - } - - var x_usize: usize = 0; - while (x_usize < self.width) { - const idx = y_usize * self.width + x_usize; - const cell = self.cells[idx]; - - // Skip wide continuation cells - if (cell.wide) { - x_usize += 1; - continue; - } - - try applyStyle(writer, ¤t_cell, cell); - current_cell = cell; - - var buf: [4]u8 = undefined; - const len = std.unicode.utf8Encode(cell.char, &buf) catch 1; - try writer.writeAll(buf[0..len]); - - const cw = unicode.charWidth(cell.char); - x_usize += if (cw > 0) cw else 1; - } - } - - try writer.writeAll(ansi.reset); - } - - fn applyStyle(writer: *Writer, current: *Cell, new: Cell) !void { - var needs_reset = false; - - // Check if we need to reset (turning off attributes) - if ((current.bold and !new.bold) or - (current.dim and !new.dim) or - (current.italic and !new.italic) or - (current.underline and !new.underline) or - (current.blink and !new.blink) or - (current.reverse and !new.reverse) or - (current.strikethrough and !new.strikethrough)) - { - needs_reset = true; - try writer.writeAll(ansi.reset); - current.* = Cell{}; - } - - // Apply foreground color - if (!eqlOptColor(current.fg, new.fg)) { - if (new.fg) |fg| { - try ansi.fgRgb(writer, fg.r, fg.g, fg.b); - } else { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.fg_default}); - } - } - - // Apply background color - if (!eqlOptColor(current.bg, new.bg)) { - if (new.bg) |bg| { - try ansi.bgRgb(writer, bg.r, bg.g, bg.b); - } else { - try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bg_default}); - } - } - - // Apply text attributes - if (!current.bold and new.bold) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.bold}); - if (!current.dim and new.dim) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.dim}); - if (!current.italic and new.italic) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.italic}); - if (!current.underline and new.underline) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.underline}); - if (!current.blink and new.blink) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.blink}); - if (!current.reverse and new.reverse) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.reverse}); - if (!current.strikethrough and new.strikethrough) try writer.print(ansi.CSI ++ "{d}m", .{ansi.SGR.strikethrough}); - } - - fn eqlOptColor(a: ?Color, b: ?Color) bool { - if (a == null and b == null) return true; - if (a == null or b == null) return false; - return a.?.eql(b.?); - } -}; diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig deleted file mode 100644 index 0e07e58..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/terminal/terminal.zig +++ /dev/null @@ -1,1914 +0,0 @@ -//! Terminal abstraction layer providing cross-platform terminal control. -//! Handles raw mode, alternate screen, mouse tracking, and input/output. - -const std = @import("std"); -const FixedWriter = std.Io.Writer.fixed; -const builtin = @import("builtin"); -pub const ansi = @import("ansi.zig"); -pub const screen = @import("screen.zig"); -const unicode = @import("../unicode.zig"); - -// Platform-specific implementation -const is_wasm = builtin.os.tag == .wasi or builtin.cpu.arch == .wasm32 or builtin.cpu.arch == .wasm64; -const platform = if (is_wasm) - @import("platform/wasm.zig") -else if (builtin.os.tag == .windows) - @import("platform/windows.zig") -else - @import("platform/posix.zig"); - -pub const Size = platform.Size; -pub const TerminalError = platform.TerminalError; - -pub const UnicodeWidthCapabilities = struct { - mode_2027: bool = false, - kitty_text_sizing: bool = false, - strategy: unicode.WidthStrategy = .legacy_wcwidth, -}; - -pub const ImageCapabilities = struct { - kitty_graphics: bool = false, - iterm2_inline_image: bool = false, - sixel: bool = false, -}; - -const Iterm2Capabilities = struct { - inline_image: bool = false, - sixel: bool = false, -}; - -pub const KittyImageFormat = enum(u16) { - rgb = 24, - rgba = 32, - png = 100, -}; - -pub const KittyImageOptions = struct { - format: KittyImageFormat = .png, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - /// Z-index for layering. Negative = behind text, positive = above. - z_index: ?i32 = null, - /// Enable unicode placeholders for text-reflow participation. - unicode_placeholder: bool = false, - /// Pixel width of the image (required for RGB/RGBA direct data). - pixel_width: ?u32 = null, - /// Pixel height of the image (required for RGB/RGBA direct data). - pixel_height: ?u32 = null, -}; - -pub const KittyImageFileOptions = struct { - width_cells: ?u16 = null, - height_cells: ?u16 = null, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// Options for transmitting an image to the Kitty cache without display. -pub const KittyTransmitOptions = struct { - image_id: u32, - format: KittyImageFormat = .png, - quiet: bool = true, - pixel_width: ?u32 = null, - pixel_height: ?u32 = null, -}; - -/// Options for placing a previously cached Kitty image. -pub const KittyPlaceOptions = struct { - image_id: u32, - placement_id: ?u32 = null, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - move_cursor: bool = true, - quiet: bool = true, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// What to delete from the Kitty image cache. -pub const KittyDeleteTarget = union(enum) { - by_id: u32, - by_placement: struct { image_id: u32, placement_id: u32 }, - all, -}; - -pub const Iterm2ImageFileOptions = struct { - width_cells: ?u16 = null, - height_cells: ?u16 = null, - preserve_aspect_ratio: bool = true, - move_cursor: bool = true, -}; - -/// Options for in-memory iTerm2 image rendering. -pub const Iterm2ImageDataOptions = struct { - width_cells: ?u16 = null, - height_cells: ?u16 = null, - preserve_aspect_ratio: bool = true, - move_cursor: bool = true, -}; - -pub const ImageFileOptions = struct { - width_cells: ?u16 = null, - height_cells: ?u16 = null, - preserve_aspect_ratio: bool = true, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// Options for rendering in-memory image data with auto protocol selection. -pub const ImageDataOptions = struct { - format: KittyImageFormat = .png, - pixel_width: ?u32 = null, - pixel_height: ?u32 = null, - width_cells: ?u16 = null, - height_cells: ?u16 = null, - preserve_aspect_ratio: bool = true, - image_id: ?u32 = null, - placement_id: ?u32 = null, - move_cursor: bool = true, - quiet: bool = true, - z_index: ?i32 = null, - unicode_placeholder: bool = false, -}; - -/// Preferred image protocol for protocol-selection overrides. -pub const ImageProtocol = enum { - auto, - kitty, - iterm2, - sixel, -}; - -pub const SixelImageFileOptions = struct { - /// Optional max captured converter output (bytes). - max_output_bytes: usize = 32 * 1024 * 1024, - /// Optional pixel width hint for img2sixel (-w flag). - width_pixels: ?u32 = null, - /// Optional pixel height hint for img2sixel (-h flag). - height_pixels: ?u32 = null, -}; - -/// OSC 52 clipboard target selector. -/// Standard values are `c`, `p`, `q`, `s`, or cut buffers `0`..`7`. -pub const Osc52Target = union(enum) { - clipboard, - primary, - secondary, - select, - cut_buffer: u3, - raw: []const u8, - - fn encode(self: Osc52Target, scratch: *[1]u8) []const u8 { - return switch (self) { - .clipboard => "c", - .primary => "p", - .secondary => "q", - .select => "s", - .cut_buffer => |n| blk: { - scratch[0] = @as(u8, '0') + @as(u8, n); - break :blk scratch[0..1]; - }, - .raw => |value| value, - }; - } -}; - -/// OSC 52 passthrough strategy. -/// `tmux` and `dcs` wrap OSC inside DCS passthrough for multiplexers. -pub const Osc52Passthrough = enum { - auto, - none, - tmux, - dcs, -}; - -/// Default OSC 52 behavior for this terminal instance. -pub const Osc52Config = struct { - /// Master switch for clipboard writes. - enabled: bool = true, - /// Allow OSC 52 clipboard queries (`?`) for reading clipboard content. - query_enabled: bool = true, - /// Require a TTY before sending OSC 52. - require_tty: bool = true, - /// Default target selection. - target: Osc52Target = .clipboard, - /// Sequence terminator (BEL is widely compatible). - terminator: ansi.OscTerminator = .bel, - /// Passthrough mode (`auto` detects tmux/screen-like environments). - passthrough: Osc52Passthrough = .auto, - /// Optional input payload limit (bytes). `null` = no library limit. - max_bytes: ?usize = null, - /// Query timeout for clipboard reads. - query_timeout_ms: i32 = 180, - /// Optional decoded output limit for clipboard reads. - max_read_bytes: ?usize = null, - /// Require selector match on responses (strict mode). - strict_query_target: bool = false, -}; - -/// Per-call OSC 52 overrides. -pub const Osc52WriteOptions = struct { - target: ?Osc52Target = null, - terminator: ?ansi.OscTerminator = null, - passthrough: ?Osc52Passthrough = null, - require_tty: ?bool = null, - max_bytes: ?usize = null, -}; - -/// Per-call OSC 52 clipboard query overrides. -pub const Osc52ReadOptions = struct { - target: ?Osc52Target = null, - terminator: ?ansi.OscTerminator = null, - passthrough: ?Osc52Passthrough = null, - require_tty: ?bool = null, - timeout_ms: ?i32 = null, - max_bytes: ?usize = null, - strict_target: ?bool = null, -}; - -/// Terminal configuration options -pub const Config = struct { - /// Use alternate screen buffer - alt_screen: bool = true, - /// Hide cursor during operation - hide_cursor: bool = true, - /// Enable mouse tracking - mouse: bool = false, - /// Enable bracketed paste mode - bracketed_paste: bool = true, - /// Custom input file (default: stdin) - input: ?std.Io.File = null, - /// Custom output file (default: stdout) - output: ?std.Io.File = null, - /// Enable Kitty keyboard protocol - kitty_keyboard: bool = false, - /// OSC 52 clipboard configuration - osc52: Osc52Config = .{}, -}; - -/// Terminal abstraction -pub const Terminal = struct { - io: std.Io, - environ_map: *const std.process.Environ.Map, - state: platform.State, - config: Config, - stdin: std.Io.File, - out: Writer, - pending_input: [8192]u8 = undefined, - pending_input_len: usize = 0, - unicode_width_caps: UnicodeWidthCapabilities = .{}, - image_caps: ImageCapabilities = .{}, - - pub fn init(io: std.Io, environ_map: *const std.process.Environ.Map, config: Config) !Terminal { - var state = platform.State.init(); - - var term: Terminal = if (is_wasm) .{ - .io = io, - .environ_map = environ_map, - .state = state, - .config = config, - .stdin = undefined, - .out = .init(io, {}), - } else blk: { - const stdout = config.output orelse std.Io.File.stdout(); - const stdin = config.input orelse std.Io.File.stdin(); - - // Apply custom fd overrides - if (builtin.os.tag != .windows) { - if (config.input) |inp| state.stdin_fd = inp.handle; - if (config.output) |o| state.stdout_fd = o.handle; - } else { - if (config.input) |inp| state.stdin_handle = inp.handle; - if (config.output) |o| state.stdout_handle = o.handle; - } - - break :blk .{ - .io = io, - .environ_map = environ_map, - .state = state, - .config = config, - .stdin = stdin, - .out = .init(io, stdout), - }; - }; - - try term.setup(); - return term; - } - - pub fn deinit(self: *Terminal) void { - self.cleanup(); - } - - pub fn setup(self: *Terminal) !void { - // Setup signal handlers - platform.setupSignals() catch {}; - - // Enable raw mode - try platform.enableRawMode(&self.state); - - // Enter alternate screen - if (self.config.alt_screen) { - try self.writeBytes(ansi.alt_screen_enter); - self.state.in_alt_screen = true; - } - - // Hide cursor - if (self.config.hide_cursor) { - try self.writeBytes(ansi.cursor_hide); - } - - // Enable mouse - if (self.config.mouse) { - try self.writeBytes("\x1b[?1003h\x1b[?1006h"); - self.state.mouse_enabled = true; - } - - // Enable bracketed paste - if (self.config.bracketed_paste) { - try self.writeBytes(ansi.bracketed_paste_enable); - } - - // Enable Kitty keyboard protocol - if (self.config.kitty_keyboard) { - try self.writeBytes(ansi.kitty_keyboard_enable); - } - - self.detectUnicodeWidthCapabilities(); - self.detectImageCapabilities(); - - // Clear screen - try self.writeBytes(ansi.screen_clear); - try self.writeBytes(ansi.cursor_home); - - try self.flush(); - } - - pub fn cleanup(self: *Terminal) void { - // Disable Kitty keyboard protocol - if (self.config.kitty_keyboard) { - self.writeBytes(ansi.kitty_keyboard_disable) catch {}; - } - - if (self.unicode_width_caps.mode_2027) { - self.writeBytes(ansi.unicode_width_mode_disable) catch {}; - self.unicode_width_caps.mode_2027 = false; - } - - // Disable bracketed paste - if (self.config.bracketed_paste) { - self.writeBytes(ansi.bracketed_paste_disable) catch {}; - } - - // Disable mouse - if (self.state.mouse_enabled) { - self.writeBytes("\x1b[?1006l\x1b[?1003l") catch {}; - self.state.mouse_enabled = false; - } - - // Show cursor - if (self.config.hide_cursor) { - self.writeBytes(ansi.cursor_show) catch {}; - } - - // Exit alternate screen - if (self.state.in_alt_screen) { - self.writeBytes(ansi.alt_screen_exit) catch {}; - self.state.in_alt_screen = false; - } - - // Reset attributes - self.writeBytes(ansi.reset) catch {}; - - self.flush() catch {}; - - // Restore terminal mode — always runs even if writes above failed - platform.disableRawMode(&self.state); - } - - /// Write bytes through the buffered terminal writer. - fn writeBytes(self: *Terminal, bytes: []const u8) !void { - try self.writer().writeAll(bytes); - } - - /// Get terminal size - pub fn getSize(self: *Terminal) !Size { - if (is_wasm) { - return platform.getSize({}); - } else if (builtin.os.tag == .windows) { - return platform.getSize(self.state.stdout_handle); - } else { - return platform.getSize(self.state.stdout_fd); - } - } - - /// Read input with timeout (in milliseconds) - pub fn readInput(self: *Terminal, buffer: []u8, timeout_ms: i32) !usize { - if (self.pending_input_len > 0) { - const take = @min(buffer.len, self.pending_input_len); - @memcpy(buffer[0..take], self.pending_input[0..take]); - if (take < self.pending_input_len) { - std.mem.copyForwards(u8, self.pending_input[0 .. self.pending_input_len - take], self.pending_input[take..self.pending_input_len]); - } - self.pending_input_len -= take; - return take; - } - return self.readPlatformInput(buffer, timeout_ms); - } - - /// Check if terminal was resized - pub fn checkResize(self: *Terminal) bool { - _ = self; - return platform.checkResize(); - } - - /// Get a Writer interface. - pub fn writer(self: *Terminal) *std.Io.Writer { - self.out.bind(); - return &self.out.writer; - } - - /// Flush buffered terminal output to the underlying sink. - pub fn flush(self: *Terminal) !void { - try self.writer().flush(); - } - - /// Clear the screen - pub fn clear(self: *Terminal) !void { - try self.writeBytes(ansi.screen_clear); - try self.writeBytes(ansi.cursor_home); - } - - /// Move cursor to position (0-indexed) - pub fn moveTo(self: *Terminal, row: u16, col: u16) !void { - var buf: [32]u8 = undefined; - const len = std.fmt.bufPrint(&buf, "\x1b[{d};{d}H", .{ row + 1, col + 1 }) catch return; - try self.writeBytes(len); - } - - /// Show the cursor - pub fn showCursor(self: *Terminal) !void { - try self.writeBytes(ansi.cursor_show); - } - - /// Hide the cursor - pub fn hideCursor(self: *Terminal) !void { - try self.writeBytes(ansi.cursor_hide); - } - - /// Enable mouse tracking - pub fn enableMouse(self: *Terminal) !void { - try self.writeBytes("\x1b[?1003h\x1b[?1006h"); - self.state.mouse_enabled = true; - } - - /// Disable mouse tracking - pub fn disableMouse(self: *Terminal) !void { - try self.writeBytes("\x1b[?1006l\x1b[?1003l"); - self.state.mouse_enabled = false; - } - - /// Set window title - pub fn setTitle(self: *Terminal, title: []const u8) !void { - try self.writeBytes("\x1b]0;"); - try self.writeBytes(title); - try self.writeBytes("\x07"); - } - - /// Copy bytes to the system clipboard using OSC 52 with instance defaults. - /// Returns `false` when disabled by config, rejected by local guardrails, or not suitable for this output. - pub fn setClipboard(self: *Terminal, bytes: []const u8) !bool { - return self.setClipboardWithOptions(bytes, .{}); - } - - /// Copy bytes to the system clipboard using OSC 52 with per-call overrides. - pub fn setClipboardWithOptions(self: *Terminal, bytes: []const u8, options: Osc52WriteOptions) !bool { - if (!self.config.osc52.enabled) return false; - - const require_tty = options.require_tty orelse self.config.osc52.require_tty; - if (require_tty and !self.isTty()) return false; - - const max_bytes = options.max_bytes orelse self.config.osc52.max_bytes; - if (max_bytes) |limit| { - if (bytes.len > limit) return false; - } - - const terminator = options.terminator orelse self.config.osc52.terminator; - const passthrough_mode = options.passthrough orelse self.config.osc52.passthrough; - const passthrough = self.resolveOsc52Passthrough(passthrough_mode); - - var target_scratch: [1]u8 = undefined; - const target = (options.target orelse self.config.osc52.target).encode(&target_scratch); - - try ansi.osc52Start(self.writer(), target, passthrough); - try self.writeBase64(bytes); - try ansi.osc52End(self.writer(), terminator, passthrough); - return true; - } - - /// Query clipboard bytes via OSC 52 (`...?;?`). - /// Returns `null` when unsupported, disabled, timed out, or rejected by guardrails. - pub fn getClipboard(self: *Terminal, allocator: std.mem.Allocator) !?[]u8 { - return self.getClipboardWithOptions(allocator, .{}); - } - - /// Query clipboard bytes via OSC 52 (`...?;?`) with per-call overrides. - /// Returns `null` when unsupported, disabled, timed out, or rejected by guardrails. - pub fn getClipboardWithOptions(self: *Terminal, allocator: std.mem.Allocator, options: Osc52ReadOptions) !?[]u8 { - if (!self.config.osc52.enabled or !self.config.osc52.query_enabled) return null; - - const require_tty = options.require_tty orelse self.config.osc52.require_tty; - if (require_tty and !self.isTty()) return null; - - const timeout_ms = options.timeout_ms orelse self.config.osc52.query_timeout_ms; - const strict_target = options.strict_target orelse self.config.osc52.strict_query_target; - const max_bytes = options.max_bytes orelse self.config.osc52.max_read_bytes; - - const terminator = options.terminator orelse self.config.osc52.terminator; - const passthrough_mode = options.passthrough orelse self.config.osc52.passthrough; - const passthrough = self.resolveOsc52Passthrough(passthrough_mode); - - var target_scratch: [1]u8 = undefined; - const target = (options.target orelse self.config.osc52.target).encode(&target_scratch); - - try ansi.osc52Start(self.writer(), target, passthrough); - try self.writeBytes("?"); - try ansi.osc52End(self.writer(), terminator, passthrough); - try self.flush(); - - var collected = std.array_list.Managed(u8).init(allocator); - defer collected.deinit(); - - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - while (withinDeadline(self.io, start, @intCast(@max(timeout_ms, 0)))) { - var chunk: [256]u8 = undefined; - const n = self.readPlatformInput(&chunk, 30) catch 0; - if (n == 0) continue; - try collected.appendSlice(chunk[0..n]); - - if (parseOsc52Response(collected.items, target, strict_target)) |parsed| { - const decoded = decodeOsc52Payload(allocator, parsed.payload_b64, max_bytes) catch null; - self.queueInputExceptRange(collected.items, parsed.consume_start, parsed.consume_end); - return decoded; - } - } - - self.queueInput(collected.items); - return null; - } - - /// Write a string at position - pub fn writeAt(self: *Terminal, row: u16, col: u16, str: []const u8) !void { - try self.moveTo(row, col); - try self.writeBytes(str); - } - - /// Check if stdin is a TTY - pub fn isTty(self: *Terminal) bool { - _ = self; - if (is_wasm) return true; - return platform.isTty(if (builtin.os.tag == .windows) - platform.State.init().stdin_handle - else - std.posix.STDIN_FILENO); - } - - pub fn getUnicodeWidthCapabilities(self: *const Terminal) UnicodeWidthCapabilities { - return self.unicode_width_caps; - } - - pub fn getImageCapabilities(self: *const Terminal) ImageCapabilities { - return self.image_caps; - } - - pub fn supportsKittyGraphics(self: *const Terminal) bool { - return self.image_caps.kitty_graphics; - } - - pub fn supportsIterm2InlineImages(self: *const Terminal) bool { - return self.image_caps.iterm2_inline_image; - } - - pub fn supportsImages(self: *const Terminal) bool { - return self.supportsKittyGraphics() or self.supportsIterm2InlineImages() or self.supportsSixel(); - } - - pub fn supportsSixel(self: *const Terminal) bool { - return self.image_caps.sixel; - } - - /// Draw image bytes using Kitty graphics protocol (`t=d`). - /// Returns `false` when unsupported or no data is provided. - pub fn drawKittyImage(self: *Terminal, image_data: []const u8, options: KittyImageOptions) !bool { - if (!self.image_caps.kitty_graphics or image_data.len == 0) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.print("a=T,t=d,f={d}", .{@intFromEnum(options.format)}); - if (options.quiet) try params_writer.writeAll(",q=2"); - if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); - if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); - if (options.image_id) |id| try params_writer.print(",i={d}", .{id}); - if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); - if (!options.move_cursor) try params_writer.writeAll(",C=1"); - if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); - if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); - if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); - if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); - - try self.sendKittyGraphicsPayload(params_writer.buffered(), image_data); - return true; - } - - /// Draw a PNG image by file path using Kitty graphics protocol (`t=f`). - /// Returns `false` when unsupported or path is empty. - pub fn drawKittyImageFromFile(self: *Terminal, path: []const u8, options: KittyImageFileOptions) !bool { - if (!self.image_caps.kitty_graphics or path.len == 0) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.writeAll("a=T,t=f,f=100"); - if (options.quiet) try params_writer.writeAll(",q=2"); - if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); - if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); - if (options.image_id) |id| try params_writer.print(",i={d}", .{id}); - if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); - if (!options.move_cursor) try params_writer.writeAll(",C=1"); - if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); - if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); - - try self.sendKittyGraphicsPayload(params_writer.buffered(), path); - return true; - } - - /// Transmit an image to the Kitty cache without displaying it (`a=t`). - /// Use `placeKittyImage` later to display it by ID. - pub fn transmitKittyImage(self: *Terminal, payload: []const u8, options: KittyTransmitOptions) !bool { - if (!self.image_caps.kitty_graphics or payload.len == 0) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.print("a=t,i={d}", .{options.image_id}); - if (options.quiet) try params_writer.writeAll(",q=2"); - - switch (options.format) { - .png => try params_writer.writeAll(",f=100"), - .rgb => { - try params_writer.writeAll(",f=24"); - if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); - if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); - }, - .rgba => { - try params_writer.writeAll(",f=32"); - if (options.pixel_width) |pw| try params_writer.print(",s={d}", .{pw}); - if (options.pixel_height) |ph| try params_writer.print(",v={d}", .{ph}); - }, - } - - try self.sendKittyGraphicsPayload(params_writer.buffered(), payload); - return true; - } - - /// Transmit an image file to the Kitty cache without displaying it (`a=t,t=f`). - pub fn transmitKittyImageFromFile(self: *Terminal, path: []const u8, options: KittyTransmitOptions) !bool { - if (!self.image_caps.kitty_graphics or path.len == 0) return false; - if (!fileExists(self.io, path)) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.print("a=t,t=f,f=100,i={d}", .{options.image_id}); - if (options.quiet) try params_writer.writeAll(",q=2"); - - try self.sendKittyGraphicsPayload(params_writer.buffered(), path); - return true; - } - - /// Display a previously cached image by ID (`a=p`). - pub fn placeKittyImage(self: *Terminal, options: KittyPlaceOptions) !bool { - if (!self.image_caps.kitty_graphics) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.print("a=p,i={d}", .{options.image_id}); - if (options.quiet) try params_writer.writeAll(",q=2"); - if (options.placement_id) |id| try params_writer.print(",p={d}", .{id}); - if (options.width_cells) |cols| try params_writer.print(",c={d}", .{cols}); - if (options.height_cells) |rows| try params_writer.print(",r={d}", .{rows}); - if (!options.move_cursor) try params_writer.writeAll(",C=1"); - if (options.z_index) |z| try params_writer.print(",z={d}", .{z}); - if (options.unicode_placeholder) try params_writer.writeAll(",U=1"); - - // Virtual placement has no payload. - try ansi.kittyGraphics(self.writer(), params_writer.buffered(), ""); - return true; - } - - /// Delete images/placements from the Kitty cache (`a=d`). - pub fn deleteKittyImage(self: *Terminal, target: KittyDeleteTarget) !bool { - if (!self.image_caps.kitty_graphics) return false; - - var params_buf: [128]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.writeAll("a=d,q=2"); - switch (target) { - .by_id => |id| try params_writer.print(",d=I,i={d}", .{id}), - .by_placement => |bp| try params_writer.print(",d=I,i={d},p={d}", .{ bp.image_id, bp.placement_id }), - .all => try params_writer.writeAll(",d=A"), - } - - try ansi.kittyGraphics(self.writer(), params_writer.buffered(), ""); - return true; - } - - /// Draw a file image via iTerm2 inline image protocol (`OSC 1337`). - /// Returns `false` when unsupported or path is empty. - pub fn drawIterm2ImageFromFile(self: *Terminal, path: []const u8, options: Iterm2ImageFileOptions) !bool { - if (!self.image_caps.iterm2_inline_image or path.len == 0) return false; - if (!fileExists(self.io, path)) return false; - - var file = try std.Io.Dir.cwd().openFile(self.io, path, .{}); - defer file.close(self.io); - const stat = try file.stat(self.io); - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.writeAll("inline=1"); - if (options.width_cells) |cols| try params_writer.print(";width={d}", .{cols}); - if (options.height_cells) |rows| try params_writer.print(";height={d}", .{rows}); - try params_writer.print(";preserveAspectRatio={d}", .{if (options.preserve_aspect_ratio) @as(u8, 1) else @as(u8, 0)}); - if (!options.move_cursor) try params_writer.writeAll(";doNotMoveCursor=1"); - try params_writer.print(";size={d}", .{stat.size}); - const file_name = std.fs.path.basename(path); - const file_name_b64_len = std.base64.standard.Encoder.calcSize(file_name.len); - if (file_name_b64_len <= 512) { - var file_name_b64_buf: [512]u8 = undefined; - const file_name_b64 = std.base64.standard.Encoder.encode(file_name_b64_buf[0..file_name_b64_len], file_name); - try params_writer.print(";name={s}", .{file_name_b64}); - } - - try self.sendIterm2InlineImagePayload(params_writer.buffered(), &file, stat.size); - return true; - } - - /// Draw in-memory image data via iTerm2 inline image protocol. - /// Returns `false` when unsupported or data is empty. - pub fn drawIterm2ImageData(self: *Terminal, data: []const u8, options: Iterm2ImageDataOptions) !bool { - if (!self.image_caps.iterm2_inline_image or data.len == 0) return false; - - var params_buf: [256]u8 = undefined; - var params_writer = FixedWriter(¶ms_buf); - - try params_writer.writeAll("inline=1"); - if (options.width_cells) |cols| try params_writer.print(";width={d}", .{cols}); - if (options.height_cells) |rows| try params_writer.print(";height={d}", .{rows}); - try params_writer.print(";preserveAspectRatio={d}", .{if (options.preserve_aspect_ratio) @as(u8, 1) else @as(u8, 0)}); - if (!options.move_cursor) try params_writer.writeAll(";doNotMoveCursor=1"); - try params_writer.print(";size={d}", .{data.len}); - - try self.sendIterm2InlineImageDataPayload(params_writer.buffered(), data); - return true; - } - - /// Draw an image file using the best available protocol. - /// Prefers Kitty graphics, then iTerm2 inline images, then Sixel. - /// Use `protocol` to override the auto-selection. - pub fn drawImageFromFile(self: *Terminal, path: []const u8, options: ImageFileOptions) !bool { - return self.drawImageFromFileWithProtocol(path, options, .auto); - } - - /// Draw an image file using a specific or auto-selected protocol. - pub fn drawImageFromFileWithProtocol(self: *Terminal, path: []const u8, options: ImageFileOptions, protocol: ImageProtocol) !bool { - if (path.len == 0) return false; - if (!fileExists(self.io, path)) return false; - - switch (protocol) { - .kitty => { - if (self.image_caps.kitty_graphics) { - return self.drawKittyImageFromFile(path, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .image_id = options.image_id, - .placement_id = options.placement_id, - .move_cursor = options.move_cursor, - .quiet = options.quiet, - .z_index = options.z_index, - .unicode_placeholder = options.unicode_placeholder, - }); - } - return false; - }, - .iterm2 => { - if (self.image_caps.iterm2_inline_image) { - return self.drawIterm2ImageFromFile(path, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .preserve_aspect_ratio = options.preserve_aspect_ratio, - .move_cursor = options.move_cursor, - }); - } - return false; - }, - .sixel => { - if (self.image_caps.sixel) { - return self.drawSixelFromFile(path, .{}); - } - return false; - }, - .auto => { - if (self.image_caps.kitty_graphics) { - return self.drawKittyImageFromFile(path, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .image_id = options.image_id, - .placement_id = options.placement_id, - .move_cursor = options.move_cursor, - .quiet = options.quiet, - .z_index = options.z_index, - .unicode_placeholder = options.unicode_placeholder, - }); - } - if (self.image_caps.iterm2_inline_image) { - return self.drawIterm2ImageFromFile(path, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .preserve_aspect_ratio = options.preserve_aspect_ratio, - .move_cursor = options.move_cursor, - }); - } - if (self.image_caps.sixel) { - return self.drawSixelFromFile(path, .{}); - } - return false; - }, - } - } - - /// Draw in-memory image data using the best available protocol. - pub fn drawImageData(self: *Terminal, data: []const u8, options: ImageDataOptions) !bool { - return self.drawImageDataWithProtocol(data, options, .auto); - } - - /// Draw in-memory image data using a specific or auto-selected protocol. - pub fn drawImageDataWithProtocol(self: *Terminal, data: []const u8, options: ImageDataOptions, protocol: ImageProtocol) !bool { - if (data.len == 0) return false; - - switch (protocol) { - .kitty => { - if (self.image_caps.kitty_graphics) { - return self.drawKittyImage(data, .{ - .format = options.format, - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .image_id = options.image_id, - .placement_id = options.placement_id, - .move_cursor = options.move_cursor, - .quiet = options.quiet, - .z_index = options.z_index, - .unicode_placeholder = options.unicode_placeholder, - .pixel_width = options.pixel_width, - .pixel_height = options.pixel_height, - }); - } - return false; - }, - .iterm2 => { - if (self.image_caps.iterm2_inline_image) { - return self.drawIterm2ImageData(data, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .preserve_aspect_ratio = options.preserve_aspect_ratio, - .move_cursor = options.move_cursor, - }); - } - return false; - }, - .sixel => { - // Sixel only supports pre-encoded data or file paths. - if (self.image_caps.sixel) { - self.sendSixelPayload(data) catch return false; - return true; - } - return false; - }, - .auto => { - if (self.image_caps.kitty_graphics) { - return self.drawKittyImage(data, .{ - .format = options.format, - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .image_id = options.image_id, - .placement_id = options.placement_id, - .move_cursor = options.move_cursor, - .quiet = options.quiet, - .z_index = options.z_index, - .unicode_placeholder = options.unicode_placeholder, - .pixel_width = options.pixel_width, - .pixel_height = options.pixel_height, - }); - } - if (self.image_caps.iterm2_inline_image) { - return self.drawIterm2ImageData(data, .{ - .width_cells = options.width_cells, - .height_cells = options.height_cells, - .preserve_aspect_ratio = options.preserve_aspect_ratio, - .move_cursor = options.move_cursor, - }); - } - if (self.image_caps.sixel) { - self.sendSixelPayload(data) catch return false; - return true; - } - return false; - }, - } - } - - /// Draw a Sixel image from file. - /// Supports either: - /// - pre-encoded `.sixel`/`.six` data files, or - /// - regular image files converted through `img2sixel` when available. - pub fn drawSixelFromFile(self: *Terminal, path: []const u8, options: SixelImageFileOptions) !bool { - if (!self.image_caps.sixel or path.len == 0) return false; - if (!fileExists(self.io, path)) return false; - - if (isSixelDataPath(path)) { - var file = try std.Io.Dir.cwd().openFile(self.io, path, .{}); - defer file.close(self.io); - try self.sendSixelPayloadFromFile(&file); - return true; - } - - if (!commandExists(self.io, "img2sixel")) return false; - - var argv_buf: [6][]const u8 = undefined; - var argc: usize = 0; - argv_buf[argc] = "img2sixel"; - argc += 1; - var w_buf: [16]u8 = undefined; - var h_buf: [16]u8 = undefined; - if (options.width_pixels) |wp| { - argv_buf[argc] = "-w"; - argc += 1; - argv_buf[argc] = std.fmt.bufPrint(&w_buf, "{d}", .{wp}) catch "0"; - argc += 1; - } - if (options.height_pixels) |hp| { - argv_buf[argc] = "-h"; - argc += 1; - argv_buf[argc] = std.fmt.bufPrint(&h_buf, "{d}", .{hp}) catch "0"; - argc += 1; - } - argv_buf[argc] = path; - argc += 1; - - const result = try std.process.run(std.heap.page_allocator, self.io, .{ - .argv = argv_buf[0..argc], - .stdout_limit = .limited(options.max_output_bytes), - .stderr_limit = .limited(options.max_output_bytes), - }); - defer std.heap.page_allocator.free(result.stdout); - defer std.heap.page_allocator.free(result.stderr); - - switch (result.term) { - .exited => |code| if (code != 0) return error.BrokenPipe, - else => return error.BrokenPipe, - } - - try self.sendSixelPayload(result.stdout); - return true; - } - - fn detectUnicodeWidthCapabilities(self: *Terminal) void { - if (is_wasm) { - self.unicode_width_caps = .{ .strategy = .legacy_wcwidth }; - return; - } - - self.unicode_width_caps = .{ - .kitty_text_sizing = self.queryKittyTextSizingSupport() catch false, - }; - - if (!self.isTty()) { - return; - } - - if (builtin.os.tag != .windows) { - self.unicode_width_caps.mode_2027 = self.queryMode2027Support() catch false; - if (self.unicode_width_caps.mode_2027) { - self.writeBytes(ansi.unicode_width_mode_enable) catch {}; - } - } - - self.unicode_width_caps.strategy = self.selectWidthStrategy(); - } - - fn detectImageCapabilities(self: *Terminal) void { - if (is_wasm) { - self.image_caps = .{}; - return; - } - - if (!self.isTty()) { - self.image_caps = .{}; - return; - } - - const term_features = self.environ_map.get("TERM_FEATURES") orelse ""; - - const kitty_candidate = looksLikeKittyTerminal(self.environ_map) or - envVarEquals(self.environ_map, "TERM_PROGRAM", "WezTerm") or - envVarContains(self.environ_map, "TERM", "wezterm") or - envVarContains(self.environ_map, "TERM", "ghostty"); - const iterm_candidate = looksLikeIterm2Terminal(self.environ_map) or - envVarEquals(self.environ_map, "TERM_PROGRAM", "WezTerm"); - const in_multiplexer = isInsideMultiplexer(self.environ_map); - - var kitty = false; - var iterm = iterm_candidate or termFeaturesContain(term_features, "F"); - var sixel = looksLikeSixelTerminal(self.environ_map) or termFeaturesContain(term_features, "Sx"); - - if (kitty_candidate) { - kitty = self.queryKittyGraphicsSupport() catch false; - // Keep an env fallback only outside multiplexers where probe failures are uncommon. - if (!kitty and !in_multiplexer) { - kitty = envVarExists(self.environ_map, "KITTY_WINDOW_ID"); - } - } - - if (iterm_candidate or term_features.len > 0) { - if (self.queryIterm2Capabilities() catch null) |caps| { - iterm = iterm or caps.inline_image; - sixel = sixel or caps.sixel; - } - } - - if (!sixel) sixel = self.queryPrimaryDeviceAttributesHasParam(4) catch false; - - self.image_caps = .{ - .kitty_graphics = kitty, - .iterm2_inline_image = iterm, - .sixel = sixel, - }; - } - - const Osc52ParsedResponse = struct { - payload_b64: []const u8, - consume_start: usize, - consume_end: usize, - }; - - fn parseOsc52Response(bytes: []const u8, expected_target: []const u8, strict_target: bool) ?Osc52ParsedResponse { - const prefix = "\x1b]52;"; - var search_from: usize = 0; - - while (search_from < bytes.len) { - const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; - const selector_start = start + prefix.len; - const selector_end = std.mem.indexOfScalarPos(u8, bytes, selector_start, ';') orelse return null; - const payload_start = selector_end + 1; - const osc_end = indexOfOscTerminator(bytes, payload_start) orelse return null; - const osc_term_len: usize = if (bytes[osc_end] == 0x07) 1 else 2; - - const selector = bytes[selector_start..selector_end]; - if (strict_target and !std.mem.eql(u8, selector, expected_target)) { - search_from = selector_end + 1; - continue; - } - - var payload_end = osc_end; - if (start > 0 and bytes[start - 1] == 0x1b and bytes[osc_end] == 0x1b and osc_end + 1 < bytes.len and bytes[osc_end + 1] == '\\') { - // DCS passthrough can encode inner ST as ESC ESC \. - if (payload_end > payload_start) payload_end -= 1; - } - - var consume_start = start; - var consume_end = osc_end + osc_term_len; - - if (findOpenDcsStart(bytes, start)) |dcs_start| { - if (indexOfSt(bytes, consume_end)) |outer_st| { - consume_start = dcs_start; - consume_end = outer_st + 2; - } - } - - return .{ - .payload_b64 = bytes[payload_start..payload_end], - .consume_start = consume_start, - .consume_end = consume_end, - }; - } - - return null; - } - - fn findOpenDcsStart(bytes: []const u8, pos: usize) ?usize { - if (pos == 0) return null; - - var i: usize = 0; - var open: ?usize = null; - while (i + 1 < pos) : (i += 1) { - if (bytes[i] != 0x1b) continue; - if (bytes[i + 1] == 'P') { - open = i; - i += 1; - continue; - } - if (bytes[i + 1] == '\\') { - open = null; - i += 1; - continue; - } - } - return open; - } - - fn decodeOsc52Payload(allocator: std.mem.Allocator, payload_b64: []const u8, max_bytes: ?usize) !?[]u8 { - if (payload_b64.len == 0 or (payload_b64.len == 1 and payload_b64[0] == '?')) return null; - - const decoder = std.base64.standard.Decoder; - const out_len = decoder.calcSizeForSlice(payload_b64) catch return null; - - if (max_bytes) |limit| { - if (out_len > limit) return null; - } - - const out = try allocator.alloc(u8, out_len); - errdefer allocator.free(out); - _ = decoder.decode(out, payload_b64) catch return null; - return out; - } - - fn readPlatformInput(self: *Terminal, buffer: []u8, timeout_ms: i32) !usize { - return platform.readInput(&self.state, buffer, timeout_ms); - } - - fn queueInput(self: *Terminal, bytes: []const u8) void { - if (bytes.len == 0) return; - - const free_space = self.pending_input.len - self.pending_input_len; - const take = @min(bytes.len, free_space); - if (take == 0) return; - - @memcpy(self.pending_input[self.pending_input_len .. self.pending_input_len + take], bytes[0..take]); - self.pending_input_len += take; - } - - fn queueInputExceptRange(self: *Terminal, bytes: []const u8, start: usize, end: usize) void { - if (start > 0) { - self.queueInput(bytes[0..start]); - } - if (end < bytes.len) { - self.queueInput(bytes[end..]); - } - } - - fn resolveOsc52Passthrough(self: *const Terminal, mode: Osc52Passthrough) ansi.Osc52Passthrough { - return switch (mode) { - .none => .none, - .tmux => .tmux, - .dcs => .dcs, - .auto => blk: { - if (envVarExists(self.environ_map, "TMUX")) break :blk .tmux; - if (envVarContains(self.environ_map, "TERM", "screen")) break :blk .dcs; - break :blk .none; - }, - }; - } - - fn writeBase64(self: *Terminal, bytes: []const u8) !void { - const encoder = std.base64.standard.Encoder; - var b64_buf: [4096]u8 = undefined; - const raw_chunk_max: usize = (b64_buf.len / 4) * 3; - - var src_index: usize = 0; - while (src_index < bytes.len) { - const take = @min(bytes.len - src_index, raw_chunk_max); - const chunk = bytes[src_index .. src_index + take]; - const encoded_len = encoder.calcSize(chunk.len); - const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); - try self.writeBytes(encoded); - src_index += take; - } - } - - fn sendKittyGraphicsPayload(self: *Terminal, first_params: []const u8, payload: []const u8) !void { - const encoder = std.base64.standard.Encoder; - var b64_buf: [4096]u8 = undefined; - const raw_chunk_max: usize = (b64_buf.len / 4) * 3; - - var src_index: usize = 0; - var first = true; - - while (true) { - const remaining = payload.len - src_index; - const take = @min(remaining, raw_chunk_max); - const chunk = payload[src_index .. src_index + take]; - - const encoded_len = encoder.calcSize(chunk.len); - const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); - const has_more = src_index + take < payload.len; - - if (first) { - var first_chunk_params: [192]u8 = undefined; - const params = try std.fmt.bufPrint( - &first_chunk_params, - "{s},m={d}", - .{ first_params, if (has_more) @as(u8, 1) else @as(u8, 0) }, - ); - try ansi.kittyGraphics(self.writer(), params, encoded); - first = false; - } else { - const params = if (has_more) "m=1" else "m=0"; - try ansi.kittyGraphics(self.writer(), params, encoded); - } - - if (!has_more) break; - src_index += take; - } - } - - fn sendIterm2InlineImagePayload(self: *Terminal, params: []const u8, file: *std.Io.File, file_size: u64) !void { - const encoder = std.base64.standard.Encoder; - var raw_buf: [3072]u8 = undefined; - var b64_buf: [4096]u8 = undefined; - const encoded_total = std.math.cast(usize, encoder.calcSize(@intCast(file_size))) orelse std.math.maxInt(usize); - const single_sequence_soft_limit: usize = 750 * 1024; - - if (encoded_total <= single_sequence_soft_limit) { - try self.writeBytes(ansi.OSC ++ "1337;File="); - try self.writeBytes(params); - try self.writeBytes(":"); - - while (true) { - const n = file.readStreaming(self.io, &.{&raw_buf}) catch |err| switch (err) { - error.EndOfStream => break, - else => |e| return e, - }; - if (n == 0) continue; - const encoded_len = encoder.calcSize(n); - const encoded = encoder.encode(b64_buf[0..encoded_len], raw_buf[0..n]); - try self.writeBytes(encoded); - } - try self.writeBytes("\x07"); - return; - } - - // iTerm2 supports multipart transfer to avoid oversized OSC sequences. - try self.writeBytes(ansi.OSC ++ "1337;MultipartFile="); - try self.writeBytes(params); - try self.writeBytes("\x07"); - - while (true) { - const n = file.readStreaming(self.io, &.{&raw_buf}) catch |err| switch (err) { - error.EndOfStream => break, - else => |e| return e, - }; - if (n == 0) break; - const encoded_len = encoder.calcSize(n); - const encoded = encoder.encode(b64_buf[0..encoded_len], raw_buf[0..n]); - try self.writeBytes(ansi.OSC ++ "1337;FilePart="); - try self.writeBytes(encoded); - try self.writeBytes("\x07"); - } - - try self.writeBytes(ansi.OSC ++ "1337;FileEnd\x07"); - } - - fn sendIterm2InlineImageDataPayload(self: *Terminal, params: []const u8, data: []const u8) !void { - const encoder = std.base64.standard.Encoder; - const encoded_total = encoder.calcSize(data.len); - const single_sequence_soft_limit: usize = 750 * 1024; - - if (encoded_total <= single_sequence_soft_limit) { - try self.writeBytes(ansi.OSC ++ "1337;File="); - try self.writeBytes(params); - try self.writeBytes(":"); - - var src_index: usize = 0; - var b64_buf: [4096]u8 = undefined; - const raw_chunk_max: usize = (b64_buf.len / 4) * 3; - while (src_index < data.len) { - const take = @min(data.len - src_index, raw_chunk_max); - const chunk = data[src_index .. src_index + take]; - const encoded_len = encoder.calcSize(chunk.len); - const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); - try self.writeBytes(encoded); - src_index += take; - } - try self.writeBytes("\x07"); - return; - } - - // Multipart transfer for large payloads. - try self.writeBytes(ansi.OSC ++ "1337;MultipartFile="); - try self.writeBytes(params); - try self.writeBytes("\x07"); - - var src_index: usize = 0; - var b64_buf: [4096]u8 = undefined; - const raw_chunk_max: usize = (b64_buf.len / 4) * 3; - while (src_index < data.len) { - const take = @min(data.len - src_index, raw_chunk_max); - const chunk = data[src_index .. src_index + take]; - const encoded_len = encoder.calcSize(chunk.len); - const encoded = encoder.encode(b64_buf[0..encoded_len], chunk); - try self.writeBytes(ansi.OSC ++ "1337;FilePart="); - try self.writeBytes(encoded); - try self.writeBytes("\x07"); - src_index += take; - } - - try self.writeBytes(ansi.OSC ++ "1337;FileEnd\x07"); - } - - fn sendSixelPayloadFromFile(self: *Terminal, file: *std.Io.File) !void { - var payload_buf: [4096]u8 = undefined; - var first_read = true; - var wrapped = false; - - while (true) { - const n = file.readStreaming(self.io, &.{&payload_buf}) catch |err| switch (err) { - error.EndOfStream => break, - else => |e| return e, - }; - if (n == 0) break; - const chunk = payload_buf[0..n]; - - if (first_read) { - first_read = false; - if (isLikelyFullSixelSequence(chunk)) { - wrapped = true; - } else { - try self.writeBytes(ansi.DCS ++ "q"); - } - } - try self.writeBytes(chunk); - } - - if (!first_read and !wrapped) { - try self.writeBytes(ansi.ST); - } - } - - fn sendSixelPayload(self: *Terminal, bytes: []const u8) !void { - if (bytes.len == 0) return; - if (isLikelyFullSixelSequence(bytes)) { - try self.writeBytes(bytes); - return; - } - try self.writeBytes(ansi.DCS ++ "q"); - try self.writeBytes(bytes); - try self.writeBytes(ansi.ST); - } - - fn queryKittyGraphicsSupport(self: *Terminal) !bool { - const probe_id: u32 = 9931; - self.drainInput(); - try ansi.kittyGraphics(self.writer(), "a=q,i=9931,s=1,v=1,t=d,f=24", "AAAA"); - try self.flush(); - - var collected: [1024]u8 = undefined; - var collected_len: usize = 0; - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - - while (withinDeadline(self.io, start, 180)) { - var chunk: [128]u8 = undefined; - const n = self.readInput(&chunk, 30) catch 0; - if (n == 0) continue; - - const copy_len = @min(n, collected.len - collected_len); - if (copy_len > 0) { - @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); - collected_len += copy_len; - } - - if (parseKittyGraphicsProbeResponse(collected[0..collected_len], probe_id)) |supported| { - return supported; - } - } - - return false; - } - - fn parseKittyGraphicsProbeResponse(bytes: []const u8, probe_id: u32) ?bool { - const prefix = "\x1b_G"; - var search_from: usize = 0; - - var id_buf: [24]u8 = undefined; - const expected_id = std.fmt.bufPrint(&id_buf, "i={d}", .{probe_id}) catch return null; - - while (search_from < bytes.len) { - const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; - const content_start = start + prefix.len; - const semicolon = std.mem.indexOfScalarPos(u8, bytes, content_start, ';') orelse return null; - const st_index = indexOfSt(bytes, semicolon + 1) orelse return null; - - const params = bytes[content_start..semicolon]; - const payload = bytes[semicolon + 1 .. st_index]; - - if (std.mem.indexOf(u8, params, expected_id) != null) { - return std.mem.startsWith(u8, payload, "OK"); - } - - search_from = st_index + 2; - } - - return null; - } - - fn queryIterm2Capabilities(self: *Terminal) !?Iterm2Capabilities { - self.drainInput(); - try self.writeBytes(ansi.OSC ++ "1337;Capabilities\x07"); - try self.flush(); - - var collected: [2048]u8 = undefined; - var collected_len: usize = 0; - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - - while (withinDeadline(self.io, start, 180)) { - var chunk: [128]u8 = undefined; - const n = self.readInput(&chunk, 30) catch 0; - if (n == 0) continue; - - const copy_len = @min(n, collected.len - collected_len); - if (copy_len > 0) { - @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); - collected_len += copy_len; - } - - if (parseIterm2CapabilitiesResponse(collected[0..collected_len])) |caps| { - return caps; - } - } - - return null; - } - - fn parseIterm2CapabilitiesResponse(bytes: []const u8) ?Iterm2Capabilities { - const prefix = "\x1b]1337;Capabilities="; - const start = std.mem.indexOf(u8, bytes, prefix) orelse return null; - const payload_start = start + prefix.len; - const end = indexOfOscTerminator(bytes, payload_start) orelse return null; - const payload = bytes[payload_start..end]; - return .{ - .inline_image = termFeaturesContain(payload, "F"), - .sixel = termFeaturesContain(payload, "Sx"), - }; - } - - fn queryPrimaryDeviceAttributesHasParam(self: *Terminal, needle: u16) !bool { - self.drainInput(); - try self.writeBytes(ansi.CSI ++ "c"); - try self.flush(); - - var collected: [1024]u8 = undefined; - var collected_len: usize = 0; - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - - while (withinDeadline(self.io, start, 120)) { - var chunk: [128]u8 = undefined; - const n = self.readInput(&chunk, 25) catch 0; - if (n == 0) continue; - - const copy_len = @min(n, collected.len - collected_len); - if (copy_len > 0) { - @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); - collected_len += copy_len; - } - - if (parsePrimaryDeviceAttributes(collected[0..collected_len])) |params| { - return primaryDeviceAttributesHasParam(params, needle); - } - } - - return false; - } - - fn parsePrimaryDeviceAttributes(bytes: []const u8) ?[]const u8 { - const prefix = "\x1b["; - var search_from: usize = 0; - - while (search_from < bytes.len) { - const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; - var i = start + prefix.len; - - if (i < bytes.len and bytes[i] == '?') i += 1; - const params_start = i; - - while (i < bytes.len and ((bytes[i] >= '0' and bytes[i] <= '9') or bytes[i] == ';')) : (i += 1) {} - if (i >= bytes.len) return null; - - if (bytes[i] == 'c' and i > params_start) { - return bytes[params_start..i]; - } - - search_from = start + 1; - } - - return null; - } - - fn primaryDeviceAttributesHasParam(params: []const u8, needle: u16) bool { - var it = std.mem.splitScalar(u8, params, ';'); - while (it.next()) |part| { - if (part.len == 0) continue; - const value = std.fmt.parseInt(u16, part, 10) catch continue; - if (value == needle) return true; - } - return false; - } - - fn queryMode2027Support(self: *Terminal) !bool { - try self.writeBytes(ansi.unicode_width_mode_query); - try self.flush(); - - var collected: [512]u8 = undefined; - var collected_len: usize = 0; - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - - while (withinDeadline(self.io, start, 250)) { - var chunk: [128]u8 = undefined; - const n = self.readInput(&chunk, 40) catch 0; - if (n == 0) continue; - - const copy_len = @min(n, collected.len - collected_len); - if (copy_len > 0) { - @memcpy(collected[collected_len .. collected_len + copy_len], chunk[0..copy_len]); - collected_len += copy_len; - } - - if (parseMode2027Response(collected[0..collected_len])) |supported| { - return supported; - } - } - - return false; - } - - fn parseMode2027Response(bytes: []const u8) ?bool { - const prefix = "\x1b[?2027;"; - var search_from: usize = 0; - - while (search_from < bytes.len) { - const start = std.mem.indexOfPos(u8, bytes, search_from, prefix) orelse return null; - var i = start + prefix.len; - var param: usize = 0; - var saw_digit = false; - - while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) { - saw_digit = true; - param = param * 10 + (bytes[i] - '0'); - } - - if (!saw_digit) { - search_from = start + 1; - continue; - } - - if (i + 1 < bytes.len and bytes[i] == '$' and bytes[i + 1] == 'y') { - return param != 0; - } - - search_from = start + 1; - } - - return null; - } - - fn selectWidthStrategy(self: *const Terminal) unicode.WidthStrategy { - if (isInsideMultiplexer(self.environ_map)) { - return .legacy_wcwidth; - } - - if (self.unicode_width_caps.mode_2027) { - return .unicode; - } - - if (self.unicode_width_caps.kitty_text_sizing) { - return .unicode; - } - - if (isKnownUnicodeWidthTerminal(self.environ_map)) { - return .unicode; - } - - return .legacy_wcwidth; - } - - fn queryKittyTextSizingSupport(self: *Terminal) !bool { - if (!looksLikeKittyTerminal(self.environ_map)) return false; - - const cpr = "\x1b[6n"; - // CR, CPR, draw 2-cell space via kitty OSC 66 width-only, CPR. - const probe = "\r" ++ cpr ++ "\x1b]66;w=2; \x07" ++ cpr; - try self.writeBytes(probe); - try self.flush(); - - var buf: [512]u8 = undefined; - var len: usize = 0; - const start = std.Io.Clock.Timestamp.now(self.io, .boot); - - while (withinDeadline(self.io, start, 250)) { - var chunk: [128]u8 = undefined; - const n = self.readInput(&chunk, 40) catch 0; - if (n == 0) continue; - - const copy_len = @min(n, buf.len - len); - if (copy_len > 0) { - @memcpy(buf[len .. len + copy_len], chunk[0..copy_len]); - len += copy_len; - } - - if (parseTwoCprColumns(buf[0..len])) |cols| { - return cols.second == cols.first + 2; - } - } - - return false; - } - - fn parseTwoCprColumns(bytes: []const u8) ?struct { first: usize, second: usize } { - var idx: usize = 0; - var found: [2]usize = .{ 0, 0 }; - var count: usize = 0; - - while (idx < bytes.len and count < 2) { - const esc = std.mem.indexOfPos(u8, bytes, idx, "\x1b[") orelse break; - var i = esc + 2; - - while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) {} - if (i >= bytes.len or bytes[i] != ';') { - idx = esc + 1; - continue; - } - i += 1; - - const col_start = i; - while (i < bytes.len and bytes[i] >= '0' and bytes[i] <= '9') : (i += 1) {} - if (i >= bytes.len or bytes[i] != 'R' or col_start == i) { - idx = esc + 1; - continue; - } - - const col = std.fmt.parseInt(usize, bytes[col_start..i], 10) catch { - idx = esc + 1; - continue; - }; - found[count] = col; - count += 1; - idx = i + 1; - } - - if (count == 2) { - return .{ .first = found[0], .second = found[1] }; - } - return null; - } - - fn isInsideMultiplexer(environ_map: *const std.process.Environ.Map) bool { - return envVarExists(environ_map, "TMUX") or envVarExists(environ_map, "ZELLIJ") or envVarContains(environ_map, "TERM", "screen"); - } - - fn drainInput(self: *Terminal) void { - var buf: [128]u8 = undefined; - while (true) { - const n = self.readInput(&buf, 0) catch return; - if (n == 0) return; - } - } - - fn termFeaturesContain(features: []const u8, needle: []const u8) bool { - if (features.len == 0 or needle.len == 0) return false; - - var i: usize = 0; - while (i < features.len) { - if (!std.ascii.isUpper(features[i])) { - i += 1; - continue; - } - - var j = i + 1; - while (j < features.len and std.ascii.isLower(features[j])) : (j += 1) {} - const code = features[i..j]; - - while (j < features.len and std.ascii.isDigit(features[j])) : (j += 1) {} - if (std.mem.eql(u8, code, needle)) return true; - - i = j; - } - - return false; - } - - fn indexOfOscTerminator(bytes: []const u8, start: usize) ?usize { - var i = start; - while (i < bytes.len) : (i += 1) { - if (bytes[i] == 0x07) return i; - if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { - return i; - } - } - return null; - } - - fn indexOfSt(bytes: []const u8, start: usize) ?usize { - var i = start; - while (i + 1 < bytes.len) : (i += 1) { - if (bytes[i] == 0x1b and bytes[i + 1] == '\\') return i; - } - return null; - } - - fn isKnownUnicodeWidthTerminal(environ_map: *const std.process.Environ.Map) bool { - // Terminals known to use grapheme-aware width by default. - return envVarEquals(environ_map, "TERM_PROGRAM", "WezTerm") or - envVarEquals(environ_map, "TERM_PROGRAM", "iTerm.app") or - envVarContains(environ_map, "TERM", "wezterm") or - envVarContains(environ_map, "TERM", "ghostty"); - } - - fn looksLikeKittyTerminal(environ_map: *const std.process.Environ.Map) bool { - return envVarExists(environ_map, "KITTY_WINDOW_ID") or envVarContains(environ_map, "TERM", "kitty"); - } - - fn looksLikeIterm2Terminal(environ_map: *const std.process.Environ.Map) bool { - return envVarEquals(environ_map, "TERM_PROGRAM", "iTerm.app") or - envVarEquals(environ_map, "LC_TERMINAL", "iTerm2"); - } - - fn looksLikeSixelTerminal(environ_map: *const std.process.Environ.Map) bool { - return envVarContains(environ_map, "TERM", "sixel") or - envVarContains(environ_map, "TERM", "mlterm") or - envVarContains(environ_map, "TERM", "yaft") or - envVarContains(environ_map, "TERM", "contour"); - } - - fn isLikelyFullSixelSequence(bytes: []const u8) bool { - if (bytes.len == 0) return false; - return std.mem.startsWith(u8, bytes, ansi.DCS) or bytes[0] == 0x90; - } - - fn isSixelDataPath(path: []const u8) bool { - return std.mem.endsWith(u8, path, ".sixel") or - std.mem.endsWith(u8, path, ".SIXEL") or - std.mem.endsWith(u8, path, ".six") or - std.mem.endsWith(u8, path, ".SIX"); - } - - fn fileExists(io: std.Io, path: []const u8) bool { - std.Io.Dir.cwd().access(io, path, .{}) catch return false; - return true; - } - - fn withinDeadline(io: std.Io, start: std.Io.Clock.Timestamp, timeout_ms: u64) bool { - const elapsed_ns = start.untilNow(io).raw.nanoseconds; - const deadline_ns: i96 = @as(i96, @intCast(timeout_ms)) * std.time.ns_per_ms; - return elapsed_ns < deadline_ns; - } - - fn commandExists(io: std.Io, name: []const u8) bool { - const argv = [_][]const u8{ name, "--version" }; - const result = std.process.run(std.heap.page_allocator, io, .{ - .argv = &argv, - .stdout_limit = .limited(1024), - .stderr_limit = .limited(1024), - }) catch return false; - defer std.heap.page_allocator.free(result.stdout); - defer std.heap.page_allocator.free(result.stderr); - return true; - } - - fn envVarExists(environ_map: *const std.process.Environ.Map, name: []const u8) bool { - const value = environ_map.get(name) orelse return false; - return value.len > 0; - } - - fn envVarEquals(environ_map: *const std.process.Environ.Map, name: []const u8, expected: []const u8) bool { - const value = environ_map.get(name) orelse return false; - return std.ascii.eqlIgnoreCase(value, expected); - } - - fn envVarContains(environ_map: *const std.process.Environ.Map, name: []const u8, needle: []const u8) bool { - const value = environ_map.get(name) orelse return false; - return std.mem.indexOf(u8, value, needle) != null; - } - - /// Buffered writer that exposes a `std.Io.Writer` interface and drains to - /// the terminal's output sink (stdout file, or the wasm host on wasm). - pub const Writer = struct { - io: std.Io, - file: if (is_wasm) void else std.Io.File, - buffer: [4096]u8 = undefined, - writer: std.Io.Writer, - - const vtable: std.Io.Writer.VTable = .{ .drain = drain }; - - pub fn init(io: std.Io, file: if (is_wasm) void else std.Io.File) Writer { - return .{ - .io = io, - .file = file, - .writer = .{ .vtable = &vtable, .buffer = &.{} }, - }; - } - - /// Wires the `std.Io.Writer` to the local buffer. Called by the - /// containing `Terminal` whenever it hands the writer out, so the - /// buffer pointer stays valid even if the `Terminal` was moved. - /// `writer.end` is preserved across moves, so re-binding is safe. - pub fn bind(self: *Writer) void { - self.writer.buffer = &self.buffer; - } - - fn drain(io_w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const self: *Writer = @fieldParentPtr("writer", io_w); - - const buffered = io_w.buffered(); - if (buffered.len != 0) { - try self.sinkAll(buffered); - io_w.end = 0; - } - - // The std.Io.Writer.VTable contract treats data.len == 0 as a - // pure flush; the splat pattern lives at data[data.len - 1] so we - // must early-return before indexing. - if (data.len == 0) return 0; - - var consumed: usize = 0; - if (data.len > 1) { - for (data[0 .. data.len - 1]) |chunk| { - if (chunk.len == 0) continue; - try self.sinkAll(chunk); - consumed += chunk.len; - } - } - - const pattern = data[data.len - 1]; - if (pattern.len > 0 and splat > 0) { - var i: usize = 0; - while (i < splat) : (i += 1) try self.sinkAll(pattern); - consumed += pattern.len * splat; - } - - return consumed; - } - - fn sinkAll(self: *Writer, bytes: []const u8) std.Io.Writer.Error!void { - if (is_wasm) { - try platform.wasm_writer_instance.writer.writeAll(bytes); - } else { - self.file.writeStreamingAll(self.io, bytes) catch return error.WriteFailed; - } - } - }; -}; - -test "parseOsc52Response direct BEL" { - const bytes = "\x1b]52;c;YQ==\x07"; - const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; - try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); - try std.testing.expectEqual(bytes.len, parsed.consume_end); - try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); -} - -test "parseOsc52Response direct ST" { - const bytes = "\x1b]52;c;YQ==\x1b\\"; - const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; - try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); - try std.testing.expectEqual(bytes.len, parsed.consume_end); - try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); -} - -test "parseOsc52Response tmux passthrough BEL" { - const bytes = "\x1bPtmux;\x1b\x1b]52;c;YQ==\x07\x1b\\"; - const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; - try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); - try std.testing.expectEqual(bytes.len, parsed.consume_end); - try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); -} - -test "parseOsc52Response tmux passthrough ST" { - const bytes = "\x1bPtmux;\x1b\x1b]52;c;YQ==\x1b\x1b\\\x1b\\"; - const parsed = Terminal.parseOsc52Response(bytes, "c", true).?; - try std.testing.expectEqual(@as(usize, 0), parsed.consume_start); - try std.testing.expectEqual(bytes.len, parsed.consume_end); - try std.testing.expectEqualStrings("YQ==", parsed.payload_b64); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig deleted file mode 100644 index b230bdf..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/testing/snapshot.zig +++ /dev/null @@ -1,232 +0,0 @@ -//! 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); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig deleted file mode 100644 index 3f9cedf..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode.zig +++ /dev/null @@ -1,96 +0,0 @@ -//! Unicode utilities for display width calculation. - -const std = @import("std"); - -pub const display_width = @import("unicode/display_width.zig"); - -/// Runtime width strategy. -/// - legacy_wcwidth: conservative fallback for terminals without negotiated width support. -/// - unicode: full Unicode table behavior. -pub const WidthStrategy = enum(u8) { - legacy_wcwidth, - unicode, -}; - -var width_strategy: std.atomic.Value(u8) = std.atomic.Value(u8).init(@intFromEnum(WidthStrategy.legacy_wcwidth)); - -pub fn setWidthStrategy(strategy: WidthStrategy) void { - width_strategy.store(@intFromEnum(strategy), .release); -} - -pub fn getWidthStrategy() WidthStrategy { - return @enumFromInt(width_strategy.load(.acquire)); -} - -pub fn charWidth(codepoint: u21) usize { - return switch (getWidthStrategy()) { - .legacy_wcwidth => charWidthLegacy(codepoint), - .unicode => display_width.charWidth(codepoint), - }; -} - -pub fn codepointWidth(codepoint: u21) i8 { - return switch (getWidthStrategy()) { - .unicode => @as(i8, display_width.codepointWidth(codepoint)), - .legacy_wcwidth => blk: { - const w = display_width.codepointWidth(codepoint); - if (w <= 0) break :blk @as(i8, w); - if (w == 2 and isLegacyAmbiguousWide(codepoint)) break :blk 1; - break :blk @as(i8, w); - }, - }; -} - -pub fn strWidth(str: []const u8) usize { - var total: usize = 0; - var i: usize = 0; - while (i < str.len) { - const len = std.unicode.utf8ByteSequenceLength(str[i]) catch { - total += 1; - i += 1; - continue; - }; - if (i + len > str.len) { - total += 1; - i += 1; - continue; - } - const cp = std.unicode.utf8Decode(str[i..][0..len]) catch { - total += 1; - i += 1; - continue; - }; - total += charWidth(cp); - i += len; - } - return total; -} - -fn charWidthLegacy(codepoint: u21) usize { - const w = display_width.charWidth(codepoint); - if (w == 2 and isLegacyAmbiguousWide(codepoint)) return 1; - return w; -} - -/// Legacy terminals often render many BMP symbol/emoji codepoints as narrow. -fn isLegacyAmbiguousWide(codepoint: u21) bool { - return (codepoint >= 0x2300 and codepoint <= 0x23FF) or - (codepoint >= 0x2600 and codepoint <= 0x27BF) or - (codepoint >= 0x2B00 and codepoint <= 0x2BFF); -} - -test { - _ = display_width; -} - -test "legacy strategy narrows ambiguous bmp symbols" { - setWidthStrategy(.legacy_wcwidth); - defer setWidthStrategy(.unicode); - try std.testing.expectEqual(@as(usize, 1), charWidth(0x2764)); // Heart -} - -test "unicode strategy keeps full table behavior" { - setWidthStrategy(.unicode); - defer setWidthStrategy(.legacy_wcwidth); - try std.testing.expectEqual(display_width.charWidth(0x2764), charWidth(0x2764)); -} diff --git a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig b/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig deleted file mode 100644 index 5a31def..0000000 --- a/zig-pkg/zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv/src/unicode/display_width.zig +++ /dev/null @@ -1,677 +0,0 @@ -//! Unicode display width lookup based on Unicode 16.0. -//! Provides wcwidth-equivalent functionality for determining how many -//! terminal columns a character occupies. - -const std = @import("std"); - -/// A Unicode codepoint range (inclusive). -const Range = struct { - first: u21, - last: u21, -}; - -/// Zero-width character ranges: combining marks (Mn/Me/Mc subset), format chars (Cf), -/// default ignorable code points, variation selectors, Hangul Jamo medials/finals, etc. -const zero_width_ranges = [_]Range{ - .{ .first = 0x00AD, .last = 0x00AD }, // SOFT HYPHEN - .{ .first = 0x0300, .last = 0x036F }, // Combining Diacritical Marks - .{ .first = 0x0483, .last = 0x0489 }, // Combining Cyrillic - .{ .first = 0x0591, .last = 0x05BD }, // Hebrew combining - .{ .first = 0x05BF, .last = 0x05BF }, - .{ .first = 0x05C1, .last = 0x05C2 }, - .{ .first = 0x05C4, .last = 0x05C5 }, - .{ .first = 0x05C7, .last = 0x05C7 }, - .{ .first = 0x0600, .last = 0x0605 }, // Arabic format - .{ .first = 0x0610, .last = 0x061A }, // Arabic combining - .{ .first = 0x061C, .last = 0x061C }, // Arabic Letter Mark - .{ .first = 0x064B, .last = 0x065F }, // Arabic combining - .{ .first = 0x0670, .last = 0x0670 }, - .{ .first = 0x06D6, .last = 0x06DD }, - .{ .first = 0x06DF, .last = 0x06E4 }, - .{ .first = 0x06E7, .last = 0x06E8 }, - .{ .first = 0x06EA, .last = 0x06ED }, - .{ .first = 0x070F, .last = 0x070F }, // Syriac Abbreviation Mark - .{ .first = 0x0711, .last = 0x0711 }, // Syriac combining - .{ .first = 0x0730, .last = 0x074A }, // Syriac combining - .{ .first = 0x07A6, .last = 0x07B0 }, // Thaana combining - .{ .first = 0x07EB, .last = 0x07F3 }, // NKo combining - .{ .first = 0x07FD, .last = 0x07FD }, - .{ .first = 0x0816, .last = 0x0819 }, // Samaritan combining - .{ .first = 0x081B, .last = 0x0823 }, - .{ .first = 0x0825, .last = 0x0827 }, - .{ .first = 0x0829, .last = 0x082D }, - .{ .first = 0x0859, .last = 0x085B }, // Mandaic combining - .{ .first = 0x0890, .last = 0x0891 }, // Arabic format - .{ .first = 0x0898, .last = 0x089F }, // Arabic combining - .{ .first = 0x08CA, .last = 0x08E1 }, // Arabic combining - .{ .first = 0x08E3, .last = 0x0902 }, // Arabic/Devanagari combining - .{ .first = 0x093A, .last = 0x093A }, - .{ .first = 0x093C, .last = 0x093C }, - .{ .first = 0x0941, .last = 0x0948 }, - .{ .first = 0x094D, .last = 0x094D }, - .{ .first = 0x0951, .last = 0x0957 }, - .{ .first = 0x0962, .last = 0x0963 }, - .{ .first = 0x0981, .last = 0x0981 }, // Bengali - .{ .first = 0x09BC, .last = 0x09BC }, - .{ .first = 0x09C1, .last = 0x09C4 }, - .{ .first = 0x09CD, .last = 0x09CD }, - .{ .first = 0x09E2, .last = 0x09E3 }, - .{ .first = 0x09FE, .last = 0x09FE }, - .{ .first = 0x0A01, .last = 0x0A02 }, // Gurmukhi - .{ .first = 0x0A3C, .last = 0x0A3C }, - .{ .first = 0x0A41, .last = 0x0A42 }, - .{ .first = 0x0A47, .last = 0x0A48 }, - .{ .first = 0x0A4B, .last = 0x0A4D }, - .{ .first = 0x0A51, .last = 0x0A51 }, - .{ .first = 0x0A70, .last = 0x0A71 }, - .{ .first = 0x0A75, .last = 0x0A75 }, - .{ .first = 0x0A81, .last = 0x0A82 }, // Gujarati - .{ .first = 0x0ABC, .last = 0x0ABC }, - .{ .first = 0x0AC1, .last = 0x0AC5 }, - .{ .first = 0x0AC7, .last = 0x0AC8 }, - .{ .first = 0x0ACD, .last = 0x0ACD }, - .{ .first = 0x0AE2, .last = 0x0AE3 }, - .{ .first = 0x0AFA, .last = 0x0AFF }, - .{ .first = 0x0B01, .last = 0x0B01 }, // Oriya - .{ .first = 0x0B3C, .last = 0x0B3C }, - .{ .first = 0x0B3F, .last = 0x0B3F }, - .{ .first = 0x0B41, .last = 0x0B44 }, - .{ .first = 0x0B4D, .last = 0x0B4D }, - .{ .first = 0x0B55, .last = 0x0B56 }, - .{ .first = 0x0B62, .last = 0x0B63 }, - .{ .first = 0x0B82, .last = 0x0B82 }, // Tamil - .{ .first = 0x0BC0, .last = 0x0BC0 }, - .{ .first = 0x0BCD, .last = 0x0BCD }, - .{ .first = 0x0C00, .last = 0x0C00 }, // Telugu - .{ .first = 0x0C04, .last = 0x0C04 }, - .{ .first = 0x0C3C, .last = 0x0C3C }, - .{ .first = 0x0C3E, .last = 0x0C40 }, - .{ .first = 0x0C46, .last = 0x0C48 }, - .{ .first = 0x0C4A, .last = 0x0C4D }, - .{ .first = 0x0C55, .last = 0x0C56 }, - .{ .first = 0x0C62, .last = 0x0C63 }, - .{ .first = 0x0C81, .last = 0x0C81 }, // Kannada - .{ .first = 0x0CBC, .last = 0x0CBC }, - .{ .first = 0x0CBF, .last = 0x0CBF }, - .{ .first = 0x0CC6, .last = 0x0CC6 }, - .{ .first = 0x0CCC, .last = 0x0CCD }, - .{ .first = 0x0CE2, .last = 0x0CE3 }, - .{ .first = 0x0D00, .last = 0x0D01 }, // Malayalam - .{ .first = 0x0D3B, .last = 0x0D3C }, - .{ .first = 0x0D41, .last = 0x0D44 }, - .{ .first = 0x0D4D, .last = 0x0D4D }, - .{ .first = 0x0D62, .last = 0x0D63 }, - .{ .first = 0x0D81, .last = 0x0D81 }, // Sinhala - .{ .first = 0x0DCA, .last = 0x0DCA }, - .{ .first = 0x0DD2, .last = 0x0DD4 }, - .{ .first = 0x0DD6, .last = 0x0DD6 }, - .{ .first = 0x0E31, .last = 0x0E31 }, // Thai - .{ .first = 0x0E34, .last = 0x0E3A }, - .{ .first = 0x0E47, .last = 0x0E4E }, - .{ .first = 0x0EB1, .last = 0x0EB1 }, // Lao - .{ .first = 0x0EB4, .last = 0x0EBC }, - .{ .first = 0x0EC8, .last = 0x0ECE }, - .{ .first = 0x0F18, .last = 0x0F19 }, // Tibetan - .{ .first = 0x0F35, .last = 0x0F35 }, - .{ .first = 0x0F37, .last = 0x0F37 }, - .{ .first = 0x0F39, .last = 0x0F39 }, - .{ .first = 0x0F71, .last = 0x0F7E }, - .{ .first = 0x0F80, .last = 0x0F84 }, - .{ .first = 0x0F86, .last = 0x0F87 }, - .{ .first = 0x0F8D, .last = 0x0F97 }, - .{ .first = 0x0F99, .last = 0x0FBC }, - .{ .first = 0x0FC6, .last = 0x0FC6 }, - .{ .first = 0x102D, .last = 0x1030 }, // Myanmar - .{ .first = 0x1032, .last = 0x1037 }, - .{ .first = 0x1039, .last = 0x103A }, - .{ .first = 0x103D, .last = 0x103E }, - .{ .first = 0x1058, .last = 0x1059 }, - .{ .first = 0x105E, .last = 0x1060 }, - .{ .first = 0x1071, .last = 0x1074 }, - .{ .first = 0x1082, .last = 0x1082 }, - .{ .first = 0x1085, .last = 0x1086 }, - .{ .first = 0x108D, .last = 0x108D }, - .{ .first = 0x109D, .last = 0x109D }, - .{ .first = 0x1160, .last = 0x11FF }, // Hangul Jamo medial vowels and final consonants - .{ .first = 0x135D, .last = 0x135F }, // Ethiopic combining - .{ .first = 0x1712, .last = 0x1714 }, // Tagalog - .{ .first = 0x1732, .last = 0x1733 }, // Hanunoo - .{ .first = 0x1752, .last = 0x1753 }, // Buhid - .{ .first = 0x1772, .last = 0x1773 }, // Tagbanwa - .{ .first = 0x17B4, .last = 0x17B5 }, // Khmer - .{ .first = 0x17B7, .last = 0x17BD }, - .{ .first = 0x17C6, .last = 0x17C6 }, - .{ .first = 0x17C9, .last = 0x17D3 }, - .{ .first = 0x17DD, .last = 0x17DD }, - .{ .first = 0x180B, .last = 0x180F }, // Mongolian format/combining - .{ .first = 0x1885, .last = 0x1886 }, // Mongolian combining - .{ .first = 0x18A9, .last = 0x18A9 }, - .{ .first = 0x1920, .last = 0x1922 }, // Limbu - .{ .first = 0x1927, .last = 0x1928 }, - .{ .first = 0x1932, .last = 0x1932 }, - .{ .first = 0x1939, .last = 0x193B }, - .{ .first = 0x1A17, .last = 0x1A18 }, // Buginese - .{ .first = 0x1A1B, .last = 0x1A1B }, - .{ .first = 0x1A56, .last = 0x1A56 }, // Tai Tham - .{ .first = 0x1A58, .last = 0x1A5E }, - .{ .first = 0x1A60, .last = 0x1A60 }, - .{ .first = 0x1A62, .last = 0x1A62 }, - .{ .first = 0x1A65, .last = 0x1A6C }, - .{ .first = 0x1A73, .last = 0x1A7C }, - .{ .first = 0x1A7F, .last = 0x1A7F }, - .{ .first = 0x1AB0, .last = 0x1ACE }, // Combining Diacritical Marks Extended - .{ .first = 0x1B00, .last = 0x1B03 }, // Balinese - .{ .first = 0x1B34, .last = 0x1B34 }, - .{ .first = 0x1B36, .last = 0x1B3A }, - .{ .first = 0x1B3C, .last = 0x1B3C }, - .{ .first = 0x1B42, .last = 0x1B42 }, - .{ .first = 0x1B6B, .last = 0x1B73 }, - .{ .first = 0x1B80, .last = 0x1B81 }, // Sundanese - .{ .first = 0x1BA2, .last = 0x1BA5 }, - .{ .first = 0x1BA8, .last = 0x1BA9 }, - .{ .first = 0x1BAB, .last = 0x1BAD }, - .{ .first = 0x1BE6, .last = 0x1BE6 }, // Batak - .{ .first = 0x1BE8, .last = 0x1BE9 }, - .{ .first = 0x1BED, .last = 0x1BED }, - .{ .first = 0x1BEF, .last = 0x1BF1 }, - .{ .first = 0x1C2C, .last = 0x1C33 }, // Lepcha - .{ .first = 0x1C36, .last = 0x1C37 }, - .{ .first = 0x1CD0, .last = 0x1CD2 }, // Vedic Extensions - .{ .first = 0x1CD4, .last = 0x1CE0 }, - .{ .first = 0x1CE2, .last = 0x1CE8 }, - .{ .first = 0x1CED, .last = 0x1CED }, - .{ .first = 0x1CF4, .last = 0x1CF4 }, - .{ .first = 0x1CF8, .last = 0x1CF9 }, - .{ .first = 0x1DC0, .last = 0x1DFF }, // Combining Diacritical Marks Supplement - .{ .first = 0x200B, .last = 0x200F }, // Zero-width/format chars - .{ .first = 0x202A, .last = 0x202E }, // Bidi format - .{ .first = 0x2060, .last = 0x2064 }, // Invisible operators - .{ .first = 0x2066, .last = 0x206F }, // Bidi format - .{ .first = 0x20D0, .last = 0x20F0 }, // Combining Diacritical Marks for Symbols - .{ .first = 0x2CEF, .last = 0x2CF1 }, // Coptic combining - .{ .first = 0x2D7F, .last = 0x2D7F }, // Tifinagh combining - .{ .first = 0x2DE0, .last = 0x2DFF }, // Cyrillic Extended-A combining - .{ .first = 0x302A, .last = 0x302D }, // CJK ideographic tone marks - .{ .first = 0x3099, .last = 0x309A }, // Japanese combining - .{ .first = 0xA66F, .last = 0xA672 }, // Combining Cyrillic - .{ .first = 0xA674, .last = 0xA67D }, - .{ .first = 0xA69E, .last = 0xA69F }, - .{ .first = 0xA6F0, .last = 0xA6F1 }, // Bamum combining - .{ .first = 0xA802, .last = 0xA802 }, // Syloti Nagri - .{ .first = 0xA806, .last = 0xA806 }, - .{ .first = 0xA80B, .last = 0xA80B }, - .{ .first = 0xA825, .last = 0xA826 }, - .{ .first = 0xA82C, .last = 0xA82C }, - .{ .first = 0xA8C4, .last = 0xA8C5 }, // Saurashtra - .{ .first = 0xA8E0, .last = 0xA8F1 }, // Devanagari Extended combining - .{ .first = 0xA8FF, .last = 0xA8FF }, - .{ .first = 0xA926, .last = 0xA92D }, // Kayah Li - .{ .first = 0xA947, .last = 0xA951 }, // Rejang - .{ .first = 0xA980, .last = 0xA982 }, // Javanese - .{ .first = 0xA9B3, .last = 0xA9B3 }, - .{ .first = 0xA9B6, .last = 0xA9B9 }, - .{ .first = 0xA9BC, .last = 0xA9BD }, - .{ .first = 0xA9E5, .last = 0xA9E5 }, // Myanmar Extended-B - .{ .first = 0xAA29, .last = 0xAA2E }, // Cham - .{ .first = 0xAA31, .last = 0xAA32 }, - .{ .first = 0xAA35, .last = 0xAA36 }, - .{ .first = 0xAA43, .last = 0xAA43 }, - .{ .first = 0xAA4C, .last = 0xAA4C }, - .{ .first = 0xAA7C, .last = 0xAA7C }, - .{ .first = 0xAAB0, .last = 0xAAB0 }, // Tai Viet - .{ .first = 0xAAB2, .last = 0xAAB4 }, - .{ .first = 0xAAB7, .last = 0xAAB8 }, - .{ .first = 0xAABE, .last = 0xAABF }, - .{ .first = 0xAAC1, .last = 0xAAC1 }, - .{ .first = 0xAAEC, .last = 0xAAED }, - .{ .first = 0xAAF6, .last = 0xAAF6 }, - .{ .first = 0xABE5, .last = 0xABE5 }, // Meetei Mayek - .{ .first = 0xABE8, .last = 0xABE8 }, - .{ .first = 0xABED, .last = 0xABED }, - .{ .first = 0xFB1E, .last = 0xFB1E }, // Hebrew combining - .{ .first = 0xFE00, .last = 0xFE0F }, // Variation Selectors - .{ .first = 0xFE20, .last = 0xFE2F }, // Combining Half Marks - .{ .first = 0xFEFF, .last = 0xFEFF }, // BOM / ZWNBSP - .{ .first = 0xFFF9, .last = 0xFFFB }, // Interlinear annotation - .{ .first = 0x101FD, .last = 0x101FD }, // Phaistos combining - .{ .first = 0x102E0, .last = 0x102E0 }, // Coptic Epact combining - .{ .first = 0x10376, .last = 0x1037A }, // Old Permic combining - .{ .first = 0x10A01, .last = 0x10A03 }, // Kharoshthi combining - .{ .first = 0x10A05, .last = 0x10A06 }, - .{ .first = 0x10A0C, .last = 0x10A0F }, - .{ .first = 0x10A38, .last = 0x10A3A }, - .{ .first = 0x10A3F, .last = 0x10A3F }, - .{ .first = 0x10AE5, .last = 0x10AE6 }, // Manichaean combining - .{ .first = 0x10D24, .last = 0x10D27 }, // Hanifi Rohingya - .{ .first = 0x10EAB, .last = 0x10EAC }, // Yezidi combining - .{ .first = 0x10EFD, .last = 0x10EFF }, // Arabic Extended-C - .{ .first = 0x10F46, .last = 0x10F50 }, // Sogdian combining - .{ .first = 0x10F82, .last = 0x10F85 }, // Old Uyghur combining - .{ .first = 0x11001, .last = 0x11001 }, // Brahmi - .{ .first = 0x11038, .last = 0x11046 }, - .{ .first = 0x11070, .last = 0x11070 }, - .{ .first = 0x11073, .last = 0x11074 }, - .{ .first = 0x1107F, .last = 0x11081 }, // Kaithi - .{ .first = 0x110B3, .last = 0x110B6 }, - .{ .first = 0x110B9, .last = 0x110BA }, - .{ .first = 0x110C2, .last = 0x110C2 }, - .{ .first = 0x11100, .last = 0x11102 }, // Chakma - .{ .first = 0x11127, .last = 0x1112B }, - .{ .first = 0x1112D, .last = 0x11134 }, - .{ .first = 0x11173, .last = 0x11173 }, // Mahajani - .{ .first = 0x11180, .last = 0x11181 }, // Sharada - .{ .first = 0x111B6, .last = 0x111BE }, - .{ .first = 0x111C9, .last = 0x111CC }, - .{ .first = 0x111CF, .last = 0x111CF }, - .{ .first = 0x1122F, .last = 0x11231 }, // Khojki - .{ .first = 0x11234, .last = 0x11234 }, - .{ .first = 0x11236, .last = 0x11237 }, - .{ .first = 0x1123E, .last = 0x1123E }, - .{ .first = 0x11241, .last = 0x11241 }, - .{ .first = 0x112DF, .last = 0x112DF }, // Khudawadi - .{ .first = 0x112E3, .last = 0x112EA }, - .{ .first = 0x11300, .last = 0x11301 }, // Grantha - .{ .first = 0x1133B, .last = 0x1133C }, - .{ .first = 0x11340, .last = 0x11340 }, - .{ .first = 0x11366, .last = 0x1136C }, - .{ .first = 0x11370, .last = 0x11374 }, - .{ .first = 0x11438, .last = 0x1143F }, // Newa - .{ .first = 0x11442, .last = 0x11444 }, - .{ .first = 0x11446, .last = 0x11446 }, - .{ .first = 0x1145E, .last = 0x1145E }, - .{ .first = 0x114B3, .last = 0x114B8 }, // Tirhuta - .{ .first = 0x114BA, .last = 0x114BA }, - .{ .first = 0x114BF, .last = 0x114C0 }, - .{ .first = 0x114C2, .last = 0x114C3 }, - .{ .first = 0x115B2, .last = 0x115B5 }, // Siddham - .{ .first = 0x115BC, .last = 0x115BD }, - .{ .first = 0x115BF, .last = 0x115C0 }, - .{ .first = 0x115DC, .last = 0x115DD }, - .{ .first = 0x11633, .last = 0x1163A }, // Modi - .{ .first = 0x1163D, .last = 0x1163D }, - .{ .first = 0x1163F, .last = 0x11640 }, - .{ .first = 0x116AB, .last = 0x116AB }, // Takri - .{ .first = 0x116AD, .last = 0x116AD }, - .{ .first = 0x116B0, .last = 0x116B5 }, - .{ .first = 0x116B7, .last = 0x116B7 }, - .{ .first = 0x1171D, .last = 0x1171F }, // Ahom - .{ .first = 0x11722, .last = 0x11725 }, - .{ .first = 0x11727, .last = 0x1172B }, - .{ .first = 0x1182F, .last = 0x11837 }, // Dogra - .{ .first = 0x11839, .last = 0x1183A }, - .{ .first = 0x1193B, .last = 0x1193C }, // Dives Akuru - .{ .first = 0x1193E, .last = 0x1193E }, - .{ .first = 0x11943, .last = 0x11943 }, - .{ .first = 0x119D4, .last = 0x119D7 }, // Nandinagari - .{ .first = 0x119DA, .last = 0x119DB }, - .{ .first = 0x119E0, .last = 0x119E0 }, - .{ .first = 0x11A01, .last = 0x11A0A }, // Zanabazar Square - .{ .first = 0x11A33, .last = 0x11A38 }, - .{ .first = 0x11A3B, .last = 0x11A3E }, - .{ .first = 0x11A47, .last = 0x11A47 }, - .{ .first = 0x11A51, .last = 0x11A56 }, // Soyombo - .{ .first = 0x11A59, .last = 0x11A5B }, - .{ .first = 0x11A8A, .last = 0x11A96 }, - .{ .first = 0x11A98, .last = 0x11A99 }, - .{ .first = 0x11C30, .last = 0x11C36 }, // Bhaiksuki - .{ .first = 0x11C38, .last = 0x11C3D }, - .{ .first = 0x11C3F, .last = 0x11C3F }, - .{ .first = 0x11C92, .last = 0x11CA7 }, // Marchen - .{ .first = 0x11CAA, .last = 0x11CB0 }, - .{ .first = 0x11CB2, .last = 0x11CB3 }, - .{ .first = 0x11CB5, .last = 0x11CB6 }, - .{ .first = 0x11D31, .last = 0x11D36 }, // Masaram Gondi - .{ .first = 0x11D3A, .last = 0x11D3A }, - .{ .first = 0x11D3C, .last = 0x11D3D }, - .{ .first = 0x11D3F, .last = 0x11D45 }, - .{ .first = 0x11D47, .last = 0x11D47 }, - .{ .first = 0x11D90, .last = 0x11D91 }, // Gunjala Gondi - .{ .first = 0x11D95, .last = 0x11D95 }, - .{ .first = 0x11D97, .last = 0x11D97 }, - .{ .first = 0x11EF3, .last = 0x11EF4 }, // Makasar - .{ .first = 0x11F00, .last = 0x11F01 }, // Siddham Extended - .{ .first = 0x11F36, .last = 0x11F3A }, - .{ .first = 0x11F40, .last = 0x11F40 }, - .{ .first = 0x11F42, .last = 0x11F42 }, - .{ .first = 0x13430, .last = 0x13440 }, // Egyptian Hieroglyph format - .{ .first = 0x13447, .last = 0x13455 }, - .{ .first = 0x16AF0, .last = 0x16AF4 }, // Bassa Vah combining - .{ .first = 0x16B30, .last = 0x16B36 }, // Pahawh Hmong combining - .{ .first = 0x16F4F, .last = 0x16F4F }, // Miao combining - .{ .first = 0x16F8F, .last = 0x16F92 }, - .{ .first = 0x16FE4, .last = 0x16FE4 }, // Ideographic combining - .{ .first = 0x1BC9D, .last = 0x1BC9E }, // Duployan combining - .{ .first = 0x1BCA0, .last = 0x1BCA3 }, // Shorthand format - .{ .first = 0x1CF00, .last = 0x1CF2D }, // Znamenny Musical combining - .{ .first = 0x1CF30, .last = 0x1CF46 }, - .{ .first = 0x1D167, .last = 0x1D169 }, // Musical Symbols combining - .{ .first = 0x1D173, .last = 0x1D182 }, - .{ .first = 0x1D185, .last = 0x1D18B }, - .{ .first = 0x1D1AA, .last = 0x1D1AD }, - .{ .first = 0x1D242, .last = 0x1D244 }, // Combining Greek Musical - .{ .first = 0x1DA00, .last = 0x1DA36 }, // Signwriting combining - .{ .first = 0x1DA3B, .last = 0x1DA6C }, - .{ .first = 0x1DA75, .last = 0x1DA75 }, - .{ .first = 0x1DA84, .last = 0x1DA84 }, - .{ .first = 0x1DA9B, .last = 0x1DA9F }, - .{ .first = 0x1DAA1, .last = 0x1DAAF }, - .{ .first = 0x1E000, .last = 0x1E006 }, // Glagolitic combining - .{ .first = 0x1E008, .last = 0x1E018 }, - .{ .first = 0x1E01B, .last = 0x1E021 }, - .{ .first = 0x1E023, .last = 0x1E024 }, - .{ .first = 0x1E026, .last = 0x1E02A }, - .{ .first = 0x1E08F, .last = 0x1E08F }, // Cyrillic Extended-D - .{ .first = 0x1E130, .last = 0x1E136 }, // Nyiakeng Puachue Hmong - .{ .first = 0x1E2AE, .last = 0x1E2AE }, // Wancho combining - .{ .first = 0x1E2EC, .last = 0x1E2EF }, // Mende Kikakui combining - .{ .first = 0x1E4EC, .last = 0x1E4EF }, // Cypro-Minoan - .{ .first = 0x1E8D0, .last = 0x1E8D6 }, // Mende Kikakui combining - .{ .first = 0x1E944, .last = 0x1E94A }, // Adlam combining - .{ .first = 0xE0001, .last = 0xE0001 }, // Language Tag - .{ .first = 0xE0020, .last = 0xE007F }, // Tag characters - .{ .first = 0xE0100, .last = 0xE01EF }, // Variation Selectors Supplement -}; - -/// Wide character ranges (2 cells): CJK, Hangul, fullwidth forms, emoji presentation, etc. -const wide_ranges = [_]Range{ - .{ .first = 0x1100, .last = 0x115F }, // Hangul Jamo initial consonants - .{ .first = 0x231A, .last = 0x231B }, // Watch, Hourglass - .{ .first = 0x2329, .last = 0x232A }, // Angle brackets - .{ .first = 0x23E9, .last = 0x23EC }, // Double triangles - .{ .first = 0x23F0, .last = 0x23F0 }, // Alarm clock - .{ .first = 0x23F3, .last = 0x23F3 }, // Hourglass flowing - .{ .first = 0x25FD, .last = 0x25FE }, // Medium small squares - .{ .first = 0x2614, .last = 0x2615 }, // Umbrella, Hot beverage - .{ .first = 0x2648, .last = 0x2653 }, // Zodiac signs - .{ .first = 0x267F, .last = 0x267F }, // Wheelchair - .{ .first = 0x2693, .last = 0x2693 }, // Anchor - .{ .first = 0x26A1, .last = 0x26A1 }, // High voltage - .{ .first = 0x26AA, .last = 0x26AB }, // Medium circles - .{ .first = 0x26BD, .last = 0x26BE }, // Soccer, Baseball - .{ .first = 0x26C4, .last = 0x26C5 }, // Snowman, Sun behind cloud - .{ .first = 0x26CE, .last = 0x26CE }, // Ophiuchus - .{ .first = 0x26D4, .last = 0x26D4 }, // No entry - .{ .first = 0x26EA, .last = 0x26EA }, // Church - .{ .first = 0x26F2, .last = 0x26F3 }, // Fountain, Golf - .{ .first = 0x26F5, .last = 0x26F5 }, // Sailboat - .{ .first = 0x26FA, .last = 0x26FA }, // Tent - .{ .first = 0x26FD, .last = 0x26FD }, // Fuel pump - .{ .first = 0x2702, .last = 0x2702 }, // Scissors - .{ .first = 0x2705, .last = 0x2705 }, // Check mark - .{ .first = 0x2708, .last = 0x270D }, // Airplane..Writing hand - .{ .first = 0x270F, .last = 0x270F }, // Pencil - .{ .first = 0x2712, .last = 0x2712 }, // Black nib - .{ .first = 0x2714, .last = 0x2714 }, // Check mark - .{ .first = 0x2716, .last = 0x2716 }, // Heavy multiplication - .{ .first = 0x271D, .last = 0x271D }, // Latin cross - .{ .first = 0x2721, .last = 0x2721 }, // Star of David - .{ .first = 0x2728, .last = 0x2728 }, // Sparkles - .{ .first = 0x2733, .last = 0x2734 }, // Eight spoked asterisk - .{ .first = 0x2744, .last = 0x2744 }, // Snowflake - .{ .first = 0x2747, .last = 0x2747 }, // Sparkle - .{ .first = 0x274C, .last = 0x274C }, // Cross mark - .{ .first = 0x274E, .last = 0x274E }, // Cross mark - .{ .first = 0x2753, .last = 0x2755 }, // Question marks - .{ .first = 0x2757, .last = 0x2757 }, // Exclamation mark - .{ .first = 0x2763, .last = 0x2764 }, // Heart exclamation, Heart - .{ .first = 0x2795, .last = 0x2797 }, // Plus, Minus, Division - .{ .first = 0x27A1, .last = 0x27A1 }, // Right arrow - .{ .first = 0x27B0, .last = 0x27B0 }, // Curly loop - .{ .first = 0x27BF, .last = 0x27BF }, // Double curly loop - .{ .first = 0x2934, .last = 0x2935 }, // Arrows - .{ .first = 0x2B05, .last = 0x2B07 }, // Arrows - .{ .first = 0x2B1B, .last = 0x2B1C }, // Large squares - .{ .first = 0x2B50, .last = 0x2B50 }, // Star - .{ .first = 0x2B55, .last = 0x2B55 }, // Large circle - .{ .first = 0x2E80, .last = 0x2E99 }, // CJK Radicals Supplement - .{ .first = 0x2E9B, .last = 0x2EF3 }, - .{ .first = 0x2F00, .last = 0x2FD5 }, // Kangxi Radicals - .{ .first = 0x2FF0, .last = 0x303E }, // Ideographic Description + CJK Symbols - .{ .first = 0x3041, .last = 0x3096 }, // Hiragana - .{ .first = 0x3099, .last = 0x30FF }, // Hiragana/Katakana - .{ .first = 0x3105, .last = 0x312F }, // Bopomofo - .{ .first = 0x3131, .last = 0x318E }, // Hangul Compatibility Jamo - .{ .first = 0x3190, .last = 0x31E3 }, // Kanbun + CJK Strokes - .{ .first = 0x31EF, .last = 0x321E }, // CJK Ideographic Telegraph + Enclosed CJK - .{ .first = 0x3220, .last = 0x3247 }, - .{ .first = 0x3250, .last = 0x4DBF }, // Enclosed CJK + CJK Unified Ext A - .{ .first = 0x4E00, .last = 0xA48C }, // CJK Unified Ideographs + Yi Syllables - .{ .first = 0xA490, .last = 0xA4C6 }, // Yi Radicals - .{ .first = 0xA960, .last = 0xA97C }, // Hangul Jamo Extended-A - .{ .first = 0xAC00, .last = 0xD7A3 }, // Hangul Syllables - .{ .first = 0xF900, .last = 0xFAFF }, // CJK Compatibility Ideographs - .{ .first = 0xFE10, .last = 0xFE19 }, // Vertical Forms - .{ .first = 0xFE30, .last = 0xFE6B }, // CJK Compatibility Forms + Small Form Variants - .{ .first = 0xFF01, .last = 0xFF60 }, // Fullwidth ASCII + Fullwidth punctuation - .{ .first = 0xFFE0, .last = 0xFFE6 }, // Fullwidth signs - .{ .first = 0x16FE0, .last = 0x16FE4 }, // Ideographic Symbols - .{ .first = 0x16FF0, .last = 0x16FF1 }, - .{ .first = 0x17000, .last = 0x187F7 }, // Tangut - .{ .first = 0x18800, .last = 0x18CD5 }, // Tangut Components - .{ .first = 0x18D00, .last = 0x18D08 }, // Tangut Supplement - .{ .first = 0x1AFF0, .last = 0x1AFF3 }, // Kana Extended-B - .{ .first = 0x1AFF5, .last = 0x1AFFB }, - .{ .first = 0x1AFFD, .last = 0x1AFFE }, - .{ .first = 0x1B000, .last = 0x1B122 }, // Kana Supplement + Kana Extended-A - .{ .first = 0x1B132, .last = 0x1B132 }, - .{ .first = 0x1B150, .last = 0x1B152 }, // Small Kana Extension - .{ .first = 0x1B155, .last = 0x1B155 }, - .{ .first = 0x1B164, .last = 0x1B167 }, - .{ .first = 0x1B170, .last = 0x1B2FB }, // Nushu - .{ .first = 0x1F004, .last = 0x1F004 }, // Mahjong tile - .{ .first = 0x1F0CF, .last = 0x1F0CF }, // Playing card - .{ .first = 0x1F18E, .last = 0x1F18E }, // AB button - .{ .first = 0x1F191, .last = 0x1F19A }, // Squared symbols - .{ .first = 0x1F1E0, .last = 0x1F1FF }, // Regional Indicators (flags) - .{ .first = 0x1F200, .last = 0x1F202 }, // Enclosed Ideographic Supplement - .{ .first = 0x1F210, .last = 0x1F23B }, - .{ .first = 0x1F240, .last = 0x1F248 }, - .{ .first = 0x1F250, .last = 0x1F251 }, - .{ .first = 0x1F260, .last = 0x1F265 }, - .{ .first = 0x1F300, .last = 0x1F320 }, // Miscellaneous Symbols and Pictographs - .{ .first = 0x1F32D, .last = 0x1F335 }, - .{ .first = 0x1F337, .last = 0x1F37C }, - .{ .first = 0x1F37E, .last = 0x1F393 }, - .{ .first = 0x1F3A0, .last = 0x1F3CA }, - .{ .first = 0x1F3CF, .last = 0x1F3D3 }, - .{ .first = 0x1F3E0, .last = 0x1F3F0 }, - .{ .first = 0x1F3F4, .last = 0x1F3F4 }, - .{ .first = 0x1F3F8, .last = 0x1F43E }, - .{ .first = 0x1F440, .last = 0x1F440 }, - .{ .first = 0x1F442, .last = 0x1F4FC }, - .{ .first = 0x1F4FF, .last = 0x1F53D }, - .{ .first = 0x1F54B, .last = 0x1F54E }, - .{ .first = 0x1F550, .last = 0x1F567 }, - .{ .first = 0x1F57A, .last = 0x1F57A }, - .{ .first = 0x1F595, .last = 0x1F596 }, - .{ .first = 0x1F5A4, .last = 0x1F5A4 }, - .{ .first = 0x1F5FB, .last = 0x1F64F }, - .{ .first = 0x1F680, .last = 0x1F6C5 }, - .{ .first = 0x1F6CC, .last = 0x1F6CC }, - .{ .first = 0x1F6D0, .last = 0x1F6D2 }, - .{ .first = 0x1F6D5, .last = 0x1F6D7 }, - .{ .first = 0x1F6DC, .last = 0x1F6DF }, - .{ .first = 0x1F6EB, .last = 0x1F6EC }, - .{ .first = 0x1F6F4, .last = 0x1F6FC }, - .{ .first = 0x1F7E0, .last = 0x1F7EB }, - .{ .first = 0x1F7F0, .last = 0x1F7F0 }, - .{ .first = 0x1F90C, .last = 0x1F93A }, - .{ .first = 0x1F93C, .last = 0x1F945 }, - .{ .first = 0x1F947, .last = 0x1F9FF }, - .{ .first = 0x1FA70, .last = 0x1FA7C }, - .{ .first = 0x1FA80, .last = 0x1FA89 }, - .{ .first = 0x1FA8F, .last = 0x1FAC6 }, - .{ .first = 0x1FACE, .last = 0x1FADC }, - .{ .first = 0x1FADF, .last = 0x1FAE9 }, - .{ .first = 0x1FAF0, .last = 0x1FAF8 }, - .{ .first = 0x20000, .last = 0x2FFFD }, // CJK Unified Ideographs Extension B-F + Supplementary - .{ .first = 0x30000, .last = 0x3FFFD }, // CJK Unified Ideographs Extension G-I + Tertiary -}; - -/// Binary search for a codepoint within sorted range tables. -fn inRanges(cp: u21, ranges: []const Range) bool { - var lo: usize = 0; - var hi: usize = ranges.len; - while (lo < hi) { - const mid = lo + (hi - lo) / 2; - if (cp > ranges[mid].last) { - lo = mid + 1; - } else if (cp < ranges[mid].first) { - hi = mid; - } else { - return true; - } - } - return false; -} - -/// Returns the display width of a Unicode codepoint. -/// -1 = non-printable control, 0 = zero-width, 1 = normal, 2 = wide (double-width). -pub fn codepointWidth(cp: u21) i3 { - // C0 controls (except HT, LF which callers handle) - if (cp < 0x20) return -1; - // DEL - if (cp == 0x7F) return -1; - // C1 controls - if (cp >= 0x80 and cp <= 0x9F) return -1; - - // Zero-width - if (inRanges(cp, &zero_width_ranges)) return 0; - - // Wide - if (inRanges(cp, &wide_ranges)) return 2; - - // Private Use Areas — treat as width 1 - // Noncharacters — treat as width 1 - - return 1; -} - -/// Convenience wrapper: returns display width clamped to 0 (controls treated as 0). -pub fn charWidth(cp: u21) usize { - const w = codepointWidth(cp); - return if (w > 0) @intCast(w) else 0; -} - -/// Calculate the display width of a UTF-8 string (no ANSI awareness). -pub fn strWidth(str: []const u8) usize { - var w: usize = 0; - var i: usize = 0; - while (i < str.len) { - const byte_len = std.unicode.utf8ByteSequenceLength(str[i]) catch { - i += 1; - continue; - }; - if (i + byte_len > str.len) break; - const cp = std.unicode.utf8Decode(str[i..][0..byte_len]) catch { - i += 1; - continue; - }; - w += charWidth(cp); - i += byte_len; - } - return w; -} - -// ── Tests ────────────────────────────────────────────────────────────── - -test "ASCII characters are width 1" { - try std.testing.expectEqual(@as(usize, 1), charWidth('A')); - try std.testing.expectEqual(@as(usize, 1), charWidth('z')); - try std.testing.expectEqual(@as(usize, 1), charWidth(' ')); - try std.testing.expectEqual(@as(usize, 1), charWidth('~')); -} - -test "control characters are width 0 via charWidth" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0x00)); // NUL - try std.testing.expectEqual(@as(usize, 0), charWidth(0x01)); // SOH - try std.testing.expectEqual(@as(usize, 0), charWidth(0x7F)); // DEL - try std.testing.expectEqual(@as(usize, 0), charWidth(0x80)); // C1 - try std.testing.expectEqual(@as(usize, 0), charWidth(0x9F)); // C1 end -} - -test "control characters are -1 via codepointWidth" { - try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x00)); - try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x7F)); - try std.testing.expectEqual(@as(i3, -1), codepointWidth(0x9F)); -} - -test "combining marks are zero-width" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0x0300)); // Combining Grave Accent - try std.testing.expectEqual(@as(usize, 0), charWidth(0x0301)); // Combining Acute Accent - try std.testing.expectEqual(@as(usize, 0), charWidth(0x036F)); // End of basic combining - try std.testing.expectEqual(@as(usize, 0), charWidth(0x20D0)); // Combining symbol marks - try std.testing.expectEqual(@as(usize, 0), charWidth(0xFE0F)); // Variation Selector-16 - try std.testing.expectEqual(@as(usize, 0), charWidth(0xFE00)); // Variation Selector-1 -} - -test "zero-width format characters" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0x200B)); // ZWSP - try std.testing.expectEqual(@as(usize, 0), charWidth(0x200C)); // ZWNJ - try std.testing.expectEqual(@as(usize, 0), charWidth(0x200D)); // ZWJ - try std.testing.expectEqual(@as(usize, 0), charWidth(0xFEFF)); // BOM - try std.testing.expectEqual(@as(usize, 0), charWidth(0x2060)); // Word Joiner -} - -test "CJK ideographs are wide" { - try std.testing.expectEqual(@as(usize, 2), charWidth(0x4E00)); // CJK Unified start - try std.testing.expectEqual(@as(usize, 2), charWidth(0x9FFF)); // CJK Unified - try std.testing.expectEqual(@as(usize, 2), charWidth(0x4E2D)); // 中 - try std.testing.expectEqual(@as(usize, 2), charWidth(0x6587)); // 文 -} - -test "Hangul syllables are wide" { - try std.testing.expectEqual(@as(usize, 2), charWidth(0xAC00)); // Hangul Syllable start - try std.testing.expectEqual(@as(usize, 2), charWidth(0xD7A3)); // Hangul Syllable end -} - -test "Hangul Jamo medials/finals are zero-width" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0x1160)); // Jamo medial start - try std.testing.expectEqual(@as(usize, 0), charWidth(0x11FF)); // Jamo final end -} - -test "fullwidth forms are wide" { - try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF01)); // Fullwidth ! - try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF21)); // Fullwidth A - try std.testing.expectEqual(@as(usize, 2), charWidth(0xFF41)); // Fullwidth a -} - -test "halfwidth Katakana is normal width" { - try std.testing.expectEqual(@as(usize, 1), charWidth(0xFF61)); // Halfwidth Katakana start - try std.testing.expectEqual(@as(usize, 1), charWidth(0xFF9F)); // Halfwidth Katakana end -} - -test "emoji are wide" { - try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F600)); // Grinning face - try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F4A9)); // Pile of poo - try std.testing.expectEqual(@as(usize, 2), charWidth(0x1F680)); // Rocket - try std.testing.expectEqual(@as(usize, 2), charWidth(0x2615)); // Hot beverage - try std.testing.expectEqual(@as(usize, 2), charWidth(0x231A)); // Watch -} - -test "variation selectors are zero-width" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0xE0100)); // VS17 - try std.testing.expectEqual(@as(usize, 0), charWidth(0xE01EF)); // VS256 -} - -test "strWidth with mixed content" { - try std.testing.expectEqual(@as(usize, 4), strWidth("中文")); // 2 wide chars - try std.testing.expectEqual(@as(usize, 5), strWidth("hello")); - try std.testing.expectEqual(@as(usize, 6), strWidth("hi中文")); // h=1 i=1 中=2 文=2 => 6 -} - -test "strWidth with combining characters" { - // e + combining acute accent = 1 display column - try std.testing.expectEqual(@as(usize, 1), strWidth("e\xcc\x81")); - // a + combining ring above = 1 - try std.testing.expectEqual(@as(usize, 1), strWidth("a\xcc\x8a")); -} - -test "CJK Extension B is wide" { - try std.testing.expectEqual(@as(usize, 2), charWidth(0x20000)); // Extension B start - try std.testing.expectEqual(@as(usize, 2), charWidth(0x2A6DF)); // Extension B range -} - -test "soft hyphen is zero-width" { - try std.testing.expectEqual(@as(usize, 0), charWidth(0x00AD)); -} From 3f625e2d5af29342d07f76f426fd110a0c225fec Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 7 May 2026 21:37:35 +0900 Subject: [PATCH 07/10] fix: address PR #3 review feedback - main: guard args[1][0] with len > 0 to avoid OOB on empty arg - checker: unlock mutex on toOwnedSlice OOM in joinAllThreads - checker: parse IPv4/IPv6 literals before HostName.init so bare IPv6 hosts no longer always report offline - ssh_config: createDirPath before openDir in writeFile so save succeeds when ~/.ssh is missing - ssh_config/meta: propagate dir/file errors instead of swallowing them in createDirPath/backupFile/rotateBackups --- src/checker.zig | 13 ++++++++++++- src/main.zig | 2 +- src/meta.zig | 2 +- src/ssh_config.zig | 11 ++++++----- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/checker.zig b/src/checker.zig index 7ba32a7..fd5a0d6 100644 --- a/src/checker.zig +++ b/src/checker.zig @@ -82,7 +82,10 @@ pub const StatusChecker = struct { fn joinAllThreads(self: *StatusChecker) void { self.threads_mutex.lockUncancelable(self.io); - const threads = self.threads.toOwnedSlice(self.allocator) catch return; + const threads = self.threads.toOwnedSlice(self.allocator) catch { + self.threads_mutex.unlock(self.io); + return; + }; self.threads_mutex.unlock(self.io); for (threads) |t| t.join(); self.allocator.free(threads); @@ -154,6 +157,14 @@ pub const StatusChecker = struct { }; fn tcpCheck(io: std.Io, hostname: []const u8, port: u16) HostStatus { + // Try IPv4/IPv6 literals first; HostName.init rejects ':' so a bare IPv6 + // address would otherwise always report offline. + if (std.Io.net.IpAddress.parse(hostname, port)) |addr| { + const stream = addr.connect(io, .{ .mode = .stream }) catch return .offline; + stream.close(io); + return .online; + } else |_| {} + const host = std.Io.net.HostName.init(hostname) catch return .offline; const stream = host.connect(io, port, .{ .mode = .stream }) catch return .offline; stream.close(io); diff --git a/src/main.zig b/src/main.zig index 7f10c2a..a22f1f0 100644 --- a/src/main.zig +++ b/src/main.zig @@ -26,7 +26,7 @@ pub fn main(init: std.process.Init) !void { } // sshz [command...] — direct connect - if (args.len >= 2 and args[1][0] != '-') { + if (args.len >= 2 and args[1].len > 0 and args[1][0] != '-') { try directConnect(allocator, init.io, init.environ_map, args[1], args[2..]); return; } diff --git a/src/meta.zig b/src/meta.zig index 3a2fba8..1a2f3e9 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -227,7 +227,7 @@ pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, store: *const MetaSto const basename = std.fs.path.basename(path); const cwd = std.Io.Dir.cwd(); - cwd.createDirPath(io, dir_path) catch {}; + try cwd.createDirPath(io, dir_path); var tmp_buf: [256]u8 = undefined; const tmp_name = std.fmt.bufPrint(&tmp_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 1857cdc..09ccbfe 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -305,6 +305,7 @@ pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config const tmp_name = std.fmt.bufPrint(&tmp_name_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir_path); var dir_fd = try cwd.openDir(io, dir_path, .{}); defer dir_fd.close(io); @@ -322,7 +323,7 @@ pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, backup_dir: []const u8) !void { const cwd = std.Io.Dir.cwd(); - cwd.createDirPath(io, backup_dir) catch {}; + try cwd.createDirPath(io, backup_dir); const content = cwd.readFileAlloc(io, source_path, allocator, .limited(1024 * 1024)) catch return; defer allocator.free(content); @@ -335,12 +336,12 @@ fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, const backup_path = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ backup_dir, backup_name }) catch return; { - const dest = cwd.createFile(io, backup_path, .{}) catch return; + const dest = try cwd.createFile(io, backup_path, .{}); defer dest.close(io); var write_buf: [4096]u8 = undefined; var w = dest.writer(io, &write_buf); - w.interface.writeAll(content) catch return; - w.interface.flush() catch return; + try w.interface.writeAll(content); + try w.interface.flush(); } rotateBackups(allocator, io, backup_dir) catch {}; @@ -374,7 +375,7 @@ fn rotateBackups(allocator: std.mem.Allocator, io: std.Io, backup_dir: []const u const to_delete = entries.items.len - 10; for (entries.items[0..to_delete]) |name| { - dir.deleteFile(io, name) catch {}; + try dir.deleteFile(io, name); } } From 316e53be83b804baab303453f4f36dc379704eb4 Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 7 May 2026 21:55:07 +0900 Subject: [PATCH 08/10] fix: address pre-existing bugs flagged in PR #3 review - ssh_config: Config now owns the raw file buffer so hosts/raw_lines slices remain valid after readFile (CodeRabbit critical: dangling reference on `parse` content) - meta: JSON-escape host names, tags, and port-forward fields when serialising so values containing `"`, `\\`, or control characters no longer corrupt meta.json (CodeRabbit major) - app.deleteSelectedHost: look up the config entry by name from the visible list instead of by display index, so sorting no longer causes the wrong host to be deleted (CodeRabbit critical) - app.saveForm: always call setTags so clearing the tags field in the edit form persists an empty list (CodeRabbit major) - app.connectToSelected: stop recording the connection in the TUI path; directConnect already records it after the TUI exits, so this was double-counting connect_count (CodeAnt major) --- src/app.zig | 32 ++++++++++++++++---------------- src/meta.zig | 46 +++++++++++++++++++++++++++++++++------------- src/ssh_config.zig | 13 +++++++++++-- 3 files changed, 60 insertions(+), 31 deletions(-) diff --git a/src/app.zig b/src/app.zig index eea6edf..682f653 100644 --- a/src/app.zig +++ b/src/app.zig @@ -403,8 +403,8 @@ pub const Model = struct { fn connectToSelected(self: *Model) void { if (self.selected >= self.hosts.items.len) return; const entry = self.hosts.items[self.selected]; - self.meta_store.recordConnection(self.pa, self.io, entry.config.name) catch {}; - meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; + // Connection metadata is recorded by `directConnect` after the TUI + // exits, so don't record here as well — that double-counts. self.connect_host = self.pa.dupe(u8, entry.config.name) catch null; } @@ -457,17 +457,16 @@ pub const Model = struct { ssh_config.addHost(self.pa, &self.config, new_host) catch {}; ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; - // Save tags - if (tags_val.len > 0) { - var tags: std.ArrayList([]const u8) = .empty; - defer tags.deinit(self.pa); - var tag_it = std.mem.splitScalar(u8, tags_val, ','); - while (tag_it.next()) |tag| { - const trimmed = std.mem.trim(u8, tag, " "); - if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {}; - } - self.meta_store.setTags(self.pa, name, tags.items) catch {}; + // Save tags. Always call setTags so clearing the tags field in the + // edit form actually persists an empty tag list. + var tags: std.ArrayList([]const u8) = .empty; + defer tags.deinit(self.pa); + var tag_it = std.mem.splitScalar(u8, tags_val, ','); + while (tag_it.next()) |tag| { + const trimmed = std.mem.trim(u8, tag, " "); + if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {}; } + self.meta_store.setTags(self.pa, name, tags.items) catch {}; meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; self.rebuildHostList(); @@ -479,15 +478,16 @@ pub const Model = struct { fn deleteSelectedHost(self: *Model) void { if (self.selected >= self.hosts.items.len) return; + // Look up the config entry by name from the visible list so sorting + // and tag-filtering don't desynchronise the display index from the + // raw config order. + const selected_name = self.hosts.items[self.selected].config.name; var config_index: ?usize = null; - var display_i: usize = 0; for (self.config.hosts, 0..) |h, ci| { - if (h.is_wildcard) continue; - if (display_i == self.selected) { + if (std.mem.eql(u8, h.name, selected_name)) { config_index = ci; break; } - display_i += 1; } if (config_index) |ci| { diff --git a/src/meta.zig b/src/meta.zig index 1a2f3e9..e4920e2 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -157,6 +157,28 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { return store; } +/// Append a JSON string literal (including surrounding quotes) with proper +/// escaping for `"`, `\`, and ASCII control characters. +fn appendJsonString(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, s: []const u8) !void { + try buf.append(allocator, '"'); + for (s) |c| switch (c) { + '"' => try buf.appendSlice(allocator, "\\\""), + '\\' => try buf.appendSlice(allocator, "\\\\"), + '\n' => try buf.appendSlice(allocator, "\\n"), + '\r' => try buf.appendSlice(allocator, "\\r"), + '\t' => try buf.appendSlice(allocator, "\\t"), + 0x08 => try buf.appendSlice(allocator, "\\b"), + 0x0C => try buf.appendSlice(allocator, "\\f"), + 0x00...0x07, 0x0B, 0x0E...0x1F => { + var hex_buf: [6]u8 = undefined; + const hex = std.fmt.bufPrint(&hex_buf, "\\u{x:0>4}", .{c}) catch unreachable; + try buf.appendSlice(allocator, hex); + }, + else => try buf.append(allocator, c), + }; + try buf.append(allocator, '"'); +} + pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const u8 { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(allocator); @@ -172,15 +194,13 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const while (it.next()) |entry| { if (!first) try buf.appendSlice(allocator, ","); first = false; - try buf.appendSlice(allocator, "\n \""); - try buf.appendSlice(allocator, entry.key_ptr.*); - try buf.appendSlice(allocator, "\": {\n \"tags\": ["); + try buf.appendSlice(allocator, "\n "); + try appendJsonString(&buf, allocator, entry.key_ptr.*); + try buf.appendSlice(allocator, ": {\n \"tags\": ["); for (entry.value_ptr.tags, 0..) |tag, i| { if (i > 0) try buf.appendSlice(allocator, ", "); - try buf.appendSlice(allocator, "\""); - try buf.appendSlice(allocator, tag); - try buf.appendSlice(allocator, "\""); + try appendJsonString(&buf, allocator, tag); } try buf.appendSlice(allocator, "],\n \"last_connected\": "); @@ -193,13 +213,13 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const for (entry.value_ptr.port_forwards, 0..) |fwd, i| { if (i > 0) try buf.appendSlice(allocator, ", "); - try buf.appendSlice(allocator, "{\"type\": \""); - try buf.appendSlice(allocator, fwd.forward_type); - try buf.appendSlice(allocator, "\", \"bind\": \""); - try buf.appendSlice(allocator, fwd.bind); - try buf.appendSlice(allocator, "\", \"target\": \""); - try buf.appendSlice(allocator, fwd.target); - try buf.appendSlice(allocator, "\"}"); + try buf.appendSlice(allocator, "{\"type\": "); + try appendJsonString(&buf, allocator, fwd.forward_type); + try buf.appendSlice(allocator, ", \"bind\": "); + try appendJsonString(&buf, allocator, fwd.bind); + try buf.appendSlice(allocator, ", \"target\": "); + try appendJsonString(&buf, allocator, fwd.target); + try buf.append(allocator, '}'); } try buf.appendSlice(allocator, "]\n }"); diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 09ccbfe..d476a02 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -41,10 +41,15 @@ pub const Host = struct { pub const Config = struct { hosts: []Host, raw_lines: [][]const u8, + /// Backing storage for slices in `hosts` and `raw_lines` that originate + /// from `parse(content)`. Transferred to `Config` by `readFile` so the + /// borrowed slices stay valid for the Config's lifetime. + raw_buffer: []u8 = &[_]u8{}, pub fn deinit(self: *Config, allocator: std.mem.Allocator) void { allocator.free(self.hosts); allocator.free(self.raw_lines); + if (self.raw_buffer.len > 0) allocator.free(self.raw_buffer); } pub fn effectiveHostname(host: Host) []const u8 { @@ -288,8 +293,12 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Config { const cwd = std.Io.Dir.cwd(); const content = try cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)); - defer allocator.free(content); - return parse(allocator, content); + errdefer allocator.free(content); + var config = try parse(allocator, content); + // Transfer ownership: hosts/raw_lines borrow from `content`, so the + // Config must keep the buffer alive until deinit. + config.raw_buffer = content; + return config; } pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config, path: []const u8, backup_dir: []const u8) !void { From efb6ac704bc1c8cefe229df2a991cf484e0bc1f3 Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 7 May 2026 22:12:40 +0900 Subject: [PATCH 09/10] fix: maintain visible_indices so search/tag filters keep selected in sync Move filter logic from the renderer into Model.rebuildVisibleIndices. `selected` is now an index into `visible_indices` (the filtered display order), so navigation, edit ('e'), forward ('f'), delete ('d'), connect (Enter), and confirm-delete prompts all reference the same host the user actually sees highlighted, regardless of search text or tag filter. - add Model.visible_indices, rebuilt on rebuildHostList, cycleSortMode, cycleTagFilter, and every search-text mutation - moveDown bounds-check against visible_indices.items.len - views/host_list.zig drops matchesSearch/hasTag (now in app.zig) and iterates model.visible_indices directly --- src/app.zig | 99 ++++++++++++++++++++++++++++++++++------- src/views/host_list.zig | 52 ++++------------------ 2 files changed, 93 insertions(+), 58 deletions(-) diff --git a/src/app.zig b/src/app.zig index 682f653..10c22dd 100644 --- a/src/app.zig +++ b/src/app.zig @@ -26,6 +26,9 @@ pub const HostEntry = struct { pub const Model = struct { screen: Screen = .list, hosts: std.ArrayList(HostEntry), + /// Indices into `hosts` that pass the active search/tag filters, in + /// display order. `selected` is an index into this list, NOT `hosts`. + visible_indices: std.ArrayList(usize), config: ssh_config.Config, meta_store: meta_mod.MetaStore, config_path: []const u8, @@ -64,6 +67,7 @@ pub const Model = struct { self.env = ctx.environ_map; self.hosts = .empty; + self.visible_indices = .empty; self.search_text = .empty; self.all_tags = .empty; @@ -92,6 +96,7 @@ pub const Model = struct { pub fn deinit(self: *Model) void { self.status_checker.deinit(); self.hosts.deinit(self.pa); + self.visible_indices.deinit(self.pa); self.search_text.deinit(self.pa); self.all_tags.deinit(self.pa); self.result_queue.deinit(); @@ -110,6 +115,52 @@ pub const Model = struct { .status = .unknown, }) catch {}; } + self.rebuildVisibleIndices(); + } + + fn rebuildVisibleIndices(self: *Model) void { + self.visible_indices.clearRetainingCapacity(); + for (self.hosts.items, 0..) |entry, i| { + if (!self.entryMatchesFilters(entry)) continue; + self.visible_indices.append(self.pa, i) catch {}; + } + // Clamp `selected` so it stays in range when filters shrink the list. + if (self.selected >= self.visible_indices.items.len) { + self.selected = if (self.visible_indices.items.len == 0) 0 else self.visible_indices.items.len - 1; + } + } + + fn entryMatchesFilters(self: *const Model, entry: HostEntry) bool { + if (self.search_text.items.len > 0 and !matchesSearch(entry, self.search_text.items)) return false; + if (self.tag_filter) |tag| { + if (!hasTag(entry, tag)) return false; + } + return true; + } + + fn matchesSearch(entry: HostEntry, search: []const u8) bool { + if (std.mem.indexOf(u8, entry.config.name, search) != null) return true; + if (entry.config.hostname) |hn| { + if (std.mem.indexOf(u8, hn, search) != null) return true; + } + if (entry.config.user) |u| { + if (std.mem.indexOf(u8, u, search) != null) return true; + } + if (entry.meta) |m| { + for (m.tags) |tag| { + if (std.mem.indexOf(u8, tag, search) != null) return true; + } + } + return false; + } + + fn hasTag(entry: HostEntry, tag: []const u8) bool { + if (entry.meta) |m| { + for (m.tags) |t| { + if (std.mem.eql(u8, t, tag)) return true; + } + } + return false; } fn startStatusChecks(self: *Model) void { @@ -200,21 +251,32 @@ pub const Model = struct { // Search mode if (self.search_active) { + var changed = false; switch (k.key) { .escape => { self.search_active = false; self.search_text.clearRetainingCapacity(); + changed = true; }, .backspace => { - if (self.search_text.items.len > 0) _ = self.search_text.pop(); + if (self.search_text.items.len > 0) { + _ = self.search_text.pop(); + changed = true; + } }, .enter => self.search_active = false, .char => |c| { - if (c < 128) self.search_text.append(self.pa, @intCast(c)) catch {}; + if (c < 128) { + self.search_text.append(self.pa, @intCast(c)) catch {}; + changed = true; + } }, else => {}, } - self.selected = 0; + if (changed) { + self.selected = 0; + self.rebuildVisibleIndices(); + } return .none; } @@ -250,9 +312,10 @@ pub const Model = struct { self.screen = .add_form; }, 'e' => { - if (self.hosts.items.len > 0 and self.selected < self.hosts.items.len) { + if (self.selected < self.visible_indices.items.len) { var form = host_form.FormState.init(self.pa); - const entry = self.hosts.items[self.selected]; + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; form.editing_host = entry.config.name; // Load values form.fields[0].setValue(entry.config.name) catch {}; @@ -271,14 +334,15 @@ pub const Model = struct { } }, 'd' => { - if (self.hosts.items.len > 0) self.confirm_delete = true; + if (self.visible_indices.items.len > 0) self.confirm_delete = true; }, 'r' => self.startStatusChecks(), 's' => self.cycleSortMode(), 't' => self.cycleTagFilter(), 'f' => { - if (self.selected < self.hosts.items.len) { - const entry = self.hosts.items[self.selected]; + if (self.selected < self.visible_indices.items.len) { + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; const fwds = if (entry.meta) |m| m.port_forwards else &.{}; self.forward_state = forward_view.ForwardState.init(self.pa, entry.config.name, fwds); self.screen = .forward_select; @@ -288,7 +352,7 @@ pub const Model = struct { else => {}, }, .enter => { - if (self.hosts.items.len > 0 and self.selected < self.hosts.items.len) { + if (self.selected < self.visible_indices.items.len) { self.connectToSelected(); return .quit; } @@ -356,7 +420,7 @@ pub const Model = struct { } fn moveDown(self: *Model) void { - if (self.selected + 1 < self.hosts.items.len) self.selected += 1; + if (self.selected + 1 < self.visible_indices.items.len) self.selected += 1; } fn cycleSortMode(self: *Model) void { @@ -366,6 +430,8 @@ pub const Model = struct { .tag => .name, }; self.sortHosts(); + // hosts.items has been reordered; visible_indices points to old slots. + self.rebuildVisibleIndices(); } fn sortHosts(self: *Model) void { @@ -398,11 +464,13 @@ pub const Model = struct { if (self.tag_filter_index > self.all_tags.items.len) self.tag_filter_index = 0; self.tag_filter = if (self.tag_filter_index == 0) null else self.all_tags.items[self.tag_filter_index - 1]; self.selected = 0; + self.rebuildVisibleIndices(); } fn connectToSelected(self: *Model) void { - if (self.selected >= self.hosts.items.len) return; - const entry = self.hosts.items[self.selected]; + if (self.selected >= self.visible_indices.items.len) return; + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; // Connection metadata is recorded by `directConnect` after the TUI // exits, so don't record here as well — that double-counts. self.connect_host = self.pa.dupe(u8, entry.config.name) catch null; @@ -476,12 +544,13 @@ pub const Model = struct { } fn deleteSelectedHost(self: *Model) void { - if (self.selected >= self.hosts.items.len) return; + if (self.selected >= self.visible_indices.items.len) return; // Look up the config entry by name from the visible list so sorting // and tag-filtering don't desynchronise the display index from the // raw config order. - const selected_name = self.hosts.items[self.selected].config.name; + const hi = self.visible_indices.items[self.selected]; + const selected_name = self.hosts.items[hi].config.name; var config_index: ?usize = null; for (self.config.hosts, 0..) |h, ci| { if (std.mem.eql(u8, h.name, selected_name)) { @@ -495,8 +564,8 @@ pub const Model = struct { ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; } + // rebuildHostList → rebuildVisibleIndices clamps `selected` for us. self.rebuildHostList(); - if (self.selected > 0 and self.selected >= self.hosts.items.len) self.selected -= 1; self.notification = "Host deleted"; self.notification_timer = 30; } diff --git a/src/views/host_list.zig b/src/views/host_list.zig index 64d4337..27edfd9 100644 --- a/src/views/host_list.zig +++ b/src/views/host_list.zig @@ -39,26 +39,16 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { try lines.append(a, header); try lines.append(a, separator); - // Filtered host list - var display_idx: usize = 0; - for (model.hosts.items) |entry| { - // Search filter - if (model.search_text.items.len > 0) { - if (!matchesSearch(entry, model.search_text.items)) continue; - } - - // Tag filter - if (model.tag_filter) |tag| { - if (!hasTag(entry, tag)) continue; - } - - const is_selected = (display_idx == model.selected); + // Filtered host list (filter logic lives in app.zig now; + // model.visible_indices already reflects search + tag filters). + for (model.visible_indices.items, 0..) |hi, idx| { + const entry = model.hosts.items[hi]; + const is_selected = (idx == model.selected); const line = try renderHostLine(a, ctx.io, entry, is_selected, w); try lines.append(a, line); - display_idx += 1; } - if (display_idx == 0) { + if (model.visible_indices.items.len == 0) { const empty_style = (zz.Style{}).fg(zz.Color.gray(10)).italic(true); try lines.append(a, try empty_style.render(a, " No hosts found. Press 'a' to add one.")); } @@ -71,9 +61,10 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const prompt = try std.fmt.allocPrint(a, " /{s}_", .{model.search_text.items}); try lines.append(a, try search_style.render(a, prompt)); } else if (model.confirm_delete) { - if (model.selected < model.hosts.items.len) { + if (model.selected < model.visible_indices.items.len) { const warn_style = (zz.Style{}).fg(zz.Color.fromRgb(255, 80, 80)).bold(true); - const name = model.hosts.items[model.selected].config.name; + const hi = model.visible_indices.items[model.selected]; + const name = model.hosts.items[hi].config.name; const msg = try std.fmt.allocPrint(a, " Delete '{s}'? (y/n)", .{name}); try lines.append(a, try warn_style.render(a, msg)); } @@ -100,31 +91,6 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { return try zz.joinVertical(a, lines.items); } -fn matchesSearch(entry: App.HostEntry, search: []const u8) bool { - if (std.mem.indexOf(u8, entry.config.name, search) != null) return true; - if (entry.config.hostname) |hn| { - if (std.mem.indexOf(u8, hn, search) != null) return true; - } - if (entry.config.user) |u| { - if (std.mem.indexOf(u8, u, search) != null) return true; - } - if (entry.meta) |m| { - for (m.tags) |tag| { - if (std.mem.indexOf(u8, tag, search) != null) return true; - } - } - return false; -} - -fn hasTag(entry: App.HostEntry, tag: []const u8) bool { - if (entry.meta) |m| { - for (m.tags) |t| { - if (std.mem.eql(u8, t, tag)) return true; - } - } - return false; -} - fn renderHostLine(a: std.mem.Allocator, io: std.Io, entry: App.HostEntry, is_selected: bool, width: u16) ![]const u8 { // Status indicator const StatusInfo = struct { sym: []const u8, color: zz.Color }; From b9ba2b5dbb7783e05308b1b44db17826502cdc7a Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 7 May 2026 22:16:49 +0900 Subject: [PATCH 10/10] fix: deep-copy strings in ssh_config so addHost/removeHost don't leak MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `parse` previously returned a `Config` whose `Host` fields and `raw_lines` borrowed from the input buffer; `addHost` mixed in allocPrint'd lines, leaving `deinit` unable to tell which strings to free. The pre-existing leak forced one test to use `page_allocator` and skip `deinit` entirely. This change makes Config the sole owner of every string inside it: - `parse` deep-copies host names, host fields, and every raw line (with `errdefer` cleanup on partial OOM) - `setHostField` becomes fallible and dupes its value - `addHost` deep-copies its incoming `Host` and lines, then commits with a two-phase swap so a failed `toOwnedSlice` doesn't strand half-owned state on `config` - `removeHost` frees the dropped host's strings and the dropped `raw_lines` entries - `Config.deinit` walks hosts/lines and frees their strings via a shared `freeHostStrings` helper - `readFile` reverts to `defer free(content)` — no buffer transfer needed now that `parse` owns its copies - `Model.saveForm` no longer pre-dupes form values, since `addHost` now takes ownership; this also closes a leak when the form `name` field was empty - ssh_config tests for addHost switch to `std.testing.allocator` with `defer config.deinit(...)`, validating the ownership story with the leak detector --- src/app.zig | 14 +-- src/ssh_config.zig | 210 ++++++++++++++++++++++++++++---------- tests/test_ssh_config.zig | 15 +-- 3 files changed, 173 insertions(+), 66 deletions(-) diff --git a/src/app.zig b/src/app.zig index 10c22dd..a6f57b8 100644 --- a/src/app.zig +++ b/src/app.zig @@ -484,8 +484,10 @@ pub const Model = struct { fn saveForm(self: *Model) void { const form = &(self.form_state orelse return); - // IMPORTANT: dupe values before form deinit - const name = self.pa.dupe(u8, form.getValue(.name)) catch return; + // The form values stay valid until handleFormKey calls form.deinit + // after saveForm returns. ssh_config.addHost / meta_store.setTags + // both deep-copy what they need, so we can pass form-owned slices. + const name = form.getValue(.name); if (name.len == 0) return; const hostname_val = form.getValue(.hostname); @@ -498,11 +500,11 @@ pub const Model = struct { const new_host = ssh_config.Host{ .name = name, - .hostname = if (hostname_val.len > 0) (self.pa.dupe(u8, hostname_val) catch null) else null, - .user = if (user_val.len > 0) (self.pa.dupe(u8, user_val) catch null) else null, + .hostname = if (hostname_val.len > 0) hostname_val else null, + .user = if (user_val.len > 0) user_val else null, .port = if (port_val.len > 0) std.fmt.parseInt(u16, port_val, 10) catch null else null, - .identity_file = if (identity_val.len > 0) (self.pa.dupe(u8, identity_val) catch null) else null, - .proxy_jump = if (proxy_val.len > 0) (self.pa.dupe(u8, proxy_val) catch null) else null, + .identity_file = if (identity_val.len > 0) identity_val else null, + .proxy_jump = if (proxy_val.len > 0) proxy_val else null, .address_family = if (addr_family_val.len > 0) ssh_config.AddressFamily.fromString(addr_family_val) else null, }; diff --git a/src/ssh_config.zig b/src/ssh_config.zig index d476a02..e414937 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -39,17 +39,18 @@ pub const Host = struct { }; pub const Config = struct { + /// Each Host's string fields (`name`, `hostname`, `user`, ...) are + /// owned by `allocator`. `parse`/`addHost` allocate copies; `removeHost` + /// and `deinit` free them via `freeHostStrings`. hosts: []Host, + /// Each `raw_lines` element is owned by `allocator`. raw_lines: [][]const u8, - /// Backing storage for slices in `hosts` and `raw_lines` that originate - /// from `parse(content)`. Transferred to `Config` by `readFile` so the - /// borrowed slices stay valid for the Config's lifetime. - raw_buffer: []u8 = &[_]u8{}, pub fn deinit(self: *Config, allocator: std.mem.Allocator) void { + for (self.hosts) |h| freeHostStrings(allocator, h); allocator.free(self.hosts); + for (self.raw_lines) |line| allocator.free(line); allocator.free(self.raw_lines); - if (self.raw_buffer.len > 0) allocator.free(self.raw_buffer); } pub fn effectiveHostname(host: Host) []const u8 { @@ -80,20 +81,44 @@ fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool { return true; } +fn freeHostStrings(allocator: std.mem.Allocator, host: Host) void { + allocator.free(host.name); + if (host.hostname) |v| allocator.free(v); + if (host.user) |v| allocator.free(v); + if (host.identity_file) |v| allocator.free(v); + if (host.proxy_jump) |v| allocator.free(v); + if (host.proxy_command) |v| allocator.free(v); + if (host.local_forward) |v| allocator.free(v); + if (host.remote_forward) |v| allocator.free(v); + if (host.dynamic_forward) |v| allocator.free(v); +} + pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { var hosts: std.ArrayList(Host) = .empty; - defer hosts.deinit(allocator); + errdefer { + for (hosts.items) |h| freeHostStrings(allocator, h); + hosts.deinit(allocator); + } var lines_list: std.ArrayList([]const u8) = .empty; - defer lines_list.deinit(allocator); + errdefer { + for (lines_list.items) |line| allocator.free(line); + lines_list.deinit(allocator); + } + + var current_host: ?Host = null; + errdefer if (current_host) |h| freeHostStrings(allocator, h); var line_iter = std.mem.splitScalar(u8, content, '\n'); var line_num: usize = 0; - var current_host: ?Host = null; var in_match_block: bool = false; while (line_iter.next()) |line| { - try lines_list.append(allocator, line); + const owned_line = try allocator.dupe(u8, line); + { + errdefer allocator.free(owned_line); + try lines_list.append(allocator, owned_line); + } const trimmed = std.mem.trim(u8, line, " \t\r"); if (trimmed.len == 0 or trimmed[0] == '#') { @@ -113,9 +138,10 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { if (startsWithIgnoreCase(trimmed, "Match ") or startsWithIgnoreCase(trimmed, "Match\t")) { - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); current_host = null; } in_match_block = true; @@ -130,29 +156,34 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { if (std.ascii.eqlIgnoreCase(kv.key, "Host")) { in_match_block = false; - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); + current_host = null; } const is_wildcard = std.mem.indexOfScalar(u8, kv.value, '*') != null or std.mem.indexOfScalar(u8, kv.value, '?') != null; + const name_dup = try allocator.dupe(u8, kv.value); current_host = Host{ - .name = kv.value, + .name = name_dup, .start_line = line_num, .is_wildcard = is_wildcard, }; } else if (!in_match_block) { if (current_host) |*h| { - setHostField(h, kv.key, kv.value); + try setHostField(allocator, h, kv.key, kv.value); } } line_num += 1; } - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); + current_host = null; } return Config{ @@ -177,25 +208,43 @@ fn parseKeyValue(line: []const u8) ?KeyValue { return KeyValue{ .key = key, .value = value }; } -fn setHostField(h: *Host, key: []const u8, value: []const u8) void { +fn setHostField(allocator: std.mem.Allocator, h: *Host, key: []const u8, value: []const u8) !void { + // Pattern: dupe first, then free old (so a failed dup doesn't dangle the + // old value). Repeated keys in the same Host block are rare but legal. if (std.ascii.eqlIgnoreCase(key, "HostName")) { - h.hostname = value; + const new_val = try allocator.dupe(u8, value); + if (h.hostname) |old| allocator.free(old); + h.hostname = new_val; } else if (std.ascii.eqlIgnoreCase(key, "User")) { - h.user = value; + const new_val = try allocator.dupe(u8, value); + if (h.user) |old| allocator.free(old); + h.user = new_val; } else if (std.ascii.eqlIgnoreCase(key, "Port")) { h.port = std.fmt.parseInt(u16, value, 10) catch null; } else if (std.ascii.eqlIgnoreCase(key, "IdentityFile")) { - h.identity_file = value; + const new_val = try allocator.dupe(u8, value); + if (h.identity_file) |old| allocator.free(old); + h.identity_file = new_val; } else if (std.ascii.eqlIgnoreCase(key, "ProxyJump")) { - h.proxy_jump = value; + const new_val = try allocator.dupe(u8, value); + if (h.proxy_jump) |old| allocator.free(old); + h.proxy_jump = new_val; } else if (std.ascii.eqlIgnoreCase(key, "ProxyCommand")) { - h.proxy_command = value; + const new_val = try allocator.dupe(u8, value); + if (h.proxy_command) |old| allocator.free(old); + h.proxy_command = new_val; } else if (std.ascii.eqlIgnoreCase(key, "LocalForward")) { - h.local_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.local_forward) |old| allocator.free(old); + h.local_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "RemoteForward")) { - h.remote_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.remote_forward) |old| allocator.free(old); + h.remote_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "DynamicForward")) { - h.dynamic_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.dynamic_forward) |old| allocator.free(old); + h.dynamic_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "AddressFamily")) { h.address_family = AddressFamily.fromString(value); } @@ -213,15 +262,25 @@ pub fn serialize(allocator: std.mem.Allocator, config: *const Config) ![]const u return try result.toOwnedSlice(allocator); } +/// Append `host` to `config`. `addHost` takes ownership: it deep-copies +/// every string field of `host` and every line in `config.raw_lines`, so +/// callers may pass borrowed slices (form input, string literals) safely. pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void { + // Phase 1: build all new owned state in locals. On any failure, the + // errdefers free everything we allocated; `config` stays untouched. + var new_lines: std.ArrayList([]const u8) = .empty; - defer new_lines.deinit(allocator); - for (config.raw_lines) |l| try new_lines.append(allocator, l); - try new_lines.append(allocator, ""); + errdefer { + for (new_lines.items) |s| allocator.free(s); + new_lines.deinit(allocator); + } - // Track where the new host block starts - const host_start_line = new_lines.items.len; + for (config.raw_lines) |l| { + try new_lines.append(allocator, try allocator.dupe(u8, l)); + } + try new_lines.append(allocator, try allocator.dupe(u8, "")); + const host_start_line = new_lines.items.len; try new_lines.append(allocator, try std.fmt.allocPrint(allocator, "Host {s}", .{host.name})); if (host.hostname) |v| { try new_lines.append(allocator, try std.fmt.allocPrint(allocator, " HostName {s}", .{v})); @@ -241,21 +300,51 @@ pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void if (host.address_family) |af| { try new_lines.append(allocator, try std.fmt.allocPrint(allocator, " AddressFamily {s}", .{af.toString()})); } - const host_end_line = new_lines.items.len; - allocator.free(config.raw_lines); - config.raw_lines = try new_lines.toOwnedSlice(allocator); + var new_host: Host = .{ + .name = try allocator.dupe(u8, host.name), + .start_line = host_start_line, + .end_line = host_end_line, + .is_wildcard = host.is_wildcard, + .port = host.port, + .address_family = host.address_family, + }; + errdefer freeHostStrings(allocator, new_host); + + if (host.hostname) |v| new_host.hostname = try allocator.dupe(u8, v); + if (host.user) |v| new_host.user = try allocator.dupe(u8, v); + if (host.identity_file) |v| new_host.identity_file = try allocator.dupe(u8, v); + if (host.proxy_jump) |v| new_host.proxy_jump = try allocator.dupe(u8, v); + if (host.proxy_command) |v| new_host.proxy_command = try allocator.dupe(u8, v); + if (host.local_forward) |v| new_host.local_forward = try allocator.dupe(u8, v); + if (host.remote_forward) |v| new_host.remote_forward = try allocator.dupe(u8, v); + if (host.dynamic_forward) |v| new_host.dynamic_forward = try allocator.dupe(u8, v); var new_hosts: std.ArrayList(Host) = .empty; - defer new_hosts.deinit(allocator); + errdefer new_hosts.deinit(allocator); for (config.hosts) |h| try new_hosts.append(allocator, h); - var new_host = host; - new_host.start_line = host_start_line; - new_host.end_line = host_end_line; try new_hosts.append(allocator, new_host); + + // Phase 2: commit. Past `toOwnedSlice` only no-fail operations remain. + const new_lines_slice = try new_lines.toOwnedSlice(allocator); + const new_hosts_slice = new_hosts.toOwnedSlice(allocator) catch |err| { + // Couldn't commit hosts — release the lines we just took ownership of + // (they reference the allocator-owned strings we duped above). + for (new_lines_slice) |s| allocator.free(s); + allocator.free(new_lines_slice); + return err; + }; + + // Free old raw_lines content (each element was allocator-owned) and array. + for (config.raw_lines) |l| allocator.free(l); + allocator.free(config.raw_lines); + config.raw_lines = new_lines_slice; + + // Old `config.hosts` array is replaced; the host structs inside still + // reference their own owned strings, which transfer through `new_hosts`. allocator.free(config.hosts); - config.hosts = try new_hosts.toOwnedSlice(allocator); + config.hosts = new_hosts_slice; } pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) !void { @@ -264,19 +353,18 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! const host = config.hosts[index]; const start = host.start_line; const end = @min(host.end_line, config.raw_lines.len); + const removed_count = end - start; + // Phase 1: build new arrays without committing. var new_lines: std.ArrayList([]const u8) = .empty; - defer new_lines.deinit(allocator); + errdefer new_lines.deinit(allocator); for (config.raw_lines, 0..) |line, i| { if (i >= start and i < end) continue; try new_lines.append(allocator, line); } - allocator.free(config.raw_lines); - config.raw_lines = try new_lines.toOwnedSlice(allocator); - const removed_count = end - start; var new_hosts: std.ArrayList(Host) = .empty; - defer new_hosts.deinit(allocator); + errdefer new_hosts.deinit(allocator); for (config.hosts, 0..) |h, i| { if (i == index) continue; var adjusted = h; @@ -286,19 +374,33 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! } try new_hosts.append(allocator, adjusted); } + + // Phase 2: commit. Take ownership of the new slices, then free the + // strings that are no longer referenced. + const new_lines_slice = try new_lines.toOwnedSlice(allocator); + const new_hosts_slice = new_hosts.toOwnedSlice(allocator) catch |err| { + allocator.free(new_lines_slice); + return err; + }; + + // Free strings of the lines being dropped, then the old array. + for (config.raw_lines[start..end]) |line| allocator.free(line); + allocator.free(config.raw_lines); + config.raw_lines = new_lines_slice; + + // Free the removed host's owned string fields, then the old array. + freeHostStrings(allocator, host); allocator.free(config.hosts); - config.hosts = try new_hosts.toOwnedSlice(allocator); + config.hosts = new_hosts_slice; } pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Config { const cwd = std.Io.Dir.cwd(); const content = try cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)); - errdefer allocator.free(content); - var config = try parse(allocator, content); - // Transfer ownership: hosts/raw_lines borrow from `content`, so the - // Config must keep the buffer alive until deinit. - config.raw_buffer = content; - return config; + defer allocator.free(content); + // `parse` deep-copies all strings out of `content`, so it's safe to free + // the buffer here. + return parse(allocator, content); } pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config, path: []const u8, backup_dir: []const u8) !void { diff --git a/tests/test_ssh_config.zig b/tests/test_ssh_config.zig index 996f1f3..6609daa 100644 --- a/tests/test_ssh_config.zig +++ b/tests/test_ssh_config.zig @@ -162,15 +162,13 @@ test "remove all hosts" { } test "add then remove host" { - // Use page_allocator because addHost allocPrints new lines - // that aren't tracked for individual deallocation (by design— - // parsed lines are slices into original content, added lines are owned). - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); // Add a new host try ssh_config.addHost(allocator, &config, .{ @@ -188,6 +186,7 @@ test "add then remove host" { // Serialize const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, "newhost") != null); try std.testing.expect(std.mem.indexOf(u8, output, "existing") == null); } @@ -258,12 +257,13 @@ test "parse invalid AddressFamily yields null" { } test "addHost with AddressFamily serializes correctly" { - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); try ssh_config.addHost(allocator, &config, .{ .name = "v6host", @@ -274,16 +274,18 @@ test "addHost with AddressFamily serializes correctly" { try std.testing.expectEqual(@as(usize, 2), config.hosts.len); const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, " AddressFamily inet6") != null); } test "addHost without AddressFamily omits directive" { - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); try ssh_config.addHost(allocator, &config, .{ .name = "v4host", @@ -291,6 +293,7 @@ test "addHost without AddressFamily omits directive" { }); const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, "AddressFamily") == null); }