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