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