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