//! 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(); }