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