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