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