╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2333 failure: UserFailure, 2334 // passwords are never retained 2335 fields: struct { email: []const u8 }, 2336 }, 2337 repo: struct { 2338 failure: RepoFailure, 2339 fields: struct { 2340 name: []const u8, 2341 description: []const u8, 2342 hash: hash.HashKind, 2343 access: evt.Repo.Access, 2344 }, 2345 }, 2346 repo_settings: struct { 2347 failure: RepoFailure, 2348 fields: struct { 2349 name: []const u8, 2350 description: []const u8, 2351 access: evt.Repo.Access, 2352 discuss_role: ?evt.Repo.Role, 2353 issue_role: ?evt.Repo.Role, 2354 patch_role: ?evt.Repo.Role, 2355 }, 2356 }, 2357 repo_roles: struct { 2358 failure: RolesFailure, 2359 name: []const u8, 2360 }, 2361 assignment: struct { 2362 failure: AssignmentFailure, 2363 text: []const u8, 2364 }, 2365 issue: struct { 2366 failure: ThreadFailure, 2367 fields: ?struct { 2368 title: []const u8, 2369 labels: []const u8, 2370 description: []const u8, 2371 } = null, 2372 }, 2373 patch: struct { 2374 failure: PatchFailure, 2375 fields: ?struct { 2376 title: []const u8, 2377 labels: []const u8, 2378 description: []const u8, 2379 target_branch: []const u8, 2380 source_branch: []const u8 = "", 2381 source_kind: Repo.Patches.Source.Kind = .fork, 2382 } = null, 2383 }, 2384 discussion: struct { 2385 failure: ThreadFailure, 2386 fields: ?struct { 2387 title: []const u8, 2388 labels: []const u8, 2389 description: []const u8, 2390 } = null, 2391 }, 2392 }; 2393 2394 const Self = @This(); 2395 2396 // serializable data sent down to web client 2397 pub const Data = struct { 2398 // the server's reference time for relative timestamps on this page. 2399 now: i64 = 0, 2400 user_id: ?[]const u8 = null, 2401 // the logged-in user's name and email, for the views that show them 2402 user_name: ?[]const u8 = null, 2403 user_email: ?[]const u8 = null, 2404 // a failed form retained long enough to render it for correction 2405 form_feedback: ?FormFeedback = null, 2406 // a transient local event-sync error 2407 sync_failure: ?[]const u8 = null, 2408 // a failed terminal undo retained on the current tab 2409 undo_failure: ?[]const u8 = null, 2410 current_page: RoutablePage = .default, 2411 // the selected ANSI art. the server serializes one image for WASM so 2412 // the browser does not need the whole build-generated collection. 2413 ansi_art: []const u8 = "", 2414 // the bound git-service ports. absent in local mode, where remote urls 2415 // are not shown. 2416 git_http_port: ?u16 = null, 2417 git_ssh_port: ?u16 = null, 2418 git_ssh_prefix: []const u8 = "", 2419 // whether this session views a local repo or the server. unlike `local` 2420 // (the host-side filesystem source) this travels in the snapshot, so 2421 // the wasm side also parses elided link urls and hides the multi-user 2422 // chrome. 2423 host_kind: evt.HostKind = .server, 2424 }; 2425 2426 pub fn init( 2427 arena: *std.heap.ArenaAllocator, 2428 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2429 data: Data, 2430 ) !Self { 2431 var session = Self{ 2432 .data = data, 2433 .arena = arena, 2434 // until a host swaps in a page-scoped arena (Nav does this), page 2435 // allocations land in the session arena. on the web path that's the 2436 // intended behavior, since the whole arena is per-request. 2437 .page_arena = arena, 2438 .admin_repo = repo, 2439 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2440 }; 2441 try session.loadUser(); 2442 return session; 2443 } 2444 2445 // web views share the page's reference time; terminals use the live clock. 2446 pub fn nowSeconds(self: *const Self) !i64 { 2447 if (builtin.target.cpu.arch == .wasm32 or !self.is_terminal) return self.data.now; 2448 const io = self.io orelse return error.NoClock; 2449 return std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse error.TimestampOutOfRange; 2450 } 2451 2452 // load the logged-in user's name and persisted preferences from the db 2453 pub fn loadUser(self: *Self) !void { 2454 const user_id = self.userId() orelse return; 2455 const moment = self.haxy_moment orelse return; 2456 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2457 self.data.user_name = user.event.name; 2458 self.data.user_email = user.event.email; 2459 } 2460 2461 // forget the logged-in user, on a logout or once their account is removed 2462 pub fn logOut(self: *Self) void { 2463 self.data.user_id = null; 2464 self.data.user_name = null; 2465 self.data.user_email = null; 2466 } 2467 2468 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2469 const bytes = self.data.user_id orelse return null; 2470 if (bytes.len != evt.event_id_size) return null; 2471 var id: [evt.event_id_size]u8 = undefined; 2472 @memcpy(&id, bytes); 2473 return id; 2474 } 2475 2476 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2477 const feedback = self.data.form_feedback orelse return null; 2478 if (std.meta.activeTag(feedback) != tag) return null; 2479 return @field(feedback, @tagName(tag)); 2480 } 2481 2482 pub fn clearFormFeedback(self: *Self) void { 2483 self.data.form_feedback = null; 2484 } 2485 2486 // the actor for a write to the repo `identity` names, or null when the 2487 // session may not write there with at least `min_role` or in the 2488 // `thread_kind` tab. local mode always writes. 2489 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2490 if (self.data.host_kind == .local) { 2491 const author = blk: { 2492 const src = self.local orelse break :blk local_author_fallback; 2493 const io = self.io orelse break :blk local_author_fallback; 2494 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2495 }; 2496 return .{ .author = author, .role = .owner }; 2497 } 2498 const user_id = self.userId() orelse return null; 2499 // the session's moment predates this input, so read the roles afresh 2500 const admin_repo = self.admin_repo orelse return null; 2501 const io = self.io orelse return null; 2502 const users_dir = self.users_dir orelse return null; 2503 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2504 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2505 .actor => |actor| actor, 2506 .login_required, .repo_not_found, .forbidden => null, 2507 }; 2508 } 2509 2510 // where this session's event writes go. a server session always has a users dir 2511 pub fn eventHost(self: *const Self) evt.Host { 2512 return switch (self.data.host_kind) { 2513 .local => .local, 2514 .server => .{ .server = .{ .users_dir = self.users_dir orelse unreachable } }, 2515 }; 2516 } 2517 2518 // reload the moment from the admin repo and log out a removed user 2519 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2520 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2521 self.haxy_moment = moment; 2522 2523 const user_id = self.userId() orelse return; 2524 var arena = std.heap.ArenaAllocator.init(allocator); 2525 defer arena.deinit(); 2526 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2527 } 2528 2529 // request a forward navigation to `route`; the host consumes next_page 2530 // (Nav.sync on the terminal, the wasm tick on the web). 2531 pub fn navigate(self: *Session, route: RoutablePage) !void { 2532 self.clearFormFeedback(); 2533 self.next_page = route; 2534 } 2535 }; 2536 2537 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2538 var nav = try Nav.init(allocator, session); 2539 defer nav.deinit(allocator); 2540 2541 var terminal = try term.Terminal.init(io, allocator); 2542 terminal.render_state.no_color = !session.color; 2543 var terminal_live = true; 2544 defer if (terminal_live) terminal.deinit(io); 2545 2546 // set term as active so it will be properly cooked 2547 // when a panic/segfault happens 2548 term.setActive(&terminal); 2549 defer term.setActive(null); 2550 2551 try terminal.queryBackground(); 2552 2553 while (!terminal.shouldQuit()) { 2554 const grid_changed = try terminal.render(&nav.root); 2555 2556 // process any inputs. 2557 // 2558 // if the grid didn't change, then first do a blocking 2559 // read, so the thread will sleep until further input. 2560 // after that, all remaining reads are non-blocking so 2561 // we can process the rest of the queued inputs. 2562 // 2563 // if the grid *did* change, then only do non-blocking 2564 // reads. we do not want to sleep the thread because 2565 // there may be an animation that requires more looping. 2566 var blocking = !grid_changed; 2567 while (try terminal.readKey(io, blocking)) |key| { 2568 blocking = false; 2569 try inputKey(allocator, &nav.root, key, session); 2570 } 2571 2572 if (session.host_request) |request| { 2573 session.host_request = null; 2574 switch (request) { 2575 .show_copyable_text => |copyable_text| { 2576 term.setActive(null); 2577 terminal.deinit(io); 2578 terminal_live = false; 2579 showCopyableText(io, copyable_text) catch |show_err| { 2580 terminal = try term.Terminal.init(io, allocator); 2581 terminal_live = true; 2582 term.setActive(&terminal); 2583 return show_err; 2584 }; 2585 terminal = try term.Terminal.init(io, allocator); 2586 terminal.render_state.no_color = !session.color; 2587 terminal_live = true; 2588 term.setActive(&terminal); 2589 }, 2590 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2591 .sync_events => { 2592 try nav.root.build(allocator, .{ 2593 .min_size = .{ .width = null, .height = null }, 2594 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2595 }, nav.root.getFocus()); 2596 _ = try terminal.render(&nav.root); 2597 try Repo.Events.performSync(allocator, session); 2598 }, 2599 } 2600 } 2601 2602 // reload so the next navigation builds its page from the current moment 2603 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2604 2605 // reconcile navigation: forward to a new page, or back on escape. 2606 // the terminal background can change at any time, so recheck it on each page 2607 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2608 2609 // the quit button (on the quit tab) asks the host to tear down. 2610 if (session.quit_requested) terminal.requestQuit(); 2611 2612 try nav.root.build(allocator, .{ 2613 .min_size = .{ .width = null, .height = null }, 2614 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2615 }, nav.root.getFocus()); 2616 } 2617 } 2618 2619 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2620 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2621 null 2622 else 2623 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2624 defer if (tty) |file| file.close(io); 2625 2626 const input = if (tty) |file| file else std.Io.File.stdin(); 2627 const output = if (tty) |file| file else std.Io.File.stdout(); 2628 2629 var write_buf: [1024]u8 = undefined; 2630 var writer = output.writer(io, &write_buf); 2631 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}); 2632 try writer.interface.flush(); 2633 2634 var read_buf: [1]u8 = undefined; 2635 var reader = input.reader(io, &read_buf); 2636 while (true) { 2637 const byte = try reader.interface.takeByte(); 2638 if (byte == '\r' or byte == '\n') return; 2639 } 2640 } 2641 2642 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2643 const root_focus = root.getFocus(); 2644 const focused_before = root_focus.grandchild_id; 2645 var activate_in_page_link = false; 2646 switch (key) { 2647 // request a navigation pop; the host's Nav.sync goes back a page, or 2648 // quits when there's no history left. 2649 .escape => { 2650 session.back = .requested; 2651 return; 2652 }, 2653 .ctrl => |letter| switch (letter) { 2654 'r' => { 2655 session.refresh_requested = true; 2656 return; 2657 }, 2658 else => try root.input(allocator, key, root_focus), 2659 }, 2660 .enter => { 2661 if (root_focus.grandchild_id) |gid| { 2662 // follow a cross-page link 2663 if (crossPageLink(root_focus, gid, session.data)) |route| { 2664 return session.navigate(route); 2665 } 2666 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2667 } 2668 activate_in_page_link = true; 2669 try root.input(allocator, key, root_focus); 2670 }, 2671 .mouse => |mouse| { 2672 if (mouse.button == .left) { 2673 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2674 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2675 const focus_id = hit.id; 2676 if (hit.kind == .background) { 2677 root_focus.setFocus(focus_id); 2678 return; 2679 } 2680 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2681 if (session.back == .available) session.back = .requested; 2682 return; 2683 } 2684 // follow a cross-page link 2685 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2686 return session.navigate(route); 2687 } 2688 if (currentPageLink(root_focus, focus_id, session.data)) return; 2689 if (rawLink(root_focus, focus_id)) |url| { 2690 if (!mouse.ctrl) try requestRawLink(session, url); 2691 return; 2692 } 2693 root_focus.setFocus(focus_id); 2694 activate_in_page_link = true; 2695 } 2696 // forward the press into the widget tree so buttons (and any 2697 // future click-aware widgets) can react. widgets that don't 2698 // care about presses ignore it. 2699 try root.input(allocator, key, root_focus); 2700 } else { 2701 try root.input(allocator, key, root_focus); 2702 } 2703 }, 2704 .event => |event| switch (event) { 2705 .background => |rgb| session.terminal_background = rgb, 2706 .resize => try root.input(allocator, key, root_focus), 2707 }, 2708 // a scroll tick goes to the pane under the pointer, focusing it first 2709 .scroll_up, .scroll_down => |position| { 2710 if (scrollUnder(root_focus, position)) |scroll_id| { 2711 if (!focusInside(root_focus, scroll_id)) root_focus.setFocus(scroll_id); 2712 } 2713 try root.input(allocator, key, root_focus); 2714 }, 2715 else => try root.input(allocator, key, root_focus), 2716 } 2717 2718 const focused_after = root_focus.grandchild_id; 2719 if (!activate_in_page_link and focused_before == focused_after) return; 2720 const focus_id = focused_after orelse return; 2721 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2722 } 2723 2724 // the innermost vertically scrolling widget laid out under `position` 2725 fn scrollUnder(root_focus: *const Focus, position: xitui.input.Position) ?usize { 2726 var found: ?usize = null; 2727 var found_area: usize = std.math.maxInt(usize); 2728 var iter = root_focus.children.iterator(); 2729 while (iter.next()) |entry| { 2730 const info = entry.value_ptr.focus.scroll orelse continue; 2731 if (info.direction == .horiz) continue; 2732 const r = entry.value_ptr.rect; 2733 if (position.x < r.x or position.y < r.y or position.x >= r.x + r.size.width or position.y >= r.y + r.size.height) continue; 2734 // a nested scroll lies within its parent, so the smallest is innermost 2735 const area = r.size.width * r.size.height; 2736 if (area < found_area) { 2737 found = entry.key_ptr.*; 2738 found_area = area; 2739 } 2740 } 2741 return found; 2742 } 2743 2744 // whether the focused widget is `id` or lies under it 2745 fn focusInside(root_focus: *const Focus, id: usize) bool { 2746 var current = root_focus.grandchild_id orelse return false; 2747 while (true) { 2748 if (current == id) return true; 2749 const child = root_focus.children.get(current) orelse return false; 2750 current = child.parent_id; 2751 } 2752 } 2753 2754 // a link to bytes the server serves directly rather than to a page route, so 2755 // it never resolves to a RoutablePage 2756 pub const raw_link_prefix = "ax:"; 2757 2758 // a route already loaded into the current page; focusing it changes the url 2759 // without rebuilding the page 2760 pub const in_page_link_prefix = "ai:"; 2761 2762 // an in-page tab's base route, or the exact current route when it is selected 2763 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2764 const target = if (selected) session.data.current_page else route; 2765 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2766 } 2767 2768 // a button the web renderer covers with a file picker that posts the chosen 2769 // file to the url after the prefix 2770 pub const file_input_prefix = "file:"; 2771 2772 // a submit button that overrides its enclosing form's action 2773 pub const submit_action_prefix = "submit:"; 2774 2775 // one option of a radio field, as `radio:<name>=<value>` 2776 pub const radio_prefix = "radio:"; 2777 2778 // the url an `ax:` link points at, or null for anything else. a host that 2779 // suppresses the anchor's own navigation needs this to follow the link. 2780 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2781 const child = root_focus.children.get(focus_id) orelse return null; 2782 const custom = switch (child.focus.kind) { 2783 .custom => |c| c, 2784 else => return null, 2785 }; 2786 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2787 return custom[raw_link_prefix.len..]; 2788 } 2789 2790 fn requestRawLink(session: *Session, url: []const u8) !void { 2791 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2792 } 2793 2794 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2795 // an absolute url is already complete 2796 if (!std.mem.startsWith(u8, path, "/")) return path; 2797 return if (session.web_port) |port| 2798 try allocator.print("http://localhost:{d}{s}", .{ port, path }) 2799 else 2800 path; 2801 } 2802 2803 // if the focus target at focus_id is an `a:` link that should navigate (a 2804 // different parent page, or a different files directory within the repo page), 2805 // return its route; otherwise null. lets a host turn a click / enter on such a 2806 // link into a navigation rather than a focus change. 2807 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2808 const current = data.current_page; 2809 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2810 // a link to a different parent page always navigates; within a page, a 2811 // files-directory / commits-page / list-window change navigates while tab 2812 // links stay in-page. 2813 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; 2814 return null; 2815 } 2816 2817 // the page the clicked cell links to, from a link inside a text box's content 2818 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 2819 const grid = root.getGrid() orelse return null; 2820 const cell = grid.cell(x, y) catch return null; 2821 const link = cell.link orelse return null; 2822 if (link.len == 0 or link[0] != '/') return null; 2823 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 2824 } 2825 2826 // whether the `a:` focus target links to the page already shown, which a click 2827 // leaves alone rather than focusing 2828 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 2829 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 2830 return route.eql(data.current_page); 2831 } 2832 2833 // the route carried by an `ai:` focus target, or null for any other target 2834 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2835 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2836 } 2837 2838 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2839 const child = root_focus.children.get(focus_id) orelse return null; 2840 const custom = switch (child.focus.kind) { 2841 .custom => |c| c, 2842 else => return null, 2843 }; 2844 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2845 const path = custom[prefix.len..]; 2846 // local sessions build (and parse) links with the repo identity elided 2847 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2848 } 2849 2850 // an assignee as the detail view shows it: the stored email, and the name of 2851 // the user holding it on this instance when there is one 2852 pub const Assignee = struct { 2853 email: []const u8, 2854 name: ?[]const u8 = null, 2855 2856 pub fn display(self: Assignee) []const u8 { 2857 return self.name orelse self.email; 2858 } 2859 }; 2860 2861 // a display author, resolved against the admin db at read time 2862 pub const Author = union(enum) { 2863 unknown, 2864 email: []const u8, // an email no user matches 2865 user_name: []const u8, 2866 2867 // the commit author line's email, resolved like initFromEmail 2868 pub fn init( 2869 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2870 arena: *std.heap.ArenaAllocator, 2871 author_line: []const u8, 2872 ) !Author { 2873 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2874 } 2875 2876 // from a record's stored author email: it resolves to the user currently 2877 // holding it, else stays the email. the result is allocated in `arena`, 2878 // so the email may borrow transient memory. 2879 pub fn initFromEmail( 2880 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2881 arena: *std.heap.ArenaAllocator, 2882 author_email: ?[]const u8, 2883 ) !Author { 2884 const email = author_email orelse return .unknown; 2885 if (haxy_moment) |moment| { 2886 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2887 return .{ .user_name = user.name }; 2888 } 2889 } 2890 return .{ .email = try arena.allocator().dupe(u8, email) }; 2891 } 2892 }; 2893 2894 // the "a:" link to user `name`'s page. 2895 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2896 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2897 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2898 return page_arena.allocator().print("a:{s}", .{url}); 2899 } 2900 2901 // a focusable " author " box showing `author`, linking to their user page 2902 // when it is a known user 2903 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2904 const text = switch (author) { 2905 .unknown => "", 2906 .email, .user_name => |t| t, 2907 }; 2908 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 2909 errdefer tb.deinit(allocator); 2910 tb.getFocus().mode = .all; 2911 switch (author) { 2912 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2913 else => {}, 2914 } 2915 return tb; 2916 } 2917 2918 // native-TUI navigation 2919 pub const Nav = struct { 2920 root: Widget, 2921 // backs the current page (its Page data and the page-scoped strings its 2922 // widgets build). owned here, swapped on each navigation. session.page_arena 2923 // tracks whichever of these is current so widgets allocate into it. 2924 arena: *std.heap.ArenaAllocator, 2925 // the login the current root was built for 2926 user_id: ?[evt.event_id_size]u8, 2927 history: std.ArrayList(Entry), 2928 2929 // each retained page keeps its own arena, freed when the page leaves the 2930 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2931 // long-lived session from accumulating every page it ever visited. 2932 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 2933 2934 // cap on retained back-history so the chain can't grow memory without bound 2935 const max_history: usize = 16; 2936 2937 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2938 session.back = .unavailable; 2939 const arena = try allocator.create(std.heap.ArenaAllocator); 2940 arena.* = std.heap.ArenaAllocator.init(allocator); 2941 errdefer { 2942 arena.deinit(); 2943 allocator.destroy(arena); 2944 } 2945 2946 return .{ 2947 .root = try initCurrentRoot(allocator, arena, session), 2948 .arena = arena, 2949 .user_id = session.userId(), 2950 .history = .empty, 2951 }; 2952 } 2953 2954 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2955 self.root.deinit(allocator); 2956 freeArena(allocator, self.arena); 2957 for (self.history.items) |*entry| { 2958 entry.root.deinit(allocator); 2959 freeArena(allocator, entry.arena); 2960 } 2961 self.history.deinit(allocator); 2962 } 2963 2964 // rebuild the current page in place from a current moment 2965 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2966 if (session.haxy_moment == null and session.local == null) return; 2967 const arena = try allocator.create(std.heap.ArenaAllocator); 2968 arena.* = std.heap.ArenaAllocator.init(allocator); 2969 errdefer freeArena(allocator, arena); 2970 2971 const new_root = try initCurrentRoot(allocator, arena, session); 2972 2973 self.root.deinit(allocator); 2974 freeArena(allocator, self.arena); 2975 self.root = new_root; 2976 self.arena = arena; 2977 self.user_id = session.userId(); 2978 } 2979 2980 // build the current page's root in `arena`, or the not-found page's when 2981 // the route names nothing 2982 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 2983 session.page_arena = arena; 2984 const page = try arena.allocator().create(Page); 2985 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 2986 error.NotFound => blk: { 2987 session.data.current_page = .not_found; 2988 break :blk .not_found; 2989 }, 2990 else => |e| return e, 2991 }; 2992 return initRoot(allocator, page, session); 2993 } 2994 2995 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2996 arena.deinit(); 2997 allocator.destroy(arena); 2998 } 2999 3000 // reconcile the displayed root with the session's navigation state. a 3001 // forward nav (current_page moved to a different parent page) pushes the 3002 // current root and builds the new page in a fresh arena; a back request 3003 // frees the current page and restores the previous one. when escape is 3004 // pressed with no history left we switch to the quit tab instead of quitting. 3005 // returns whether the root was replaced. 3006 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 3007 // refresh: rebuild the current page in place from a current moment 3008 if (session.refresh_requested) { 3009 session.refresh_requested = false; 3010 try self.rebuild(allocator, session); 3011 return true; 3012 } 3013 3014 if (session.back == .requested) { 3015 if (self.history.pop()) |entry| { 3016 session.back = if (self.history.items.len == 0) .unavailable else .available; 3017 self.root.deinit(allocator); 3018 freeArena(allocator, self.arena); 3019 self.root = entry.root; 3020 self.arena = entry.arena; 3021 self.user_id = entry.user_id; 3022 session.page_arena = entry.arena; 3023 session.data.current_page = entry.route; 3024 // a page built under another login is rebuilt rather than restored 3025 if (!std.meta.eql(entry.user_id, session.userId())) { 3026 try self.rebuild(allocator, session); 3027 return true; 3028 } 3029 chooseAnsiArtForNavigation(session); 3030 return true; 3031 } 3032 session.back = .unavailable; 3033 // nothing to go back to; switch to the quit confirmation 3034 const root_focus = self.root.getFocus(); 3035 var iter = root_focus.children.iterator(); 3036 while (iter.next()) |entry| { 3037 switch (entry.value_ptr.focus.kind) { 3038 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 3039 root_focus.setFocus(entry.key_ptr.*); 3040 // a Stack only builds its selected child, so the quit 3041 // button isn't in the focus tree until a build runs with 3042 // the quit tab selected. build once, then send a 3043 // synthetic arrow_down to drop focus from the tab onto 3044 // the button so it's ready to confirm. 3045 try self.root.build(allocator, .{ 3046 .min_size = .{ .width = null, .height = 40 }, 3047 .max_size = .{ .width = 80, .height = null }, 3048 }, root_focus); 3049 try self.root.input(allocator, .arrow_down, root_focus); 3050 break; 3051 }, 3052 else => {}, 3053 } 3054 } 3055 return false; 3056 } 3057 3058 // forward navigation: navigate() set next_page to the page to move to (a 3059 // cross-page link or tab change crossing pages) 3060 if (session.next_page) |route| { 3061 session.next_page = null; 3062 if (session.haxy_moment == null and session.local == null) return false; 3063 const previous_route = session.data.current_page; 3064 // the page we navigated to becomes the current page 3065 session.data.current_page = route; 3066 session.back = .available; 3067 3068 const arena = try allocator.create(std.heap.ArenaAllocator); 3069 arena.* = std.heap.ArenaAllocator.init(allocator); 3070 errdefer freeArena(allocator, arena); 3071 3072 const new_root = try initCurrentRoot(allocator, arena, session); 3073 3074 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 3075 // drop the oldest entry (freeing its widget tree and arena) once over cap 3076 if (self.history.items.len > max_history) { 3077 var oldest = self.history.orderedRemove(0); 3078 oldest.root.deinit(allocator); 3079 freeArena(allocator, oldest.arena); 3080 } 3081 self.root = new_root; 3082 self.arena = arena; 3083 self.user_id = session.userId(); 3084 return true; 3085 } 3086 return false; 3087 } 3088 }; 3089 3090 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3091 const page_widget: Widget = switch (page.*) { 3092 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3093 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3094 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3095 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3096 .not_found => .{ .not_found = try .init(allocator, session) }, 3097 }; 3098 3099 chooseAnsiArtForNavigation(session); 3100 3101 // on the TUI/SSH, the page sits above a one-row footer showing its web 3102 // url, when there's a web UI to point at 3103 var root = if (session.is_terminal) blk: { 3104 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3105 errdefer box.deinit(allocator); 3106 const bg_id = bg_blk: { 3107 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3108 errdefer background.deinit(allocator); 3109 const id = background.getFocus().id; 3110 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3111 break :bg_blk id; 3112 }; 3113 if (session.web_port != null) { 3114 var footer = try widget.Footer.init(allocator, session); 3115 errdefer footer.deinit(allocator); 3116 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3117 } 3118 box.getFocus().child_id = bg_id; 3119 break :blk Widget{ .box = box }; 3120 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3121 errdefer root.deinit(allocator); 3122 3123 // input-owning views build their TextInputs in init, so reset their 3124 // registrations here 3125 session.text_inputs.clearRetainingCapacity(); 3126 3127 try root.build(allocator, .{ 3128 .min_size = .{ .width = null, .height = 40 }, 3129 .max_size = .{ .width = 100, .height = null }, 3130 }, root.getFocus()); 3131 3132 return root; 3133 } 3134 3135 // native and server-side sessions choose from the embedded collection. WASM 3136 // keeps the art serialized by the server instead. 3137 fn chooseAnsiArtForNavigation(session: *Session) void { 3138 if (comptime ansi_art.art.len == 0) return; 3139 if (session.data.current_page == .not_found) { 3140 session.data.ansi_art = ansi_art.not_found; 3141 return; 3142 } 3143 const io = session.io orelse return; 3144 var random: usize = undefined; 3145 io.random(std.mem.asBytes(&random)); 3146 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3147 } 3148