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