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