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