╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
2313 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2314 // filesystem io and the path to <server>/repos, for opening on-disk repos 2315 // during page construction. both null on wasm, which has no filesystem and 2316 // rebuilds pages from the serialized snapshot rather than from disk. 2317 io: ?std.Io = null, 2318 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2319 users_dir: ?[]const u8 = null, 2320 // the single on-disk repo this session views, when running in local mode 2321 // (haxy invoked with no arguments inside a repo). null on the server paths, 2322 // which resolve repos from the admin db instead. 2323 local: ?RepoSource = null, 2324 // focus id -> the live TextInput, refreshed each frame by the views that own 2325 // inputs. web/wasm form handling looks widgets up here by focus id. 2326 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2327 back: enum { unavailable, available, requested } = .unavailable, 2328 refresh_requested: bool = false, // set by input (ctrl+r) 2329 // a requested forward navigation. set this (via navigate) to move to a new 2330 // page; Nav.sync builds it and then copies it into current_page, clearing 2331 // this back to null. setting current_page directly only updates the url and 2332 // does not navigate. 2333 next_page: ?RoutablePage = null, 2334 is_terminal: bool = false, // true on remote SSH and local TUI 2335 color: bool = true, // false when NO_COLOR is set, which also hides the art 2336 // the terminal's reported default background, which the art blends toward 2337 terminal_background: ?Grid.Color.Rgb = null, 2338 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 2339 // url. null on the web itself (no footer there). 2340 web_port: ?u16 = null, 2341 // the authorized_keys line of the key an ssh session connected with 2342 ssh_key: ?[]const u8 = null, 2343 // a host operation requested by a widget 2344 host_request: ?HostRequest = null, 2345 quit_requested: bool = false, 2346 2347 pub const HostRequest = union(enum) { 2348 show_copyable_text: []const u8, 2349 sync_events, 2350 undo: RoutablePage.RepoUndoRoute, 2351 }; 2352 2353 pub const FormFeedback = union(enum) { 2354 pub const LoginFailure = enum { unknown_user, wrong_password }; 2355 pub const ThreadFailure = enum { required_title }; 2356 pub const PatchFailure = enum { 2357 required_title, 2358 invalid_target_branch, 2359 invalid_source_branch, 2360 same_branch, 2361 unrelated_branches, 2362 2363 pub fn fromError(err: anyerror) ?PatchFailure { 2364 return switch (err) { 2365 error.InvalidTargetBranch => .invalid_target_branch, 2366 error.InvalidSourceBranch => .invalid_source_branch, 2367 error.SameBranch => .same_branch, 2368 error.UnrelatedBranches => .unrelated_branches, 2369 else => null, 2370 }; 2371 } 2372 }; 2373 2374 pub const RepoFailure = enum { 2375 required_name, 2376 invalid_name, 2377 name_taken, 2378 2379 pub fn fromError(err: anyerror) ?RepoFailure { 2380 return switch (err) { 2381 error.NameEmpty => .required_name, 2382 error.NameTooLong, error.InvalidName => .invalid_name, 2383 error.NameTaken => .name_taken, 2384 else => null, 2385 }; 2386 } 2387 }; 2388 2389 pub const MembersFailure = enum { not_found, already_added }; 2390 2391 pub const BranchesFailure = enum { 2392 not_found, 2393 already_added, 2394 too_many, 2395 too_long, 2396 2397 pub fn fromError(err: anyerror) ?BranchesFailure { 2398 return switch (err) { 2399 error.BranchProtected => .already_added, 2400 error.TooManyProtectedBranches => .too_many, 2401 else => null, 2402 }; 2403 } 2404 }; 2405 2406 pub const AssignmentFailure = enum { not_found, not_an_email, already_assigned }; 2407 2408 pub const KeyFailure = enum { 2409 invalid, 2410 unsupported, 2411 already_added, 2412 too_many, 2413 2414 pub fn fromError(err: anyerror) ?KeyFailure { 2415 return switch (err) { 2416 error.InvalidKey => .invalid, 2417 error.UnsupportedKey => .unsupported, 2418 error.KeyAdded => .already_added, 2419 error.TooManyKeys => .too_many, 2420 else => null, 2421 }; 2422 } 2423 }; 2424 2425 pub const UserFailure = enum { 2426 required_name, 2427 invalid_name, 2428 name_taken, 2429 required_email, 2430 email_taken, 2431 required_password, 2432 password_mismatch, 2433 wrong_password, 2434 2435 pub fn fromError(err: anyerror) ?UserFailure { 2436 return switch (err) { 2437 error.NameEmpty => .required_name, 2438 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2439 error.NameTaken => .name_taken, 2440 error.EmailEmpty => .required_email, 2441 error.EmailTaken => .email_taken, 2442 error.PasswordEmpty => .required_password, 2443 error.PasswordMismatch => .password_mismatch, 2444 error.WrongPassword => .wrong_password, 2445 else => null, 2446 }; 2447 } 2448 }; 2449 2450 login: struct { 2451 failure: LoginFailure, 2452 username: []const u8, 2453 }, 2454 user: struct { 2455 failure: UserFailure, 2456 // passwords are never retained 2457 fields: struct { 2458 name: []const u8, 2459 email: []const u8, 2460 }, 2461 }, 2462 user_settings: struct { 2463 failure: UserFailure, 2464 // passwords are never retained 2465 fields: struct { email: []const u8 }, 2466 }, 2467 user_keys: struct { 2468 failure: KeyFailure, 2469 key: []const u8, 2470 }, 2471 repo: struct { 2472 failure: RepoFailure, 2473 fields: struct { 2474 name: []const u8, 2475 description: []const u8, 2476 hash: hash.HashKind, 2477 access: evt.Repo.Access, 2478 }, 2479 }, 2480 repo_settings: struct { 2481 failure: RepoFailure, 2482 fields: struct { 2483 name: []const u8, 2484 description: []const u8, 2485 access: evt.Repo.Access, 2486 discuss_role: ?evt.Repo.Role, 2487 issue_role: ?evt.Repo.Role, 2488 patch_role: ?evt.Repo.Role, 2489 }, 2490 }, 2491 repo_members: struct { 2492 failure: MembersFailure, 2493 name: []const u8, 2494 }, 2495 repo_branches: struct { 2496 failure: BranchesFailure, 2497 name: []const u8, 2498 }, 2499 assignment: struct { 2500 failure: AssignmentFailure, 2501 text: []const u8, 2502 }, 2503 issue: struct { 2504 failure: ThreadFailure, 2505 fields: ?struct { 2506 title: []const u8, 2507 labels: []const u8, 2508 description: []const u8, 2509 } = null, 2510 }, 2511 patch: struct { 2512 failure: PatchFailure, 2513 fields: ?struct { 2514 title: []const u8, 2515 labels: []const u8, 2516 description: []const u8, 2517 target_branch: []const u8, 2518 source_branch: []const u8 = "", 2519 source_kind: Repo.Patches.Source.Kind = .fork, 2520 } = null, 2521 }, 2522 discussion: struct { 2523 failure: ThreadFailure, 2524 fields: ?struct { 2525 title: []const u8, 2526 labels: []const u8, 2527 description: []const u8, 2528 } = null, 2529 }, 2530 }; 2531 2532 const Self = @This(); 2533 2534 // serializable data sent down to web client 2535 pub const Data = struct { 2536 // the server's reference time for relative timestamps on this page. 2537 now: i64 = 0, 2538 user_id: ?[]const u8 = null, 2539 // the logged-in user's name and email, for the views that show them 2540 user_name: ?[]const u8 = null, 2541 user_email: ?[]const u8 = null, 2542 // the logged-in user's unread notifications, refreshed on each page build 2543 unread_notifs: u64 = 0, 2544 // a failed form retained long enough to render it for correction 2545 form_feedback: ?FormFeedback = null, 2546 // a transient local event-sync error 2547 sync_failure: ?[]const u8 = null, 2548 // a failed terminal undo retained on the current tab 2549 undo_failure: ?[]const u8 = null, 2550 current_page: RoutablePage = .default, 2551 // the selected ANSI art. the server serializes one image for WASM so 2552 // the browser does not need the whole build-generated collection. 2553 ansi_art: []const u8 = "", 2554 // the bound git-service ports. absent in local mode, where remote urls 2555 // are not shown. 2556 git_http_port: ?u16 = null, 2557 git_ssh_port: ?u16 = null, 2558 git_ssh_prefix: []const u8 = "", 2559 // whether this session views a local repo or the server. unlike `local` 2560 // (the host-side filesystem source) this travels in the snapshot, so 2561 // the wasm side also parses elided link urls and hides the multi-user 2562 // chrome. 2563 host_kind: evt.HostKind = .server, 2564 }; 2565 2566 pub fn init( 2567 arena: *std.heap.ArenaAllocator, 2568 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2569 data: Data, 2570 ) !Self { 2571 var session = Self{ 2572 .data = data, 2573 .arena = arena, 2574 // until a host swaps in a page-scoped arena (Nav does this), page 2575 // allocations land in the session arena. on the web path that's the 2576 // intended behavior, since the whole arena is per-request. 2577 .page_arena = arena, 2578 .admin_repo = repo, 2579 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2580 }; 2581 try session.loadUser(); 2582 return session; 2583 } 2584 2585 // web views share the page's reference time; terminals use the live clock. 2586 pub fn nowSeconds(self: *const Self) !i64 { 2587 if (builtin.target.cpu.arch == .wasm32 or !self.is_terminal) return self.data.now; 2588 const io = self.io orelse return error.NoClock; 2589 return std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse error.TimestampOutOfRange; 2590 } 2591 2592 // load the logged-in user's name and persisted preferences from the db 2593 pub fn loadUser(self: *Self) !void { 2594 const user_id = self.userId() orelse return; 2595 const moment = self.haxy_moment orelse return; 2596 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2597 self.data.user_name = user.event.name; 2598 self.data.user_email = user.event.email; 2599 } 2600 2601 // forget the logged-in user, on a logout or once their account is removed 2602 pub fn logOut(self: *Self) void { 2603 self.data.user_id = null; 2604 self.data.user_name = null; 2605 self.data.user_email = null; 2606 } 2607 2608 // log in as the account the session's ssh key last logged into with a 2609 // password, while that account still holds the key 2610 pub fn logInWithSshKey(self: *Self) !void { 2611 const key = self.ssh_key orelse return; 2612 const admin_repo = self.admin_repo orelse return; 2613 const moment = self.haxy_moment orelse return; 2614 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2615 const user_id = (try evt.readLoginKeyUser(try admin_repo.core.latestMoment(), &fingerprint)) orelse return; 2616 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, &user_id, &fingerprint)) return; 2617 self.data.user_id = try self.arena.allocator().dupe(u8, &user_id); 2618 try self.loadUser(); 2619 } 2620 2621 // add the session's ssh key to the user who just logged in with a 2622 // password, which proves they hold it, and let it log them in from now on 2623 pub fn rememberSshKey(self: *Self) !void { 2624 if (builtin.target.cpu.arch == .wasm32) return; 2625 const key = self.ssh_key orelse return; 2626 const io = self.io orelse return; 2627 const users_dir = self.users_dir orelse return; 2628 const admin_repo = self.admin_repo orelse return; 2629 const user_id = self.userId() orelse return; 2630 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2631 const allocator = self.arena.child_allocator; 2632 2633 const day = (std.time.epoch.EpochSeconds{ .secs = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()) }).getEpochDay().calculateYearDay(); 2634 const month = day.calculateMonthDay(); 2635 const line = try std.fmt.allocPrint(allocator, "{s} added {d:0>4}-{d:0>2}-{d:0>2} via login", .{ key, day.year, month.month.numeric(), month.day_index + 1 }); 2636 defer allocator.free(line); 2637 evt.addUserKey(io, allocator, users_dir, admin_repo, &user_id, line) catch |err| switch (err) { 2638 // it's already there, or there's no room for it 2639 error.KeyAdded, error.TooManyKeys => {}, 2640 else => return err, 2641 }; 2642 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .trust); 2643 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2644 } 2645 2646 // stop the session's ssh key logging the user in, on a logout 2647 pub fn forgetSshKey(self: *Self) !void { 2648 if (builtin.target.cpu.arch == .wasm32) return; 2649 const key = self.ssh_key orelse return; 2650 const io = self.io orelse return; 2651 const admin_repo = self.admin_repo orelse return; 2652 const user_id = self.userId() orelse return; 2653 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2654 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .forget); 2655 } 2656 2657 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2658 const bytes = self.data.user_id orelse return null; 2659 if (bytes.len != evt.event_id_size) return null; 2660 var id: [evt.event_id_size]u8 = undefined; 2661 @memcpy(&id, bytes); 2662 return id; 2663 } 2664 2665 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2666 const feedback = self.data.form_feedback orelse return null; 2667 if (std.meta.activeTag(feedback) != tag) return null; 2668 return @field(feedback, @tagName(tag)); 2669 } 2670 2671 pub fn clearFormFeedback(self: *Self) void { 2672 self.data.form_feedback = null; 2673 } 2674 2675 // the actor for a write to the repo `identity` names, or null when the 2676 // session may not write there with at least `min_role` or in the 2677 // `thread_kind` tab. local mode always writes. 2678 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2679 if (self.data.host_kind == .local) { 2680 const author = blk: { 2681 const src = self.local orelse break :blk local_author_fallback; 2682 const io = self.io orelse break :blk local_author_fallback; 2683 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2684 }; 2685 return .{ .author = author, .role = .owner }; 2686 } 2687 const user_id = self.userId() orelse return null; 2688 // the session's moment predates this input, so read the roles afresh 2689 const admin_repo = self.admin_repo orelse return null; 2690 const io = self.io orelse return null; 2691 const users_dir = self.users_dir orelse return null; 2692 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2693 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2694 .actor => |actor| actor, 2695 .login_required, .repo_not_found, .forbidden => null, 2696 }; 2697 } 2698 2699 // where this session's event writes go. a server session always has a users dir and an admin repo 2700 pub fn eventHost(self: *const Self) evt.Host { 2701 return switch (self.data.host_kind) { 2702 .local => .local, 2703 .server => .{ .server = .{ 2704 .users_dir = self.users_dir orelse unreachable, 2705 .admin_repo_path = (self.admin_repo orelse unreachable).core.work_path, 2706 } }, 2707 }; 2708 } 2709 2710 // reload the moment from the admin repo and log out a removed user 2711 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2712 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2713 self.haxy_moment = moment; 2714 2715 const user_id = self.userId() orelse return; 2716 var arena = std.heap.ArenaAllocator.init(allocator); 2717 defer arena.deinit(); 2718 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2719 } 2720 2721 // request a forward navigation to `route`; the host consumes next_page 2722 // (Nav.sync on the terminal, the wasm tick on the web). 2723 pub fn navigate(self: *Session, route: RoutablePage) !void { 2724 self.clearFormFeedback(); 2725 self.next_page = route; 2726 } 2727 }; 2728 2729 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2730 var nav = try Nav.init(allocator, session); 2731 defer nav.deinit(allocator); 2732 2733 var terminal = try term.Terminal.init(io, allocator); 2734 terminal.render_state.no_color = !session.color; 2735 var terminal_live = true; 2736 defer if (terminal_live) terminal.deinit(io); 2737 2738 // set term as active so it will be properly cooked 2739 // when a panic/segfault happens 2740 term.setActive(&terminal); 2741 defer term.setActive(null); 2742 2743 try terminal.queryBackground(); 2744 2745 while (!terminal.shouldQuit()) { 2746 const grid_changed = try terminal.render(&nav.root); 2747 2748 // process any inputs. 2749 // 2750 // if the grid didn't change, then first do a blocking 2751 // read, so the thread will sleep until further input. 2752 // after that, all remaining reads are non-blocking so 2753 // we can process the rest of the queued inputs. 2754 // 2755 // if the grid *did* change, then only do non-blocking 2756 // reads. we do not want to sleep the thread because 2757 // there may be an animation that requires more looping. 2758 var blocking = !grid_changed; 2759 while (try terminal.readKey(io, blocking)) |key| { 2760 blocking = false; 2761 try inputKey(allocator, &nav.root, key, session); 2762 } 2763 2764 if (session.host_request) |request| { 2765 session.host_request = null; 2766 switch (request) { 2767 .show_copyable_text => |copyable_text| { 2768 term.setActive(null); 2769 terminal.deinit(io); 2770 terminal_live = false; 2771 showCopyableText(io, copyable_text) catch |show_err| { 2772 terminal = try term.Terminal.init(io, allocator); 2773 terminal_live = true; 2774 term.setActive(&terminal); 2775 return show_err; 2776 }; 2777 terminal = try term.Terminal.init(io, allocator); 2778 terminal.render_state.no_color = !session.color; 2779 terminal_live = true; 2780 term.setActive(&terminal); 2781 }, 2782 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2783 .sync_events => { 2784 try nav.root.build(allocator, .{ 2785 .min_size = .{ .width = null, .height = null }, 2786 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2787 }, nav.root.getFocus()); 2788 _ = try terminal.render(&nav.root); 2789 try Repo.Events.performSync(allocator, session); 2790 }, 2791 } 2792 } 2793 2794 // reload so the next navigation builds its page from the current moment 2795 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2796 2797 // reconcile navigation: forward to a new page, or back on escape. 2798 // the terminal background can change at any time, so recheck it on each page 2799 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2800 2801 // the quit button (on the quit tab) asks the host to tear down. 2802 if (session.quit_requested) terminal.requestQuit(); 2803 2804 try nav.root.build(allocator, .{ 2805 .min_size = .{ .width = null, .height = null }, 2806 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2807 }, nav.root.getFocus()); 2808 } 2809 } 2810 2811 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2812 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2813 null 2814 else 2815 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2816 defer if (tty) |file| file.close(io); 2817 2818 const input = if (tty) |file| file else std.Io.File.stdin(); 2819 const output = if (tty) |file| file else std.Io.File.stdout(); 2820 2821 var write_buf: [1024]u8 = undefined; 2822 var writer = output.writer(io, &write_buf); 2823 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}); 2824 try writer.interface.flush(); 2825 2826 var read_buf: [1]u8 = undefined; 2827 var reader = input.reader(io, &read_buf); 2828 while (true) { 2829 const byte = try reader.interface.takeByte(); 2830 if (byte == '\r' or byte == '\n') return; 2831 } 2832 } 2833 2834 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2835 const root_focus = root.getFocus(); 2836 const focused_before = root_focus.grandchild_id; 2837 var activate_in_page_link = false; 2838 switch (key) { 2839 // request a navigation pop; the host's Nav.sync goes back a page, or 2840 // quits when there's no history left. 2841 .escape => { 2842 session.back = .requested; 2843 return; 2844 }, 2845 .ctrl => |letter| switch (letter) { 2846 'r' => { 2847 session.refresh_requested = true; 2848 return; 2849 }, 2850 else => try root.input(allocator, key, root_focus), 2851 }, 2852 .enter => { 2853 if (root_focus.grandchild_id) |gid| { 2854 // follow a cross-page link 2855 if (crossPageLink(root_focus, gid, session.data)) |route| { 2856 return session.navigate(route); 2857 } 2858 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2859 } 2860 activate_in_page_link = true; 2861 try root.input(allocator, key, root_focus); 2862 }, 2863 .mouse => |mouse| { 2864 if (mouse.button == .left) { 2865 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2866 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2867 const focus_id = hit.id; 2868 if (hit.kind == .background) { 2869 root_focus.setFocus(focus_id); 2870 return; 2871 } 2872 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2873 if (session.back == .available) session.back = .requested; 2874 return; 2875 } 2876 // follow a cross-page link 2877 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2878 return session.navigate(route); 2879 } 2880 if (currentPageLink(root_focus, focus_id, session.data)) return; 2881 if (rawLink(root_focus, focus_id)) |url| { 2882 if (!mouse.ctrl) try requestRawLink(session, url); 2883 return; 2884 } 2885 root_focus.setFocus(focus_id); 2886 activate_in_page_link = true; 2887 } 2888 // forward the press into the widget tree so buttons (and any 2889 // future click-aware widgets) can react. widgets that don't 2890 // care about presses ignore it. 2891 try root.input(allocator, key, root_focus); 2892 } else { 2893 try root.input(allocator, key, root_focus); 2894 } 2895 }, 2896 .event => |event| switch (event) { 2897 .background => |rgb| session.terminal_background = rgb, 2898 .resize => try root.input(allocator, key, root_focus), 2899 }, 2900 // a scroll tick goes to the pane under the pointer, focusing it first. 2901 // from outside any pane (the tabs, a sub-header) or from a text input 2902 // it moves like the arrows instead, so scrolling up from a search box 2903 // reaches the header and stops there. 2904 .scroll_up, .scroll_down => |position| { 2905 if (focusedPane(root_focus)) |pane| if (scrollUnder(root_focus, position)) |under| { 2906 if (under != pane) root_focus.setFocus(under); 2907 }; 2908 try root.input(allocator, key, root_focus); 2909 }, 2910 else => try root.input(allocator, key, root_focus), 2911 } 2912 2913 const focused_after = root_focus.grandchild_id; 2914 if (!activate_in_page_link and focused_before == focused_after) return; 2915 const focus_id = focused_after orelse return; 2916 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2917 } 2918 2919 // the innermost vertically scrolling widget laid out under `position` 2920 fn scrollUnder(root_focus: *const Focus, position: xitui.input.Position) ?usize { 2921 var found: ?usize = null; 2922 var found_area: usize = std.math.maxInt(usize); 2923 var iter = root_focus.children.iterator(); 2924 while (iter.next()) |entry| { 2925 const info = entry.value_ptr.focus.scroll orelse continue; 2926 if (info.direction == .horiz) continue; 2927 const r = entry.value_ptr.rect; 2928 if (position.x < r.x or position.y < r.y or position.x >= r.x + r.size.width or position.y >= r.y + r.size.height) continue; 2929 // a nested scroll lies within its parent, so the smallest is innermost 2930 const area = r.size.width * r.size.height; 2931 if (area < found_area) { 2932 found = entry.key_ptr.*; 2933 found_area = area; 2934 } 2935 } 2936 return found; 2937 } 2938 2939 // the innermost vertically scrolling widget the focus lies in, unless the 2940 // focused widget is a text input 2941 fn focusedPane(root_focus: *const Focus) ?usize { 2942 var current = root_focus.grandchild_id orelse return null; 2943 switch ((root_focus.children.get(current) orelse return null).focus.kind) { 2944 .text_input, .text_input_password, .text_area => return null, 2945 else => {}, 2946 } 2947 while (root_focus.children.get(current)) |child| { 2948 if (child.focus.scroll) |info| if (info.direction != .horiz) return current; 2949 current = child.parent_id; 2950 } 2951 return null; 2952 } 2953 2954 // a link to bytes the server serves directly rather than to a page route, so 2955 // it never resolves to a RoutablePage 2956 pub const raw_link_prefix = "ax:"; 2957 2958 // a route already loaded into the current page; focusing it changes the url 2959 // without rebuilding the page 2960 pub const in_page_link_prefix = "ai:"; 2961 2962 // an in-page tab's base route, or the exact current route when it is selected 2963 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2964 const target = if (selected) session.data.current_page else route; 2965 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2966 } 2967 2968 // a button the web renderer covers with a file picker that posts the chosen 2969 // file to the url after the prefix 2970 pub const file_input_prefix = "file:"; 2971 2972 // a submit button that overrides its enclosing form's action 2973 pub const submit_action_prefix = "submit:"; 2974 2975 // one option of a radio field, as `radio:<name>=<value>` 2976 pub const radio_prefix = "radio:"; 2977 2978 // the url an `ax:` link points at, or null for anything else. a host that 2979 // suppresses the anchor's own navigation needs this to follow the link. 2980 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2981 const child = root_focus.children.get(focus_id) orelse return null; 2982 const custom = switch (child.focus.kind) { 2983 .custom => |c| c, 2984 else => return null, 2985 }; 2986 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2987 return custom[raw_link_prefix.len..]; 2988 } 2989 2990 fn requestRawLink(session: *Session, url: []const u8) !void { 2991 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2992 } 2993 2994 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2995 // an absolute url is already complete 2996 if (!std.mem.startsWith(u8, path, "/")) return path; 2997 return if (session.web_port) |port| 2998 try allocator.print("http://localhost:{d}{s}", .{ port, path }) 2999 else 3000 path; 3001 } 3002 3003 // if the focus target at focus_id is an `a:` link that should navigate (a 3004 // different parent page, or a different files directory within the repo page), 3005 // return its route; otherwise null. lets a host turn a click / enter on such a 3006 // link into a navigation rather than a focus change. 3007 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3008 const current = data.current_page; 3009 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 3010 // a link to a different parent page always navigates; within a page, a 3011 // files-directory / commits-page / list-window change navigates while tab 3012 // links stay in-page. 3013 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; 3014 return null; 3015 } 3016 3017 // the page the clicked cell links to, from a link inside a text box's content 3018 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 3019 const grid = root.getGrid() orelse return null; 3020 const cell = grid.cell(x, y) catch return null; 3021 const link = cell.link orelse return null; 3022 if (link.len == 0 or link[0] != '/') return null; 3023 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 3024 } 3025 3026 // whether the `a:` focus target links to the page already shown, which a click 3027 // leaves alone rather than focusing 3028 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 3029 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 3030 return route.eql(data.current_page); 3031 } 3032 3033 // the route carried by an `ai:` focus target, or null for any other target 3034 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3035 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 3036 } 3037 3038 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 3039 const child = root_focus.children.get(focus_id) orelse return null; 3040 const custom = switch (child.focus.kind) { 3041 .custom => |c| c, 3042 else => return null, 3043 }; 3044 if (!std.mem.startsWith(u8, custom, prefix)) return null; 3045 const path = custom[prefix.len..]; 3046 // local sessions build (and parse) links with the repo identity elided 3047 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 3048 } 3049 3050 // an assignee as the detail view shows it: the stored email, and the name of 3051 // the user holding it on this instance when there is one 3052 pub const Assignee = struct { 3053 email: []const u8, 3054 name: ?[]const u8 = null, 3055 3056 pub fn display(self: Assignee) []const u8 { 3057 return self.name orelse self.email; 3058 } 3059 }; 3060 3061 // a display author, resolved against the admin db at read time 3062 pub const Author = union(enum) { 3063 unknown, 3064 email: []const u8, // an email no user matches 3065 user_name: []const u8, 3066 3067 // the commit author line's email, resolved like initFromEmail 3068 pub fn init( 3069 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3070 arena: *std.heap.ArenaAllocator, 3071 author_line: []const u8, 3072 ) !Author { 3073 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 3074 } 3075 3076 // from a record's stored author email: it resolves to the user currently 3077 // holding it, else stays the email. the result is allocated in `arena`, 3078 // so the email may borrow transient memory. 3079 pub fn initFromEmail( 3080 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3081 arena: *std.heap.ArenaAllocator, 3082 author_email: ?[]const u8, 3083 ) !Author { 3084 const email = author_email orelse return .unknown; 3085 if (haxy_moment) |moment| { 3086 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 3087 return .{ .user_name = user.name }; 3088 } 3089 } 3090 return .{ .email = try arena.allocator().dupe(u8, email) }; 3091 } 3092 }; 3093 3094 // the "a:" link to user `name`'s page. 3095 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 3096 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 3097 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 3098 return page_arena.allocator().print("a:{s}", .{url}); 3099 } 3100 3101 // a focusable " author " box showing `author`, linking to their user page 3102 // when it is a known user 3103 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 3104 const text = switch (author) { 3105 .unknown => "", 3106 .email, .user_name => |t| t, 3107 }; 3108 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 3109 errdefer tb.deinit(allocator); 3110 tb.getFocus().mode = .all; 3111 switch (author) { 3112 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 3113 else => {}, 3114 } 3115 return tb; 3116 } 3117 3118 // native-TUI navigation 3119 pub const Nav = struct { 3120 root: Widget, 3121 // backs the current page (its Page data and the page-scoped strings its 3122 // widgets build). owned here, swapped on each navigation. session.page_arena 3123 // tracks whichever of these is current so widgets allocate into it. 3124 arena: *std.heap.ArenaAllocator, 3125 // the login the current root was built for 3126 user_id: ?[evt.event_id_size]u8, 3127 history: std.ArrayList(Entry), 3128 3129 // each retained page keeps its own arena, freed when the page leaves the 3130 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 3131 // long-lived session from accumulating every page it ever visited. 3132 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 3133 3134 // cap on retained back-history so the chain can't grow memory without bound 3135 const max_history: usize = 16; 3136 3137 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 3138 session.back = .unavailable; 3139 const arena = try allocator.create(std.heap.ArenaAllocator); 3140 arena.* = std.heap.ArenaAllocator.init(allocator); 3141 errdefer { 3142 arena.deinit(); 3143 allocator.destroy(arena); 3144 } 3145 3146 return .{ 3147 .root = try initCurrentRoot(allocator, arena, session), 3148 .arena = arena, 3149 .user_id = session.userId(), 3150 .history = .empty, 3151 }; 3152 } 3153 3154 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 3155 self.root.deinit(allocator); 3156 freeArena(allocator, self.arena); 3157 for (self.history.items) |*entry| { 3158 entry.root.deinit(allocator); 3159 freeArena(allocator, entry.arena); 3160 } 3161 self.history.deinit(allocator); 3162 } 3163 3164 // rebuild the current page in place from a current moment 3165 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 3166 if (session.haxy_moment == null and session.local == null) return; 3167 const arena = try allocator.create(std.heap.ArenaAllocator); 3168 arena.* = std.heap.ArenaAllocator.init(allocator); 3169 errdefer freeArena(allocator, arena); 3170 3171 const new_root = try initCurrentRoot(allocator, arena, session); 3172 3173 self.root.deinit(allocator); 3174 freeArena(allocator, self.arena); 3175 self.root = new_root; 3176 self.arena = arena; 3177 self.user_id = session.userId(); 3178 } 3179 3180 // build the current page's root in `arena`, or the not-found page's when 3181 // the route names nothing 3182 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 3183 session.page_arena = arena; 3184 const page = try arena.allocator().create(Page); 3185 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 3186 error.NotFound => blk: { 3187 session.data.current_page = .not_found; 3188 break :blk .not_found; 3189 }, 3190 else => |e| return e, 3191 }; 3192 return initRoot(allocator, page, session); 3193 } 3194 3195 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 3196 arena.deinit(); 3197 allocator.destroy(arena); 3198 } 3199 3200 // reconcile the displayed root with the session's navigation state. a 3201 // forward nav (current_page moved to a different parent page) pushes the 3202 // current root and builds the new page in a fresh arena; a back request 3203 // frees the current page and restores the previous one. when escape is 3204 // pressed with no history left we switch to the quit tab instead of quitting. 3205 // returns whether the root was replaced. 3206 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 3207 // refresh: rebuild the current page in place from a current moment 3208 if (session.refresh_requested) { 3209 session.refresh_requested = false; 3210 try self.rebuild(allocator, session); 3211 return true; 3212 } 3213 3214 if (session.back == .requested) { 3215 if (self.history.pop()) |entry| { 3216 session.back = if (self.history.items.len == 0) .unavailable else .available; 3217 self.root.deinit(allocator); 3218 freeArena(allocator, self.arena); 3219 self.root = entry.root; 3220 self.arena = entry.arena; 3221 self.user_id = entry.user_id; 3222 session.page_arena = entry.arena; 3223 session.data.current_page = entry.route; 3224 // a page built under another login is rebuilt rather than restored 3225 if (!std.meta.eql(entry.user_id, session.userId())) { 3226 try self.rebuild(allocator, session); 3227 return true; 3228 } 3229 chooseAnsiArtForNavigation(session); 3230 return true; 3231 } 3232 session.back = .unavailable; 3233 // nothing to go back to; switch to the quit confirmation 3234 const root_focus = self.root.getFocus(); 3235 var iter = root_focus.children.iterator(); 3236 while (iter.next()) |entry| { 3237 switch (entry.value_ptr.focus.kind) { 3238 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 3239 root_focus.setFocus(entry.key_ptr.*); 3240 // a Stack only builds its selected child, so the quit 3241 // button isn't in the focus tree until a build runs with 3242 // the quit tab selected. build once, then send a 3243 // synthetic arrow_down to drop focus from the tab onto 3244 // the button so it's ready to confirm. 3245 try self.root.build(allocator, .{ 3246 .min_size = .{ .width = null, .height = 40 }, 3247 .max_size = .{ .width = 80, .height = null }, 3248 }, root_focus); 3249 try self.root.input(allocator, .arrow_down, root_focus); 3250 break; 3251 }, 3252 else => {}, 3253 } 3254 } 3255 return false; 3256 } 3257 3258 // forward navigation: navigate() set next_page to the page to move to (a 3259 // cross-page link or tab change crossing pages) 3260 if (session.next_page) |route| { 3261 session.next_page = null; 3262 if (session.haxy_moment == null and session.local == null) return false; 3263 const previous_route = session.data.current_page; 3264 // the page we navigated to becomes the current page 3265 session.data.current_page = route; 3266 session.back = .available; 3267 3268 const arena = try allocator.create(std.heap.ArenaAllocator); 3269 arena.* = std.heap.ArenaAllocator.init(allocator); 3270 errdefer freeArena(allocator, arena); 3271 3272 const new_root = try initCurrentRoot(allocator, arena, session); 3273 3274 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 3275 // drop the oldest entry (freeing its widget tree and arena) once over cap 3276 if (self.history.items.len > max_history) { 3277 var oldest = self.history.orderedRemove(0); 3278 oldest.root.deinit(allocator); 3279 freeArena(allocator, oldest.arena); 3280 } 3281 self.root = new_root; 3282 self.arena = arena; 3283 self.user_id = session.userId(); 3284 return true; 3285 } 3286 return false; 3287 } 3288 }; 3289 3290 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3291 const page_widget: Widget = switch (page.*) { 3292 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3293 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3294 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3295 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3296 .not_found => .{ .not_found = try .init(allocator, session) }, 3297 }; 3298 3299 chooseAnsiArtForNavigation(session); 3300 3301 // on the TUI/SSH, the page sits above a one-row footer showing its web 3302 // url, when there's a web UI to point at 3303 var root = if (session.is_terminal) blk: { 3304 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3305 errdefer box.deinit(allocator); 3306 const bg_id = bg_blk: { 3307 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3308 errdefer background.deinit(allocator); 3309 const id = background.getFocus().id; 3310 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3311 break :bg_blk id; 3312 }; 3313 if (session.web_port != null) { 3314 var footer = try widget.Footer.init(allocator, session); 3315 errdefer footer.deinit(allocator); 3316 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3317 } 3318 box.getFocus().child_id = bg_id; 3319 break :blk Widget{ .box = box }; 3320 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3321 errdefer root.deinit(allocator); 3322 3323 // input-owning views build their TextInputs in init, so reset their 3324 // registrations here 3325 session.text_inputs.clearRetainingCapacity(); 3326 3327 try root.build(allocator, .{ 3328 .min_size = .{ .width = null, .height = 40 }, 3329 .max_size = .{ .width = 100, .height = null }, 3330 }, root.getFocus()); 3331 3332 return root; 3333 } 3334 3335 // native and server-side sessions choose from the embedded collection. WASM 3336 // keeps the art serialized by the server instead. 3337 fn chooseAnsiArtForNavigation(session: *Session) void { 3338 if (comptime ansi_art.art.len == 0) return; 3339 if (session.data.current_page == .not_found) { 3340 session.data.ansi_art = ansi_art.not_found; 3341 return; 3342 } 3343 const io = session.io orelse return; 3344 var random: usize = undefined; 3345 io.random(std.mem.asBytes(&random)); 3346 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3347 } 3348