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