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