╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2131 git_ssh_port: ?u16 = null, 2132 git_ssh_prefix: []const u8 = "", 2133 // whether this session views a local repo or the server. unlike `local` 2134 // (the host-side filesystem source) this travels in the snapshot, so 2135 // the wasm side also parses elided link urls and hides the multi-user 2136 // chrome. 2137 host_kind: evt.HostKind = .server, 2138 }; 2139 2140 // a user-initiated state change. widgets enqueue these on the session during 2141 // input instead of mutating state or touching the DB themselves; the host 2142 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 2143 // side effects out of the widget tree and gives every render path one place to 2144 // turn a UI action into a state change + event. 2145 pub const Action = union(enum) { 2146 toggle_ansi, 2147 }; 2148 2149 pub fn init( 2150 arena: *std.heap.ArenaAllocator, 2151 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2152 data: Data, 2153 ) !Self { 2154 var session = Self{ 2155 .data = data, 2156 .arena = arena, 2157 // until a host swaps in a page-scoped arena (Nav does this), page 2158 // allocations land in the session arena. on the web path that's the 2159 // intended behavior, since the whole arena is per-request. 2160 .page_arena = arena, 2161 .admin_repo = repo, 2162 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2163 }; 2164 try session.loadUser(); 2165 return session; 2166 } 2167 2168 // load the logged-in user's name and persisted preferences from the db 2169 pub fn loadUser(self: *Self) !void { 2170 const user_id = self.userId() orelse return; 2171 const moment = self.haxy_moment orelse return; 2172 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2173 self.data.user_name = user.event.name; 2174 self.data.enable_ansi = user.event.enable_ansi; 2175 } 2176 2177 // forget the logged-in user, on a logout or once their account is removed 2178 pub fn logOut(self: *Self) void { 2179 self.data.user_id = null; 2180 self.data.user_name = null; 2181 } 2182 2183 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2184 const bytes = self.data.user_id orelse return null; 2185 if (bytes.len != evt.event_id_size) return null; 2186 var id: [evt.event_id_size]u8 = undefined; 2187 @memcpy(&id, bytes); 2188 return id; 2189 } 2190 2191 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2192 const feedback = self.data.form_feedback orelse return null; 2193 if (std.meta.activeTag(feedback) != tag) return null; 2194 return @field(feedback, @tagName(tag)); 2195 } 2196 2197 pub fn clearFormFeedback(self: *Self) void { 2198 self.data.form_feedback = null; 2199 } 2200 2201 // the actor for a write to the repo `identity` names, or null when the 2202 // session may not write there with at least `min_role`. local mode always 2203 // writes. 2204 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role) !?Actor { 2205 if (self.data.host_kind == .local) { 2206 const author = blk: { 2207 const src = self.local orelse break :blk local_author_fallback; 2208 const io = self.io orelse break :blk local_author_fallback; 2209 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2210 }; 2211 return .{ .author = author, .role = .owner }; 2212 } 2213 const user_id = self.userId() orelse return null; 2214 // the session's moment predates this input, so read the roles afresh 2215 const admin_repo = self.admin_repo orelse return null; 2216 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2217 return switch (try authorizeUser(moment, self.page_arena, user_id, identity, min_role)) { 2218 .actor => |actor| actor, 2219 .login_required, .repo_not_found, .forbidden => null, 2220 }; 2221 } 2222 2223 // queue an action for the host to drain this frame. 2224 pub fn push(self: *Self, action: Action) !void { 2225 try self.pending.append(self.arena.allocator(), action); 2226 } 2227 2228 // apply a single action's in-memory effect only (no persistence). 2229 fn apply(self: *Self, action: Action) void { 2230 switch (action) { 2231 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 2232 } 2233 } 2234 2235 // drain the session's queued actions by applying them to the session. 2236 // used on the wasm path, which has no repo to persist to. 2237 pub fn applyPending(self: *Self) void { 2238 for (self.pending.items) |action| self.apply(action); 2239 self.pending.clearRetainingCapacity(); 2240 } 2241 2242 // drain the session's queued actions by applying them to the session and 2243 // writing them to the db 2244 pub fn applyAndWritePending( 2245 self: *Self, 2246 io: std.Io, 2247 allocator: std.mem.Allocator, 2248 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2249 ) !void { 2250 defer self.pending.clearRetainingCapacity(); 2251 for (self.pending.items) |action| { 2252 self.apply(action); 2253 switch (action) { 2254 .toggle_ansi => if (self.data.user_id) |user_id| { 2255 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 2256 }, 2257 } 2258 } 2259 } 2260 2261 // reload the moment from the admin repo and re-read user preferences 2262 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2263 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2264 self.haxy_moment = moment; 2265 2266 const user_id = self.userId() orelse return; 2267 var arena = std.heap.ArenaAllocator.init(allocator); 2268 defer arena.deinit(); 2269 const user = (try activeUser(moment, &arena, user_id)) orelse return self.logOut(); 2270 self.data.enable_ansi = user.event.enable_ansi; 2271 } 2272 2273 // request a forward navigation to `route`; the host consumes next_page 2274 // (Nav.sync on the terminal, the wasm tick on the web). 2275 pub fn navigate(self: *Session, route: RoutablePage) !void { 2276 self.clearFormFeedback(); 2277 self.next_page = route; 2278 } 2279 }; 2280 2281 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2282 var nav = try Nav.init(allocator, session); 2283 defer nav.deinit(allocator); 2284 2285 var terminal = try term.Terminal.init(io, allocator); 2286 var terminal_live = true; 2287 defer if (terminal_live) terminal.deinit(io); 2288 2289 // set term as active so it will be properly cooked 2290 // when a panic/segfault happens 2291 term.setActive(&terminal); 2292 defer term.setActive(null); 2293 2294 while (!terminal.shouldQuit()) { 2295 const grid_changed = try terminal.render(&nav.root); 2296 2297 // process any inputs. 2298 // 2299 // if the grid didn't change, then first do a blocking 2300 // read, so the thread will sleep until further input. 2301 // after that, all remaining reads are non-blocking so 2302 // we can process the rest of the queued inputs. 2303 // 2304 // if the grid *did* change, then only do non-blocking 2305 // reads. we do not want to sleep the thread because 2306 // there may be an animation that requires more looping. 2307 var blocking = !grid_changed; 2308 while (try terminal.readKey(io, blocking)) |key| { 2309 blocking = false; 2310 try inputKey(allocator, &nav.root, key, session); 2311 } 2312 2313 if (session.host_request) |request| { 2314 session.host_request = null; 2315 switch (request) { 2316 .show_copyable_text => |copyable_text| { 2317 term.setActive(null); 2318 terminal.deinit(io); 2319 terminal_live = false; 2320 showCopyableText(io, copyable_text) catch |show_err| { 2321 terminal = try term.Terminal.init(io, allocator); 2322 terminal_live = true; 2323 term.setActive(&terminal); 2324 return show_err; 2325 }; 2326 terminal = try term.Terminal.init(io, allocator); 2327 terminal_live = true; 2328 term.setActive(&terminal); 2329 }, 2330 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2331 .sync_events => { 2332 try nav.root.build(allocator, .{ 2333 .min_size = .{ .width = null, .height = null }, 2334 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2335 }, nav.root.getFocus()); 2336 _ = try terminal.render(&nav.root); 2337 try Repo.Events.performSync(allocator, session); 2338 }, 2339 } 2340 } 2341 2342 // persist queued actions when there's a repo; local mode has none, 2343 // so just apply in-memory 2344 if (repo_maybe) |repo| { 2345 try session.applyAndWritePending(io, allocator, repo); 2346 // reload so the next navigation builds its page from the current moment 2347 try session.reloadMoment(allocator, repo); 2348 } else { 2349 session.applyPending(); 2350 } 2351 2352 // reconcile navigation: forward to a new page, or back on escape. 2353 try nav.sync(allocator, session); 2354 2355 // the quit button (on the quit tab) asks the host to tear down. 2356 if (session.quit_requested) terminal.requestQuit(); 2357 2358 try nav.root.build(allocator, .{ 2359 .min_size = .{ .width = null, .height = null }, 2360 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2361 }, nav.root.getFocus()); 2362 } 2363 } 2364 2365 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2366 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 2367 null 2368 else 2369 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2370 defer if (tty) |file| file.close(io); 2371 2372 const input = if (tty) |file| file else std.Io.File.stdin(); 2373 const output = if (tty) |file| file else std.Io.File.stdout(); 2374 2375 var write_buf: [1024]u8 = undefined; 2376 var writer = output.writer(io, &write_buf); 2377 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}); 2378 try writer.interface.flush(); 2379 2380 var read_buf: [1]u8 = undefined; 2381 var reader = input.reader(io, &read_buf); 2382 while (true) { 2383 const byte = try reader.interface.takeByte(); 2384 if (byte == '\r' or byte == '\n') return; 2385 } 2386 } 2387 2388 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2389 const root_focus = root.getFocus(); 2390 const focused_before = root_focus.grandchild_id; 2391 var activate_in_page_link = false; 2392 switch (key) { 2393 // request a navigation pop; the host's Nav.sync goes back a page, or 2394 // quits when there's no history left. 2395 .escape => { 2396 session.back = .requested; 2397 return; 2398 }, 2399 .ctrl => |letter| switch (letter) { 2400 'r' => { 2401 session.refresh_requested = true; 2402 return; 2403 }, 2404 else => try root.input(allocator, key, root_focus), 2405 }, 2406 .enter => { 2407 if (root_focus.grandchild_id) |gid| { 2408 // follow a cross-page link 2409 if (crossPageLink(root_focus, gid, session.data)) |route| { 2410 return session.navigate(route); 2411 } 2412 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2413 } 2414 activate_in_page_link = true; 2415 try root.input(allocator, key, root_focus); 2416 }, 2417 .mouse => |mouse| { 2418 if (mouse.action == .press and mouse.action.press == .left) { 2419 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2420 const focus_id = hit.id; 2421 if (hit.kind == .background) { 2422 root_focus.setFocus(focus_id); 2423 return; 2424 } 2425 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2426 if (session.back == .available) session.back = .requested; 2427 return; 2428 } 2429 // follow a cross-page link 2430 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2431 return session.navigate(route); 2432 } 2433 if (rawLink(root_focus, focus_id)) |url| { 2434 if (!mouse.ctrl) try requestRawLink(session, url); 2435 return; 2436 } 2437 root_focus.setFocus(focus_id); 2438 activate_in_page_link = true; 2439 } 2440 // forward the press into the widget tree so buttons (and any 2441 // future click-aware widgets) can react. widgets that don't 2442 // care about presses ignore it. 2443 try root.input(allocator, key, root_focus); 2444 } else { 2445 try root.input(allocator, key, root_focus); 2446 } 2447 }, 2448 else => try root.input(allocator, key, root_focus), 2449 } 2450 2451 const focused_after = root_focus.grandchild_id; 2452 if (!activate_in_page_link and focused_before == focused_after) return; 2453 const focus_id = focused_after orelse return; 2454 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2455 } 2456 2457 // a link to bytes the server serves directly rather than to a page route, so 2458 // it never resolves to a RoutablePage 2459 pub const raw_link_prefix = "ax:"; 2460 2461 // a route already loaded into the current page; focusing it changes the url 2462 // without rebuilding the page 2463 pub const in_page_link_prefix = "ai:"; 2464 2465 // an in-page tab's base route, or the exact current route when it is selected 2466 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2467 const target = if (selected) session.data.current_page else route; 2468 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2469 } 2470 2471 // a button the web renderer covers with a file picker that posts the chosen 2472 // file to the url after the prefix 2473 pub const file_input_prefix = "file:"; 2474 2475 // a submit button that overrides its enclosing form's action 2476 pub const submit_action_prefix = "submit:"; 2477 2478 // the url an `ax:` link points at, or null for anything else. a host that 2479 // suppresses the anchor's own navigation needs this to follow the link. 2480 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2481 const child = root_focus.children.get(focus_id) orelse return null; 2482 const custom = switch (child.focus.kind) { 2483 .custom => |c| c, 2484 else => return null, 2485 }; 2486 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2487 return custom[raw_link_prefix.len..]; 2488 } 2489 2490 fn requestRawLink(session: *Session, url: []const u8) !void { 2491 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2492 } 2493 2494 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2495 return if (session.web_port) |port| 2496 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 2497 else 2498 path; 2499 } 2500 2501 // if the focus target at focus_id is an `a:` link that should navigate (a 2502 // different parent page, or a different files directory within the repo page), 2503 // return its route; otherwise null. lets a host turn a click / enter on such a 2504 // link into a navigation rather than a focus change. 2505 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2506 const current = data.current_page; 2507 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2508 // a link to a different parent page always navigates; within a page, a 2509 // files-directory / commits-page / list-window change navigates while tab 2510 // links stay in-page. 2511 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; 2512 return null; 2513 } 2514 2515 // the route carried by an `ai:` focus target, or null for any other target 2516 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2517 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2518 } 2519 2520 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2521 const child = root_focus.children.get(focus_id) orelse return null; 2522 const custom = switch (child.focus.kind) { 2523 .custom => |c| c, 2524 else => return null, 2525 }; 2526 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2527 const path = custom[prefix.len..]; 2528 // local sessions build (and parse) links with the repo identity elided 2529 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2530 } 2531 2532 // a display author, resolved against the admin db at read time 2533 pub const Author = union(enum) { 2534 unknown, 2535 email: []const u8, // an email no user matches 2536 user_name: []const u8, 2537 2538 // the commit author line's email, resolved like initFromEmail 2539 pub fn init( 2540 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2541 arena: *std.heap.ArenaAllocator, 2542 author_line: []const u8, 2543 ) !Author { 2544 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2545 } 2546 2547 // from a record's stored author email: it resolves to the user currently 2548 // holding it, else stays the email. the result is allocated in `arena`, 2549 // so the email may borrow transient memory. 2550 pub fn initFromEmail( 2551 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2552 arena: *std.heap.ArenaAllocator, 2553 author_email: ?[]const u8, 2554 ) !Author { 2555 const email = author_email orelse return .unknown; 2556 if (haxy_moment) |moment| { 2557 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2558 return .{ .user_name = user.event.name }; 2559 } 2560 } 2561 return .{ .email = try arena.allocator().dupe(u8, email) }; 2562 } 2563 }; 2564 2565 // the "a:" link to user `name`'s page. 2566 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2567 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2568 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2569 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 2570 } 2571 2572 // a focusable " author " box showing `author`, linking to their user page 2573 // when it is a known user 2574 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2575 const text = switch (author) { 2576 .unknown => "", 2577 .email, .user_name => |t| t, 2578 }; 2579 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 2580 errdefer tb.deinit(allocator); 2581 tb.getFocus().mode = .all; 2582 switch (author) { 2583 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2584 else => {}, 2585 } 2586 return tb; 2587 } 2588 2589 // native-TUI navigation 2590 pub const Nav = struct { 2591 root: Widget, 2592 // backs the current page (its Page data and the page-scoped strings its 2593 // widgets build). owned here, swapped on each navigation. session.page_arena 2594 // tracks whichever of these is current so widgets allocate into it. 2595 arena: *std.heap.ArenaAllocator, 2596 history: std.ArrayList(Entry), 2597 2598 // each retained page keeps its own arena, freed when the page leaves the 2599 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2600 // long-lived session from accumulating every page it ever visited. 2601 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 2602 2603 // cap on retained back-history so the chain can't grow memory without bound 2604 const max_history: usize = 16; 2605 2606 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2607 session.back = .unavailable; 2608 const arena = try allocator.create(std.heap.ArenaAllocator); 2609 arena.* = std.heap.ArenaAllocator.init(allocator); 2610 errdefer { 2611 arena.deinit(); 2612 allocator.destroy(arena); 2613 } 2614 2615 session.page_arena = arena; 2616 const route = session.data.current_page; 2617 2618 const page = try arena.allocator().create(Page); 2619 page.* = try Page.init(arena, session, route); 2620 return .{ 2621 .root = try initRoot(allocator, page, session), 2622 .arena = arena, 2623 .history = .empty, 2624 }; 2625 } 2626 2627 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2628 self.root.deinit(allocator); 2629 freeArena(allocator, self.arena); 2630 for (self.history.items) |*entry| { 2631 entry.root.deinit(allocator); 2632 freeArena(allocator, entry.arena); 2633 } 2634 self.history.deinit(allocator); 2635 } 2636 2637 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2638 arena.deinit(); 2639 allocator.destroy(arena); 2640 } 2641 2642 // reconcile the displayed root with the session's navigation state. a 2643 // forward nav (current_page moved to a different parent page) pushes the 2644 // current root and builds the new page in a fresh arena; a back request 2645 // frees the current page and restores the previous one. when escape is 2646 // pressed with no history left we switch to the quit tab instead of quitting. 2647 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2648 // refresh: rebuild the current page in place from a current moment 2649 if (session.refresh_requested) { 2650 session.refresh_requested = false; 2651 if (session.haxy_moment != null or session.local != null) { 2652 const arena = try allocator.create(std.heap.ArenaAllocator); 2653 arena.* = std.heap.ArenaAllocator.init(allocator); 2654 errdefer freeArena(allocator, arena); 2655 2656 session.page_arena = arena; 2657 2658 const route = session.data.current_page; 2659 const page = try arena.allocator().create(Page); 2660 page.* = try Page.init(arena, session, route); 2661 const new_root = try initRoot(allocator, page, session); 2662 2663 self.root.deinit(allocator); 2664 freeArena(allocator, self.arena); 2665 self.root = new_root; 2666 self.arena = arena; 2667 } 2668 return; 2669 } 2670 2671 if (session.back == .requested) { 2672 if (self.history.pop()) |entry| { 2673 session.back = if (self.history.items.len == 0) .unavailable else .available; 2674 self.root.deinit(allocator); 2675 freeArena(allocator, self.arena); 2676 self.root = entry.root; 2677 self.arena = entry.arena; 2678 session.page_arena = entry.arena; 2679 session.data.current_page = entry.route; 2680 chooseAnsiArtForNavigation(session); 2681 return; 2682 } 2683 session.back = .unavailable; 2684 // nothing to go back to; switch to the quit confirmation 2685 const root_focus = self.root.getFocus(); 2686 var iter = root_focus.children.iterator(); 2687 while (iter.next()) |entry| { 2688 switch (entry.value_ptr.focus.kind) { 2689 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2690 root_focus.setFocus(entry.key_ptr.*); 2691 // a Stack only builds its selected child, so the quit 2692 // button isn't in the focus tree until a build runs with 2693 // the quit tab selected. build once, then send a 2694 // synthetic arrow_down to drop focus from the tab onto 2695 // the button so it's ready to confirm. 2696 try self.root.build(allocator, .{ 2697 .min_size = .{ .width = null, .height = 40 }, 2698 .max_size = .{ .width = 80, .height = null }, 2699 }, root_focus); 2700 try self.root.input(allocator, .arrow_down, root_focus); 2701 break; 2702 }, 2703 else => {}, 2704 } 2705 } 2706 return; 2707 } 2708 2709 // forward navigation: navigate() set next_page to the page to move to (a 2710 // cross-page link or tab change crossing pages) 2711 if (session.next_page) |route| { 2712 session.next_page = null; 2713 if (session.haxy_moment == null and session.local == null) return; 2714 const previous_route = session.data.current_page; 2715 // the page we navigated to becomes the current page 2716 session.data.current_page = route; 2717 session.back = .available; 2718 2719 const arena = try allocator.create(std.heap.ArenaAllocator); 2720 arena.* = std.heap.ArenaAllocator.init(allocator); 2721 errdefer freeArena(allocator, arena); 2722 2723 session.page_arena = arena; 2724 2725 const page = try arena.allocator().create(Page); 2726 page.* = try Page.init(arena, session, route); 2727 const new_root = try initRoot(allocator, page, session); 2728 2729 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena }); 2730 // drop the oldest entry (freeing its widget tree and arena) once over cap 2731 if (self.history.items.len > max_history) { 2732 var oldest = self.history.orderedRemove(0); 2733 oldest.root.deinit(allocator); 2734 freeArena(allocator, oldest.arena); 2735 } 2736 self.root = new_root; 2737 self.arena = arena; 2738 } 2739 } 2740 }; 2741 2742 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2743 const page_widget: Widget = switch (page.*) { 2744 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2745 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2746 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2747 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2748 }; 2749 2750 chooseAnsiArtForNavigation(session); 2751 2752 // on the TUI/SSH, the page sits above a one-row footer showing the url 2753 var root = if (session.is_terminal) blk: { 2754 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2755 errdefer box.deinit(allocator); 2756 const bg_id = bg_blk: { 2757 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2758 errdefer background.deinit(allocator); 2759 const id = background.getFocus().id; 2760 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2761 break :bg_blk id; 2762 }; 2763 { 2764 var footer = try widget.Footer.init(allocator, session); 2765 errdefer footer.deinit(allocator); 2766 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2767 } 2768 box.getFocus().child_id = bg_id; 2769 break :blk Widget{ .box = box }; 2770 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2771 errdefer root.deinit(allocator); 2772 2773 // input-owning views build their TextInputs in init, so reset their 2774 // registrations here 2775 session.text_inputs.clearRetainingCapacity(); 2776 2777 try root.build(allocator, .{ 2778 .min_size = .{ .width = null, .height = 40 }, 2779 .max_size = .{ .width = 100, .height = null }, 2780 }, root.getFocus()); 2781 2782 return root; 2783 } 2784 2785 // native and server-side sessions choose from the embedded collection. WASM 2786 // keeps the art serialized by the server instead. 2787 fn chooseAnsiArtForNavigation(session: *Session) void { 2788 if (comptime ansi_arts.len == 0) return; 2789 const io = session.io orelse return; 2790 var random: usize = undefined; 2791 io.random(std.mem.asBytes(&random)); 2792 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2793 } 2794