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