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