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