╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const term = xitui.terminal; 6 const wgt = xitui.widget; 7 const layout = xitui.layout; 8 const inp = xitui.input; 9 const Grid = xitui.grid.Grid; 10 const Focus = xitui.focus.Focus; 11 const evt = @import("./event.zig"); 12 13 pub const Home = @import("./ui/Home.zig"); 14 pub const User = @import("./ui/User.zig"); 15 pub const Title = @import("./ui/Title.zig"); 16 17 pub const PageKind = enum { 18 home, 19 user, 20 }; 21 22 pub const Page = union(PageKind) { 23 home: Home, 24 user: User, 25 26 pub fn init(arena: *std.heap.ArenaAllocator, haxy_moment: evt.AdminDB.HashMap(.read_only), route: RoutablePage) !Page { 27 return switch (route.parent()) { 28 .home => .{ .home = try Home.init(arena, haxy_moment) }, 29 .user => switch (route) { 30 .user, .user_settings, .user_auth => |name| .{ .user = try User.init(arena, haxy_moment, name) }, 31 else => return error.UnexpectedRoute, 32 }, 33 }; 34 } 35 }; 36 37 // what the server hands to the client (and what main_wasm parses on _start). 38 // keeps Page free of any per-request session state. 39 pub const Snapshot = struct { 40 page: Page, 41 session: Session.Data = .{}, 42 }; 43 44 // a top-level "page" the user can navigate to. the user_* variants are the 45 // tabs of a user page; they each carry the user's name and all map to the 46 // .user parent page, so switching between them stays on that page (and just 47 // updates the url) rather than navigating away. 48 pub const RoutablePage = union(enum) { 49 home_users, 50 home_repos, 51 home_settings, 52 home_auth, 53 user: Array(evt.User.name_max_len), 54 user_settings: Array(evt.User.name_max_len), 55 user_auth: Array(evt.User.name_max_len), 56 57 pub const default: RoutablePage = .home_users; 58 59 const user_segment = "/user/"; 60 61 // an inline, owned array of data. keeping it in the route (rather than a 62 // borrowed slice) makes RoutablePage a plain value: it can be copied, stored 63 // in history, and serialized without any arena tracking. 64 pub fn Array(comptime max_len: usize) type { 65 return struct { 66 bytes: [max_len]u8 = undefined, 67 len: u8 = 0, 68 69 pub fn from(s: []const u8) ?Array(max_len) { 70 if (s.len > max_len) return null; 71 var name = Array(max_len){ .len = @intCast(s.len) }; 72 @memcpy(name.bytes[0..s.len], s); 73 return name; 74 } 75 76 pub fn slice(self: *const Array(max_len)) []const u8 { 77 return self.bytes[0..self.len]; 78 } 79 }; 80 } 81 82 pub fn url(comptime self: RoutablePage) []const u8 { 83 return switch (self) { 84 .home_users => "/users", 85 .home_repos => "/repos", 86 .home_settings => "/settings", 87 .home_auth => "/auth", 88 // user routes carry a runtime name; build them with urlAlloc. 89 .user, .user_settings, .user_auth => @compileError("user routes are dynamic; use urlAlloc"), 90 }; 91 } 92 93 pub fn urlAlloc(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 94 return switch (self) { 95 .user => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}", .{name.slice()}), 96 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name.slice()}), 97 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name.slice()}), 98 inline else => |_, tag| url(tag), 99 }; 100 } 101 102 pub fn parent(self: RoutablePage) PageKind { 103 return switch (self) { 104 .home_users, .home_repos, .home_settings, .home_auth => .home, 105 .user, .user_settings, .user_auth => .user, 106 }; 107 } 108 109 pub fn fromUrl(path: []const u8) ?RoutablePage { 110 if (std.mem.eql(u8, path, "/")) return default; 111 if (std.mem.eql(u8, path, "/users")) return .home_users; 112 if (std.mem.eql(u8, path, "/repos")) return .home_repos; 113 if (std.mem.eql(u8, path, "/settings")) return .home_settings; 114 if (std.mem.eql(u8, path, "/auth")) return .home_auth; 115 if (std.mem.startsWith(u8, path, user_segment)) { 116 const rest = path[user_segment.len..]; 117 const slash = std.mem.indexOfScalar(u8, rest, '/'); 118 const name = if (slash) |s| rest[0..s] else rest; 119 if (name.len == 0) return null; 120 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 121 if (slash) |s| { 122 const sub = rest[s + 1 ..]; 123 if (std.mem.eql(u8, sub, "settings")) return .{ .user_settings = parsed }; 124 if (std.mem.eql(u8, sub, "auth")) return .{ .user_auth = parsed }; 125 return null; // unknown user sub-path 126 } 127 return .{ .user = parsed }; 128 } 129 return null; 130 } 131 132 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 133 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 134 return switch (a) { 135 .user => |a_name| std.mem.eql(u8, a_name.slice(), b.user.slice()), 136 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 137 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 138 else => true, 139 }; 140 } 141 142 // serialize as { "kind": <tag>, "name"?: <user name> }. the default 143 // union(enum) codec doesn't round-trip here: Stringify emits a void 144 // variant as a bare tag string, but the parser expects an object — so the 145 // server->wasm Snapshot JSON would fail to parse. 146 pub fn jsonStringify(self: RoutablePage, jw: anytype) !void { 147 try jw.beginObject(); 148 try jw.objectField("kind"); 149 try jw.write(@tagName(self)); 150 switch (self) { 151 .user, .user_settings, .user_auth => |name| { 152 try jw.objectField("name"); 153 try jw.write(name.slice()); 154 }, 155 else => {}, 156 } 157 try jw.endObject(); 158 } 159 160 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !RoutablePage { 161 const Helper = struct { kind: std.meta.Tag(RoutablePage), name: ?[]const u8 = null }; 162 const helper = try std.json.innerParse(Helper, allocator, source, options); 163 const parseName = struct { 164 // errors must stay within std.json's ParseError set; ValueTooLong 165 // is its member for an over-long field. 166 fn f(maybe: ?[]const u8) !Array(evt.User.name_max_len) { 167 return Array(evt.User.name_max_len).from(maybe orelse return error.MissingField) orelse error.ValueTooLong; 168 } 169 }.f; 170 return switch (helper.kind) { 171 .home_users => .home_users, 172 .home_repos => .home_repos, 173 .home_settings => .home_settings, 174 .home_auth => .home_auth, 175 .user => .{ .user = try parseName(helper.name) }, 176 .user_settings => .{ .user_settings = try parseName(helper.name) }, 177 .user_auth => .{ .user_auth = try parseName(helper.name) }, 178 }; 179 } 180 }; 181 182 // per-connection mutable state. each SSH session / web session / local TUI 183 // run gets its own. 184 pub const Session = struct { 185 data: Data = .{}, 186 // session-lifetime allocations: login/user_id, persisted prefs, queued 187 // actions. lives as long as the connection. 188 arena: *std.heap.ArenaAllocator, 189 // current page's allocations: page data and the page-scoped strings widgets 190 // build (form actions, links). owned by Nav, swapped on each navigation, so 191 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 192 // where a render is one-shot, this points at the same arena as `arena`. 193 page_arena: *std.heap.ArenaAllocator, 194 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 195 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 196 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 197 198 const Self = @This(); 199 200 // serializable data sent down to web client 201 pub const Data = struct { 202 user_id: ?[]const u8 = null, 203 // a transient outcome to surface from the last /login POST attempt 204 login_failure: ?Home.Auth.Login.Failure = null, 205 current_page: RoutablePage = .default, 206 // whether to render the ANSI art backdrop 207 enable_ansi: bool = false, 208 }; 209 210 // a user-initiated state change. widgets enqueue these on the session during 211 // input instead of mutating state or touching the DB themselves; the host 212 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 213 // side effects out of the widget tree and gives every render path one place to 214 // turn a UI action into a state change + event. 215 pub const Action = union(enum) { 216 toggle_ansi, 217 }; 218 219 pub fn init( 220 arena: *std.heap.ArenaAllocator, 221 repo: *rp.Repo(.xit, evt.admin_repo_opts), 222 data: Data, 223 ) !Self { 224 var session = Self{ 225 .data = data, 226 .arena = arena, 227 // until a host swaps in a page-scoped arena (Nav does this), page 228 // allocations land in the session arena. on the web path that's the 229 // intended behavior, since the whole arena is per-request. 230 .page_arena = arena, 231 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 232 }; 233 try session.loadUserPrefs(); 234 return session; 235 } 236 237 // load the logged-in user's persisted preferences from the db 238 pub fn loadUserPrefs(self: *Self) !void { 239 const user_id = self.data.user_id orelse return; 240 const moment = self.haxy_moment orelse return; 241 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 242 self.data.enable_ansi = user.enable_ansi; 243 } 244 } 245 246 // queue an action for the host to drain this frame. 247 pub fn push(self: *Self, action: Action) !void { 248 try self.pending.append(self.arena.allocator(), action); 249 } 250 251 // apply a single action's in-memory effect only (no persistence). 252 fn apply(self: *Self, action: Action) void { 253 switch (action) { 254 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 255 } 256 } 257 258 // drain the session's queued actions by applying them to the session. 259 // used on the wasm path, which has no repo to persist to. 260 pub fn applyPending(self: *Self) void { 261 for (self.pending.items) |action| self.apply(action); 262 self.pending.clearRetainingCapacity(); 263 } 264 265 // drain the session's queued actions by applying them to the session and 266 // writing them to the db 267 pub fn applyAndWritePending( 268 self: *Self, 269 io: std.Io, 270 allocator: std.mem.Allocator, 271 repo: *rp.Repo(.xit, evt.admin_repo_opts), 272 ) !void { 273 defer self.pending.clearRetainingCapacity(); 274 for (self.pending.items) |action| { 275 self.apply(action); 276 switch (action) { 277 .toggle_ansi => if (self.data.user_id) |user_id| { 278 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 279 }, 280 } 281 } 282 } 283 284 // record the requested page. `route` may borrow a name slice from the 285 // current page's widget tree, which stays alive until Nav.sync runs (this 286 // frame); sync re-anchors the name into the new page's arena. 287 fn navigate(self: *Session, route: RoutablePage) !void { 288 self.data.current_page = route; 289 } 290 }; 291 292 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session) !void { 293 var nav = try Nav.init(allocator, session); 294 defer nav.deinit(allocator); 295 296 var terminal = try term.Terminal.init(io, allocator); 297 defer terminal.deinit(io); 298 299 var last_size = layout.Size{ .width = 0, .height = 0 }; 300 var last_grid = try Grid.init(allocator, last_size); 301 defer last_grid.deinit(); 302 303 while (!terminal.shouldQuit()) { 304 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 305 306 // process any inputs. 307 // 308 // if the grid didn't change, then first do a blocking 309 // read, so the thread will sleep until further input. 310 // after that, all remaining reads are non-blocking so 311 // we can process the rest of the queued inputs. 312 // 313 // if the grid *did* change, then only do non-blocking 314 // reads. we do not want to sleep the thread because 315 // there may be an animation that requires more looping. 316 var blocking = !grid_changed; 317 while (try terminal.readKey(io, blocking)) |key| { 318 try inputKey(allocator, &nav.root, key, session); 319 blocking = false; 320 } 321 322 // local run has no repo to persist to, so just apply in-memory 323 session.applyPending(); 324 325 // reconcile navigation: forward to a new page, or back on escape (and 326 // quit when there's nothing left to go back to). 327 if (!try nav.sync(allocator, session)) terminal.requestQuit(); 328 329 try nav.root.build(allocator, .{ 330 .min_size = .{ .width = null, .height = null }, 331 .max_size = .{ .width = last_size.width, .height = last_size.height }, 332 }, nav.root.getFocus()); 333 } 334 } 335 336 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: inp.Key, session: *Session) !void { 337 switch (key) { 338 // request a navigation pop; the host's Nav.sync goes back a page, or 339 // quits when there's no history left. 340 .escape => session.nav_back = true, 341 .enter => { 342 const root_focus = root.getFocus(); 343 if (root_focus.grandchild_id) |gid| { 344 // follow a cross-page link 345 if (crossPageLink(root_focus, gid, session.data.current_page)) |route| { 346 return session.navigate(route); 347 } 348 } 349 try root.input(allocator, key, root_focus); 350 }, 351 .mouse => |mouse| { 352 if (mouse.action == .press and mouse.action.press == .left) { 353 const root_focus = root.getFocus(); 354 var clicked: ?usize = null; 355 var iter = root_focus.children.iterator(); 356 while (iter.next()) |entry| { 357 const child = entry.value_ptr.*; 358 if (!child.focus.focusable) continue; 359 const r = child.rect; 360 if (mouse.x >= r.x and mouse.y >= r.y and 361 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 362 { 363 clicked = entry.key_ptr.*; 364 break; 365 } 366 } 367 if (clicked) |focus_id| { 368 // follow a cross-page link 369 if (crossPageLink(root_focus, focus_id, session.data.current_page)) |route| { 370 return session.navigate(route); 371 } 372 try root_focus.setFocus(focus_id); 373 } 374 // forward the press into the widget tree so buttons (and any 375 // future click-aware widgets) can react. widgets that don't 376 // care about presses ignore it. 377 try root.input(allocator, key, root.getFocus()); 378 } else { 379 try root.input(allocator, key, root.getFocus()); 380 } 381 }, 382 else => try root.input(allocator, key, root.getFocus()), 383 } 384 } 385 386 // if the focus target at focus_id is an `a:` link to a different top-level page 387 // than `current`, return its route; otherwise null. lets a host turn a click / 388 // enter on such a link into a navigation rather than a focus change. 389 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, current: RoutablePage) ?RoutablePage { 390 const child = root_focus.children.get(focus_id) orelse return null; 391 const custom = switch (child.focus.kind) { 392 .custom => |c| c, 393 else => return null, 394 }; 395 const a_prefix = "a:"; 396 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 397 const route = RoutablePage.fromUrl(custom[a_prefix.len..]) orelse return null; 398 if (route.parent() == current.parent()) return null; 399 return route; 400 } 401 402 // native-TUI navigation 403 pub const Nav = struct { 404 root: Widget, 405 route: RoutablePage, 406 // backs the current page (its Page data and the page-scoped strings its 407 // widgets build). owned here, swapped on each navigation. session.page_arena 408 // tracks whichever of these is current so widgets allocate into it. 409 arena: *std.heap.ArenaAllocator, 410 history: std.ArrayList(Entry), 411 412 // each retained page keeps its own arena, freed when the page leaves the 413 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 414 // long-lived session from accumulating every page it ever visited. 415 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 416 417 // cap on retained back-history so the chain can't grow memory without bound 418 const max_history: usize = 16; 419 420 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 421 const moment = session.haxy_moment orelse unreachable; 422 const arena = try allocator.create(std.heap.ArenaAllocator); 423 arena.* = std.heap.ArenaAllocator.init(allocator); 424 errdefer { 425 arena.deinit(); 426 allocator.destroy(arena); 427 } 428 429 session.page_arena = arena; 430 const route = session.data.current_page; 431 432 const page = try arena.allocator().create(Page); 433 page.* = try Page.init(arena, moment, route); 434 return .{ 435 .root = try initRoot(allocator, page, session), 436 .route = route, 437 .arena = arena, 438 .history = .empty, 439 }; 440 } 441 442 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 443 self.root.deinit(allocator); 444 freeArena(allocator, self.arena); 445 for (self.history.items) |*entry| { 446 entry.root.deinit(allocator); 447 freeArena(allocator, entry.arena); 448 } 449 self.history.deinit(allocator); 450 } 451 452 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 453 arena.deinit(); 454 allocator.destroy(arena); 455 } 456 457 // reconcile the displayed root with the session's navigation state. returns 458 // false when escape was pressed with no history left, so the caller can quit. 459 // a forward nav (current_page moved to a different parent page) pushes the 460 // current root and builds the new page in a fresh arena; a back request frees 461 // the current page and restores the previous one. 462 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 463 if (session.nav_back) { 464 session.nav_back = false; 465 const entry = self.history.pop() orelse return false; 466 self.root.deinit(allocator); 467 freeArena(allocator, self.arena); 468 self.root = entry.root; 469 self.route = entry.route; 470 self.arena = entry.arena; 471 session.page_arena = entry.arena; 472 session.data.current_page = entry.route; 473 return true; 474 } 475 476 if (session.data.current_page.parent() != self.route.parent()) { 477 const moment = session.haxy_moment orelse return true; 478 const arena = try allocator.create(std.heap.ArenaAllocator); 479 arena.* = std.heap.ArenaAllocator.init(allocator); 480 errdefer freeArena(allocator, arena); 481 482 session.page_arena = arena; 483 const route = session.data.current_page; 484 485 const page = try arena.allocator().create(Page); 486 page.* = try Page.init(arena, moment, route); 487 const new_root = try initRoot(allocator, page, session); 488 489 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 490 // drop the oldest entry (freeing its widget tree and arena) once over cap 491 if (self.history.items.len > max_history) { 492 var oldest = self.history.orderedRemove(0); 493 oldest.root.deinit(allocator); 494 freeArena(allocator, oldest.arena); 495 } 496 self.root = new_root; 497 self.route = route; 498 self.arena = arena; 499 } 500 return true; 501 } 502 }; 503 504 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 505 const page_widget: Widget = switch (page.*) { 506 .home => |*p| .{ .home = try .init(allocator, p, session) }, 507 .user => |*p| .{ .user = try .init(allocator, p, session) }, 508 }; 509 510 const demon_art = @embedFile("embed/demon.ans"); 511 512 var root = Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 513 errdefer root.deinit(allocator); 514 515 try root.build(allocator, .{ 516 .min_size = .{ .width = null, .height = 40 }, 517 .max_size = .{ .width = 80, .height = null }, 518 }, root.getFocus()); 519 if (root.getFocus().child_id) |child_id| { 520 try root.getFocus().setFocus(child_id); 521 } 522 523 return root; 524 } 525 526 pub const Widget = union(enum) { 527 text: wgt.Text(Widget), 528 box: wgt.Box(Widget), 529 text_box: wgt.TextBox(Widget), 530 text_input: wgt.TextInput(Widget), 531 scroll: wgt.Scroll(Widget), 532 stack: wgt.Stack(Widget), 533 flow_box: FlowBox, 534 flow_box_scroll: FlowBox.Scroll, 535 spacer: Spacer, 536 center: Center, 537 ansi_art: AnsiArt, 538 background: AnsiBackground, 539 home: Home.View, 540 user: User.View, 541 title: Title.View, 542 home_header: Home.Header.View, 543 user_header: User.Header.View, 544 home_users: Home.Users.View, 545 home_repos: Home.Repos.View, 546 auth_tab: Home.Header.AuthTab.View, 547 home_settings: Home.Settings.View, 548 home_auth: Home.Auth.View, 549 550 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 551 switch (self.*) { 552 inline else => |*case| case.deinit(allocator), 553 } 554 } 555 556 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 557 switch (self.*) { 558 inline else => |*case| try case.build(allocator, constraint, root_focus), 559 } 560 } 561 562 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 563 switch (self.*) { 564 inline else => |*case| try case.input(allocator, key, root_focus), 565 } 566 } 567 568 pub fn clearGrid(self: *Widget) void { 569 switch (self.*) { 570 inline else => |*case| case.clearGrid(), 571 } 572 } 573 574 pub fn getGrid(self: Widget) ?Grid { 575 switch (self) { 576 inline else => |*case| return case.getGrid(), 577 } 578 } 579 580 pub fn getFocus(self: *Widget) *Focus { 581 switch (self.*) { 582 inline else => |*case| return case.getFocus(), 583 } 584 } 585 }; 586 587 pub const FlowBox = struct { 588 focus: Focus, 589 grid: ?Grid, 590 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 591 // backs the per-item strings the text boxes borrow: each box's `content` 592 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 593 // wholesale on each setItems so there's no per-string ownership to track. 594 arena: std.heap.ArenaAllocator, 595 // column count from the last build — FlowBox.Scroll.input uses it so arrow 596 // up/down can step by a row's worth of items. 597 last_cols: usize, 598 options: Options, 599 600 const border_rows: usize = 2; 601 602 pub const Options = struct { 603 cell_width: usize = 40, 604 cell_height: usize = 3, 605 }; 606 607 pub fn init(allocator: std.mem.Allocator, options: Options) FlowBox { 608 return .{ 609 .focus = Focus.init(.container), 610 .grid = null, 611 .text_boxes = .empty, 612 .arena = std.heap.ArenaAllocator.init(allocator), 613 .last_cols = 1, 614 .options = options, 615 }; 616 } 617 618 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 619 self.focus.deinit(allocator); 620 if (self.grid) |*grid| { 621 grid.deinit(); 622 self.grid = null; 623 } 624 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 625 self.text_boxes.deinit(allocator); 626 self.arena.deinit(); 627 } 628 629 // `links`, when given, is parallel to `items`: a non-empty entry sets that 630 // item's focus kind to `.{ .custom = link }` (e.g. "a:/user/foo"), which the 631 // web renderer turns into an anchor. pass null when items aren't links. 632 // both the item text and the link are copied into the arena, so the caller's 633 // slices needn't outlive this call. 634 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 635 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 636 self.text_boxes.clearAndFree(allocator); 637 638 // the old text boxes (and their borrowed content/links) are gone now, so 639 // the arena that backed those strings can be reclaimed. 640 _ = self.arena.reset(.retain_capacity); 641 const aa = self.arena.allocator(); 642 643 self.focus.clear(); 644 self.focus.child_id = null; 645 646 for (items, 0..) |item, i| { 647 const line = try aa.dupe(u8, item); 648 649 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 650 errdefer text_box.deinit(allocator); 651 text_box.getFocus().focusable = true; 652 653 if (links) |link_items| { 654 if (i < link_items.len and link_items[i].len > 0) { 655 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, link_items[i]) }; 656 } 657 } 658 659 try self.text_boxes.append(allocator, text_box); 660 } 661 662 if (self.text_boxes.items.len > 0) { 663 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 664 } 665 } 666 667 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 668 self.clearGrid(); 669 self.focus.clear(); 670 671 const cell_width = self.options.cell_width; 672 const max_width = constraint.max_size.width orelse cell_width; 673 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 674 self.last_cols = cols; 675 676 const count = self.text_boxes.items.len; 677 if (count == 0) return; 678 const slot_height = self.options.cell_height + border_rows; 679 if (slot_height == 0) return; 680 681 // build at the slot size so every text box fits a single grid cell 682 for (self.text_boxes.items) |*tb| { 683 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 684 try tb.build(allocator, .{ 685 .min_size = .{ .width = cell_width, .height = null }, 686 .max_size = .{ .width = cell_width, .height = slot_height }, 687 }, root_focus); 688 } 689 690 const rows = (count + cols - 1) / cols; 691 const content_height = rows * slot_height; 692 const total_width = cols * cell_width; 693 if (total_width == 0 or content_height == 0) return; 694 695 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 696 errdefer grid.deinit(); 697 698 for (self.text_boxes.items, 0..) |*tb, i| { 699 const tb_grid = tb.getGrid() orelse continue; 700 const col = i % cols; 701 const row = i / cols; 702 const cell_x = col * cell_width; 703 const cell_y = row * slot_height; 704 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 705 try grid.drawGrid(tb_grid, cell_x, cell_y); 706 } 707 708 self.grid = grid; 709 } 710 711 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 712 _ = self; 713 _ = allocator; 714 _ = key; 715 _ = root_focus; 716 } 717 718 pub fn clearGrid(self: *FlowBox) void { 719 if (self.grid) |*grid| { 720 grid.deinit(); 721 self.grid = null; 722 } 723 for (self.text_boxes.items) |*tb| tb.clearGrid(); 724 } 725 726 pub fn getGrid(self: FlowBox) ?Grid { 727 return self.grid; 728 } 729 730 pub fn getFocus(self: *FlowBox) *Focus { 731 return &self.focus; 732 } 733 734 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 735 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 736 const slot_height = self.options.cell_height + border_rows; 737 const col = index % self.last_cols; 738 const row = index / self.last_cols; 739 return .{ 740 .x = @intCast(col * self.options.cell_width), 741 .y = @intCast(row * slot_height), 742 .size = .{ .width = self.options.cell_width, .height = slot_height }, 743 }; 744 } 745 746 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 747 for (self.text_boxes.items, 0..) |tb, i| { 748 if (tb.box.focus.id == focus_id) return i; 749 } 750 return null; 751 } 752 753 pub const Scroll = struct { 754 scroll: wgt.Scroll(Widget), 755 756 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options) !Scroll { 757 var layout_inner = FlowBox.init(allocator, options); 758 errdefer layout_inner.deinit(allocator); 759 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .vert); 760 errdefer scroll.deinit(allocator); 761 return .{ .scroll = scroll }; 762 } 763 764 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 765 self.scroll.deinit(allocator); 766 } 767 768 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 769 self.scroll.x = 0; 770 self.scroll.y = 0; 771 try self.inner().setItems(allocator, items, links); 772 } 773 774 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 775 try self.scroll.build(allocator, constraint, root_focus); 776 } 777 778 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 779 _ = allocator; 780 const in = self.inner(); 781 const child_id = in.focus.child_id orelse return; 782 const current_index = in.indexOfFocusId(child_id) orelse return; 783 const count = in.text_boxes.items.len; 784 if (count == 0) return; 785 const cols = in.last_cols; 786 const slot_height = in.options.cell_height + FlowBox.border_rows; 787 788 var index = current_index; 789 switch (key) { 790 .arrow_up => index -|= cols, 791 .arrow_down => if (index + cols < count) { 792 index += cols; 793 }, 794 .arrow_left => index -|= 1, 795 .arrow_right => if (index + 1 < count) { 796 index += 1; 797 }, 798 .home => index = 0, 799 .end => index = count - 1, 800 .page_up => { 801 if (self.scroll.grid) |grid| if (slot_height > 0) { 802 const rows_per_page = grid.size.height / slot_height; 803 index -|= rows_per_page * cols; 804 }; 805 }, 806 .page_down => { 807 if (self.scroll.grid) |grid| if (slot_height > 0) { 808 const rows_per_page = grid.size.height / slot_height; 809 index = @min(index + rows_per_page * cols, count - 1); 810 }; 811 }, 812 // scroll wheel moves the focused cell by a full row so the 813 // viewport (via scrollToRect) follows in row-sized steps, 814 // matching how a scroll wheel feels in a grid view. 815 .mouse => |mouse| switch (mouse.action) { 816 .scroll => |dir| switch (dir) { 817 .up => index -|= cols, 818 .down => if (index + cols < count) { 819 index += cols; 820 }, 821 }, 822 else => {}, 823 }, 824 else => {}, 825 } 826 827 if (index != current_index) { 828 try root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 829 if (in.cellRect(index)) |rect| { 830 self.scroll.scrollToRect(rect); 831 } 832 } 833 } 834 835 pub fn clearGrid(self: *Scroll) void { 836 self.scroll.clearGrid(); 837 } 838 839 pub fn getGrid(self: Scroll) ?Grid { 840 return self.scroll.getGrid(); 841 } 842 843 pub fn getFocus(self: *Scroll) *Focus { 844 return self.scroll.getFocus(); 845 } 846 847 pub fn getSelectedIndex(self: Scroll) ?usize { 848 const in = self.scroll.child.flow_box; 849 const child_id = in.focus.child_id orelse return null; 850 return in.indexOfFocusId(child_id); 851 } 852 853 fn inner(self: *Scroll) *FlowBox { 854 return &self.scroll.child.flow_box; 855 } 856 }; 857 }; 858 859 // an invisible widget that fills the horizontal space granted by its parent. 860 // used inside Box(horiz) with a min_size so the box reserves space for the 861 // children that follow, pushing them to the right. 862 pub const Spacer = struct { 863 focus: Focus, 864 grid: ?Grid, 865 866 pub fn init() Spacer { 867 return .{ 868 .focus = Focus.init(.container), 869 .grid = null, 870 }; 871 } 872 873 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 874 self.focus.deinit(allocator); 875 if (self.grid) |*grid| { 876 grid.deinit(); 877 self.grid = null; 878 } 879 } 880 881 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 882 _ = root_focus; 883 self.clearGrid(); 884 const width = constraint.max_size.width orelse return; 885 if (width == 0) return; 886 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 887 } 888 889 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 890 _ = self; 891 _ = allocator; 892 _ = key; 893 _ = root_focus; 894 } 895 896 pub fn clearGrid(self: *Spacer) void { 897 if (self.grid) |*grid| { 898 grid.deinit(); 899 self.grid = null; 900 } 901 } 902 903 pub fn getGrid(self: Spacer) ?Grid { 904 return self.grid; 905 } 906 907 pub fn getFocus(self: *Spacer) *Focus { 908 return &self.focus; 909 } 910 }; 911 912 // a single-child wrapper that builds the child at its natural size and 913 // positions its grid in the middle of the area granted by the parent 914 pub const Center = struct { 915 focus: Focus, 916 grid: ?Grid, 917 child: *Widget, 918 direction: Direction, 919 920 pub const Direction = enum { both, horiz, vert }; 921 922 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, direction: Direction) !Center { 923 const child = try allocator.create(Widget); 924 errdefer allocator.destroy(child); 925 child.* = child_widget; 926 return .{ 927 .focus = Focus.init(.container), 928 .grid = null, 929 .child = child, 930 .direction = direction, 931 }; 932 } 933 934 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 935 self.focus.deinit(allocator); 936 if (self.grid) |*grid| { 937 grid.deinit(); 938 self.grid = null; 939 } 940 self.child.deinit(allocator); 941 allocator.destroy(self.child); 942 } 943 944 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 945 self.clearGrid(); 946 self.getFocus().clear(); 947 948 // build the child without forcing it to fill min_size; it sizes 949 // itself to its content within the available max. 950 try self.child.build(allocator, .{ 951 .min_size = .{ .width = null, .height = null }, 952 .max_size = constraint.max_size, 953 }, root_focus); 954 955 const child_grid = self.child.getGrid() orelse return; 956 957 // prefer max when given; otherwise grow to max(min, child) so that 958 // when only a min is set (e.g. the wasm path passes viewport rows 959 // as min_height with no max), we can still vertically center while 960 // letting taller content extend past the min. 961 const width = if (constraint.max_size.width) |w| w else if (constraint.min_size.width) |min_w| @max(min_w, child_grid.size.width) else child_grid.size.width; 962 const height = if (constraint.max_size.height) |h| h else if (constraint.min_size.height) |min_h| @max(min_h, child_grid.size.height) else child_grid.size.height; 963 if (width == 0 or height == 0) return; 964 965 const offset_x: usize = if (self.direction == .horiz or self.direction == .both) 966 (width -| child_grid.size.width) / 2 967 else 968 0; 969 const offset_y: usize = if (self.direction == .vert or self.direction == .both) 970 (height -| child_grid.size.height) / 2 971 else 972 0; 973 974 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 975 errdefer grid.deinit(); 976 try grid.drawGrid(child_grid, offset_x, offset_y); 977 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 978 self.getFocus().child_id = self.child.getFocus().id; 979 980 self.grid = grid; 981 } 982 983 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 984 try self.child.input(allocator, key, root_focus); 985 } 986 987 pub fn clearGrid(self: *Center) void { 988 if (self.grid) |*grid| { 989 grid.deinit(); 990 self.grid = null; 991 } 992 self.child.clearGrid(); 993 } 994 995 pub fn getGrid(self: Center) ?Grid { 996 return self.grid; 997 } 998 999 pub fn getFocus(self: *Center) *Focus { 1000 return &self.focus; 1001 } 1002 }; 1003 1004 // renders truecolor ANSI art 1005 pub const AnsiArt = struct { 1006 focus: Focus, 1007 grid: ?Grid, 1008 content: []const u8, 1009 1010 pub fn init(content: []const u8) AnsiArt { 1011 return .{ 1012 .focus = Focus.init(.container), 1013 .grid = null, 1014 .content = content, 1015 }; 1016 } 1017 1018 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1019 self.focus.deinit(allocator); 1020 if (self.grid) |*grid| { 1021 grid.deinit(); 1022 self.grid = null; 1023 } 1024 } 1025 1026 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1027 _ = root_focus; 1028 self.clearGrid(); 1029 1030 // parse into rows of cells, then copy into a rectangular grid 1031 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1032 defer { 1033 for (rows.items) |*row| row.deinit(allocator); 1034 rows.deinit(allocator); 1035 } 1036 var row: std.ArrayList(Grid.Cell) = .empty; 1037 errdefer row.deinit(allocator); 1038 1039 var style: Grid.Style = .{}; 1040 var width: usize = 0; 1041 const content = self.content; 1042 var i: usize = 0; 1043 while (i < content.len) { 1044 const byte = content[i]; 1045 if (byte == '\n') { 1046 width = @max(width, row.items.len); 1047 try rows.append(allocator, row); 1048 row = .empty; 1049 i += 1; 1050 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1051 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1052 var j = i + 2; 1053 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1054 if (j >= content.len) { 1055 i = content.len; // malformed trailing escape; stop 1056 } else { 1057 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1058 i = j + 1; 1059 } 1060 } else { 1061 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1062 const end = @min(content.len, i + len); 1063 const rune = content[i..end]; 1064 const transparent = end - i == 1 and rune[0] == ' ' and 1065 style.fg == null and style.bg == null and !style.inverted; 1066 try row.append(allocator, .{ 1067 .rune = if (transparent) null else rune, 1068 .style = style, 1069 }); 1070 i = end; 1071 } 1072 } 1073 // a trailing row with content but no closing newline 1074 if (row.items.len > 0) { 1075 width = @max(width, row.items.len); 1076 try rows.append(allocator, row); 1077 } else { 1078 row.deinit(allocator); 1079 } 1080 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1081 1082 const height = rows.items.len; 1083 if (width == 0 or height == 0) return; 1084 1085 const clamped_w = @min(width, constraint.max_size.width orelse width); 1086 const clamped_h = @min(height, constraint.max_size.height orelse height); 1087 1088 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1089 errdefer grid.deinit(); 1090 for (rows.items[0..clamped_h], 0..) |r, y| { 1091 const n = @min(r.items.len, clamped_w); 1092 for (r.items[0..n], 0..) |cell, x| { 1093 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1094 } 1095 } 1096 self.grid = grid; 1097 } 1098 1099 pub fn input(self: *AnsiArt, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1100 _ = self; 1101 _ = allocator; 1102 _ = key; 1103 _ = root_focus; 1104 } 1105 1106 pub fn clearGrid(self: *AnsiArt) void { 1107 if (self.grid) |*grid| { 1108 grid.deinit(); 1109 self.grid = null; 1110 } 1111 } 1112 1113 pub fn getGrid(self: AnsiArt) ?Grid { 1114 return self.grid; 1115 } 1116 1117 pub fn getFocus(self: *AnsiArt) *Focus { 1118 return &self.focus; 1119 } 1120 1121 fn applySgr(style: *Grid.Style, params: []const u8) void { 1122 var nums: [16]u32 = undefined; 1123 var n: usize = 0; 1124 var it = std.mem.splitScalar(u8, params, ';'); 1125 while (it.next()) |tok| { 1126 if (n >= nums.len) break; 1127 // an empty parameter (e.g. bare "\x1b[m") means 0 1128 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1129 n += 1; 1130 } 1131 if (n == 0) { 1132 style.* = .{}; 1133 return; 1134 } 1135 var i: usize = 0; 1136 while (i < n) : (i += 1) { 1137 switch (nums[i]) { 1138 0 => style.* = .{}, 1139 7 => style.inverted = true, 1140 27 => style.inverted = false, 1141 39 => style.fg = null, 1142 49 => style.bg = null, 1143 38, 48 => { 1144 // truecolor form: 38;2;r;g;b — anything else is ignored 1145 if (i + 4 < n and nums[i + 1] == 2) { 1146 const c = Grid.Color{ 1147 .r = @truncate(nums[i + 2]), 1148 .g = @truncate(nums[i + 3]), 1149 .b = @truncate(nums[i + 4]), 1150 }; 1151 if (nums[i] == 38) style.fg = c else style.bg = c; 1152 i += 4; 1153 } 1154 }, 1155 else => {}, 1156 } 1157 } 1158 } 1159 }; 1160 1161 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1162 pub const AnsiBackground = struct { 1163 grid: ?Grid, 1164 child: *Widget, 1165 art: AnsiArt, 1166 session: *Session, 1167 1168 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1169 var cw = child_widget; 1170 const child = allocator.create(Widget) catch |e| { 1171 cw.deinit(allocator); 1172 return e; 1173 }; 1174 child.* = cw; 1175 return .{ .grid = null, .child = child, .art = AnsiArt.init(art_content), .session = session }; 1176 } 1177 1178 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1179 if (self.grid) |*grid| grid.deinit(); 1180 self.art.deinit(allocator); 1181 self.child.deinit(allocator); 1182 allocator.destroy(self.child); 1183 } 1184 1185 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1186 self.clearGrid(); 1187 1188 // make the wrapped page fill the whole available area 1189 try self.child.build(allocator, .{ 1190 .min_size = .{ 1191 .width = constraint.max_size.width orelse constraint.min_size.width, 1192 .height = constraint.max_size.height orelse constraint.min_size.height, 1193 }, 1194 .max_size = constraint.max_size, 1195 }, root_focus); 1196 1197 if (self.session.data.enable_ansi) { 1198 if (self.child.getGrid()) |fg| { 1199 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1200 } 1201 } 1202 } 1203 1204 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1205 try self.child.input(allocator, key, root_focus); 1206 } 1207 1208 pub fn clearGrid(self: *AnsiBackground) void { 1209 if (self.grid) |*grid| { 1210 grid.deinit(); 1211 self.grid = null; 1212 } 1213 self.child.clearGrid(); 1214 self.art.clearGrid(); 1215 } 1216 1217 pub fn getGrid(self: AnsiBackground) ?Grid { 1218 return self.grid orelse self.child.getGrid(); 1219 } 1220 1221 pub fn getFocus(self: *AnsiBackground) *Focus { 1222 return self.child.getFocus(); 1223 } 1224 1225 // which top corner the art hugs. 1226 const ArtAnchor = enum { top_left, top_right }; 1227 1228 // a foreground cell counts as blank if it's empty or a bare space without styling 1229 fn cellIsBlank(cell: Grid.Cell) bool { 1230 if (cell.rune) |rune| { 1231 return std.mem.eql(u8, rune, " ") and 1232 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1233 } 1234 return true; 1235 } 1236 1237 // a single representative color for an art cell 1238 fn artCellColor(style: Grid.Style) ?Grid.Color { 1239 const f = style.fg orelse return style.bg; 1240 const b = style.bg orelse return f; 1241 return .{ 1242 .r = @intCast((@as(u16, f.r) + b.r) / 2), 1243 .g = @intCast((@as(u16, f.g) + b.g) / 2), 1244 .b = @intCast((@as(u16, f.b) + b.b) / 2), 1245 }; 1246 } 1247 1248 // behind a visible glyph the art color is dimmed to this fraction of its 1249 // brightness so light terminal text stays legible on top of it 1250 const glyph_bg_brightness = 45; // percent 1251 1252 // a glyph sitting over the art also gets its foreground pinned to this color 1253 // (unless it set its own), so the text stays legible 1254 const glyph_fg_over_art = Grid.Color{ .r = 235, .g = 235, .b = 235 }; 1255 1256 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1257 const c = color orelse return null; 1258 return .{ 1259 .r = @intCast(@as(u16, c.r) * glyph_bg_brightness / 100), 1260 .g = @intCast(@as(u16, c.g) * glyph_bg_brightness / 100), 1261 .b = @intCast(@as(u16, c.b) * glyph_bg_brightness / 100), 1262 }; 1263 } 1264 1265 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1266 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1267 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1268 // snap such channels clear of that range so the backdrop doesn't blink or 1269 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1270 // actually render truecolor. 1271 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1272 const c = color orelse return null; 1273 const snap = struct { 1274 fn f(v: u8) u8 { 1275 return if (v >= 1 and v <= 9) 10 else v; 1276 } 1277 }.f; 1278 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1279 } 1280 1281 // composites ANSI art behind a foreground grid 1282 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1283 art.clearGrid(); 1284 try art.build(allocator, .{ 1285 .min_size = .{ .width = null, .height = null }, 1286 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1287 }, root_focus); 1288 1289 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1290 errdefer out.deinit(); 1291 1292 if (art.getGrid()) |art_grid| { 1293 const anchor_x = switch (anchor) { 1294 .top_left => 0, 1295 .top_right => foreground.size.width -| art_grid.size.width, 1296 }; 1297 for (0..art_grid.size.height) |y| { 1298 for (0..art_grid.size.width) |x| { 1299 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1300 if (src.rune == null) continue; 1301 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1302 const dst = &out.cells.items[idx]; 1303 if (cellIsBlank(dst.*)) { 1304 dst.* = src; 1305 dst.style.fg = sgrSafe(dst.style.fg); 1306 dst.style.bg = sgrSafe(dst.style.bg); 1307 } else if (dst.style.bg == null) { 1308 dst.style.bg = sgrSafe(dimColor(artCellColor(src.style))); 1309 if (dst.style.fg == null) dst.style.fg = glyph_fg_over_art; 1310 } 1311 } 1312 } 1313 } 1314 return out; 1315 } 1316 }; 1317