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