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