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