╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1351 } 1352 }, 1353 } 1354 } 1355 1356 // per-connection mutable state. each SSH session / web session / local TUI 1357 // run gets its own. 1358 pub const Session = struct { 1359 data: Data = .{}, 1360 // session-lifetime allocations: login/user_id, persisted prefs, queued 1361 // actions. lives as long as the connection. 1362 arena: *std.heap.ArenaAllocator, 1363 // current page's allocations: page data and the page-scoped strings widgets 1364 // build (form actions, links). owned by Nav, swapped on each navigation, so 1365 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 1366 // where a render is one-shot, this points at the same arena as `arena`. 1367 page_arena: *std.heap.ArenaAllocator, 1368 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 1369 // filesystem io and the path to <server>/repos, for opening on-disk repos 1370 // during page construction. both null on wasm, which has no filesystem and 1371 // rebuilds pages from the serialized snapshot rather than from disk. 1372 io: ?std.Io = null, 1373 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 1374 repos_dir: ?[]const u8 = null, 1375 // the single on-disk repo this session views, when running in local mode 1376 // (haxy invoked with no arguments inside a repo). null on the server paths, 1377 // which resolve repos from the admin db instead. 1378 local: ?RepoSource = null, 1379 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 1380 // focus id -> the live TextInput, refreshed each frame by the views that own 1381 // inputs. web/wasm form handling looks widgets up here by focus id. 1382 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 1383 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 1384 refresh_requested: bool = false, // set by input (ctrl+r) 1385 // a requested forward navigation. set this (via navigate) to move to a new 1386 // page; Nav.sync builds it and then copies it into current_page, clearing 1387 // this back to null. setting current_page directly only updates the url and 1388 // does not navigate. 1389 next_page: ?RoutablePage = null, 1390 is_terminal: bool = false, // true on remote SSH and local TUI 1391 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 1392 // url. null on the web itself (no footer there). 1393 web_port: ?u16 = null, 1394 // a host operation requested by a widget 1395 host_request: ?HostRequest = null, 1396 quit_requested: bool = false, 1397 1398 pub const HostRequest = union(enum) { 1399 show_copyable_text: []const u8, 1400 sync_events, 1401 }; 1402 1403 const Self = @This(); 1404 1405 // serializable data sent down to web client 1406 pub const Data = struct { 1407 user_id: ?[]const u8 = null, 1408 // the logged-in user's name, for the views that show it 1409 user_name: ?[]const u8 = null, 1410 // a transient outcome to surface from the last /login POST attempt 1411 login_failure: ?Home.Auth.Login.Failure = null, 1412 // a transient local event-sync error 1413 sync_failure: ?[]const u8 = null, 1414 current_page: RoutablePage = .default, 1415 // whether to render the ANSI art backdrop 1416 enable_ansi: bool = true, 1417 // the selected ANSI art. the server serializes one image for WASM so 1418 // the browser does not need the whole build-generated collection. 1419 ansi_art: []const u8 = "", 1420 // the bound git-service ports. absent in local mode, where remote urls 1421 // are not shown. 1422 git_http_port: ?u16 = null, 1423 git_ssh_port: ?u16 = null, 1424 git_ssh_prefix: []const u8 = "", 1425 // true when this session views a single local repo. unlike `local` 1426 // (the host-side filesystem source) this travels in the snapshot, so 1427 // the wasm side also parses elided link urls and hides the multi-user 1428 // chrome. 1429 is_local: bool = false, 1430 }; 1431 1432 // a user-initiated state change. widgets enqueue these on the session during 1433 // input instead of mutating state or touching the DB themselves; the host 1434 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1435 // side effects out of the widget tree and gives every render path one place to 1436 // turn a UI action into a state change + event. 1437 pub const Action = union(enum) { 1438 toggle_ansi, 1439 }; 1440 1441 pub fn init( 1442 arena: *std.heap.ArenaAllocator, 1443 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1444 data: Data, 1445 ) !Self { 1446 var session = Self{ 1447 .data = data, 1448 .arena = arena, 1449 // until a host swaps in a page-scoped arena (Nav does this), page 1450 // allocations land in the session arena. on the web path that's the 1451 // intended behavior, since the whole arena is per-request. 1452 .page_arena = arena, 1453 .admin_repo = repo, 1454 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1455 }; 1456 try session.loadUser(); 1457 return session; 1458 } 1459 1460 // load the logged-in user's name and persisted preferences from the db 1461 pub fn loadUser(self: *Self) !void { 1462 const user_id = self.data.user_id orelse return; 1463 const moment = self.haxy_moment orelse return; 1464 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1465 self.data.user_name = user.event.name; 1466 self.data.enable_ansi = user.event.enable_ansi; 1467 } 1468 } 1469 1470 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 1471 const bytes = self.data.user_id orelse return null; 1472 if (bytes.len != evt.event_id_size) return null; 1473 var id: [evt.event_id_size]u8 = undefined; 1474 @memcpy(&id, bytes); 1475 return id; 1476 } 1477 1478 // the commit author for an event this session creates, or null when it may 1479 // not create one 1480 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1481 if (self.data.is_local) { 1482 const src = self.local orelse return local_author_fallback; 1483 const io = self.io orelse return local_author_fallback; 1484 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1485 } 1486 const user_id = self.data.user_id orelse return null; 1487 const moment = self.haxy_moment orelse return null; 1488 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1489 return .{ .name = user.event.name, .email = user.event.email }; 1490 } 1491 1492 // queue an action for the host to drain this frame. 1493 pub fn push(self: *Self, action: Action) !void { 1494 try self.pending.append(self.arena.allocator(), action); 1495 } 1496 1497 // apply a single action's in-memory effect only (no persistence). 1498 fn apply(self: *Self, action: Action) void { 1499 switch (action) { 1500 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1501 } 1502 } 1503 1504 // drain the session's queued actions by applying them to the session. 1505 // used on the wasm path, which has no repo to persist to. 1506 pub fn applyPending(self: *Self) void { 1507 for (self.pending.items) |action| self.apply(action); 1508 self.pending.clearRetainingCapacity(); 1509 } 1510 1511 // drain the session's queued actions by applying them to the session and 1512 // writing them to the db 1513 pub fn applyAndWritePending( 1514 self: *Self, 1515 io: std.Io, 1516 allocator: std.mem.Allocator, 1517 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1518 ) !void { 1519 defer self.pending.clearRetainingCapacity(); 1520 for (self.pending.items) |action| { 1521 self.apply(action); 1522 switch (action) { 1523 .toggle_ansi => if (self.data.user_id) |user_id| { 1524 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1525 }, 1526 } 1527 } 1528 } 1529 1530 // reload the moment from the admin repo and re-read user preferences 1531 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1532 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1533 self.haxy_moment = moment; 1534 1535 const user_id = self.data.user_id orelse return; 1536 var arena = std.heap.ArenaAllocator.init(allocator); 1537 defer arena.deinit(); 1538 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1539 self.data.enable_ansi = user.event.enable_ansi; 1540 } 1541 } 1542 1543 // request a forward navigation to `route`; the host consumes next_page 1544 // (Nav.sync on the terminal, the wasm tick on the web). 1545 pub fn navigate(self: *Session, route: RoutablePage) !void { 1546 self.next_page = route; 1547 } 1548 }; 1549 1550 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1551 var nav = try Nav.init(allocator, session); 1552 defer nav.deinit(allocator); 1553 1554 var terminal = try term.Terminal.init(io, allocator); 1555 var terminal_live = true; 1556 defer if (terminal_live) terminal.deinit(io); 1557 1558 // set term as active so it will be properly cooked 1559 // when a panic/segfault happens 1560 term.setActive(&terminal); 1561 defer term.setActive(null); 1562 1563 while (!terminal.shouldQuit()) { 1564 const grid_changed = try terminal.render(&nav.root); 1565 1566 // process any inputs. 1567 // 1568 // if the grid didn't change, then first do a blocking 1569 // read, so the thread will sleep until further input. 1570 // after that, all remaining reads are non-blocking so 1571 // we can process the rest of the queued inputs. 1572 // 1573 // if the grid *did* change, then only do non-blocking 1574 // reads. we do not want to sleep the thread because 1575 // there may be an animation that requires more looping. 1576 var blocking = !grid_changed; 1577 while (try terminal.readKey(io, blocking)) |key| { 1578 blocking = false; 1579 try inputKey(allocator, &nav.root, key, session); 1580 } 1581 1582 if (session.host_request) |request| { 1583 session.host_request = null; 1584 switch (request) { 1585 .show_copyable_text => |copyable_text| { 1586 term.setActive(null); 1587 terminal.deinit(io); 1588 terminal_live = false; 1589 showCopyableText(io, copyable_text) catch |show_err| { 1590 terminal = try term.Terminal.init(io, allocator); 1591 terminal_live = true; 1592 term.setActive(&terminal); 1593 return show_err; 1594 }; 1595 terminal = try term.Terminal.init(io, allocator); 1596 terminal_live = true; 1597 term.setActive(&terminal); 1598 }, 1599 .sync_events => { 1600 try nav.root.build(allocator, .{ 1601 .min_size = .{ .width = null, .height = null }, 1602 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 1603 }, nav.root.getFocus()); 1604 _ = try terminal.render(&nav.root); 1605 try Repo.Events.performSync(allocator, session); 1606 }, 1607 } 1608 } 1609 1610 // persist queued actions when there's a repo; local mode has none, 1611 // so just apply in-memory 1612 if (repo_maybe) |repo| { 1613 try session.applyAndWritePending(io, allocator, repo); 1614 // reload so the next navigation builds its page from the current moment 1615 try session.reloadMoment(allocator, repo); 1616 } else { 1617 session.applyPending(); 1618 } 1619 1620 // reconcile navigation: forward to a new page, or back on escape. 1621 try nav.sync(allocator, session); 1622 1623 // the quit button (on the quit tab) asks the host to tear down. 1624 if (session.quit_requested) terminal.requestQuit(); 1625 1626 try nav.root.build(allocator, .{ 1627 .min_size = .{ .width = null, .height = null }, 1628 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 1629 }, nav.root.getFocus()); 1630 } 1631 } 1632 1633 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 1634 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 1635 null 1636 else 1637 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 1638 defer if (tty) |file| file.close(io); 1639 1640 const input = if (tty) |file| file else std.Io.File.stdin(); 1641 const output = if (tty) |file| file else std.Io.File.stdout(); 1642 1643 var write_buf: [1024]u8 = undefined; 1644 var writer = output.writer(io, &write_buf); 1645 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}); 1646 try writer.interface.flush(); 1647 1648 var read_buf: [1]u8 = undefined; 1649 var reader = input.reader(io, &read_buf); 1650 while (true) { 1651 const byte = try reader.interface.takeByte(); 1652 if (byte == '\r' or byte == '\n') return; 1653 } 1654 } 1655 1656 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 1657 const root_focus = root.getFocus(); 1658 const focused_before = root_focus.grandchild_id; 1659 var activate_in_page_link = false; 1660 switch (key) { 1661 // request a navigation pop; the host's Nav.sync goes back a page, or 1662 // quits when there's no history left. 1663 .escape => { 1664 session.nav_back = true; 1665 return; 1666 }, 1667 .ctrl => |letter| switch (letter) { 1668 'r' => { 1669 session.refresh_requested = true; 1670 return; 1671 }, 1672 else => try root.input(allocator, key, root_focus), 1673 }, 1674 .enter => { 1675 if (root_focus.grandchild_id) |gid| { 1676 // follow a cross-page link 1677 if (crossPageLink(root_focus, gid, session.data)) |route| { 1678 return session.navigate(route); 1679 } 1680 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 1681 } 1682 activate_in_page_link = true; 1683 try root.input(allocator, key, root_focus); 1684 }, 1685 .mouse => |mouse| { 1686 if (mouse.action == .press and mouse.action.press == .left) { 1687 var clicked: ?usize = null; 1688 var iter = root_focus.children.iterator(); 1689 while (iter.next()) |entry| { 1690 const child = entry.value_ptr.*; 1691 if (!child.focus.focusable) continue; 1692 const r = child.rect; 1693 if (mouse.x >= r.x and mouse.y >= r.y and 1694 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 1695 { 1696 clicked = entry.key_ptr.*; 1697 break; 1698 } 1699 } 1700 if (clicked) |focus_id| { 1701 // follow a cross-page link 1702 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 1703 return session.navigate(route); 1704 } 1705 if (rawLink(root_focus, focus_id)) |url| { 1706 if (!mouse.ctrl) try requestRawLink(session, url); 1707 return; 1708 } 1709 root_focus.setFocus(focus_id); 1710 activate_in_page_link = true; 1711 } 1712 // forward the press into the widget tree so buttons (and any 1713 // future click-aware widgets) can react. widgets that don't 1714 // care about presses ignore it. 1715 try root.input(allocator, key, root_focus); 1716 } else { 1717 try root.input(allocator, key, root_focus); 1718 } 1719 }, 1720 else => try root.input(allocator, key, root_focus), 1721 } 1722 1723 const focused_after = root_focus.grandchild_id; 1724 if (!activate_in_page_link and focused_before == focused_after) return; 1725 const focus_id = focused_after orelse return; 1726 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 1727 } 1728 1729 // a link to bytes the server serves directly rather than to a page route, so 1730 // it never resolves to a RoutablePage 1731 pub const raw_link_prefix = "ax:"; 1732 1733 // a route already loaded into the current page; focusing it changes the url 1734 // without rebuilding the page 1735 pub const in_page_link_prefix = "ai:"; 1736 1737 // an in-page tab's base route, or the exact current route when it is selected 1738 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 1739 const target = if (selected) session.data.current_page else route; 1740 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 1741 } 1742 1743 // a button the web renderer covers with a file picker that posts the chosen 1744 // file to the url after the prefix 1745 pub const file_input_prefix = "file:"; 1746 1747 // a submit button that overrides its enclosing form's action 1748 pub const submit_action_prefix = "submit:"; 1749 1750 // the url an `ax:` link points at, or null for anything else. a host that 1751 // suppresses the anchor's own navigation needs this to follow the link. 1752 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 1753 const child = root_focus.children.get(focus_id) orelse return null; 1754 const custom = switch (child.focus.kind) { 1755 .custom => |c| c, 1756 else => return null, 1757 }; 1758 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 1759 return custom[raw_link_prefix.len..]; 1760 } 1761 1762 fn requestRawLink(session: *Session, url: []const u8) !void { 1763 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 1764 } 1765 1766 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 1767 return if (session.web_port) |port| 1768 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 1769 else 1770 path; 1771 } 1772 1773 // if the focus target at focus_id is an `a:` link that should navigate (a 1774 // different parent page, or a different files directory within the repo page), 1775 // return its route; otherwise null. lets a host turn a click / enter on such a 1776 // link into a navigation rather than a focus change. 1777 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1778 const current = data.current_page; 1779 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 1780 // a link to a different parent page always navigates; within a page, a 1781 // files-directory / commits-page / list-window change navigates while tab 1782 // links stay in-page. 1783 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 1784 return null; 1785 } 1786 1787 // the route carried by an `ai:` focus target, or null for any other target 1788 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1789 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 1790 } 1791 1792 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 1793 const child = root_focus.children.get(focus_id) orelse return null; 1794 const custom = switch (child.focus.kind) { 1795 .custom => |c| c, 1796 else => return null, 1797 }; 1798 if (!std.mem.startsWith(u8, custom, prefix)) return null; 1799 const path = custom[prefix.len..]; 1800 // local sessions build (and parse) links with the repo identity elided 1801 return if (data.is_local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 1802 } 1803 1804 // a display author, resolved against the admin db at read time 1805 pub const Author = union(enum) { 1806 unknown, 1807 email: []const u8, // an email no user matches 1808 user_name: []const u8, 1809 1810 // the commit author line's email, resolved like initFromEmail 1811 pub fn init( 1812 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1813 arena: *std.heap.ArenaAllocator, 1814 author_line: []const u8, 1815 ) !Author { 1816 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 1817 } 1818 1819 // from a record's stored author email: it resolves to the user currently 1820 // holding it, else stays the email. the result is allocated in `arena`, 1821 // so the email may borrow transient memory. 1822 pub fn initFromEmail( 1823 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1824 arena: *std.heap.ArenaAllocator, 1825 author_email: ?[]const u8, 1826 ) !Author { 1827 const email = author_email orelse return .unknown; 1828 if (haxy_moment) |moment| { 1829 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 1830 return .{ .user_name = user.event.name }; 1831 } 1832 } 1833 return .{ .email = try arena.allocator().dupe(u8, email) }; 1834 } 1835 }; 1836 1837 // the "a:" link to user `name`'s page. 1838 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 1839 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 1840 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 1841 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 1842 } 1843 1844 // a focusable " author " box showing `author`, linking to their user page 1845 // when it is a known user 1846 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 1847 const text = switch (author) { 1848 .unknown => "", 1849 .email, .user_name => |t| t, 1850 }; 1851 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 1852 errdefer tb.deinit(allocator); 1853 tb.getFocus().focusable = true; 1854 switch (author) { 1855 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 1856 else => {}, 1857 } 1858 return tb; 1859 } 1860 1861 // native-TUI navigation 1862 pub const Nav = struct { 1863 root: Widget, 1864 route: RoutablePage, 1865 // backs the current page (its Page data and the page-scoped strings its 1866 // widgets build). owned here, swapped on each navigation. session.page_arena 1867 // tracks whichever of these is current so widgets allocate into it. 1868 arena: *std.heap.ArenaAllocator, 1869 history: std.ArrayList(Entry), 1870 1871 // each retained page keeps its own arena, freed when the page leaves the 1872 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 1873 // long-lived session from accumulating every page it ever visited. 1874 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 1875 1876 // cap on retained back-history so the chain can't grow memory without bound 1877 const max_history: usize = 16; 1878 1879 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 1880 const arena = try allocator.create(std.heap.ArenaAllocator); 1881 arena.* = std.heap.ArenaAllocator.init(allocator); 1882 errdefer { 1883 arena.deinit(); 1884 allocator.destroy(arena); 1885 } 1886 1887 session.page_arena = arena; 1888 const route = session.data.current_page; 1889 1890 const page = try arena.allocator().create(Page); 1891 page.* = try Page.init(arena, session, route); 1892 return .{ 1893 .root = try initRoot(allocator, page, session), 1894 .route = route, 1895 .arena = arena, 1896 .history = .empty, 1897 }; 1898 } 1899 1900 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 1901 self.root.deinit(allocator); 1902 freeArena(allocator, self.arena); 1903 for (self.history.items) |*entry| { 1904 entry.root.deinit(allocator); 1905 freeArena(allocator, entry.arena); 1906 } 1907 self.history.deinit(allocator); 1908 } 1909 1910 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 1911 arena.deinit(); 1912 allocator.destroy(arena); 1913 } 1914 1915 // reconcile the displayed root with the session's navigation state. a 1916 // forward nav (current_page moved to a different parent page) pushes the 1917 // current root and builds the new page in a fresh arena; a back request 1918 // frees the current page and restores the previous one. when escape is 1919 // pressed with no history left we switch to the quit tab instead of quitting. 1920 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 1921 // refresh: rebuild the current page in place from a current moment 1922 if (session.refresh_requested) { 1923 session.refresh_requested = false; 1924 if (session.haxy_moment != null or session.local != null) { 1925 const arena = try allocator.create(std.heap.ArenaAllocator); 1926 arena.* = std.heap.ArenaAllocator.init(allocator); 1927 errdefer freeArena(allocator, arena); 1928 1929 session.page_arena = arena; 1930 1931 const route = session.data.current_page; 1932 const page = try arena.allocator().create(Page); 1933 page.* = try Page.init(arena, session, route); 1934 const new_root = try initRoot(allocator, page, session); 1935 1936 self.root.deinit(allocator); 1937 freeArena(allocator, self.arena); 1938 self.root = new_root; 1939 self.route = route; 1940 self.arena = arena; 1941 } 1942 return; 1943 } 1944 1945 if (session.nav_back) { 1946 session.nav_back = false; 1947 if (self.history.pop()) |entry| { 1948 self.root.deinit(allocator); 1949 freeArena(allocator, self.arena); 1950 self.root = entry.root; 1951 self.route = entry.route; 1952 self.arena = entry.arena; 1953 session.page_arena = entry.arena; 1954 session.data.current_page = entry.route; 1955 chooseAnsiArtForNavigation(session); 1956 return; 1957 } 1958 // nothing to go back to; switch to the quit confirmation 1959 const root_focus = self.root.getFocus(); 1960 var iter = root_focus.children.iterator(); 1961 while (iter.next()) |entry| { 1962 switch (entry.value_ptr.focus.kind) { 1963 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 1964 root_focus.setFocus(entry.key_ptr.*); 1965 // a Stack only builds its selected child, so the quit 1966 // button isn't in the focus tree until a build runs with 1967 // the quit tab selected. build once, then send a 1968 // synthetic arrow_down to drop focus from the tab onto 1969 // the button so it's ready to confirm. 1970 try self.root.build(allocator, .{ 1971 .min_size = .{ .width = null, .height = 40 }, 1972 .max_size = .{ .width = 80, .height = null }, 1973 }, root_focus); 1974 try self.root.input(allocator, .arrow_down, root_focus); 1975 break; 1976 }, 1977 else => {}, 1978 } 1979 } 1980 return; 1981 } 1982 1983 // forward navigation: navigate() set next_page to the page to move to (a 1984 // cross-page link or tab change crossing pages) 1985 if (session.next_page) |route| { 1986 session.next_page = null; 1987 if (session.haxy_moment == null and session.local == null) return; 1988 // the page we navigated to becomes the current page 1989 session.data.current_page = route; 1990 1991 const arena = try allocator.create(std.heap.ArenaAllocator); 1992 arena.* = std.heap.ArenaAllocator.init(allocator); 1993 errdefer freeArena(allocator, arena); 1994 1995 session.page_arena = arena; 1996 1997 const page = try arena.allocator().create(Page); 1998 page.* = try Page.init(arena, session, route); 1999 const new_root = try initRoot(allocator, page, session); 2000 2001 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 2002 // drop the oldest entry (freeing its widget tree and arena) once over cap 2003 if (self.history.items.len > max_history) { 2004 var oldest = self.history.orderedRemove(0); 2005 oldest.root.deinit(allocator); 2006 freeArena(allocator, oldest.arena); 2007 } 2008 self.root = new_root; 2009 self.route = route; 2010 self.arena = arena; 2011 } 2012 } 2013 }; 2014 2015 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2016 const page_widget: Widget = switch (page.*) { 2017 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2018 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2019 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2020 }; 2021 2022 chooseAnsiArtForNavigation(session); 2023 2024 // on the TUI/SSH, the page sits above a one-row footer showing the url 2025 var root = if (session.is_terminal) blk: { 2026 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2027 errdefer box.deinit(allocator); 2028 const bg_id = bg_blk: { 2029 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2030 errdefer background.deinit(allocator); 2031 const id = background.getFocus().id; 2032 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2033 break :bg_blk id; 2034 }; 2035 { 2036 var footer = try widget.Footer.init(allocator, session); 2037 errdefer footer.deinit(allocator); 2038 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2039 } 2040 box.getFocus().child_id = bg_id; 2041 break :blk Widget{ .box = box }; 2042 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2043 errdefer root.deinit(allocator); 2044 2045 // input-owning views build their TextInputs in init, so reset their 2046 // registrations here 2047 session.text_inputs.clearRetainingCapacity(); 2048 2049 try root.build(allocator, .{ 2050 .min_size = .{ .width = null, .height = 40 }, 2051 .max_size = .{ .width = 100, .height = null }, 2052 }, root.getFocus()); 2053 2054 return root; 2055 } 2056 2057 // native and server-side sessions choose from the embedded collection. WASM 2058 // keeps the art serialized by the server instead. 2059 fn chooseAnsiArtForNavigation(session: *Session) void { 2060 if (comptime ansi_arts.len == 0) return; 2061 const io = session.io orelse return; 2062 var random: usize = undefined; 2063 io.random(std.mem.asBytes(&random)); 2064 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2065 } 2066