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