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