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