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