╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1920 std.mem.eql(u8, a_d.base_oid.slice(), b.repo_diff.base_oid.slice()) and 1921 std.mem.eql(u8, a_d.patchrev_id.slice(), b.repo_diff.patchrev_id.slice()) and 1922 a_d.start == b.repo_diff.start and std.mem.eql(u8, a_d.path.slice(), b.repo_diff.path.slice()), 1923 .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()) and std.mem.eql(u8, a_r.search.slice(), b.repo_refs.search.slice()), 1924 .repo_issues => |a_i| std.mem.eql(u8, a_i.name.slice(), b.repo_issues.name.slice()) and 1925 std.mem.eql(u8, a_i.search.slice(), b.repo_issues.search.slice()) and 1926 std.mem.eql(u8, a_i.selected.slice(), b.repo_issues.selected.slice()) and 1927 std.mem.eql(u8, a_i.theirs.slice(), b.repo_issues.theirs.slice()) and 1928 a_i.view == b.repo_issues.view and 1929 a_i.comments_start == b.repo_issues.comments_start and 1930 std.mem.eql(u8, a_i.comment.slice(), b.repo_issues.comment.slice()), 1931 .repo_discussions => |a_t| std.mem.eql(u8, a_t.name.slice(), b.repo_discussions.name.slice()) and 1932 std.mem.eql(u8, a_t.search.slice(), b.repo_discussions.search.slice()) and 1933 std.mem.eql(u8, a_t.selected.slice(), b.repo_discussions.selected.slice()) and 1934 a_t.view == b.repo_discussions.view and 1935 a_t.comments_start == b.repo_discussions.comments_start and 1936 std.mem.eql(u8, a_t.comment.slice(), b.repo_discussions.comment.slice()), 1937 .repo_patches => |a_p| std.mem.eql(u8, a_p.name.slice(), b.repo_patches.name.slice()) and 1938 std.mem.eql(u8, a_p.search.slice(), b.repo_patches.search.slice()) and 1939 std.mem.eql(u8, a_p.selected.slice(), b.repo_patches.selected.slice()) and 1940 std.mem.eql(u8, a_p.theirs.slice(), b.repo_patches.theirs.slice()) and 1941 a_p.view == b.repo_patches.view and 1942 a_p.comments_start == b.repo_patches.comments_start and 1943 std.mem.eql(u8, a_p.comment.slice(), b.repo_patches.comment.slice()), 1944 .repo_undo => |a_u| std.mem.eql(u8, a_u.name.slice(), b.repo_undo.name.slice()) and 1945 a_u.index == b.repo_undo.index, 1946 .repo_events => |a_e| std.mem.eql(u8, a_e.name.slice(), b.repo_events.name.slice()) and 1947 a_e.view == b.repo_events.view and 1948 a_e.moment == b.repo_events.moment and 1949 a_e.kind == b.repo_events.kind and 1950 std.mem.eql(u8, a_e.selected.slice(), b.repo_events.selected.slice()), 1951 .repo_repo_new => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_repo_new.slice()), 1952 .repo_user_new => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_user_new.slice()), 1953 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 1954 .repo_members => |a_r| std.mem.eql(u8, a_r.name.slice(), b.repo_members.name.slice()) and 1955 a_r.start == b.repo_members.start and 1956 std.mem.eql(u8, a_r.user.slice(), b.repo_members.user.slice()) and 1957 a_r.confirm == b.repo_members.confirm, 1958 .repo_branches => |a_b| std.mem.eql(u8, a_b.name.slice(), b.repo_branches.name.slice()) and 1959 std.mem.eql(u8, a_b.branch.slice(), b.repo_branches.branch.slice()), 1960 .repo_delete => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_delete.slice()), 1961 .repo_user => |a_u| std.mem.eql(u8, a_u.name.slice(), b.repo_user.name.slice()) and a_u.tab.eql(b.repo_user.tab), 1962 .fork_patch => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_patch.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_patch.id.slice()), 1963 .fork_diff => |a_d| std.mem.eql(u8, a_d.fork.name.slice(), b.fork_diff.fork.name.slice()) and 1964 std.mem.eql(u8, a_d.fork.id.slice(), b.fork_diff.fork.id.slice()) and 1965 std.mem.eql(u8, a_d.oid.slice(), b.fork_diff.oid.slice()) and 1966 std.mem.eql(u8, a_d.base_oid.slice(), b.fork_diff.base_oid.slice()) and 1967 a_d.start == b.fork_diff.start and std.mem.eql(u8, a_d.path.slice(), b.fork_diff.path.slice()), 1968 .fork_files => |a_f| std.mem.eql(u8, a_f.fork.name.slice(), b.fork_files.fork.name.slice()) and 1969 std.mem.eql(u8, a_f.fork.id.slice(), b.fork_files.fork.id.slice()) and 1970 std.mem.eql(u8, a_f.oid.slice(), b.fork_files.oid.slice()) and 1971 std.mem.eql(u8, a_f.find.slice(), b.fork_files.find.slice()) and 1972 std.mem.eql(u8, a_f.path.slice(), b.fork_files.path.slice()) and 1973 a_f.line == b.fork_files.line, 1974 .fork_commits => |a_c| std.mem.eql(u8, a_c.fork.name.slice(), b.fork_commits.fork.name.slice()) and 1975 std.mem.eql(u8, a_c.fork.id.slice(), b.fork_commits.fork.id.slice()) and 1976 std.mem.eql(u8, a_c.oid.slice(), b.fork_commits.oid.slice()) and 1977 a_c.message == b.fork_commits.message, 1978 .fork_delete => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_delete.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_delete.id.slice()), 1979 .fork_repo_new => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_repo_new.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_repo_new.id.slice()), 1980 .fork_user_new => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_user_new.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_user_new.id.slice()), 1981 .fork_user => |a_u| std.mem.eql(u8, a_u.fork.name.slice(), b.fork_user.fork.name.slice()) and 1982 std.mem.eql(u8, a_u.fork.id.slice(), b.fork_user.fork.id.slice()) and 1983 a_u.tab.eql(b.fork_user.tab), 1984 else => true, 1985 }; 1986 } 1987 1988 // true when following a link from `b` to `a` (both repo routes) should reload 1989 // rather than stay in page 1990 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 1991 if (a.parent() != .repo or b.parent() != .repo) return false; 1992 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 1993 a.repo_refs.from.len == 0 and b.repo_refs.from.len == 0) 1994 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 1995 return !a.eql(b); 1996 } 1997 1998 pub fn forkPageChanged(a: RoutablePage, b: RoutablePage) bool { 1999 return a.parent() == .fork and b.parent() == .fork and !a.eql(b); 2000 } 2001 2002 // true when `a` and `b` are different users' pages, or the same user 2003 // paginated to a different repos window or search. switching between a 2004 // user's tabs is in-page, so only a changed `start` or search on the same 2005 // list navigates. 2006 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 2007 if (a.userPageName()) |a_name| if (b.userPageName()) |b_name| { 2008 if (!std.mem.eql(u8, a_name, b_name)) return true; 2009 }; 2010 return switch (a) { 2011 .user_repos => |aa| switch (b) { 2012 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and !a.eql(b), 2013 else => false, 2014 }, 2015 .user_forks => |aa| switch (b) { 2016 .user_forks => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 2017 else => false, 2018 }, 2019 .user_user => |aa| switch (b) { 2020 .user_user => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and !a.eql(b), 2021 else => false, 2022 }, 2023 else => false, 2024 }; 2025 } 2026 2027 // the user a user page belongs to, or null for any other page 2028 fn userPageName(self: *const RoutablePage) ?[]const u8 { 2029 return switch (self.*) { 2030 .user_repos => |*page| page.name.slice(), 2031 .user_forks => |*page| page.name.slice(), 2032 .user_user => |*page| page.name.slice(), 2033 .user_repo_new, .user_user_new => |*name| name.slice(), 2034 else => null, 2035 }; 2036 } 2037 2038 // true when `a` and `b` are the same home list tab paginated to a different 2039 // window or search. switching tabs is in-page, so only a changed `start` or 2040 // search on the same tab navigates. 2041 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 2042 return switch (a) { 2043 .home_users => switch (b) { 2044 .home_users => !a.eql(b), 2045 else => false, 2046 }, 2047 .home_user => switch (b) { 2048 .home_user => !a.eql(b), 2049 else => false, 2050 }, 2051 else => false, 2052 }; 2053 } 2054 }; 2055 2056 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 2057 fn isUnreserved(c: u8) bool { 2058 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2059 } 2060 2061 // percent-encode a ref name for use as a single url path segment. 2062 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 2063 var out: std.Io.Writer.Allocating = .init(aa); 2064 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 2065 return out.written(); 2066 } 2067 2068 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 2069 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2070 return struct { 2071 pub const hex_len = hash.hexLen(repo_opts.hash); 2072 2073 // the concrete ref/oid (a null request resolves to the default branch) 2074 ref_or_oid: RoutablePage.RefOrOid, 2075 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 2076 // the route layer — which splits on '/' — stores them encoded). duped 2077 // into `aa`. 2078 value: []const u8, 2079 // the commit oid it points at 2080 oid: [hex_len]u8, 2081 2082 const Self = @This(); 2083 2084 // resolve a requested ref/oid (null = the repo's default branch) to a 2085 // concrete ref/oid plus the commit oid it points at. `requested_value` is 2086 // the url-encoded form (as it appears in the route). null when it doesn't 2087 // resolve (an unknown branch/tag, or a malformed/unknown oid). 2088 pub fn init( 2089 repo: *rp.Repo(repo_kind, repo_opts), 2090 io: std.Io, 2091 aa: std.mem.Allocator, 2092 requested_ref_or_oid: ?RoutablePage.RefOrOid, 2093 requested_value: []const u8, 2094 ) !?Self { 2095 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 2096 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 2097 var value: []const u8 = if (requested_ref_or_oid == null) 2098 requested_value 2099 else 2100 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 2101 // no ref named: fall back to HEAD's branch (or its oid when detached). 2102 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 2103 if (requested_ref_or_oid == null) { 2104 if (repo.head(io, &head_buf)) |head| switch (head) { 2105 .ref => |r| { 2106 ref_or_oid = .branch; 2107 value = r.name; 2108 }, 2109 .oid => |o| { 2110 ref_or_oid = .object; 2111 value = o; 2112 }, 2113 } else |_| {} 2114 } 2115 2116 var oid: [hex_len]u8 = undefined; 2117 switch (ref_or_oid) { 2118 .object => { 2119 if (value.len != hex_len) return null; 2120 @memcpy(&oid, value); 2121 }, 2122 .branch, .tag => { 2123 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 2124 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 2125 }, 2126 } 2127 // store url-encoded so the route layer can hold the value verbatim. 2128 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 2129 } 2130 }; 2131 } 2132 2133 // who a repo page is built for, which picks the actions it shows 2134 pub const Viewer = struct { 2135 role: evt.Repo.Role, 2136 email: []const u8, 2137 2138 // the session's viewer of a repo it holds `role` in, or null when logged 2139 // out. local mode owns everything. 2140 pub fn init(session: *Session, arena: *std.heap.ArenaAllocator, role: evt.Repo.Role) !?Viewer { 2141 if (session.data.host_kind == .local) return .{ .role = .owner, .email = "" }; 2142 const user_id = session.userId() orelse return null; 2143 const moment = session.haxy_moment orelse unreachable; 2144 const user = (try activeUser(moment, arena, user_id)) orelse return null; 2145 return .{ .role = role, .email = user.event.email }; 2146 } 2147 }; 2148 2149 // a repo a page shows, and what its viewer may do there 2150 pub const RepoHandle = struct { 2151 location: RoutablePage.RepoLocation, 2152 viewer: ?Viewer = null, 2153 // only a public repo can be cloned over http 2154 read_access: evt.Repo.Access = .private, 2155 2156 pub fn dupe(self: RepoHandle, allocator: std.mem.Allocator) !RepoHandle { 2157 var copy = self; 2158 copy.location = try self.location.dupe(allocator); 2159 return copy; 2160 } 2161 2162 // pushing, and seeing the events and undo tabs. local mode is always owner. 2163 pub fn canWrite(self: RepoHandle) bool { 2164 const viewer = self.viewer orelse return false; 2165 return viewer.role.atLeast(.write); 2166 } 2167 2168 pub fn canUndo(self: RepoHandle) bool { 2169 const viewer = self.viewer orelse return false; 2170 return viewer.role == .owner; 2171 } 2172 }; 2173 2174 // where a repo page reads its on-disk repo from 2175 pub const RepoSource = struct { 2176 path: []const u8, 2177 repo_kind: rp.RepoKind, 2178 // the user's global git config, so local mode picks up their identity and 2179 // their signing and ssh settings. null on the server paths, which must not 2180 // read whoever runs the server. 2181 global_config_path: ?[]const u8 = null, 2182 2183 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 2184 return .{ .path = self.path, .global_config_path = self.global_config_path }; 2185 } 2186 2187 pub fn hasBranch(self: RepoSource, io: std.Io, allocator: std.mem.Allocator, branch: []const u8) !bool { 2188 if (!xit.ref.validateName(branch)) return false; 2189 return switch (self.repo_kind) { 2190 inline else => |repo_kind| blk: { 2191 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2192 defer any_repo.deinit(io, allocator); 2193 break :blk switch (any_repo) { 2194 inline else => |*repo| (try repo.readRef(io, .{ .kind = .head, .name = branch })) != null, 2195 }; 2196 }, 2197 }; 2198 } 2199 2200 // whether the actor may change the event `id` names 2201 pub fn canModify( 2202 self: RepoSource, 2203 io: std.Io, 2204 allocator: std.mem.Allocator, 2205 actor: Actor, 2206 kind: evt.EventKind, 2207 id: *const [evt.event_id_size]u8, 2208 ) !bool { 2209 // a role that may change an event with no author needs no read 2210 if (actor.role.canModify(actor.author.email, null)) return true; 2211 2212 var arena = std.heap.ArenaAllocator.init(allocator); 2213 defer arena.deinit(); 2214 return switch (self.repo_kind) { 2215 inline else => |repo_kind| blk: { 2216 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2217 defer any_repo.deinit(io, allocator); 2218 break :blk switch (any_repo) { 2219 inline else => |*repo| actor.role.canModify(actor.author.email, try evt.readAuthorEmail(repo_kind, repo.self_repo_opts, io, allocator, &arena, repo, kind, id)), 2220 }; 2221 }, 2222 }; 2223 } 2224 }; 2225 2226 // who a write acts as and the role they hold in its repo 2227 // the thread button that changes the viewer's notifications, named by its label 2228 pub const NotifyAction = enum { subscribe, mute }; 2229 2230 pub const Actor = struct { 2231 author: evt.CommitAuthor, 2232 // local mode has no accounts, so it has no user id 2233 user_id: ?[evt.event_id_size]u8 = null, 2234 role: evt.Repo.Role, 2235 // the repo owner's id, which local mode lacks 2236 repo_user_id: ?[evt.event_id_size]u8 = null, 2237 }; 2238 2239 pub const Authorization = union(enum) { 2240 actor: Actor, 2241 login_required, 2242 repo_not_found, 2243 forbidden, 2244 }; 2245 2246 // the account `user_id` names, or null once it has been removed. a user id is 2247 // checked here wherever one enters, so the role lookups can trust theirs. 2248 pub fn activeUser( 2249 moment: evt.AdminDB.HashMap(.read_only), 2250 arena: *std.heap.ArenaAllocator, 2251 user_id: [evt.event_id_size]u8, 2252 ) !?evt.User.Record { 2253 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 2254 return if (user.removed) null else user; 2255 } 2256 2257 // what the typed assignee resolves to 2258 pub const AssigneeLookup = union(enum) { 2259 email: []const u8, 2260 failure: Session.FormFeedback.AssignmentFailure, 2261 }; 2262 2263 // the email `text` assigns: itself when it holds an @, else the email of the 2264 // user it names. a null moment is local mode, which has no users to look up. 2265 pub fn assigneeEmail(moment_maybe: ?evt.AdminDB.HashMap(.read_only), arena: *std.heap.ArenaAllocator, text: []const u8) !AssigneeLookup { 2266 const trimmed = std.mem.trim(u8, text, " \t\r\n"); 2267 if (std.mem.indexOfScalar(u8, trimmed, '@') != null) return .{ .email = trimmed }; 2268 const moment = moment_maybe orelse return .{ .failure = .not_an_email }; 2269 const user_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, trimmed)) orelse return .{ .failure = .not_found }; 2270 const user = (try activeUser(moment, arena, user_id)) orelse return .{ .failure = .not_found }; 2271 return .{ .email = user.event.email }; 2272 } 2273 2274 // whether the user may write to the repo `identity` names with at least 2275 // `min_role`, and to the `thread_kind` tab when there is one 2276 pub fn authorizeUser( 2277 io: std.Io, 2278 moment: evt.AdminDB.HashMap(.read_only), 2279 arena: *std.heap.ArenaAllocator, 2280 users_dir: []const u8, 2281 user_id: [evt.event_id_size]u8, 2282 identity: []const u8, 2283 min_role: evt.Repo.Role, 2284 thread_kind: ?evt.EventKind, 2285 ) !Authorization { 2286 const user = (try activeUser(moment, arena, user_id)) orelse return .login_required; 2287 2288 const owner_repo = evt.parseOwnerRepoPath(identity) orelse return .repo_not_found; 2289 const repo = (try evt.readRepoByOwnerAndName(io, arena.child_allocator, arena, moment, users_dir, owner_repo.owner, owner_repo.name, user_id)) orelse return .repo_not_found; 2290 // a repo the user can't read doesn't exist to them 2291 const role = repo.role orelse return .repo_not_found; 2292 if (!role.atLeast(min_role)) return .forbidden; 2293 if (thread_kind) |kind| { 2294 // a tab that is off doesn't exist 2295 const tab_role = repo.repo.event.threadRole(kind) orelse return .repo_not_found; 2296 if (!role.atLeast(tab_role)) return .forbidden; 2297 } 2298 return .{ .actor = .{ 2299 .author = .{ .name = user.event.name, .email = user.event.email }, 2300 .user_id = user_id, 2301 .role = role, 2302 .repo_user_id = try evt.parseEventId(&repo.repo.event.user_id), 2303 } }; 2304 } 2305 2306 // events created in local mode have no account behind them, so the commit 2307 // author comes from the repo's config, which the global config feeds into. 2308 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 2309 2310 pub fn localAuthor( 2311 src: RepoSource, 2312 io: std.Io, 2313 allocator: std.mem.Allocator, 2314 arena: *std.heap.ArenaAllocator, 2315 ) !evt.CommitAuthor { 2316 switch (src.repo_kind) { 2317 inline else => |repo_kind| { 2318 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 2319 defer any_repo.deinit(io, allocator); 2320 2321 switch (any_repo) { 2322 inline else => |*repo| { 2323 var config = try repo.listConfig(io, allocator); 2324 defer config.deinit(); 2325 2326 const user = config.sections.get("user") orelse return local_author_fallback; 2327 const name = user.get("name") orelse return local_author_fallback; 2328 const email = user.get("email") orelse return local_author_fallback; 2329 return .{ 2330 .name = try arena.allocator().dupe(u8, name), 2331 .email = try arena.allocator().dupe(u8, email), 2332 }; 2333 }, 2334 } 2335 }, 2336 } 2337 } 2338 2339 // per-connection mutable state. each SSH session / web session / local TUI 2340 // run gets its own. 2341 pub const Session = struct { 2342 data: Data = .{}, 2343 // session-lifetime allocations: login/user_id, persisted prefs, queued 2344 // actions. lives as long as the connection. 2345 arena: *std.heap.ArenaAllocator, 2346 // current page's allocations: page data and the page-scoped strings widgets 2347 // build (form actions, links). owned by Nav, swapped on each navigation, so 2348 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 2349 // where a render is one-shot, this points at the same arena as `arena`. 2350 page_arena: *std.heap.ArenaAllocator, 2351 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2352 // filesystem io and the path to <server>/repos, for opening on-disk repos 2353 // during page construction. both null on wasm, which has no filesystem and 2354 // rebuilds pages from the serialized snapshot rather than from disk. 2355 io: ?std.Io = null, 2356 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2357 users_dir: ?[]const u8 = null, 2358 // the single on-disk repo this session views, when running in local mode 2359 // (haxy invoked with no arguments inside a repo). null on the server paths, 2360 // which resolve repos from the admin db instead. 2361 local: ?RepoSource = null, 2362 // focus id -> the live TextInput, refreshed each frame by the views that own 2363 // inputs. web/wasm form handling looks widgets up here by focus id. 2364 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2365 back: enum { unavailable, available, requested } = .unavailable, 2366 refresh_requested: bool = false, // set by input (ctrl+r) 2367 // a requested forward navigation. set this (via navigate) to move to a new 2368 // page; Nav.sync builds it and then copies it into current_page, clearing 2369 // this back to null. setting current_page directly only updates the url and 2370 // does not navigate. 2371 next_page: ?RoutablePage = null, 2372 is_terminal: bool = false, // true on remote SSH and local TUI 2373 color: bool = true, // false when NO_COLOR is set, which also hides the art 2374 // the terminal's reported default background, which the art blends toward 2375 terminal_background: ?Grid.Color.Rgb = null, 2376 // the web UI's url, for the TUI/SSH footer. null on the web itself (no 2377 // footer there). 2378 web_url: ?[]const u8 = null, 2379 // the authorized_keys line of the key an ssh session connected with 2380 ssh_key: ?[]const u8 = null, 2381 // a host operation requested by a widget 2382 host_request: ?HostRequest = null, 2383 quit_requested: bool = false, 2384 2385 pub const HostRequest = union(enum) { 2386 show_copyable_text: []const u8, 2387 sync_events, 2388 undo: RoutablePage.RepoUndoRoute, 2389 }; 2390 2391 pub const FormFeedback = union(enum) { 2392 pub const LoginFailure = enum { unknown_user, wrong_password }; 2393 pub const ThreadFailure = enum { required_title }; 2394 pub const PatchFailure = enum { 2395 required_title, 2396 invalid_target_branch, 2397 invalid_source_branch, 2398 same_branch, 2399 unrelated_branches, 2400 2401 pub fn fromError(err: anyerror) ?PatchFailure { 2402 return switch (err) { 2403 error.InvalidTargetBranch => .invalid_target_branch, 2404 error.InvalidSourceBranch => .invalid_source_branch, 2405 error.SameBranch => .same_branch, 2406 error.UnrelatedBranches => .unrelated_branches, 2407 else => null, 2408 }; 2409 } 2410 }; 2411 2412 pub const RepoFailure = enum { 2413 required_name, 2414 invalid_name, 2415 name_taken, 2416 2417 pub fn fromError(err: anyerror) ?RepoFailure { 2418 return switch (err) { 2419 error.NameEmpty => .required_name, 2420 error.NameTooLong, error.InvalidName => .invalid_name, 2421 error.NameTaken => .name_taken, 2422 else => null, 2423 }; 2424 } 2425 }; 2426 2427 pub const MembersFailure = enum { not_found, already_added }; 2428 2429 pub const BranchesFailure = enum { 2430 not_found, 2431 already_added, 2432 too_many, 2433 too_long, 2434 2435 pub fn fromError(err: anyerror) ?BranchesFailure { 2436 return switch (err) { 2437 error.BranchProtected => .already_added, 2438 error.TooManyProtectedBranches => .too_many, 2439 else => null, 2440 }; 2441 } 2442 }; 2443 2444 pub const AssignmentFailure = enum { not_found, not_an_email, already_assigned }; 2445 2446 pub const DeleteFailure = enum { wrong_confirm, wrong_password }; 2447 2448 pub const KeyFailure = enum { 2449 invalid, 2450 unsupported, 2451 already_added, 2452 too_many, 2453 2454 pub fn fromError(err: anyerror) ?KeyFailure { 2455 return switch (err) { 2456 error.InvalidKey => .invalid, 2457 error.UnsupportedKey => .unsupported, 2458 error.KeyAdded => .already_added, 2459 error.TooManyKeys => .too_many, 2460 else => null, 2461 }; 2462 } 2463 }; 2464 2465 pub const UserFailure = enum { 2466 required_name, 2467 invalid_name, 2468 name_taken, 2469 required_email, 2470 email_taken, 2471 required_password, 2472 password_mismatch, 2473 wrong_password, 2474 2475 pub fn fromError(err: anyerror) ?UserFailure { 2476 return switch (err) { 2477 error.NameEmpty => .required_name, 2478 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2479 error.NameTaken => .name_taken, 2480 error.EmailEmpty => .required_email, 2481 error.EmailTaken => .email_taken, 2482 error.PasswordEmpty => .required_password, 2483 error.PasswordMismatch => .password_mismatch, 2484 error.WrongPassword => .wrong_password, 2485 else => null, 2486 }; 2487 } 2488 }; 2489 2490 login: struct { 2491 failure: LoginFailure, 2492 username: []const u8, 2493 }, 2494 user: struct { 2495 failure: UserFailure, 2496 // passwords are never retained 2497 fields: struct { 2498 name: []const u8, 2499 email: []const u8, 2500 }, 2501 }, 2502 user_settings: struct { 2503 failure: UserFailure, 2504 // passwords are never retained 2505 fields: struct { email: []const u8 }, 2506 }, 2507 user_keys: struct { 2508 failure: KeyFailure, 2509 key: []const u8, 2510 }, 2511 repo: struct { 2512 failure: RepoFailure, 2513 fields: struct { 2514 name: []const u8, 2515 description: []const u8, 2516 hash: hash.HashKind, 2517 access: evt.Repo.Access, 2518 }, 2519 }, 2520 repo_settings: struct { 2521 failure: RepoFailure, 2522 fields: struct { 2523 name: []const u8, 2524 description: []const u8, 2525 access: evt.Repo.Access, 2526 discuss_role: ?evt.Repo.Role, 2527 issue_role: ?evt.Repo.Role, 2528 patch_role: ?evt.Repo.Role, 2529 }, 2530 }, 2531 repo_members: struct { 2532 failure: MembersFailure, 2533 name: []const u8, 2534 }, 2535 repo_branches: struct { 2536 failure: BranchesFailure, 2537 name: []const u8, 2538 }, 2539 assignment: struct { 2540 failure: AssignmentFailure, 2541 text: []const u8, 2542 }, 2543 delete: struct { 2544 failure: DeleteFailure, 2545 // a page can hold two delete forms, so this names the failed one 2546 target: std.meta.Tag(Delete.Target), 2547 // the password is never retained 2548 confirm: []const u8, 2549 }, 2550 issue: struct { 2551 failure: ThreadFailure, 2552 fields: ?struct { 2553 title: []const u8, 2554 labels: []const u8, 2555 description: []const u8, 2556 } = null, 2557 }, 2558 patch: struct { 2559 failure: PatchFailure, 2560 fields: ?struct { 2561 title: []const u8, 2562 labels: []const u8, 2563 description: []const u8, 2564 target_branch: []const u8, 2565 source_branch: []const u8 = "", 2566 source_kind: Repo.Patches.Source.Kind = .fork, 2567 } = null, 2568 }, 2569 discussion: struct { 2570 failure: ThreadFailure, 2571 fields: ?struct { 2572 title: []const u8, 2573 labels: []const u8, 2574 description: []const u8, 2575 } = null, 2576 }, 2577 }; 2578 2579 const Self = @This(); 2580 2581 // serializable data sent down to web client 2582 pub const Data = struct { 2583 // the server's reference time for relative timestamps on this page. 2584 now: i64 = 0, 2585 user_id: ?[]const u8 = null, 2586 // the logged-in user's name and email, for the views that show them 2587 user_name: ?[]const u8 = null, 2588 user_email: ?[]const u8 = null, 2589 // the logged-in user's unread notifications, refreshed on each page build 2590 unread_notifs: u64 = 0, 2591 // a failed form retained long enough to render it for correction 2592 form_feedback: ?FormFeedback = null, 2593 // a transient local event-sync error 2594 sync_failure: ?[]const u8 = null, 2595 // a failed terminal undo retained on the current tab 2596 undo_failure: ?[]const u8 = null, 2597 current_page: RoutablePage = .default, 2598 // the selected ANSI art. the server serializes one image for WASM so 2599 // the browser does not need the whole build-generated collection. 2600 ansi_art: []const u8 = "", 2601 // where git clones and pushes go. absent in local mode, where remote 2602 // urls are not shown. 2603 git_http_url: ?[]const u8 = null, 2604 git_ssh_url: ?[]const u8 = null, 2605 git_ssh_prefix: []const u8 = "", 2606 // whether this session views a local repo or the server. unlike `local` 2607 // (the host-side filesystem source) this travels in the snapshot, so 2608 // the wasm side also parses elided link urls and hides the multi-user 2609 // chrome. 2610 host_kind: evt.HostKind = .server, 2611 }; 2612 2613 pub fn init( 2614 arena: *std.heap.ArenaAllocator, 2615 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2616 data: Data, 2617 ) !Self { 2618 var session = Self{ 2619 .data = data, 2620 .arena = arena, 2621 // until a host swaps in a page-scoped arena (Nav does this), page 2622 // allocations land in the session arena. on the web path that's the 2623 // intended behavior, since the whole arena is per-request. 2624 .page_arena = arena, 2625 .admin_repo = repo, 2626 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2627 }; 2628 try session.loadUser(); 2629 return session; 2630 } 2631 2632 // web views share the page's reference time; terminals use the live clock. 2633 pub fn nowSeconds(self: *const Self) !i64 { 2634 if (builtin.target.cpu.arch == .wasm32 or !self.is_terminal) return self.data.now; 2635 const io = self.io orelse return error.NoClock; 2636 return std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse error.TimestampOutOfRange; 2637 } 2638 2639 // load the logged-in user's name and persisted preferences from the db 2640 pub fn loadUser(self: *Self) !void { 2641 const user_id = self.userId() orelse return; 2642 const moment = self.haxy_moment orelse return; 2643 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2644 self.data.user_name = user.event.name; 2645 self.data.user_email = user.event.email; 2646 } 2647 2648 // forget the logged-in user, on a logout or once their account is removed 2649 pub fn logOut(self: *Self) void { 2650 self.data.user_id = null; 2651 self.data.user_name = null; 2652 self.data.user_email = null; 2653 } 2654 2655 // log in as the account the session's ssh key last logged into with a 2656 // password, while that account still holds the key 2657 pub fn logInWithSshKey(self: *Self) !void { 2658 const key = self.ssh_key orelse return; 2659 const admin_repo = self.admin_repo orelse return; 2660 const moment = self.haxy_moment orelse return; 2661 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2662 const user_id = (try evt.readLoginKeyUser(try admin_repo.core.latestMoment(), &fingerprint)) orelse return; 2663 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, &user_id, &fingerprint)) return; 2664 self.data.user_id = try self.arena.allocator().dupe(u8, &user_id); 2665 try self.loadUser(); 2666 } 2667 2668 // add the session's ssh key to the user who just logged in with a 2669 // password, which proves they hold it, and let it log them in from now on 2670 pub fn rememberSshKey(self: *Self) !void { 2671 if (builtin.target.cpu.arch == .wasm32) return; 2672 const key = self.ssh_key orelse return; 2673 const io = self.io orelse return; 2674 const users_dir = self.users_dir orelse return; 2675 const admin_repo = self.admin_repo orelse return; 2676 const user_id = self.userId() orelse return; 2677 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2678 const allocator = self.arena.child_allocator; 2679 2680 const day = (std.time.epoch.EpochSeconds{ .secs = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()) }).getEpochDay().calculateYearDay(); 2681 const month = day.calculateMonthDay(); 2682 const line = try std.fmt.allocPrint(allocator, "{s} added {d:0>4}-{d:0>2}-{d:0>2} via login", .{ key, day.year, month.month.numeric(), month.day_index + 1 }); 2683 defer allocator.free(line); 2684 evt.addUserKey(io, allocator, users_dir, admin_repo, &user_id, line) catch |err| switch (err) { 2685 // it's already there, or there's no room for it 2686 error.KeyAdded, error.TooManyKeys => {}, 2687 else => return err, 2688 }; 2689 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .trust); 2690 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2691 } 2692 2693 // stop the session's ssh key logging the user in, on a logout 2694 pub fn forgetSshKey(self: *Self) !void { 2695 if (builtin.target.cpu.arch == .wasm32) return; 2696 const key = self.ssh_key orelse return; 2697 const io = self.io orelse return; 2698 const admin_repo = self.admin_repo orelse return; 2699 const user_id = self.userId() orelse return; 2700 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2701 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .forget); 2702 } 2703 2704 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2705 const bytes = self.data.user_id orelse return null; 2706 if (bytes.len != evt.event_id_size) return null; 2707 var id: [evt.event_id_size]u8 = undefined; 2708 @memcpy(&id, bytes); 2709 return id; 2710 } 2711 2712 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2713 const feedback = self.data.form_feedback orelse return null; 2714 if (std.meta.activeTag(feedback) != tag) return null; 2715 return @field(feedback, @tagName(tag)); 2716 } 2717 2718 pub fn clearFormFeedback(self: *Self) void { 2719 self.data.form_feedback = null; 2720 } 2721 2722 // the actor for a write to the repo `identity` names, or null when the 2723 // session may not write there with at least `min_role` or in the 2724 // `thread_kind` tab. local mode always writes. 2725 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2726 if (self.data.host_kind == .local) { 2727 const author = blk: { 2728 const src = self.local orelse break :blk local_author_fallback; 2729 const io = self.io orelse break :blk local_author_fallback; 2730 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2731 }; 2732 return .{ .author = author, .role = .owner }; 2733 } 2734 const user_id = self.userId() orelse return null; 2735 // the session's moment predates this input, so read the roles afresh 2736 const admin_repo = self.admin_repo orelse return null; 2737 const io = self.io orelse return null; 2738 const users_dir = self.users_dir orelse return null; 2739 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2740 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2741 .actor => |actor| actor, 2742 .login_required, .repo_not_found, .forbidden => null, 2743 }; 2744 } 2745 2746 // where this session's event writes go. a server session always has a users dir and an admin repo 2747 pub fn eventHost(self: *const Self) evt.Host { 2748 return switch (self.data.host_kind) { 2749 .local => .local, 2750 .server => .{ .server = .{ 2751 .users_dir = self.users_dir orelse unreachable, 2752 .admin_repo_path = (self.admin_repo orelse unreachable).core.work_path, 2753 } }, 2754 }; 2755 } 2756 2757 // reload the moment from the admin repo and log out a removed user 2758 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2759 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2760 self.haxy_moment = moment; 2761 2762 const user_id = self.userId() orelse return; 2763 var arena = std.heap.ArenaAllocator.init(allocator); 2764 defer arena.deinit(); 2765 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2766 } 2767 2768 // request a forward navigation to `route`; the host consumes next_page 2769 // (Nav.sync on the terminal, the wasm tick on the web). 2770 pub fn navigate(self: *Session, route: RoutablePage) !void { 2771 self.clearFormFeedback(); 2772 self.next_page = route; 2773 } 2774 }; 2775 2776 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2777 var nav = try Nav.init(allocator, session); 2778 defer nav.deinit(allocator); 2779 2780 var terminal = try term.Terminal.init(io, allocator); 2781 terminal.render_state.no_color = !session.color; 2782 var terminal_live = true; 2783 defer if (terminal_live) terminal.deinit(io); 2784 2785 // set term as active so it will be properly cooked 2786 // when a panic/segfault happens 2787 term.setActive(&terminal); 2788 defer term.setActive(null); 2789 2790 try terminal.queryBackground(); 2791 2792 while (!terminal.shouldQuit()) { 2793 const grid_changed = try terminal.render(&nav.root); 2794 2795 // process any inputs. 2796 // 2797 // if the grid didn't change, then first do a blocking 2798 // read, so the thread will sleep until further input. 2799 // after that, all remaining reads are non-blocking so 2800 // we can process the rest of the queued inputs. 2801 // 2802 // if the grid *did* change, then only do non-blocking 2803 // reads. we do not want to sleep the thread because 2804 // there may be an animation that requires more looping. 2805 var blocking = !grid_changed; 2806 while (try terminal.readKey(io, blocking)) |key| { 2807 blocking = false; 2808 try inputKey(allocator, &nav.root, key, session); 2809 } 2810 2811 if (session.host_request) |request| { 2812 session.host_request = null; 2813 switch (request) { 2814 .show_copyable_text => |copyable_text| { 2815 term.setActive(null); 2816 terminal.deinit(io); 2817 terminal_live = false; 2818 showCopyableText(io, copyable_text) catch |show_err| { 2819 terminal = try term.Terminal.init(io, allocator); 2820 terminal_live = true; 2821 term.setActive(&terminal); 2822 return show_err; 2823 }; 2824 terminal = try term.Terminal.init(io, allocator); 2825 terminal.render_state.no_color = !session.color; 2826 terminal_live = true; 2827 term.setActive(&terminal); 2828 }, 2829 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2830 .sync_events => { 2831 try nav.root.build(allocator, .{ 2832 .min_size = .{ .width = null, .height = null }, 2833 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2834 }, nav.root.getFocus()); 2835 _ = try terminal.render(&nav.root); 2836 try Repo.Events.performSync(allocator, session); 2837 }, 2838 } 2839 } 2840 2841 // reload so the next navigation builds its page from the current moment 2842 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2843 2844 // reconcile navigation: forward to a new page, or back on escape. 2845 // the terminal background can change at any time, so recheck it on each page 2846 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2847 2848 // the quit button (on the quit tab) asks the host to tear down. 2849 if (session.quit_requested) terminal.requestQuit(); 2850 2851 try nav.root.build(allocator, .{ 2852 .min_size = .{ .width = null, .height = null }, 2853 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2854 }, nav.root.getFocus()); 2855 } 2856 } 2857 2858 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2859 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2860 null 2861 else 2862 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2863 defer if (tty) |file| file.close(io); 2864 2865 const input = if (tty) |file| file else std.Io.File.stdin(); 2866 const output = if (tty) |file| file else std.Io.File.stdout(); 2867 2868 var write_buf: [1024]u8 = undefined; 2869 var writer = output.writer(io, &write_buf); 2870 try writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 2871 try writer.interface.flush(); 2872 2873 var read_buf: [1]u8 = undefined; 2874 var reader = input.reader(io, &read_buf); 2875 while (true) { 2876 const byte = try reader.interface.takeByte(); 2877 if (byte == '\r' or byte == '\n') return; 2878 } 2879 } 2880 2881 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2882 const root_focus = root.getFocus(); 2883 const focused_before = root_focus.grandchild_id; 2884 var activate_in_page_link = false; 2885 switch (key) { 2886 // request a navigation pop; the host's Nav.sync goes back a page, or 2887 // quits when there's no history left. 2888 .escape => { 2889 session.back = .requested; 2890 return; 2891 }, 2892 .ctrl => |letter| switch (letter) { 2893 'r' => { 2894 session.refresh_requested = true; 2895 return; 2896 }, 2897 else => try root.input(allocator, key, root_focus), 2898 }, 2899 .enter => { 2900 if (root_focus.grandchild_id) |gid| { 2901 // follow a cross-page link 2902 if (crossPageLink(root_focus, gid, session.data)) |route| { 2903 return session.navigate(route); 2904 } 2905 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2906 } 2907 activate_in_page_link = true; 2908 try root.input(allocator, key, root_focus); 2909 }, 2910 .mouse => |mouse| { 2911 if (mouse.button == .left) { 2912 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2913 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2914 const focus_id = hit.id; 2915 if (hit.kind == .background) { 2916 root_focus.setFocus(focus_id); 2917 return; 2918 } 2919 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2920 if (session.back == .available) session.back = .requested; 2921 return; 2922 } 2923 // follow a cross-page link 2924 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2925 return session.navigate(route); 2926 } 2927 if (currentPageLink(root_focus, focus_id, session.data)) return; 2928 if (rawLink(root_focus, focus_id)) |url| { 2929 if (!mouse.ctrl) try requestRawLink(session, url); 2930 return; 2931 } 2932 root_focus.setFocus(focus_id); 2933 activate_in_page_link = true; 2934 } 2935 // forward the press into the widget tree so buttons (and any 2936 // future click-aware widgets) can react. widgets that don't 2937 // care about presses ignore it. 2938 try root.input(allocator, key, root_focus); 2939 } else { 2940 try root.input(allocator, key, root_focus); 2941 } 2942 }, 2943 .event => |event| switch (event) { 2944 .background => |rgb| session.terminal_background = rgb, 2945 .resize => try root.input(allocator, key, root_focus), 2946 }, 2947 // a scroll tick goes to the pane under the pointer, focusing it first. 2948 // from outside any pane (the tabs, a sub-header) or from a text input 2949 // it moves like the arrows instead, so scrolling up from a search box 2950 // reaches the header and stops there. 2951 .scroll_up, .scroll_down => |position| { 2952 if (focusedPane(root_focus)) |pane| if (scrollUnder(root_focus, position)) |under| { 2953 if (under != pane) root_focus.setFocus(under); 2954 }; 2955 try root.input(allocator, key, root_focus); 2956 }, 2957 else => try root.input(allocator, key, root_focus), 2958 } 2959 2960 const focused_after = root_focus.grandchild_id; 2961 if (!activate_in_page_link and focused_before == focused_after) return; 2962 const focus_id = focused_after orelse return; 2963 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2964 } 2965 2966 // the innermost vertically scrolling widget laid out under `position` 2967 fn scrollUnder(root_focus: *const Focus, position: xitui.input.Position) ?usize { 2968 var found: ?usize = null; 2969 var found_area: usize = std.math.maxInt(usize); 2970 var iter = root_focus.children.iterator(); 2971 while (iter.next()) |entry| { 2972 const info = entry.value_ptr.focus.scroll orelse continue; 2973 if (info.direction == .horiz) continue; 2974 const r = entry.value_ptr.rect; 2975 if (position.x < r.x or position.y < r.y or position.x >= r.x + r.size.width or position.y >= r.y + r.size.height) continue; 2976 // a nested scroll lies within its parent, so the smallest is innermost 2977 const area = r.size.width * r.size.height; 2978 if (area < found_area) { 2979 found = entry.key_ptr.*; 2980 found_area = area; 2981 } 2982 } 2983 return found; 2984 } 2985 2986 // the innermost vertically scrolling widget the focus lies in, unless the 2987 // focused widget is a text input 2988 fn focusedPane(root_focus: *const Focus) ?usize { 2989 var current = root_focus.grandchild_id orelse return null; 2990 switch ((root_focus.children.get(current) orelse return null).focus.kind) { 2991 .text_input, .text_input_password, .text_area => return null, 2992 else => {}, 2993 } 2994 while (root_focus.children.get(current)) |child| { 2995 if (child.focus.scroll) |info| if (info.direction != .horiz) return current; 2996 current = child.parent_id; 2997 } 2998 return null; 2999 } 3000 3001 // a link to bytes the server serves directly rather than to a page route, so 3002 // it never resolves to a RoutablePage 3003 pub const raw_link_prefix = "ax:"; 3004 3005 // a route already loaded into the current page; focusing it changes the url 3006 // without rebuilding the page 3007 pub const in_page_link_prefix = "ai:"; 3008 3009 // an in-page tab's base route, or the exact current route when it is selected 3010 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 3011 const target = if (selected) session.data.current_page else route; 3012 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 3013 } 3014 3015 // a button the web renderer covers with a file picker that posts the chosen 3016 // file to the url after the prefix 3017 pub const file_input_prefix = "file:"; 3018 3019 // a submit button that overrides its enclosing form's action 3020 pub const submit_action_prefix = "submit:"; 3021 3022 // one option of a radio field, as `radio:<name>=<value>` 3023 pub const radio_prefix = "radio:"; 3024 3025 // the url an `ax:` link points at, or null for anything else. a host that 3026 // suppresses the anchor's own navigation needs this to follow the link. 3027 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 3028 const child = root_focus.children.get(focus_id) orelse return null; 3029 const custom = switch (child.focus.kind) { 3030 .custom => |c| c, 3031 else => return null, 3032 }; 3033 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 3034 return custom[raw_link_prefix.len..]; 3035 } 3036 3037 fn requestRawLink(session: *Session, url: []const u8) !void { 3038 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 3039 } 3040 3041 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 3042 // an absolute url is already complete 3043 if (!std.mem.startsWith(u8, path, "/")) return path; 3044 return if (session.web_url) |web_url| 3045 try allocator.print("{s}{s}", .{ web_url, path }) 3046 else 3047 path; 3048 } 3049 3050 // if the focus target at focus_id is an `a:` link that should navigate (a 3051 // different parent page, or a different files directory within the repo page), 3052 // return its route; otherwise null. lets a host turn a click / enter on such a 3053 // link into a navigation rather than a focus change. 3054 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3055 const current = data.current_page; 3056 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 3057 // a link to a different parent page always navigates; within a page, a 3058 // files-directory / commits-page / list-window change navigates while tab 3059 // links stay in-page. 3060 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.forkPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 3061 return null; 3062 } 3063 3064 // the page the clicked cell links to, from a link inside a text box's content 3065 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 3066 const grid = root.getGrid() orelse return null; 3067 const cell = grid.cell(x, y) catch return null; 3068 const link = cell.link orelse return null; 3069 if (link.len == 0 or link[0] != '/') return null; 3070 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 3071 } 3072 3073 // whether the `a:` focus target links to the page already shown, which a click 3074 // leaves alone rather than focusing 3075 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 3076 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 3077 return route.eql(data.current_page); 3078 } 3079 3080 // the route carried by an `ai:` focus target, or null for any other target 3081 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3082 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 3083 } 3084 3085 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 3086 const child = root_focus.children.get(focus_id) orelse return null; 3087 const custom = switch (child.focus.kind) { 3088 .custom => |c| c, 3089 else => return null, 3090 }; 3091 if (!std.mem.startsWith(u8, custom, prefix)) return null; 3092 const path = custom[prefix.len..]; 3093 // local sessions build (and parse) links with the repo identity elided 3094 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 3095 } 3096 3097 // an assignee as the detail view shows it: the stored email, and the name of 3098 // the user holding it on this instance when there is one 3099 pub const Assignee = struct { 3100 email: []const u8, 3101 name: ?[]const u8 = null, 3102 3103 pub fn display(self: Assignee) []const u8 { 3104 return self.name orelse self.email; 3105 } 3106 }; 3107 3108 // a display author, resolved against the admin db at read time 3109 pub const Author = union(enum) { 3110 unknown, 3111 email: []const u8, // an email no user matches 3112 user_name: []const u8, 3113 3114 // the commit author line's email, resolved like initFromEmail 3115 pub fn init( 3116 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3117 arena: *std.heap.ArenaAllocator, 3118 author_line: []const u8, 3119 ) !Author { 3120 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 3121 } 3122 3123 // from a record's stored author email: it resolves to the user currently 3124 // holding it, else stays the email. the result is allocated in `arena`, 3125 // so the email may borrow transient memory. 3126 pub fn initFromEmail( 3127 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3128 arena: *std.heap.ArenaAllocator, 3129 author_email: ?[]const u8, 3130 ) !Author { 3131 const email = author_email orelse return .unknown; 3132 if (haxy_moment) |moment| { 3133 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 3134 return .{ .user_name = user.name }; 3135 } 3136 } 3137 return .{ .email = try arena.allocator().dupe(u8, email) }; 3138 } 3139 }; 3140 3141 // the "a:" link to user `name`'s page. 3142 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 3143 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 3144 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 3145 return page_arena.allocator().print("a:{s}", .{url}); 3146 } 3147 3148 // a focusable " author " box showing `author`, linking to their user page 3149 // when it is a known user 3150 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 3151 const text = switch (author) { 3152 .unknown => "", 3153 .email, .user_name => |t| t, 3154 }; 3155 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 3156 errdefer tb.deinit(allocator); 3157 tb.getFocus().mode = .all; 3158 switch (author) { 3159 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 3160 else => {}, 3161 } 3162 return tb; 3163 } 3164 3165 // native-TUI navigation 3166 pub const Nav = struct { 3167 root: Widget, 3168 // backs the current page (its Page data and the page-scoped strings its 3169 // widgets build). owned here, swapped on each navigation. session.page_arena 3170 // tracks whichever of these is current so widgets allocate into it. 3171 arena: *std.heap.ArenaAllocator, 3172 // the login the current root was built for 3173 user_id: ?[evt.event_id_size]u8, 3174 history: std.ArrayList(Entry), 3175 3176 // each retained page keeps its own arena, freed when the page leaves the 3177 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 3178 // long-lived session from accumulating every page it ever visited. 3179 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 3180 3181 // cap on retained back-history so the chain can't grow memory without bound 3182 const max_history: usize = 16; 3183 3184 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 3185 session.back = .unavailable; 3186 const arena = try allocator.create(std.heap.ArenaAllocator); 3187 arena.* = std.heap.ArenaAllocator.init(allocator); 3188 errdefer { 3189 arena.deinit(); 3190 allocator.destroy(arena); 3191 } 3192 3193 return .{ 3194 .root = try initCurrentRoot(allocator, arena, session), 3195 .arena = arena, 3196 .user_id = session.userId(), 3197 .history = .empty, 3198 }; 3199 } 3200 3201 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 3202 self.root.deinit(allocator); 3203 freeArena(allocator, self.arena); 3204 for (self.history.items) |*entry| { 3205 entry.root.deinit(allocator); 3206 freeArena(allocator, entry.arena); 3207 } 3208 self.history.deinit(allocator); 3209 } 3210 3211 // rebuild the current page in place from a current moment 3212 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 3213 if (session.haxy_moment == null and session.local == null) return; 3214 const arena = try allocator.create(std.heap.ArenaAllocator); 3215 arena.* = std.heap.ArenaAllocator.init(allocator); 3216 errdefer freeArena(allocator, arena); 3217 3218 const new_root = try initCurrentRoot(allocator, arena, session); 3219 3220 self.root.deinit(allocator); 3221 freeArena(allocator, self.arena); 3222 self.root = new_root; 3223 self.arena = arena; 3224 self.user_id = session.userId(); 3225 } 3226 3227 // build the current page's root in `arena`, or the not-found page's when 3228 // the route names nothing 3229 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 3230 session.page_arena = arena; 3231 const page = try arena.allocator().create(Page); 3232 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 3233 error.NotFound => blk: { 3234 session.data.current_page = .not_found; 3235 break :blk .not_found; 3236 }, 3237 else => |e| return e, 3238 }; 3239 return initRoot(allocator, page, session); 3240 } 3241 3242 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 3243 arena.deinit(); 3244 allocator.destroy(arena); 3245 } 3246 3247 // reconcile the displayed root with the session's navigation state. a 3248 // forward nav (current_page moved to a different parent page) pushes the 3249 // current root and builds the new page in a fresh arena; a back request 3250 // frees the current page and restores the previous one. when escape is 3251 // pressed with no history left we switch to the quit tab instead of quitting. 3252 // returns whether the root was replaced. 3253 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 3254 // refresh: rebuild the current page in place from a current moment 3255 if (session.refresh_requested) { 3256 session.refresh_requested = false; 3257 try self.rebuild(allocator, session); 3258 return true; 3259 } 3260 3261 if (session.back == .requested) { 3262 if (self.history.pop()) |entry| { 3263 session.back = if (self.history.items.len == 0) .unavailable else .available; 3264 self.root.deinit(allocator); 3265 freeArena(allocator, self.arena); 3266 self.root = entry.root; 3267 self.arena = entry.arena; 3268 self.user_id = entry.user_id; 3269 session.page_arena = entry.arena; 3270 session.data.current_page = entry.route; 3271 // a page built under another login is rebuilt rather than restored 3272 if (!std.meta.eql(entry.user_id, session.userId())) { 3273 try self.rebuild(allocator, session); 3274 return true; 3275 } 3276 chooseAnsiArtForNavigation(session); 3277 return true; 3278 } 3279 session.back = .unavailable; 3280 // nothing to go back to; switch to the quit confirmation 3281 const root_focus = self.root.getFocus(); 3282 var iter = root_focus.children.iterator(); 3283 while (iter.next()) |entry| { 3284 switch (entry.value_ptr.focus.kind) { 3285 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 3286 root_focus.setFocus(entry.key_ptr.*); 3287 // a Stack only builds its selected child, so the quit 3288 // button isn't in the focus tree until a build runs with 3289 // the quit tab selected. build once, then send a 3290 // synthetic arrow_down to drop focus from the tab onto 3291 // the button so it's ready to confirm. 3292 try self.root.build(allocator, .{ 3293 .min_size = .{ .width = null, .height = 40 }, 3294 .max_size = .{ .width = 80, .height = null }, 3295 }, root_focus); 3296 try self.root.input(allocator, .arrow_down, root_focus); 3297 break; 3298 }, 3299 else => {}, 3300 } 3301 } 3302 return false; 3303 } 3304 3305 // forward navigation: navigate() set next_page to the page to move to (a 3306 // cross-page link or tab change crossing pages) 3307 if (session.next_page) |route| { 3308 session.next_page = null; 3309 if (session.haxy_moment == null and session.local == null) return false; 3310 const previous_route = session.data.current_page; 3311 // the page we navigated to becomes the current page 3312 session.data.current_page = route; 3313 session.back = .available; 3314 3315 const arena = try allocator.create(std.heap.ArenaAllocator); 3316 arena.* = std.heap.ArenaAllocator.init(allocator); 3317 errdefer freeArena(allocator, arena); 3318 3319 const new_root = try initCurrentRoot(allocator, arena, session); 3320 3321 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 3322 // drop the oldest entry (freeing its widget tree and arena) once over cap 3323 if (self.history.items.len > max_history) { 3324 var oldest = self.history.orderedRemove(0); 3325 oldest.root.deinit(allocator); 3326 freeArena(allocator, oldest.arena); 3327 } 3328 self.root = new_root; 3329 self.arena = arena; 3330 self.user_id = session.userId(); 3331 return true; 3332 } 3333 return false; 3334 } 3335 }; 3336 3337 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3338 const page_widget: Widget = switch (page.*) { 3339 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3340 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3341 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3342 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3343 .not_found => .{ .not_found = try .init(allocator, session) }, 3344 }; 3345 3346 chooseAnsiArtForNavigation(session); 3347 3348 // on the TUI/SSH, the page sits above a one-row footer showing its web 3349 // url, when there's a web UI to point at 3350 var root = if (session.is_terminal) blk: { 3351 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3352 errdefer box.deinit(allocator); 3353 const bg_id = bg_blk: { 3354 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3355 errdefer background.deinit(allocator); 3356 const id = background.getFocus().id; 3357 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3358 break :bg_blk id; 3359 }; 3360 if (session.web_url != null) { 3361 var footer = try widget.Footer.init(allocator, session); 3362 errdefer footer.deinit(allocator); 3363 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3364 } 3365 box.getFocus().child_id = bg_id; 3366 break :blk Widget{ .box = box }; 3367 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3368 errdefer root.deinit(allocator); 3369 3370 // input-owning views build their TextInputs in init, so reset their 3371 // registrations here 3372 session.text_inputs.clearRetainingCapacity(); 3373 3374 try root.build(allocator, .{ 3375 .min_size = .{ .width = null, .height = 40 }, 3376 .max_size = .{ .width = 100, .height = null }, 3377 }, root.getFocus()); 3378 3379 return root; 3380 } 3381 3382 // native and server-side sessions choose from the embedded collection. WASM 3383 // keeps the art serialized by the server instead. 3384 fn chooseAnsiArtForNavigation(session: *Session) void { 3385 if (comptime ansi_art.art.len == 0) return; 3386 if (session.data.current_page == .not_found) { 3387 session.data.ansi_art = ansi_art.not_found; 3388 return; 3389 } 3390 const io = session.io orelse return; 3391 var random: usize = undefined; 3392 io.random(std.mem.asBytes(&random)); 3393 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3394 } 3395