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