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