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