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