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