╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1779 // a requested forward navigation. set this (via navigate) to move to a new 1780 // page; Nav.sync builds it and then copies it into current_page, clearing 1781 // this back to null. setting current_page directly only updates the url and 1782 // does not navigate. 1783 next_page: ?RoutablePage = null, 1784 is_terminal: bool = false, // true on remote SSH and local TUI 1785 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 1786 // url. null on the web itself (no footer there). 1787 web_port: ?u16 = null, 1788 // a host operation requested by a widget 1789 host_request: ?HostRequest = null, 1790 quit_requested: bool = false, 1791 1792 pub const HostRequest = union(enum) { 1793 show_copyable_text: []const u8, 1794 sync_events, 1795 }; 1796 1797 pub const FormFeedback = union(enum) { 1798 pub const LoginFailure = enum { unknown_user, wrong_password }; 1799 pub const ThreadFailure = enum { required_title }; 1800 pub const PatchFailure = enum { 1801 required_title, 1802 invalid_target_branch, 1803 invalid_source_branch, 1804 same_branch, 1805 unrelated_branches, 1806 1807 pub fn fromError(err: anyerror) ?PatchFailure { 1808 return switch (err) { 1809 error.InvalidTargetBranch => .invalid_target_branch, 1810 error.InvalidSourceBranch => .invalid_source_branch, 1811 error.SameBranch => .same_branch, 1812 error.UnrelatedBranches => .unrelated_branches, 1813 else => null, 1814 }; 1815 } 1816 }; 1817 1818 login: struct { 1819 failure: LoginFailure, 1820 username: []const u8, 1821 }, 1822 issue: struct { 1823 failure: ThreadFailure, 1824 fields: ?struct { 1825 title: []const u8, 1826 tags: []const u8, 1827 description: []const u8, 1828 } = null, 1829 }, 1830 patch: struct { 1831 failure: PatchFailure, 1832 fields: ?struct { 1833 title: []const u8, 1834 tags: []const u8, 1835 description: []const u8, 1836 target_branch: []const u8, 1837 source_branch: []const u8 = "", 1838 source_kind: Repo.Patches.Source.Kind = .fork, 1839 } = null, 1840 }, 1841 discussion: struct { 1842 failure: ThreadFailure, 1843 fields: ?struct { 1844 title: []const u8, 1845 tags: []const u8, 1846 description: []const u8, 1847 } = null, 1848 }, 1849 }; 1850 1851 const Self = @This(); 1852 1853 // serializable data sent down to web client 1854 pub const Data = struct { 1855 user_id: ?[]const u8 = null, 1856 // the logged-in user's name, for the views that show it 1857 user_name: ?[]const u8 = null, 1858 // a failed form retained long enough to render it for correction 1859 form_feedback: ?FormFeedback = null, 1860 // a transient local event-sync error 1861 sync_failure: ?[]const u8 = null, 1862 current_page: RoutablePage = .default, 1863 // whether to render the ANSI art backdrop 1864 enable_ansi: bool = true, 1865 // the selected ANSI art. the server serializes one image for WASM so 1866 // the browser does not need the whole build-generated collection. 1867 ansi_art: []const u8 = "", 1868 // the bound git-service ports. absent in local mode, where remote urls 1869 // are not shown. 1870 git_http_port: ?u16 = null, 1871 git_ssh_port: ?u16 = null, 1872 git_ssh_prefix: []const u8 = "", 1873 // whether this session views a local repo or the server. unlike `local` 1874 // (the host-side filesystem source) this travels in the snapshot, so 1875 // the wasm side also parses elided link urls and hides the multi-user 1876 // chrome. 1877 host_kind: evt.HostKind = .server, 1878 }; 1879 1880 // a user-initiated state change. widgets enqueue these on the session during 1881 // input instead of mutating state or touching the DB themselves; the host 1882 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1883 // side effects out of the widget tree and gives every render path one place to 1884 // turn a UI action into a state change + event. 1885 pub const Action = union(enum) { 1886 toggle_ansi, 1887 }; 1888 1889 pub fn init( 1890 arena: *std.heap.ArenaAllocator, 1891 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1892 data: Data, 1893 ) !Self { 1894 var session = Self{ 1895 .data = data, 1896 .arena = arena, 1897 // until a host swaps in a page-scoped arena (Nav does this), page 1898 // allocations land in the session arena. on the web path that's the 1899 // intended behavior, since the whole arena is per-request. 1900 .page_arena = arena, 1901 .admin_repo = repo, 1902 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1903 }; 1904 try session.loadUser(); 1905 return session; 1906 } 1907 1908 // load the logged-in user's name and persisted preferences from the db 1909 pub fn loadUser(self: *Self) !void { 1910 const user_id = self.data.user_id orelse return; 1911 const moment = self.haxy_moment orelse return; 1912 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1913 self.data.user_name = user.event.name; 1914 self.data.enable_ansi = user.event.enable_ansi; 1915 } 1916 } 1917 1918 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 1919 const bytes = self.data.user_id orelse return null; 1920 if (bytes.len != evt.event_id_size) return null; 1921 var id: [evt.event_id_size]u8 = undefined; 1922 @memcpy(&id, bytes); 1923 return id; 1924 } 1925 1926 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 1927 const feedback = self.data.form_feedback orelse return null; 1928 if (std.meta.activeTag(feedback) != tag) return null; 1929 return @field(feedback, @tagName(tag)); 1930 } 1931 1932 pub fn clearFormFeedback(self: *Self) void { 1933 self.data.form_feedback = null; 1934 } 1935 1936 // the commit author for an event this session creates, or null when it may 1937 // not create one 1938 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1939 if (self.data.host_kind == .local) { 1940 const src = self.local orelse return local_author_fallback; 1941 const io = self.io orelse return local_author_fallback; 1942 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1943 } 1944 const user_id = self.data.user_id orelse return null; 1945 const moment = self.haxy_moment orelse return null; 1946 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1947 return .{ .name = user.event.name, .email = user.event.email }; 1948 } 1949 1950 // queue an action for the host to drain this frame. 1951 pub fn push(self: *Self, action: Action) !void { 1952 try self.pending.append(self.arena.allocator(), action); 1953 } 1954 1955 // apply a single action's in-memory effect only (no persistence). 1956 fn apply(self: *Self, action: Action) void { 1957 switch (action) { 1958 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1959 } 1960 } 1961 1962 // drain the session's queued actions by applying them to the session. 1963 // used on the wasm path, which has no repo to persist to. 1964 pub fn applyPending(self: *Self) void { 1965 for (self.pending.items) |action| self.apply(action); 1966 self.pending.clearRetainingCapacity(); 1967 } 1968 1969 // drain the session's queued actions by applying them to the session and 1970 // writing them to the db 1971 pub fn applyAndWritePending( 1972 self: *Self, 1973 io: std.Io, 1974 allocator: std.mem.Allocator, 1975 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1976 ) !void { 1977 defer self.pending.clearRetainingCapacity(); 1978 for (self.pending.items) |action| { 1979 self.apply(action); 1980 switch (action) { 1981 .toggle_ansi => if (self.data.user_id) |user_id| { 1982 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1983 }, 1984 } 1985 } 1986 } 1987 1988 // reload the moment from the admin repo and re-read user preferences 1989 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1990 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1991 self.haxy_moment = moment; 1992 1993 const user_id = self.data.user_id orelse return; 1994 var arena = std.heap.ArenaAllocator.init(allocator); 1995 defer arena.deinit(); 1996 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1997 self.data.enable_ansi = user.event.enable_ansi; 1998 } 1999 } 2000 2001 // request a forward navigation to `route`; the host consumes next_page 2002 // (Nav.sync on the terminal, the wasm tick on the web). 2003 pub fn navigate(self: *Session, route: RoutablePage) !void { 2004 self.clearFormFeedback(); 2005 self.next_page = route; 2006 } 2007 }; 2008 2009 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2010 var nav = try Nav.init(allocator, session); 2011 defer nav.deinit(allocator); 2012 2013 var terminal = try term.Terminal.init(io, allocator); 2014 var terminal_live = true; 2015 defer if (terminal_live) terminal.deinit(io); 2016 2017 // set term as active so it will be properly cooked 2018 // when a panic/segfault happens 2019 term.setActive(&terminal); 2020 defer term.setActive(null); 2021 2022 while (!terminal.shouldQuit()) { 2023 const grid_changed = try terminal.render(&nav.root); 2024 2025 // process any inputs. 2026 // 2027 // if the grid didn't change, then first do a blocking 2028 // read, so the thread will sleep until further input. 2029 // after that, all remaining reads are non-blocking so 2030 // we can process the rest of the queued inputs. 2031 // 2032 // if the grid *did* change, then only do non-blocking 2033 // reads. we do not want to sleep the thread because 2034 // there may be an animation that requires more looping. 2035 var blocking = !grid_changed; 2036 while (try terminal.readKey(io, blocking)) |key| { 2037 blocking = false; 2038 try inputKey(allocator, &nav.root, key, session); 2039 } 2040 2041 if (session.host_request) |request| { 2042 session.host_request = null; 2043 switch (request) { 2044 .show_copyable_text => |copyable_text| { 2045 term.setActive(null); 2046 terminal.deinit(io); 2047 terminal_live = false; 2048 showCopyableText(io, copyable_text) catch |show_err| { 2049 terminal = try term.Terminal.init(io, allocator); 2050 terminal_live = true; 2051 term.setActive(&terminal); 2052 return show_err; 2053 }; 2054 terminal = try term.Terminal.init(io, allocator); 2055 terminal_live = true; 2056 term.setActive(&terminal); 2057 }, 2058 .sync_events => { 2059 try nav.root.build(allocator, .{ 2060 .min_size = .{ .width = null, .height = null }, 2061 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2062 }, nav.root.getFocus()); 2063 _ = try terminal.render(&nav.root); 2064 try Repo.Events.performSync(allocator, session); 2065 }, 2066 } 2067 } 2068 2069 // persist queued actions when there's a repo; local mode has none, 2070 // so just apply in-memory 2071 if (repo_maybe) |repo| { 2072 try session.applyAndWritePending(io, allocator, repo); 2073 // reload so the next navigation builds its page from the current moment 2074 try session.reloadMoment(allocator, repo); 2075 } else { 2076 session.applyPending(); 2077 } 2078 2079 // reconcile navigation: forward to a new page, or back on escape. 2080 try nav.sync(allocator, session); 2081 2082 // the quit button (on the quit tab) asks the host to tear down. 2083 if (session.quit_requested) terminal.requestQuit(); 2084 2085 try nav.root.build(allocator, .{ 2086 .min_size = .{ .width = null, .height = null }, 2087 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2088 }, nav.root.getFocus()); 2089 } 2090 } 2091 2092 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2093 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 2094 null 2095 else 2096 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2097 defer if (tty) |file| file.close(io); 2098 2099 const input = if (tty) |file| file else std.Io.File.stdin(); 2100 const output = if (tty) |file| file else std.Io.File.stdout(); 2101 2102 var write_buf: [1024]u8 = undefined; 2103 var writer = output.writer(io, &write_buf); 2104 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}); 2105 try writer.interface.flush(); 2106 2107 var read_buf: [1]u8 = undefined; 2108 var reader = input.reader(io, &read_buf); 2109 while (true) { 2110 const byte = try reader.interface.takeByte(); 2111 if (byte == '\r' or byte == '\n') return; 2112 } 2113 } 2114 2115 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2116 const root_focus = root.getFocus(); 2117 const focused_before = root_focus.grandchild_id; 2118 var activate_in_page_link = false; 2119 switch (key) { 2120 // request a navigation pop; the host's Nav.sync goes back a page, or 2121 // quits when there's no history left. 2122 .escape => { 2123 session.back = .requested; 2124 return; 2125 }, 2126 .ctrl => |letter| switch (letter) { 2127 'r' => { 2128 session.refresh_requested = true; 2129 return; 2130 }, 2131 else => try root.input(allocator, key, root_focus), 2132 }, 2133 .enter => { 2134 if (root_focus.grandchild_id) |gid| { 2135 // follow a cross-page link 2136 if (crossPageLink(root_focus, gid, session.data)) |route| { 2137 return session.navigate(route); 2138 } 2139 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2140 } 2141 activate_in_page_link = true; 2142 try root.input(allocator, key, root_focus); 2143 }, 2144 .mouse => |mouse| { 2145 if (mouse.action == .press and mouse.action.press == .left) { 2146 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2147 const focus_id = hit.id; 2148 if (hit.kind == .background) { 2149 root_focus.setFocus(focus_id); 2150 return; 2151 } 2152 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2153 if (session.back == .available) session.back = .requested; 2154 return; 2155 } 2156 // follow a cross-page link 2157 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2158 return session.navigate(route); 2159 } 2160 if (rawLink(root_focus, focus_id)) |url| { 2161 if (!mouse.ctrl) try requestRawLink(session, url); 2162 return; 2163 } 2164 root_focus.setFocus(focus_id); 2165 activate_in_page_link = true; 2166 } 2167 // forward the press into the widget tree so buttons (and any 2168 // future click-aware widgets) can react. widgets that don't 2169 // care about presses ignore it. 2170 try root.input(allocator, key, root_focus); 2171 } else { 2172 try root.input(allocator, key, root_focus); 2173 } 2174 }, 2175 else => try root.input(allocator, key, root_focus), 2176 } 2177 2178 const focused_after = root_focus.grandchild_id; 2179 if (!activate_in_page_link and focused_before == focused_after) return; 2180 const focus_id = focused_after orelse return; 2181 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2182 } 2183 2184 // a link to bytes the server serves directly rather than to a page route, so 2185 // it never resolves to a RoutablePage 2186 pub const raw_link_prefix = "ax:"; 2187 2188 // a route already loaded into the current page; focusing it changes the url 2189 // without rebuilding the page 2190 pub const in_page_link_prefix = "ai:"; 2191 2192 // an in-page tab's base route, or the exact current route when it is selected 2193 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2194 const target = if (selected) session.data.current_page else route; 2195 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2196 } 2197 2198 // a button the web renderer covers with a file picker that posts the chosen 2199 // file to the url after the prefix 2200 pub const file_input_prefix = "file:"; 2201 2202 // a submit button that overrides its enclosing form's action 2203 pub const submit_action_prefix = "submit:"; 2204 2205 // the url an `ax:` link points at, or null for anything else. a host that 2206 // suppresses the anchor's own navigation needs this to follow the link. 2207 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2208 const child = root_focus.children.get(focus_id) orelse return null; 2209 const custom = switch (child.focus.kind) { 2210 .custom => |c| c, 2211 else => return null, 2212 }; 2213 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2214 return custom[raw_link_prefix.len..]; 2215 } 2216 2217 fn requestRawLink(session: *Session, url: []const u8) !void { 2218 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2219 } 2220 2221 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2222 return if (session.web_port) |port| 2223 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 2224 else 2225 path; 2226 } 2227 2228 // if the focus target at focus_id is an `a:` link that should navigate (a 2229 // different parent page, or a different files directory within the repo page), 2230 // return its route; otherwise null. lets a host turn a click / enter on such a 2231 // link into a navigation rather than a focus change. 2232 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2233 const current = data.current_page; 2234 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2235 // a link to a different parent page always navigates; within a page, a 2236 // files-directory / commits-page / list-window change navigates while tab 2237 // links stay in-page. 2238 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; 2239 return null; 2240 } 2241 2242 // the route carried by an `ai:` focus target, or null for any other target 2243 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2244 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2245 } 2246 2247 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2248 const child = root_focus.children.get(focus_id) orelse return null; 2249 const custom = switch (child.focus.kind) { 2250 .custom => |c| c, 2251 else => return null, 2252 }; 2253 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2254 const path = custom[prefix.len..]; 2255 // local sessions build (and parse) links with the repo identity elided 2256 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2257 } 2258 2259 // a display author, resolved against the admin db at read time 2260 pub const Author = union(enum) { 2261 unknown, 2262 email: []const u8, // an email no user matches 2263 user_name: []const u8, 2264 2265 // the commit author line's email, resolved like initFromEmail 2266 pub fn init( 2267 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2268 arena: *std.heap.ArenaAllocator, 2269 author_line: []const u8, 2270 ) !Author { 2271 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2272 } 2273 2274 // from a record's stored author email: it resolves to the user currently 2275 // holding it, else stays the email. the result is allocated in `arena`, 2276 // so the email may borrow transient memory. 2277 pub fn initFromEmail( 2278 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2279 arena: *std.heap.ArenaAllocator, 2280 author_email: ?[]const u8, 2281 ) !Author { 2282 const email = author_email orelse return .unknown; 2283 if (haxy_moment) |moment| { 2284 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2285 return .{ .user_name = user.event.name }; 2286 } 2287 } 2288 return .{ .email = try arena.allocator().dupe(u8, email) }; 2289 } 2290 }; 2291 2292 // the "a:" link to user `name`'s page. 2293 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2294 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2295 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2296 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 2297 } 2298 2299 // a focusable " author " box showing `author`, linking to their user page 2300 // when it is a known user 2301 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2302 const text = switch (author) { 2303 .unknown => "", 2304 .email, .user_name => |t| t, 2305 }; 2306 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 2307 errdefer tb.deinit(allocator); 2308 tb.getFocus().mode = .all; 2309 switch (author) { 2310 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2311 else => {}, 2312 } 2313 return tb; 2314 } 2315 2316 // native-TUI navigation 2317 pub const Nav = struct { 2318 root: Widget, 2319 // backs the current page (its Page data and the page-scoped strings its 2320 // widgets build). owned here, swapped on each navigation. session.page_arena 2321 // tracks whichever of these is current so widgets allocate into it. 2322 arena: *std.heap.ArenaAllocator, 2323 history: std.ArrayList(Entry), 2324 2325 // each retained page keeps its own arena, freed when the page leaves the 2326 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2327 // long-lived session from accumulating every page it ever visited. 2328 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 2329 2330 // cap on retained back-history so the chain can't grow memory without bound 2331 const max_history: usize = 16; 2332 2333 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2334 session.back = .unavailable; 2335 const arena = try allocator.create(std.heap.ArenaAllocator); 2336 arena.* = std.heap.ArenaAllocator.init(allocator); 2337 errdefer { 2338 arena.deinit(); 2339 allocator.destroy(arena); 2340 } 2341 2342 session.page_arena = arena; 2343 const route = session.data.current_page; 2344 2345 const page = try arena.allocator().create(Page); 2346 page.* = try Page.init(arena, session, route); 2347 return .{ 2348 .root = try initRoot(allocator, page, session), 2349 .arena = arena, 2350 .history = .empty, 2351 }; 2352 } 2353 2354 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2355 self.root.deinit(allocator); 2356 freeArena(allocator, self.arena); 2357 for (self.history.items) |*entry| { 2358 entry.root.deinit(allocator); 2359 freeArena(allocator, entry.arena); 2360 } 2361 self.history.deinit(allocator); 2362 } 2363 2364 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2365 arena.deinit(); 2366 allocator.destroy(arena); 2367 } 2368 2369 // reconcile the displayed root with the session's navigation state. a 2370 // forward nav (current_page moved to a different parent page) pushes the 2371 // current root and builds the new page in a fresh arena; a back request 2372 // frees the current page and restores the previous one. when escape is 2373 // pressed with no history left we switch to the quit tab instead of quitting. 2374 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2375 // refresh: rebuild the current page in place from a current moment 2376 if (session.refresh_requested) { 2377 session.refresh_requested = false; 2378 if (session.haxy_moment != null or session.local != null) { 2379 const arena = try allocator.create(std.heap.ArenaAllocator); 2380 arena.* = std.heap.ArenaAllocator.init(allocator); 2381 errdefer freeArena(allocator, arena); 2382 2383 session.page_arena = arena; 2384 2385 const route = session.data.current_page; 2386 const page = try arena.allocator().create(Page); 2387 page.* = try Page.init(arena, session, route); 2388 const new_root = try initRoot(allocator, page, session); 2389 2390 self.root.deinit(allocator); 2391 freeArena(allocator, self.arena); 2392 self.root = new_root; 2393 self.arena = arena; 2394 } 2395 return; 2396 } 2397 2398 if (session.back == .requested) { 2399 if (self.history.pop()) |entry| { 2400 session.back = if (self.history.items.len == 0) .unavailable else .available; 2401 self.root.deinit(allocator); 2402 freeArena(allocator, self.arena); 2403 self.root = entry.root; 2404 self.arena = entry.arena; 2405 session.page_arena = entry.arena; 2406 session.data.current_page = entry.route; 2407 chooseAnsiArtForNavigation(session); 2408 return; 2409 } 2410 session.back = .unavailable; 2411 // nothing to go back to; switch to the quit confirmation 2412 const root_focus = self.root.getFocus(); 2413 var iter = root_focus.children.iterator(); 2414 while (iter.next()) |entry| { 2415 switch (entry.value_ptr.focus.kind) { 2416 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2417 root_focus.setFocus(entry.key_ptr.*); 2418 // a Stack only builds its selected child, so the quit 2419 // button isn't in the focus tree until a build runs with 2420 // the quit tab selected. build once, then send a 2421 // synthetic arrow_down to drop focus from the tab onto 2422 // the button so it's ready to confirm. 2423 try self.root.build(allocator, .{ 2424 .min_size = .{ .width = null, .height = 40 }, 2425 .max_size = .{ .width = 80, .height = null }, 2426 }, root_focus); 2427 try self.root.input(allocator, .arrow_down, root_focus); 2428 break; 2429 }, 2430 else => {}, 2431 } 2432 } 2433 return; 2434 } 2435 2436 // forward navigation: navigate() set next_page to the page to move to (a 2437 // cross-page link or tab change crossing pages) 2438 if (session.next_page) |route| { 2439 session.next_page = null; 2440 if (session.haxy_moment == null and session.local == null) return; 2441 const previous_route = session.data.current_page; 2442 // the page we navigated to becomes the current page 2443 session.data.current_page = route; 2444 session.back = .available; 2445 2446 const arena = try allocator.create(std.heap.ArenaAllocator); 2447 arena.* = std.heap.ArenaAllocator.init(allocator); 2448 errdefer freeArena(allocator, arena); 2449 2450 session.page_arena = arena; 2451 2452 const page = try arena.allocator().create(Page); 2453 page.* = try Page.init(arena, session, route); 2454 const new_root = try initRoot(allocator, page, session); 2455 2456 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena }); 2457 // drop the oldest entry (freeing its widget tree and arena) once over cap 2458 if (self.history.items.len > max_history) { 2459 var oldest = self.history.orderedRemove(0); 2460 oldest.root.deinit(allocator); 2461 freeArena(allocator, oldest.arena); 2462 } 2463 self.root = new_root; 2464 self.arena = arena; 2465 } 2466 } 2467 }; 2468 2469 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2470 const page_widget: Widget = switch (page.*) { 2471 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2472 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2473 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2474 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2475 }; 2476 2477 chooseAnsiArtForNavigation(session); 2478 2479 // on the TUI/SSH, the page sits above a one-row footer showing the url 2480 var root = if (session.is_terminal) blk: { 2481 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2482 errdefer box.deinit(allocator); 2483 const bg_id = bg_blk: { 2484 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2485 errdefer background.deinit(allocator); 2486 const id = background.getFocus().id; 2487 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2488 break :bg_blk id; 2489 }; 2490 { 2491 var footer = try widget.Footer.init(allocator, session); 2492 errdefer footer.deinit(allocator); 2493 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2494 } 2495 box.getFocus().child_id = bg_id; 2496 break :blk Widget{ .box = box }; 2497 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2498 errdefer root.deinit(allocator); 2499 2500 // input-owning views build their TextInputs in init, so reset their 2501 // registrations here 2502 session.text_inputs.clearRetainingCapacity(); 2503 2504 try root.build(allocator, .{ 2505 .min_size = .{ .width = null, .height = 40 }, 2506 .max_size = .{ .width = 100, .height = null }, 2507 }, root.getFocus()); 2508 2509 return root; 2510 } 2511 2512 // native and server-side sessions choose from the embedded collection. WASM 2513 // keeps the art serialized by the server instead. 2514 fn chooseAnsiArtForNavigation(session: *Session) void { 2515 if (comptime ansi_arts.len == 0) return; 2516 const io = session.io orelse return; 2517 var random: usize = undefined; 2518 io.random(std.mem.asBytes(&random)); 2519 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2520 } 2521