╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1925 } 1926 1927 var oid: [hex_len]u8 = undefined; 1928 switch (ref_or_oid) { 1929 .object => { 1930 if (value.len != hex_len) return null; 1931 @memcpy(&oid, value); 1932 }, 1933 .branch, .tag => { 1934 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 1935 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 1936 }, 1937 } 1938 // store url-encoded so the route layer can hold the value verbatim. 1939 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 1940 } 1941 }; 1942 } 1943 1944 // who a repo page is built for, which picks the actions it shows 1945 pub const Viewer = struct { 1946 role: evt.Repo.Role, 1947 email: []const u8, 1948 1949 // the session's viewer of a repo it holds `role` in, or null when logged 1950 // out. local mode owns everything. 1951 pub fn init(session: *Session, arena: *std.heap.ArenaAllocator, role: evt.Repo.Role) !?Viewer { 1952 if (session.data.host_kind == .local) return .{ .role = .owner, .email = "" }; 1953 const user_id = session.userId() orelse return null; 1954 const moment = session.haxy_moment orelse unreachable; 1955 const user = (try activeUser(moment, arena, user_id)) orelse return null; 1956 return .{ .role = role, .email = user.event.email }; 1957 } 1958 }; 1959 1960 // a repo a page shows, and what its viewer may do there 1961 pub const RepoHandle = struct { 1962 location: RoutablePage.RepoLocation, 1963 viewer: ?Viewer = null, 1964 1965 pub fn dupe(self: RepoHandle, allocator: std.mem.Allocator) !RepoHandle { 1966 var copy = self; 1967 copy.location = try self.location.dupe(allocator); 1968 return copy; 1969 } 1970 1971 // pushing, and seeing the events and undo tabs. local mode is always owner. 1972 pub fn canWrite(self: RepoHandle) bool { 1973 const viewer = self.viewer orelse return false; 1974 return viewer.role.atLeast(.write); 1975 } 1976 1977 pub fn canUndo(self: RepoHandle) bool { 1978 const viewer = self.viewer orelse return false; 1979 return viewer.role == .owner; 1980 } 1981 }; 1982 1983 // where a repo page reads its on-disk repo from 1984 pub const RepoSource = struct { 1985 path: []const u8, 1986 repo_kind: rp.RepoKind, 1987 // the user's global git config, so local mode picks up their identity and 1988 // their signing and ssh settings. null on the server paths, which must not 1989 // read whoever runs the server. 1990 global_config_path: ?[]const u8 = null, 1991 1992 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 1993 return .{ .path = self.path, .global_config_path = self.global_config_path }; 1994 } 1995 1996 pub fn hasBranch(self: RepoSource, io: std.Io, allocator: std.mem.Allocator, branch: []const u8) !bool { 1997 if (!xit.ref.validateName(branch)) return false; 1998 return switch (self.repo_kind) { 1999 inline else => |repo_kind| blk: { 2000 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2001 defer any_repo.deinit(io, allocator); 2002 break :blk switch (any_repo) { 2003 inline else => |*repo| (try repo.readRef(io, .{ .kind = .head, .name = branch })) != null, 2004 }; 2005 }, 2006 }; 2007 } 2008 2009 // whether the actor may change the event `id` names 2010 pub fn canModify( 2011 self: RepoSource, 2012 io: std.Io, 2013 allocator: std.mem.Allocator, 2014 actor: Actor, 2015 kind: evt.EventKind, 2016 id: *const [evt.event_id_size]u8, 2017 ) !bool { 2018 // a role that may change an event with no author needs no read 2019 if (actor.role.canModify(actor.author.email, null)) return true; 2020 2021 var arena = std.heap.ArenaAllocator.init(allocator); 2022 defer arena.deinit(); 2023 return switch (self.repo_kind) { 2024 inline else => |repo_kind| blk: { 2025 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2026 defer any_repo.deinit(io, allocator); 2027 break :blk switch (any_repo) { 2028 inline else => |*repo| actor.role.canModify(actor.author.email, try evt.readAuthorEmail(repo_kind, repo.self_repo_opts, io, allocator, &arena, repo, kind, id)), 2029 }; 2030 }, 2031 }; 2032 } 2033 }; 2034 2035 // who a write acts as and the role they hold in its repo 2036 pub const Actor = struct { 2037 author: evt.CommitAuthor, 2038 // local mode has no accounts, so it has no user id 2039 user_id: ?[evt.event_id_size]u8 = null, 2040 role: evt.Repo.Role, 2041 // the repo owner's id, which local mode lacks 2042 repo_user_id: ?[evt.event_id_size]u8 = null, 2043 }; 2044 2045 pub const Authorization = union(enum) { 2046 actor: Actor, 2047 login_required, 2048 repo_not_found, 2049 forbidden, 2050 }; 2051 2052 // the account `user_id` names, or null once it has been removed. a user id is 2053 // checked here wherever one enters, so the role lookups can trust theirs. 2054 pub fn activeUser( 2055 moment: evt.AdminDB.HashMap(.read_only), 2056 arena: *std.heap.ArenaAllocator, 2057 user_id: [evt.event_id_size]u8, 2058 ) !?evt.User.Record { 2059 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 2060 return if (user.removed) null else user; 2061 } 2062 2063 // whether the user may write to the repo `identity` names with at least 2064 // `min_role`, and to the `thread_kind` tab when there is one 2065 pub fn authorizeUser( 2066 io: std.Io, 2067 moment: evt.AdminDB.HashMap(.read_only), 2068 arena: *std.heap.ArenaAllocator, 2069 users_dir: []const u8, 2070 user_id: [evt.event_id_size]u8, 2071 identity: []const u8, 2072 min_role: evt.Repo.Role, 2073 thread_kind: ?evt.EventKind, 2074 ) !Authorization { 2075 const user = (try activeUser(moment, arena, user_id)) orelse return .login_required; 2076 2077 const owner_repo = evt.parseOwnerRepoPath(identity) orelse return .repo_not_found; 2078 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; 2079 // a repo the user can't read doesn't exist to them 2080 const role = repo.role orelse return .repo_not_found; 2081 if (!role.atLeast(min_role)) return .forbidden; 2082 if (thread_kind) |kind| { 2083 // a tab that is off doesn't exist 2084 const tab_role = repo.repo.event.threadRole(kind) orelse return .repo_not_found; 2085 if (!role.atLeast(tab_role)) return .forbidden; 2086 } 2087 return .{ .actor = .{ 2088 .author = .{ .name = user.event.name, .email = user.event.email }, 2089 .user_id = user_id, 2090 .role = role, 2091 .repo_user_id = repo.repo.event.user_id[0..evt.event_id_size].*, 2092 } }; 2093 } 2094 2095 // events created in local mode have no account behind them, so the commit 2096 // author comes from the repo's config, which the global config feeds into. 2097 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 2098 2099 pub fn localAuthor( 2100 src: RepoSource, 2101 io: std.Io, 2102 allocator: std.mem.Allocator, 2103 arena: *std.heap.ArenaAllocator, 2104 ) !evt.CommitAuthor { 2105 switch (src.repo_kind) { 2106 inline else => |repo_kind| { 2107 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 2108 defer any_repo.deinit(io, allocator); 2109 2110 switch (any_repo) { 2111 inline else => |*repo| { 2112 var config = try repo.listConfig(io, allocator); 2113 defer config.deinit(); 2114 2115 const user = config.sections.get("user") orelse return local_author_fallback; 2116 const name = user.get("name") orelse return local_author_fallback; 2117 const email = user.get("email") orelse return local_author_fallback; 2118 return .{ 2119 .name = try arena.allocator().dupe(u8, name), 2120 .email = try arena.allocator().dupe(u8, email), 2121 }; 2122 }, 2123 } 2124 }, 2125 } 2126 } 2127 2128 // per-connection mutable state. each SSH session / web session / local TUI 2129 // run gets its own. 2130 pub const Session = struct { 2131 data: Data = .{}, 2132 // session-lifetime allocations: login/user_id, persisted prefs, queued 2133 // actions. lives as long as the connection. 2134 arena: *std.heap.ArenaAllocator, 2135 // current page's allocations: page data and the page-scoped strings widgets 2136 // build (form actions, links). owned by Nav, swapped on each navigation, so 2137 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 2138 // where a render is one-shot, this points at the same arena as `arena`. 2139 page_arena: *std.heap.ArenaAllocator, 2140 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2141 // filesystem io and the path to <server>/repos, for opening on-disk repos 2142 // during page construction. both null on wasm, which has no filesystem and 2143 // rebuilds pages from the serialized snapshot rather than from disk. 2144 io: ?std.Io = null, 2145 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2146 users_dir: ?[]const u8 = null, 2147 // the single on-disk repo this session views, when running in local mode 2148 // (haxy invoked with no arguments inside a repo). null on the server paths, 2149 // which resolve repos from the admin db instead. 2150 local: ?RepoSource = null, 2151 // focus id -> the live TextInput, refreshed each frame by the views that own 2152 // inputs. web/wasm form handling looks widgets up here by focus id. 2153 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2154 back: enum { unavailable, available, requested } = .unavailable, 2155 refresh_requested: bool = false, // set by input (ctrl+r) 2156 // a requested forward navigation. set this (via navigate) to move to a new 2157 // page; Nav.sync builds it and then copies it into current_page, clearing 2158 // this back to null. setting current_page directly only updates the url and 2159 // does not navigate. 2160 next_page: ?RoutablePage = null, 2161 is_terminal: bool = false, // true on remote SSH and local TUI 2162 color: bool = true, // false when NO_COLOR is set, which also hides the art 2163 // the terminal's reported default background, which the art blends toward 2164 terminal_background: ?Grid.Color.Rgb = null, 2165 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 2166 // url. null on the web itself (no footer there). 2167 web_port: ?u16 = null, 2168 // a host operation requested by a widget 2169 host_request: ?HostRequest = null, 2170 quit_requested: bool = false, 2171 2172 pub const HostRequest = union(enum) { 2173 show_copyable_text: []const u8, 2174 sync_events, 2175 undo: RoutablePage.RepoUndoRoute, 2176 }; 2177 2178 pub const FormFeedback = union(enum) { 2179 pub const LoginFailure = enum { unknown_user, wrong_password }; 2180 pub const ThreadFailure = enum { required_title }; 2181 pub const PatchFailure = enum { 2182 required_title, 2183 invalid_target_branch, 2184 invalid_source_branch, 2185 same_branch, 2186 unrelated_branches, 2187 2188 pub fn fromError(err: anyerror) ?PatchFailure { 2189 return switch (err) { 2190 error.InvalidTargetBranch => .invalid_target_branch, 2191 error.InvalidSourceBranch => .invalid_source_branch, 2192 error.SameBranch => .same_branch, 2193 error.UnrelatedBranches => .unrelated_branches, 2194 else => null, 2195 }; 2196 } 2197 }; 2198 2199 pub const RepoFailure = enum { 2200 required_name, 2201 invalid_name, 2202 name_taken, 2203 2204 pub fn fromError(err: anyerror) ?RepoFailure { 2205 return switch (err) { 2206 error.NameEmpty => .required_name, 2207 error.NameTooLong, error.InvalidName => .invalid_name, 2208 error.NameTaken => .name_taken, 2209 else => null, 2210 }; 2211 } 2212 }; 2213 2214 pub const UserFailure = enum { 2215 required_name, 2216 invalid_name, 2217 name_taken, 2218 required_email, 2219 email_taken, 2220 required_password, 2221 password_mismatch, 2222 wrong_password, 2223 2224 pub fn fromError(err: anyerror) ?UserFailure { 2225 return switch (err) { 2226 error.NameEmpty => .required_name, 2227 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2228 error.NameTaken => .name_taken, 2229 error.EmailEmpty => .required_email, 2230 error.EmailTaken => .email_taken, 2231 error.PasswordEmpty => .required_password, 2232 error.PasswordMismatch => .password_mismatch, 2233 error.WrongPassword => .wrong_password, 2234 else => null, 2235 }; 2236 } 2237 }; 2238 2239 login: struct { 2240 failure: LoginFailure, 2241 username: []const u8, 2242 }, 2243 user: struct { 2244 failure: UserFailure, 2245 // passwords are never retained 2246 fields: struct { 2247 name: []const u8, 2248 email: []const u8, 2249 }, 2250 }, 2251 user_settings: struct { 2252 failure: UserFailure, 2253 // passwords are never retained 2254 fields: struct { email: []const u8 }, 2255 }, 2256 repo: struct { 2257 failure: RepoFailure, 2258 fields: struct { 2259 name: []const u8, 2260 description: []const u8, 2261 hash: hash.HashKind, 2262 access: evt.Repo.Access, 2263 }, 2264 }, 2265 repo_settings: struct { 2266 failure: RepoFailure, 2267 fields: struct { 2268 name: []const u8, 2269 description: []const u8, 2270 access: evt.Repo.Access, 2271 discuss_role: ?evt.Repo.Role, 2272 issue_role: ?evt.Repo.Role, 2273 patch_role: ?evt.Repo.Role, 2274 }, 2275 }, 2276 issue: struct { 2277 failure: ThreadFailure, 2278 fields: ?struct { 2279 title: []const u8, 2280 labels: []const u8, 2281 description: []const u8, 2282 } = null, 2283 }, 2284 patch: struct { 2285 failure: PatchFailure, 2286 fields: ?struct { 2287 title: []const u8, 2288 labels: []const u8, 2289 description: []const u8, 2290 target_branch: []const u8, 2291 source_branch: []const u8 = "", 2292 source_kind: Repo.Patches.Source.Kind = .fork, 2293 } = null, 2294 }, 2295 discussion: struct { 2296 failure: ThreadFailure, 2297 fields: ?struct { 2298 title: []const u8, 2299 labels: []const u8, 2300 description: []const u8, 2301 } = null, 2302 }, 2303 }; 2304 2305 const Self = @This(); 2306 2307 // serializable data sent down to web client 2308 pub const Data = struct { 2309 user_id: ?[]const u8 = null, 2310 // the logged-in user's name and email, for the views that show them 2311 user_name: ?[]const u8 = null, 2312 user_email: ?[]const u8 = null, 2313 // a failed form retained long enough to render it for correction 2314 form_feedback: ?FormFeedback = null, 2315 // a transient local event-sync error 2316 sync_failure: ?[]const u8 = null, 2317 // a failed terminal undo retained on the current tab 2318 undo_failure: ?[]const u8 = null, 2319 current_page: RoutablePage = .default, 2320 // the selected ANSI art. the server serializes one image for WASM so 2321 // the browser does not need the whole build-generated collection. 2322 ansi_art: []const u8 = "", 2323 // the bound git-service ports. absent in local mode, where remote urls 2324 // are not shown. 2325 git_http_port: ?u16 = null, 2326 git_ssh_port: ?u16 = null, 2327 git_ssh_prefix: []const u8 = "", 2328 // whether this session views a local repo or the server. unlike `local` 2329 // (the host-side filesystem source) this travels in the snapshot, so 2330 // the wasm side also parses elided link urls and hides the multi-user 2331 // chrome. 2332 host_kind: evt.HostKind = .server, 2333 }; 2334 2335 pub fn init( 2336 arena: *std.heap.ArenaAllocator, 2337 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2338 data: Data, 2339 ) !Self { 2340 var session = Self{ 2341 .data = data, 2342 .arena = arena, 2343 // until a host swaps in a page-scoped arena (Nav does this), page 2344 // allocations land in the session arena. on the web path that's the 2345 // intended behavior, since the whole arena is per-request. 2346 .page_arena = arena, 2347 .admin_repo = repo, 2348 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2349 }; 2350 try session.loadUser(); 2351 return session; 2352 } 2353 2354 // load the logged-in user's name and persisted preferences from the db 2355 pub fn loadUser(self: *Self) !void { 2356 const user_id = self.userId() orelse return; 2357 const moment = self.haxy_moment orelse return; 2358 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2359 self.data.user_name = user.event.name; 2360 self.data.user_email = user.event.email; 2361 } 2362 2363 // forget the logged-in user, on a logout or once their account is removed 2364 pub fn logOut(self: *Self) void { 2365 self.data.user_id = null; 2366 self.data.user_name = null; 2367 self.data.user_email = null; 2368 } 2369 2370 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2371 const bytes = self.data.user_id orelse return null; 2372 if (bytes.len != evt.event_id_size) return null; 2373 var id: [evt.event_id_size]u8 = undefined; 2374 @memcpy(&id, bytes); 2375 return id; 2376 } 2377 2378 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2379 const feedback = self.data.form_feedback orelse return null; 2380 if (std.meta.activeTag(feedback) != tag) return null; 2381 return @field(feedback, @tagName(tag)); 2382 } 2383 2384 pub fn clearFormFeedback(self: *Self) void { 2385 self.data.form_feedback = null; 2386 } 2387 2388 // the actor for a write to the repo `identity` names, or null when the 2389 // session may not write there with at least `min_role` or in the 2390 // `thread_kind` tab. local mode always writes. 2391 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2392 if (self.data.host_kind == .local) { 2393 const author = blk: { 2394 const src = self.local orelse break :blk local_author_fallback; 2395 const io = self.io orelse break :blk local_author_fallback; 2396 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2397 }; 2398 return .{ .author = author, .role = .owner }; 2399 } 2400 const user_id = self.userId() orelse return null; 2401 // the session's moment predates this input, so read the roles afresh 2402 const admin_repo = self.admin_repo orelse return null; 2403 const io = self.io orelse return null; 2404 const users_dir = self.users_dir orelse return null; 2405 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2406 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2407 .actor => |actor| actor, 2408 .login_required, .repo_not_found, .forbidden => null, 2409 }; 2410 } 2411 2412 // where this session's event writes go. a server session always has a users dir 2413 pub fn eventHost(self: *const Self) evt.Host { 2414 return switch (self.data.host_kind) { 2415 .local => .local, 2416 .server => .{ .server = .{ .users_dir = self.users_dir orelse unreachable } }, 2417 }; 2418 } 2419 2420 // reload the moment from the admin repo and log out a removed user 2421 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2422 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2423 self.haxy_moment = moment; 2424 2425 const user_id = self.userId() orelse return; 2426 var arena = std.heap.ArenaAllocator.init(allocator); 2427 defer arena.deinit(); 2428 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2429 } 2430 2431 // request a forward navigation to `route`; the host consumes next_page 2432 // (Nav.sync on the terminal, the wasm tick on the web). 2433 pub fn navigate(self: *Session, route: RoutablePage) !void { 2434 self.clearFormFeedback(); 2435 self.next_page = route; 2436 } 2437 }; 2438 2439 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2440 var nav = try Nav.init(allocator, session); 2441 defer nav.deinit(allocator); 2442 2443 var terminal = try term.Terminal.init(io, allocator); 2444 terminal.render_state.no_color = !session.color; 2445 var terminal_live = true; 2446 defer if (terminal_live) terminal.deinit(io); 2447 2448 // set term as active so it will be properly cooked 2449 // when a panic/segfault happens 2450 term.setActive(&terminal); 2451 defer term.setActive(null); 2452 2453 try terminal.queryBackground(); 2454 2455 while (!terminal.shouldQuit()) { 2456 const grid_changed = try terminal.render(&nav.root); 2457 2458 // process any inputs. 2459 // 2460 // if the grid didn't change, then first do a blocking 2461 // read, so the thread will sleep until further input. 2462 // after that, all remaining reads are non-blocking so 2463 // we can process the rest of the queued inputs. 2464 // 2465 // if the grid *did* change, then only do non-blocking 2466 // reads. we do not want to sleep the thread because 2467 // there may be an animation that requires more looping. 2468 var blocking = !grid_changed; 2469 while (try terminal.readKey(io, blocking)) |key| { 2470 blocking = false; 2471 try inputKey(allocator, &nav.root, key, session); 2472 } 2473 2474 if (session.host_request) |request| { 2475 session.host_request = null; 2476 switch (request) { 2477 .show_copyable_text => |copyable_text| { 2478 term.setActive(null); 2479 terminal.deinit(io); 2480 terminal_live = false; 2481 showCopyableText(io, copyable_text) catch |show_err| { 2482 terminal = try term.Terminal.init(io, allocator); 2483 terminal_live = true; 2484 term.setActive(&terminal); 2485 return show_err; 2486 }; 2487 terminal = try term.Terminal.init(io, allocator); 2488 terminal.render_state.no_color = !session.color; 2489 terminal_live = true; 2490 term.setActive(&terminal); 2491 }, 2492 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2493 .sync_events => { 2494 try nav.root.build(allocator, .{ 2495 .min_size = .{ .width = null, .height = null }, 2496 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2497 }, nav.root.getFocus()); 2498 _ = try terminal.render(&nav.root); 2499 try Repo.Events.performSync(allocator, session); 2500 }, 2501 } 2502 } 2503 2504 // reload so the next navigation builds its page from the current moment 2505 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2506 2507 // reconcile navigation: forward to a new page, or back on escape. 2508 // the terminal background can change at any time, so recheck it on each page 2509 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2510 2511 // the quit button (on the quit tab) asks the host to tear down. 2512 if (session.quit_requested) terminal.requestQuit(); 2513 2514 try nav.root.build(allocator, .{ 2515 .min_size = .{ .width = null, .height = null }, 2516 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2517 }, nav.root.getFocus()); 2518 } 2519 } 2520 2521 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2522 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2523 null 2524 else 2525 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2526 defer if (tty) |file| file.close(io); 2527 2528 const input = if (tty) |file| file else std.Io.File.stdin(); 2529 const output = if (tty) |file| file else std.Io.File.stdout(); 2530 2531 var write_buf: [1024]u8 = undefined; 2532 var writer = output.writer(io, &write_buf); 2533 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}); 2534 try writer.interface.flush(); 2535 2536 var read_buf: [1]u8 = undefined; 2537 var reader = input.reader(io, &read_buf); 2538 while (true) { 2539 const byte = try reader.interface.takeByte(); 2540 if (byte == '\r' or byte == '\n') return; 2541 } 2542 } 2543 2544 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2545 const root_focus = root.getFocus(); 2546 const focused_before = root_focus.grandchild_id; 2547 var activate_in_page_link = false; 2548 switch (key) { 2549 // request a navigation pop; the host's Nav.sync goes back a page, or 2550 // quits when there's no history left. 2551 .escape => { 2552 session.back = .requested; 2553 return; 2554 }, 2555 .ctrl => |letter| switch (letter) { 2556 'r' => { 2557 session.refresh_requested = true; 2558 return; 2559 }, 2560 else => try root.input(allocator, key, root_focus), 2561 }, 2562 .enter => { 2563 if (root_focus.grandchild_id) |gid| { 2564 // follow a cross-page link 2565 if (crossPageLink(root_focus, gid, session.data)) |route| { 2566 return session.navigate(route); 2567 } 2568 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2569 } 2570 activate_in_page_link = true; 2571 try root.input(allocator, key, root_focus); 2572 }, 2573 .mouse => |mouse| { 2574 if (mouse.action == .press and mouse.action.press == .left) { 2575 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2576 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2577 const focus_id = hit.id; 2578 if (hit.kind == .background) { 2579 root_focus.setFocus(focus_id); 2580 return; 2581 } 2582 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2583 if (session.back == .available) session.back = .requested; 2584 return; 2585 } 2586 // follow a cross-page link 2587 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2588 return session.navigate(route); 2589 } 2590 if (currentPageLink(root_focus, focus_id, session.data)) return; 2591 if (rawLink(root_focus, focus_id)) |url| { 2592 if (!mouse.ctrl) try requestRawLink(session, url); 2593 return; 2594 } 2595 root_focus.setFocus(focus_id); 2596 activate_in_page_link = true; 2597 } 2598 // forward the press into the widget tree so buttons (and any 2599 // future click-aware widgets) can react. widgets that don't 2600 // care about presses ignore it. 2601 try root.input(allocator, key, root_focus); 2602 } else { 2603 try root.input(allocator, key, root_focus); 2604 } 2605 }, 2606 .event => |event| switch (event) { 2607 .background => |rgb| session.terminal_background = rgb, 2608 .resize => try root.input(allocator, key, root_focus), 2609 }, 2610 else => try root.input(allocator, key, root_focus), 2611 } 2612 2613 const focused_after = root_focus.grandchild_id; 2614 if (!activate_in_page_link and focused_before == focused_after) return; 2615 const focus_id = focused_after orelse return; 2616 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2617 } 2618 2619 // a link to bytes the server serves directly rather than to a page route, so 2620 // it never resolves to a RoutablePage 2621 pub const raw_link_prefix = "ax:"; 2622 2623 // a route already loaded into the current page; focusing it changes the url 2624 // without rebuilding the page 2625 pub const in_page_link_prefix = "ai:"; 2626 2627 // an in-page tab's base route, or the exact current route when it is selected 2628 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2629 const target = if (selected) session.data.current_page else route; 2630 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2631 } 2632 2633 // a button the web renderer covers with a file picker that posts the chosen 2634 // file to the url after the prefix 2635 pub const file_input_prefix = "file:"; 2636 2637 // a submit button that overrides its enclosing form's action 2638 pub const submit_action_prefix = "submit:"; 2639 2640 // one option of a radio field, as `radio:<name>=<value>` 2641 pub const radio_prefix = "radio:"; 2642 2643 // the url an `ax:` link points at, or null for anything else. a host that 2644 // suppresses the anchor's own navigation needs this to follow the link. 2645 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2646 const child = root_focus.children.get(focus_id) orelse return null; 2647 const custom = switch (child.focus.kind) { 2648 .custom => |c| c, 2649 else => return null, 2650 }; 2651 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2652 return custom[raw_link_prefix.len..]; 2653 } 2654 2655 fn requestRawLink(session: *Session, url: []const u8) !void { 2656 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2657 } 2658 2659 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2660 // an absolute url is already complete 2661 if (!std.mem.startsWith(u8, path, "/")) return path; 2662 return if (session.web_port) |port| 2663 try allocator.print("http://localhost:{d}{s}", .{ port, path }) 2664 else 2665 path; 2666 } 2667 2668 // if the focus target at focus_id is an `a:` link that should navigate (a 2669 // different parent page, or a different files directory within the repo page), 2670 // return its route; otherwise null. lets a host turn a click / enter on such a 2671 // link into a navigation rather than a focus change. 2672 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2673 const current = data.current_page; 2674 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2675 // a link to a different parent page always navigates; within a page, a 2676 // files-directory / commits-page / list-window change navigates while tab 2677 // links stay in-page. 2678 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; 2679 return null; 2680 } 2681 2682 // the page the clicked cell links to, from a link inside a text box's content 2683 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 2684 const grid = root.getGrid() orelse return null; 2685 const cell = grid.cell(x, y) catch return null; 2686 const link = cell.link orelse return null; 2687 if (link.len == 0 or link[0] != '/') return null; 2688 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 2689 } 2690 2691 // whether the `a:` focus target links to the page already shown, which a click 2692 // leaves alone rather than focusing 2693 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 2694 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 2695 return route.eql(data.current_page); 2696 } 2697 2698 // the route carried by an `ai:` focus target, or null for any other target 2699 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2700 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2701 } 2702 2703 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2704 const child = root_focus.children.get(focus_id) orelse return null; 2705 const custom = switch (child.focus.kind) { 2706 .custom => |c| c, 2707 else => return null, 2708 }; 2709 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2710 const path = custom[prefix.len..]; 2711 // local sessions build (and parse) links with the repo identity elided 2712 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2713 } 2714 2715 // a display author, resolved against the admin db at read time 2716 pub const Author = union(enum) { 2717 unknown, 2718 email: []const u8, // an email no user matches 2719 user_name: []const u8, 2720 2721 // the commit author line's email, resolved like initFromEmail 2722 pub fn init( 2723 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2724 arena: *std.heap.ArenaAllocator, 2725 author_line: []const u8, 2726 ) !Author { 2727 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2728 } 2729 2730 // from a record's stored author email: it resolves to the user currently 2731 // holding it, else stays the email. the result is allocated in `arena`, 2732 // so the email may borrow transient memory. 2733 pub fn initFromEmail( 2734 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2735 arena: *std.heap.ArenaAllocator, 2736 author_email: ?[]const u8, 2737 ) !Author { 2738 const email = author_email orelse return .unknown; 2739 if (haxy_moment) |moment| { 2740 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2741 return .{ .user_name = user.name }; 2742 } 2743 } 2744 return .{ .email = try arena.allocator().dupe(u8, email) }; 2745 } 2746 }; 2747 2748 // the "a:" link to user `name`'s page. 2749 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2750 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2751 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2752 return page_arena.allocator().print("a:{s}", .{url}); 2753 } 2754 2755 // a focusable " author " box showing `author`, linking to their user page 2756 // when it is a known user 2757 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2758 const text = switch (author) { 2759 .unknown => "", 2760 .email, .user_name => |t| t, 2761 }; 2762 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 2763 errdefer tb.deinit(allocator); 2764 tb.getFocus().mode = .all; 2765 switch (author) { 2766 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2767 else => {}, 2768 } 2769 return tb; 2770 } 2771 2772 // native-TUI navigation 2773 pub const Nav = struct { 2774 root: Widget, 2775 // backs the current page (its Page data and the page-scoped strings its 2776 // widgets build). owned here, swapped on each navigation. session.page_arena 2777 // tracks whichever of these is current so widgets allocate into it. 2778 arena: *std.heap.ArenaAllocator, 2779 // the login the current root was built for 2780 user_id: ?[evt.event_id_size]u8, 2781 history: std.ArrayList(Entry), 2782 2783 // each retained page keeps its own arena, freed when the page leaves the 2784 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2785 // long-lived session from accumulating every page it ever visited. 2786 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 2787 2788 // cap on retained back-history so the chain can't grow memory without bound 2789 const max_history: usize = 16; 2790 2791 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2792 session.back = .unavailable; 2793 const arena = try allocator.create(std.heap.ArenaAllocator); 2794 arena.* = std.heap.ArenaAllocator.init(allocator); 2795 errdefer { 2796 arena.deinit(); 2797 allocator.destroy(arena); 2798 } 2799 2800 return .{ 2801 .root = try initCurrentRoot(allocator, arena, session), 2802 .arena = arena, 2803 .user_id = session.userId(), 2804 .history = .empty, 2805 }; 2806 } 2807 2808 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2809 self.root.deinit(allocator); 2810 freeArena(allocator, self.arena); 2811 for (self.history.items) |*entry| { 2812 entry.root.deinit(allocator); 2813 freeArena(allocator, entry.arena); 2814 } 2815 self.history.deinit(allocator); 2816 } 2817 2818 // rebuild the current page in place from a current moment 2819 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2820 if (session.haxy_moment == null and session.local == null) return; 2821 const arena = try allocator.create(std.heap.ArenaAllocator); 2822 arena.* = std.heap.ArenaAllocator.init(allocator); 2823 errdefer freeArena(allocator, arena); 2824 2825 const new_root = try initCurrentRoot(allocator, arena, session); 2826 2827 self.root.deinit(allocator); 2828 freeArena(allocator, self.arena); 2829 self.root = new_root; 2830 self.arena = arena; 2831 self.user_id = session.userId(); 2832 } 2833 2834 // build the current page's root in `arena`, or the not-found page's when 2835 // the route names nothing 2836 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 2837 session.page_arena = arena; 2838 const page = try arena.allocator().create(Page); 2839 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 2840 error.NotFound => blk: { 2841 session.data.current_page = .not_found; 2842 break :blk .not_found; 2843 }, 2844 else => |e| return e, 2845 }; 2846 return initRoot(allocator, page, session); 2847 } 2848 2849 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2850 arena.deinit(); 2851 allocator.destroy(arena); 2852 } 2853 2854 // reconcile the displayed root with the session's navigation state. a 2855 // forward nav (current_page moved to a different parent page) pushes the 2856 // current root and builds the new page in a fresh arena; a back request 2857 // frees the current page and restores the previous one. when escape is 2858 // pressed with no history left we switch to the quit tab instead of quitting. 2859 // returns whether the root was replaced. 2860 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 2861 // refresh: rebuild the current page in place from a current moment 2862 if (session.refresh_requested) { 2863 session.refresh_requested = false; 2864 try self.rebuild(allocator, session); 2865 return true; 2866 } 2867 2868 if (session.back == .requested) { 2869 if (self.history.pop()) |entry| { 2870 session.back = if (self.history.items.len == 0) .unavailable else .available; 2871 self.root.deinit(allocator); 2872 freeArena(allocator, self.arena); 2873 self.root = entry.root; 2874 self.arena = entry.arena; 2875 self.user_id = entry.user_id; 2876 session.page_arena = entry.arena; 2877 session.data.current_page = entry.route; 2878 // a page built under another login is rebuilt rather than restored 2879 if (!std.meta.eql(entry.user_id, session.userId())) { 2880 try self.rebuild(allocator, session); 2881 return true; 2882 } 2883 chooseAnsiArtForNavigation(session); 2884 return true; 2885 } 2886 session.back = .unavailable; 2887 // nothing to go back to; switch to the quit confirmation 2888 const root_focus = self.root.getFocus(); 2889 var iter = root_focus.children.iterator(); 2890 while (iter.next()) |entry| { 2891 switch (entry.value_ptr.focus.kind) { 2892 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2893 root_focus.setFocus(entry.key_ptr.*); 2894 // a Stack only builds its selected child, so the quit 2895 // button isn't in the focus tree until a build runs with 2896 // the quit tab selected. build once, then send a 2897 // synthetic arrow_down to drop focus from the tab onto 2898 // the button so it's ready to confirm. 2899 try self.root.build(allocator, .{ 2900 .min_size = .{ .width = null, .height = 40 }, 2901 .max_size = .{ .width = 80, .height = null }, 2902 }, root_focus); 2903 try self.root.input(allocator, .arrow_down, root_focus); 2904 break; 2905 }, 2906 else => {}, 2907 } 2908 } 2909 return false; 2910 } 2911 2912 // forward navigation: navigate() set next_page to the page to move to (a 2913 // cross-page link or tab change crossing pages) 2914 if (session.next_page) |route| { 2915 session.next_page = null; 2916 if (session.haxy_moment == null and session.local == null) return false; 2917 const previous_route = session.data.current_page; 2918 // the page we navigated to becomes the current page 2919 session.data.current_page = route; 2920 session.back = .available; 2921 2922 const arena = try allocator.create(std.heap.ArenaAllocator); 2923 arena.* = std.heap.ArenaAllocator.init(allocator); 2924 errdefer freeArena(allocator, arena); 2925 2926 const new_root = try initCurrentRoot(allocator, arena, session); 2927 2928 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 2929 // drop the oldest entry (freeing its widget tree and arena) once over cap 2930 if (self.history.items.len > max_history) { 2931 var oldest = self.history.orderedRemove(0); 2932 oldest.root.deinit(allocator); 2933 freeArena(allocator, oldest.arena); 2934 } 2935 self.root = new_root; 2936 self.arena = arena; 2937 self.user_id = session.userId(); 2938 return true; 2939 } 2940 return false; 2941 } 2942 }; 2943 2944 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2945 const page_widget: Widget = switch (page.*) { 2946 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2947 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2948 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2949 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2950 .not_found => .{ .not_found = try .init(allocator, session) }, 2951 }; 2952 2953 chooseAnsiArtForNavigation(session); 2954 2955 // on the TUI/SSH, the page sits above a one-row footer showing its web 2956 // url, when there's a web UI to point at 2957 var root = if (session.is_terminal) blk: { 2958 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 2959 errdefer box.deinit(allocator); 2960 const bg_id = bg_blk: { 2961 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2962 errdefer background.deinit(allocator); 2963 const id = background.getFocus().id; 2964 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2965 break :bg_blk id; 2966 }; 2967 if (session.web_port != null) { 2968 var footer = try widget.Footer.init(allocator, session); 2969 errdefer footer.deinit(allocator); 2970 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2971 } 2972 box.getFocus().child_id = bg_id; 2973 break :blk Widget{ .box = box }; 2974 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2975 errdefer root.deinit(allocator); 2976 2977 // input-owning views build their TextInputs in init, so reset their 2978 // registrations here 2979 session.text_inputs.clearRetainingCapacity(); 2980 2981 try root.build(allocator, .{ 2982 .min_size = .{ .width = null, .height = 40 }, 2983 .max_size = .{ .width = 100, .height = null }, 2984 }, root.getFocus()); 2985 2986 return root; 2987 } 2988 2989 // native and server-side sessions choose from the embedded collection. WASM 2990 // keeps the art serialized by the server instead. 2991 fn chooseAnsiArtForNavigation(session: *Session) void { 2992 if (comptime ansi_art.art.len == 0) return; 2993 if (session.data.current_page == .not_found) { 2994 session.data.ansi_art = ansi_art.not_found; 2995 return; 2996 } 2997 const io = session.io orelse return; 2998 var random: usize = undefined; 2999 io.random(std.mem.asBytes(&random)); 3000 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3001 } 3002