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