╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1928 else => false, 1929 }, 1930 else => false, 1931 }; 1932 } 1933 1934 // true when `a` and `b` are the same home list tab paginated to a different 1935 // window or search. switching tabs is in-page, so only a changed `start` or 1936 // search on the same tab navigates. 1937 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 1938 return switch (a) { 1939 .home_users => switch (b) { 1940 .home_users => !a.eql(b), 1941 else => false, 1942 }, 1943 .home_user => switch (b) { 1944 .home_user => !a.eql(b), 1945 else => false, 1946 }, 1947 else => false, 1948 }; 1949 } 1950 }; 1951 1952 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 1953 fn isUnreserved(c: u8) bool { 1954 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1955 } 1956 1957 // percent-encode a ref name for use as a single url path segment. 1958 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 1959 var out: std.Io.Writer.Allocating = .init(aa); 1960 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 1961 return out.written(); 1962 } 1963 1964 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 1965 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1966 return struct { 1967 pub const hex_len = hash.hexLen(repo_opts.hash); 1968 1969 // the concrete ref/oid (a null request resolves to the default branch) 1970 ref_or_oid: RoutablePage.RefOrOid, 1971 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 1972 // the route layer — which splits on '/' — stores them encoded). duped 1973 // into `aa`. 1974 value: []const u8, 1975 // the commit oid it points at 1976 oid: [hex_len]u8, 1977 1978 const Self = @This(); 1979 1980 // resolve a requested ref/oid (null = the repo's default branch) to a 1981 // concrete ref/oid plus the commit oid it points at. `requested_value` is 1982 // the url-encoded form (as it appears in the route). null when it doesn't 1983 // resolve (an unknown branch/tag, or a malformed/unknown oid). 1984 pub fn init( 1985 repo: *rp.Repo(repo_kind, repo_opts), 1986 io: std.Io, 1987 aa: std.mem.Allocator, 1988 requested_ref_or_oid: ?RoutablePage.RefOrOid, 1989 requested_value: []const u8, 1990 ) !?Self { 1991 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 1992 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 1993 var value: []const u8 = if (requested_ref_or_oid == null) 1994 requested_value 1995 else 1996 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 1997 // no ref named: fall back to HEAD's branch (or its oid when detached). 1998 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1999 if (requested_ref_or_oid == null) { 2000 if (repo.head(io, &head_buf)) |head| switch (head) { 2001 .ref => |r| { 2002 ref_or_oid = .branch; 2003 value = r.name; 2004 }, 2005 .oid => |o| { 2006 ref_or_oid = .object; 2007 value = o; 2008 }, 2009 } else |_| {} 2010 } 2011 2012 var oid: [hex_len]u8 = undefined; 2013 switch (ref_or_oid) { 2014 .object => { 2015 if (value.len != hex_len) return null; 2016 @memcpy(&oid, value); 2017 }, 2018 .branch, .tag => { 2019 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 2020 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 2021 }, 2022 } 2023 // store url-encoded so the route layer can hold the value verbatim. 2024 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 2025 } 2026 }; 2027 } 2028 2029 // who a repo page is built for, which picks the actions it shows 2030 pub const Viewer = struct { 2031 role: evt.Repo.Role, 2032 email: []const u8, 2033 2034 // the session's viewer of a repo it holds `role` in, or null when logged 2035 // out. local mode owns everything. 2036 pub fn init(session: *Session, arena: *std.heap.ArenaAllocator, role: evt.Repo.Role) !?Viewer { 2037 if (session.data.host_kind == .local) return .{ .role = .owner, .email = "" }; 2038 const user_id = session.userId() orelse return null; 2039 const moment = session.haxy_moment orelse unreachable; 2040 const user = (try activeUser(moment, arena, user_id)) orelse return null; 2041 return .{ .role = role, .email = user.event.email }; 2042 } 2043 }; 2044 2045 // a repo a page shows, and what its viewer may do there 2046 pub const RepoHandle = struct { 2047 location: RoutablePage.RepoLocation, 2048 viewer: ?Viewer = null, 2049 2050 pub fn dupe(self: RepoHandle, allocator: std.mem.Allocator) !RepoHandle { 2051 var copy = self; 2052 copy.location = try self.location.dupe(allocator); 2053 return copy; 2054 } 2055 2056 // pushing, and seeing the events and undo tabs. local mode is always owner. 2057 pub fn canWrite(self: RepoHandle) bool { 2058 const viewer = self.viewer orelse return false; 2059 return viewer.role.atLeast(.write); 2060 } 2061 2062 pub fn canUndo(self: RepoHandle) bool { 2063 const viewer = self.viewer orelse return false; 2064 return viewer.role == .owner; 2065 } 2066 }; 2067 2068 // where a repo page reads its on-disk repo from 2069 pub const RepoSource = struct { 2070 path: []const u8, 2071 repo_kind: rp.RepoKind, 2072 // the user's global git config, so local mode picks up their identity and 2073 // their signing and ssh settings. null on the server paths, which must not 2074 // read whoever runs the server. 2075 global_config_path: ?[]const u8 = null, 2076 2077 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 2078 return .{ .path = self.path, .global_config_path = self.global_config_path }; 2079 } 2080 2081 pub fn hasBranch(self: RepoSource, io: std.Io, allocator: std.mem.Allocator, branch: []const u8) !bool { 2082 if (!xit.ref.validateName(branch)) return false; 2083 return switch (self.repo_kind) { 2084 inline else => |repo_kind| blk: { 2085 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2086 defer any_repo.deinit(io, allocator); 2087 break :blk switch (any_repo) { 2088 inline else => |*repo| (try repo.readRef(io, .{ .kind = .head, .name = branch })) != null, 2089 }; 2090 }, 2091 }; 2092 } 2093 2094 // whether the actor may change the event `id` names 2095 pub fn canModify( 2096 self: RepoSource, 2097 io: std.Io, 2098 allocator: std.mem.Allocator, 2099 actor: Actor, 2100 kind: evt.EventKind, 2101 id: *const [evt.event_id_size]u8, 2102 ) !bool { 2103 // a role that may change an event with no author needs no read 2104 if (actor.role.canModify(actor.author.email, null)) return true; 2105 2106 var arena = std.heap.ArenaAllocator.init(allocator); 2107 defer arena.deinit(); 2108 return switch (self.repo_kind) { 2109 inline else => |repo_kind| blk: { 2110 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2111 defer any_repo.deinit(io, allocator); 2112 break :blk switch (any_repo) { 2113 inline else => |*repo| actor.role.canModify(actor.author.email, try evt.readAuthorEmail(repo_kind, repo.self_repo_opts, io, allocator, &arena, repo, kind, id)), 2114 }; 2115 }, 2116 }; 2117 } 2118 }; 2119 2120 // who a write acts as and the role they hold in its repo 2121 // the thread button that changes the viewer's notifications, named by its label 2122 pub const NotifyAction = enum { subscribe, mute }; 2123 2124 pub const Actor = struct { 2125 author: evt.CommitAuthor, 2126 // local mode has no accounts, so it has no user id 2127 user_id: ?[evt.event_id_size]u8 = null, 2128 role: evt.Repo.Role, 2129 // the repo owner's id, which local mode lacks 2130 repo_user_id: ?[evt.event_id_size]u8 = null, 2131 }; 2132 2133 pub const Authorization = union(enum) { 2134 actor: Actor, 2135 login_required, 2136 repo_not_found, 2137 forbidden, 2138 }; 2139 2140 // the account `user_id` names, or null once it has been removed. a user id is 2141 // checked here wherever one enters, so the role lookups can trust theirs. 2142 pub fn activeUser( 2143 moment: evt.AdminDB.HashMap(.read_only), 2144 arena: *std.heap.ArenaAllocator, 2145 user_id: [evt.event_id_size]u8, 2146 ) !?evt.User.Record { 2147 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 2148 return if (user.removed) null else user; 2149 } 2150 2151 // what the typed assignee resolves to 2152 pub const AssigneeLookup = union(enum) { 2153 email: []const u8, 2154 failure: Session.FormFeedback.AssignmentFailure, 2155 }; 2156 2157 // the email `text` assigns: itself when it holds an @, else the email of the 2158 // user it names. a null moment is local mode, which has no users to look up. 2159 pub fn assigneeEmail(moment_maybe: ?evt.AdminDB.HashMap(.read_only), arena: *std.heap.ArenaAllocator, text: []const u8) !AssigneeLookup { 2160 const trimmed = std.mem.trim(u8, text, " \t\r\n"); 2161 if (std.mem.indexOfScalar(u8, trimmed, '@') != null) return .{ .email = trimmed }; 2162 const moment = moment_maybe orelse return .{ .failure = .not_an_email }; 2163 const user_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, trimmed)) orelse return .{ .failure = .not_found }; 2164 const user = (try activeUser(moment, arena, user_id)) orelse return .{ .failure = .not_found }; 2165 return .{ .email = user.event.email }; 2166 } 2167 2168 // whether the user may write to the repo `identity` names with at least 2169 // `min_role`, and to the `thread_kind` tab when there is one 2170 pub fn authorizeUser( 2171 io: std.Io, 2172 moment: evt.AdminDB.HashMap(.read_only), 2173 arena: *std.heap.ArenaAllocator, 2174 users_dir: []const u8, 2175 user_id: [evt.event_id_size]u8, 2176 identity: []const u8, 2177 min_role: evt.Repo.Role, 2178 thread_kind: ?evt.EventKind, 2179 ) !Authorization { 2180 const user = (try activeUser(moment, arena, user_id)) orelse return .login_required; 2181 2182 const owner_repo = evt.parseOwnerRepoPath(identity) orelse return .repo_not_found; 2183 const repo = (try evt.readRepoByOwnerAndName(io, arena.child_allocator, arena, moment, users_dir, owner_repo.owner, owner_repo.name, user_id)) orelse return .repo_not_found; 2184 // a repo the user can't read doesn't exist to them 2185 const role = repo.role orelse return .repo_not_found; 2186 if (!role.atLeast(min_role)) return .forbidden; 2187 if (thread_kind) |kind| { 2188 // a tab that is off doesn't exist 2189 const tab_role = repo.repo.event.threadRole(kind) orelse return .repo_not_found; 2190 if (!role.atLeast(tab_role)) return .forbidden; 2191 } 2192 return .{ .actor = .{ 2193 .author = .{ .name = user.event.name, .email = user.event.email }, 2194 .user_id = user_id, 2195 .role = role, 2196 .repo_user_id = try evt.parseEventId(&repo.repo.event.user_id), 2197 } }; 2198 } 2199 2200 // events created in local mode have no account behind them, so the commit 2201 // author comes from the repo's config, which the global config feeds into. 2202 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 2203 2204 pub fn localAuthor( 2205 src: RepoSource, 2206 io: std.Io, 2207 allocator: std.mem.Allocator, 2208 arena: *std.heap.ArenaAllocator, 2209 ) !evt.CommitAuthor { 2210 switch (src.repo_kind) { 2211 inline else => |repo_kind| { 2212 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 2213 defer any_repo.deinit(io, allocator); 2214 2215 switch (any_repo) { 2216 inline else => |*repo| { 2217 var config = try repo.listConfig(io, allocator); 2218 defer config.deinit(); 2219 2220 const user = config.sections.get("user") orelse return local_author_fallback; 2221 const name = user.get("name") orelse return local_author_fallback; 2222 const email = user.get("email") orelse return local_author_fallback; 2223 return .{ 2224 .name = try arena.allocator().dupe(u8, name), 2225 .email = try arena.allocator().dupe(u8, email), 2226 }; 2227 }, 2228 } 2229 }, 2230 } 2231 } 2232 2233 // per-connection mutable state. each SSH session / web session / local TUI 2234 // run gets its own. 2235 pub const Session = struct { 2236 data: Data = .{}, 2237 // session-lifetime allocations: login/user_id, persisted prefs, queued 2238 // actions. lives as long as the connection. 2239 arena: *std.heap.ArenaAllocator, 2240 // current page's allocations: page data and the page-scoped strings widgets 2241 // build (form actions, links). owned by Nav, swapped on each navigation, so 2242 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 2243 // where a render is one-shot, this points at the same arena as `arena`. 2244 page_arena: *std.heap.ArenaAllocator, 2245 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2246 // filesystem io and the path to <server>/repos, for opening on-disk repos 2247 // during page construction. both null on wasm, which has no filesystem and 2248 // rebuilds pages from the serialized snapshot rather than from disk. 2249 io: ?std.Io = null, 2250 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2251 users_dir: ?[]const u8 = null, 2252 // the notify worker's queue, null where no worker runs 2253 dirty_repos: ?*notify.DirtyRepos = null, 2254 // the single on-disk repo this session views, when running in local mode 2255 // (haxy invoked with no arguments inside a repo). null on the server paths, 2256 // which resolve repos from the admin db instead. 2257 local: ?RepoSource = null, 2258 // focus id -> the live TextInput, refreshed each frame by the views that own 2259 // inputs. web/wasm form handling looks widgets up here by focus id. 2260 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2261 back: enum { unavailable, available, requested } = .unavailable, 2262 refresh_requested: bool = false, // set by input (ctrl+r) 2263 // a requested forward navigation. set this (via navigate) to move to a new 2264 // page; Nav.sync builds it and then copies it into current_page, clearing 2265 // this back to null. setting current_page directly only updates the url and 2266 // does not navigate. 2267 next_page: ?RoutablePage = null, 2268 is_terminal: bool = false, // true on remote SSH and local TUI 2269 color: bool = true, // false when NO_COLOR is set, which also hides the art 2270 // the terminal's reported default background, which the art blends toward 2271 terminal_background: ?Grid.Color.Rgb = null, 2272 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 2273 // url. null on the web itself (no footer there). 2274 web_port: ?u16 = null, 2275 // a host operation requested by a widget 2276 host_request: ?HostRequest = null, 2277 quit_requested: bool = false, 2278 2279 pub const HostRequest = union(enum) { 2280 show_copyable_text: []const u8, 2281 sync_events, 2282 undo: RoutablePage.RepoUndoRoute, 2283 }; 2284 2285 pub const FormFeedback = union(enum) { 2286 pub const LoginFailure = enum { unknown_user, wrong_password }; 2287 pub const ThreadFailure = enum { required_title }; 2288 pub const PatchFailure = enum { 2289 required_title, 2290 invalid_target_branch, 2291 invalid_source_branch, 2292 same_branch, 2293 unrelated_branches, 2294 2295 pub fn fromError(err: anyerror) ?PatchFailure { 2296 return switch (err) { 2297 error.InvalidTargetBranch => .invalid_target_branch, 2298 error.InvalidSourceBranch => .invalid_source_branch, 2299 error.SameBranch => .same_branch, 2300 error.UnrelatedBranches => .unrelated_branches, 2301 else => null, 2302 }; 2303 } 2304 }; 2305 2306 pub const RepoFailure = enum { 2307 required_name, 2308 invalid_name, 2309 name_taken, 2310 2311 pub fn fromError(err: anyerror) ?RepoFailure { 2312 return switch (err) { 2313 error.NameEmpty => .required_name, 2314 error.NameTooLong, error.InvalidName => .invalid_name, 2315 error.NameTaken => .name_taken, 2316 else => null, 2317 }; 2318 } 2319 }; 2320 2321 pub const RolesFailure = enum { not_found, already_added }; 2322 2323 pub const AssignmentFailure = enum { not_found, not_an_email, already_assigned }; 2324 2325 pub const KeyFailure = enum { 2326 invalid, 2327 unsupported, 2328 already_added, 2329 2330 pub fn fromError(err: anyerror) ?KeyFailure { 2331 return switch (err) { 2332 error.InvalidKey => .invalid, 2333 error.UnsupportedKey => .unsupported, 2334 error.KeyAdded => .already_added, 2335 else => null, 2336 }; 2337 } 2338 }; 2339 2340 pub const UserFailure = enum { 2341 required_name, 2342 invalid_name, 2343 name_taken, 2344 required_email, 2345 email_taken, 2346 required_password, 2347 password_mismatch, 2348 wrong_password, 2349 2350 pub fn fromError(err: anyerror) ?UserFailure { 2351 return switch (err) { 2352 error.NameEmpty => .required_name, 2353 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2354 error.NameTaken => .name_taken, 2355 error.EmailEmpty => .required_email, 2356 error.EmailTaken => .email_taken, 2357 error.PasswordEmpty => .required_password, 2358 error.PasswordMismatch => .password_mismatch, 2359 error.WrongPassword => .wrong_password, 2360 else => null, 2361 }; 2362 } 2363 }; 2364 2365 login: struct { 2366 failure: LoginFailure, 2367 username: []const u8, 2368 }, 2369 user: struct { 2370 failure: UserFailure, 2371 // passwords are never retained 2372 fields: struct { 2373 name: []const u8, 2374 email: []const u8, 2375 }, 2376 }, 2377 user_settings: struct { 2378 failure: UserFailure, 2379 // passwords are never retained 2380 fields: struct { email: []const u8 }, 2381 }, 2382 user_keys: struct { 2383 failure: KeyFailure, 2384 key: []const u8, 2385 }, 2386 repo: struct { 2387 failure: RepoFailure, 2388 fields: struct { 2389 name: []const u8, 2390 description: []const u8, 2391 hash: hash.HashKind, 2392 access: evt.Repo.Access, 2393 }, 2394 }, 2395 repo_settings: struct { 2396 failure: RepoFailure, 2397 fields: struct { 2398 name: []const u8, 2399 description: []const u8, 2400 access: evt.Repo.Access, 2401 discuss_role: ?evt.Repo.Role, 2402 issue_role: ?evt.Repo.Role, 2403 patch_role: ?evt.Repo.Role, 2404 }, 2405 }, 2406 repo_roles: struct { 2407 failure: RolesFailure, 2408 name: []const u8, 2409 }, 2410 assignment: struct { 2411 failure: AssignmentFailure, 2412 text: []const u8, 2413 }, 2414 issue: struct { 2415 failure: ThreadFailure, 2416 fields: ?struct { 2417 title: []const u8, 2418 labels: []const u8, 2419 description: []const u8, 2420 } = null, 2421 }, 2422 patch: struct { 2423 failure: PatchFailure, 2424 fields: ?struct { 2425 title: []const u8, 2426 labels: []const u8, 2427 description: []const u8, 2428 target_branch: []const u8, 2429 source_branch: []const u8 = "", 2430 source_kind: Repo.Patches.Source.Kind = .fork, 2431 } = null, 2432 }, 2433 discussion: struct { 2434 failure: ThreadFailure, 2435 fields: ?struct { 2436 title: []const u8, 2437 labels: []const u8, 2438 description: []const u8, 2439 } = null, 2440 }, 2441 }; 2442 2443 const Self = @This(); 2444 2445 // serializable data sent down to web client 2446 pub const Data = struct { 2447 // the server's reference time for relative timestamps on this page. 2448 now: i64 = 0, 2449 user_id: ?[]const u8 = null, 2450 // the logged-in user's name and email, for the views that show them 2451 user_name: ?[]const u8 = null, 2452 user_email: ?[]const u8 = null, 2453 // the logged-in user's unread notifications, refreshed on each page build 2454 unread_notifs: u64 = 0, 2455 // a failed form retained long enough to render it for correction 2456 form_feedback: ?FormFeedback = null, 2457 // a transient local event-sync error 2458 sync_failure: ?[]const u8 = null, 2459 // a failed terminal undo retained on the current tab 2460 undo_failure: ?[]const u8 = null, 2461 current_page: RoutablePage = .default, 2462 // the selected ANSI art. the server serializes one image for WASM so 2463 // the browser does not need the whole build-generated collection. 2464 ansi_art: []const u8 = "", 2465 // the bound git-service ports. absent in local mode, where remote urls 2466 // are not shown. 2467 git_http_port: ?u16 = null, 2468 git_ssh_port: ?u16 = null, 2469 git_ssh_prefix: []const u8 = "", 2470 // whether this session views a local repo or the server. unlike `local` 2471 // (the host-side filesystem source) this travels in the snapshot, so 2472 // the wasm side also parses elided link urls and hides the multi-user 2473 // chrome. 2474 host_kind: evt.HostKind = .server, 2475 }; 2476 2477 pub fn init( 2478 arena: *std.heap.ArenaAllocator, 2479 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2480 data: Data, 2481 ) !Self { 2482 var session = Self{ 2483 .data = data, 2484 .arena = arena, 2485 // until a host swaps in a page-scoped arena (Nav does this), page 2486 // allocations land in the session arena. on the web path that's the 2487 // intended behavior, since the whole arena is per-request. 2488 .page_arena = arena, 2489 .admin_repo = repo, 2490 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2491 }; 2492 try session.loadUser(); 2493 return session; 2494 } 2495 2496 // web views share the page's reference time; terminals use the live clock. 2497 pub fn nowSeconds(self: *const Self) !i64 { 2498 if (builtin.target.cpu.arch == .wasm32 or !self.is_terminal) return self.data.now; 2499 const io = self.io orelse return error.NoClock; 2500 return std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse error.TimestampOutOfRange; 2501 } 2502 2503 // load the logged-in user's name and persisted preferences from the db 2504 pub fn loadUser(self: *Self) !void { 2505 const user_id = self.userId() orelse return; 2506 const moment = self.haxy_moment orelse return; 2507 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2508 self.data.user_name = user.event.name; 2509 self.data.user_email = user.event.email; 2510 } 2511 2512 // forget the logged-in user, on a logout or once their account is removed 2513 pub fn logOut(self: *Self) void { 2514 self.data.user_id = null; 2515 self.data.user_name = null; 2516 self.data.user_email = null; 2517 } 2518 2519 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2520 const bytes = self.data.user_id orelse return null; 2521 if (bytes.len != evt.event_id_size) return null; 2522 var id: [evt.event_id_size]u8 = undefined; 2523 @memcpy(&id, bytes); 2524 return id; 2525 } 2526 2527 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2528 const feedback = self.data.form_feedback orelse return null; 2529 if (std.meta.activeTag(feedback) != tag) return null; 2530 return @field(feedback, @tagName(tag)); 2531 } 2532 2533 pub fn clearFormFeedback(self: *Self) void { 2534 self.data.form_feedback = null; 2535 } 2536 2537 // the actor for a write to the repo `identity` names, or null when the 2538 // session may not write there with at least `min_role` or in the 2539 // `thread_kind` tab. local mode always writes. 2540 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2541 if (self.data.host_kind == .local) { 2542 const author = blk: { 2543 const src = self.local orelse break :blk local_author_fallback; 2544 const io = self.io orelse break :blk local_author_fallback; 2545 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2546 }; 2547 return .{ .author = author, .role = .owner }; 2548 } 2549 const user_id = self.userId() orelse return null; 2550 // the session's moment predates this input, so read the roles afresh 2551 const admin_repo = self.admin_repo orelse return null; 2552 const io = self.io orelse return null; 2553 const users_dir = self.users_dir orelse return null; 2554 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2555 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2556 .actor => |actor| actor, 2557 .login_required, .repo_not_found, .forbidden => null, 2558 }; 2559 } 2560 2561 // where this session's event writes go. a server session always has a users dir and an admin repo 2562 pub fn eventHost(self: *const Self) evt.Host { 2563 return switch (self.data.host_kind) { 2564 .local => .local, 2565 .server => .{ .server = .{ 2566 .users_dir = self.users_dir orelse unreachable, 2567 .dirty_repos = self.dirty_repos, 2568 .admin_repo_path = (self.admin_repo orelse unreachable).core.work_path, 2569 } }, 2570 }; 2571 } 2572 2573 // reload the moment from the admin repo and log out a removed user 2574 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2575 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2576 self.haxy_moment = moment; 2577 2578 const user_id = self.userId() orelse return; 2579 var arena = std.heap.ArenaAllocator.init(allocator); 2580 defer arena.deinit(); 2581 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2582 } 2583 2584 // request a forward navigation to `route`; the host consumes next_page 2585 // (Nav.sync on the terminal, the wasm tick on the web). 2586 pub fn navigate(self: *Session, route: RoutablePage) !void { 2587 self.clearFormFeedback(); 2588 self.next_page = route; 2589 } 2590 }; 2591 2592 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2593 var nav = try Nav.init(allocator, session); 2594 defer nav.deinit(allocator); 2595 2596 var terminal = try term.Terminal.init(io, allocator); 2597 terminal.render_state.no_color = !session.color; 2598 var terminal_live = true; 2599 defer if (terminal_live) terminal.deinit(io); 2600 2601 // set term as active so it will be properly cooked 2602 // when a panic/segfault happens 2603 term.setActive(&terminal); 2604 defer term.setActive(null); 2605 2606 try terminal.queryBackground(); 2607 2608 while (!terminal.shouldQuit()) { 2609 const grid_changed = try terminal.render(&nav.root); 2610 2611 // process any inputs. 2612 // 2613 // if the grid didn't change, then first do a blocking 2614 // read, so the thread will sleep until further input. 2615 // after that, all remaining reads are non-blocking so 2616 // we can process the rest of the queued inputs. 2617 // 2618 // if the grid *did* change, then only do non-blocking 2619 // reads. we do not want to sleep the thread because 2620 // there may be an animation that requires more looping. 2621 var blocking = !grid_changed; 2622 while (try terminal.readKey(io, blocking)) |key| { 2623 blocking = false; 2624 try inputKey(allocator, &nav.root, key, session); 2625 } 2626 2627 if (session.host_request) |request| { 2628 session.host_request = null; 2629 switch (request) { 2630 .show_copyable_text => |copyable_text| { 2631 term.setActive(null); 2632 terminal.deinit(io); 2633 terminal_live = false; 2634 showCopyableText(io, copyable_text) catch |show_err| { 2635 terminal = try term.Terminal.init(io, allocator); 2636 terminal_live = true; 2637 term.setActive(&terminal); 2638 return show_err; 2639 }; 2640 terminal = try term.Terminal.init(io, allocator); 2641 terminal.render_state.no_color = !session.color; 2642 terminal_live = true; 2643 term.setActive(&terminal); 2644 }, 2645 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2646 .sync_events => { 2647 try nav.root.build(allocator, .{ 2648 .min_size = .{ .width = null, .height = null }, 2649 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2650 }, nav.root.getFocus()); 2651 _ = try terminal.render(&nav.root); 2652 try Repo.Events.performSync(allocator, session); 2653 }, 2654 } 2655 } 2656 2657 // reload so the next navigation builds its page from the current moment 2658 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2659 2660 // reconcile navigation: forward to a new page, or back on escape. 2661 // the terminal background can change at any time, so recheck it on each page 2662 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2663 2664 // the quit button (on the quit tab) asks the host to tear down. 2665 if (session.quit_requested) terminal.requestQuit(); 2666 2667 try nav.root.build(allocator, .{ 2668 .min_size = .{ .width = null, .height = null }, 2669 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2670 }, nav.root.getFocus()); 2671 } 2672 } 2673 2674 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2675 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2676 null 2677 else 2678 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2679 defer if (tty) |file| file.close(io); 2680 2681 const input = if (tty) |file| file else std.Io.File.stdin(); 2682 const output = if (tty) |file| file else std.Io.File.stdout(); 2683 2684 var write_buf: [1024]u8 = undefined; 2685 var writer = output.writer(io, &write_buf); 2686 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}); 2687 try writer.interface.flush(); 2688 2689 var read_buf: [1]u8 = undefined; 2690 var reader = input.reader(io, &read_buf); 2691 while (true) { 2692 const byte = try reader.interface.takeByte(); 2693 if (byte == '\r' or byte == '\n') return; 2694 } 2695 } 2696 2697 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2698 const root_focus = root.getFocus(); 2699 const focused_before = root_focus.grandchild_id; 2700 var activate_in_page_link = false; 2701 switch (key) { 2702 // request a navigation pop; the host's Nav.sync goes back a page, or 2703 // quits when there's no history left. 2704 .escape => { 2705 session.back = .requested; 2706 return; 2707 }, 2708 .ctrl => |letter| switch (letter) { 2709 'r' => { 2710 session.refresh_requested = true; 2711 return; 2712 }, 2713 else => try root.input(allocator, key, root_focus), 2714 }, 2715 .enter => { 2716 if (root_focus.grandchild_id) |gid| { 2717 // follow a cross-page link 2718 if (crossPageLink(root_focus, gid, session.data)) |route| { 2719 return session.navigate(route); 2720 } 2721 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2722 } 2723 activate_in_page_link = true; 2724 try root.input(allocator, key, root_focus); 2725 }, 2726 .mouse => |mouse| { 2727 if (mouse.button == .left) { 2728 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2729 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2730 const focus_id = hit.id; 2731 if (hit.kind == .background) { 2732 root_focus.setFocus(focus_id); 2733 return; 2734 } 2735 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2736 if (session.back == .available) session.back = .requested; 2737 return; 2738 } 2739 // follow a cross-page link 2740 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2741 return session.navigate(route); 2742 } 2743 if (currentPageLink(root_focus, focus_id, session.data)) return; 2744 if (rawLink(root_focus, focus_id)) |url| { 2745 if (!mouse.ctrl) try requestRawLink(session, url); 2746 return; 2747 } 2748 root_focus.setFocus(focus_id); 2749 activate_in_page_link = true; 2750 } 2751 // forward the press into the widget tree so buttons (and any 2752 // future click-aware widgets) can react. widgets that don't 2753 // care about presses ignore it. 2754 try root.input(allocator, key, root_focus); 2755 } else { 2756 try root.input(allocator, key, root_focus); 2757 } 2758 }, 2759 .event => |event| switch (event) { 2760 .background => |rgb| session.terminal_background = rgb, 2761 .resize => try root.input(allocator, key, root_focus), 2762 }, 2763 // a scroll tick goes to the pane under the pointer, focusing it first. 2764 // from outside any pane (the tabs, a sub-header) or from a text input 2765 // it moves like the arrows instead, so scrolling up from a search box 2766 // reaches the header and stops there. 2767 .scroll_up, .scroll_down => |position| { 2768 if (focusedPane(root_focus)) |pane| if (scrollUnder(root_focus, position)) |under| { 2769 if (under != pane) root_focus.setFocus(under); 2770 }; 2771 try root.input(allocator, key, root_focus); 2772 }, 2773 else => try root.input(allocator, key, root_focus), 2774 } 2775 2776 const focused_after = root_focus.grandchild_id; 2777 if (!activate_in_page_link and focused_before == focused_after) return; 2778 const focus_id = focused_after orelse return; 2779 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2780 } 2781 2782 // the innermost vertically scrolling widget laid out under `position` 2783 fn scrollUnder(root_focus: *const Focus, position: xitui.input.Position) ?usize { 2784 var found: ?usize = null; 2785 var found_area: usize = std.math.maxInt(usize); 2786 var iter = root_focus.children.iterator(); 2787 while (iter.next()) |entry| { 2788 const info = entry.value_ptr.focus.scroll orelse continue; 2789 if (info.direction == .horiz) continue; 2790 const r = entry.value_ptr.rect; 2791 if (position.x < r.x or position.y < r.y or position.x >= r.x + r.size.width or position.y >= r.y + r.size.height) continue; 2792 // a nested scroll lies within its parent, so the smallest is innermost 2793 const area = r.size.width * r.size.height; 2794 if (area < found_area) { 2795 found = entry.key_ptr.*; 2796 found_area = area; 2797 } 2798 } 2799 return found; 2800 } 2801 2802 // the innermost vertically scrolling widget the focus lies in, unless the 2803 // focused widget is a text input 2804 fn focusedPane(root_focus: *const Focus) ?usize { 2805 var current = root_focus.grandchild_id orelse return null; 2806 switch ((root_focus.children.get(current) orelse return null).focus.kind) { 2807 .text_input, .text_input_password, .text_area => return null, 2808 else => {}, 2809 } 2810 while (root_focus.children.get(current)) |child| { 2811 if (child.focus.scroll) |info| if (info.direction != .horiz) return current; 2812 current = child.parent_id; 2813 } 2814 return null; 2815 } 2816 2817 // a link to bytes the server serves directly rather than to a page route, so 2818 // it never resolves to a RoutablePage 2819 pub const raw_link_prefix = "ax:"; 2820 2821 // a route already loaded into the current page; focusing it changes the url 2822 // without rebuilding the page 2823 pub const in_page_link_prefix = "ai:"; 2824 2825 // an in-page tab's base route, or the exact current route when it is selected 2826 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2827 const target = if (selected) session.data.current_page else route; 2828 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2829 } 2830 2831 // a button the web renderer covers with a file picker that posts the chosen 2832 // file to the url after the prefix 2833 pub const file_input_prefix = "file:"; 2834 2835 // a submit button that overrides its enclosing form's action 2836 pub const submit_action_prefix = "submit:"; 2837 2838 // one option of a radio field, as `radio:<name>=<value>` 2839 pub const radio_prefix = "radio:"; 2840 2841 // the url an `ax:` link points at, or null for anything else. a host that 2842 // suppresses the anchor's own navigation needs this to follow the link. 2843 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2844 const child = root_focus.children.get(focus_id) orelse return null; 2845 const custom = switch (child.focus.kind) { 2846 .custom => |c| c, 2847 else => return null, 2848 }; 2849 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2850 return custom[raw_link_prefix.len..]; 2851 } 2852 2853 fn requestRawLink(session: *Session, url: []const u8) !void { 2854 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2855 } 2856 2857 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2858 // an absolute url is already complete 2859 if (!std.mem.startsWith(u8, path, "/")) return path; 2860 return if (session.web_port) |port| 2861 try allocator.print("http://localhost:{d}{s}", .{ port, path }) 2862 else 2863 path; 2864 } 2865 2866 // if the focus target at focus_id is an `a:` link that should navigate (a 2867 // different parent page, or a different files directory within the repo page), 2868 // return its route; otherwise null. lets a host turn a click / enter on such a 2869 // link into a navigation rather than a focus change. 2870 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2871 const current = data.current_page; 2872 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2873 // a link to a different parent page always navigates; within a page, a 2874 // files-directory / commits-page / list-window change navigates while tab 2875 // links stay in-page. 2876 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; 2877 return null; 2878 } 2879 2880 // the page the clicked cell links to, from a link inside a text box's content 2881 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 2882 const grid = root.getGrid() orelse return null; 2883 const cell = grid.cell(x, y) catch return null; 2884 const link = cell.link orelse return null; 2885 if (link.len == 0 or link[0] != '/') return null; 2886 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 2887 } 2888 2889 // whether the `a:` focus target links to the page already shown, which a click 2890 // leaves alone rather than focusing 2891 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 2892 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 2893 return route.eql(data.current_page); 2894 } 2895 2896 // the route carried by an `ai:` focus target, or null for any other target 2897 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2898 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2899 } 2900 2901 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2902 const child = root_focus.children.get(focus_id) orelse return null; 2903 const custom = switch (child.focus.kind) { 2904 .custom => |c| c, 2905 else => return null, 2906 }; 2907 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2908 const path = custom[prefix.len..]; 2909 // local sessions build (and parse) links with the repo identity elided 2910 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2911 } 2912 2913 // an assignee as the detail view shows it: the stored email, and the name of 2914 // the user holding it on this instance when there is one 2915 pub const Assignee = struct { 2916 email: []const u8, 2917 name: ?[]const u8 = null, 2918 2919 pub fn display(self: Assignee) []const u8 { 2920 return self.name orelse self.email; 2921 } 2922 }; 2923 2924 // a display author, resolved against the admin db at read time 2925 pub const Author = union(enum) { 2926 unknown, 2927 email: []const u8, // an email no user matches 2928 user_name: []const u8, 2929 2930 // the commit author line's email, resolved like initFromEmail 2931 pub fn init( 2932 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2933 arena: *std.heap.ArenaAllocator, 2934 author_line: []const u8, 2935 ) !Author { 2936 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2937 } 2938 2939 // from a record's stored author email: it resolves to the user currently 2940 // holding it, else stays the email. the result is allocated in `arena`, 2941 // so the email may borrow transient memory. 2942 pub fn initFromEmail( 2943 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2944 arena: *std.heap.ArenaAllocator, 2945 author_email: ?[]const u8, 2946 ) !Author { 2947 const email = author_email orelse return .unknown; 2948 if (haxy_moment) |moment| { 2949 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2950 return .{ .user_name = user.name }; 2951 } 2952 } 2953 return .{ .email = try arena.allocator().dupe(u8, email) }; 2954 } 2955 }; 2956 2957 // the "a:" link to user `name`'s page. 2958 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2959 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2960 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2961 return page_arena.allocator().print("a:{s}", .{url}); 2962 } 2963 2964 // a focusable " author " box showing `author`, linking to their user page 2965 // when it is a known user 2966 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2967 const text = switch (author) { 2968 .unknown => "", 2969 .email, .user_name => |t| t, 2970 }; 2971 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 2972 errdefer tb.deinit(allocator); 2973 tb.getFocus().mode = .all; 2974 switch (author) { 2975 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2976 else => {}, 2977 } 2978 return tb; 2979 } 2980 2981 // native-TUI navigation 2982 pub const Nav = struct { 2983 root: Widget, 2984 // backs the current page (its Page data and the page-scoped strings its 2985 // widgets build). owned here, swapped on each navigation. session.page_arena 2986 // tracks whichever of these is current so widgets allocate into it. 2987 arena: *std.heap.ArenaAllocator, 2988 // the login the current root was built for 2989 user_id: ?[evt.event_id_size]u8, 2990 history: std.ArrayList(Entry), 2991 2992 // each retained page keeps its own arena, freed when the page leaves the 2993 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2994 // long-lived session from accumulating every page it ever visited. 2995 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 2996 2997 // cap on retained back-history so the chain can't grow memory without bound 2998 const max_history: usize = 16; 2999 3000 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 3001 session.back = .unavailable; 3002 const arena = try allocator.create(std.heap.ArenaAllocator); 3003 arena.* = std.heap.ArenaAllocator.init(allocator); 3004 errdefer { 3005 arena.deinit(); 3006 allocator.destroy(arena); 3007 } 3008 3009 return .{ 3010 .root = try initCurrentRoot(allocator, arena, session), 3011 .arena = arena, 3012 .user_id = session.userId(), 3013 .history = .empty, 3014 }; 3015 } 3016 3017 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 3018 self.root.deinit(allocator); 3019 freeArena(allocator, self.arena); 3020 for (self.history.items) |*entry| { 3021 entry.root.deinit(allocator); 3022 freeArena(allocator, entry.arena); 3023 } 3024 self.history.deinit(allocator); 3025 } 3026 3027 // rebuild the current page in place from a current moment 3028 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 3029 if (session.haxy_moment == null and session.local == null) return; 3030 const arena = try allocator.create(std.heap.ArenaAllocator); 3031 arena.* = std.heap.ArenaAllocator.init(allocator); 3032 errdefer freeArena(allocator, arena); 3033 3034 const new_root = try initCurrentRoot(allocator, arena, session); 3035 3036 self.root.deinit(allocator); 3037 freeArena(allocator, self.arena); 3038 self.root = new_root; 3039 self.arena = arena; 3040 self.user_id = session.userId(); 3041 } 3042 3043 // build the current page's root in `arena`, or the not-found page's when 3044 // the route names nothing 3045 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 3046 session.page_arena = arena; 3047 const page = try arena.allocator().create(Page); 3048 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 3049 error.NotFound => blk: { 3050 session.data.current_page = .not_found; 3051 break :blk .not_found; 3052 }, 3053 else => |e| return e, 3054 }; 3055 return initRoot(allocator, page, session); 3056 } 3057 3058 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 3059 arena.deinit(); 3060 allocator.destroy(arena); 3061 } 3062 3063 // reconcile the displayed root with the session's navigation state. a 3064 // forward nav (current_page moved to a different parent page) pushes the 3065 // current root and builds the new page in a fresh arena; a back request 3066 // frees the current page and restores the previous one. when escape is 3067 // pressed with no history left we switch to the quit tab instead of quitting. 3068 // returns whether the root was replaced. 3069 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 3070 // refresh: rebuild the current page in place from a current moment 3071 if (session.refresh_requested) { 3072 session.refresh_requested = false; 3073 try self.rebuild(allocator, session); 3074 return true; 3075 } 3076 3077 if (session.back == .requested) { 3078 if (self.history.pop()) |entry| { 3079 session.back = if (self.history.items.len == 0) .unavailable else .available; 3080 self.root.deinit(allocator); 3081 freeArena(allocator, self.arena); 3082 self.root = entry.root; 3083 self.arena = entry.arena; 3084 self.user_id = entry.user_id; 3085 session.page_arena = entry.arena; 3086 session.data.current_page = entry.route; 3087 // a page built under another login is rebuilt rather than restored 3088 if (!std.meta.eql(entry.user_id, session.userId())) { 3089 try self.rebuild(allocator, session); 3090 return true; 3091 } 3092 chooseAnsiArtForNavigation(session); 3093 return true; 3094 } 3095 session.back = .unavailable; 3096 // nothing to go back to; switch to the quit confirmation 3097 const root_focus = self.root.getFocus(); 3098 var iter = root_focus.children.iterator(); 3099 while (iter.next()) |entry| { 3100 switch (entry.value_ptr.focus.kind) { 3101 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 3102 root_focus.setFocus(entry.key_ptr.*); 3103 // a Stack only builds its selected child, so the quit 3104 // button isn't in the focus tree until a build runs with 3105 // the quit tab selected. build once, then send a 3106 // synthetic arrow_down to drop focus from the tab onto 3107 // the button so it's ready to confirm. 3108 try self.root.build(allocator, .{ 3109 .min_size = .{ .width = null, .height = 40 }, 3110 .max_size = .{ .width = 80, .height = null }, 3111 }, root_focus); 3112 try self.root.input(allocator, .arrow_down, root_focus); 3113 break; 3114 }, 3115 else => {}, 3116 } 3117 } 3118 return false; 3119 } 3120 3121 // forward navigation: navigate() set next_page to the page to move to (a 3122 // cross-page link or tab change crossing pages) 3123 if (session.next_page) |route| { 3124 session.next_page = null; 3125 if (session.haxy_moment == null and session.local == null) return false; 3126 const previous_route = session.data.current_page; 3127 // the page we navigated to becomes the current page 3128 session.data.current_page = route; 3129 session.back = .available; 3130 3131 const arena = try allocator.create(std.heap.ArenaAllocator); 3132 arena.* = std.heap.ArenaAllocator.init(allocator); 3133 errdefer freeArena(allocator, arena); 3134 3135 const new_root = try initCurrentRoot(allocator, arena, session); 3136 3137 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 3138 // drop the oldest entry (freeing its widget tree and arena) once over cap 3139 if (self.history.items.len > max_history) { 3140 var oldest = self.history.orderedRemove(0); 3141 oldest.root.deinit(allocator); 3142 freeArena(allocator, oldest.arena); 3143 } 3144 self.root = new_root; 3145 self.arena = arena; 3146 self.user_id = session.userId(); 3147 return true; 3148 } 3149 return false; 3150 } 3151 }; 3152 3153 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3154 const page_widget: Widget = switch (page.*) { 3155 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3156 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3157 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3158 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3159 .not_found => .{ .not_found = try .init(allocator, session) }, 3160 }; 3161 3162 chooseAnsiArtForNavigation(session); 3163 3164 // on the TUI/SSH, the page sits above a one-row footer showing its web 3165 // url, when there's a web UI to point at 3166 var root = if (session.is_terminal) blk: { 3167 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3168 errdefer box.deinit(allocator); 3169 const bg_id = bg_blk: { 3170 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3171 errdefer background.deinit(allocator); 3172 const id = background.getFocus().id; 3173 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3174 break :bg_blk id; 3175 }; 3176 if (session.web_port != null) { 3177 var footer = try widget.Footer.init(allocator, session); 3178 errdefer footer.deinit(allocator); 3179 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3180 } 3181 box.getFocus().child_id = bg_id; 3182 break :blk Widget{ .box = box }; 3183 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3184 errdefer root.deinit(allocator); 3185 3186 // input-owning views build their TextInputs in init, so reset their 3187 // registrations here 3188 session.text_inputs.clearRetainingCapacity(); 3189 3190 try root.build(allocator, .{ 3191 .min_size = .{ .width = null, .height = 40 }, 3192 .max_size = .{ .width = 100, .height = null }, 3193 }, root.getFocus()); 3194 3195 return root; 3196 } 3197 3198 // native and server-side sessions choose from the embedded collection. WASM 3199 // keeps the art serialized by the server instead. 3200 fn chooseAnsiArtForNavigation(session: *Session) void { 3201 if (comptime ansi_art.art.len == 0) return; 3202 if (session.data.current_page == .not_found) { 3203 session.data.ansi_art = ansi_art.not_found; 3204 return; 3205 } 3206 const io = session.io orelse return; 3207 var random: usize = undefined; 3208 io.random(std.mem.asBytes(&random)); 3209 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3210 } 3211