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