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