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