Something went wrong. Try again.
Charm-like tui library
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106//! Interactive demo of the `leaves.Tree` component: a collapsible file-tree//! style view. Navigate with `↓`/`j` and `↑`/`k`, expand/collapse the current//! node with `⏎`, jump to top/bottom with `g`/`G`, and open the full help with//! `?`. Quit with `q` or `Ctrl+C`.const std = @import("std");const tea = @import("blacktea");const buds = @import("buds");
const Writer = std.Io.Writer;const key = buds.key;const Allocator = std.mem.Allocator;const Init = std.process.Init;const Tree = buds.Tree;
const KeyMap = struct { quit: key.Binding = .new(&.{ .q, .ctrl(.c) }, "quit", .{}),};
const State = struct { model: tea.Model = .{ .vtable = &.{ .init = init, .update = update, .view = view, } }, tree: Tree = .{}, quitting: bool = false, help: buds.Help = .{}, keymap: KeyMap = .{},
fn init(m: *tea.Model) ?tea.Cmd { const state: *State = @fieldParentPtr("model", m); state.tree.gpa = m.gpa; state.tree.setRoot((buildProject(m.gpa) catch @panic("OOM"))); return null; }
fn buildProject(gpa: Allocator) !*Tree.Node { const root: *Tree.Node = try .new(gpa, "charm"); root.setOpen(true);
const src: *Tree.Node = try .new(gpa, "src"); src.setOpen(true); try src.child(gpa, "main.zig"); const ui: *Tree.Node = try .new(gpa, "ui"); ui.setOpen(true); try ui.child(gpa, "theme.zig"); try ui.child(gpa, "spinner.zig"); try src.childNode(gpa, ui); try root.childNode(gpa, src);
try root.child(gpa, "build.zig"); try root.child(gpa, "build.zig.zon");
const examples: *Tree.Node = try .new(gpa, "examples"); examples.setOpen(false); try examples.child(gpa, "basic.zig"); try examples.child(gpa, "styled.zig"); try root.childNode(gpa, examples);
try root.child(gpa, "README.md"); return root; }
fn update(m: *tea.Model, msg: tea.Msg) ?tea.Cmd { const state: *State = @fieldParentPtr("model", m); switch (msg) { .key_press => |k| if (state.keymap.quit.matches(k)) { state.quitting = true; return .quit; }, .window_size => |ws| { state.tree.setSize(ws.width, ws.height); return null; }, .interrupt => return .quit, else => {}, } return state.tree.update(msg); }
fn view(m: *tea.Model, writer: *Writer) !tea.View { const state: *State = @fieldParentPtr("model", m); if (state.quitting) { try writer.writeAll("\n bye!\n\n"); return .{}; } try state.tree.view(writer); try writer.writeAll("\n\n"); const bindings = [_]key.Binding{ state.keymap.quit, }; try state.help.shortView(writer, &bindings); return .{ .alt_screen = true }; }};
pub fn tree(init: Init) !void { var state: State = .{}; state.tree.gpa = init.gpa; defer state.tree.deinit();
var program: tea.Program = try .init(init, &state.model, .{}); defer program.deinit(); try program.run();}