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