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