╭ 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 const list_max_width: usize = 40; 279 const diff_min_width: usize = 40; 280 // how many rows a page up/down jumps, and the scroll-wheel step. 281 const page_rows = 10; 282 283 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 284 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 285 errdefer box.deinit(allocator); 286 287 // the commit list (one focusable row each), plus a "next" link 288 { 289 var list_scroll = blk: { 290 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 291 errdefer list_box.deinit(allocator); 292 for (data.commits) |commit| { 293 try addRow(allocator, &list_box, commit.message, ""); 294 } 295 if (data.next_start) |next| { 296 try addRow(allocator, &list_box, "next", try commitsPageLink(session.page_arena, data.identity, next)); 297 } 298 if (list_box.children.count() > 0) list_box.getFocus().child_id = list_box.children.keys()[0]; 299 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert }); 300 }; 301 errdefer list_scroll.deinit(allocator); 302 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 } }); 303 } 304 305 // the diff pane — a frame around a scroll of the hunks 306 { 307 var diff_outer = blk: { 308 var diff_scroll = blk2: { 309 var diff_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 310 errdefer diff_inner.deinit(allocator); 311 break :blk2 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = diff_inner }, .{ .direction = .both }); 312 }; 313 errdefer diff_scroll.deinit(allocator); 314 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = .hidden, .direction = .vert }); 315 errdefer outer.deinit(allocator); 316 try outer.children.put(allocator, diff_scroll.getFocus().id, .{ .widget = .{ .scroll = diff_scroll }, .rect = null, .min_size = null }); 317 break :blk outer; 318 }; 319 errdefer diff_outer.deinit(allocator); 320 try box.children.put(allocator, diff_outer.getFocus().id, .{ .widget = .{ .box = diff_outer }, .rect = null, .min_size = .{ .width = diff_min_width, .height = null } }); 321 } 322 323 box.getFocus().child_id = box.children.keys()[list_index]; 324 325 return .{ 326 .box = box, 327 .data = data, 328 .session = session, 329 .diffed_index = null, 330 .shown_hunks = 0, 331 .has_more = false, 332 .load_more_id = null, 333 }; 334 } 335 336 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !void { 337 var row = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 338 errdefer row.deinit(allocator); 339 row.getFocus().focusable = true; 340 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 341 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null, .max_size = .{ .width = null, .height = 5 } }); 342 } 343 344 // one hunk as a focusable multi-line text box. its lines sit flush (the 345 // inner Text rows have no border); the box's hidden border reserves the 346 // space the double border occupies when focused, so focusing doesn't shift 347 // layout. `lines` are joined into the page arena (text_box borrows it). 348 fn addHunkBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), lines: []const []const u8) !void { 349 if (lines.len == 0) return; 350 const text = try std.mem.join(self.session.page_arena.allocator(), "\n", lines); 351 var tb = try wgt.TextBox(ui.Widget).init(allocator, text, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 352 errdefer tb.deinit(allocator); 353 tb.getFocus().focusable = true; 354 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 355 } 356 357 // the focusable "load more" row; its kind carries the GET endpoint the web 358 // client fetches (the TUI reopens the repo instead). 359 fn addLoadMore(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), oid: []const u8, after_hunks: usize) !void { 360 const link = try std.fmt.allocPrint(self.session.page_arena.allocator(), "fetch:/_diff/{s}/{s}?after={d}", .{ self.data.identity, oid, after_hunks }); 361 var tb = try wgt.TextBox(ui.Widget).init(allocator, "load more", .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 362 errdefer tb.deinit(allocator); 363 tb.getFocus().focusable = true; 364 tb.getFocus().kind = .{ .custom = link }; 365 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 366 self.load_more_id = tb.getFocus().id; 367 } 368 369 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 370 self.box.deinit(allocator); 371 } 372 373 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 374 return &self.box.children.values()[list_index].widget.scroll; 375 } 376 377 fn listBox(self: *View) *wgt.Box(ui.Widget) { 378 return &self.listScroll().child.box; 379 } 380 381 fn diffOuter(self: *View) *wgt.Box(ui.Widget) { 382 return &self.box.children.values()[diff_index].widget.box; 383 } 384 385 fn diffScroll(self: *View) *wgt.Scroll(ui.Widget) { 386 return &self.diffOuter().children.values()[0].widget.scroll; 387 } 388 389 fn diffInner(self: *View) *wgt.Box(ui.Widget) { 390 return &self.diffScroll().child.box; 391 } 392 393 fn diffActive(self: *View) bool { 394 const cid = self.box.getFocus().child_id orelse return false; 395 return self.box.children.getIndex(cid) == diff_index; 396 } 397 398 // the selected commit's index, or null when the "next" row is selected. 399 fn selectedCommitIndex(self: *View) ?usize { 400 const lb = self.listBox(); 401 const cid = lb.getFocus().child_id orelse return null; 402 const idx = lb.children.getIndex(cid) orelse return null; 403 if (idx >= self.data.commits.len) return null; 404 return idx; 405 } 406 407 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 408 self.clearGrid(); 409 410 // swap the diff pane to the selected commit when it changes. 411 try self.refreshDiff(allocator); 412 413 // mirror the focused commit into the url so it updates as the selection 414 // moves, but only while focus is inside this view (the list or diff). when 415 // focus sits on the header tab, use the page's base /commits route. 416 if (root_focus.grandchild_id) |g| { 417 if (self.box.getFocus().children.contains(g)) { 418 if (self.selectedCommitIndex()) |sel| { 419 if (ui.RoutablePage.repoCommitsRoute(self.data.identity, self.data.commits[sel].oid)) |route| 420 self.session.data.current_page = route; 421 } 422 } 423 } 424 425 // the selected list row shows a border (the focused TextBox upgrades it 426 // to a double border itself); the rest stay borderless. 427 const lb = self.listBox(); 428 for (lb.children.keys(), lb.children.values()) |id, *child| { 429 switch (child.widget) { 430 .text_box => |*tb| tb.options.border_style = if (lb.getFocus().child_id == id) .single else .hidden, 431 else => {}, 432 } 433 } 434 435 // the selected hunk (or the "load more" row) shows a single border (the 436 // focused TextBox upgrades it to a double border itself, so it stays 437 // single when focus is on the commit list); the rest keep their 438 // space-reserving hidden border. 439 const inner = self.diffInner(); 440 for (inner.children.keys(), inner.children.values()) |id, *child| { 441 switch (child.widget) { 442 .text_box => |*tb| tb.options.border_style = if (inner.getFocus().child_id == id) .single else .hidden, 443 else => {}, 444 } 445 } 446 447 // cap the list at list_max_width only while the diff pane fits beside it. 448 // the box drops the diff when the width can't hold both minimums, so when 449 // it's that narrow we lift the cap and let the list fill the whole width. 450 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + diff_min_width else true; 451 self.box.children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 452 453 // web browsers provide scrolling, so let every widget grow to 454 // its natural size instead of clipping inside the diff scroll 455 const build_constraint = if (self.session.is_terminal) constraint else layout.Constraint{ 456 .min_size = .{ .width = null, .height = null }, 457 .max_size = .{ .width = null, .height = null }, 458 }; 459 try self.box.build(allocator, build_constraint, root_focus); 460 461 // if the diff pane is selected but focus is still elsewhere in this view, 462 // the pane was too narrow to lay out when focus crossed over. it's laid 463 // out now, so focus its hunk. 464 if (self.diffActive() and inner.children.count() > 0) { 465 if (root_focus.grandchild_id) |g| { 466 const in_view = self.box.getFocus().children.contains(g); 467 const in_diff = inner.children.contains(g); 468 if (in_view and !in_diff) 469 try root_focus.setFocus(inner.getFocus().child_id orelse inner.children.keys()[0]); 470 } 471 } 472 } 473 474 fn refreshDiff(self: *View, allocator: std.mem.Allocator) !void { 475 const sel = self.selectedCommitIndex() orelse return; 476 if (self.diffed_index) |d| if (d == sel) return; 477 try self.populateDiff(allocator, sel); 478 self.diffed_index = sel; 479 } 480 481 fn populateDiff(self: *View, allocator: std.mem.Allocator, sel: usize) !void { 482 const commit = self.data.commits[sel]; 483 const inner = self.diffInner(); 484 485 for (inner.children.values()) |*child| child.widget.deinit(allocator); 486 inner.children.clearAndFree(allocator); 487 inner.getFocus().child_id = null; 488 self.load_more_id = null; 489 490 for (commit.hunks) |hunk| try self.addHunkBox(allocator, inner, hunk.lines); 491 if (commit.has_more) try self.addLoadMore(allocator, inner, commit.oid, commit.shown_hunks); 492 self.shown_hunks = commit.shown_hunks; 493 self.has_more = commit.has_more; 494 495 const sc = self.diffScroll(); 496 sc.x = 0; 497 sc.y = 0; 498 } 499 500 pub fn input(self: *View, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 501 if (self.diffActive()) { 502 try self.diffInput(allocator, key, root_focus); 503 } else { 504 try self.listInput(key, root_focus); 505 } 506 } 507 508 fn listInput(self: *View, key: inp.Key, root_focus: *Focus) !void { 509 // up/down (and the scroll wheel) move the selection a row; page up/down 510 // jump a fixed amount. right/Enter cross into the diff pane. Enter/clicks 511 // on the "next" row become navigation in the host before reaching here. 512 switch (key) { 513 .arrow_right, .enter => try self.focusDiff(root_focus), 514 .arrow_down => try self.moveSelection(root_focus, 1), 515 .arrow_up => try self.moveSelection(root_focus, -1), 516 .page_down => try self.moveSelection(root_focus, page_rows), 517 .page_up => try self.moveSelection(root_focus, -page_rows), 518 .mouse => |mouse| switch (mouse.action) { 519 .scroll => |dir| try self.moveSelection(root_focus, if (dir == .up) -1 else 1), 520 else => {}, 521 }, 522 else => {}, 523 } 524 } 525 526 fn diffInput(self: *View, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 527 const sc = self.diffScroll(); 528 switch (key) { 529 // left scrolls horizontally, then leaves for the list once flush left. 530 .arrow_left => { 531 if (sc.x > 0) { 532 sc.x -= 1; 533 self.clampDiffScroll(); 534 } else try self.focusList(root_focus); 535 }, 536 .arrow_right => { 537 sc.x += 1; 538 self.clampDiffScroll(); 539 }, 540 .arrow_up => try self.moveDiff(root_focus, -1), 541 .arrow_down => try self.moveDiff(root_focus, 1), 542 .page_up => try self.pageDiff(root_focus, -page_rows), 543 .page_down => try self.pageDiff(root_focus, page_rows), 544 .enter => if (self.focusedIsLoadMore(root_focus)) try self.loadMore(allocator, root_focus), 545 .mouse => |mouse| switch (mouse.action) { 546 .scroll => |dir| try self.moveDiff(root_focus, if (dir == .up) -1 else 1), 547 .press => |btn| if (btn == .left and self.focusedIsLoadMore(root_focus)) try self.loadMore(allocator, root_focus), 548 else => {}, 549 }, 550 else => {}, 551 } 552 } 553 554 // move focus one hunk in `dir` (+1 down, -1 up). if the adjacent hunk is 555 // already visible, just move focus to it — don't scroll. only when it isn't 556 // visible yet do we scroll one line toward it (and focus it once it appears), 557 // so scrolling never skips past an on-screen hunk. when nothing fits to 558 // scroll (e.g. the web, where the browser scrolls the page), the clamp keeps 559 // the offset put and focus simply steps to the adjacent hunk. 560 fn moveDiff(self: *View, root_focus: *Focus, dir: isize) !void { 561 const inner = self.diffInner(); 562 const keys = inner.children.keys(); 563 if (keys.len == 0) return; 564 const cur: usize = if (root_focus.grandchild_id) |g| (inner.children.getIndex(g) orelse 0) else 0; 565 const target = @as(isize, @intCast(cur)) + dir; 566 const in_range = target >= 0 and target < @as(isize, @intCast(keys.len)); 567 568 if (in_range and self.hunkVisible(@intCast(target))) { 569 try root_focus.setFocus(keys[@intCast(target)]); 570 return; 571 } 572 573 const sc = self.diffScroll(); 574 sc.y += dir; 575 self.clampDiffScroll(); 576 if (in_range and self.hunkVisible(@intCast(target))) 577 try root_focus.setFocus(keys[@intCast(target)]); 578 } 579 580 // page a fixed number of lines, then focus the leading visible hunk 581 // (bottom-most when paging down, top-most when paging up). 582 fn pageDiff(self: *View, root_focus: *Focus, delta: isize) !void { 583 const sc = self.diffScroll(); 584 sc.y += delta; 585 self.clampDiffScroll(); 586 try self.focusVisible(root_focus, delta > 0); 587 } 588 589 // whether hunk `index` is at least partly within the diff viewport, per the 590 // last build's layout rects (content space) and the current scroll offset. 591 fn hunkVisible(self: *View, index: usize) bool { 592 const inner = self.diffInner(); 593 const sc = self.diffScroll(); 594 const vp = sc.grid orelse return false; 595 const r = inner.children.values()[index].rect orelse return false; 596 const top = sc.y; 597 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 598 return (r.y + @as(isize, @intCast(r.size.height))) > top and r.y < bottom; 599 } 600 601 // focus the visible hunk at the scroll's leading edge. `prefer_last` picks 602 // the bottom-most visible (for downward motion), else the top-most. 603 fn focusVisible(self: *View, root_focus: *Focus, prefer_last: bool) !void { 604 const inner = self.diffInner(); 605 const sc = self.diffScroll(); 606 const vp = sc.grid orelse return; 607 const top = sc.y; 608 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 609 var chosen: ?usize = null; 610 for (inner.children.keys(), inner.children.values()) |id, *child| { 611 const r = child.rect orelse continue; // content-space layout rect 612 const r_top = r.y; 613 const r_bot = r.y + @as(isize, @intCast(r.size.height)); 614 if (r_bot <= top or r_top >= bottom) continue; // not visible 615 chosen = id; 616 if (!prefer_last) break; // first visible 617 } 618 if (chosen) |id| try root_focus.setFocus(id); 619 } 620 621 fn focusedIsLoadMore(self: *View, root_focus: *Focus) bool { 622 const id = self.load_more_id orelse return false; 623 return root_focus.grandchild_id == id; 624 } 625 626 // keep the diff scroll within its content, using the last build's grids. the 627 // scroll bar's reserved column/row isn't part of the content viewport, so 628 // exclude it (as scrollToRect does) or the last column/row stays unreachable. 629 fn clampDiffScroll(self: *View) void { 630 const sc = self.diffScroll(); 631 const vp = sc.grid orelse return; 632 const content = sc.child.box.grid orelse return; 633 const view_w = vp.size.width - sc.bar_w; 634 const view_h = vp.size.height - sc.bar_h; 635 const max_y: isize = if (content.size.height > view_h) @intCast(content.size.height - view_h) else 0; 636 const max_x: isize = if (content.size.width > view_w) @intCast(content.size.width - view_w) else 0; 637 sc.y = std.math.clamp(sc.y, 0, max_y); 638 sc.x = std.math.clamp(sc.x, 0, max_x); 639 } 640 641 // enter the diff pane by focusing the hunk that was focused last (the box's 642 // child_id remembers it across the trip to the commit list); fall back to the 643 // first hunk on a fresh diff. the host arrives here on right-arrow or Enter 644 // from the list. a diff with no hunks can't be entered. 645 fn focusDiff(self: *View, root_focus: *Focus) !void { 646 const inner = self.diffInner(); 647 if (inner.children.count() == 0) return; 648 const target = inner.getFocus().child_id orelse inner.children.keys()[0]; 649 try root_focus.setFocus(target); 650 if (root_focus.grandchild_id == target) return; 651 // the diff pane wasn't laid out last build (too narrow to show beside 652 // the list), so its hunks aren't in the focus tree yet. select the pane 653 // at the box level, and the hunk will be focused after the next build. 654 self.box.getFocus().child_id = self.diffOuter().getFocus().id; 655 } 656 657 fn focusList(self: *View, root_focus: *Focus) !void { 658 const lb = self.listBox(); 659 const id = lb.getFocus().child_id orelse (if (lb.children.count() > 0) lb.children.keys()[0] else return); 660 try root_focus.setFocus(id); 661 } 662 663 fn moveSelection(self: *View, root_focus: *Focus, delta: isize) !void { 664 const lb = self.listBox(); 665 const keys = lb.children.keys(); 666 if (keys.len == 0) return; 667 const cur_id = lb.getFocus().child_id orelse return; 668 const cur: isize = @intCast(lb.children.getIndex(cur_id) orelse return); 669 const last: isize = @intCast(keys.len - 1); 670 const next: usize = @intCast(std.math.clamp(cur + delta, 0, last)); 671 if (next == @as(usize, @intCast(cur))) return; 672 try root_focus.setFocus(keys[next]); 673 if (lb.children.values()[next].rect) |rect| self.listScroll().scrollToRect(rect); 674 } 675 676 // render the next budget of hunks for the displayed commit and append them. 677 // the TUI reopens the repo here; the wasm path has no repo and the web host 678 // drives "load more" via the GET endpoint instead, so the repo code is 679 // comptime-elided from the wasm build. 680 fn loadMore(self: *View, allocator: std.mem.Allocator, root_focus: *Focus) !void { 681 // the wasm build has no repo; it drives "load more" via the GET endpoint. 682 if (!builtin.cpu.arch.isWasm()) try self.loadMoreNative(allocator, root_focus); 683 } 684 685 fn loadMoreNative(self: *View, allocator: std.mem.Allocator, root_focus: *Focus) !void { 686 const io = self.session.io orelse return; 687 const repos_dir = self.session.repos_dir orelse return; 688 const sel = self.diffed_index orelse return; 689 const commit = self.data.commits[sel]; 690 if (commit.oid.len != xit.hash.hexLen(.sha1)) return; 691 692 const aa = self.session.page_arena.allocator(); 693 const gpa = self.session.page_arena.child_allocator; 694 const repo_path = try std.fs.path.join(aa, &.{ repos_dir, self.data.repo_dir_hex }); 695 var repo = rp.Repo(.xit, .{}).open(io, gpa, .{ .path = repo_path }) catch return; 696 defer repo.deinit(io, gpa); 697 698 var oid: [xit.hash.hexLen(.sha1)]u8 = undefined; 699 @memcpy(&oid, commit.oid); 700 const rendered = renderCommitDiff(io, gpa, aa, &repo, oid, self.shown_hunks, diff_budget) catch return; 701 702 const inner = self.diffInner(); 703 if (self.load_more_id) |id| { 704 if (inner.children.fetchOrderedRemove(id)) |kv| { 705 var w = kv.value.widget; 706 w.deinit(allocator); 707 } 708 self.load_more_id = null; 709 } 710 // focus the last already-shown hunk (the one just above where "load 711 // more" was). it's already in the focus tree from the last build, so the 712 // focus lands; the freshly-appended hunks aren't in the tree until the 713 // next build, so focusing one here would silently no-op. the user scrolls 714 // down into the new hunks from here. 715 const shown = inner.children.count(); // old hunk count ("load more" removed) 716 for (rendered.hunks) |hunk| try self.addHunkBox(allocator, inner, hunk.lines); 717 self.shown_hunks = rendered.shown_hunks; 718 self.has_more = rendered.has_more; 719 if (rendered.has_more) try self.addLoadMore(allocator, inner, commit.oid, rendered.shown_hunks); 720 if (shown > 0) try root_focus.setFocus(inner.children.keys()[shown - 1]); 721 } 722 723 pub fn clearGrid(self: *View) void { 724 self.box.clearGrid(); 725 } 726 727 pub fn getGrid(self: View) ?Grid { 728 return self.box.getGrid(); 729 } 730 731 pub fn getFocus(self: *View) *Focus { 732 return self.box.getFocus(); 733 } 734 735 // for the parent's "scroll up at the top jumps to the header" check. in the 736 // diff pane that means the first hunk is focused and the diff can't scroll up 737 // any further; otherwise up-arrow stays in the pane (scrolling or moving 738 // between hunks). when the list holds focus, report its selection directly. 739 pub fn getSelectedIndex(self: *View) ?usize { 740 if (self.diffActive()) { 741 const inner = self.diffInner(); 742 const cid = inner.getFocus().child_id orelse return 1; 743 const first_focused = inner.children.count() > 0 and cid == inner.children.keys()[0]; 744 return if (first_focused and self.diffScroll().y == 0) 0 else 1; 745 } 746 const lb = self.listBox(); 747 const cid = lb.getFocus().child_id orelse return null; 748 return lb.children.getIndex(cid); 749 } 750 }; 751 752 // the "a:" link for the commits page starting at `start_oid` within `identity`. 753 fn commitsPageLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, start_oid: []const u8) ![]const u8 { 754 const route = ui.RoutablePage.repoCommitsRoute(identity, start_oid) orelse return error.RouteTooLong; 755 const url = try route.urlAlloc(page_arena); 756 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 757 } 758