╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1462 }; 1463 } 1464 }; 1465 1466 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 1467 fn isUnreserved(c: u8) bool { 1468 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1469 } 1470 1471 // percent-encode a ref name for use as a single url path segment. 1472 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 1473 var out: std.Io.Writer.Allocating = .init(aa); 1474 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 1475 return out.written(); 1476 } 1477 1478 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 1479 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1480 return struct { 1481 pub const hex_len = hash.hexLen(repo_opts.hash); 1482 1483 // the concrete ref/oid (a null request resolves to the default branch) 1484 ref_or_oid: RoutablePage.RefOrOid, 1485 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 1486 // the route layer — which splits on '/' — stores them encoded). duped 1487 // into `aa`. 1488 value: []const u8, 1489 // the commit oid it points at 1490 oid: [hex_len]u8, 1491 1492 const Self = @This(); 1493 1494 // resolve a requested ref/oid (null = the repo's default branch) to a 1495 // concrete ref/oid plus the commit oid it points at. `requested_value` is 1496 // the url-encoded form (as it appears in the route). null when it doesn't 1497 // resolve (an unknown branch/tag, or a malformed/unknown oid). 1498 pub fn init( 1499 repo: *rp.Repo(repo_kind, repo_opts), 1500 io: std.Io, 1501 aa: std.mem.Allocator, 1502 requested_ref_or_oid: ?RoutablePage.RefOrOid, 1503 requested_value: []const u8, 1504 ) !?Self { 1505 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 1506 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 1507 var value: []const u8 = if (requested_ref_or_oid == null) 1508 requested_value 1509 else 1510 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 1511 // no ref named: fall back to HEAD's branch (or its oid when detached). 1512 if (requested_ref_or_oid == null) { 1513 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1514 if (repo.head(io, &head_buf)) |head| switch (head) { 1515 .ref => |r| { 1516 ref_or_oid = .branch; 1517 value = r.name; 1518 }, 1519 .oid => |o| { 1520 ref_or_oid = .object; 1521 value = o; 1522 }, 1523 } else |_| {} 1524 } 1525 1526 var oid: [hex_len]u8 = undefined; 1527 switch (ref_or_oid) { 1528 .object => { 1529 if (value.len != hex_len) return null; 1530 @memcpy(&oid, value); 1531 }, 1532 .branch, .tag => { 1533 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 1534 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 1535 }, 1536 } 1537 // store url-encoded so the route layer can hold the value verbatim. 1538 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 1539 } 1540 }; 1541 } 1542 1543 // where a repo page reads its on-disk repo from 1544 pub const RepoSource = struct { 1545 path: []const u8, 1546 repo_kind: rp.RepoKind, 1547 // the user's global git config, so local mode picks up their identity and 1548 // their signing and ssh settings. null on the server paths, which must not 1549 // read whoever runs the server. 1550 global_config_path: ?[]const u8 = null, 1551 1552 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 1553 return .{ .path = self.path, .global_config_path = self.global_config_path }; 1554 } 1555 }; 1556 1557 // events created in local mode have no account behind them, so the commit 1558 // author comes from the repo's config, which the global config feeds into. 1559 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 1560 1561 pub fn localAuthor( 1562 src: RepoSource, 1563 io: std.Io, 1564 allocator: std.mem.Allocator, 1565 arena: *std.heap.ArenaAllocator, 1566 ) !evt.CommitAuthor { 1567 switch (src.repo_kind) { 1568 inline else => |repo_kind| { 1569 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 1570 defer any_repo.deinit(io, allocator); 1571 1572 switch (any_repo) { 1573 inline else => |*repo| { 1574 var config = try repo.listConfig(io, allocator); 1575 defer config.deinit(); 1576 1577 const user = config.sections.get("user") orelse return local_author_fallback; 1578 const name = user.get("name") orelse return local_author_fallback; 1579 const email = user.get("email") orelse return local_author_fallback; 1580 return .{ 1581 .name = try arena.allocator().dupe(u8, name), 1582 .email = try arena.allocator().dupe(u8, email), 1583 }; 1584 }, 1585 } 1586 }, 1587 } 1588 } 1589 1590 // per-connection mutable state. each SSH session / web session / local TUI 1591 // run gets its own. 1592 pub const Session = struct { 1593 data: Data = .{}, 1594 // session-lifetime allocations: login/user_id, persisted prefs, queued 1595 // actions. lives as long as the connection. 1596 arena: *std.heap.ArenaAllocator, 1597 // current page's allocations: page data and the page-scoped strings widgets 1598 // build (form actions, links). owned by Nav, swapped on each navigation, so 1599 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 1600 // where a render is one-shot, this points at the same arena as `arena`. 1601 page_arena: *std.heap.ArenaAllocator, 1602 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 1603 // filesystem io and the path to <server>/repos, for opening on-disk repos 1604 // during page construction. both null on wasm, which has no filesystem and 1605 // rebuilds pages from the serialized snapshot rather than from disk. 1606 io: ?std.Io = null, 1607 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 1608 repos_dir: ?[]const u8 = null, 1609 // the single on-disk repo this session views, when running in local mode 1610 // (haxy invoked with no arguments inside a repo). null on the server paths, 1611 // which resolve repos from the admin db instead. 1612 local: ?RepoSource = null, 1613 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 1614 // focus id -> the live TextInput, refreshed each frame by the views that own 1615 // inputs. web/wasm form handling looks widgets up here by focus id. 1616 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 1617 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 1618 refresh_requested: bool = false, // set by input (ctrl+r) 1619 // a requested forward navigation. set this (via navigate) to move to a new 1620 // page; Nav.sync builds it and then copies it into current_page, clearing 1621 // this back to null. setting current_page directly only updates the url and 1622 // does not navigate. 1623 next_page: ?RoutablePage = null, 1624 is_terminal: bool = false, // true on remote SSH and local TUI 1625 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 1626 // url. null on the web itself (no footer there). 1627 web_port: ?u16 = null, 1628 // a host operation requested by a widget 1629 host_request: ?HostRequest = null, 1630 quit_requested: bool = false, 1631 1632 pub const HostRequest = union(enum) { 1633 show_copyable_text: []const u8, 1634 sync_events, 1635 }; 1636 1637 const Self = @This(); 1638 1639 // serializable data sent down to web client 1640 pub const Data = struct { 1641 user_id: ?[]const u8 = null, 1642 // the logged-in user's name, for the views that show it 1643 user_name: ?[]const u8 = null, 1644 // a transient outcome to surface from the last /login POST attempt 1645 login_failure: ?Home.Auth.Login.Failure = null, 1646 // a transient local event-sync error 1647 sync_failure: ?[]const u8 = null, 1648 current_page: RoutablePage = .default, 1649 // whether to render the ANSI art backdrop 1650 enable_ansi: bool = true, 1651 // the selected ANSI art. the server serializes one image for WASM so 1652 // the browser does not need the whole build-generated collection. 1653 ansi_art: []const u8 = "", 1654 // the bound git-service ports. absent in local mode, where remote urls 1655 // are not shown. 1656 git_http_port: ?u16 = null, 1657 git_ssh_port: ?u16 = null, 1658 git_ssh_prefix: []const u8 = "", 1659 // true when this session views a single local repo. unlike `local` 1660 // (the host-side filesystem source) this travels in the snapshot, so 1661 // the wasm side also parses elided link urls and hides the multi-user 1662 // chrome. 1663 is_local: bool = false, 1664 }; 1665 1666 // a user-initiated state change. widgets enqueue these on the session during 1667 // input instead of mutating state or touching the DB themselves; the host 1668 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1669 // side effects out of the widget tree and gives every render path one place to 1670 // turn a UI action into a state change + event. 1671 pub const Action = union(enum) { 1672 toggle_ansi, 1673 }; 1674 1675 pub fn init( 1676 arena: *std.heap.ArenaAllocator, 1677 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1678 data: Data, 1679 ) !Self { 1680 var session = Self{ 1681 .data = data, 1682 .arena = arena, 1683 // until a host swaps in a page-scoped arena (Nav does this), page 1684 // allocations land in the session arena. on the web path that's the 1685 // intended behavior, since the whole arena is per-request. 1686 .page_arena = arena, 1687 .admin_repo = repo, 1688 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1689 }; 1690 try session.loadUser(); 1691 return session; 1692 } 1693 1694 // load the logged-in user's name and persisted preferences from the db 1695 pub fn loadUser(self: *Self) !void { 1696 const user_id = self.data.user_id orelse return; 1697 const moment = self.haxy_moment orelse return; 1698 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1699 self.data.user_name = user.event.name; 1700 self.data.enable_ansi = user.event.enable_ansi; 1701 } 1702 } 1703 1704 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 1705 const bytes = self.data.user_id orelse return null; 1706 if (bytes.len != evt.event_id_size) return null; 1707 var id: [evt.event_id_size]u8 = undefined; 1708 @memcpy(&id, bytes); 1709 return id; 1710 } 1711 1712 // the commit author for an event this session creates, or null when it may 1713 // not create one 1714 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1715 if (self.data.is_local) { 1716 const src = self.local orelse return local_author_fallback; 1717 const io = self.io orelse return local_author_fallback; 1718 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1719 } 1720 const user_id = self.data.user_id orelse return null; 1721 const moment = self.haxy_moment orelse return null; 1722 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1723 return .{ .name = user.event.name, .email = user.event.email }; 1724 } 1725 1726 // queue an action for the host to drain this frame. 1727 pub fn push(self: *Self, action: Action) !void { 1728 try self.pending.append(self.arena.allocator(), action); 1729 } 1730 1731 // apply a single action's in-memory effect only (no persistence). 1732 fn apply(self: *Self, action: Action) void { 1733 switch (action) { 1734 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1735 } 1736 } 1737 1738 // drain the session's queued actions by applying them to the session. 1739 // used on the wasm path, which has no repo to persist to. 1740 pub fn applyPending(self: *Self) void { 1741 for (self.pending.items) |action| self.apply(action); 1742 self.pending.clearRetainingCapacity(); 1743 } 1744 1745 // drain the session's queued actions by applying them to the session and 1746 // writing them to the db 1747 pub fn applyAndWritePending( 1748 self: *Self, 1749 io: std.Io, 1750 allocator: std.mem.Allocator, 1751 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1752 ) !void { 1753 defer self.pending.clearRetainingCapacity(); 1754 for (self.pending.items) |action| { 1755 self.apply(action); 1756 switch (action) { 1757 .toggle_ansi => if (self.data.user_id) |user_id| { 1758 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1759 }, 1760 } 1761 } 1762 } 1763 1764 // reload the moment from the admin repo and re-read user preferences 1765 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1766 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1767 self.haxy_moment = moment; 1768 1769 const user_id = self.data.user_id orelse return; 1770 var arena = std.heap.ArenaAllocator.init(allocator); 1771 defer arena.deinit(); 1772 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1773 self.data.enable_ansi = user.event.enable_ansi; 1774 } 1775 } 1776 1777 // request a forward navigation to `route`; the host consumes next_page 1778 // (Nav.sync on the terminal, the wasm tick on the web). 1779 pub fn navigate(self: *Session, route: RoutablePage) !void { 1780 self.next_page = route; 1781 } 1782 }; 1783 1784 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1785 var nav = try Nav.init(allocator, session); 1786 defer nav.deinit(allocator); 1787 1788 var terminal = try term.Terminal.init(io, allocator); 1789 var terminal_live = true; 1790 defer if (terminal_live) terminal.deinit(io); 1791 1792 // set term as active so it will be properly cooked 1793 // when a panic/segfault happens 1794 term.setActive(&terminal); 1795 defer term.setActive(null); 1796 1797 while (!terminal.shouldQuit()) { 1798 const grid_changed = try terminal.render(&nav.root); 1799 1800 // process any inputs. 1801 // 1802 // if the grid didn't change, then first do a blocking 1803 // read, so the thread will sleep until further input. 1804 // after that, all remaining reads are non-blocking so 1805 // we can process the rest of the queued inputs. 1806 // 1807 // if the grid *did* change, then only do non-blocking 1808 // reads. we do not want to sleep the thread because 1809 // there may be an animation that requires more looping. 1810 var blocking = !grid_changed; 1811 while (try terminal.readKey(io, blocking)) |key| { 1812 blocking = false; 1813 try inputKey(allocator, &nav.root, key, session); 1814 } 1815 1816 if (session.host_request) |request| { 1817 session.host_request = null; 1818 switch (request) { 1819 .show_copyable_text => |copyable_text| { 1820 term.setActive(null); 1821 terminal.deinit(io); 1822 terminal_live = false; 1823 showCopyableText(io, copyable_text) catch |show_err| { 1824 terminal = try term.Terminal.init(io, allocator); 1825 terminal_live = true; 1826 term.setActive(&terminal); 1827 return show_err; 1828 }; 1829 terminal = try term.Terminal.init(io, allocator); 1830 terminal_live = true; 1831 term.setActive(&terminal); 1832 }, 1833 .sync_events => { 1834 try nav.root.build(allocator, .{ 1835 .min_size = .{ .width = null, .height = null }, 1836 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 1837 }, nav.root.getFocus()); 1838 _ = try terminal.render(&nav.root); 1839 try Repo.Events.performSync(allocator, session); 1840 }, 1841 } 1842 } 1843 1844 // persist queued actions when there's a repo; local mode has none, 1845 // so just apply in-memory 1846 if (repo_maybe) |repo| { 1847 try session.applyAndWritePending(io, allocator, repo); 1848 // reload so the next navigation builds its page from the current moment 1849 try session.reloadMoment(allocator, repo); 1850 } else { 1851 session.applyPending(); 1852 } 1853 1854 // reconcile navigation: forward to a new page, or back on escape. 1855 try nav.sync(allocator, session); 1856 1857 // the quit button (on the quit tab) asks the host to tear down. 1858 if (session.quit_requested) terminal.requestQuit(); 1859 1860 try nav.root.build(allocator, .{ 1861 .min_size = .{ .width = null, .height = null }, 1862 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 1863 }, nav.root.getFocus()); 1864 } 1865 } 1866 1867 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 1868 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 1869 null 1870 else 1871 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 1872 defer if (tty) |file| file.close(io); 1873 1874 const input = if (tty) |file| file else std.Io.File.stdin(); 1875 const output = if (tty) |file| file else std.Io.File.stdout(); 1876 1877 var write_buf: [1024]u8 = undefined; 1878 var writer = output.writer(io, &write_buf); 1879 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}); 1880 try writer.interface.flush(); 1881 1882 var read_buf: [1]u8 = undefined; 1883 var reader = input.reader(io, &read_buf); 1884 while (true) { 1885 const byte = try reader.interface.takeByte(); 1886 if (byte == '\r' or byte == '\n') return; 1887 } 1888 } 1889 1890 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 1891 const root_focus = root.getFocus(); 1892 const focused_before = root_focus.grandchild_id; 1893 var activate_in_page_link = false; 1894 switch (key) { 1895 // request a navigation pop; the host's Nav.sync goes back a page, or 1896 // quits when there's no history left. 1897 .escape => { 1898 session.nav_back = true; 1899 return; 1900 }, 1901 .ctrl => |letter| switch (letter) { 1902 'r' => { 1903 session.refresh_requested = true; 1904 return; 1905 }, 1906 else => try root.input(allocator, key, root_focus), 1907 }, 1908 .enter => { 1909 if (root_focus.grandchild_id) |gid| { 1910 // follow a cross-page link 1911 if (crossPageLink(root_focus, gid, session.data)) |route| { 1912 return session.navigate(route); 1913 } 1914 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 1915 } 1916 activate_in_page_link = true; 1917 try root.input(allocator, key, root_focus); 1918 }, 1919 .mouse => |mouse| { 1920 if (mouse.action == .press and mouse.action.press == .left) { 1921 var clicked: ?usize = null; 1922 var iter = root_focus.children.iterator(); 1923 while (iter.next()) |entry| { 1924 const child = entry.value_ptr.*; 1925 if (!child.focus.focusable) continue; 1926 const r = child.rect; 1927 if (mouse.x >= r.x and mouse.y >= r.y and 1928 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 1929 { 1930 clicked = entry.key_ptr.*; 1931 break; 1932 } 1933 } 1934 if (clicked) |focus_id| { 1935 // follow a cross-page link 1936 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 1937 return session.navigate(route); 1938 } 1939 if (rawLink(root_focus, focus_id)) |url| { 1940 if (!mouse.ctrl) try requestRawLink(session, url); 1941 return; 1942 } 1943 root_focus.setFocus(focus_id); 1944 activate_in_page_link = true; 1945 } 1946 // forward the press into the widget tree so buttons (and any 1947 // future click-aware widgets) can react. widgets that don't 1948 // care about presses ignore it. 1949 try root.input(allocator, key, root_focus); 1950 } else { 1951 try root.input(allocator, key, root_focus); 1952 } 1953 }, 1954 else => try root.input(allocator, key, root_focus), 1955 } 1956 1957 const focused_after = root_focus.grandchild_id; 1958 if (!activate_in_page_link and focused_before == focused_after) return; 1959 const focus_id = focused_after orelse return; 1960 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 1961 } 1962 1963 // a link to bytes the server serves directly rather than to a page route, so 1964 // it never resolves to a RoutablePage 1965 pub const raw_link_prefix = "ax:"; 1966 1967 // a route already loaded into the current page; focusing it changes the url 1968 // without rebuilding the page 1969 pub const in_page_link_prefix = "ai:"; 1970 1971 // an in-page tab's base route, or the exact current route when it is selected 1972 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 1973 const target = if (selected) session.data.current_page else route; 1974 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 1975 } 1976 1977 // a button the web renderer covers with a file picker that posts the chosen 1978 // file to the url after the prefix 1979 pub const file_input_prefix = "file:"; 1980 1981 // a submit button that overrides its enclosing form's action 1982 pub const submit_action_prefix = "submit:"; 1983 1984 // the url an `ax:` link points at, or null for anything else. a host that 1985 // suppresses the anchor's own navigation needs this to follow the link. 1986 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 1987 const child = root_focus.children.get(focus_id) orelse return null; 1988 const custom = switch (child.focus.kind) { 1989 .custom => |c| c, 1990 else => return null, 1991 }; 1992 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 1993 return custom[raw_link_prefix.len..]; 1994 } 1995 1996 fn requestRawLink(session: *Session, url: []const u8) !void { 1997 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 1998 } 1999 2000 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2001 return if (session.web_port) |port| 2002 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 2003 else 2004 path; 2005 } 2006 2007 // if the focus target at focus_id is an `a:` link that should navigate (a 2008 // different parent page, or a different files directory within the repo page), 2009 // return its route; otherwise null. lets a host turn a click / enter on such a 2010 // link into a navigation rather than a focus change. 2011 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2012 const current = data.current_page; 2013 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2014 // a link to a different parent page always navigates; within a page, a 2015 // files-directory / commits-page / list-window change navigates while tab 2016 // links stay in-page. 2017 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; 2018 return null; 2019 } 2020 2021 // the route carried by an `ai:` focus target, or null for any other target 2022 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2023 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2024 } 2025 2026 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2027 const child = root_focus.children.get(focus_id) orelse return null; 2028 const custom = switch (child.focus.kind) { 2029 .custom => |c| c, 2030 else => return null, 2031 }; 2032 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2033 const path = custom[prefix.len..]; 2034 // local sessions build (and parse) links with the repo identity elided 2035 return if (data.is_local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2036 } 2037 2038 // a display author, resolved against the admin db at read time 2039 pub const Author = union(enum) { 2040 unknown, 2041 email: []const u8, // an email no user matches 2042 user_name: []const u8, 2043 2044 // the commit author line's email, resolved like initFromEmail 2045 pub fn init( 2046 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2047 arena: *std.heap.ArenaAllocator, 2048 author_line: []const u8, 2049 ) !Author { 2050 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2051 } 2052 2053 // from a record's stored author email: it resolves to the user currently 2054 // holding it, else stays the email. the result is allocated in `arena`, 2055 // so the email may borrow transient memory. 2056 pub fn initFromEmail( 2057 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2058 arena: *std.heap.ArenaAllocator, 2059 author_email: ?[]const u8, 2060 ) !Author { 2061 const email = author_email orelse return .unknown; 2062 if (haxy_moment) |moment| { 2063 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2064 return .{ .user_name = user.event.name }; 2065 } 2066 } 2067 return .{ .email = try arena.allocator().dupe(u8, email) }; 2068 } 2069 }; 2070 2071 // the "a:" link to user `name`'s page. 2072 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2073 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2074 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2075 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 2076 } 2077 2078 // a focusable " author " box showing `author`, linking to their user page 2079 // when it is a known user 2080 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2081 const text = switch (author) { 2082 .unknown => "", 2083 .email, .user_name => |t| t, 2084 }; 2085 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 2086 errdefer tb.deinit(allocator); 2087 tb.getFocus().focusable = true; 2088 switch (author) { 2089 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2090 else => {}, 2091 } 2092 return tb; 2093 } 2094 2095 // native-TUI navigation 2096 pub const Nav = struct { 2097 root: Widget, 2098 route: RoutablePage, 2099 // backs the current page (its Page data and the page-scoped strings its 2100 // widgets build). owned here, swapped on each navigation. session.page_arena 2101 // tracks whichever of these is current so widgets allocate into it. 2102 arena: *std.heap.ArenaAllocator, 2103 history: std.ArrayList(Entry), 2104 2105 // each retained page keeps its own arena, freed when the page leaves the 2106 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2107 // long-lived session from accumulating every page it ever visited. 2108 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 2109 2110 // cap on retained back-history so the chain can't grow memory without bound 2111 const max_history: usize = 16; 2112 2113 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2114 const arena = try allocator.create(std.heap.ArenaAllocator); 2115 arena.* = std.heap.ArenaAllocator.init(allocator); 2116 errdefer { 2117 arena.deinit(); 2118 allocator.destroy(arena); 2119 } 2120 2121 session.page_arena = arena; 2122 const route = session.data.current_page; 2123 2124 const page = try arena.allocator().create(Page); 2125 page.* = try Page.init(arena, session, route); 2126 return .{ 2127 .root = try initRoot(allocator, page, session), 2128 .route = route, 2129 .arena = arena, 2130 .history = .empty, 2131 }; 2132 } 2133 2134 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2135 self.root.deinit(allocator); 2136 freeArena(allocator, self.arena); 2137 for (self.history.items) |*entry| { 2138 entry.root.deinit(allocator); 2139 freeArena(allocator, entry.arena); 2140 } 2141 self.history.deinit(allocator); 2142 } 2143 2144 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2145 arena.deinit(); 2146 allocator.destroy(arena); 2147 } 2148 2149 // reconcile the displayed root with the session's navigation state. a 2150 // forward nav (current_page moved to a different parent page) pushes the 2151 // current root and builds the new page in a fresh arena; a back request 2152 // frees the current page and restores the previous one. when escape is 2153 // pressed with no history left we switch to the quit tab instead of quitting. 2154 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2155 // refresh: rebuild the current page in place from a current moment 2156 if (session.refresh_requested) { 2157 session.refresh_requested = false; 2158 if (session.haxy_moment != null or session.local != null) { 2159 const arena = try allocator.create(std.heap.ArenaAllocator); 2160 arena.* = std.heap.ArenaAllocator.init(allocator); 2161 errdefer freeArena(allocator, arena); 2162 2163 session.page_arena = arena; 2164 2165 const route = session.data.current_page; 2166 const page = try arena.allocator().create(Page); 2167 page.* = try Page.init(arena, session, route); 2168 const new_root = try initRoot(allocator, page, session); 2169 2170 self.root.deinit(allocator); 2171 freeArena(allocator, self.arena); 2172 self.root = new_root; 2173 self.route = route; 2174 self.arena = arena; 2175 } 2176 return; 2177 } 2178 2179 if (session.nav_back) { 2180 session.nav_back = false; 2181 if (self.history.pop()) |entry| { 2182 self.root.deinit(allocator); 2183 freeArena(allocator, self.arena); 2184 self.root = entry.root; 2185 self.route = entry.route; 2186 self.arena = entry.arena; 2187 session.page_arena = entry.arena; 2188 session.data.current_page = entry.route; 2189 chooseAnsiArtForNavigation(session); 2190 return; 2191 } 2192 // nothing to go back to; switch to the quit confirmation 2193 const root_focus = self.root.getFocus(); 2194 var iter = root_focus.children.iterator(); 2195 while (iter.next()) |entry| { 2196 switch (entry.value_ptr.focus.kind) { 2197 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2198 root_focus.setFocus(entry.key_ptr.*); 2199 // a Stack only builds its selected child, so the quit 2200 // button isn't in the focus tree until a build runs with 2201 // the quit tab selected. build once, then send a 2202 // synthetic arrow_down to drop focus from the tab onto 2203 // the button so it's ready to confirm. 2204 try self.root.build(allocator, .{ 2205 .min_size = .{ .width = null, .height = 40 }, 2206 .max_size = .{ .width = 80, .height = null }, 2207 }, root_focus); 2208 try self.root.input(allocator, .arrow_down, root_focus); 2209 break; 2210 }, 2211 else => {}, 2212 } 2213 } 2214 return; 2215 } 2216 2217 // forward navigation: navigate() set next_page to the page to move to (a 2218 // cross-page link or tab change crossing pages) 2219 if (session.next_page) |route| { 2220 session.next_page = null; 2221 if (session.haxy_moment == null and session.local == null) return; 2222 // the page we navigated to becomes the current page 2223 session.data.current_page = route; 2224 2225 const arena = try allocator.create(std.heap.ArenaAllocator); 2226 arena.* = std.heap.ArenaAllocator.init(allocator); 2227 errdefer freeArena(allocator, arena); 2228 2229 session.page_arena = arena; 2230 2231 const page = try arena.allocator().create(Page); 2232 page.* = try Page.init(arena, session, route); 2233 const new_root = try initRoot(allocator, page, session); 2234 2235 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 2236 // drop the oldest entry (freeing its widget tree and arena) once over cap 2237 if (self.history.items.len > max_history) { 2238 var oldest = self.history.orderedRemove(0); 2239 oldest.root.deinit(allocator); 2240 freeArena(allocator, oldest.arena); 2241 } 2242 self.root = new_root; 2243 self.route = route; 2244 self.arena = arena; 2245 } 2246 } 2247 }; 2248 2249 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2250 const page_widget: Widget = switch (page.*) { 2251 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2252 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2253 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2254 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2255 }; 2256 2257 chooseAnsiArtForNavigation(session); 2258 2259 // on the TUI/SSH, the page sits above a one-row footer showing the url 2260 var root = if (session.is_terminal) blk: { 2261 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2262 errdefer box.deinit(allocator); 2263 const bg_id = bg_blk: { 2264 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2265 errdefer background.deinit(allocator); 2266 const id = background.getFocus().id; 2267 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2268 break :bg_blk id; 2269 }; 2270 { 2271 var footer = try widget.Footer.init(allocator, session); 2272 errdefer footer.deinit(allocator); 2273 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2274 } 2275 box.getFocus().child_id = bg_id; 2276 break :blk Widget{ .box = box }; 2277 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2278 errdefer root.deinit(allocator); 2279 2280 // input-owning views build their TextInputs in init, so reset their 2281 // registrations here 2282 session.text_inputs.clearRetainingCapacity(); 2283 2284 try root.build(allocator, .{ 2285 .min_size = .{ .width = null, .height = 40 }, 2286 .max_size = .{ .width = 100, .height = null }, 2287 }, root.getFocus()); 2288 2289 return root; 2290 } 2291 2292 // native and server-side sessions choose from the embedded collection. WASM 2293 // keeps the art serialized by the server instead. 2294 fn chooseAnsiArtForNavigation(session: *Session) void { 2295 if (comptime ansi_arts.len == 0) return; 2296 const io = session.io orelse return; 2297 var random: usize = undefined; 2298 io.random(std.mem.asBytes(&random)); 2299 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2300 } 2301