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