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