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