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