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