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