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