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