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