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