╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1036 return null; // unknown sub-path 1037 } 1038 // "fork/<username>/<reponame>/patch:<id>[/files|/commits]"; the 1039 // patch branch is implicit, while object ids and view-specific params 1040 // use the same tails as the repo files and commits routes. 1041 if (std.mem.eql(u8, first, "fork")) { 1042 const rest = segments.rest(); 1043 const owner = segments.next() orelse return null; 1044 const repo_name = segments.next() orelse return null; 1045 if (owner.len == 0 or repo_name.len == 0) return null; 1046 const identity = rest[0 .. owner.len + 1 + repo_name.len]; 1047 const patch = segments.next() orelse return null; 1048 if (!std.mem.startsWith(u8, patch, patch_seg)) return null; 1049 const id = patch[patch_seg.len..]; 1050 if (id.len != evt.event_id_size * 2) return null; 1051 const tab = segments.next() orelse return forkPatchRoute(identity, id); 1052 var params = Params{}; 1053 if (std.mem.eql(u8, tab, "diff")) { 1054 params.scanPairs(&segments) catch return null; 1055 if (!params.only(&.{.start})) return null; 1056 return forkDiffRoute(identity, id, params.start() orelse return null, pathValue(segments.rest()) orelse return null); 1057 } 1058 if (std.mem.eql(u8, tab, files_seg)) { 1059 params.scanPairs(&segments) catch return null; 1060 if (!params.only(&.{ .line, .object })) return null; 1061 const line = params.line() orelse return null; 1062 const ref = params.ref() catch return null; 1063 const oid = if (ref) |value| if (value.kind == .object) value.value else return null else ""; 1064 const file_path = pathValue(segments.rest()) orelse return null; 1065 return forkFilesRoute(identity, id, oid, file_path, line); 1066 } 1067 if (std.mem.eql(u8, tab, commits_seg)) { 1068 params.scanPairs(&segments) catch return null; 1069 if (!params.only(&.{ .start, .object })) return null; 1070 const start = params.start() orelse return null; 1071 const ref = params.ref() catch return null; 1072 const oid = if (ref) |value| if (value.kind == .object) value.value else return null else ""; 1073 if (std.mem.eql(u8, segments.rest(), message_seg)) 1074 return if (start == 0 and oid.len != 0) forkCommitMessageRoute(identity, id, oid) else null; 1075 const file_path = pathValue(segments.rest()) orelse return null; 1076 return forkCommitsRoute(identity, id, oid, start, file_path); 1077 } 1078 if (std.mem.eql(u8, tab, "settings")) return if (segments.next() == null) forkSettingsRoute(identity, id) else null; 1079 if (std.mem.eql(u8, tab, "auth")) return if (segments.next() == null) forkAuthRoute(identity, id) else null; 1080 return null; 1081 } 1082 // "repo/<username>/<reponame>[/<tab tail>]"; the bare pair is the 1083 // files root 1084 if (std.mem.eql(u8, first, "repo")) { 1085 const rest = segments.rest(); // "username/reponame[/...]" 1086 const owner = segments.next() orelse return null; 1087 const repo_name = segments.next() orelse return null; 1088 // reject an empty username or reponame 1089 if (owner.len == 0 or repo_name.len == 0) return null; 1090 const pair = rest[0 .. owner.len + 1 + repo_name.len]; // "username/reponame" 1091 if (segments.peek() != null) { 1092 return repoSubRoute(pair, segments.rest()); 1093 } 1094 return repoFilesRoute(pair, null, "", "", 0); 1095 } 1096 return null; 1097 } 1098 1099 // parse a local-mode url, which elides the "/repo/<owner>/<name>" prefix: 1100 // "/" is the files root and the sub-paths follow directly. 1101 pub fn fromUrlLocal(path: []const u8) ?RoutablePage { 1102 if (std.mem.eql(u8, path, "/")) return repoFilesRoute("", null, "", "", 0); 1103 if (path.len < 2 or path[0] != '/') return null; 1104 return repoSubRoute("", path[1..]); 1105 } 1106 1107 // the url prefix for a repo route's identity: "/repo/<identity>", or "" 1108 // when the identity is elided. 1109 fn repoUrlPrefix(arena: *std.heap.ArenaAllocator, identity: []const u8) ![]const u8 { 1110 if (identity.len == 0) return ""; 1111 return std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{identity}); 1112 } 1113 1114 // true when the page builds at its content height on the web, letting the 1115 // browser scroll the whole page, rather than being pinned to the viewport 1116 pub fn fullHeight(self: RoutablePage) bool { 1117 return switch (self) { 1118 .repo_issues => |i| i.view == .resolve, 1119 .repo_patches => |p| p.view == .resolve, 1120 else => false, 1121 }; 1122 } 1123 1124 // the "owner/name" a repo route carries, null for any other route. the 1125 // result borrows the route, so it must outlive the slice. 1126 pub fn repoIdentity(self: *const RoutablePage) ?[]const u8 { 1127 return switch (self.*) { 1128 .repo_files => |*f| f.name.slice(), 1129 .repo_commits => |*c| c.name.slice(), 1130 .repo_refs => |*r| r.name.slice(), 1131 .repo_issues => |*i| i.name.slice(), 1132 .repo_patches => |*p| p.name.slice(), 1133 .repo_discussions => |*t| t.name.slice(), 1134 .repo_events => |*e| e.name.slice(), 1135 .repo_settings, .repo_auth => |*name| name.slice(), 1136 else => null, 1137 }; 1138 } 1139 1140 pub fn forkRoute(self: *const RoutablePage) ?*const ForkRoute { 1141 return switch (self.*) { 1142 .fork_patch => |*f| f, 1143 .fork_diff => |*d| &d.fork, 1144 .fork_files => |*f| &f.fork, 1145 .fork_commits => |*f| &f.fork, 1146 .fork_settings => |*f| f, 1147 .fork_auth => |*f| f, 1148 else => null, 1149 }; 1150 } 1151 1152 // the route this route's page lands on, with no tab or params: the users 1153 // list, a user's repos, or a repo's files root. 1154 pub fn pageRoot(self: RoutablePage) RoutablePage { 1155 return switch (self.parent()) { 1156 .home => .default, 1157 .user => switch (self) { 1158 .user_repos => |u| .{ .user_repos = .{ .name = u.name } }, 1159 .user_forks => |u| .{ .user_repos = .{ .name = u.name } }, 1160 .user_settings, .user_auth => |name| .{ .user_repos = .{ .name = name } }, 1161 else => self, 1162 }, 1163 // every repo route stores the same identity, so it always fits 1164 .repo => repoFilesRoute(self.repoIdentity() orelse return self, null, "", "", 0) orelse self, 1165 .fork => blk: { 1166 const f = self.forkRoute() orelse break :blk self; 1167 break :blk forkPatchRoute(f.name.slice(), f.id.slice()) orelse self; 1168 }, 1169 }; 1170 } 1171 1172 pub fn parent(self: RoutablePage) PageKind { 1173 return switch (self) { 1174 .home_users, .home_repos, .home_settings, .home_auth => .home, 1175 .user_repos, .user_forks, .user_settings, .user_auth => .user, 1176 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_patches, .repo_discussions, .repo_events, .repo_settings, .repo_auth => .repo, 1177 .fork_patch, .fork_diff, .fork_files, .fork_commits, .fork_settings, .fork_auth => .fork, 1178 }; 1179 } 1180 1181 // the dir a trailing "path:<dir>" names: the raw remainder ("" when 1182 // absent, null when malformed) 1183 fn pathValue(rest: []const u8) ?[]const u8 { 1184 if (rest.len == 0) return ""; 1185 if (!std.mem.startsWith(u8, rest, path_seg)) return null; 1186 const dir = rest[path_seg.len..]; 1187 return if (dir.len == 0) null else dir; 1188 } 1189 1190 // a list route's tail: at most a "start:<n>" param, null on anything else 1191 fn listStart(segments: *std.mem.SplitIterator(u8, .scalar)) ?usize { 1192 var params = Params{}; 1193 const word = params.scanTail(segments) catch return null; 1194 if (word != null or !params.only(&.{.start})) return null; 1195 return params.start(); 1196 } 1197 1198 // parse the sub-path after a repo route's identity ("" for a local 1199 // route): a tab keyword followed by "key:value" params in any order, plus 1200 // the files tab's trailing "path:<dir>". 1201 fn repoSubRoute(pair: []const u8, sub: []const u8) ?RoutablePage { 1202 var segments = std.mem.splitScalar(u8, sub, '/'); 1203 const tab = segments.next() orelse return null; 1204 var params = Params{}; 1205 if (std.mem.eql(u8, tab, "settings")) return if (segments.next() == null) .{ .repo_settings = Array(repo_route_max_len).from(pair) orelse return null } else null; 1206 if (std.mem.eql(u8, tab, "auth")) return if (segments.next() == null) .{ .repo_auth = Array(repo_route_max_len).from(pair) orelse return null } else null; 1207 if (std.mem.eql(u8, tab, "refs")) { 1208 const word = params.scanTail(&segments) catch return null; 1209 if (word != null or !params.only(&.{ .branch, .tag })) return null; 1210 const ref = (params.ref() catch return null) orelse return repoRefsRoute(pair, .branch, ""); 1211 const kind = std.meta.stringToEnum(RefKind, @tagName(ref.kind)) orelse return null; 1212 return repoRefsRoute(pair, kind, ref.value); 1213 } 1214 if (std.mem.startsWith(u8, tab, issue_seg)) { 1215 const issue_id = tab[issue_seg.len..]; 1216 if (issue_id.len == 0) return null; 1217 if (segments.peek()) |tail| { 1218 if (std.mem.startsWith(u8, tail, comment_seg)) { 1219 _ = segments.next(); 1220 const comment_id = tail[comment_seg.len..]; 1221 if (comment_id.len == 0) return null; 1222 const word = params.scanTail(&segments) catch return null; 1223 if (word) |last| { 1224 if (!params.only(&.{})) return null; 1225 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.issue, pair, issue_id, comment_id); 1226 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.issue, pair, issue_id, comment_id); 1227 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.issue, pair, issue_id, comment_id); 1228 return null; 1229 } 1230 if (!params.only(&.{.start})) return null; 1231 return repoThreadCommentRoute(.issue, pair, issue_id, comment_id, params.start() orelse return null); 1232 } 1233 } 1234 const word = params.scanTail(&segments) catch return null; 1235 if (word) |tail| { 1236 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.issue, pair, issue_id, "") else null; 1237 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.issue, pair, issue_id) else null; 1238 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.issue, pair, issue_id, "") else null; 1239 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.issue, pair, issue_id) else null; 1240 if (std.mem.eql(u8, tail, "resolve")) { 1241 if (!params.only(&.{.theirs})) return null; 1242 return repoIssuesResolveRoute(pair, issue_id, params.values.get(.theirs) orelse ""); 1243 } 1244 return null; 1245 } 1246 if (!params.only(&.{.start})) return null; 1247 return repoThreadCommentsRoute(.issue, pair, issue_id, params.start() orelse return null); 1248 } 1249 if (std.mem.startsWith(u8, tab, patch_seg)) { 1250 const patch_id = tab[patch_seg.len..]; 1251 if (patch_id.len == 0) return null; 1252 if (segments.peek()) |tail| { 1253 if (std.mem.startsWith(u8, tail, comment_seg)) { 1254 _ = segments.next(); 1255 const comment_id = tail[comment_seg.len..]; 1256 if (comment_id.len == 0) return null; 1257 const word = params.scanTail(&segments) catch return null; 1258 if (word) |last| { 1259 if (!params.only(&.{})) return null; 1260 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.patch, pair, patch_id, comment_id); 1261 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.patch, pair, patch_id, comment_id); 1262 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.patch, pair, patch_id, comment_id); 1263 return null; 1264 } 1265 if (!params.only(&.{.start})) return null; 1266 return repoThreadCommentRoute(.patch, pair, patch_id, comment_id, params.start() orelse return null); 1267 } 1268 } 1269 const word = params.scanTail(&segments) catch return null; 1270 if (word) |tail| { 1271 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.patch, pair, patch_id, "") else null; 1272 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.patch, pair, patch_id) else null; 1273 if (std.mem.eql(u8, tail, "publish")) return if (params.only(&.{})) repoPatchPublishRoute(pair, patch_id) else null; 1274 if (std.mem.eql(u8, tail, "merge")) return if (params.only(&.{})) repoPatchMergeRoute(pair, patch_id) else null; 1275 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.patch, pair, patch_id, "") else null; 1276 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.patch, pair, patch_id) else null; 1277 if (std.mem.eql(u8, tail, "resolve")) { 1278 if (!params.only(&.{.theirs})) return null; 1279 return repoPatchesResolveRoute(pair, patch_id, params.values.get(.theirs) orelse ""); 1280 } 1281 return null; 1282 } 1283 if (!params.only(&.{.start})) return null; 1284 return repoThreadCommentsRoute(.patch, pair, patch_id, params.start() orelse return null); 1285 } 1286 if (std.mem.startsWith(u8, tab, discuss_seg)) { 1287 const discussion_id = tab[discuss_seg.len..]; 1288 if (discussion_id.len == 0) return null; 1289 if (segments.peek()) |tail| { 1290 if (std.mem.startsWith(u8, tail, comment_seg)) { 1291 _ = segments.next(); 1292 const comment_id = tail[comment_seg.len..]; 1293 if (comment_id.len == 0) return null; 1294 const word = params.scanTail(&segments) catch return null; 1295 if (word) |last| { 1296 if (!params.only(&.{})) return null; 1297 if (std.mem.eql(u8, last, "new")) return repoThreadCommentNewRoute(.discuss, pair, discussion_id, comment_id); 1298 if (std.mem.eql(u8, last, "edit")) return repoThreadCommentEditRoute(.discuss, pair, discussion_id, comment_id); 1299 if (std.mem.eql(u8, last, "remove")) return repoThreadRemoveRoute(.discuss, pair, discussion_id, comment_id); 1300 return null; 1301 } 1302 if (!params.only(&.{.start})) return null; 1303 return repoThreadCommentRoute(.discuss, pair, discussion_id, comment_id, params.start() orelse return null); 1304 } 1305 } 1306 const word = params.scanTail(&segments) catch return null; 1307 if (word) |tail| { 1308 if (std.mem.eql(u8, tail, "new")) return if (params.only(&.{})) repoThreadCommentNewRoute(.discuss, pair, discussion_id, "") else null; 1309 if (std.mem.eql(u8, tail, "edit")) return if (params.only(&.{})) repoThreadEditRoute(.discuss, pair, discussion_id) else null; 1310 if (std.mem.eql(u8, tail, "remove")) return if (params.only(&.{})) repoThreadRemoveRoute(.discuss, pair, discussion_id, "") else null; 1311 if (std.mem.eql(u8, tail, "description")) return if (params.only(&.{})) repoThreadDescriptionRoute(.discuss, pair, discussion_id) else null; 1312 return null; 1313 } 1314 if (!params.only(&.{.start})) return null; 1315 return repoThreadCommentsRoute(.discuss, pair, discussion_id, params.start() orelse return null); 1316 } 1317 if (std.mem.eql(u8, tab, "issues")) { 1318 // the word is a list view; a filter with neither is never emitted. 1319 const word = params.scanTail(&segments) catch return null; 1320 const tag_value = params.values.get(.tag) orelse ""; 1321 const w = word orelse return if (params.only(&.{})) repoIssuesRoute(pair, .open, "", "") else null; 1322 // the conflicts list windows by an issue id, not a number, so it 1323 // reads the start param raw 1324 if (std.mem.eql(u8, w, "conflicts")) { 1325 if (!params.only(&.{.start})) return null; 1326 return repoIssuesConflictsRoute(pair, params.values.get(.start) orelse ""); 1327 } 1328 if (!params.only(&.{.tag})) return null; 1329 if (std.meta.stringToEnum(evt.Issue.Status, w)) |status| return repoIssuesRoute(pair, status, tag_value, ""); 1330 if (std.mem.eql(u8, w, "tags")) return repoThreadTagsRoute(.issue, pair, tag_value); 1331 if (std.mem.eql(u8, w, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.issue, pair) else null; 1332 return null; 1333 } 1334 if (std.mem.eql(u8, tab, "patches")) { 1335 const word = params.scanTail(&segments) catch return null; 1336 const tag_value = params.values.get(.tag) orelse ""; 1337 const view = word orelse return if (params.only(&.{})) repoPatchesRoute(pair, .open, "", "") else null; 1338 if (std.mem.eql(u8, view, "conflicts")) { 1339 if (!params.only(&.{.start})) return null; 1340 return repoPatchesConflictsRoute(pair, params.values.get(.start) orelse ""); 1341 } 1342 if (!params.only(&.{.tag})) return null; 1343 if (std.meta.stringToEnum(evt.Patch.StatusKind, view)) |status| return repoPatchesRoute(pair, status, tag_value, ""); 1344 if (std.mem.eql(u8, view, "tags")) return repoThreadTagsRoute(.patch, pair, tag_value); 1345 if (std.mem.eql(u8, view, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.patch, pair) else null; 1346 if (std.mem.eql(u8, view, "drafts")) return if (tag_value.len == 0) repoPatchesDraftsRoute(pair) else null; 1347 return null; 1348 } 1349 if (std.mem.eql(u8, tab, "discussions")) { 1350 const word = params.scanTail(&segments) catch return null; 1351 const tag_value = params.values.get(.tag) orelse ""; 1352 const view = word orelse return if (params.only(&.{})) repoDiscussionsRoute(pair, "", "") else null; 1353 if (!params.only(&.{.tag})) return null; 1354 if (std.mem.eql(u8, view, "recent")) return repoDiscussionsRoute(pair, tag_value, ""); 1355 if (std.mem.eql(u8, view, "tags")) return repoThreadTagsRoute(.discuss, pair, tag_value); 1356 if (std.mem.eql(u8, view, "new")) return if (tag_value.len == 0) repoThreadNewRoute(.discuss, pair) else null; 1357 return null; 1358 } 1359 if (std.mem.eql(u8, tab, "events")) { 1360 const view = if (segments.next()) |word| 1361 std.meta.stringToEnum(EventsView, word) orelse return null 1362 else 1363 .active; 1364 return if (segments.next() == null) repoEventsRoute(pair, view, null, "") else null; 1365 } 1366 if (std.mem.startsWith(u8, tab, "event:")) { 1367 const event_id = tab["event:".len..]; 1368 const kind_segment = segments.next() orelse return null; 1369 if (!std.mem.startsWith(u8, kind_segment, "kind:")) return null; 1370 const kind = std.meta.stringToEnum(evt.EventKind, kind_segment["kind:".len..]) orelse return null; 1371 if (event_id.len == 0 or segments.next() != null) return null; 1372 return repoEventsRoute(pair, .active, kind, event_id); 1373 } 1374 if (std.mem.eql(u8, tab, files_seg)) { 1375 params.scanPairs(&segments) catch return null; 1376 if (!params.only(&.{ .line, .branch, .tag, .object })) return null; 1377 const line = params.line() orelse return null; 1378 const dir = pathValue(segments.rest()) orelse return null; 1379 const ref = (params.ref() catch return null) orelse 1380 return if (dir.len == 0) repoFilesRoute(pair, null, "", "", line) else null; 1381 return repoFilesRoute(pair, ref.kind, ref.value, dir, line); 1382 } 1383 if (std.mem.eql(u8, tab, commits_seg)) { 1384 params.scanPairs(&segments) catch return null; 1385 if (!params.only(&.{ .start, .branch, .tag, .object })) return null; 1386 const start = params.start() orelse return null; 1387 const ref = (params.ref() catch return null) orelse { 1388 const file = pathValue(segments.rest()) orelse return null; 1389 return if (file.len == 0) repoCommitsRoute(pair, null, "", start, "") else null; 1390 }; 1391 // the message page names its commit and nothing else 1392 if (std.mem.eql(u8, segments.rest(), message_seg)) 1393 return if (start == 0) repoCommitMessageRoute(pair, ref.kind, ref.value) else null; 1394 const file = pathValue(segments.rest()) orelse return null; 1395 return repoCommitsRoute(pair, ref.kind, ref.value, start, file); 1396 } 1397 return null; // unknown sub-path 1398 } 1399 1400 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 1401 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1402 return switch (a) { 1403 .home_users => |a_start| a_start == b.home_users, 1404 .home_repos => |a_start| a_start == b.home_repos, 1405 .user_repos => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_repos.name.slice()) and a_u.start == b.user_repos.start, 1406 .user_forks => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_forks.name.slice()) and a_u.start == b.user_forks.start, 1407 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 1408 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 1409 .repo_files => |a_f| std.mem.eql(u8, a_f.name.slice(), b.repo_files.name.slice()) and 1410 a_f.ref_kind == b.repo_files.ref_kind and 1411 std.mem.eql(u8, a_f.ref_value.slice(), b.repo_files.ref_value.slice()) and 1412 std.mem.eql(u8, a_f.path.slice(), b.repo_files.path.slice()) and 1413 a_f.line == b.repo_files.line, 1414 .repo_commits => |a_c| std.mem.eql(u8, a_c.name.slice(), b.repo_commits.name.slice()) and 1415 a_c.ref_or_oid == b.repo_commits.ref_or_oid and 1416 std.mem.eql(u8, a_c.value.slice(), b.repo_commits.value.slice()) and 1417 switch (a_c.content) { 1418 .diff => |a_d| switch (b.repo_commits.content) { 1419 .diff => |b_d| a_d.start == b_d.start and std.mem.eql(u8, a_d.path.slice(), b_d.path.slice()), 1420 .message => false, 1421 }, 1422 .message => std.meta.activeTag(b.repo_commits.content) == .message, 1423 }, 1424 .repo_refs => |a_r| std.mem.eql(u8, a_r.name.slice(), b.repo_refs.name.slice()) and a_r.kind == b.repo_refs.kind and std.mem.eql(u8, a_r.from.slice(), b.repo_refs.from.slice()), 1425 .repo_issues => |a_i| std.mem.eql(u8, a_i.name.slice(), b.repo_issues.name.slice()) and 1426 std.mem.eql(u8, a_i.tag.slice(), b.repo_issues.tag.slice()) and 1427 std.mem.eql(u8, a_i.selected.slice(), b.repo_issues.selected.slice()) and 1428 std.mem.eql(u8, a_i.theirs.slice(), b.repo_issues.theirs.slice()) and 1429 a_i.view == b.repo_issues.view and 1430 a_i.comments_start == b.repo_issues.comments_start and 1431 std.mem.eql(u8, a_i.comment.slice(), b.repo_issues.comment.slice()), 1432 .repo_discussions => |a_t| std.mem.eql(u8, a_t.name.slice(), b.repo_discussions.name.slice()) and 1433 std.mem.eql(u8, a_t.tag.slice(), b.repo_discussions.tag.slice()) and 1434 std.mem.eql(u8, a_t.selected.slice(), b.repo_discussions.selected.slice()) and 1435 a_t.view == b.repo_discussions.view and 1436 a_t.comments_start == b.repo_discussions.comments_start and 1437 std.mem.eql(u8, a_t.comment.slice(), b.repo_discussions.comment.slice()), 1438 .repo_patches => |a_p| std.mem.eql(u8, a_p.name.slice(), b.repo_patches.name.slice()) and 1439 std.mem.eql(u8, a_p.tag.slice(), b.repo_patches.tag.slice()) and 1440 std.mem.eql(u8, a_p.selected.slice(), b.repo_patches.selected.slice()) and 1441 std.mem.eql(u8, a_p.theirs.slice(), b.repo_patches.theirs.slice()) and 1442 a_p.view == b.repo_patches.view and 1443 a_p.comments_start == b.repo_patches.comments_start and 1444 std.mem.eql(u8, a_p.comment.slice(), b.repo_patches.comment.slice()), 1445 .repo_events => |a_e| std.mem.eql(u8, a_e.name.slice(), b.repo_events.name.slice()) and 1446 a_e.view == b.repo_events.view and 1447 a_e.kind == b.repo_events.kind and 1448 std.mem.eql(u8, a_e.selected.slice(), b.repo_events.selected.slice()), 1449 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 1450 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 1451 .fork_patch => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_patch.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_patch.id.slice()), 1452 .fork_diff => |a_d| std.mem.eql(u8, a_d.fork.name.slice(), b.fork_diff.fork.name.slice()) and 1453 std.mem.eql(u8, a_d.fork.id.slice(), b.fork_diff.fork.id.slice()) and 1454 a_d.start == b.fork_diff.start and std.mem.eql(u8, a_d.path.slice(), b.fork_diff.path.slice()), 1455 .fork_files => |a_f| std.mem.eql(u8, a_f.fork.name.slice(), b.fork_files.fork.name.slice()) and 1456 std.mem.eql(u8, a_f.fork.id.slice(), b.fork_files.fork.id.slice()) and 1457 std.mem.eql(u8, a_f.oid.slice(), b.fork_files.oid.slice()) and 1458 std.mem.eql(u8, a_f.path.slice(), b.fork_files.path.slice()) and 1459 a_f.line == b.fork_files.line, 1460 .fork_commits => |a_c| std.mem.eql(u8, a_c.fork.name.slice(), b.fork_commits.fork.name.slice()) and 1461 std.mem.eql(u8, a_c.fork.id.slice(), b.fork_commits.fork.id.slice()) and 1462 std.mem.eql(u8, a_c.oid.slice(), b.fork_commits.oid.slice()) and 1463 switch (a_c.content) { 1464 .diff => |a_d| switch (b.fork_commits.content) { 1465 .diff => |b_d| a_d.start == b_d.start and std.mem.eql(u8, a_d.path.slice(), b_d.path.slice()), 1466 .message => false, 1467 }, 1468 .message => std.meta.activeTag(b.fork_commits.content) == .message, 1469 }, 1470 .fork_settings => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_settings.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_settings.id.slice()), 1471 .fork_auth => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_auth.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_auth.id.slice()), 1472 else => true, 1473 }; 1474 } 1475 1476 // true when following a link from `b` to `a` (both repo routes) should reload 1477 // rather than stay in page 1478 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 1479 if (a.parent() != .repo or b.parent() != .repo) return false; 1480 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 1481 a.repo_refs.from.len == 0 and b.repo_refs.from.len == 0) 1482 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 1483 return !a.eql(b); 1484 } 1485 1486 pub fn forkPageChanged(a: RoutablePage, b: RoutablePage) bool { 1487 return a.parent() == .fork and b.parent() == .fork and !a.eql(b); 1488 } 1489 1490 // true when `a` and `b` are the same user paginated to a different repos 1491 // window. switching between a user's tabs is in-page, so 1492 // only a changed `start` on the repos list navigates. 1493 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 1494 return switch (a) { 1495 .user_repos => |aa| switch (b) { 1496 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 1497 else => false, 1498 }, 1499 .user_forks => |aa| switch (b) { 1500 .user_forks => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 1501 else => false, 1502 }, 1503 else => false, 1504 }; 1505 } 1506 1507 // true when `a` and `b` are the same home list tab paginated to a different 1508 // window. switching between the users/repos tabs is in-page (the home page 1509 // holds both lists), so only a changed `after` on the same tab navigates. 1510 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 1511 return switch (a) { 1512 .home_users => |aa| switch (b) { 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 same_branch, 1717 unrelated_branches, 1718 1719 pub fn fromError(err: anyerror) ?PatchFailure { 1720 return switch (err) { 1721 error.InvalidTargetBranch => .invalid_target_branch, 1722 error.InvalidSourceBranch => .invalid_source_branch, 1723 error.SameBranch => .same_branch, 1724 error.UnrelatedBranches => .unrelated_branches, 1725 else => null, 1726 }; 1727 } 1728 }; 1729 1730 login: struct { 1731 failure: LoginFailure, 1732 username: []const u8, 1733 }, 1734 issue: struct { 1735 failure: ThreadFailure, 1736 fields: ?struct { 1737 title: []const u8, 1738 tags: []const u8, 1739 description: []const u8, 1740 } = null, 1741 }, 1742 patch: struct { 1743 failure: PatchFailure, 1744 fields: ?struct { 1745 title: []const u8, 1746 tags: []const u8, 1747 description: []const u8, 1748 target_branch: []const u8, 1749 source_branch: []const u8 = "", 1750 source_kind: Repo.Patches.Source.Kind = .fork, 1751 } = null, 1752 }, 1753 discussion: struct { 1754 failure: ThreadFailure, 1755 fields: ?struct { 1756 title: []const u8, 1757 tags: []const u8, 1758 description: []const u8, 1759 } = null, 1760 }, 1761 }; 1762 1763 const Self = @This(); 1764 1765 // serializable data sent down to web client 1766 pub const Data = struct { 1767 user_id: ?[]const u8 = null, 1768 // the logged-in user's name, for the views that show it 1769 user_name: ?[]const u8 = null, 1770 // a failed form retained long enough to render it for correction 1771 form_feedback: ?FormFeedback = null, 1772 // a transient local event-sync error 1773 sync_failure: ?[]const u8 = null, 1774 current_page: RoutablePage = .default, 1775 // whether to render the ANSI art backdrop 1776 enable_ansi: bool = true, 1777 // the selected ANSI art. the server serializes one image for WASM so 1778 // the browser does not need the whole build-generated collection. 1779 ansi_art: []const u8 = "", 1780 // the bound git-service ports. absent in local mode, where remote urls 1781 // are not shown. 1782 git_http_port: ?u16 = null, 1783 git_ssh_port: ?u16 = null, 1784 git_ssh_prefix: []const u8 = "", 1785 // whether this session views a local repo or the server. unlike `local` 1786 // (the host-side filesystem source) this travels in the snapshot, so 1787 // the wasm side also parses elided link urls and hides the multi-user 1788 // chrome. 1789 host_kind: evt.HostKind = .server, 1790 }; 1791 1792 // a user-initiated state change. widgets enqueue these on the session during 1793 // input instead of mutating state or touching the DB themselves; the host 1794 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1795 // side effects out of the widget tree and gives every render path one place to 1796 // turn a UI action into a state change + event. 1797 pub const Action = union(enum) { 1798 toggle_ansi, 1799 }; 1800 1801 pub fn init( 1802 arena: *std.heap.ArenaAllocator, 1803 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1804 data: Data, 1805 ) !Self { 1806 var session = Self{ 1807 .data = data, 1808 .arena = arena, 1809 // until a host swaps in a page-scoped arena (Nav does this), page 1810 // allocations land in the session arena. on the web path that's the 1811 // intended behavior, since the whole arena is per-request. 1812 .page_arena = arena, 1813 .admin_repo = repo, 1814 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1815 }; 1816 try session.loadUser(); 1817 return session; 1818 } 1819 1820 // load the logged-in user's name and persisted preferences from the db 1821 pub fn loadUser(self: *Self) !void { 1822 const user_id = self.data.user_id orelse return; 1823 const moment = self.haxy_moment orelse return; 1824 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1825 self.data.user_name = user.event.name; 1826 self.data.enable_ansi = user.event.enable_ansi; 1827 } 1828 } 1829 1830 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 1831 const bytes = self.data.user_id orelse return null; 1832 if (bytes.len != evt.event_id_size) return null; 1833 var id: [evt.event_id_size]u8 = undefined; 1834 @memcpy(&id, bytes); 1835 return id; 1836 } 1837 1838 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 1839 const feedback = self.data.form_feedback orelse return null; 1840 if (std.meta.activeTag(feedback) != tag) return null; 1841 return @field(feedback, @tagName(tag)); 1842 } 1843 1844 pub fn clearFormFeedback(self: *Self) void { 1845 self.data.form_feedback = null; 1846 } 1847 1848 // the commit author for an event this session creates, or null when it may 1849 // not create one 1850 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1851 if (self.data.host_kind == .local) { 1852 const src = self.local orelse return local_author_fallback; 1853 const io = self.io orelse return local_author_fallback; 1854 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1855 } 1856 const user_id = self.data.user_id orelse return null; 1857 const moment = self.haxy_moment orelse return null; 1858 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1859 return .{ .name = user.event.name, .email = user.event.email }; 1860 } 1861 1862 // queue an action for the host to drain this frame. 1863 pub fn push(self: *Self, action: Action) !void { 1864 try self.pending.append(self.arena.allocator(), action); 1865 } 1866 1867 // apply a single action's in-memory effect only (no persistence). 1868 fn apply(self: *Self, action: Action) void { 1869 switch (action) { 1870 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1871 } 1872 } 1873 1874 // drain the session's queued actions by applying them to the session. 1875 // used on the wasm path, which has no repo to persist to. 1876 pub fn applyPending(self: *Self) void { 1877 for (self.pending.items) |action| self.apply(action); 1878 self.pending.clearRetainingCapacity(); 1879 } 1880 1881 // drain the session's queued actions by applying them to the session and 1882 // writing them to the db 1883 pub fn applyAndWritePending( 1884 self: *Self, 1885 io: std.Io, 1886 allocator: std.mem.Allocator, 1887 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1888 ) !void { 1889 defer self.pending.clearRetainingCapacity(); 1890 for (self.pending.items) |action| { 1891 self.apply(action); 1892 switch (action) { 1893 .toggle_ansi => if (self.data.user_id) |user_id| { 1894 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1895 }, 1896 } 1897 } 1898 } 1899 1900 // reload the moment from the admin repo and re-read user preferences 1901 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1902 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1903 self.haxy_moment = moment; 1904 1905 const user_id = self.data.user_id orelse return; 1906 var arena = std.heap.ArenaAllocator.init(allocator); 1907 defer arena.deinit(); 1908 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1909 self.data.enable_ansi = user.event.enable_ansi; 1910 } 1911 } 1912 1913 // request a forward navigation to `route`; the host consumes next_page 1914 // (Nav.sync on the terminal, the wasm tick on the web). 1915 pub fn navigate(self: *Session, route: RoutablePage) !void { 1916 self.clearFormFeedback(); 1917 self.next_page = route; 1918 } 1919 }; 1920 1921 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1922 var nav = try Nav.init(allocator, session); 1923 defer nav.deinit(allocator); 1924 1925 var terminal = try term.Terminal.init(io, allocator); 1926 var terminal_live = true; 1927 defer if (terminal_live) terminal.deinit(io); 1928 1929 // set term as active so it will be properly cooked 1930 // when a panic/segfault happens 1931 term.setActive(&terminal); 1932 defer term.setActive(null); 1933 1934 while (!terminal.shouldQuit()) { 1935 const grid_changed = try terminal.render(&nav.root); 1936 1937 // process any inputs. 1938 // 1939 // if the grid didn't change, then first do a blocking 1940 // read, so the thread will sleep until further input. 1941 // after that, all remaining reads are non-blocking so 1942 // we can process the rest of the queued inputs. 1943 // 1944 // if the grid *did* change, then only do non-blocking 1945 // reads. we do not want to sleep the thread because 1946 // there may be an animation that requires more looping. 1947 var blocking = !grid_changed; 1948 while (try terminal.readKey(io, blocking)) |key| { 1949 blocking = false; 1950 try inputKey(allocator, &nav.root, key, session); 1951 } 1952 1953 if (session.host_request) |request| { 1954 session.host_request = null; 1955 switch (request) { 1956 .show_copyable_text => |copyable_text| { 1957 term.setActive(null); 1958 terminal.deinit(io); 1959 terminal_live = false; 1960 showCopyableText(io, copyable_text) catch |show_err| { 1961 terminal = try term.Terminal.init(io, allocator); 1962 terminal_live = true; 1963 term.setActive(&terminal); 1964 return show_err; 1965 }; 1966 terminal = try term.Terminal.init(io, allocator); 1967 terminal_live = true; 1968 term.setActive(&terminal); 1969 }, 1970 .sync_events => { 1971 try nav.root.build(allocator, .{ 1972 .min_size = .{ .width = null, .height = null }, 1973 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 1974 }, nav.root.getFocus()); 1975 _ = try terminal.render(&nav.root); 1976 try Repo.Events.performSync(allocator, session); 1977 }, 1978 } 1979 } 1980 1981 // persist queued actions when there's a repo; local mode has none, 1982 // so just apply in-memory 1983 if (repo_maybe) |repo| { 1984 try session.applyAndWritePending(io, allocator, repo); 1985 // reload so the next navigation builds its page from the current moment 1986 try session.reloadMoment(allocator, repo); 1987 } else { 1988 session.applyPending(); 1989 } 1990 1991 // reconcile navigation: forward to a new page, or back on escape. 1992 try nav.sync(allocator, session); 1993 1994 // the quit button (on the quit tab) asks the host to tear down. 1995 if (session.quit_requested) terminal.requestQuit(); 1996 1997 try nav.root.build(allocator, .{ 1998 .min_size = .{ .width = null, .height = null }, 1999 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2000 }, nav.root.getFocus()); 2001 } 2002 } 2003 2004 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2005 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 2006 null 2007 else 2008 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2009 defer if (tty) |file| file.close(io); 2010 2011 const input = if (tty) |file| file else std.Io.File.stdin(); 2012 const output = if (tty) |file| file else std.Io.File.stdout(); 2013 2014 var write_buf: [1024]u8 = undefined; 2015 var writer = output.writer(io, &write_buf); 2016 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}); 2017 try writer.interface.flush(); 2018 2019 var read_buf: [1]u8 = undefined; 2020 var reader = input.reader(io, &read_buf); 2021 while (true) { 2022 const byte = try reader.interface.takeByte(); 2023 if (byte == '\r' or byte == '\n') return; 2024 } 2025 } 2026 2027 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2028 const root_focus = root.getFocus(); 2029 const focused_before = root_focus.grandchild_id; 2030 var activate_in_page_link = false; 2031 switch (key) { 2032 // request a navigation pop; the host's Nav.sync goes back a page, or 2033 // quits when there's no history left. 2034 .escape => { 2035 session.back = .requested; 2036 return; 2037 }, 2038 .ctrl => |letter| switch (letter) { 2039 'r' => { 2040 session.refresh_requested = true; 2041 return; 2042 }, 2043 else => try root.input(allocator, key, root_focus), 2044 }, 2045 .enter => { 2046 if (root_focus.grandchild_id) |gid| { 2047 // follow a cross-page link 2048 if (crossPageLink(root_focus, gid, session.data)) |route| { 2049 return session.navigate(route); 2050 } 2051 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2052 } 2053 activate_in_page_link = true; 2054 try root.input(allocator, key, root_focus); 2055 }, 2056 .mouse => |mouse| { 2057 if (mouse.action == .press and mouse.action.press == .left) { 2058 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2059 const focus_id = hit.id; 2060 if (hit.kind == .background) { 2061 root_focus.setFocus(focus_id); 2062 return; 2063 } 2064 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2065 if (session.back == .available) session.back = .requested; 2066 return; 2067 } 2068 // follow a cross-page link 2069 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2070 return session.navigate(route); 2071 } 2072 if (rawLink(root_focus, focus_id)) |url| { 2073 if (!mouse.ctrl) try requestRawLink(session, url); 2074 return; 2075 } 2076 root_focus.setFocus(focus_id); 2077 activate_in_page_link = true; 2078 } 2079 // forward the press into the widget tree so buttons (and any 2080 // future click-aware widgets) can react. widgets that don't 2081 // care about presses ignore it. 2082 try root.input(allocator, key, root_focus); 2083 } else { 2084 try root.input(allocator, key, root_focus); 2085 } 2086 }, 2087 else => try root.input(allocator, key, root_focus), 2088 } 2089 2090 const focused_after = root_focus.grandchild_id; 2091 if (!activate_in_page_link and focused_before == focused_after) return; 2092 const focus_id = focused_after orelse return; 2093 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2094 } 2095 2096 // a link to bytes the server serves directly rather than to a page route, so 2097 // it never resolves to a RoutablePage 2098 pub const raw_link_prefix = "ax:"; 2099 2100 // a route already loaded into the current page; focusing it changes the url 2101 // without rebuilding the page 2102 pub const in_page_link_prefix = "ai:"; 2103 2104 // an in-page tab's base route, or the exact current route when it is selected 2105 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2106 const target = if (selected) session.data.current_page else route; 2107 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2108 } 2109 2110 // a button the web renderer covers with a file picker that posts the chosen 2111 // file to the url after the prefix 2112 pub const file_input_prefix = "file:"; 2113 2114 // a submit button that overrides its enclosing form's action 2115 pub const submit_action_prefix = "submit:"; 2116 2117 // the url an `ax:` link points at, or null for anything else. a host that 2118 // suppresses the anchor's own navigation needs this to follow the link. 2119 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2120 const child = root_focus.children.get(focus_id) orelse return null; 2121 const custom = switch (child.focus.kind) { 2122 .custom => |c| c, 2123 else => return null, 2124 }; 2125 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2126 return custom[raw_link_prefix.len..]; 2127 } 2128 2129 fn requestRawLink(session: *Session, url: []const u8) !void { 2130 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2131 } 2132 2133 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2134 return if (session.web_port) |port| 2135 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 2136 else 2137 path; 2138 } 2139 2140 // if the focus target at focus_id is an `a:` link that should navigate (a 2141 // different parent page, or a different files directory within the repo page), 2142 // return its route; otherwise null. lets a host turn a click / enter on such a 2143 // link into a navigation rather than a focus change. 2144 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2145 const current = data.current_page; 2146 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2147 // a link to a different parent page always navigates; within a page, a 2148 // files-directory / commits-page / list-window change navigates while tab 2149 // links stay in-page. 2150 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; 2151 return null; 2152 } 2153 2154 // the route carried by an `ai:` focus target, or null for any other target 2155 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2156 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2157 } 2158 2159 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2160 const child = root_focus.children.get(focus_id) orelse return null; 2161 const custom = switch (child.focus.kind) { 2162 .custom => |c| c, 2163 else => return null, 2164 }; 2165 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2166 const path = custom[prefix.len..]; 2167 // local sessions build (and parse) links with the repo identity elided 2168 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2169 } 2170 2171 // a display author, resolved against the admin db at read time 2172 pub const Author = union(enum) { 2173 unknown, 2174 email: []const u8, // an email no user matches 2175 user_name: []const u8, 2176 2177 // the commit author line's email, resolved like initFromEmail 2178 pub fn init( 2179 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2180 arena: *std.heap.ArenaAllocator, 2181 author_line: []const u8, 2182 ) !Author { 2183 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2184 } 2185 2186 // from a record's stored author email: it resolves to the user currently 2187 // holding it, else stays the email. the result is allocated in `arena`, 2188 // so the email may borrow transient memory. 2189 pub fn initFromEmail( 2190 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2191 arena: *std.heap.ArenaAllocator, 2192 author_email: ?[]const u8, 2193 ) !Author { 2194 const email = author_email orelse return .unknown; 2195 if (haxy_moment) |moment| { 2196 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2197 return .{ .user_name = user.event.name }; 2198 } 2199 } 2200 return .{ .email = try arena.allocator().dupe(u8, email) }; 2201 } 2202 }; 2203 2204 // the "a:" link to user `name`'s page. 2205 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2206 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2207 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2208 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 2209 } 2210 2211 // a focusable " author " box showing `author`, linking to their user page 2212 // when it is a known user 2213 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2214 const text = switch (author) { 2215 .unknown => "", 2216 .email, .user_name => |t| t, 2217 }; 2218 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 2219 errdefer tb.deinit(allocator); 2220 tb.getFocus().mode = .all; 2221 switch (author) { 2222 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2223 else => {}, 2224 } 2225 return tb; 2226 } 2227 2228 // native-TUI navigation 2229 pub const Nav = struct { 2230 root: Widget, 2231 // backs the current page (its Page data and the page-scoped strings its 2232 // widgets build). owned here, swapped on each navigation. session.page_arena 2233 // tracks whichever of these is current so widgets allocate into it. 2234 arena: *std.heap.ArenaAllocator, 2235 history: std.ArrayList(Entry), 2236 2237 // each retained page keeps its own arena, freed when the page leaves the 2238 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2239 // long-lived session from accumulating every page it ever visited. 2240 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 2241 2242 // cap on retained back-history so the chain can't grow memory without bound 2243 const max_history: usize = 16; 2244 2245 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2246 session.back = .unavailable; 2247 const arena = try allocator.create(std.heap.ArenaAllocator); 2248 arena.* = std.heap.ArenaAllocator.init(allocator); 2249 errdefer { 2250 arena.deinit(); 2251 allocator.destroy(arena); 2252 } 2253 2254 session.page_arena = arena; 2255 const route = session.data.current_page; 2256 2257 const page = try arena.allocator().create(Page); 2258 page.* = try Page.init(arena, session, route); 2259 return .{ 2260 .root = try initRoot(allocator, page, session), 2261 .arena = arena, 2262 .history = .empty, 2263 }; 2264 } 2265 2266 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2267 self.root.deinit(allocator); 2268 freeArena(allocator, self.arena); 2269 for (self.history.items) |*entry| { 2270 entry.root.deinit(allocator); 2271 freeArena(allocator, entry.arena); 2272 } 2273 self.history.deinit(allocator); 2274 } 2275 2276 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2277 arena.deinit(); 2278 allocator.destroy(arena); 2279 } 2280 2281 // reconcile the displayed root with the session's navigation state. a 2282 // forward nav (current_page moved to a different parent page) pushes the 2283 // current root and builds the new page in a fresh arena; a back request 2284 // frees the current page and restores the previous one. when escape is 2285 // pressed with no history left we switch to the quit tab instead of quitting. 2286 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2287 // refresh: rebuild the current page in place from a current moment 2288 if (session.refresh_requested) { 2289 session.refresh_requested = false; 2290 if (session.haxy_moment != null or session.local != null) { 2291 const arena = try allocator.create(std.heap.ArenaAllocator); 2292 arena.* = std.heap.ArenaAllocator.init(allocator); 2293 errdefer freeArena(allocator, arena); 2294 2295 session.page_arena = arena; 2296 2297 const route = session.data.current_page; 2298 const page = try arena.allocator().create(Page); 2299 page.* = try Page.init(arena, session, route); 2300 const new_root = try initRoot(allocator, page, session); 2301 2302 self.root.deinit(allocator); 2303 freeArena(allocator, self.arena); 2304 self.root = new_root; 2305 self.arena = arena; 2306 } 2307 return; 2308 } 2309 2310 if (session.back == .requested) { 2311 if (self.history.pop()) |entry| { 2312 session.back = if (self.history.items.len == 0) .unavailable else .available; 2313 self.root.deinit(allocator); 2314 freeArena(allocator, self.arena); 2315 self.root = entry.root; 2316 self.arena = entry.arena; 2317 session.page_arena = entry.arena; 2318 session.data.current_page = entry.route; 2319 chooseAnsiArtForNavigation(session); 2320 return; 2321 } 2322 session.back = .unavailable; 2323 // nothing to go back to; switch to the quit confirmation 2324 const root_focus = self.root.getFocus(); 2325 var iter = root_focus.children.iterator(); 2326 while (iter.next()) |entry| { 2327 switch (entry.value_ptr.focus.kind) { 2328 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2329 root_focus.setFocus(entry.key_ptr.*); 2330 // a Stack only builds its selected child, so the quit 2331 // button isn't in the focus tree until a build runs with 2332 // the quit tab selected. build once, then send a 2333 // synthetic arrow_down to drop focus from the tab onto 2334 // the button so it's ready to confirm. 2335 try self.root.build(allocator, .{ 2336 .min_size = .{ .width = null, .height = 40 }, 2337 .max_size = .{ .width = 80, .height = null }, 2338 }, root_focus); 2339 try self.root.input(allocator, .arrow_down, root_focus); 2340 break; 2341 }, 2342 else => {}, 2343 } 2344 } 2345 return; 2346 } 2347 2348 // forward navigation: navigate() set next_page to the page to move to (a 2349 // cross-page link or tab change crossing pages) 2350 if (session.next_page) |route| { 2351 session.next_page = null; 2352 if (session.haxy_moment == null and session.local == null) return; 2353 const previous_route = session.data.current_page; 2354 // the page we navigated to becomes the current page 2355 session.data.current_page = route; 2356 session.back = .available; 2357 2358 const arena = try allocator.create(std.heap.ArenaAllocator); 2359 arena.* = std.heap.ArenaAllocator.init(allocator); 2360 errdefer freeArena(allocator, arena); 2361 2362 session.page_arena = arena; 2363 2364 const page = try arena.allocator().create(Page); 2365 page.* = try Page.init(arena, session, route); 2366 const new_root = try initRoot(allocator, page, session); 2367 2368 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena }); 2369 // drop the oldest entry (freeing its widget tree and arena) once over cap 2370 if (self.history.items.len > max_history) { 2371 var oldest = self.history.orderedRemove(0); 2372 oldest.root.deinit(allocator); 2373 freeArena(allocator, oldest.arena); 2374 } 2375 self.root = new_root; 2376 self.arena = arena; 2377 } 2378 } 2379 }; 2380 2381 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2382 const page_widget: Widget = switch (page.*) { 2383 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2384 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2385 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2386 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2387 }; 2388 2389 chooseAnsiArtForNavigation(session); 2390 2391 // on the TUI/SSH, the page sits above a one-row footer showing the url 2392 var root = if (session.is_terminal) blk: { 2393 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2394 errdefer box.deinit(allocator); 2395 const bg_id = bg_blk: { 2396 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2397 errdefer background.deinit(allocator); 2398 const id = background.getFocus().id; 2399 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2400 break :bg_blk id; 2401 }; 2402 { 2403 var footer = try widget.Footer.init(allocator, session); 2404 errdefer footer.deinit(allocator); 2405 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2406 } 2407 box.getFocus().child_id = bg_id; 2408 break :blk Widget{ .box = box }; 2409 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2410 errdefer root.deinit(allocator); 2411 2412 // input-owning views build their TextInputs in init, so reset their 2413 // registrations here 2414 session.text_inputs.clearRetainingCapacity(); 2415 2416 try root.build(allocator, .{ 2417 .min_size = .{ .width = null, .height = 40 }, 2418 .max_size = .{ .width = 100, .height = null }, 2419 }, root.getFocus()); 2420 2421 return root; 2422 } 2423 2424 // native and server-side sessions choose from the embedded collection. WASM 2425 // keeps the art serialized by the server instead. 2426 fn chooseAnsiArtForNavigation(session: *Session) void { 2427 if (comptime ansi_arts.len == 0) return; 2428 const io = session.io orelse return; 2429 var random: usize = undefined; 2430 io.random(std.mem.asBytes(&random)); 2431 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2432 } 2433