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