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