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