╭ 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 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 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 994 return root; 995 } 996 997 pub const Widget = union(enum) { 998 text: wgt.Text(Widget), 999 box: wgt.Box(Widget), 1000 text_box: wgt.TextBox(Widget), 1001 text_input: wgt.TextInput(Widget), 1002 scroll: wgt.Scroll(Widget), 1003 stack: wgt.Stack(Widget), 1004 flow_box: FlowBox, 1005 flow_box_scroll: FlowBox.Scroll, 1006 spacer: Spacer, 1007 center: Center, 1008 ansi_art: AnsiArt, 1009 background: AnsiBackground, 1010 home: Home.View, 1011 user: User.View, 1012 repo: Repo.View, 1013 quit: Quit.View, 1014 title: Title.View, 1015 sub_title: SubTitle.View, 1016 home_header: Home.Header.View, 1017 user_header: User.Header.View, 1018 repo_header: Repo.Header.View, 1019 repo_sub_header: Repo.SubHeader.View, 1020 repo_files: Repo.Files.View, 1021 repo_commits: Repo.Commits.View, 1022 repo_refs: Repo.Refs.View, 1023 home_users: Home.Users.View, 1024 home_repos: Home.Repos.View, 1025 auth_tab: Home.Header.AuthTab.View, 1026 home_settings: Home.Settings.View, 1027 home_auth: Home.Auth.View, 1028 footer: Footer, 1029 1030 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 1031 switch (self.*) { 1032 inline else => |*case| case.deinit(allocator), 1033 } 1034 } 1035 1036 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 1037 switch (self.*) { 1038 inline else => |*case| try case.build(allocator, constraint, root_focus), 1039 } 1040 } 1041 1042 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 1043 switch (self.*) { 1044 inline else => |*case| try case.input(allocator, key, root_focus), 1045 } 1046 } 1047 1048 pub fn clearGrid(self: *Widget) void { 1049 switch (self.*) { 1050 inline else => |*case| case.clearGrid(), 1051 } 1052 } 1053 1054 pub fn getGrid(self: Widget) ?Grid { 1055 switch (self) { 1056 inline else => |*case| return case.getGrid(), 1057 } 1058 } 1059 1060 pub fn getFocus(self: *Widget) *Focus { 1061 switch (self.*) { 1062 inline else => |*case| return case.getFocus(), 1063 } 1064 } 1065 }; 1066 1067 pub const FlowBox = struct { 1068 focus: *Focus, 1069 grid: ?Grid, 1070 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1071 // backs the per-item strings the text boxes borrow: each box's `content` 1072 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 1073 // wholesale on each setItems so there's no per-string ownership to track. 1074 arena: std.heap.ArenaAllocator, 1075 // column count from the last build — FlowBox.Scroll.input uses it so arrow 1076 // up/down can step by a row's worth of items. 1077 last_cols: usize, 1078 options: Options, 1079 1080 const border_rows: usize = 2; 1081 1082 pub const Options = struct { 1083 cell_width: usize = 40, 1084 cell_height: usize = 3, 1085 }; 1086 1087 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 1088 return .{ 1089 .focus = try Focus.create(allocator, .container), 1090 .grid = null, 1091 .text_boxes = .empty, 1092 .arena = std.heap.ArenaAllocator.init(allocator), 1093 .last_cols = 1, 1094 .options = options, 1095 }; 1096 } 1097 1098 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 1099 self.focus.destroy(allocator); 1100 if (self.grid) |*grid| { 1101 grid.deinit(); 1102 self.grid = null; 1103 } 1104 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1105 self.text_boxes.deinit(allocator); 1106 self.arena.deinit(); 1107 } 1108 1109 // one flow item: its display text plus an optional link. a non-empty `link` 1110 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 1111 // the web renderer turns into an anchor. 1112 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1113 1114 // both the item text and the link are copied into the arena, so the caller's 1115 // slices needn't outlive this call. 1116 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 1117 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1118 self.text_boxes.clearAndFree(allocator); 1119 1120 // the old text boxes (and their borrowed content/links) are gone now, so 1121 // the arena that backed those strings can be reclaimed. 1122 _ = self.arena.reset(.retain_capacity); 1123 const aa = self.arena.allocator(); 1124 1125 self.focus.clear(); 1126 self.focus.child_id = null; 1127 1128 for (items) |item| { 1129 const line = try aa.dupe(u8, item.text); 1130 1131 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 1132 errdefer text_box.deinit(allocator); 1133 text_box.getFocus().focusable = true; 1134 1135 if (item.link.len > 0) { 1136 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1137 } 1138 1139 try self.text_boxes.append(allocator, text_box); 1140 } 1141 1142 if (self.text_boxes.items.len > 0) { 1143 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1144 } 1145 } 1146 1147 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1148 self.clearGrid(); 1149 self.focus.clear(); 1150 1151 const cell_width = self.options.cell_width; 1152 const max_width = constraint.max_size.width orelse cell_width; 1153 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 1154 self.last_cols = cols; 1155 1156 const count = self.text_boxes.items.len; 1157 if (count == 0) return; 1158 const slot_height = self.options.cell_height + border_rows; 1159 if (slot_height == 0) return; 1160 1161 // build at the slot size so every text box fits a single grid cell 1162 for (self.text_boxes.items) |*tb| { 1163 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1164 try tb.build(allocator, .{ 1165 .min_size = .{ .width = cell_width, .height = null }, 1166 .max_size = .{ .width = cell_width, .height = slot_height }, 1167 }, root_focus); 1168 } 1169 1170 const rows = (count + cols - 1) / cols; 1171 const content_height = rows * slot_height; 1172 const total_width = cols * cell_width; 1173 if (total_width == 0 or content_height == 0) return; 1174 1175 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 1176 errdefer grid.deinit(); 1177 1178 for (self.text_boxes.items, 0..) |*tb, i| { 1179 const tb_grid = tb.getGrid() orelse continue; 1180 const col = i % cols; 1181 const row = i / cols; 1182 const cell_x = col * cell_width; 1183 const cell_y = row * slot_height; 1184 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 1185 try grid.drawGrid(tb_grid, cell_x, cell_y); 1186 } 1187 1188 self.grid = grid; 1189 } 1190 1191 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1192 _ = self; 1193 _ = allocator; 1194 _ = key; 1195 _ = root_focus; 1196 } 1197 1198 pub fn clearGrid(self: *FlowBox) void { 1199 if (self.grid) |*grid| { 1200 grid.deinit(); 1201 self.grid = null; 1202 } 1203 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1204 } 1205 1206 pub fn getGrid(self: FlowBox) ?Grid { 1207 return self.grid; 1208 } 1209 1210 pub fn getFocus(self: *FlowBox) *Focus { 1211 return self.focus; 1212 } 1213 1214 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 1215 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 1216 const slot_height = self.options.cell_height + border_rows; 1217 const col = index % self.last_cols; 1218 const row = index / self.last_cols; 1219 return .{ 1220 .x = @intCast(col * self.options.cell_width), 1221 .y = @intCast(row * slot_height), 1222 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1223 }; 1224 } 1225 1226 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1227 for (self.text_boxes.items, 0..) |tb, i| { 1228 if (tb.box.focus.id == focus_id) return i; 1229 } 1230 return null; 1231 } 1232 1233 pub const Scroll = struct { 1234 scroll: wgt.Scroll(Widget), 1235 1236 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 1237 var layout_inner = try FlowBox.init(allocator, options); 1238 errdefer layout_inner.deinit(allocator); 1239 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 1240 errdefer scroll.deinit(allocator); 1241 return .{ .scroll = scroll }; 1242 } 1243 1244 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1245 self.scroll.deinit(allocator); 1246 } 1247 1248 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 1249 self.scroll.x = 0; 1250 self.scroll.y = 0; 1251 try self.inner().setItems(allocator, items); 1252 } 1253 1254 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1255 try self.scroll.build(allocator, constraint, root_focus); 1256 } 1257 1258 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1259 _ = allocator; 1260 const in = self.inner(); 1261 const child_id = in.focus.child_id orelse return; 1262 const current_index = in.indexOfFocusId(child_id) orelse return; 1263 const count = in.text_boxes.items.len; 1264 if (count == 0) return; 1265 const cols = in.last_cols; 1266 const slot_height = in.options.cell_height + FlowBox.border_rows; 1267 1268 var index = current_index; 1269 switch (key) { 1270 .arrow_up => index -|= cols, 1271 .arrow_down => if (index + cols < count) { 1272 index += cols; 1273 }, 1274 .arrow_left => index -|= 1, 1275 .arrow_right => if (index + 1 < count) { 1276 index += 1; 1277 }, 1278 .home => index = 0, 1279 .end => index = count - 1, 1280 .page_up => { 1281 if (self.scroll.grid) |grid| if (slot_height > 0) { 1282 const rows_per_page = grid.size.height / slot_height; 1283 index -|= rows_per_page * cols; 1284 }; 1285 }, 1286 .page_down => { 1287 if (self.scroll.grid) |grid| if (slot_height > 0) { 1288 const rows_per_page = grid.size.height / slot_height; 1289 index = @min(index + rows_per_page * cols, count - 1); 1290 }; 1291 }, 1292 // scroll wheel moves the focused cell by a full row so the 1293 // viewport (via scrollToRect) follows in row-sized steps, 1294 // matching how a scroll wheel feels in a grid view. 1295 .mouse => |mouse| switch (mouse.action) { 1296 .scroll => |dir| switch (dir) { 1297 .up => index -|= cols, 1298 .down => if (index + cols < count) { 1299 index += cols; 1300 }, 1301 }, 1302 else => {}, 1303 }, 1304 else => {}, 1305 } 1306 1307 if (index != current_index) { 1308 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1309 if (in.cellRect(index)) |rect| { 1310 self.scroll.scrollToRect(rect); 1311 } 1312 } 1313 } 1314 1315 pub fn clearGrid(self: *Scroll) void { 1316 self.scroll.clearGrid(); 1317 } 1318 1319 pub fn getGrid(self: Scroll) ?Grid { 1320 return self.scroll.getGrid(); 1321 } 1322 1323 pub fn getFocus(self: *Scroll) *Focus { 1324 return self.scroll.getFocus(); 1325 } 1326 1327 pub fn getSelectedIndex(self: Scroll) ?usize { 1328 const in = self.scroll.child.flow_box; 1329 const child_id = in.focus.child_id orelse return null; 1330 return in.indexOfFocusId(child_id); 1331 } 1332 1333 fn inner(self: *Scroll) *FlowBox { 1334 return &self.scroll.child.flow_box; 1335 } 1336 }; 1337 }; 1338 1339 // an invisible widget that fills the horizontal space granted by its parent. 1340 // used inside Box(horiz) with a min_size so the box reserves space for the 1341 // children that follow, pushing them to the right. 1342 pub const Spacer = struct { 1343 focus: *Focus, 1344 grid: ?Grid, 1345 1346 pub fn init(allocator: std.mem.Allocator) !Spacer { 1347 return .{ 1348 .focus = try Focus.create(allocator, .container), 1349 .grid = null, 1350 }; 1351 } 1352 1353 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1354 self.focus.destroy(allocator); 1355 if (self.grid) |*grid| { 1356 grid.deinit(); 1357 self.grid = null; 1358 } 1359 } 1360 1361 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1362 _ = root_focus; 1363 self.clearGrid(); 1364 const width = constraint.max_size.width orelse return; 1365 if (width == 0) return; 1366 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1367 } 1368 1369 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1370 _ = self; 1371 _ = allocator; 1372 _ = key; 1373 _ = root_focus; 1374 } 1375 1376 pub fn clearGrid(self: *Spacer) void { 1377 if (self.grid) |*grid| { 1378 grid.deinit(); 1379 self.grid = null; 1380 } 1381 } 1382 1383 pub fn getGrid(self: Spacer) ?Grid { 1384 return self.grid; 1385 } 1386 1387 pub fn getFocus(self: *Spacer) *Focus { 1388 return self.focus; 1389 } 1390 }; 1391 1392 // a one-row, non-focusable status bar showing the current page's url 1393 pub const Footer = struct { 1394 focus: *Focus, 1395 grid: ?Grid, 1396 session: *Session, 1397 arena: std.heap.ArenaAllocator, 1398 1399 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 1400 return .{ 1401 .focus = try Focus.create(allocator, .container), 1402 .grid = null, 1403 .session = session, 1404 .arena = std.heap.ArenaAllocator.init(allocator), 1405 }; 1406 } 1407 1408 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 1409 self.focus.destroy(allocator); 1410 if (self.grid) |*grid| grid.deinit(); 1411 self.arena.deinit(); 1412 } 1413 1414 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1415 _ = root_focus; 1416 self.clearGrid(); 1417 const width = constraint.max_size.width orelse return; 1418 if (width == 0) return; 1419 1420 _ = self.arena.reset(.retain_capacity); 1421 const aa = self.arena.allocator(); 1422 const path = self.session.data.current_page.urlAlloc(&self.arena) catch return; 1423 const text = if (self.session.web_port) |port| 1424 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 1425 else 1426 path; 1427 1428 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1429 errdefer grid.deinit(); 1430 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 1431 var i: usize = 0; 1432 while (utf8.nextCodepointSlice()) |ch| { 1433 if (i == width) break; 1434 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 1435 i += 1; 1436 } 1437 self.grid = grid; 1438 } 1439 1440 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1441 _ = self; 1442 _ = allocator; 1443 _ = key; 1444 _ = root_focus; 1445 } 1446 1447 pub fn clearGrid(self: *Footer) void { 1448 if (self.grid) |*grid| { 1449 grid.deinit(); 1450 self.grid = null; 1451 } 1452 } 1453 1454 pub fn getGrid(self: Footer) ?Grid { 1455 return self.grid; 1456 } 1457 1458 pub fn getFocus(self: *Footer) *Focus { 1459 return self.focus; 1460 } 1461 }; 1462 1463 // a single-child wrapper that builds the child at its natural size and 1464 // positions its grid in the middle of the area granted by the parent 1465 pub const Center = struct { 1466 focus: *Focus, 1467 grid: ?Grid, 1468 child: *Widget, 1469 direction: Direction, 1470 1471 pub const Direction = enum { both, horiz, vert }; 1472 1473 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, direction: Direction) !Center { 1474 const child = try allocator.create(Widget); 1475 errdefer allocator.destroy(child); 1476 child.* = child_widget; 1477 return .{ 1478 .focus = try Focus.create(allocator, .container), 1479 .grid = null, 1480 .child = child, 1481 .direction = direction, 1482 }; 1483 } 1484 1485 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 1486 self.focus.destroy(allocator); 1487 if (self.grid) |*grid| { 1488 grid.deinit(); 1489 self.grid = null; 1490 } 1491 self.child.deinit(allocator); 1492 allocator.destroy(self.child); 1493 } 1494 1495 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1496 self.clearGrid(); 1497 self.getFocus().clear(); 1498 1499 // build the child without forcing it to fill min_size; it sizes 1500 // itself to its content within the available max. 1501 try self.child.build(allocator, .{ 1502 .min_size = .{ .width = null, .height = null }, 1503 .max_size = constraint.max_size, 1504 }, root_focus); 1505 1506 const child_grid = self.child.getGrid() orelse return; 1507 1508 // prefer max when given; otherwise grow to max(min, child) so that 1509 // when only a min is set (e.g. the wasm path passes viewport rows 1510 // as min_height with no max), we can still vertically center while 1511 // letting taller content extend past the min. 1512 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; 1513 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; 1514 if (width == 0 or height == 0) return; 1515 1516 const offset_x: usize = if (self.direction == .horiz or self.direction == .both) 1517 (width -| child_grid.size.width) / 2 1518 else 1519 0; 1520 const offset_y: usize = if (self.direction == .vert or self.direction == .both) 1521 (height -| child_grid.size.height) / 2 1522 else 1523 0; 1524 1525 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 1526 errdefer grid.deinit(); 1527 try grid.drawGrid(child_grid, offset_x, offset_y); 1528 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 1529 self.getFocus().child_id = self.child.getFocus().id; 1530 1531 self.grid = grid; 1532 } 1533 1534 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1535 try self.child.input(allocator, key, root_focus); 1536 } 1537 1538 pub fn clearGrid(self: *Center) void { 1539 if (self.grid) |*grid| { 1540 grid.deinit(); 1541 self.grid = null; 1542 } 1543 self.child.clearGrid(); 1544 } 1545 1546 pub fn getGrid(self: Center) ?Grid { 1547 return self.grid; 1548 } 1549 1550 pub fn getFocus(self: *Center) *Focus { 1551 return self.focus; 1552 } 1553 }; 1554 1555 // renders truecolor ANSI art 1556 pub const AnsiArt = struct { 1557 focus: *Focus, 1558 grid: ?Grid, 1559 content: []const u8, 1560 1561 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 1562 return .{ 1563 .focus = try Focus.create(allocator, .container), 1564 .grid = null, 1565 .content = content, 1566 }; 1567 } 1568 1569 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1570 self.focus.destroy(allocator); 1571 if (self.grid) |*grid| { 1572 grid.deinit(); 1573 self.grid = null; 1574 } 1575 } 1576 1577 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1578 _ = root_focus; 1579 self.clearGrid(); 1580 1581 // parse into rows of cells, then copy into a rectangular grid 1582 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1583 defer { 1584 for (rows.items) |*row| row.deinit(allocator); 1585 rows.deinit(allocator); 1586 } 1587 var row: std.ArrayList(Grid.Cell) = .empty; 1588 errdefer row.deinit(allocator); 1589 1590 var style: Grid.Style = .{}; 1591 var width: usize = 0; 1592 const content = self.content; 1593 var i: usize = 0; 1594 while (i < content.len) { 1595 const byte = content[i]; 1596 if (byte == '\n') { 1597 width = @max(width, row.items.len); 1598 try rows.append(allocator, row); 1599 row = .empty; 1600 i += 1; 1601 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1602 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1603 var j = i + 2; 1604 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1605 if (j >= content.len) { 1606 i = content.len; // malformed trailing escape; stop 1607 } else { 1608 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1609 i = j + 1; 1610 } 1611 } else { 1612 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1613 const end = @min(content.len, i + len); 1614 const rune = content[i..end]; 1615 const transparent = end - i == 1 and rune[0] == ' ' and 1616 style.fg == null and style.bg == null and !style.inverted; 1617 try row.append(allocator, .{ 1618 .rune = if (transparent) null else rune, 1619 .style = style, 1620 }); 1621 i = end; 1622 } 1623 } 1624 // a trailing row with content but no closing newline 1625 if (row.items.len > 0) { 1626 width = @max(width, row.items.len); 1627 try rows.append(allocator, row); 1628 } else { 1629 row.deinit(allocator); 1630 } 1631 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1632 1633 const height = rows.items.len; 1634 if (width == 0 or height == 0) return; 1635 1636 const clamped_w = @min(width, constraint.max_size.width orelse width); 1637 const clamped_h = @min(height, constraint.max_size.height orelse height); 1638 1639 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1640 errdefer grid.deinit(); 1641 for (rows.items[0..clamped_h], 0..) |r, y| { 1642 const n = @min(r.items.len, clamped_w); 1643 for (r.items[0..n], 0..) |cell, x| { 1644 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1645 } 1646 } 1647 self.grid = grid; 1648 } 1649 1650 pub fn input(self: *AnsiArt, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1651 _ = self; 1652 _ = allocator; 1653 _ = key; 1654 _ = root_focus; 1655 } 1656 1657 pub fn clearGrid(self: *AnsiArt) void { 1658 if (self.grid) |*grid| { 1659 grid.deinit(); 1660 self.grid = null; 1661 } 1662 } 1663 1664 pub fn getGrid(self: AnsiArt) ?Grid { 1665 return self.grid; 1666 } 1667 1668 pub fn getFocus(self: *AnsiArt) *Focus { 1669 return self.focus; 1670 } 1671 1672 fn applySgr(style: *Grid.Style, params: []const u8) void { 1673 var nums: [16]u32 = undefined; 1674 var n: usize = 0; 1675 var it = std.mem.splitScalar(u8, params, ';'); 1676 while (it.next()) |tok| { 1677 if (n >= nums.len) break; 1678 // an empty parameter (e.g. bare "\x1b[m") means 0 1679 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1680 n += 1; 1681 } 1682 if (n == 0) { 1683 style.* = .{}; 1684 return; 1685 } 1686 var i: usize = 0; 1687 while (i < n) : (i += 1) { 1688 switch (nums[i]) { 1689 0 => style.* = .{}, 1690 7 => style.inverted = true, 1691 27 => style.inverted = false, 1692 39 => style.fg = null, 1693 49 => style.bg = null, 1694 38, 48 => { 1695 // truecolor form: 38;2;r;g;b — anything else is ignored 1696 if (i + 4 < n and nums[i + 1] == 2) { 1697 const c = Grid.Color{ 1698 .r = @truncate(nums[i + 2]), 1699 .g = @truncate(nums[i + 3]), 1700 .b = @truncate(nums[i + 4]), 1701 }; 1702 if (nums[i] == 38) style.fg = c else style.bg = c; 1703 i += 4; 1704 } 1705 }, 1706 else => {}, 1707 } 1708 } 1709 } 1710 }; 1711 1712 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1713 pub const AnsiBackground = struct { 1714 grid: ?Grid, 1715 child: *Widget, 1716 art: AnsiArt, 1717 session: *Session, 1718 1719 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1720 var cw = child_widget; 1721 const child = allocator.create(Widget) catch |e| { 1722 cw.deinit(allocator); 1723 return e; 1724 }; 1725 child.* = cw; 1726 errdefer { 1727 child.deinit(allocator); 1728 allocator.destroy(child); 1729 } 1730 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 1731 } 1732 1733 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1734 if (self.grid) |*grid| grid.deinit(); 1735 self.art.deinit(allocator); 1736 self.child.deinit(allocator); 1737 allocator.destroy(self.child); 1738 } 1739 1740 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1741 self.clearGrid(); 1742 1743 // make the wrapped page fill the whole available area 1744 try self.child.build(allocator, .{ 1745 .min_size = .{ 1746 .width = constraint.max_size.width orelse constraint.min_size.width, 1747 .height = constraint.max_size.height orelse constraint.min_size.height, 1748 }, 1749 .max_size = constraint.max_size, 1750 }, root_focus); 1751 1752 if (self.session.data.enable_ansi) { 1753 if (self.child.getGrid()) |fg| { 1754 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1755 } 1756 } 1757 } 1758 1759 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1760 try self.child.input(allocator, key, root_focus); 1761 } 1762 1763 pub fn clearGrid(self: *AnsiBackground) void { 1764 if (self.grid) |*grid| { 1765 grid.deinit(); 1766 self.grid = null; 1767 } 1768 self.child.clearGrid(); 1769 self.art.clearGrid(); 1770 } 1771 1772 pub fn getGrid(self: AnsiBackground) ?Grid { 1773 return self.grid orelse self.child.getGrid(); 1774 } 1775 1776 pub fn getFocus(self: *AnsiBackground) *Focus { 1777 return self.child.getFocus(); 1778 } 1779 1780 // which top corner the art hugs. 1781 const ArtAnchor = enum { top_left, top_right }; 1782 1783 // a foreground cell counts as blank if it's empty or a bare space without styling 1784 fn cellIsBlank(cell: Grid.Cell) bool { 1785 if (cell.rune) |rune| { 1786 return std.mem.eql(u8, rune, " ") and 1787 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1788 } 1789 return true; 1790 } 1791 1792 // the art is dimmed to this fraction of its brightness so foreground text 1793 // stays legible over it 1794 const art_brightness = 45; // percent 1795 1796 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1797 const c = color orelse return null; 1798 return .{ 1799 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 1800 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 1801 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 1802 }; 1803 } 1804 1805 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1806 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1807 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1808 // snap such channels clear of that range so the backdrop doesn't blink or 1809 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1810 // actually render truecolor. 1811 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1812 const c = color orelse return null; 1813 const snap = struct { 1814 fn f(v: u8) u8 { 1815 return if (v >= 1 and v <= 9) 10 else v; 1816 } 1817 }.f; 1818 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1819 } 1820 1821 // composites ANSI art behind a foreground grid 1822 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1823 art.clearGrid(); 1824 try art.build(allocator, .{ 1825 .min_size = .{ .width = null, .height = null }, 1826 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1827 }, root_focus); 1828 1829 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1830 errdefer out.deinit(); 1831 1832 if (art.getGrid()) |art_grid| { 1833 const anchor_x = switch (anchor) { 1834 .top_left => 0, 1835 .top_right => foreground.size.width -| art_grid.size.width, 1836 }; 1837 for (0..art_grid.size.height) |y| { 1838 for (0..art_grid.size.width) |x| { 1839 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1840 if (src.rune == null) continue; 1841 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1842 const dst = &out.cells.items[idx]; 1843 // composite the dimmed art behind every cell so it shows 1844 // through the whole UI: a blank cell becomes the art, while a 1845 // cell with a glyph keeps the glyph but takes the dimmed art as 1846 // its background (replacing whatever background it had, which 1847 // would otherwise obscure the art). 1848 if (cellIsBlank(dst.*)) { 1849 dst.* = src; 1850 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 1851 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 1852 } else { 1853 dst.style.bg = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 1854 } 1855 } 1856 } 1857 } 1858 return out; 1859 } 1860 }; 1861