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