╭ Commits.zig ──────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const evt = @import("../../event.zig"); 4 const ui = @import("../../ui.zig"); 5 const xit = @import("xit"); 6 const rp = xit.repo; 7 const df = xit.diff; 8 const xitui = xit.xitui; 9 const wgt = xitui.widget; 10 const layout = xitui.layout; 11 const Key = xitui.input.Key; 12 const Grid = xitui.grid.Grid; 13 const Focus = xitui.focus.Focus; 14 const inp = @import("../input.zig"); 15 16 const SubHeader = @import("SubHeader.zig"); 17 18 // how many commits a page shows before a "next" link appears. 19 const page_size = 20; 20 // how many diff hunks one window of a commit's diff shows; "next"/"previous" 21 // move to the adjacent window. 22 const diff_page = 10; 23 24 pub const Hunk = struct { 25 path: ?[]const u8 = null, // the file this hunk belongs to 26 lines: []const []const u8, 27 }; 28 29 // one commit on the current page, with its diff against its first parent 30 // pre-rendered up to the budget so the web client can show it without a repo. 31 pub const Commit = struct { 32 oid: []const u8, 33 date: []const u8, // "YYYY-MM-DD" 34 message: []const u8, // first line only 35 hunks: []const Hunk, 36 // the hunk index this window starts at (0 = the first window). 37 window_start: usize, 38 // whether hunks exist before this window / after it. 39 has_prev: bool, 40 has_more: bool, 41 }; 42 43 // "owner/name", so the view can build /repo/owner/name/commits/... links. 44 identity: []const u8, 45 // the resolved ref/oid this log walks from (the default branch when the route 46 // didn't name one), so the page can canonicalize its url to it. 47 ref_or_oid: ui.RoutablePage.RefOrOid, 48 ref_or_oid_value: []const u8, 49 commits: []const Commit, 50 // the first oid of the next page, or null when this is the last page. 51 next_start: ?[]const u8, 52 // the "viewing <ref> <value>" banner shown above the log. 53 sub_header: SubHeader, 54 55 const Self = @This(); 56 57 pub fn init( 58 arena: *std.heap.ArenaAllocator, 59 session: *ui.Session, 60 source_maybe: ?ui.RepoSource, 61 identity: []const u8, 62 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 63 requested_value: []const u8, 64 // the hunk index the selected commit's (the first one, the walk root) diff 65 // window starts at; 0 is the first window. moved by "next"/"previous". 66 after: usize, 67 ) !Self { 68 const aa = arena.allocator(); 69 70 // no filesystem (wasm) or nowhere to look: empty listing. the wasm path 71 // never calls init anyway — it rebuilds from the serialized snapshot. 72 const io = session.io orelse return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value); 73 const source = source_maybe orelse return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value); 74 75 // walk the log with the arena's backing allocator (transient; the commits 76 // we keep are duped into the page arena so they outlive it). AnyRepo opens 77 // both sha1 and sha256 repos. 78 const gpa = arena.child_allocator; 79 switch (source.repo_kind) { 80 inline else => |repo_kind| { 81 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, gpa, .{ .path = source.path }) catch return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value); 82 defer any_repo.deinit(io, gpa); 83 84 return switch (any_repo) { 85 inline else => |*repo| collect(repo_kind, repo.self_repo_opts, arena, repo, io, gpa, identity, requested_ref_or_oid, requested_value, after), 86 }; 87 }, 88 } 89 } 90 91 // walk the log for an opened repo. generic over the repo's backend and hash 92 // kind so the oid buffers and diff types it threads through match the repo's 93 // opts. 94 fn collect( 95 comptime repo_kind: rp.RepoKind, 96 comptime repo_opts: rp.RepoOpts(repo_kind), 97 arena: *std.heap.ArenaAllocator, 98 repo: *rp.Repo(repo_kind, repo_opts), 99 io: std.Io, 100 gpa: std.mem.Allocator, 101 identity: []const u8, 102 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 103 requested_value: []const u8, 104 after: usize, 105 ) !Self { 106 const aa = arena.allocator(); 107 const hex_len = ui.ResolvedRefOrOid(repo_kind, repo_opts).hex_len; 108 109 // resolve the requested ref (or the default branch) to the commit oid to 110 // walk from. an explicitly named ref that doesn't resolve is a bad url 111 // (NotFound -> 404); the default-branch path falls through to empty. 112 const resolved = (try ui.ResolvedRefOrOid(repo_kind, repo_opts).init(repo, io, aa, requested_ref_or_oid, requested_value)) orelse { 113 if (requested_ref_or_oid != null) return error.NotFound; 114 return emptyResult(aa, identity, .branch, requested_value); 115 }; 116 var start_arr = [1][hex_len]u8{resolved.oid}; 117 const start_oids: []const [hex_len]u8 = start_arr[0..1]; 118 119 // collect this page's commit metadata, plus a peek at the one after it (its 120 // oid is the next page's start). the diff for each is rendered afterward, so 121 // the log iterator is closed before opening per-commit diff iterators. 122 var buf: [page_size]Commit = undefined; 123 var oids: [page_size][hex_len]u8 = undefined; 124 var count: usize = 0; 125 var next_start: ?[]const u8 = null; 126 { 127 var iter = repo.log(io, gpa, start_oids) catch return emptyResult(aa, identity, resolved.ref_or_oid, resolved.value); 128 defer iter.deinit(); 129 while (try iter.next(gpa)) |commit_object| { 130 defer commit_object.deinit(); 131 if (count == page_size) { 132 next_start = try aa.dupe(u8, &commit_object.oid); 133 break; 134 } 135 const md = commit_object.content.commit.metadata; 136 @memcpy(&oids[count], &commit_object.oid); 137 buf[count] = .{ 138 .oid = try aa.dupe(u8, &commit_object.oid), 139 .date = try formatDate(aa, md.timestamp), 140 .message = try aa.dupe(u8, firstLine(md.message orelse "")), 141 .hunks = &.{}, 142 .window_start = 0, 143 .has_prev = false, 144 .has_more = false, 145 }; 146 count += 1; 147 } 148 } 149 150 // render each commit's diff (best effort: a failed diff leaves it empty). 151 // the diff machinery isn't wasm-clean and the wasm client never runs it (it 152 // renders from the snapshot), so gate it out of the wasm build. 153 if (!builtin.cpu.arch.isWasm()) { 154 for (buf[0..count], oids[0..count], 0..) |*commit, oid, i| { 155 // the selected commit (the first, == start_oid) shows the window the 156 // url asks for; the rest show their first window. 157 const start = if (i == 0) after else 0; 158 const rendered = renderCommitDiff(repo_kind, repo_opts, io, gpa, aa, repo, oid, start, diff_page) catch 159 RenderedDiff{ .hunks = &.{}, .has_prev = false, .has_more = false }; 160 commit.hunks = rendered.hunks; 161 commit.window_start = start; 162 commit.has_prev = rendered.has_prev; 163 commit.has_more = rendered.has_more; 164 } 165 } 166 167 return .{ 168 .identity = try aa.dupe(u8, identity), 169 .ref_or_oid = resolved.ref_or_oid, 170 .ref_or_oid_value = resolved.value, 171 .commits = try aa.dupe(Commit, buf[0..count]), 172 .next_start = next_start, 173 .sub_header = try SubHeader.init(aa, resolved.ref_or_oid, resolved.value), 174 }; 175 } 176 177 // an empty listing pinned to a ref, for the wasm / no-repo / unresolved paths. 178 fn emptyResult(aa: std.mem.Allocator, identity: []const u8, ref_or_oid: ui.RoutablePage.RefOrOid, value: []const u8) !Self { 179 return .{ 180 .identity = try aa.dupe(u8, identity), 181 .ref_or_oid = ref_or_oid, 182 .ref_or_oid_value = try aa.dupe(u8, value), 183 .commits = &.{}, 184 .next_start = null, 185 .sub_header = try SubHeader.init(aa, ref_or_oid, value), 186 }; 187 } 188 189 const RenderedDiff = struct { 190 hunks: []const Hunk, 191 has_prev: bool, 192 has_more: bool, 193 }; 194 195 // render the window [start, start+len) of a commit's diff against its first 196 // parent into `arena`-owned hunks. has_prev/has_more flag adjacent windows. 197 fn renderCommitDiff( 198 comptime repo_kind: rp.RepoKind, 199 comptime repo_opts: rp.RepoOpts(repo_kind), 200 io: std.Io, 201 gpa: std.mem.Allocator, 202 arena: std.mem.Allocator, 203 repo: *rp.Repo(repo_kind, repo_opts), 204 oid: [xit.hash.hexLen(repo_opts.hash)]u8, 205 start: usize, 206 len: usize, 207 ) !RenderedDiff { 208 const empty = RenderedDiff{ .hunks = &.{}, .has_prev = false, .has_more = false }; 209 210 // load the commit so we can diff it against its first parent. 211 var start_oids = [_][xit.hash.hexLen(repo_opts.hash)]u8{oid}; 212 var commit_iter = repo.log(io, gpa, start_oids[0..1]) catch return empty; 213 defer commit_iter.deinit(); 214 const commit_object = (commit_iter.next(gpa) catch return empty) orelse return empty; 215 defer commit_object.deinit(); 216 217 const parent_maybe = commit_object.content.commit.metadata.firstParent(); 218 219 var tree_diff = repo.treeDiff(io, gpa, parent_maybe, &commit_object.oid) catch return empty; 220 defer tree_diff.deinit(); 221 222 var file_iter = repo.filePairs(io, gpa, .{ .tree = .{ .tree_diff = &tree_diff } }) catch return empty; 223 224 var hunks: std.ArrayList(Hunk) = .empty; 225 var index: usize = 0; // running hunk index across all files 226 var has_more = false; 227 228 file_loop: while (file_iter.next() catch null) |pair_val| { 229 var pair = pair_val; 230 defer pair.deinit(); 231 232 var hunk_iter = df.HunkIterator(repo_kind, repo_opts).init(gpa, &pair.a, &pair.b) catch continue; 233 defer hunk_iter.deinit(gpa); 234 235 // the path label rides on the first of this file's hunks we actually show. 236 var path_attached = false; 237 while (try hunk_iter.next(gpa)) |hunk_val| { 238 var hunk = hunk_val; 239 defer hunk.deinit(gpa); 240 241 const i = index; 242 index += 1; 243 if (i < start) continue; // before this window 244 if (hunks.items.len >= len) { 245 has_more = true; 246 break :file_loop; 247 } 248 var lines: std.ArrayList([]const u8) = .empty; 249 try appendHunkLines(repo_kind, repo_opts, arena, &lines, &hunk_iter, &hunk); 250 try hunks.append(arena, .{ 251 .path = if (path_attached) null else try arena.dupe(u8, pair.path), 252 .lines = try lines.toOwnedSlice(arena), 253 }); 254 path_attached = true; 255 } 256 } 257 258 return .{ .hunks = try hunks.toOwnedSlice(arena), .has_prev = start > 0, .has_more = has_more }; 259 } 260 261 // append a hunk's header and its edit lines, each prefixed with a right-aligned 262 // line number in a column wide enough for the hunk's largest number, then a space 263 fn appendHunkLines( 264 comptime repo_kind: rp.RepoKind, 265 comptime repo_opts: rp.RepoOpts(repo_kind), 266 arena: std.mem.Allocator, 267 lines: *std.ArrayList([]const u8), 268 hunk_iter: *df.HunkIterator(repo_kind, repo_opts), 269 hunk: *df.Hunk(repo_kind, repo_opts), 270 ) !void { 271 var max_num: usize = 1; 272 for (hunk.edits.items) |edit| { 273 const n = editLineNum(edit) + 1; 274 if (n > max_num) max_num = n; 275 } 276 const width = std.fmt.count("{d}", .{max_num}); 277 // a run of spaces sliced to each line's leading pad. 278 const indent = try arena.alloc(u8, width); 279 @memset(indent, ' '); 280 281 for (hunk.edits.items) |edit| { 282 const text = switch (edit) { 283 .eql => |e| try hunk_iter.line_iter_b.get(e.new_line.num), 284 .ins => |e| try hunk_iter.line_iter_b.get(e.new_line.num), 285 .del => |e| try hunk_iter.line_iter_a.get(e.old_line.num), 286 }; 287 defer switch (edit) { 288 .eql, .ins => hunk_iter.line_iter_b.free(text), 289 .del => hunk_iter.line_iter_a.free(text), 290 }; 291 const prefix: u8 = switch (edit) { 292 .eql => ' ', 293 .ins => '+', 294 .del => '-', 295 }; 296 const num_str = try std.fmt.allocPrint(arena, "{d}", .{editLineNum(edit) + 1}); 297 try lines.append(arena, try std.fmt.allocPrint(arena, "{s}{s} {c}{s}", .{ 298 indent[0 .. width - num_str.len], num_str, prefix, text, 299 })); 300 } 301 } 302 303 // the line number to show for an edit: the new-side number for kept and inserted 304 // lines, the old-side number for deletions (0-based in the diff machinery). 305 fn editLineNum(edit: df.Edit) usize { 306 return switch (edit) { 307 .eql => |e| e.new_line.num, 308 .ins => |e| e.new_line.num, 309 .del => |e| e.old_line.num, 310 }; 311 } 312 313 // "YYYY-MM-DD" for a unix timestamp. 314 fn formatDate(arena: std.mem.Allocator, timestamp: u64) ![]const u8 { 315 const epoch_secs = std.time.epoch.EpochSeconds{ .secs = timestamp }; 316 const year_day = epoch_secs.getEpochDay().calculateYearDay(); 317 const month_day = year_day.calculateMonthDay(); 318 return std.fmt.allocPrint(arena, "{d:0>4}-{d:0>2}-{d:0>2}", .{ 319 year_day.year, 320 month_day.month.numeric(), 321 month_day.day_index + 1, 322 }); 323 } 324 325 // the first line of a commit message, with surrounding whitespace trimmed. 326 fn firstLine(message: []const u8) []const u8 { 327 const trimmed = std.mem.trim(u8, message, " \t\r\n"); 328 const nl = std.mem.indexOfScalar(u8, trimmed, '\n'); 329 return if (nl) |i| trimmed[0..i] else trimmed; 330 } 331 332 pub const View = struct { 333 // a vertical stack: the "viewing <ref>" banner on top, then a horizontal 334 // split with the commit list on the left and a diff pane on the right 335 // showing the selected commit's diff. 336 box: wgt.Box(ui.Widget), // vert: [sub_header_index] = banner, [content_index] = split 337 data: *const Self, 338 session: *ui.Session, 339 // the commit whose diff the pane currently shows (index into data.commits). 340 diffed_index: ?usize, 341 342 const sub_header_index: usize = 0; 343 const content_index: usize = 1; 344 // indices within the content box (the horizontal split). 345 const list_index: usize = 0; 346 const diff_index: usize = 1; 347 const list_max_width: usize = 40; 348 const diff_min_width: usize = 40; 349 350 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 351 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 352 errdefer outer.deinit(allocator); 353 354 // the ref banner at the top. 355 { 356 var sub_header = try SubHeader.View.init(allocator, &data.sub_header, session); 357 errdefer sub_header.deinit(allocator); 358 try outer.children.put(allocator, sub_header.getFocus().id, .{ .widget = .{ .repo_sub_header = sub_header }, .rect = null, .min_size = .{ .width = null, .height = 3 } }); 359 } 360 361 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 362 errdefer box.deinit(allocator); 363 364 // the commit list (one focusable row each), plus a "next" link 365 { 366 var list_scroll = blk: { 367 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 368 errdefer list_box.deinit(allocator); 369 for (data.commits) |commit| { 370 // an in-page "ai:" anchor so a commit row is clickable with 371 // js off (the browser follows it, rooting the list there); 372 // with wasm the click just selects it and swaps the diff pane. 373 try addRow(allocator, &list_box, commit.message, try commitRowLink(session.page_arena, data.identity, commit.oid)); 374 } 375 if (data.next_start) |next| { 376 try addRow(allocator, &list_box, "next →", try commitsLink(session.page_arena, data.identity, next, 0)); 377 } 378 if (list_box.children.count() > 0) list_box.getFocus().child_id = list_box.children.keys()[0]; 379 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert, .web_native = !session.is_terminal }); 380 }; 381 errdefer list_scroll.deinit(allocator); 382 try box.children.put(allocator, list_scroll.getFocus().id, .{ .widget = .{ .scroll = list_scroll }, .rect = null, .min_size = .{ .width = list_max_width, .height = null }, .max_size = .{ .width = list_max_width, .height = null } }); 383 } 384 385 // the diff pane — a frame around a scroll of the hunks 386 { 387 var diff_outer = blk: { 388 var diff_scroll = blk2: { 389 var diff_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 390 errdefer diff_inner.deinit(allocator); 391 // fill the pane (content top-left, scroll bars pinned to the 392 // edges) rather than shrinking to the diff content. 393 break :blk2 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = diff_inner }, .{ .direction = .both, .web_native = !session.is_terminal, .fill = true }); 394 }; 395 errdefer diff_scroll.deinit(allocator); 396 var frame = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = .hidden, .direction = .vert }); 397 errdefer frame.deinit(allocator); 398 // the frame's selected child is its scroll, so the focus chain 399 // reaches a hunk (populateDiff points the scroll's inner box at 400 // one), letting focus recovery descend into the diff pane after 401 // it's laid out beside a too-narrow list. 402 frame.getFocus().child_id = diff_scroll.getFocus().id; 403 try frame.children.put(allocator, diff_scroll.getFocus().id, .{ .widget = .{ .scroll = diff_scroll }, .rect = null, .min_size = null }); 404 break :blk frame; 405 }; 406 errdefer diff_outer.deinit(allocator); 407 try box.children.put(allocator, diff_outer.getFocus().id, .{ .widget = .{ .box = diff_outer }, .rect = null, .min_size = .{ .width = diff_min_width, .height = null } }); 408 } 409 410 box.getFocus().child_id = box.children.keys()[list_index]; 411 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 412 413 // focus lives in the split; the banner isn't focusable. 414 outer.getFocus().child_id = outer.children.keys()[content_index]; 415 416 return .{ 417 .box = outer, 418 .data = data, 419 .session = session, 420 .diffed_index = null, 421 }; 422 } 423 424 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !void { 425 var row = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 426 errdefer row.deinit(allocator); 427 row.getFocus().focusable = true; 428 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 429 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null, .max_size = .{ .width = null, .height = 5 } }); 430 } 431 432 // one hunk as a focusable multi-line text box. its lines sit flush (the 433 // inner Text rows have no border); the box's hidden border reserves the 434 // space the double border occupies when focused, so focusing doesn't shift 435 // layout. `lines` are joined into the page arena (text_box borrows it). 436 fn addHunkBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), lines: []const []const u8) !void { 437 if (lines.len == 0) return; 438 const text = try std.mem.join(self.session.page_arena.allocator(), "\n", lines); 439 var tb = try wgt.TextBox(ui.Widget).init(allocator, text, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 440 errdefer tb.deinit(allocator); 441 tb.getFocus().focusable = true; 442 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 443 } 444 445 // a focusable file-path label shown above the first hunk of each file. 446 fn addPathBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), path: []const u8) !void { 447 _ = self; 448 var tb = try wgt.TextBox(ui.Widget).init(allocator, path, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 449 errdefer tb.deinit(allocator); 450 tb.getFocus().focusable = true; 451 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 452 } 453 454 // a focusable window-navigation row ("previous"/"next"). it's a link to this 455 // commit's route at `target_after`, so activating it (the host follows the 456 // "a:" link) reloads the page on the adjacent window — same on TUI and web. 457 fn addNavLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, oid: []const u8, target_after: usize) !void { 458 const link = try commitsLink(self.session.page_arena, self.data.identity, oid, target_after); 459 var tb = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 460 errdefer tb.deinit(allocator); 461 tb.getFocus().focusable = true; 462 tb.getFocus().kind = .{ .custom = link }; 463 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 464 } 465 466 // a focusable row for the top of the diff pane linking to the files tab at 467 // this commit's tree, so its files are always viewable as of this object. 468 fn addViewFilesLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), oid: []const u8) !void { 469 const link = try filesObjectLink(self.session.page_arena, self.data.identity, oid); 470 var tb = try wgt.TextBox(ui.Widget).init(allocator, "view files at this commit", .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 471 errdefer tb.deinit(allocator); 472 tb.getFocus().focusable = true; 473 tb.getFocus().kind = .{ .custom = link }; 474 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 475 } 476 477 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 478 self.box.deinit(allocator); 479 } 480 481 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 482 return &self.box.children.values()[content_index].widget.box; 483 } 484 485 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 486 return &self.contentBox().children.values()[list_index].widget.scroll; 487 } 488 489 fn listBox(self: *View) *wgt.Box(ui.Widget) { 490 return &self.listScroll().child.box; 491 } 492 493 fn diffOuter(self: *View) *wgt.Box(ui.Widget) { 494 return &self.contentBox().children.values()[diff_index].widget.box; 495 } 496 497 fn diffScroll(self: *View) *wgt.Scroll(ui.Widget) { 498 return &self.diffOuter().children.values()[0].widget.scroll; 499 } 500 501 fn diffInner(self: *View) *wgt.Box(ui.Widget) { 502 return &self.diffScroll().child.box; 503 } 504 505 fn diffActive(self: *View) bool { 506 const content = self.contentBox(); 507 const cid = content.getFocus().child_id orelse return false; 508 return content.children.getIndex(cid) == diff_index; 509 } 510 511 // the selected commit's index, or null when the "next" row is selected. 512 fn selectedCommitIndex(self: *View) ?usize { 513 const lb = self.listBox(); 514 const cid = lb.getFocus().child_id orelse return null; 515 const idx = lb.children.getIndex(cid) orelse return null; 516 if (idx >= self.data.commits.len) return null; 517 return idx; 518 } 519 520 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 521 self.clearGrid(); 522 523 // swap the diff pane to the selected commit when it changes. 524 try self.refreshDiff(allocator); 525 526 // mirror the focused commit into the url so it updates as the selection 527 // moves, but only while focus is inside this view (the list or diff). when 528 // focus sits on the header tab, use the page's base /commits route. 529 if (root_focus.grandchild_id) |g| { 530 if (self.box.getFocus().children.contains(g)) { 531 if (self.selectedCommitIndex()) |sel| { 532 // mirror the commit's current diff window so the url stays 533 // linkable (0 for any commit but the windowed start one). 534 if (ui.RoutablePage.repoCommitsRoute(self.data.identity, .object, self.data.commits[sel].oid, self.data.commits[sel].window_start)) |route| 535 self.session.data.current_page = route; 536 } 537 } 538 } 539 540 // the selected list row shows a border (the focused TextBox upgrades it 541 // to a double border itself); the rest stay borderless. 542 const lb = self.listBox(); 543 for (lb.children.keys(), lb.children.values()) |id, *child| { 544 switch (child.widget) { 545 .text_box => |*tb| tb.options.border_style = if (lb.getFocus().child_id == id) .single else .hidden, 546 else => {}, 547 } 548 } 549 550 // the selected hunk (or the "load more" row) shows a single border (the 551 // focused TextBox upgrades it to a double border itself, so it stays 552 // single when focus is on the commit list); the rest keep their 553 // space-reserving hidden border. 554 const inner = self.diffInner(); 555 for (inner.children.keys(), inner.children.values()) |id, *child| { 556 switch (child.widget) { 557 .text_box => |*tb| tb.options.border_style = if (inner.getFocus().child_id == id) .single else .hidden, 558 else => {}, 559 } 560 } 561 562 // cap the list at list_max_width only while the diff pane fits beside it. 563 // the box drops the diff when the width can't hold both minimums, so when 564 // it's that narrow we lift the cap and let the list fill the whole width. 565 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + diff_min_width else true; 566 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 567 568 // stretch the diff pane across the rest of the width so it fills the area 569 // rather than shrinking to its content; its scroll fills the pane. when 570 // too narrow for both, it fills the whole width. 571 if (constraint.max_size.width) |w| { 572 self.contentBox().children.values()[diff_index].min_size = .{ .width = if (both_panes_fit) w - list_max_width else w, .height = null }; 573 } else { 574 self.contentBox().children.values()[diff_index].min_size = .{ .width = diff_min_width, .height = null }; 575 } 576 577 // the web bounds the layout to the browser viewport like the terminal; 578 // each Scroll's web-native mode hands its full content to a real 579 // scrollable element, so we no longer build unbounded here. 580 // 581 // crossing panes only re-selects the content box's child (focusDiff / 582 // focusList); when the window is too narrow to show both, the pane that 583 // held focus is dropped here. the framework recovers focus after the 584 // top-level build by re-deriving it down the selected-child chain, so 585 // there's nothing to fix up afterward. 586 try self.box.build(allocator, constraint, root_focus); 587 } 588 589 fn refreshDiff(self: *View, allocator: std.mem.Allocator) !void { 590 const sel = self.selectedCommitIndex() orelse return; 591 if (self.diffed_index) |d| if (d == sel) return; 592 try self.populateDiff(allocator, sel); 593 self.diffed_index = sel; 594 } 595 596 fn populateDiff(self: *View, allocator: std.mem.Allocator, sel: usize) !void { 597 const commit = self.data.commits[sel]; 598 const inner = self.diffInner(); 599 600 for (inner.children.values()) |*child| child.widget.deinit(allocator); 601 inner.children.clearAndFree(allocator); 602 inner.getFocus().child_id = null; 603 604 // the first row always links to viewing the repo's files at this commit. 605 try self.addViewFilesLink(allocator, inner, commit.oid); 606 607 // a "previous" row and a "next" row at the bottom reload the page on the 608 // adjacent diff window. 609 if (commit.has_prev) try self.addNavLink(allocator, inner, "← previous", commit.oid, commit.window_start -| diff_page); 610 for (commit.hunks) |hunk| { 611 if (hunk.path) |path| try self.addPathBox(allocator, inner, path); 612 try self.addHunkBox(allocator, inner, hunk.lines); 613 } 614 if (commit.has_more) try self.addNavLink(allocator, inner, "next →", commit.oid, commit.window_start + diff_page); 615 616 // point the pane at its first row so focus recovery can land here. 617 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 618 619 // reset the scroll to the top for the newly-shown commit: directly on the 620 // terminal (the wasm offset), and via a version bump on the web (so the 621 // renderer's scroll id changes and JS drops the preserved position). 622 const sc = self.diffScroll(); 623 sc.x = 0; 624 sc.y = 0; 625 sc.getFocus().version +%= 1; 626 } 627 628 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 629 _ = allocator; 630 if (self.diffActive()) { 631 try self.diffInput(key, root_focus); 632 } else { 633 try self.listInput(key, root_focus); 634 } 635 } 636 637 fn listInput(self: *View, key: Key, root_focus: *Focus) !void { 638 // up/down (and the scroll wheel) move the selection a row; page up/down 639 // jump a fixed amount. right/Enter cross into the diff pane. Enter/clicks 640 // on the "next" row become navigation in the host before reaching here. 641 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 642 ui.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 643 return; 644 } 645 switch (key) { 646 .enter => if (self.selectedCommitIndex() != null) 647 try self.focusDiff(root_focus) 648 else if (self.data.next_start) |next| { 649 if (ui.RoutablePage.repoCommitsRoute(self.data.identity, .object, next, 0)) |route| 650 try self.session.navigate(route); 651 }, 652 .arrow_right => try self.focusDiff(root_focus), 653 else => {}, 654 } 655 } 656 657 fn diffInput(self: *View, key: Key, root_focus: *Focus) !void { 658 const sc = self.diffScroll(); 659 switch (key) { 660 // left scrolls horizontally, then leaves for the list once flush left. 661 .arrow_left => { 662 if (sc.x > 0) { 663 sc.x -= 1; 664 self.diffScroll().clampToContent(); 665 } else try self.focusList(root_focus); 666 }, 667 .arrow_right => { 668 sc.x += 1; 669 self.diffScroll().clampToContent(); 670 }, 671 .arrow_up => try self.moveDiff(root_focus, -1), 672 .arrow_down => try self.moveDiff(root_focus, 1), 673 .page_up => try self.pageDiff(root_focus, -10), 674 .page_down => try self.pageDiff(root_focus, 10), 675 .home => try self.jumpDiff(root_focus, false), 676 .end => try self.jumpDiff(root_focus, true), 677 // Enter / a click on a "previous"/"next" row follow its "a:" link in 678 // the host (it reloads the adjacent window), so they don't reach here. 679 .mouse => |mouse| switch (mouse.action) { 680 .scroll => |dir| try self.moveDiff(root_focus, if (dir == .up) -1 else 1), 681 else => {}, 682 }, 683 else => {}, 684 } 685 } 686 687 // move one step in `delta` (+ down, - up). in the terminal, `delta` is a 688 // line count unless there is a new hunk visible (in which case it is a 689 // hunk count). on the web `delta` is always a hunk count. 690 fn moveDiff(self: *View, root_focus: *Focus, delta: isize) !void { 691 const inner = self.diffInner(); 692 const keys = inner.children.keys(); 693 if (keys.len == 0) return; 694 const cur: usize = if (root_focus.grandchild_id) |g| (inner.children.getIndex(g) orelse 0) else 0; 695 const target = @as(isize, @intCast(cur)) + delta; 696 const in_range = target >= 0 and target < @as(isize, @intCast(keys.len)); 697 698 if (self.session.is_terminal) { 699 if (in_range and self.hunkVisible(@intCast(target))) { 700 root_focus.setFocus(keys[@intCast(target)]); 701 return; 702 } 703 704 const sc = self.diffScroll(); 705 sc.y += delta * 5; // magnify because it's a line count 706 self.diffScroll().clampToContent(); 707 if (in_range and self.hunkVisible(@intCast(target))) { 708 root_focus.setFocus(keys[@intCast(target)]); 709 } 710 } else { 711 if (in_range) { 712 root_focus.setFocus(keys[@intCast(target)]); 713 } 714 } 715 } 716 717 // page a fixed number of lines, then focus the leading visible hunk 718 // (bottom-most when paging down, top-most when paging up). in the 719 // terminal, `delta` is a line count, and on the web it's a hunk count. 720 fn pageDiff(self: *View, root_focus: *Focus, delta: isize) !void { 721 if (self.session.is_terminal) { 722 const sc = self.diffScroll(); 723 sc.y += delta * 5; // magnify because it's a line count 724 self.diffScroll().clampToContent(); 725 try self.focusVisible(root_focus, delta > 0); 726 } else { 727 const inner = self.diffInner(); 728 const keys = inner.children.keys(); 729 if (keys.len == 0) return; 730 const cur: isize = if (root_focus.grandchild_id) |g| @intCast(inner.children.getIndex(g) orelse 0) else 0; 731 const target: usize = @intCast(std.math.clamp(cur + delta, 0, @as(isize, @intCast(keys.len - 1)))); 732 root_focus.setFocus(keys[target]); 733 } 734 } 735 736 // jump to the first or last hunk. on the web the browser scrolls to the 737 // focused hunk; on the terminal pin the scroll to the top/bottom too. 738 fn jumpDiff(self: *View, root_focus: *Focus, to_end: bool) !void { 739 const inner = self.diffInner(); 740 const keys = inner.children.keys(); 741 if (keys.len == 0) return; 742 if (self.session.is_terminal) { 743 const sc = self.diffScroll(); 744 sc.y = if (to_end) std.math.maxInt(isize) else 0; 745 self.diffScroll().clampToContent(); 746 } 747 root_focus.setFocus(if (to_end) keys[keys.len - 1] else keys[0]); 748 } 749 750 // whether hunk `index` is at least partly within the diff viewport, per the 751 // last build's layout rects (content space) and the current scroll offset. 752 fn hunkVisible(self: *View, index: usize) bool { 753 const inner = self.diffInner(); 754 const sc = self.diffScroll(); 755 const vp = sc.grid orelse return false; 756 const r = inner.children.values()[index].rect orelse return false; 757 const top = sc.y; 758 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 759 return (r.y + @as(isize, @intCast(r.size.height))) > top and r.y < bottom; 760 } 761 762 // focus the visible hunk at the scroll's leading edge. `prefer_last` picks 763 // the bottom-most visible (for downward motion), else the top-most. 764 fn focusVisible(self: *View, root_focus: *Focus, prefer_last: bool) !void { 765 const inner = self.diffInner(); 766 const sc = self.diffScroll(); 767 const vp = sc.grid orelse return; 768 const top = sc.y; 769 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 770 var chosen: ?usize = null; 771 for (inner.children.keys(), inner.children.values()) |id, *child| { 772 const r = child.rect orelse continue; // content-space layout rect 773 const r_top = r.y; 774 const r_bot = r.y + @as(isize, @intCast(r.size.height)); 775 if (r_bot <= top or r_top >= bottom) continue; // not visible 776 chosen = id; 777 if (!prefer_last) break; // first visible 778 } 779 if (chosen) |id| root_focus.setFocus(id); 780 } 781 782 // enter the diff pane. the host arrives here on right-arrow or Enter from the 783 // list. a diff with no rows can't be entered. setFocus handles the too-narrow 784 // case where the pane isn't laid out yet (it gets selected, then focused after 785 // the next build, landing on its remembered hunk). 786 fn focusDiff(self: *View, root_focus: *Focus) !void { 787 if (self.diffInner().children.count() == 0) return; 788 root_focus.setFocus(self.diffOuter().getFocus().id); 789 } 790 791 // return to the list. 792 fn focusList(self: *View, root_focus: *Focus) !void { 793 root_focus.setFocus(self.listScroll().getFocus().id); 794 } 795 796 pub fn clearGrid(self: *View) void { 797 self.box.clearGrid(); 798 } 799 800 pub fn getGrid(self: View) ?Grid { 801 return self.box.getGrid(); 802 } 803 804 pub fn getFocus(self: *View) *Focus { 805 return self.box.getFocus(); 806 } 807 808 // for the parent's "scroll up at the top jumps to the header" check. in the 809 // diff pane that means the first hunk is focused and the diff can't scroll up 810 // any further; otherwise up-arrow stays in the pane (scrolling or moving 811 // between hunks). when the list holds focus, report its selection directly. 812 pub fn getSelectedIndex(self: *View) ?usize { 813 if (self.diffActive()) { 814 const inner = self.diffInner(); 815 const cid = inner.getFocus().child_id orelse return 1; 816 const first_focused = inner.children.count() > 0 and cid == inner.children.keys()[0]; 817 return if (first_focused and self.diffScroll().y == 0) 0 else 1; 818 } 819 const lb = self.listBox(); 820 const cid = lb.getFocus().child_id orelse return null; 821 return lb.children.getIndex(cid); 822 } 823 }; 824 825 // the "a:" navigation link for the commits page walking from commit `oid` within 826 // `identity`, showing the selected commit's first `after` hunks (0 = default). 827 fn commitsLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8, after: usize) ![]const u8 { 828 const route = ui.RoutablePage.repoCommitsRoute(identity, .object, oid, after) orelse return error.RouteTooLong; 829 const url = try route.urlAlloc(page_arena); 830 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 831 } 832 833 // the "a:" link to the files tab at commit `oid` (an object ref), at its root 834 // directory, within `identity` ("owner/name"). 835 fn filesObjectLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8) ![]const u8 { 836 const route = ui.RoutablePage.repoFilesRoute(identity, .object, oid, "", 0) orelse return error.RouteTooLong; 837 const url = try route.urlAlloc(page_arena); 838 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 839 } 840 841 // the in-page "ai:" anchor for selecting `oid` in `identity`'s commit list. it 842 // points at the same route as commitsLink but the "ai:" prefix keeps wasm clicks 843 // in-page (crossPageLink ignores it); the href is only followed with js off. 844 fn commitRowLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8) ![]const u8 { 845 const route = ui.RoutablePage.repoCommitsRoute(identity, .object, oid, 0) orelse return error.RouteTooLong; 846 const url = try route.urlAlloc(page_arena); 847 return std.fmt.allocPrint(page_arena.allocator(), "ai:{s}", .{url}); 848 } 849