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