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