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