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