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