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