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