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