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