╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const rf = xit.ref; 6 const hash = xit.hash; 7 const xitui = xit.xitui; 8 const term = xitui.terminal; 9 const wgt = xitui.widget; 10 const layout = xitui.layout; 11 const Key = xitui.input.Key; 12 const Grid = xitui.grid.Grid; 13 const Focus = xitui.focus.Focus; 14 const evt = @import("./event.zig"); 15 const inp = @import("./ui/input.zig"); 16 17 pub const Home = @import("./ui/Home.zig"); 18 pub const User = @import("./ui/User.zig"); 19 pub const Repo = @import("./ui/Repo.zig"); 20 pub const Title = @import("./ui/Title.zig"); 21 pub const SubTitle = @import("./ui/SubTitle.zig"); 22 pub const Quit = @import("./ui/Quit.zig"); 23 pub const CloneUrl = @import("./ui/CloneUrl.zig"); 24 pub const Unauthorized = @import("./ui/Unauthorized.zig"); 25 26 pub const clipped_bottom_label_max_len = 10 * 4; 27 28 pub fn clippedBottomLabel(buffer: []u8, text: []const u8) ![]const u8 { 29 var iter = (try std.unicode.Utf8View.init(text)).iterator(); 30 var end: usize = 0; 31 var clipped_end: usize = 0; 32 for (0..10) |i| { 33 const codepoint = iter.nextCodepointSlice() orelse break; 34 end += codepoint.len; 35 if (i == 7) clipped_end = end; 36 } 37 const clipped = iter.nextCodepointSlice() != null; 38 return try std.fmt.bufPrint(buffer, "{s}{s}", .{ text[0..if (clipped) clipped_end else end], if (clipped) ".." else "" }); 39 } 40 41 pub const PageKind = enum { 42 home, 43 user, 44 repo, 45 }; 46 47 pub const Page = union(PageKind) { 48 home: Home, 49 user: User, 50 repo: Repo, 51 52 pub fn init(arena: *std.heap.ArenaAllocator, session: *Session, route: RoutablePage) !Page { 53 // the repo page can build without a moment in local mode; the home and 54 // user pages always read from the admin db. 55 return switch (route.parent()) { 56 .home => .{ .home = try Home.init(arena, session.haxy_moment orelse return error.NoMoment, switch (route) { 57 .home_users => |start| start, 58 else => 0, 59 }, switch (route) { 60 .home_repos => |start| start, 61 else => 0, 62 }) }, 63 .user => blk: { 64 const haxy_moment = session.haxy_moment orelse return error.NoMoment; 65 break :blk switch (route) { 66 .user_repos => |u| .{ .user = try User.init(arena, session, haxy_moment, u.name, u.start, 0) }, 67 .user_forks => |u| .{ .user = try User.init(arena, session, haxy_moment, u.name, 0, u.start) }, 68 .user_settings, .user_auth => |name| .{ .user = try User.init(arena, session, haxy_moment, name, 0, 0) }, 69 else => return error.UnexpectedRoute, 70 }; 71 }, 72 .repo => switch (route) { 73 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_patches, .repo_discussions, .repo_events, .repo_settings, .repo_auth => .{ .repo = try Repo.init(arena, session, route) }, 74 else => return error.UnexpectedRoute, 75 }, 76 }; 77 } 78 }; 79 80 // what the server hands to the client (and what main_wasm parses on _start). 81 // keeps Page free of any per-request session state. 82 pub const Snapshot = struct { 83 page: Page, 84 session: Session.Data = .{}, 85 }; 86 87 // a top-level "page" the user can navigate to. the user_* variants are the 88 // tabs of a user page; they each carry the user's name and all map to the 89 // .user parent page, so switching between them stays on that page (and just 90 // updates the url) rather than navigating away. 91 pub const RoutablePage = union(enum) { 92 home_users: usize, // 0 = first page 93 home_repos: usize, // 0 = first page 94 home_settings, 95 home_auth, 96 user_repos: struct { name: Array(evt.User.name_max_len), start: usize = 0 }, 97 user_forks: struct { name: Array(evt.User.name_max_len), start: usize = 0 }, 98 user_settings: Array(evt.User.name_max_len), 99 user_auth: Array(evt.User.name_max_len), 100 repo_files: RepoFilesRoute, 101 repo_commits: RepoCommitsRoute, 102 repo_refs: struct { 103 name: Array(repo_route_max_len), 104 kind: RefKind = .branch, 105 // the url-encoded ref name `kind`'s column windows from ("" = the 106 // first window; the other column always shows its first window). 107 from: Array(ref_route_max_len) = .{}, 108 }, 109 repo_issues: struct { 110 name: Array(repo_route_max_len), 111 // the tag the list is filtered to, url-encoded ("" = unfiltered). 112 tag: Array(issue_tag_route_max_len) = .{}, 113 // the issue the route names: the list's window root, or the issue the 114 // edit/description/resolve view shows. 115 selected: Array(evt.event_id_size * 2) = .{}, 116 // the resolve view's comma-separated list of fields prefilled from 117 // their side of the conflict. 118 theirs: Array(theirs_route_max_len) = .{}, 119 // the view the url names; a route with `selected` derives its view 120 // from that issue's status instead. 121 view: IssuesView = .open, 122 // the selected issue's comment window (0 = the first window). 123 comments_start: usize = 0, 124 // the comment shown in the detail pane (empty = the issue thread). 125 comment: Array(evt.event_id_size * 2) = .{}, 126 }, 127 repo_patches: struct { 128 name: Array(repo_route_max_len), 129 tag: Array(patch_tag_route_max_len) = .{}, 130 selected: Array(evt.event_id_size * 2) = .{}, 131 theirs: Array(theirs_route_max_len) = .{}, 132 view: PatchesView = .open, 133 comments_start: usize = 0, 134 comment: Array(evt.event_id_size * 2) = .{}, 135 }, 136 repo_discussions: struct { 137 name: Array(repo_route_max_len), 138 tag: Array(discussion_tag_route_max_len) = .{}, 139 selected: Array(evt.event_id_size * 2) = .{}, 140 view: DiscussionsView = .recent, 141 comments_start: usize = 0, 142 comment: Array(evt.event_id_size * 2) = .{}, 143 }, 144 repo_events: RepoEventsRoute, 145 repo_settings: Array(repo_route_max_len), 146 repo_auth: Array(repo_route_max_len), 147 148 pub const default: RoutablePage = .{ .home_repos = 0 }; 149 150 pub const RefKind = enum { branch, tag }; 151 152 pub const IssuesView = enum { open, closed, tags, new, edit, description, new_comment, edit_comment, remove, conflicts, resolve }; 153 154 pub const PatchesView = enum { open, closed, merged, tags, new, drafts, edit, description, new_comment, edit_comment, remove, conflicts, resolve }; 155 156 pub const DiscussionsView = enum { recent, tags, new, edit, description, new_comment, edit_comment, remove }; 157 158 pub const EventsView = enum { active, removed }; 159 160 pub const RefOrOid = enum { 161 branch, 162 tag, 163 object, 164 }; 165 166 // the "key:value" segments of a url tail, collected in any order 167 const Params = struct { 168 const ParamKey = enum { start, line, branch, tag, object, theirs }; 169 170 // a branch:/tag:/object: param; the value stays url-encoded 171 const RefParam = struct { kind: RefOrOid, value: []const u8 }; 172 173 values: std.enums.EnumArray(ParamKey, ?[]const u8) = .initFill(null), 174 175 // consume the leading "key:value" segments, stopping at the first 176 // segment that isn't one 177 fn scanPairs(self: *Params, segments: *std.mem.SplitIterator(u8, .scalar)) error{BadUrl}!void { 178 while (segments.peek()) |seg| { 179 const colon = std.mem.indexOfScalar(u8, seg, ':') orelse return; 180 const key = std.meta.stringToEnum(ParamKey, seg[0..colon]) orelse return; 181 const value = seg[colon + 1 ..]; 182 if (value.len == 0) return error.BadUrl; 183 if (self.values.get(key) != null) return error.BadUrl; 184 self.values.set(key, value); 185 _ = segments.next(); 186 } 187 } 188 189 // consume every remaining segment: pairs plus at most one bare word, 190 // which is returned 191 fn scanTail(self: *Params, segments: *std.mem.SplitIterator(u8, .scalar)) error{BadUrl}!?[]const u8 { 192 var word: ?[]const u8 = null; 193 while (true) { 194 try self.scanPairs(segments); 195 const seg = segments.next() orelse return word; 196 if (seg.len == 0 or word != null) return error.BadUrl; 197 word = seg; 198 } 199 } 200 201 // true when every set param is one of `allowed` 202 fn only(self: Params, allowed: []const ParamKey) bool { 203 for (std.enums.values(ParamKey)) |key| { 204 if (self.values.get(key) == null) continue; 205 if (std.mem.indexOfScalar(ParamKey, allowed, key) == null) return false; 206 } 207 return true; 208 } 209 210 // the "start:<n>" window param (0 when absent), null when malformed 211 fn start(self: Params) ?usize { 212 const value = self.values.get(.start) orelse return 0; 213 return std.fmt.parseInt(usize, value, 10) catch null; 214 } 215 216 // the "line:<n>" first-line param (0 when absent), null when malformed 217 fn line(self: Params) ?usize { 218 const value = self.values.get(.line) orelse return 0; 219 return std.fmt.parseInt(usize, value, 10) catch null; 220 } 221 222 // the single branch:/tag:/object: param, null when none is set 223 fn ref(self: Params) error{BadUrl}!?RefParam { 224 var result: ?RefParam = null; 225 inline for (@typeInfo(RefOrOid).@"enum".fields) |field| { 226 if (self.values.get(@field(ParamKey, field.name))) |value| { 227 if (result != null) return error.BadUrl; 228 result = .{ .kind = @field(RefOrOid, field.name), .value = value }; 229 } 230 } 231 return result; 232 } 233 }; 234 235 const user_segment = "/user/"; 236 const repo_segment = "/repo/"; 237 const files_seg = "files"; 238 const commits_seg = "commits"; 239 // ends a commits route naming its commit's full message 240 const message_seg = "message"; 241 // the `Params` key spellings the url emitters use 242 const tag_filter_seg = @tagName(Params.ParamKey.tag) ++ ":"; 243 const start_seg = @tagName(Params.ParamKey.start) ++ ":"; 244 const line_seg = @tagName(Params.ParamKey.line) ++ ":"; 245 const theirs_seg = @tagName(Params.ParamKey.theirs) ++ ":"; 246 const issue_seg = "issue:"; 247 const patch_seg = "patch:"; 248 const discuss_seg = "discuss:"; 249 const comment_seg = "comment:"; 250 // marks a files or commits route's trailing path: the value is the raw 251 // remainder of the url, so it must come last 252 const path_seg = "path:"; 253 254 // a repo route is "username/reponame", optionally followed by the files 255 // tab's "/files/<refkind>:<refvalue>[/line:<n>][/path:<dir>]"; the bare 256 // pair means the default branch's files root. a local session's routes 257 // elide the identity: "" at the bare root, else starting at the tail's "/". 258 pub const repo_route_max_len = 1024; 259 pub const repo_identity_max_len = evt.User.name_max_len + 1 + evt.Repo.name_max_len; 260 261 // true when a repo route's stored string elides its identity (local mode). 262 // unambiguous because a full string always starts with its owner segment. 263 fn identityElided(s: []const u8) bool { 264 return s.len == 0 or s[0] == '/'; 265 } 266 267 // a url-encoded tag can grow to three bytes per source byte. 268 pub const issue_tag_route_max_len = evt.Issue.tag_max_len * 3; 269 pub const patch_tag_route_max_len = evt.Patch.tag_max_len * 3; 270 pub const discussion_tag_route_max_len = evt.Discussion.tag_max_len * 3; 271 272 // caps the resolve view's theirs: field list (a longer one doesn't route). 273 pub const theirs_route_max_len = 512; 274 275 // caps a url-encoded ref name in a route (a longer name doesn't route). 276 pub const ref_route_max_len = 512; 277 278 // the identity stored by every repo route. Local routes elide it. 279 pub const RepoIdentity = struct { 280 identity: []const u8, // "owner/name" 281 owner: []const u8, 282 name: []const u8, 283 284 pub fn parse(s: []const u8) ?RepoIdentity { 285 var result: RepoIdentity = .{ 286 .identity = "", 287 .owner = "", 288 .name = "", 289 }; 290 if (identityElided(s)) { 291 return result; 292 } else { 293 var id_segments = std.mem.splitScalar(u8, s, '/'); 294 const owner = id_segments.next() orelse return null; 295 const name = id_segments.next() orelse return null; 296 if (owner.len == 0 or name.len == 0) return null; 297 result.identity = s[0 .. owner.len + 1 + name.len]; 298 result.owner = owner; 299 result.name = name; 300 } 301 return result; 302 } 303 }; 304 305 pub const RepoFilesRoute = struct { 306 name: Array(repo_identity_max_len), 307 ref_kind: ?RefOrOid = null, 308 ref_value: Array(ref_route_max_len) = .{}, 309 path: Array(repo_route_max_len) = .{}, 310 // the selected file's first visible line (1-based; 0 = unset). 311 line: usize = 0, 312 }; 313 314 pub const RepoCommitsRoute = struct { 315 name: Array(repo_identity_max_len), 316 ref_or_oid: ?RefOrOid = null, 317 value: Array(ref_route_max_len) = .{}, 318 // what the pane shows for the commit the log walks from. 319 content: Content = .{ .diff = .{} }, 320 321 // a diff window and the message are alternatives, so the window's 322 // params can't be named alongside the message. 323 pub const Content = union(enum) { 324 diff: struct { 325 // the hunk index the window starts at. 326 start: usize = 0, 327 // the file the diff is filtered to ("" = every file). 328 path: Array(repo_route_max_len) = .{}, 329 }, 330 message, 331 }; 332 }; 333 334 pub const RepoEventsRoute = struct { 335 name: Array(repo_identity_max_len), 336 view: EventsView = .active, 337 kind: ?evt.EventKind = null, 338 selected: Array(evt.event_id_size * 2) = .{}, 339 }; 340 341 // build a `.repo_files` route (a null ref_kind = the bare default-branch 342 // root). null if the result doesn't fit the inline name. 343 pub fn repoFilesRoute(identity: []const u8, ref_kind: ?RefOrOid, ref_value: []const u8, dir: []const u8, line: usize) ?RoutablePage { 344 if (ref_kind == null and (ref_value.len != 0 or dir.len != 0)) return null; 345 if (ref_kind != null and ref_value.len == 0 and dir.len != 0) return null; 346 return .{ .repo_files = .{ 347 .name = Array(repo_identity_max_len).from(identity) orelse return null, 348 .ref_kind = ref_kind, 349 .ref_value = Array(ref_route_max_len).from(ref_value) orelse return null, 350 .path = Array(repo_route_max_len).from(dir) orelse return null, 351 .line = line, 352 } }; 353 } 354 355 // build a `.repo_commits` route (a null ref_or_oid = the default branch). 356 // always carries the `commits` marker so the bare route doesn't collide 357 // with the files root. a non-empty `path` filters the diff pane to that 358 // file and requires a ref. 359 pub fn repoCommitsRoute(identity: []const u8, ref_or_oid: ?RefOrOid, value: []const u8, start: usize, path: []const u8) ?RoutablePage { 360 if (ref_or_oid == null and (value.len != 0 or path.len != 0)) return null; 361 return .{ .repo_commits = .{ 362 .name = Array(repo_identity_max_len).from(identity) orelse return null, 363 .ref_or_oid = ref_or_oid, 364 .value = Array(ref_route_max_len).from(value) orelse return null, 365 .content = .{ .diff = .{ 366 .start = start, 367 .path = Array(repo_route_max_len).from(path) orelse return null, 368 } }, 369 } }; 370 } 371 372 // build a `.repo_commits` route showing the ref/oid's commit message in 373 // full, which is the only content that page renders. 374 pub fn repoCommitMessageRoute(identity: []const u8, ref_or_oid: RefOrOid, value: []const u8) ?RoutablePage { 375 if (value.len == 0) return null; 376 return .{ .repo_commits = .{ 377 .name = Array(repo_identity_max_len).from(identity) orelse return null, 378 .ref_or_oid = ref_or_oid, 379 .value = Array(ref_route_max_len).from(value) orelse return null, 380 .content = .message, 381 } }; 382 } 383 384 // build a `.repo_refs` route windowing `kind`'s column from the 385 // url-encoded ref name `from` ("" = the first window). 386 pub fn repoRefsRoute(identity: []const u8, kind: RefKind, from: []const u8) ?RoutablePage { 387 return .{ .repo_refs = .{ 388 .name = Array(repo_route_max_len).from(identity) orelse return null, 389 .kind = kind, 390 .from = Array(ref_route_max_len).from(from) orelse return null, 391 } }; 392 } 393 394 // build the events list or a window rooted at one event. 395 pub fn repoEventsRoute(identity: []const u8, view: EventsView, kind: ?evt.EventKind, selected: []const u8) ?RoutablePage { 396 if ((kind == null) != (selected.len == 0)) return null; 397 return .{ .repo_events = .{ 398 .name = Array(repo_identity_max_len).from(identity) orelse return null, 399 .view = view, 400 .kind = kind, 401 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 402 } }; 403 } 404 405 // build a `.repo_issues` route for "owner/name" (identity) showing 406 // `status`'s list, filtered to the url-encoded `tag` ("" = unfiltered) and 407 // rooted at the issue with hex event id `selected` ("" = the first window). 408 pub fn repoIssuesRoute(identity: []const u8, status: evt.Issue.Status, tag: []const u8, selected: []const u8) ?RoutablePage { 409 return .{ .repo_issues = .{ 410 .name = Array(repo_route_max_len).from(identity) orelse return null, 411 .tag = Array(issue_tag_route_max_len).from(tag) orelse return null, 412 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 413 .view = switch (status) { 414 .open => .open, 415 .closed => .closed, 416 }, 417 } }; 418 } 419 420 pub fn repoPatchesRoute(identity: []const u8, status: evt.Patch.Status, tag: []const u8, selected: []const u8) ?RoutablePage { 421 return .{ .repo_patches = .{ 422 .name = Array(repo_route_max_len).from(identity) orelse return null, 423 .tag = Array(patch_tag_route_max_len).from(tag) orelse return null, 424 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 425 .view = switch (status) { 426 .open => .open, 427 .closed => .closed, 428 .merged => .merged, 429 }, 430 } }; 431 } 432 433 pub fn repoPatchesDraftsRoute(identity: []const u8) ?RoutablePage { 434 return .{ .repo_patches = .{ 435 .name = Array(repo_route_max_len).from(identity) orelse return null, 436 .view = .drafts, 437 } }; 438 } 439 440 pub fn repoDiscussionsRoute(identity: []const u8, tag: []const u8, selected: []const u8) ?RoutablePage { 441 return .{ .repo_discussions = .{ 442 .name = Array(repo_route_max_len).from(identity) orelse return null, 443 .tag = Array(discussion_tag_route_max_len).from(tag) orelse return null, 444 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 445 } }; 446 } 447 448 // build the default list route for a thread event kind. 449 pub fn repoThreadRoute(kind: evt.EventKind, identity: []const u8, tag: []const u8, selected: []const u8) ?RoutablePage { 450 return switch (kind) { 451 .issue => repoIssuesRoute(identity, .open, tag, selected), 452 .patch => repoPatchesRoute(identity, .open, tag, selected), 453 .discuss => repoDiscussionsRoute(identity, tag, selected), 454 else => null, 455 }; 456 } 457 458 // build a selected thread route at one of its comment windows. 459 pub fn repoThreadCommentsRoute(kind: evt.EventKind, identity: []const u8, selected: []const u8, start: usize) ?RoutablePage { 460 var route = repoThreadRoute(kind, identity, "", selected) orelse return null; 461 switch (route) { 462 .repo_issues => |*thread| thread.comments_start = start, 463 .repo_patches => |*thread| thread.comments_start = start, 464 .repo_discussions => |*thread| thread.comments_start = start, 465 else => unreachable, 466 } 467 return route; 468 } 469 470 // build a comment permalink route at one of its immediate-reply windows. 471 pub fn repoThreadCommentRoute(kind: evt.EventKind, identity: []const u8, thread_id: []const u8, comment_id: []const u8, start: usize) ?RoutablePage { 472 if (thread_id.len == 0 or comment_id.len == 0) return null; 473 var route = repoThreadCommentsRoute(kind, identity, thread_id, start) orelse return null; 474 const comment = Array(evt.event_id_size * 2).from(comment_id) orelse return null; 475 switch (route) { 476 .repo_issues => |*thread| thread.comment = comment, 477 .repo_patches => |*thread| thread.comment = comment, 478 .repo_discussions => |*thread| thread.comment = comment, 479 else => unreachable, 480 } 481 return route; 482 } 483 484 // build the form route for replying to a thread or one of its comments. 485 pub fn repoThreadCommentNewRoute(kind: evt.EventKind, identity: []const u8, thread_id: []const u8, parent_id: []const u8) ?RoutablePage { 486 if (thread_id.len == 0) return null; 487 var route = repoThreadCommentsRoute(kind, identity, thread_id, 0) orelse return null; 488 const parent_event_id = Array(evt.event_id_size * 2).from(parent_id) orelse return null; 489 switch (route) { 490 .repo_issues => |*thread| { 491 thread.comment = parent_event_id; 492 thread.view = .new_comment; 493 }, 494 .repo_patches => |*thread| { 495 thread.comment = parent_event_id; 496 thread.view = .new_comment; 497 }, 498 .repo_discussions => |*thread| { 499 thread.comment = parent_event_id; 500 thread.view = .new_comment; 501 }, 502 else => unreachable, 503 } 504 return route; 505 } 506 507 // build the form route for editing a comment. 508 pub fn repoThreadCommentEditRoute(kind: evt.EventKind, identity: []const u8, thread_id: []const u8, comment_id: []const u8) ?RoutablePage { 509 var route = repoThreadCommentRoute(kind, identity, thread_id, comment_id, 0) orelse return null; 510 switch (route) { 511 .repo_issues => |*thread| thread.view = .edit_comment, 512 .repo_patches => |*thread| thread.view = .edit_comment, 513 .repo_discussions => |*thread| thread.view = .edit_comment, 514 else => unreachable, 515 } 516 return route; 517 } 518 519 // build the confirmation route for removing a thread or comment. 520 pub fn repoThreadRemoveRoute(kind: evt.EventKind, identity: []const u8, thread_id: []const u8, comment_id: []const u8) ?RoutablePage { 521 var route = if (comment_id.len == 0) 522 repoThreadCommentsRoute(kind, identity, thread_id, 0) orelse return null 523 else 524 repoThreadCommentRoute(kind, identity, thread_id, comment_id, 0) orelse return null; 525 switch (route) { 526 .repo_issues => |*thread| thread.view = .remove, 527 .repo_patches => |*thread| thread.view = .remove, 528 .repo_discussions => |*thread| thread.view = .remove, 529 else => unreachable, 530 } 531 return route; 532 } 533 534 // build a thread tags route, keeping its url-encoded tag filter. 535 pub fn repoThreadTagsRoute(kind: evt.EventKind, identity: []const u8, tag: []const u8) ?RoutablePage { 536 var route = repoThreadRoute(kind, identity, tag, "") orelse return null; 537 switch (route) { 538 .repo_issues => |*thread| thread.view = .tags, 539 .repo_patches => |*thread| thread.view = .tags, 540 .repo_discussions => |*thread| thread.view = .tags, 541 else => unreachable, 542 } 543 return route; 544 } 545 546 // build a new-thread form route. 547 pub fn repoThreadNewRoute(kind: evt.EventKind, identity: []const u8) ?RoutablePage { 548 var route = repoThreadRoute(kind, identity, "", "") orelse return null; 549 switch (route) { 550 .repo_issues => |*thread| thread.view = .new, 551 .repo_patches => |*thread| thread.view = .new, 552 .repo_discussions => |*thread| thread.view = .new, 553 else => unreachable, 554 } 555 return route; 556 } 557 558 // build the edit form route for a thread. 559 pub fn repoThreadEditRoute(kind: evt.EventKind, identity: []const u8, selected: []const u8) ?RoutablePage { 560 if (selected.len == 0) return null; 561 var route = repoThreadRoute(kind, identity, "", selected) orelse return null; 562 switch (route) { 563 .repo_issues => |*thread| thread.view = .edit, 564 .repo_patches => |*thread| thread.view = .edit, 565 .repo_discussions => |*thread| thread.view = .edit, 566 else => unreachable, 567 } 568 return route; 569 } 570 571 // build a route showing a thread's whole description. 572 pub fn repoThreadDescriptionRoute(kind: evt.EventKind, identity: []const u8, selected: []const u8) ?RoutablePage { 573 if (selected.len == 0) return null; 574 var route = repoThreadRoute(kind, identity, "", selected) orelse return null; 575 switch (route) { 576 .repo_issues => |*thread| thread.view = .description, 577 .repo_patches => |*thread| thread.view = .description, 578 .repo_discussions => |*thread| thread.view = .description, 579 else => unreachable, 580 } 581 return route; 582 } 583 584 // build a `.repo_issues` route showing the conflicts list, rooted at the 585 // issue with hex event id `start` ("" = the first window). 586 pub fn repoIssuesConflictsRoute(identity: []const u8, start: []const u8) ?RoutablePage { 587 return .{ .repo_issues = .{ 588 .name = Array(repo_route_max_len).from(identity) orelse return null, 589 .selected = Array(evt.event_id_size * 2).from(start) orelse return null, 590 .view = .conflicts, 591 } }; 592 } 593 594 // build a `.repo_issues` route showing the conflict resolve form for the 595 // issue with hex event id `selected`; `theirs` is the comma-separated list 596 // of fields prefilled from their side. 597 pub fn repoIssuesResolveRoute(identity: []const u8, selected: []const u8, theirs: []const u8) ?RoutablePage { 598 if (selected.len == 0) return null; 599 return .{ .repo_issues = .{ 600 .name = Array(repo_route_max_len).from(identity) orelse return null, 601 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 602 .theirs = Array(theirs_route_max_len).from(theirs) orelse return null, 603 .view = .resolve, 604 } }; 605 } 606 607 pub fn repoPatchesConflictsRoute(identity: []const u8, start: []const u8) ?RoutablePage { 608 return .{ .repo_patches = .{ 609 .name = Array(repo_route_max_len).from(identity) orelse return null, 610 .selected = Array(evt.event_id_size * 2).from(start) orelse return null, 611 .view = .conflicts, 612 } }; 613 } 614 615 pub fn repoPatchesResolveRoute(identity: []const u8, selected: []const u8, theirs: []const u8) ?RoutablePage { 616 if (selected.len == 0) return null; 617 return .{ .repo_patches = .{ 618 .name = Array(repo_route_max_len).from(identity) orelse return null, 619 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 620 .theirs = Array(theirs_route_max_len).from(theirs) orelse return null, 621 .view = .resolve, 622 } }; 623 } 624 625 // an inline, owned array of data. keeping it in the route (rather than a 626 // borrowed slice) makes RoutablePage a plain value: it can be copied, stored 627 // in history, and serialized without any arena tracking. 628 pub fn Array(comptime max_len: usize) type { 629 return struct { 630 bytes: [max_len]u8 = undefined, 631 len: u16 = 0, 632 633 pub fn from(s: []const u8) ?Array(max_len) { 634 if (s.len > max_len) return null; 635 var name = Array(max_len){ .len = @intCast(s.len) }; 636 @memcpy(name.bytes[0..s.len], s); 637 return name; 638 } 639 640 pub fn slice(self: *const Array(max_len)) []const u8 { 641 return self.bytes[0..self.len]; 642 } 643 644 // round-trip as a json string instead of an array of numbers. 645 pub fn jsonStringify(self: *const Array(max_len), jw: anytype) !void { 646 try jw.write(self.slice()); 647 } 648 649 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !Array(max_len) { 650 const s = try std.json.innerParse([]const u8, allocator, source, options); 651 // ValueTooLong is std.json's error for an over-long field. 652 return from(s) orelse error.ValueTooLong; 653 } 654 }; 655 } 656 657 pub fn toUrl(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 658 return switch (self) { 659 .home_users => |start| if (start == 0) @as([]const u8, "/users") else try std.fmt.allocPrint(arena.allocator(), "/users/" ++ start_seg ++ "{d}", .{start}), 660 .home_repos => |start| if (start == 0) @as([]const u8, "/repos") else try std.fmt.allocPrint(arena.allocator(), "/repos/" ++ start_seg ++ "{d}", .{start}), 661 .home_settings => "/settings", 662 .home_auth => "/auth", 663 .user_repos => |u| if (u.start == 0) 664 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos", .{u.name.slice()}) 665 else 666 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos/" ++ start_seg ++ "{d}", .{ u.name.slice(), u.start }), 667 .user_forks => |u| if (u.start == 0) 668 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/forks", .{u.name.slice()}) 669 else 670 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/forks/" ++ start_seg ++ "{d}", .{ u.name.slice(), u.start }), 671 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name.slice()}), 672 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name.slice()}), 673 .repo_files => |f| blk: { 674 const prefix = try repoUrlPrefix(arena, f.name.slice()); 675 if (f.ref_kind == null and f.line == 0) break :blk if (prefix.len == 0) "/" else prefix; 676 var out: std.Io.Writer.Allocating = .init(arena.allocator()); 677 try out.writer.print("{s}/" ++ files_seg, .{prefix}); 678 if (f.ref_kind) |kind| if (f.ref_value.len != 0) try out.writer.print("/{s}:{s}", .{ @tagName(kind), f.ref_value.slice() }); 679 if (f.line != 0) try out.writer.print("/" ++ line_seg ++ "{d}", .{f.line}); 680 if (f.path.len != 0) try out.writer.print("/" ++ path_seg ++ "{s}", .{f.path.slice()}); 681 break :blk out.written(); 682 }, 683 .repo_commits => |c| blk: { 684 const prefix = try repoUrlPrefix(arena, c.name.slice()); 685 var out: std.Io.Writer.Allocating = .init(arena.allocator()); 686 try out.writer.print("{s}/" ++ commits_seg, .{prefix}); 687 if (c.ref_or_oid) |kind| if (c.value.len != 0) try out.writer.print("/{s}:{s}", .{ @tagName(kind), c.value.slice() }); 688 switch (c.content) { 689 .diff => |d| { 690 if (d.start != 0) try out.writer.print("/" ++ start_seg ++ "{d}", .{d.start}); 691 if (d.path.len != 0) try out.writer.print("/" ++ path_seg ++ "{s}", .{d.path.slice()}); 692 }, 693 .message => try out.writer.print("/" ++ message_seg, .{}), 694 } 695 break :blk out.written(); 696 }, 697 .repo_refs => |r| blk: { 698 const prefix = try repoUrlPrefix(arena, r.name.slice()); 699 break :blk if (r.from.len == 0) 700 try std.fmt.allocPrint(arena.allocator(), "{s}/refs", .{prefix}) 701 else 702 try std.fmt.allocPrint(arena.allocator(), "{s}/refs/{s}:{s}", .{ prefix, @tagName(r.kind), r.from.slice() }); 703 }, 704 .repo_issues => |i| blk: { 705 const prefix = try repoUrlPrefix(arena, i.name.slice()); 706 if (i.view == .edit) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/edit", .{ prefix, i.selected.slice() }); 707 if (i.view == .description) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/description", .{ prefix, i.selected.slice() }); 708 if (i.view == .resolve) break :blk if (i.theirs.len == 0) 709 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/resolve", .{ prefix, i.selected.slice() }) 710 else 711 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ theirs_seg ++ "{s}/resolve", .{ prefix, i.selected.slice(), i.theirs.slice() }); 712 if (i.view == .new_comment) break :blk if (i.comment.len == 0) 713 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/new", .{ prefix, i.selected.slice() }) 714 else 715 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ comment_seg ++ "{s}/new", .{ prefix, i.selected.slice(), i.comment.slice() }); 716 if (i.view == .edit_comment) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ comment_seg ++ "{s}/edit", .{ prefix, i.selected.slice(), i.comment.slice() }); 717 if (i.view == .remove) break :blk if (i.comment.len == 0) 718 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/remove", .{ prefix, i.selected.slice() }) 719 else 720 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ comment_seg ++ "{s}/remove", .{ prefix, i.selected.slice(), i.comment.slice() }); 721 if (i.view == .conflicts) break :blk if (i.selected.len == 0) 722 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/conflicts", .{prefix}) 723 else 724 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/" ++ start_seg ++ "{s}/conflicts", .{ prefix, i.selected.slice() }); 725 if (i.comment.len != 0) break :blk if (i.comments_start == 0) 726 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ comment_seg ++ "{s}", .{ prefix, i.selected.slice(), i.comment.slice() }) 727 else 728 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ comment_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, i.selected.slice(), i.comment.slice(), i.comments_start }); 729 if (i.selected.len != 0) break :blk if (i.comments_start == 0) 730 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}", .{ prefix, i.selected.slice() }) 731 else 732 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ issue_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, i.selected.slice(), i.comments_start }); 733 break :blk if (i.tag.len == 0) 734 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}", .{ prefix, @tagName(i.view) }) 735 else 736 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}/" ++ tag_filter_seg ++ "{s}", .{ prefix, @tagName(i.view), i.tag.slice() }); 737 }, 738 .repo_patches => |p| blk: { 739 const prefix = try repoUrlPrefix(arena, p.name.slice()); 740 if (p.view == .edit) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/edit", .{ prefix, p.selected.slice() }); 741 if (p.view == .description) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/description", .{ prefix, p.selected.slice() }); 742 if (p.view == .resolve) break :blk if (p.theirs.len == 0) 743 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/resolve", .{ prefix, p.selected.slice() }) 744 else 745 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ theirs_seg ++ "{s}/resolve", .{ prefix, p.selected.slice(), p.theirs.slice() }); 746 if (p.view == .new_comment) break :blk if (p.comment.len == 0) 747 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/new", .{ prefix, p.selected.slice() }) 748 else 749 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ comment_seg ++ "{s}/new", .{ prefix, p.selected.slice(), p.comment.slice() }); 750 if (p.view == .edit_comment) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ comment_seg ++ "{s}/edit", .{ prefix, p.selected.slice(), p.comment.slice() }); 751 if (p.view == .remove) break :blk if (p.comment.len == 0) 752 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/remove", .{ prefix, p.selected.slice() }) 753 else 754 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ comment_seg ++ "{s}/remove", .{ prefix, p.selected.slice(), p.comment.slice() }); 755 if (p.view == .conflicts) break :blk if (p.selected.len == 0) 756 try std.fmt.allocPrint(arena.allocator(), "{s}/patches/conflicts", .{prefix}) 757 else 758 try std.fmt.allocPrint(arena.allocator(), "{s}/patches/" ++ start_seg ++ "{s}/conflicts", .{ prefix, p.selected.slice() }); 759 if (p.comment.len != 0) break :blk if (p.comments_start == 0) 760 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ comment_seg ++ "{s}", .{ prefix, p.selected.slice(), p.comment.slice() }) 761 else 762 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ comment_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, p.selected.slice(), p.comment.slice(), p.comments_start }); 763 if (p.selected.len != 0) break :blk if (p.comments_start == 0) 764 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}", .{ prefix, p.selected.slice() }) 765 else 766 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ patch_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, p.selected.slice(), p.comments_start }); 767 break :blk if (p.tag.len == 0) 768 try std.fmt.allocPrint(arena.allocator(), "{s}/patches/{s}", .{ prefix, @tagName(p.view) }) 769 else 770 try std.fmt.allocPrint(arena.allocator(), "{s}/patches/{s}/" ++ tag_filter_seg ++ "{s}", .{ prefix, @tagName(p.view), p.tag.slice() }); 771 }, 772 .repo_discussions => |t| blk: { 773 const prefix = try repoUrlPrefix(arena, t.name.slice()); 774 if (t.view == .edit) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/edit", .{ prefix, t.selected.slice() }); 775 if (t.view == .description) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/description", .{ prefix, t.selected.slice() }); 776 if (t.view == .new_comment) break :blk if (t.comment.len == 0) 777 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/new", .{ prefix, t.selected.slice() }) 778 else 779 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ comment_seg ++ "{s}/new", .{ prefix, t.selected.slice(), t.comment.slice() }); 780 if (t.view == .edit_comment) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ comment_seg ++ "{s}/edit", .{ prefix, t.selected.slice(), t.comment.slice() }); 781 if (t.view == .remove) break :blk if (t.comment.len == 0) 782 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/remove", .{ prefix, t.selected.slice() }) 783 else 784 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ comment_seg ++ "{s}/remove", .{ prefix, t.selected.slice(), t.comment.slice() }); 785 if (t.comment.len != 0) break :blk if (t.comments_start == 0) 786 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ comment_seg ++ "{s}", .{ prefix, t.selected.slice(), t.comment.slice() }) 787 else 788 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ comment_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, t.selected.slice(), t.comment.slice(), t.comments_start }); 789 if (t.selected.len != 0) break :blk if (t.comments_start == 0) 790 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}", .{ prefix, t.selected.slice() }) 791 else 792 try std.fmt.allocPrint(arena.allocator(), "{s}/" ++ discuss_seg ++ "{s}/" ++ start_seg ++ "{d}", .{ prefix, t.selected.slice(), t.comments_start }); 793 break :blk if (t.tag.len == 0) 794 try std.fmt.allocPrint(arena.allocator(), "{s}/discussions/{s}", .{ prefix, @tagName(t.view) }) 795 else 796 try std.fmt.allocPrint(arena.allocator(), "{s}/discussions/{s}/" ++ tag_filter_seg ++ "{s}", .{ prefix, @tagName(t.view), t.tag.slice() }); 797 }, 798 .repo_events => |e| blk: { 799 const prefix = try repoUrlPrefix(arena, e.name.slice()); 800 break :blk if (e.kind) |kind| 801 try std.fmt.allocPrint(arena.allocator(), "{s}/event:{s}/kind:{s}", .{ prefix, e.selected.slice(), @tagName(kind) }) 802 else 803 try std.fmt.allocPrint(arena.allocator(), "{s}/events/{s}", .{ prefix, @tagName(e.view) }); 804 }, 805 .repo_settings => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/settings", .{try repoUrlPrefix(arena, name.slice())}), 806 .repo_auth => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{try repoUrlPrefix(arena, name.slice())}), 807 }; 808 } 809 810 pub fn fromUrl(path: []const u8) ?RoutablePage { 811 if (std.mem.eql(u8, path, "/")) return default; 812 if (path.len < 2 or path[0] != '/') return null; 813 var segments = std.mem.splitScalar(u8, path[1..], '/'); 814 const first = segments.next() orelse return null; 815 if (std.mem.eql(u8, first, "users")) return .{ .home_users = listStart(&segments) orelse return null }; 816 if (std.mem.eql(u8, first, "repos")) return .{ .home_repos = listStart(&segments) orelse return null }; 817 if (std.mem.eql(u8, first, "settings")) return if (segments.next() == null) .home_settings else null; 818 if (std.mem.eql(u8, first, "auth")) return if (segments.next() == null) .home_auth else null; 819 // "user/<name>[/repos[/start:<n>]|/settings|/auth]" 820 if (std.mem.eql(u8, first, "user")) { 821 const name = segments.next() orelse return null; 822 if (name.len == 0) return null; 823 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 824 const sub = segments.next() orelse return .{ .user_repos = .{ .name = parsed } }; 825 if (std.mem.eql(u8, sub, "repos")) return .{ .user_repos = .{ .name = parsed, .start = listStart(&segments) orelse return null } }; 826 if (std.mem.eql(u8, sub, "forks")) return .{ .user_forks = .{ .name = parsed, .start = listStart(&segments) orelse return null } }; 827 if (std.mem.eql(u8, sub, "settings")) return if (segments.next() == null) .{ .user_settings = parsed } else null; 828 if (std.mem.eql(u8, sub, "auth")) return if (segments.next() == null) .{ .user_auth = parsed } else null; 829 return null; // unknown sub-path 830 } 831 // "repo/<username>/<reponame>[/<tab tail>]"; the bare pair is the 832 // files root 833 if (std.mem.eql(u8, first, "repo")) { 834 const rest = segments.rest(); // "username/reponame[/...]" 835 const owner = segments.next() orelse return null; 836 const repo_name = segments.next() orelse return null; 837 // reject an empty username or reponame 838 if (owner.len == 0 or repo_name.len == 0) return null; 839 const pair = rest[0 .. owner.len + 1 + repo_name.len]; // "username/reponame" 840 if (segments.peek() != null) { 841 return repoSubRoute(pair, segments.rest()); 842 } 843 return repoFilesRoute(pair, null, "", "", 0); 844 } 845 return null; 846 } 847 848 // parse a local-mode url, which elides the "/repo/<owner>/<name>" prefix: 849 // "/" is the files root and the sub-paths follow directly. 850 pub fn fromUrlLocal(path: []const u8) ?RoutablePage { 851 if (std.mem.eql(u8, path, "/")) return repoFilesRoute("", null, "", "", 0); 852 if (path.len < 2 or path[0] != '/') return null; 853 return repoSubRoute("", path[1..]); 854 } 855 856 // the url prefix for a repo route's identity: "/repo/<identity>", or "" 857 // when the identity is elided. 858 fn repoUrlPrefix(arena: *std.heap.ArenaAllocator, identity: []const u8) ![]const u8 { 859 if (identity.len == 0) return ""; 860 return std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{identity}); 861 } 862 863 // true when the page builds at its content height on the web, letting the 864 // browser scroll the whole page, rather than being pinned to the viewport 865 pub fn fullHeight(self: RoutablePage) bool { 866 return switch (self) { 867 .repo_issues => |i| i.view == .resolve, 868 .repo_patches => |p| p.view == .resolve, 869 else => false, 870 }; 871 } 872 873 // the "owner/name" a repo route carries, null for any other route. the 874 // result borrows the route, so it must outlive the slice. 875 pub fn repoIdentity(self: *const RoutablePage) ?[]const u8 { 876 return switch (self.*) { 877 .repo_files => |*f| f.name.slice(), 878 .repo_commits => |*c| c.name.slice(), 879 .repo_refs => |*r| r.name.slice(), 880 .repo_issues => |*i| i.name.slice(), 881 .repo_patches => |*p| p.name.slice(), 882 .repo_discussions => |*t| t.name.slice(), 883 .repo_events => |*e| e.name.slice(), 884 .repo_settings, .repo_auth => |*name| name.slice(), 885 else => null, 886 }; 887 } 888 889 // the route this route's page lands on, with no tab or params: the users 890 // list, a user's repos, or a repo's files root. 891 pub fn pageRoot(self: RoutablePage) RoutablePage { 892 return switch (self.parent()) { 893 .home => .default, 894 .user => switch (self) { 895 .user_repos => |u| .{ .user_repos = .{ .name = u.name } }, 896 .user_forks => |u| .{ .user_repos = .{ .name = u.name } }, 897 .user_settings, .user_auth => |name| .{ .user_repos = .{ .name = name } }, 898 else => self, 899 }, 900 // every repo route stores the same identity, so it always fits 901 .repo => repoFilesRoute(self.repoIdentity() orelse return self, null, "", "", 0) orelse self, 902 }; 903 } 904 905 pub fn parent(self: RoutablePage) PageKind { 906 return switch (self) { 907 .home_users, .home_repos, .home_settings, .home_auth => .home, 908 .user_repos, .user_forks, .user_settings, .user_auth => .user, 909 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_patches, .repo_discussions, .repo_events, .repo_settings, .repo_auth => .repo, 910 }; 911 } 912 913 // the dir a trailing "path:<dir>" names: the raw remainder ("" when 914 // absent, null when malformed) 915 fn pathValue(rest: []const u8) ?[]const u8 { 916 if (rest.len == 0) return ""; 917 if (!std.mem.startsWith(u8, rest, path_seg)) return null; 918 const dir = rest[path_seg.len..]; 919 return if (dir.len == 0) null else dir; 920 } 921 922 // a list route's tail: at most a "start:<n>" param, null on anything else 923 fn listStart(segments: *std.mem.SplitIterator(u8, .scalar)) ?usize { 924 var params = Params{}; 925 const word = params.scanTail(segments) catch return null; 926 if (word != null or !params.only(&.{.start})) return null; 927 return params.start(); 928 } 929 930 // parse the sub-path after a repo route's identity ("" for a local 931 // route): a tab keyword followed by "key:value" params in any order, plus 932 // the files tab's trailing "path:<dir>". 933 fn repoSubRoute(pair: []const u8, sub: []const u8) ?RoutablePage { 934 var segments = std.mem.splitScalar(u8, sub, '/'); 935 const tab = segments.next() orelse return null; 936 var params = Params{}; 937 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; 938 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; 939 if (std.mem.eql(u8, tab, "refs")) { 940 const word = params.scanTail(&segments) catch return null; 941 if (word != null or !params.only(&.{ .branch, .tag })) return null; 942 const ref = (params.ref() catch return null) orelse return repoRefsRoute(pair, .branch, ""); 943 const kind = std.meta.stringToEnum(RefKind, @tagName(ref.kind)) orelse return null; 944 return repoRefsRoute(pair, kind, ref.value); 945 } 946 if (std.mem.startsWith(u8, tab, issue_seg)) { 947 const issue_id = tab[issue_seg.len..]; 948 if (issue_id.len == 0) return null; 949 if (segments.peek()) |tail| { 950 if (std.mem.startsWith(u8, tail, comment_seg)) { 951 _ = segments.next(); 952 const comment_id = tail[comment_seg.len..]; 953 if (comment_id.len == 0) return null; 954 const word = params.scanTail(&segments) catch return null; 955 if (word) |last| { 956 if (!params.only(&.{})) return null; 957 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.issue, pair, issue_id, comment_id); 958 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.issue, pair, issue_id, comment_id); 959 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.issue, pair, issue_id, comment_id); 960 return null; 961 } 962 if (!params.only(&.{.start})) return null; 963 return repoThreadCommentRoute(.issue, pair, issue_id, comment_id, params.start() orelse return null); 964 } 965 } 966 const word = params.scanTail(&segments) catch return null; 967 if (word) |tail| { 968 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.issue, pair, issue_id, "") else null; 969 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.issue, pair, issue_id) else null; 970 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.issue, pair, issue_id, "") else null; 971 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.issue, pair, issue_id) else null; 972 if (std.mem.eql(u8, tail, "resolve")) { 973 if (!params.only(&.{.theirs})) return null; 974 return repoIssuesResolveRoute(pair, issue_id, params.values.get(.theirs) orelse ""); 975 } 976 return null; 977 } 978 if (!params.only(&.{.start})) return null; 979 return repoThreadCommentsRoute(.issue, pair, issue_id, params.start() orelse return null); 980 } 981 if (std.mem.startsWith(u8, tab, patch_seg)) { 982 const patch_id = tab[patch_seg.len..]; 983 if (patch_id.len == 0) return null; 984 if (segments.peek()) |tail| { 985 if (std.mem.startsWith(u8, tail, comment_seg)) { 986 _ = segments.next(); 987 const comment_id = tail[comment_seg.len..]; 988 if (comment_id.len == 0) return null; 989 const word = params.scanTail(&segments) catch return null; 990 if (word) |last| { 991 if (!params.only(&.{})) return null; 992 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.patch, pair, patch_id, comment_id); 993 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.patch, pair, patch_id, comment_id); 994 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.patch, pair, patch_id, comment_id); 995 return null; 996 } 997 if (!params.only(&.{.start})) return null; 998 return repoThreadCommentRoute(.patch, pair, patch_id, comment_id, params.start() orelse return null); 999 } 1000 } 1001 const word = params.scanTail(&segments) catch return null; 1002 if (word) |tail| { 1003 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.patch, pair, patch_id, "") else null; 1004 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.patch, pair, patch_id) else null; 1005 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.patch, pair, patch_id, "") else null; 1006 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.patch, pair, patch_id) else null; 1007 if (std.mem.eql(u8, tail, "resolve")) { 1008 if (!params.only(&.{.theirs})) return null; 1009 return repoPatchesResolveRoute(pair, patch_id, params.values.get(.theirs) orelse ""); 1010 } 1011 return null; 1012 } 1013 if (!params.only(&.{.start})) return null; 1014 return repoThreadCommentsRoute(.patch, pair, patch_id, params.start() orelse return null); 1015 } 1016 if (std.mem.startsWith(u8, tab, discuss_seg)) { 1017 const discussion_id = tab[discuss_seg.len..]; 1018 if (discussion_id.len == 0) return null; 1019 if (segments.peek()) |tail| { 1020 if (std.mem.startsWith(u8, tail, comment_seg)) { 1021 _ = segments.next(); 1022 const comment_id = tail[comment_seg.len..]; 1023 if (comment_id.len == 0) return null; 1024 const word = params.scanTail(&segments) catch return null; 1025 if (word) |last| { 1026 if (!params.only(&.{})) return null; 1027 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.discuss, pair, discussion_id, comment_id); 1028 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.discuss, pair, discussion_id, comment_id); 1029 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.discuss, pair, discussion_id, comment_id); 1030 return null; 1031 } 1032 if (!params.only(&.{.start})) return null; 1033 return repoThreadCommentRoute(.discuss, pair, discussion_id, comment_id, params.start() orelse return null); 1034 } 1035 } 1036 const word = params.scanTail(&segments) catch return null; 1037 if (word) |tail| { 1038 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.discuss, pair, discussion_id, "") else null; 1039 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.discuss, pair, discussion_id) else null; 1040 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.discuss, pair, discussion_id, "") else null; 1041 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.discuss, pair, discussion_id) else null; 1042 return null; 1043 } 1044 if (!params.only(&.{.start})) return null; 1045 return repoThreadCommentsRoute(.discuss, pair, discussion_id, params.start() orelse return null); 1046 } 1047 if (std.mem.eql(u8, tab, "issues")) { 1048 // the word is a list view; a filter with neither is never emitted. 1049 const word = params.scanTail(&segments) catch return null; 1050 const tag_value = params.values.get(.tag) orelse ""; 1051 const w = word orelse return if (params.only(&.{})) repoIssuesRoute(pair, .open, "", "") else null; 1052 // the conflicts list windows by an issue id, not a number, so it 1053 // reads the start param raw 1054 if (std.mem.eql(u8, w, "conflicts")) { 1055 if (!params.only(&.{.start})) return null; 1056 return repoIssuesConflictsRoute(pair, params.values.get(.start) orelse ""); 1057 } 1058 if (!params.only(&.{.tag})) return null; 1059 if (std.meta.stringToEnum(evt.Issue.Status, w)) |status| return repoIssuesRoute(pair, status, tag_value, ""); 1060 if (std.mem.eql(u8, w, "tags")) return repoThreadTagsRoute(.issue, pair, tag_value); 1061 if (std.mem.eql(u8, w, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.issue, pair) else null; 1062 return null; 1063 } 1064 if (std.mem.eql(u8, tab, "patches")) { 1065 const word = params.scanTail(&segments) catch return null; 1066 const tag_value = params.values.get(.tag) orelse ""; 1067 const view = word orelse return if (params.only(&.{})) repoPatchesRoute(pair, .open, "", "") else null; 1068 if (std.mem.eql(u8, view, "conflicts")) { 1069 if (!params.only(&.{.start})) return null; 1070 return repoPatchesConflictsRoute(pair, params.values.get(.start) orelse ""); 1071 } 1072 if (!params.only(&.{.tag})) return null; 1073 if (std.meta.stringToEnum(evt.Patch.Status, view)) |status| return repoPatchesRoute(pair, status, tag_value, ""); 1074 if (std.mem.eql(u8, view, "tags")) return repoThreadTagsRoute(.patch, pair, tag_value); 1075 if (std.mem.eql(u8, view, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.patch, pair) else null; 1076 if (std.mem.eql(u8, view, "drafts")) return if (tag_value.len == 0) repoPatchesDraftsRoute(pair) else null; 1077 return null; 1078 } 1079 if (std.mem.eql(u8, tab, "discussions")) { 1080 const word = params.scanTail(&segments) catch return null; 1081 const tag_value = params.values.get(.tag) orelse ""; 1082 const view = word orelse return if (params.only(&.{})) repoDiscussionsRoute(pair, "", "") else null; 1083 if (!params.only(&.{.tag})) return null; 1084 if (std.mem.eql(u8, view, "recent")) return repoDiscussionsRoute(pair, tag_value, ""); 1085 if (std.mem.eql(u8, view, "tags")) return repoThreadTagsRoute(.discuss, pair, tag_value); 1086 if (std.mem.eql(u8, view, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.discuss, pair) else null; 1087 return null; 1088 } 1089 if (std.mem.eql(u8, tab, "events")) { 1090 const view = if (segments.next()) |word| 1091 std.meta.stringToEnum(EventsView, word) orelse return null 1092 else 1093 .active; 1094 return if (segments.next() == null) repoEventsRoute(pair, view, null, "") else null; 1095 } 1096 if (std.mem.startsWith(u8, tab, "event:")) { 1097 const event_id = tab["event:".len..]; 1098 const kind_segment = segments.next() orelse return null; 1099 if (!std.mem.startsWith(u8, kind_segment, "kind:")) return null; 1100 const kind = std.meta.stringToEnum(evt.EventKind, kind_segment["kind:".len..]) orelse return null; 1101 if (event_id.len == 0 or segments.next() != null) return null; 1102 return repoEventsRoute(pair, .active, kind, event_id); 1103 } 1104 if (std.mem.eql(u8, tab, files_seg)) { 1105 params.scanPairs(&segments) catch return null; 1106 if (!params.only(&.{ .line, .branch, .tag, .object })) return null; 1107 const line = params.line() orelse return null; 1108 const dir = pathValue(segments.rest()) orelse return null; 1109 const ref = (params.ref() catch return null) orelse 1110 return if (dir.len == 0) repoFilesRoute(pair, null, "", "", line) else null; 1111 return repoFilesRoute(pair, ref.kind, ref.value, dir, line); 1112 } 1113 if (std.mem.eql(u8, tab, commits_seg)) { 1114 params.scanPairs(&segments) catch return null; 1115 if (!params.only(&.{ .start, .branch, .tag, .object })) return null; 1116 const start = params.start() orelse return null; 1117 const ref = (params.ref() catch return null) orelse { 1118 const file = pathValue(segments.rest()) orelse return null; 1119 return if (file.len == 0) repoCommitsRoute(pair, null, "", start, "") else null; 1120 }; 1121 // the message page names its commit and nothing else 1122 if (std.mem.eql(u8, segments.rest(), message_seg)) 1123 return if (start == 0) repoCommitMessageRoute(pair, ref.kind, ref.value) else null; 1124 const file = pathValue(segments.rest()) orelse return null; 1125 return repoCommitsRoute(pair, ref.kind, ref.value, start, file); 1126 } 1127 return null; // unknown sub-path 1128 } 1129 1130 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 1131 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1132 return switch (a) { 1133 .home_users => |a_start| a_start == b.home_users, 1134 .home_repos => |a_start| a_start == b.home_repos, 1135 .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, 1136 .user_forks => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_forks.name.slice()) and a_u.start == b.user_forks.start, 1137 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 1138 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 1139 .repo_files => |a_f| std.mem.eql(u8, a_f.name.slice(), b.repo_files.name.slice()) and 1140 a_f.ref_kind == b.repo_files.ref_kind and 1141 std.mem.eql(u8, a_f.ref_value.slice(), b.repo_files.ref_value.slice()) and 1142 std.mem.eql(u8, a_f.path.slice(), b.repo_files.path.slice()) and 1143 a_f.line == b.repo_files.line, 1144 .repo_commits => |a_c| std.mem.eql(u8, a_c.name.slice(), b.repo_commits.name.slice()) and 1145 a_c.ref_or_oid == b.repo_commits.ref_or_oid and 1146 std.mem.eql(u8, a_c.value.slice(), b.repo_commits.value.slice()) and 1147 switch (a_c.content) { 1148 .diff => |a_d| switch (b.repo_commits.content) { 1149 .diff => |b_d| a_d.start == b_d.start and std.mem.eql(u8, a_d.path.slice(), b_d.path.slice()), 1150 .message => false, 1151 }, 1152 .message => std.meta.activeTag(b.repo_commits.content) == .message, 1153 }, 1154 .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()), 1155 .repo_issues => |a_i| std.mem.eql(u8, a_i.name.slice(), b.repo_issues.name.slice()) and 1156 std.mem.eql(u8, a_i.tag.slice(), b.repo_issues.tag.slice()) and 1157 std.mem.eql(u8, a_i.selected.slice(), b.repo_issues.selected.slice()) and 1158 std.mem.eql(u8, a_i.theirs.slice(), b.repo_issues.theirs.slice()) and 1159 a_i.view == b.repo_issues.view and 1160 a_i.comments_start == b.repo_issues.comments_start and 1161 std.mem.eql(u8, a_i.comment.slice(), b.repo_issues.comment.slice()), 1162 .repo_discussions => |a_t| std.mem.eql(u8, a_t.name.slice(), b.repo_discussions.name.slice()) and 1163 std.mem.eql(u8, a_t.tag.slice(), b.repo_discussions.tag.slice()) and 1164 std.mem.eql(u8, a_t.selected.slice(), b.repo_discussions.selected.slice()) and 1165 a_t.view == b.repo_discussions.view and 1166 a_t.comments_start == b.repo_discussions.comments_start and 1167 std.mem.eql(u8, a_t.comment.slice(), b.repo_discussions.comment.slice()), 1168 .repo_patches => |a_p| std.mem.eql(u8, a_p.name.slice(), b.repo_patches.name.slice()) and 1169 std.mem.eql(u8, a_p.tag.slice(), b.repo_patches.tag.slice()) and 1170 std.mem.eql(u8, a_p.selected.slice(), b.repo_patches.selected.slice()) and 1171 std.mem.eql(u8, a_p.theirs.slice(), b.repo_patches.theirs.slice()) and 1172 a_p.view == b.repo_patches.view and 1173 a_p.comments_start == b.repo_patches.comments_start and 1174 std.mem.eql(u8, a_p.comment.slice(), b.repo_patches.comment.slice()), 1175 .repo_events => |a_e| std.mem.eql(u8, a_e.name.slice(), b.repo_events.name.slice()) and 1176 a_e.view == b.repo_events.view and 1177 a_e.kind == b.repo_events.kind and 1178 std.mem.eql(u8, a_e.selected.slice(), b.repo_events.selected.slice()), 1179 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 1180 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 1181 else => true, 1182 }; 1183 } 1184 1185 // true when following a link from `b` to `a` (both repo routes) should reload 1186 // rather than stay in page 1187 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 1188 if (a.parent() != .repo or b.parent() != .repo) return false; 1189 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 1190 a.repo_refs.from.len == 0 and b.repo_refs.from.len == 0) 1191 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 1192 return !a.eql(b); 1193 } 1194 1195 // true when `a` and `b` are the same user paginated to a different repos 1196 // window. switching between a user's tabs is in-page (header-handled), so 1197 // only a changed `start` on the repos list navigates. 1198 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 1199 return switch (a) { 1200 .user_repos => |aa| switch (b) { 1201 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 1202 else => false, 1203 }, 1204 .user_forks => |aa| switch (b) { 1205 .user_forks => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 1206 else => false, 1207 }, 1208 else => false, 1209 }; 1210 } 1211 1212 // true when `a` and `b` are the same home list tab paginated to a different 1213 // window. switching between the users/repos tabs is in-page (the home page 1214 // holds both lists), so only a changed `after` on the same tab navigates. 1215 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 1216 return switch (a) { 1217 .home_users => |aa| switch (b) { 1218 .home_users => |bb| aa != bb, 1219 else => false, 1220 }, 1221 .home_repos => |aa| switch (b) { 1222 .home_repos => |bb| aa != bb, 1223 else => false, 1224 }, 1225 else => false, 1226 }; 1227 } 1228 }; 1229 1230 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 1231 fn isUnreserved(c: u8) bool { 1232 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1233 } 1234 1235 // percent-encode a ref name for use as a single url path segment. 1236 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 1237 var out: std.Io.Writer.Allocating = .init(aa); 1238 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 1239 return out.written(); 1240 } 1241 1242 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 1243 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1244 return struct { 1245 pub const hex_len = hash.hexLen(repo_opts.hash); 1246 1247 // the concrete ref/oid (a null request resolves to the default branch) 1248 ref_or_oid: RoutablePage.RefOrOid, 1249 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 1250 // the route layer — which splits on '/' — stores them encoded). duped 1251 // into `aa`. 1252 value: []const u8, 1253 // the commit oid it points at 1254 oid: [hex_len]u8, 1255 1256 const Self = @This(); 1257 1258 // resolve a requested ref/oid (null = the repo's default branch) to a 1259 // concrete ref/oid plus the commit oid it points at. `requested_value` is 1260 // the url-encoded form (as it appears in the route). null when it doesn't 1261 // resolve (an unknown branch/tag, or a malformed/unknown oid). 1262 pub fn init( 1263 repo: *rp.Repo(repo_kind, repo_opts), 1264 io: std.Io, 1265 aa: std.mem.Allocator, 1266 requested_ref_or_oid: ?RoutablePage.RefOrOid, 1267 requested_value: []const u8, 1268 ) !?Self { 1269 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 1270 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 1271 var value: []const u8 = if (requested_ref_or_oid == null) 1272 requested_value 1273 else 1274 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 1275 // no ref named: fall back to HEAD's branch (or its oid when detached). 1276 if (requested_ref_or_oid == null) { 1277 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1278 if (repo.head(io, &head_buf)) |head| switch (head) { 1279 .ref => |r| { 1280 ref_or_oid = .branch; 1281 value = r.name; 1282 }, 1283 .oid => |o| { 1284 ref_or_oid = .object; 1285 value = o; 1286 }, 1287 } else |_| {} 1288 } 1289 1290 var oid: [hex_len]u8 = undefined; 1291 switch (ref_or_oid) { 1292 .object => { 1293 if (value.len != hex_len) return null; 1294 @memcpy(&oid, value); 1295 }, 1296 .branch, .tag => { 1297 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 1298 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 1299 }, 1300 } 1301 // store url-encoded so the route layer can hold the value verbatim. 1302 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 1303 } 1304 }; 1305 } 1306 1307 // where a repo page reads its on-disk repo from 1308 pub const RepoSource = struct { 1309 path: []const u8, 1310 repo_kind: rp.RepoKind, 1311 // the user's global git config, so local mode picks up their identity and 1312 // their signing and ssh settings. null on the server paths, which must not 1313 // read whoever runs the server. 1314 global_config_path: ?[]const u8 = null, 1315 1316 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 1317 return .{ .path = self.path, .global_config_path = self.global_config_path }; 1318 } 1319 }; 1320 1321 // events created in local mode have no account behind them, so the commit 1322 // author comes from the repo's config, which the global config feeds into. 1323 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 1324 1325 pub fn localAuthor( 1326 src: RepoSource, 1327 io: std.Io, 1328 allocator: std.mem.Allocator, 1329 arena: *std.heap.ArenaAllocator, 1330 ) !evt.CommitAuthor { 1331 switch (src.repo_kind) { 1332 inline else => |repo_kind| { 1333 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 1334 defer any_repo.deinit(io, allocator); 1335 1336 switch (any_repo) { 1337 inline else => |*repo| { 1338 var config = try repo.listConfig(io, allocator); 1339 defer config.deinit(); 1340 1341 const user = config.sections.get("user") orelse return local_author_fallback; 1342 const name = user.get("name") orelse return local_author_fallback; 1343 const email = user.get("email") orelse return local_author_fallback; 1344 return .{ 1345 .name = try arena.allocator().dupe(u8, name), 1346 .email = try arena.allocator().dupe(u8, email), 1347 }; 1348 }, 1349 } 1350 }, 1351 } 1352 } 1353 1354 // per-connection mutable state. each SSH session / web session / local TUI 1355 // run gets its own. 1356 pub const Session = struct { 1357 data: Data = .{}, 1358 // session-lifetime allocations: login/user_id, persisted prefs, queued 1359 // actions. lives as long as the connection. 1360 arena: *std.heap.ArenaAllocator, 1361 // current page's allocations: page data and the page-scoped strings widgets 1362 // build (form actions, links). owned by Nav, swapped on each navigation, so 1363 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 1364 // where a render is one-shot, this points at the same arena as `arena`. 1365 page_arena: *std.heap.ArenaAllocator, 1366 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 1367 // filesystem io and the path to <server>/repos, for opening on-disk repos 1368 // during page construction. both null on wasm, which has no filesystem and 1369 // rebuilds pages from the serialized snapshot rather than from disk. 1370 io: ?std.Io = null, 1371 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 1372 repos_dir: ?[]const u8 = null, 1373 // the single on-disk repo this session views, when running in local mode 1374 // (haxy invoked with no arguments inside a repo). null on the server paths, 1375 // which resolve repos from the admin db instead. 1376 local: ?RepoSource = null, 1377 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 1378 // focus id -> the live TextInput, refreshed each frame by the views that own 1379 // inputs. web/wasm form handling looks widgets up here by focus id. 1380 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 1381 // focus id -> the page-constant text the web overlay renders into an 1382 // input initially, refreshed each frame alongside `text_inputs`. never 1383 // the input's live content: the overlay html must not change as the 1384 // user types, or the diff in _setOverlay would rebuild the element. 1385 input_values: std.AutoHashMapUnmanaged(usize, []const u8) = .empty, 1386 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 1387 refresh_requested: bool = false, // set by input (ctrl+r) 1388 // a requested forward navigation. set this (via navigate) to move to a new 1389 // page; Nav.sync builds it and then copies it into current_page, clearing 1390 // this back to null. setting current_page directly only updates the url and 1391 // does not navigate. 1392 next_page: ?RoutablePage = null, 1393 is_terminal: bool = false, // true on remote SSH and local TUI 1394 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 1395 // url. null on the web itself (no footer there). 1396 web_port: ?u16 = null, 1397 // a host operation requested by a widget 1398 host_request: ?HostRequest = null, 1399 quit_requested: bool = false, 1400 1401 pub const HostRequest = union(enum) { 1402 show_copyable_text: []const u8, 1403 sync_events, 1404 }; 1405 1406 const Self = @This(); 1407 1408 // serializable data sent down to web client 1409 pub const Data = struct { 1410 user_id: ?[]const u8 = null, 1411 // the logged-in user's name, for the views that show it 1412 user_name: ?[]const u8 = null, 1413 // a transient outcome to surface from the last /login POST attempt 1414 login_failure: ?Home.Auth.Login.Failure = null, 1415 // a transient local event-sync error 1416 sync_failure: ?[]const u8 = null, 1417 current_page: RoutablePage = .default, 1418 // whether to render the ANSI art backdrop 1419 enable_ansi: bool = true, 1420 // the bound clone-service ports. absent in local mode, where clone urls 1421 // are not shown. 1422 clone_http_port: ?u16 = null, 1423 clone_ssh_port: ?u16 = null, 1424 // true when this session views a single local repo. unlike `local` 1425 // (the host-side filesystem source) this travels in the snapshot, so 1426 // the wasm side also parses elided link urls and hides the multi-user 1427 // chrome. 1428 is_local: bool = false, 1429 }; 1430 1431 // a user-initiated state change. widgets enqueue these on the session during 1432 // input instead of mutating state or touching the DB themselves; the host 1433 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1434 // side effects out of the widget tree and gives every render path one place to 1435 // turn a UI action into a state change + event. 1436 pub const Action = union(enum) { 1437 toggle_ansi, 1438 }; 1439 1440 pub fn init( 1441 arena: *std.heap.ArenaAllocator, 1442 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1443 data: Data, 1444 ) !Self { 1445 var session = Self{ 1446 .data = data, 1447 .arena = arena, 1448 // until a host swaps in a page-scoped arena (Nav does this), page 1449 // allocations land in the session arena. on the web path that's the 1450 // intended behavior, since the whole arena is per-request. 1451 .page_arena = arena, 1452 .admin_repo = repo, 1453 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1454 }; 1455 try session.loadUser(); 1456 return session; 1457 } 1458 1459 // load the logged-in user's name and persisted preferences from the db 1460 pub fn loadUser(self: *Self) !void { 1461 const user_id = self.data.user_id orelse return; 1462 const moment = self.haxy_moment orelse return; 1463 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1464 self.data.user_name = user.event.name; 1465 self.data.enable_ansi = user.event.enable_ansi; 1466 } 1467 } 1468 1469 // the commit author for an event this session creates, or null when it may 1470 // not create one 1471 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1472 if (self.data.is_local) { 1473 const src = self.local orelse return local_author_fallback; 1474 const io = self.io orelse return local_author_fallback; 1475 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1476 } 1477 const user_id = self.data.user_id orelse return null; 1478 const moment = self.haxy_moment orelse return null; 1479 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1480 return .{ .name = user.event.name, .email = user.event.email }; 1481 } 1482 1483 // queue an action for the host to drain this frame. 1484 pub fn push(self: *Self, action: Action) !void { 1485 try self.pending.append(self.arena.allocator(), action); 1486 } 1487 1488 // apply a single action's in-memory effect only (no persistence). 1489 fn apply(self: *Self, action: Action) void { 1490 switch (action) { 1491 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1492 } 1493 } 1494 1495 // drain the session's queued actions by applying them to the session. 1496 // used on the wasm path, which has no repo to persist to. 1497 pub fn applyPending(self: *Self) void { 1498 for (self.pending.items) |action| self.apply(action); 1499 self.pending.clearRetainingCapacity(); 1500 } 1501 1502 // drain the session's queued actions by applying them to the session and 1503 // writing them to the db 1504 pub fn applyAndWritePending( 1505 self: *Self, 1506 io: std.Io, 1507 allocator: std.mem.Allocator, 1508 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1509 ) !void { 1510 defer self.pending.clearRetainingCapacity(); 1511 for (self.pending.items) |action| { 1512 self.apply(action); 1513 switch (action) { 1514 .toggle_ansi => if (self.data.user_id) |user_id| { 1515 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1516 }, 1517 } 1518 } 1519 } 1520 1521 // reload the moment from the admin repo and re-read user preferences 1522 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1523 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1524 self.haxy_moment = moment; 1525 1526 const user_id = self.data.user_id orelse return; 1527 var arena = std.heap.ArenaAllocator.init(allocator); 1528 defer arena.deinit(); 1529 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1530 self.data.enable_ansi = user.event.enable_ansi; 1531 } 1532 } 1533 1534 // request a forward navigation to `route`; the host consumes next_page 1535 // (Nav.sync on the terminal, the wasm tick on the web). 1536 pub fn navigate(self: *Session, route: RoutablePage) !void { 1537 self.next_page = route; 1538 } 1539 }; 1540 1541 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1542 var nav = try Nav.init(allocator, session); 1543 defer nav.deinit(allocator); 1544 1545 var terminal = try term.Terminal.init(io, allocator); 1546 var terminal_live = true; 1547 defer if (terminal_live) terminal.deinit(io); 1548 1549 // set term as active so it will be properly cooked 1550 // when a panic/segfault happens 1551 term.setActive(&terminal); 1552 defer term.setActive(null); 1553 1554 var last_size = layout.Size{ .width = 0, .height = 0 }; 1555 var last_grid = try Grid.init(allocator, last_size); 1556 defer last_grid.deinit(); 1557 1558 while (!terminal.shouldQuit()) { 1559 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 1560 1561 // process any inputs. 1562 // 1563 // if the grid didn't change, then first do a blocking 1564 // read, so the thread will sleep until further input. 1565 // after that, all remaining reads are non-blocking so 1566 // we can process the rest of the queued inputs. 1567 // 1568 // if the grid *did* change, then only do non-blocking 1569 // reads. we do not want to sleep the thread because 1570 // there may be an animation that requires more looping. 1571 var blocking = !grid_changed; 1572 while (try terminal.readKey(io, blocking)) |key| { 1573 blocking = false; 1574 try inputKey(allocator, &nav.root, key, session); 1575 } 1576 1577 if (session.host_request) |request| { 1578 session.host_request = null; 1579 switch (request) { 1580 .show_copyable_text => |copyable_text| { 1581 term.setActive(null); 1582 terminal.deinit(io); 1583 terminal_live = false; 1584 showCopyableText(io, copyable_text) catch |show_err| { 1585 terminal = try term.Terminal.init(io, allocator); 1586 terminal_live = true; 1587 term.setActive(&terminal); 1588 return show_err; 1589 }; 1590 terminal = try term.Terminal.init(io, allocator); 1591 terminal_live = true; 1592 term.setActive(&terminal); 1593 last_size = .{ .width = 0, .height = 0 }; 1594 }, 1595 .sync_events => { 1596 try nav.root.build(allocator, .{ 1597 .min_size = .{ .width = null, .height = null }, 1598 .max_size = .{ .width = last_size.width, .height = last_size.height }, 1599 }, nav.root.getFocus()); 1600 _ = try terminal.render(&nav.root, &last_grid, &last_size); 1601 try Repo.Events.performSync(allocator, session); 1602 }, 1603 } 1604 } 1605 1606 // persist queued actions when there's a repo; local mode has none, 1607 // so just apply in-memory 1608 if (repo_maybe) |repo| { 1609 try session.applyAndWritePending(io, allocator, repo); 1610 // reload so the next navigation builds its page from the current moment 1611 try session.reloadMoment(allocator, repo); 1612 } else { 1613 session.applyPending(); 1614 } 1615 1616 // reconcile navigation: forward to a new page, or back on escape. 1617 try nav.sync(allocator, session); 1618 1619 // the quit button (on the quit tab) asks the host to tear down. 1620 if (session.quit_requested) terminal.requestQuit(); 1621 1622 try nav.root.build(allocator, .{ 1623 .min_size = .{ .width = null, .height = null }, 1624 .max_size = .{ .width = last_size.width, .height = last_size.height }, 1625 }, nav.root.getFocus()); 1626 } 1627 } 1628 1629 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 1630 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 1631 null 1632 else 1633 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 1634 defer if (tty) |file| file.close(io); 1635 1636 const input = if (tty) |file| file else std.Io.File.stdin(); 1637 const output = if (tty) |file| file else std.Io.File.stdout(); 1638 1639 var write_buf: [1024]u8 = undefined; 1640 var writer = output.writer(io, &write_buf); 1641 try writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 1642 try writer.interface.flush(); 1643 1644 var read_buf: [1]u8 = undefined; 1645 var reader = input.reader(io, &read_buf); 1646 while (true) { 1647 const byte = try reader.interface.takeByte(); 1648 if (byte == '\r' or byte == '\n') return; 1649 } 1650 } 1651 1652 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 1653 switch (key) { 1654 // request a navigation pop; the host's Nav.sync goes back a page, or 1655 // quits when there's no history left. 1656 .escape => session.nav_back = true, 1657 .ctrl => |letter| switch (letter) { 1658 'r' => session.refresh_requested = true, 1659 else => try root.input(allocator, key, root.getFocus()), 1660 }, 1661 .enter => { 1662 const root_focus = root.getFocus(); 1663 if (root_focus.grandchild_id) |gid| { 1664 // follow a cross-page link 1665 if (crossPageLink(root_focus, gid, session.data)) |route| { 1666 return session.navigate(route); 1667 } 1668 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 1669 } 1670 try root.input(allocator, key, root_focus); 1671 }, 1672 .mouse => |mouse| { 1673 if (mouse.action == .press and mouse.action.press == .left) { 1674 const root_focus = root.getFocus(); 1675 var clicked: ?usize = null; 1676 var iter = root_focus.children.iterator(); 1677 while (iter.next()) |entry| { 1678 const child = entry.value_ptr.*; 1679 if (!child.focus.focusable) continue; 1680 const r = child.rect; 1681 if (mouse.x >= r.x and mouse.y >= r.y and 1682 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 1683 { 1684 clicked = entry.key_ptr.*; 1685 break; 1686 } 1687 } 1688 if (clicked) |focus_id| { 1689 // follow a cross-page link 1690 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 1691 return session.navigate(route); 1692 } 1693 if (rawLink(root_focus, focus_id)) |url| { 1694 if (!mouse.ctrl) try requestRawLink(session, url); 1695 return; 1696 } 1697 root_focus.setFocus(focus_id); 1698 } 1699 // forward the press into the widget tree so buttons (and any 1700 // future click-aware widgets) can react. widgets that don't 1701 // care about presses ignore it. 1702 try root.input(allocator, key, root.getFocus()); 1703 } else { 1704 try root.input(allocator, key, root.getFocus()); 1705 } 1706 }, 1707 else => try root.input(allocator, key, root.getFocus()), 1708 } 1709 } 1710 1711 // a link to bytes the server serves directly rather than to a page route, so 1712 // it never resolves to a RoutablePage 1713 pub const raw_link_prefix = "ax:"; 1714 1715 // a button the web overlay covers with a file picker that posts the chosen 1716 // file to the url after the prefix 1717 pub const file_input_prefix = "file:"; 1718 1719 // a submit button that overrides its enclosing form's action 1720 pub const submit_action_prefix = "submit:"; 1721 1722 // the url an `ax:` link points at, or null for anything else. a host that 1723 // suppresses the anchor's own navigation needs this to follow the link. 1724 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 1725 const child = root_focus.children.get(focus_id) orelse return null; 1726 const custom = switch (child.focus.kind) { 1727 .custom => |c| c, 1728 else => return null, 1729 }; 1730 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 1731 return custom[raw_link_prefix.len..]; 1732 } 1733 1734 fn requestRawLink(session: *Session, url: []const u8) !void { 1735 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 1736 } 1737 1738 fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 1739 return if (session.web_port) |port| 1740 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 1741 else 1742 path; 1743 } 1744 1745 // if the focus target at focus_id is an `a:` link that should navigate (a 1746 // different parent page, or a different files directory within the repo page), 1747 // return its route; otherwise null. lets a host turn a click / enter on such a 1748 // link into a navigation rather than a focus change. 1749 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1750 const current = data.current_page; 1751 const child = root_focus.children.get(focus_id) orelse return null; 1752 const custom = switch (child.focus.kind) { 1753 .custom => |c| c, 1754 else => return null, 1755 }; 1756 const a_prefix = "a:"; 1757 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 1758 const path = custom[a_prefix.len..]; 1759 // local sessions build (and parse) links with the repo identity elided 1760 const route = (if (data.is_local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path)) orelse return null; 1761 // a link to a different parent page always navigates; within a page, a 1762 // files-directory / commits-page / list-window change navigates while tab 1763 // links stay in-page (header-handled). 1764 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 1765 return null; 1766 } 1767 1768 // a display author, resolved against the admin db at read time 1769 pub const Author = union(enum) { 1770 unknown, 1771 email: []const u8, // an email no user matches 1772 user_name: []const u8, 1773 1774 // the commit author line's email, resolved like initFromEmail 1775 pub fn init( 1776 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1777 arena: *std.heap.ArenaAllocator, 1778 author_line: []const u8, 1779 ) !Author { 1780 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 1781 } 1782 1783 // from a record's stored author email: it resolves to the user currently 1784 // holding it, else stays the email. the result is allocated in `arena`, 1785 // so the email may borrow transient memory. 1786 pub fn initFromEmail( 1787 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1788 arena: *std.heap.ArenaAllocator, 1789 author_email: ?[]const u8, 1790 ) !Author { 1791 const email = author_email orelse return .unknown; 1792 if (haxy_moment) |moment| { 1793 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 1794 return .{ .user_name = user.event.name }; 1795 } 1796 } 1797 return .{ .email = try arena.allocator().dupe(u8, email) }; 1798 } 1799 }; 1800 1801 // the "a:" link to user `name`'s page. 1802 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 1803 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 1804 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 1805 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 1806 } 1807 1808 // a focusable " author " box showing `author`, linking to their user page 1809 // when it is a known user 1810 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox(Widget) { 1811 const text = switch (author) { 1812 .unknown => "", 1813 .email, .user_name => |t| t, 1814 }; 1815 var tb = try wgt.TextBox(Widget).init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 1816 errdefer tb.deinit(allocator); 1817 tb.getFocus().focusable = true; 1818 switch (author) { 1819 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 1820 else => {}, 1821 } 1822 return tb; 1823 } 1824 1825 // native-TUI navigation 1826 pub const Nav = struct { 1827 root: Widget, 1828 route: RoutablePage, 1829 // backs the current page (its Page data and the page-scoped strings its 1830 // widgets build). owned here, swapped on each navigation. session.page_arena 1831 // tracks whichever of these is current so widgets allocate into it. 1832 arena: *std.heap.ArenaAllocator, 1833 history: std.ArrayList(Entry), 1834 1835 // each retained page keeps its own arena, freed when the page leaves the 1836 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 1837 // long-lived session from accumulating every page it ever visited. 1838 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 1839 1840 // cap on retained back-history so the chain can't grow memory without bound 1841 const max_history: usize = 16; 1842 1843 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 1844 const arena = try allocator.create(std.heap.ArenaAllocator); 1845 arena.* = std.heap.ArenaAllocator.init(allocator); 1846 errdefer { 1847 arena.deinit(); 1848 allocator.destroy(arena); 1849 } 1850 1851 session.page_arena = arena; 1852 const route = session.data.current_page; 1853 1854 const page = try arena.allocator().create(Page); 1855 page.* = try Page.init(arena, session, route); 1856 return .{ 1857 .root = try initRoot(allocator, page, session), 1858 .route = route, 1859 .arena = arena, 1860 .history = .empty, 1861 }; 1862 } 1863 1864 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 1865 self.root.deinit(allocator); 1866 freeArena(allocator, self.arena); 1867 for (self.history.items) |*entry| { 1868 entry.root.deinit(allocator); 1869 freeArena(allocator, entry.arena); 1870 } 1871 self.history.deinit(allocator); 1872 } 1873 1874 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 1875 arena.deinit(); 1876 allocator.destroy(arena); 1877 } 1878 1879 // reconcile the displayed root with the session's navigation state. a 1880 // forward nav (current_page moved to a different parent page) pushes the 1881 // current root and builds the new page in a fresh arena; a back request 1882 // frees the current page and restores the previous one. when escape is 1883 // pressed with no history left we switch to the quit tab instead of quitting. 1884 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 1885 // refresh: rebuild the current page in place from a current moment 1886 if (session.refresh_requested) { 1887 session.refresh_requested = false; 1888 if (session.haxy_moment != null or session.local != null) { 1889 const arena = try allocator.create(std.heap.ArenaAllocator); 1890 arena.* = std.heap.ArenaAllocator.init(allocator); 1891 errdefer freeArena(allocator, arena); 1892 1893 session.page_arena = arena; 1894 1895 const route = session.data.current_page; 1896 const page = try arena.allocator().create(Page); 1897 page.* = try Page.init(arena, session, route); 1898 const new_root = try initRoot(allocator, page, session); 1899 1900 self.root.deinit(allocator); 1901 freeArena(allocator, self.arena); 1902 self.root = new_root; 1903 self.route = route; 1904 self.arena = arena; 1905 } 1906 return; 1907 } 1908 1909 if (session.nav_back) { 1910 session.nav_back = false; 1911 if (self.history.pop()) |entry| { 1912 self.root.deinit(allocator); 1913 freeArena(allocator, self.arena); 1914 self.root = entry.root; 1915 self.route = entry.route; 1916 self.arena = entry.arena; 1917 session.page_arena = entry.arena; 1918 session.data.current_page = entry.route; 1919 return; 1920 } 1921 // nothing to go back to; switch to the quit confirmation 1922 const root_focus = self.root.getFocus(); 1923 var iter = root_focus.children.iterator(); 1924 while (iter.next()) |entry| { 1925 switch (entry.value_ptr.focus.kind) { 1926 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 1927 root_focus.setFocus(entry.key_ptr.*); 1928 // a Stack only builds its selected child, so the quit 1929 // button isn't in the focus tree until a build runs with 1930 // the quit tab selected. build once, then send a 1931 // synthetic arrow_down to drop focus from the tab onto 1932 // the button so it's ready to confirm. 1933 try self.root.build(allocator, .{ 1934 .min_size = .{ .width = null, .height = 40 }, 1935 .max_size = .{ .width = 80, .height = null }, 1936 }, root_focus); 1937 try self.root.input(allocator, .arrow_down, root_focus); 1938 break; 1939 }, 1940 else => {}, 1941 } 1942 } 1943 return; 1944 } 1945 1946 // forward navigation: navigate() set next_page to the page to move to (a 1947 // cross-page link or tab change crossing pages) 1948 if (session.next_page) |route| { 1949 session.next_page = null; 1950 if (session.haxy_moment == null and session.local == null) return; 1951 // the page we navigated to becomes the current page 1952 session.data.current_page = route; 1953 1954 const arena = try allocator.create(std.heap.ArenaAllocator); 1955 arena.* = std.heap.ArenaAllocator.init(allocator); 1956 errdefer freeArena(allocator, arena); 1957 1958 session.page_arena = arena; 1959 1960 const page = try arena.allocator().create(Page); 1961 page.* = try Page.init(arena, session, route); 1962 const new_root = try initRoot(allocator, page, session); 1963 1964 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 1965 // drop the oldest entry (freeing its widget tree and arena) once over cap 1966 if (self.history.items.len > max_history) { 1967 var oldest = self.history.orderedRemove(0); 1968 oldest.root.deinit(allocator); 1969 freeArena(allocator, oldest.arena); 1970 } 1971 self.root = new_root; 1972 self.route = route; 1973 self.arena = arena; 1974 } 1975 } 1976 }; 1977 1978 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 1979 const page_widget: Widget = switch (page.*) { 1980 .home => |*p| .{ .home = try .init(allocator, p, session) }, 1981 .user => |*p| .{ .user = try .init(allocator, p, session) }, 1982 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 1983 }; 1984 1985 const demon_art = @embedFile("embed/demon.ans"); 1986 1987 // on the TUI/SSH, the page sits above a one-row footer showing the url 1988 var root = if (session.is_terminal) blk: { 1989 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 1990 errdefer box.deinit(allocator); 1991 const bg_id = bg_blk: { 1992 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 1993 errdefer background.deinit(allocator); 1994 const id = background.getFocus().id; 1995 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 1996 break :bg_blk id; 1997 }; 1998 { 1999 var footer = try Footer.init(allocator, session); 2000 errdefer footer.deinit(allocator); 2001 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2002 } 2003 box.getFocus().child_id = bg_id; 2004 break :blk Widget{ .box = box }; 2005 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 2006 errdefer root.deinit(allocator); 2007 2008 // input-owning views build their TextInputs in init — so reset the 2009 // focus-id -> *TextInput map here 2010 session.text_inputs.clearRetainingCapacity(); 2011 session.input_values.clearRetainingCapacity(); 2012 2013 try root.build(allocator, .{ 2014 .min_size = .{ .width = null, .height = 40 }, 2015 .max_size = .{ .width = 100, .height = null }, 2016 }, root.getFocus()); 2017 2018 return root; 2019 } 2020 2021 pub const Widget = union(enum) { 2022 text: wgt.Text(Widget), 2023 box: wgt.Box(Widget), 2024 text_box: wgt.TextBox(Widget), 2025 text_input: wgt.TextInput(Widget), 2026 scroll: wgt.Scroll(Widget), 2027 stack: wgt.Stack(Widget), 2028 flow_box: FlowBox, 2029 flow_box_scroll: FlowBox.Scroll, 2030 tag_flow: TagFlow, 2031 spacer: Spacer, 2032 center: Center, 2033 section_label: SectionLabel, 2034 submit_button: SubmitButton, 2035 background: AnsiBackground, 2036 home: Home.View, 2037 user: User.View, 2038 repo: Repo.View, 2039 quit: Quit.View, 2040 unauthorized: Unauthorized.View, 2041 title: Title.View, 2042 sub_title: SubTitle.View, 2043 home_header: Home.Header.View, 2044 user_header: User.Header.View, 2045 repo_header: Repo.Header.View, 2046 repo_files_header: Repo.Files.Header.View, 2047 repo_commits_header: Repo.Commits.Header.View, 2048 repo_issues_header: Repo.Issues.Header, 2049 repo_patches_header: Repo.Patches.Header, 2050 repo_discussions_header: Repo.Discussions.Header, 2051 repo_files: Repo.Files.View, 2052 repo_commits: Repo.Commits.View, 2053 repo_refs: Repo.Refs.View, 2054 repo_issues: Repo.Issues.View, 2055 repo_patches: Repo.Patches.View, 2056 repo_discussions: Repo.Discussions.View, 2057 repo_events_header: Repo.Events.Header.View, 2058 repo_events: Repo.Events.View, 2059 repo_comment: Repo.Comment.Item, 2060 clone_url: CloneUrl.View, 2061 home_users: Home.Users.View, 2062 home_repos: Home.Repos.View, 2063 auth_tab: Home.Header.AuthTab.View, 2064 home_settings: Home.Settings.View, 2065 home_auth: Home.Auth.View, 2066 footer: Footer, 2067 2068 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 2069 switch (self.*) { 2070 inline else => |*case| case.deinit(allocator), 2071 } 2072 } 2073 2074 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 2075 switch (self.*) { 2076 inline else => |*case| try case.build(allocator, constraint, root_focus), 2077 } 2078 } 2079 2080 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) anyerror!void { 2081 switch (self.*) { 2082 inline else => |*case| try case.input(allocator, key, root_focus), 2083 } 2084 } 2085 2086 pub fn clearGrid(self: *Widget) void { 2087 switch (self.*) { 2088 inline else => |*case| case.clearGrid(), 2089 } 2090 } 2091 2092 pub fn getGrid(self: Widget) ?Grid { 2093 switch (self) { 2094 inline else => |*case| return case.getGrid(), 2095 } 2096 } 2097 2098 pub fn getFocus(self: *Widget) *Focus { 2099 switch (self.*) { 2100 inline else => |*case| return case.getFocus(), 2101 } 2102 } 2103 }; 2104 2105 // move the focused row in `box` by `delta`, clamped to the ends, scrolling 2106 // `scroll` to keep it visible. 2107 pub fn moveRowFocus(box: *wgt.Box(Widget), scroll: *wgt.Scroll(Widget), root_focus: *Focus, delta: isize) void { 2108 const keys = box.children.keys(); 2109 if (keys.len == 0) return; 2110 const cur_id = box.getFocus().child_id orelse return; 2111 const cur: isize = @intCast(box.children.getIndex(cur_id) orelse return); 2112 const last: isize = @intCast(keys.len - 1); 2113 const next: usize = @intCast(std.math.clamp(cur + delta, 0, last)); 2114 if (next == @as(usize, @intCast(cur))) return; 2115 root_focus.setFocus(keys[next]); 2116 if (box.children.values()[next].rect) |rect| scroll.scrollToRect(rect); 2117 } 2118 2119 pub const FlowBox = struct { 2120 focus: *Focus, 2121 grid: ?Grid, 2122 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 2123 // backs each link item's `.custom` focus kind (e.g. "a:/user/foo"). reset 2124 // wholesale on each setItems so there's no per-string ownership to track. 2125 arena: std.heap.ArenaAllocator, 2126 // column count from the last build — FlowBox.Scroll.input uses it so arrow 2127 // up/down can step by a row's worth of items. 2128 last_cols: usize, 2129 options: Options, 2130 2131 const border_rows: usize = 2; 2132 2133 pub const Options = struct { 2134 cell_width: usize = 40, 2135 cell_height: usize = 3, 2136 }; 2137 2138 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 2139 return .{ 2140 .focus = try Focus.create(allocator, .container), 2141 .grid = null, 2142 .text_boxes = .empty, 2143 .arena = std.heap.ArenaAllocator.init(allocator), 2144 .last_cols = 1, 2145 .options = options, 2146 }; 2147 } 2148 2149 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 2150 self.focus.destroy(allocator); 2151 if (self.grid) |*grid| { 2152 grid.deinit(); 2153 self.grid = null; 2154 } 2155 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 2156 self.text_boxes.deinit(allocator); 2157 self.arena.deinit(); 2158 } 2159 2160 // one flow item: its display text plus an optional link. a non-empty `link` 2161 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 2162 // the web renderer turns into an anchor. 2163 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 2164 2165 // the text box copies the item text; links are copied into the arena, so the 2166 // caller's slices needn't outlive this call. 2167 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 2168 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 2169 self.text_boxes.clearAndFree(allocator); 2170 2171 // the old text boxes and their borrowed links are gone now, so the link 2172 // arena can be reclaimed. 2173 _ = self.arena.reset(.retain_capacity); 2174 const aa = self.arena.allocator(); 2175 2176 self.focus.clear(); 2177 self.focus.child_id = null; 2178 2179 for (items) |item| { 2180 var text_box = try wgt.TextBox(Widget).init(allocator, item.text, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 2181 errdefer text_box.deinit(allocator); 2182 text_box.getFocus().focusable = true; 2183 2184 if (item.link.len > 0) { 2185 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 2186 } 2187 2188 try self.text_boxes.append(allocator, text_box); 2189 } 2190 2191 if (self.text_boxes.items.len > 0) { 2192 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 2193 } 2194 } 2195 2196 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2197 self.clearGrid(); 2198 self.focus.clear(); 2199 2200 const cell_width = self.options.cell_width; 2201 const max_width = constraint.max_size.width orelse cell_width; 2202 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 2203 self.last_cols = cols; 2204 2205 const count = self.text_boxes.items.len; 2206 if (count == 0) return; 2207 const slot_height = self.options.cell_height + border_rows; 2208 if (slot_height == 0) return; 2209 2210 // build at the slot size so every text box fits a single grid cell 2211 for (self.text_boxes.items) |*tb| { 2212 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 2213 try tb.build(allocator, .{ 2214 .min_size = .{ .width = cell_width, .height = null }, 2215 .max_size = .{ .width = cell_width, .height = slot_height }, 2216 }, root_focus); 2217 } 2218 2219 const rows = (count + cols - 1) / cols; 2220 const content_height = rows * slot_height; 2221 const total_width = cols * cell_width; 2222 if (total_width == 0 or content_height == 0) return; 2223 2224 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 2225 errdefer grid.deinit(); 2226 2227 for (self.text_boxes.items, 0..) |*tb, i| { 2228 const tb_grid = tb.getGrid() orelse continue; 2229 const col = i % cols; 2230 const row = i / cols; 2231 const cell_x = col * cell_width; 2232 const cell_y = row * slot_height; 2233 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 2234 try grid.drawGrid(tb_grid, cell_x, cell_y); 2235 } 2236 2237 self.grid = grid; 2238 } 2239 2240 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2241 _ = self; 2242 _ = allocator; 2243 _ = key; 2244 _ = root_focus; 2245 } 2246 2247 pub fn clearGrid(self: *FlowBox) void { 2248 if (self.grid) |*grid| { 2249 grid.deinit(); 2250 self.grid = null; 2251 } 2252 for (self.text_boxes.items) |*tb| tb.clearGrid(); 2253 } 2254 2255 pub fn getGrid(self: FlowBox) ?Grid { 2256 return self.grid; 2257 } 2258 2259 pub fn getFocus(self: *FlowBox) *Focus { 2260 return self.focus; 2261 } 2262 2263 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 2264 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 2265 const slot_height = self.options.cell_height + border_rows; 2266 const col = index % self.last_cols; 2267 const row = index / self.last_cols; 2268 return .{ 2269 .x = @intCast(col * self.options.cell_width), 2270 .y = @intCast(row * slot_height), 2271 .size = .{ .width = self.options.cell_width, .height = slot_height }, 2272 }; 2273 } 2274 2275 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 2276 for (self.text_boxes.items, 0..) |tb, i| { 2277 if (tb.box.focus.id == focus_id) return i; 2278 } 2279 return null; 2280 } 2281 2282 pub const Scroll = struct { 2283 scroll: wgt.Scroll(Widget), 2284 2285 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 2286 var layout_inner = try FlowBox.init(allocator, options); 2287 errdefer layout_inner.deinit(allocator); 2288 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 2289 errdefer scroll.deinit(allocator); 2290 return .{ .scroll = scroll }; 2291 } 2292 2293 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 2294 self.scroll.deinit(allocator); 2295 } 2296 2297 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 2298 self.scroll.x = 0; 2299 self.scroll.y = 0; 2300 try self.inner().setItems(allocator, items); 2301 } 2302 2303 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2304 try self.scroll.build(allocator, constraint, root_focus); 2305 } 2306 2307 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2308 _ = allocator; 2309 const in = self.inner(); 2310 const child_id = in.focus.child_id orelse return; 2311 const current_index = in.indexOfFocusId(child_id) orelse return; 2312 const count = in.text_boxes.items.len; 2313 if (count == 0) return; 2314 const cols = in.last_cols; 2315 const slot_height = in.options.cell_height + FlowBox.border_rows; 2316 2317 var index = current_index; 2318 switch (key) { 2319 .arrow_up => index -|= cols, 2320 .arrow_down => if (index + cols < count) { 2321 index += cols; 2322 }, 2323 .arrow_left => index -|= 1, 2324 .arrow_right => if (index + 1 < count) { 2325 index += 1; 2326 }, 2327 .home => index = 0, 2328 .end => index = count - 1, 2329 .page_up => { 2330 if (self.scroll.grid) |grid| if (slot_height > 0) { 2331 const rows_per_page = grid.size.height / slot_height; 2332 index -|= rows_per_page * cols; 2333 }; 2334 }, 2335 .page_down => { 2336 if (self.scroll.grid) |grid| if (slot_height > 0) { 2337 const rows_per_page = grid.size.height / slot_height; 2338 index = @min(index + rows_per_page * cols, count - 1); 2339 }; 2340 }, 2341 // scroll wheel moves the focused cell by a full row so the 2342 // viewport (via scrollToRect) follows in row-sized steps, 2343 // matching how a scroll wheel feels in a grid view. 2344 .mouse => |mouse| switch (mouse.action) { 2345 .scroll => |dir| switch (dir) { 2346 .up => index -|= cols, 2347 .down => if (index + cols < count) { 2348 index += cols; 2349 }, 2350 }, 2351 else => {}, 2352 }, 2353 else => {}, 2354 } 2355 2356 if (index != current_index) { 2357 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 2358 if (in.cellRect(index)) |rect| { 2359 self.scroll.scrollToRect(rect); 2360 } 2361 } 2362 } 2363 2364 pub fn clearGrid(self: *Scroll) void { 2365 self.scroll.clearGrid(); 2366 } 2367 2368 pub fn getGrid(self: Scroll) ?Grid { 2369 return self.scroll.getGrid(); 2370 } 2371 2372 pub fn getFocus(self: *Scroll) *Focus { 2373 return self.scroll.getFocus(); 2374 } 2375 2376 pub fn getSelectedIndex(self: Scroll) ?usize { 2377 const in = self.scroll.child.flow_box; 2378 const child_id = in.focus.child_id orelse return null; 2379 return in.indexOfFocusId(child_id); 2380 } 2381 2382 fn inner(self: *Scroll) *FlowBox { 2383 return &self.scroll.child.flow_box; 2384 } 2385 }; 2386 }; 2387 2388 // a left-to-right flow of variable-width focusable items that wraps at the 2389 // available width, like words in a paragraph. unlike FlowBox there is no cell 2390 // grid: each item is as wide as its text. selection movement is driven by the 2391 // owning view via indexOfFocusId/verticalNeighbor. 2392 pub const TagFlow = struct { 2393 focus: *Focus, 2394 grid: ?Grid, 2395 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 2396 // last build's item rects (content space), for vertical navigation and 2397 // scroll-into-view. 2398 rects: std.ArrayList(layout.IRect), 2399 // backs each link item's `.custom` focus kind. 2400 arena: std.heap.ArenaAllocator, 2401 2402 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 2403 2404 pub fn init(allocator: std.mem.Allocator) !TagFlow { 2405 return .{ 2406 .focus = try Focus.create(allocator, .container), 2407 .grid = null, 2408 .text_boxes = .empty, 2409 .rects = .empty, 2410 .arena = std.heap.ArenaAllocator.init(allocator), 2411 }; 2412 } 2413 2414 pub fn deinit(self: *TagFlow, allocator: std.mem.Allocator) void { 2415 self.focus.destroy(allocator); 2416 if (self.grid) |*grid| { 2417 grid.deinit(); 2418 self.grid = null; 2419 } 2420 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 2421 self.text_boxes.deinit(allocator); 2422 self.rects.deinit(allocator); 2423 self.arena.deinit(); 2424 } 2425 2426 // the text box copies the item text; links are copied into the arena, so the 2427 // caller's slices needn't outlive this call. 2428 pub fn setItems(self: *TagFlow, allocator: std.mem.Allocator, items: []const Item) !void { 2429 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 2430 self.text_boxes.clearAndFree(allocator); 2431 2432 _ = self.arena.reset(.retain_capacity); 2433 const aa = self.arena.allocator(); 2434 2435 self.focus.clear(); 2436 self.focus.child_id = null; 2437 2438 for (items) |item| { 2439 var text_box = try wgt.TextBox(Widget).init(allocator, item.text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 2440 errdefer text_box.deinit(allocator); 2441 text_box.getFocus().focusable = true; 2442 2443 if (item.link.len > 0) { 2444 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 2445 } 2446 2447 try self.text_boxes.append(allocator, text_box); 2448 } 2449 2450 if (self.text_boxes.items.len > 0) { 2451 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 2452 } 2453 } 2454 2455 pub fn build(self: *TagFlow, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2456 self.clearGrid(); 2457 self.focus.clear(); 2458 2459 if (self.text_boxes.items.len == 0) return; 2460 const max_width = constraint.max_size.width orelse 80; 2461 if (max_width == 0) return; 2462 2463 // lay the items out left to right, wrapping to a new row when the next 2464 // one wouldn't fit. 2465 self.rects.clearRetainingCapacity(); 2466 var x: usize = 0; 2467 var y: usize = 0; 2468 var row_height: usize = 0; 2469 var total_width: usize = 0; 2470 for (self.text_boxes.items) |*tb| { 2471 try tb.build(allocator, .{ 2472 .min_size = .{ .width = null, .height = null }, 2473 .max_size = .{ .width = max_width, .height = null }, 2474 }, root_focus); 2475 const tb_grid_maybe = tb.getGrid(); 2476 const w: usize = if (tb_grid_maybe) |g| g.size.width else 0; 2477 const h: usize = if (tb_grid_maybe) |g| g.size.height else 0; 2478 if (x > 0 and x + w > max_width) { 2479 x = 0; 2480 y += row_height; 2481 row_height = 0; 2482 } 2483 try self.rects.append(allocator, .{ .x = @intCast(x), .y = @intCast(y), .size = .{ .width = w, .height = h } }); 2484 if (h > row_height) row_height = h; 2485 x += w; 2486 if (x > total_width) total_width = x; 2487 } 2488 2489 const total_height = y + row_height; 2490 if (total_width == 0 or total_height == 0) return; 2491 2492 var grid = try Grid.init(allocator, .{ .width = total_width, .height = total_height }); 2493 errdefer grid.deinit(); 2494 2495 for (self.text_boxes.items, self.rects.items) |*tb, rect| { 2496 const tb_grid = tb.getGrid() orelse continue; 2497 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, @intCast(rect.x), @intCast(rect.y)); 2498 try grid.drawGrid(tb_grid, @intCast(rect.x), @intCast(rect.y)); 2499 } 2500 2501 self.grid = grid; 2502 } 2503 2504 pub fn input(self: *TagFlow, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2505 _ = self; 2506 _ = allocator; 2507 _ = key; 2508 _ = root_focus; 2509 } 2510 2511 pub fn clearGrid(self: *TagFlow) void { 2512 if (self.grid) |*grid| { 2513 grid.deinit(); 2514 self.grid = null; 2515 } 2516 for (self.text_boxes.items) |*tb| tb.clearGrid(); 2517 } 2518 2519 pub fn getGrid(self: TagFlow) ?Grid { 2520 return self.grid; 2521 } 2522 2523 pub fn getFocus(self: *TagFlow) *Focus { 2524 return self.focus; 2525 } 2526 2527 pub fn indexOfFocusId(self: TagFlow, focus_id: usize) ?usize { 2528 for (self.text_boxes.items, 0..) |tb, i| { 2529 if (tb.box.focus.id == focus_id) return i; 2530 } 2531 return null; 2532 } 2533 2534 // the first item of the row below (when `downward`) or above, or null at 2535 // the flow's edge. items are laid out in order, so y is nondecreasing. 2536 pub fn rowStep(self: TagFlow, index: usize, downward: bool) ?usize { 2537 const rects = self.rects.items; 2538 if (index >= rects.len) return null; 2539 const cur_y = rects[index].y; 2540 if (downward) { 2541 for (rects[index + 1 ..], index + 1..) |r, i| { 2542 if (r.y > cur_y) return i; 2543 } 2544 return null; 2545 } 2546 // walk the earlier rows; the last one visited is the row above. 2547 var prev_first: ?usize = null; 2548 var i: usize = 0; 2549 while (i < rects.len and rects[i].y < cur_y) { 2550 prev_first = i; 2551 const y = rects[i].y; 2552 while (i < rects.len and rects[i].y == y) i += 1; 2553 } 2554 return prev_first; 2555 } 2556 }; 2557 2558 // an invisible widget that fills the horizontal space granted by its parent. 2559 // used inside Box(horiz) with a min_size so the box reserves space for the 2560 // children that follow, pushing them to the right. 2561 pub const Spacer = struct { 2562 focus: *Focus, 2563 grid: ?Grid, 2564 2565 pub fn init(allocator: std.mem.Allocator) !Spacer { 2566 return .{ 2567 .focus = try Focus.create(allocator, .container), 2568 .grid = null, 2569 }; 2570 } 2571 2572 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 2573 self.focus.destroy(allocator); 2574 if (self.grid) |*grid| { 2575 grid.deinit(); 2576 self.grid = null; 2577 } 2578 } 2579 2580 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2581 _ = root_focus; 2582 self.clearGrid(); 2583 const width = constraint.max_size.width orelse return; 2584 if (width == 0) return; 2585 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 2586 } 2587 2588 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2589 _ = self; 2590 _ = allocator; 2591 _ = key; 2592 _ = root_focus; 2593 } 2594 2595 pub fn clearGrid(self: *Spacer) void { 2596 if (self.grid) |*grid| { 2597 grid.deinit(); 2598 self.grid = null; 2599 } 2600 } 2601 2602 pub fn getGrid(self: Spacer) ?Grid { 2603 return self.grid; 2604 } 2605 2606 pub fn getFocus(self: *Spacer) *Focus { 2607 return self.focus; 2608 } 2609 }; 2610 2611 // a one-row, non-focusable status bar showing the current page's url 2612 pub const Footer = struct { 2613 focus: *Focus, 2614 grid: ?Grid, 2615 session: *Session, 2616 arena: std.heap.ArenaAllocator, 2617 url: []const u8 = "", 2618 url_width: usize = 0, 2619 2620 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 2621 return .{ 2622 .focus = try Focus.create(allocator, .container), 2623 .grid = null, 2624 .session = session, 2625 .arena = std.heap.ArenaAllocator.init(allocator), 2626 }; 2627 } 2628 2629 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 2630 self.focus.destroy(allocator); 2631 if (self.grid) |*grid| grid.deinit(); 2632 self.arena.deinit(); 2633 } 2634 2635 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2636 _ = root_focus; 2637 self.clearGrid(); 2638 const width = constraint.max_size.width orelse return; 2639 if (width == 0) return; 2640 2641 _ = self.arena.reset(.retain_capacity); 2642 self.url = ""; 2643 self.url_width = 0; 2644 const aa = self.arena.allocator(); 2645 const path = self.session.data.current_page.toUrl(&self.arena) catch return; 2646 const text = terminalWebUrl(aa, self.session, path) catch return; 2647 self.url = text; 2648 2649 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 2650 errdefer grid.deinit(); 2651 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 2652 var i: usize = 0; 2653 while (utf8.nextCodepointSlice()) |ch| { 2654 if (i == width) break; 2655 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 2656 i += 1; 2657 } 2658 self.url_width = i; 2659 self.grid = grid; 2660 } 2661 2662 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2663 _ = allocator; 2664 switch (key) { 2665 .mouse => |mouse| { 2666 if (mouse.ctrl or !inp.leftClickOn(root_focus, self.getFocus().id, mouse)) return; 2667 const rect = (root_focus.children.get(self.getFocus().id) orelse return).rect; 2668 if (mouse.x < rect.x + self.url_width) self.session.host_request = .{ .show_copyable_text = self.url }; 2669 }, 2670 else => {}, 2671 } 2672 } 2673 2674 pub fn clearGrid(self: *Footer) void { 2675 if (self.grid) |*grid| { 2676 grid.deinit(); 2677 self.grid = null; 2678 } 2679 } 2680 2681 pub fn getGrid(self: Footer) ?Grid { 2682 return self.grid; 2683 } 2684 2685 pub fn getFocus(self: *Footer) *Focus { 2686 return self.focus; 2687 } 2688 }; 2689 2690 // a single-child wrapper that builds the child at its natural size and 2691 // positions its grid in the middle of the area granted by the parent 2692 // a bordered label, indented past the content it precedes 2693 pub const SectionLabel = struct { 2694 box: wgt.Box(Widget), 2695 2696 pub fn init(allocator: std.mem.Allocator, content: []const u8) !SectionLabel { 2697 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 2698 errdefer box.deinit(allocator); 2699 2700 { 2701 var gap = try wgt.Text(Widget).init(allocator, " "); 2702 errdefer gap.deinit(allocator); 2703 try box.children.put(allocator, gap.getFocus().id, .{ .widget = .{ .text = gap }, .rect = null, .min_size = null }); 2704 } 2705 2706 { 2707 var tb = try wgt.TextBox(Widget).init(allocator, content, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 2708 errdefer tb.deinit(allocator); 2709 tb.getFocus().focusable = true; 2710 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 2711 } 2712 2713 box.getFocus().child_id = box.children.keys()[1]; 2714 return .{ .box = box }; 2715 } 2716 2717 pub fn deinit(self: *SectionLabel, allocator: std.mem.Allocator) void { 2718 self.box.deinit(allocator); 2719 } 2720 2721 pub fn build(self: *SectionLabel, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2722 try self.box.build(allocator, constraint, root_focus); 2723 } 2724 2725 pub fn input(self: *SectionLabel, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2726 _ = self; 2727 _ = allocator; 2728 _ = key; 2729 _ = root_focus; 2730 } 2731 2732 pub fn clearGrid(self: *SectionLabel) void { 2733 self.box.clearGrid(); 2734 } 2735 2736 pub fn getGrid(self: SectionLabel) ?Grid { 2737 return self.box.getGrid(); 2738 } 2739 2740 pub fn getFocus(self: *SectionLabel) *Focus { 2741 return self.box.getFocus(); 2742 } 2743 }; 2744 2745 // a submit button, indented past its form's content. the web overlay POSTs 2746 // the button's form; terminal hosts detect presses through `buttonId`. 2747 pub const SubmitButton = struct { 2748 box: wgt.Box(Widget), 2749 2750 pub fn init(allocator: std.mem.Allocator) !SubmitButton { 2751 return initLabeled(allocator, "submit"); 2752 } 2753 2754 pub fn initLabeled(allocator: std.mem.Allocator, label: []const u8) !SubmitButton { 2755 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 2756 errdefer box.deinit(allocator); 2757 2758 { 2759 var gap = try wgt.Text(Widget).init(allocator, " "); 2760 errdefer gap.deinit(allocator); 2761 try box.children.put(allocator, gap.getFocus().id, .{ .widget = .{ .text = gap }, .rect = null, .min_size = null }); 2762 } 2763 2764 { 2765 var button = try wgt.TextBox(Widget).init(allocator, label, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 2766 errdefer button.deinit(allocator); 2767 button.getFocus().focusable = true; 2768 // the renderer distinguishes plain clickables from buttons that 2769 // should POST to a server route by this kind. 2770 button.getFocus().kind = .{ .custom = "submit" }; 2771 try box.children.put(allocator, button.getFocus().id, .{ .widget = .{ .text_box = button }, .rect = null, .min_size = .{ .width = label.len + 2, .height = null } }); 2772 } 2773 2774 box.getFocus().child_id = box.children.keys()[1]; 2775 return .{ .box = box }; 2776 } 2777 2778 pub fn deinit(self: *SubmitButton, allocator: std.mem.Allocator) void { 2779 self.box.deinit(allocator); 2780 } 2781 2782 pub fn build(self: *SubmitButton, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2783 try self.box.build(allocator, constraint, root_focus); 2784 } 2785 2786 pub fn input(self: *SubmitButton, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2787 _ = self; 2788 _ = allocator; 2789 _ = key; 2790 _ = root_focus; 2791 } 2792 2793 pub fn clearGrid(self: *SubmitButton) void { 2794 self.box.clearGrid(); 2795 } 2796 2797 pub fn getGrid(self: SubmitButton) ?Grid { 2798 return self.box.getGrid(); 2799 } 2800 2801 pub fn getFocus(self: *SubmitButton) *Focus { 2802 return self.box.getFocus(); 2803 } 2804 2805 // the button's focus id, for click hit-testing 2806 pub fn buttonId(self: *const SubmitButton) usize { 2807 return self.box.children.keys()[1]; 2808 } 2809 }; 2810 2811 pub const Center = struct { 2812 focus: *Focus, 2813 grid: ?Grid, 2814 child: *Widget, 2815 2816 pub fn init(allocator: std.mem.Allocator, child_widget: Widget) !Center { 2817 const child = try allocator.create(Widget); 2818 errdefer allocator.destroy(child); 2819 child.* = child_widget; 2820 return .{ 2821 .focus = try Focus.create(allocator, .container), 2822 .grid = null, 2823 .child = child, 2824 }; 2825 } 2826 2827 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 2828 self.focus.destroy(allocator); 2829 if (self.grid) |*grid| { 2830 grid.deinit(); 2831 self.grid = null; 2832 } 2833 self.child.deinit(allocator); 2834 allocator.destroy(self.child); 2835 } 2836 2837 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2838 self.clearGrid(); 2839 self.getFocus().clear(); 2840 2841 // build the child without forcing it to fill min_size; it sizes 2842 // itself to its content within the available max. 2843 try self.child.build(allocator, .{ 2844 .min_size = .{ .width = null, .height = null }, 2845 .max_size = constraint.max_size, 2846 }, root_focus); 2847 2848 const child_grid = self.child.getGrid() orelse return; 2849 2850 // prefer max when given; otherwise grow to max(min, child) so that 2851 // when only a min is set (e.g. the wasm path passes viewport rows 2852 // as min_height with no max), we can still vertically center while 2853 // letting taller content extend past the min. 2854 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; 2855 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; 2856 if (width == 0 or height == 0) return; 2857 2858 const offset_x: usize = (width -| child_grid.size.width) / 2; 2859 const offset_y: usize = (height -| child_grid.size.height) / 2; 2860 2861 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 2862 errdefer grid.deinit(); 2863 try grid.drawGrid(child_grid, offset_x, offset_y); 2864 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 2865 self.getFocus().child_id = self.child.getFocus().id; 2866 2867 self.grid = grid; 2868 } 2869 2870 pub fn input(self: *Center, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2871 try self.child.input(allocator, key, root_focus); 2872 } 2873 2874 pub fn clearGrid(self: *Center) void { 2875 if (self.grid) |*grid| { 2876 grid.deinit(); 2877 self.grid = null; 2878 } 2879 self.child.clearGrid(); 2880 } 2881 2882 pub fn getGrid(self: Center) ?Grid { 2883 return self.grid; 2884 } 2885 2886 pub fn getFocus(self: *Center) *Focus { 2887 return self.focus; 2888 } 2889 }; 2890 2891 // renders truecolor ANSI art 2892 pub const AnsiArt = struct { 2893 focus: *Focus, 2894 grid: ?Grid, 2895 content: []const u8, 2896 2897 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 2898 return .{ 2899 .focus = try Focus.create(allocator, .container), 2900 .grid = null, 2901 .content = content, 2902 }; 2903 } 2904 2905 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 2906 self.focus.destroy(allocator); 2907 if (self.grid) |*grid| { 2908 grid.deinit(); 2909 self.grid = null; 2910 } 2911 } 2912 2913 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2914 _ = root_focus; 2915 self.clearGrid(); 2916 2917 // parse into rows of cells, then copy into a rectangular grid 2918 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 2919 defer { 2920 for (rows.items) |*row| row.deinit(allocator); 2921 rows.deinit(allocator); 2922 } 2923 var row: std.ArrayList(Grid.Cell) = .empty; 2924 errdefer row.deinit(allocator); 2925 2926 var style: Grid.Style = .{}; 2927 var width: usize = 0; 2928 const content = self.content; 2929 var i: usize = 0; 2930 while (i < content.len) { 2931 const byte = content[i]; 2932 if (byte == '\n') { 2933 width = @max(width, row.items.len); 2934 try rows.append(allocator, row); 2935 row = .empty; 2936 i += 1; 2937 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 2938 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 2939 var j = i + 2; 2940 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 2941 if (j >= content.len) { 2942 i = content.len; // malformed trailing escape; stop 2943 } else { 2944 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 2945 i = j + 1; 2946 } 2947 } else { 2948 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 2949 const end = @min(content.len, i + len); 2950 const rune = content[i..end]; 2951 const transparent = end - i == 1 and rune[0] == ' ' and 2952 style.fg == null and style.bg == null and !style.inverted; 2953 try row.append(allocator, .{ 2954 .rune = if (transparent) null else rune, 2955 .style = style, 2956 }); 2957 i = end; 2958 } 2959 } 2960 // a trailing row with content but no closing newline 2961 if (row.items.len > 0) { 2962 width = @max(width, row.items.len); 2963 try rows.append(allocator, row); 2964 } else { 2965 row.deinit(allocator); 2966 } 2967 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 2968 2969 const height = rows.items.len; 2970 if (width == 0 or height == 0) return; 2971 2972 const clamped_w = @min(width, constraint.max_size.width orelse width); 2973 const clamped_h = @min(height, constraint.max_size.height orelse height); 2974 2975 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 2976 errdefer grid.deinit(); 2977 for (rows.items[0..clamped_h], 0..) |r, y| { 2978 const n = @min(r.items.len, clamped_w); 2979 for (r.items[0..n], 0..) |cell, x| { 2980 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 2981 } 2982 } 2983 self.grid = grid; 2984 } 2985 2986 pub fn clearGrid(self: *AnsiArt) void { 2987 if (self.grid) |*grid| { 2988 grid.deinit(); 2989 self.grid = null; 2990 } 2991 } 2992 2993 pub fn getGrid(self: AnsiArt) ?Grid { 2994 return self.grid; 2995 } 2996 2997 pub fn getFocus(self: *AnsiArt) *Focus { 2998 return self.focus; 2999 } 3000 3001 fn applySgr(style: *Grid.Style, params: []const u8) void { 3002 var nums: [16]u32 = undefined; 3003 var n: usize = 0; 3004 var it = std.mem.splitScalar(u8, params, ';'); 3005 while (it.next()) |tok| { 3006 if (n >= nums.len) break; 3007 // an empty parameter (e.g. bare "\x1b[m") means 0 3008 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 3009 n += 1; 3010 } 3011 if (n == 0) { 3012 style.* = .{}; 3013 return; 3014 } 3015 var i: usize = 0; 3016 while (i < n) : (i += 1) { 3017 switch (nums[i]) { 3018 0 => style.* = .{}, 3019 7 => style.inverted = true, 3020 27 => style.inverted = false, 3021 39 => style.fg = null, 3022 49 => style.bg = null, 3023 38, 48 => { 3024 // truecolor form: 38;2;r;g;b — anything else is ignored 3025 if (i + 4 < n and nums[i + 1] == 2) { 3026 const c = Grid.Color{ 3027 .r = @truncate(nums[i + 2]), 3028 .g = @truncate(nums[i + 3]), 3029 .b = @truncate(nums[i + 4]), 3030 }; 3031 if (nums[i] == 38) style.fg = c else style.bg = c; 3032 i += 4; 3033 } 3034 }, 3035 else => {}, 3036 } 3037 } 3038 } 3039 }; 3040 3041 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 3042 pub const AnsiBackground = struct { 3043 grid: ?Grid, 3044 child: *Widget, 3045 art: AnsiArt, 3046 session: *Session, 3047 3048 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 3049 var cw = child_widget; 3050 const child = allocator.create(Widget) catch |e| { 3051 cw.deinit(allocator); 3052 return e; 3053 }; 3054 child.* = cw; 3055 errdefer { 3056 child.deinit(allocator); 3057 allocator.destroy(child); 3058 } 3059 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 3060 } 3061 3062 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 3063 if (self.grid) |*grid| grid.deinit(); 3064 self.art.deinit(allocator); 3065 self.child.deinit(allocator); 3066 allocator.destroy(self.child); 3067 } 3068 3069 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 3070 self.clearGrid(); 3071 3072 // make the wrapped page fill the whole available area 3073 try self.child.build(allocator, .{ 3074 .min_size = .{ 3075 .width = constraint.max_size.width orelse constraint.min_size.width, 3076 .height = constraint.max_size.height orelse constraint.min_size.height, 3077 }, 3078 .max_size = constraint.max_size, 3079 }, root_focus); 3080 3081 if (self.session.data.enable_ansi) { 3082 if (self.child.getGrid()) |fg| { 3083 self.grid = try artBehind(allocator, fg, &self.art, .top_right, self.session.is_terminal, root_focus); 3084 } 3085 } 3086 } 3087 3088 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 3089 try self.child.input(allocator, key, root_focus); 3090 } 3091 3092 pub fn clearGrid(self: *AnsiBackground) void { 3093 if (self.grid) |*grid| { 3094 grid.deinit(); 3095 self.grid = null; 3096 } 3097 self.child.clearGrid(); 3098 self.art.clearGrid(); 3099 } 3100 3101 pub fn getGrid(self: AnsiBackground) ?Grid { 3102 return self.grid orelse self.child.getGrid(); 3103 } 3104 3105 pub fn getFocus(self: *AnsiBackground) *Focus { 3106 return self.child.getFocus(); 3107 } 3108 3109 // which top corner the art hugs. 3110 const ArtAnchor = enum { top_left, top_right }; 3111 3112 // a foreground cell counts as blank if it's empty or a bare space without styling 3113 fn cellIsBlank(cell: Grid.Cell) bool { 3114 if (cell.rune) |rune| { 3115 return std.mem.eql(u8, rune, " ") and 3116 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 3117 } 3118 return true; 3119 } 3120 3121 // the art is dimmed to this fraction of its brightness so foreground text 3122 // stays legible over it 3123 const art_brightness = 45; // percent 3124 3125 fn dimColor(color: ?Grid.Color) ?Grid.Color { 3126 const c = color orelse return null; 3127 return .{ 3128 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 3129 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 3130 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 3131 }; 3132 } 3133 3134 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 3135 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 3136 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 3137 // snap such channels clear of that range so the backdrop doesn't blink or 3138 // hide text there; the ≤9/255 shift is imperceptible on terminals that 3139 // actually render truecolor. 3140 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 3141 const c = color orelse return null; 3142 const snap = struct { 3143 fn f(v: u8) u8 { 3144 return if (v >= 1 and v <= 9) 10 else v; 3145 } 3146 }.f; 3147 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 3148 } 3149 3150 // composites ANSI art behind a foreground grid 3151 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, is_terminal: bool, root_focus: *Focus) !Grid { 3152 art.clearGrid(); 3153 try art.build(allocator, .{ 3154 .min_size = .{ .width = null, .height = null }, 3155 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 3156 }, root_focus); 3157 3158 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 3159 errdefer out.deinit(); 3160 3161 if (art.getGrid()) |art_grid| { 3162 const anchor_x = switch (anchor) { 3163 .top_left => 0, 3164 .top_right => foreground.size.width -| art_grid.size.width, 3165 }; 3166 for (0..art_grid.size.height) |y| { 3167 for (0..art_grid.size.width) |x| { 3168 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 3169 if (src.rune == null) continue; 3170 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 3171 const dst = &out.cells.items[idx]; 3172 // composite the dimmed art behind every cell so it shows 3173 // through the whole UI: a blank cell becomes the art, while a 3174 // cell with a glyph keeps the glyph but takes the dimmed art as 3175 // its background (replacing whatever background it had, which 3176 // would otherwise obscure the art). 3177 if (cellIsBlank(dst.*)) { 3178 dst.* = src; 3179 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 3180 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 3181 } else { 3182 const background_maybe = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 3183 dst.style.bg = background_maybe; 3184 // change the color of text overlaying ANSI art to ensure 3185 // it is readable. don't do this in the web UI, since we 3186 // have direct control of the theme there (also, inner 3187 // scroll panes allow text to move without a re-render 3188 // by the TUI, which would break this). also don't do this 3189 // if the text is explicitly styled. 3190 if (is_terminal and dst.style.fg == null) { 3191 if (background_maybe) |background| { 3192 // use near-black and near-white, which is easier on the eyes 3193 // while retaining high contrast 3194 const luminance = (@as(u32, background.r) * 299 + 3195 @as(u32, background.g) * 587 + 3196 @as(u32, background.b) * 114) / 1000; 3197 dst.style.fg = if (luminance >= 128) 3198 .{ .r = 16, .g = 16, .b = 16 } 3199 else 3200 .{ .r = 240, .g = 240, .b = 240 }; 3201 } 3202 } 3203 } 3204 } 3205 } 3206 } 3207 return out; 3208 } 3209 }; 3210