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