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