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