╭ 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 Key = xitui.input.Key; 12 const Grid = xitui.grid.Grid; 13 const Focus = xitui.focus.Focus; 14 const inp = @import("../input.zig"); 15 16 // how many commits a page shows before a "next" link appears. 17 const page_size = 20; 18 // how many diff hunks one window of a commit's diff shows; "next"/"previous" 19 // move to the adjacent window. 20 const diff_page = 10; 21 // the largest commit message a log page's detail view reads; a longer one is 22 // cut here, with the message page carrying the whole thing. 23 pub const max_message_size = 2 * 1024; 24 // the same for the message page, which only reads the one commit. 25 const max_full_message_size = 100 * 1024; 26 27 pub const Hunk = struct { 28 path: ?[]const u8 = null, // the file this hunk belongs to 29 lines: []const []const u8, 30 }; 31 32 // one commit on the current page, with its diff against its first parent 33 // pre-rendered up to the budget so the web client can show it without a repo. 34 pub const Commit = struct { 35 oid: []const u8, 36 date: []const u8, // "YYYY-MM-DD" 37 message: []const u8, // trimmed, may be multi-line 38 // whether `message` is only the first line of a message too big to read. 39 message_truncated: bool = false, 40 author: ui.Author = .unknown, 41 hunks: []const Hunk, 42 // the hunk index this window starts at (0 = the first window). 43 window_start: usize, 44 // whether hunks exist before this window / after it. 45 has_prev: bool, 46 has_more: bool, 47 }; 48 49 // "owner/name", so the view can build /repo/owner/name/commits/... links. 50 identity: []const u8, 51 // the resolved ref/oid this log walks from (the default branch when the route 52 // didn't name one), so the page can canonicalize its url to it. 53 ref_or_oid: ui.RoutablePage.RefOrOid, 54 ref_or_oid_value: []const u8, 55 commits: []const Commit, 56 // the first oid of the next page, or null when this is the last page. 57 next_start: ?[]const u8, 58 // what the pane shows for the commit the log walks from. 59 content: Content = .{ .diff = .{} }, 60 // the "viewing <ref> <value>" banner shown above the log. 61 header: Header, 62 63 const Self = @This(); 64 65 // the diff and the message are alternatives, so a filtered diff can't also be 66 // a message. the message is read whole, however big, since it's all its pane 67 // shows. 68 pub const Content = union(enum) { 69 diff: struct { 70 // the file the top commit's diff is filtered to ("" = every file). 71 path: []const u8 = "", 72 }, 73 message, 74 }; 75 76 // walk the log for an opened repo. generic over the repo's backend and hash 77 // kind so the oid buffers and diff types it threads through match the repo's 78 // opts. `content` is what the walk root's pane shows, the only commit any of 79 // it applies to. walks with the arena's backing allocator (transient; the 80 // commits we keep are duped into the page arena so they outlive it). 81 pub fn init( 82 comptime repo_kind: rp.RepoKind, 83 comptime repo_opts: rp.RepoOpts(repo_kind), 84 arena: *std.heap.ArenaAllocator, 85 repo: *rp.Repo(repo_kind, repo_opts), 86 io: std.Io, 87 gpa: std.mem.Allocator, 88 // the admin db's moment, for resolving author emails to user names (null 89 // in local mode, which has no users) 90 admin_moment: ?evt.AdminDB.HashMap(.read_only), 91 identity: []const u8, 92 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 93 requested_value: []const u8, 94 content: ui.RoutablePage.RepoCommitsRoute.Content, 95 ) !Self { 96 const aa = arena.allocator(); 97 const hex_len = ui.ResolvedRefOrOid(repo_kind, repo_opts).hex_len; 98 99 // the walk root's message replaces its diff, so it's read whole and its 100 // hunks aren't rendered. the window and the filter are its diff's. 101 const root_message = std.meta.activeTag(content) == .message; 102 const root_start: usize = switch (content) { 103 .diff => |d| d.start, 104 .message => 0, 105 }; 106 const root_path: []const u8 = switch (content) { 107 .diff => |*d| d.path.slice(), 108 .message => "", 109 }; 110 111 // resolve the requested ref (or the default branch) to the commit oid to 112 // walk from. an explicitly named ref that doesn't resolve is a bad url 113 // (NotFound -> 404); the default-branch path falls through to empty. 114 const resolved = (try ui.ResolvedRefOrOid(repo_kind, repo_opts).init(repo, io, aa, requested_ref_or_oid, requested_value)) orelse { 115 if (requested_ref_or_oid != null) return error.NotFound; 116 return emptyResult(aa, identity, .branch, requested_value, content); 117 }; 118 var start_arr = [1][hex_len]u8{resolved.oid}; 119 const start_oids: []const [hex_len]u8 = start_arr[0..1]; 120 121 // collect this page's commit metadata, plus a peek at the one after it (its 122 // oid is the next page's start). the diff for each is rendered afterward, so 123 // the log iterator is closed before opening per-commit diff iterators. 124 var buf: [page_size]Commit = undefined; 125 var oids: [page_size][hex_len]u8 = undefined; 126 var count: usize = 0; 127 var next_start: ?[]const u8 = null; 128 { 129 var iter = repo.log(io, gpa, start_oids) catch return emptyResult(aa, identity, resolved.ref_or_oid, resolved.value, content); 130 defer iter.deinit(); 131 while (try iter.next(gpa)) |commit_object| { 132 defer commit_object.deinit(); 133 if (count == page_size) { 134 next_start = try aa.dupe(u8, &commit_object.oid); 135 break; 136 } 137 const md = commit_object.content.commit.metadata; 138 @memcpy(&oids[count], &commit_object.oid); 139 // only the message the pane shows is read past the log's limit. 140 const text, const truncated = try readMessage(repo_kind, repo_opts, aa, commit_object, if (root_message and count == 0) max_full_message_size else max_message_size); 141 buf[count] = .{ 142 .oid = try aa.dupe(u8, &commit_object.oid), 143 .date = try formatDate(aa, md.timestamp), 144 .message = text, 145 .message_truncated = truncated, 146 .author = try ui.Author.init(admin_moment, arena, md.author orelse ""), 147 .hunks = &.{}, 148 .window_start = 0, 149 .has_prev = false, 150 .has_more = false, 151 }; 152 count += 1; 153 } 154 } 155 156 // render each commit's diff (best effort: a failed diff leaves it empty). 157 // the diff machinery isn't wasm-clean and the wasm client never runs it (it 158 // renders from the snapshot), so gate it out of the wasm build. 159 if (!builtin.cpu.arch.isWasm()) { 160 for (buf[0..count], oids[0..count], 0..) |*commit, oid, i| { 161 if (root_message and i == 0) continue; 162 // the walk root shows the window the url asks for and its filter; 163 // the rest show their first window, unfiltered. 164 const window_start = if (i == 0) root_start else 0; 165 const rendered = renderCommitDiff(repo_kind, repo_opts, io, gpa, aa, repo, oid, window_start, diff_page, if (i == 0) root_path else "") catch 166 RenderedDiff{ .hunks = &.{}, .has_prev = false, .has_more = false }; 167 commit.hunks = rendered.hunks; 168 commit.window_start = window_start; 169 commit.has_prev = rendered.has_prev; 170 commit.has_more = rendered.has_more; 171 } 172 } 173 174 return .{ 175 .identity = try aa.dupe(u8, identity), 176 .ref_or_oid = resolved.ref_or_oid, 177 .ref_or_oid_value = resolved.value, 178 .commits = try aa.dupe(Commit, buf[0..count]), 179 .next_start = next_start, 180 .content = try pageContent(aa, content), 181 .header = try Header.init(aa, resolved.ref_or_oid, resolved.value), 182 }; 183 } 184 185 // an empty listing pinned to a ref, for the wasm / no-repo / unresolved paths. 186 pub fn emptyResult(aa: std.mem.Allocator, identity: []const u8, ref_or_oid: ui.RoutablePage.RefOrOid, value: []const u8, content: ui.RoutablePage.RepoCommitsRoute.Content) !Self { 187 return .{ 188 .identity = try aa.dupe(u8, identity), 189 .ref_or_oid = ref_or_oid, 190 .ref_or_oid_value = try aa.dupe(u8, value), 191 .commits = &.{}, 192 .next_start = null, 193 .content = try pageContent(aa, content), 194 .header = try Header.init(aa, ref_or_oid, value), 195 }; 196 } 197 198 // the page's content for a route's, duped into `aa`. the diff window doesn't 199 // carry over: each commit holds the one its pane shows as `window_start`. 200 fn pageContent(aa: std.mem.Allocator, content: ui.RoutablePage.RepoCommitsRoute.Content) !Content { 201 return switch (content) { 202 .diff => |d| .{ .diff = .{ .path = try aa.dupe(u8, d.path.slice()) } }, 203 .message => .message, 204 }; 205 } 206 207 const RenderedDiff = struct { 208 hunks: []const Hunk, 209 has_prev: bool, 210 has_more: bool, 211 }; 212 213 // render the window [start, start+len) of a commit's diff against its first 214 // parent into `arena`-owned hunks. has_prev/has_more flag adjacent windows. 215 // a non-empty `path` filters to that file, so the window indexes its hunks. 216 fn renderCommitDiff( 217 comptime repo_kind: rp.RepoKind, 218 comptime repo_opts: rp.RepoOpts(repo_kind), 219 io: std.Io, 220 gpa: std.mem.Allocator, 221 arena: std.mem.Allocator, 222 repo: *rp.Repo(repo_kind, repo_opts), 223 oid: [xit.hash.hexLen(repo_opts.hash)]u8, 224 start: usize, 225 len: usize, 226 path: []const u8, 227 ) !RenderedDiff { 228 const empty = RenderedDiff{ .hunks = &.{}, .has_prev = false, .has_more = false }; 229 230 // load the commit so we can diff it against its first parent. 231 var start_oids = [_][xit.hash.hexLen(repo_opts.hash)]u8{oid}; 232 var commit_iter = repo.log(io, gpa, start_oids[0..1]) catch return empty; 233 defer commit_iter.deinit(); 234 const commit_object = (commit_iter.next(gpa) catch return empty) orelse return empty; 235 defer commit_object.deinit(); 236 237 const parent_maybe = commit_object.content.commit.metadata.firstParent(); 238 239 var tree_diff = repo.treeDiff(io, gpa, parent_maybe, &commit_object.oid) catch return empty; 240 defer tree_diff.deinit(); 241 242 var file_iter = repo.filePairs(io, gpa, .{ .tree = .{ .tree_diff = &tree_diff } }) catch return empty; 243 244 var hunks: std.ArrayList(Hunk) = .empty; 245 var index: usize = 0; // running hunk index across all files 246 var has_more = false; 247 248 file_loop: while (file_iter.next() catch null) |pair_val| { 249 var pair = pair_val; 250 defer pair.deinit(); 251 252 if (path.len != 0 and !std.mem.eql(u8, pair.path, path)) continue; 253 254 var hunk_iter = df.HunkIterator(repo_kind, repo_opts).init(gpa, &pair.a, &pair.b) catch continue; 255 defer hunk_iter.deinit(gpa); 256 257 // the path label rides on the first of this file's hunks we actually show. 258 var path_attached = false; 259 while (try hunk_iter.next(gpa)) |hunk_val| { 260 var hunk = hunk_val; 261 defer hunk.deinit(gpa); 262 263 const i = index; 264 index += 1; 265 if (i < start) continue; // before this window 266 if (hunks.items.len >= len) { 267 has_more = true; 268 break :file_loop; 269 } 270 var lines: std.ArrayList([]const u8) = .empty; 271 try appendHunkLines(repo_kind, repo_opts, arena, &lines, &hunk_iter, &hunk); 272 try hunks.append(arena, .{ 273 .path = if (path_attached) null else try arena.dupe(u8, pair.path), 274 .lines = try lines.toOwnedSlice(arena), 275 }); 276 path_attached = true; 277 } 278 } 279 280 return .{ .hunks = try hunks.toOwnedSlice(arena), .has_prev = start > 0, .has_more = has_more }; 281 } 282 283 // append a hunk's header and its edit lines, each prefixed with a right-aligned 284 // line number in a column wide enough for the hunk's largest number, then a space 285 fn appendHunkLines( 286 comptime repo_kind: rp.RepoKind, 287 comptime repo_opts: rp.RepoOpts(repo_kind), 288 arena: std.mem.Allocator, 289 lines: *std.ArrayList([]const u8), 290 hunk_iter: *df.HunkIterator(repo_kind, repo_opts), 291 hunk: *df.Hunk(repo_kind, repo_opts), 292 ) !void { 293 var max_num: usize = 1; 294 for (hunk.edits.items) |edit| { 295 const n = editLineNum(edit) + 1; 296 if (n > max_num) max_num = n; 297 } 298 const width = std.fmt.count("{d}", .{max_num}); 299 // a run of spaces sliced to each line's leading pad. 300 const indent = try arena.alloc(u8, width); 301 @memset(indent, ' '); 302 303 for (hunk.edits.items) |edit| { 304 const text = switch (edit) { 305 .eql => |e| try hunk_iter.line_iter_b.get(e.new_line.num), 306 .ins => |e| try hunk_iter.line_iter_b.get(e.new_line.num), 307 .del => |e| try hunk_iter.line_iter_a.get(e.old_line.num), 308 }; 309 defer switch (edit) { 310 .eql, .ins => hunk_iter.line_iter_b.free(text), 311 .del => hunk_iter.line_iter_a.free(text), 312 }; 313 const prefix: u8 = switch (edit) { 314 .eql => ' ', 315 .ins => '+', 316 .del => '-', 317 }; 318 const num_str = try std.fmt.allocPrint(arena, "{d}", .{editLineNum(edit) + 1}); 319 try lines.append(arena, try std.fmt.allocPrint(arena, "{s}{s} {c}{s}", .{ 320 indent[0 .. width - num_str.len], num_str, prefix, text, 321 })); 322 } 323 } 324 325 // the line number to show for an edit: the new-side number for kept and inserted 326 // lines, the old-side number for deletions (0-based in the diff machinery). 327 fn editLineNum(edit: df.Edit) usize { 328 return switch (edit) { 329 .eql => |e| e.new_line.num, 330 .ins => |e| e.new_line.num, 331 .del => |e| e.old_line.num, 332 }; 333 } 334 335 // "YYYY-MM-DD" for a unix timestamp. 336 fn formatDate(arena: std.mem.Allocator, timestamp: u64) ![]const u8 { 337 const epoch_secs = std.time.epoch.EpochSeconds{ .secs = timestamp }; 338 const year_day = epoch_secs.getEpochDay().calculateYearDay(); 339 const month_day = year_day.calculateMonthDay(); 340 return std.fmt.allocPrint(arena, "{d:0>4}-{d:0>2}-{d:0>2}", .{ 341 year_day.year, 342 month_day.month.numeric(), 343 month_day.day_index + 1, 344 }); 345 } 346 347 // the commit message, trimmed and read into `aa`, plus whether it ran past 348 // `limit` and was cut short there. 349 fn readMessage( 350 comptime repo_kind: rp.RepoKind, 351 comptime repo_opts: rp.RepoOpts(repo_kind), 352 aa: std.mem.Allocator, 353 commit_object: *xit.object.Object(repo_kind, repo_opts), 354 limit: usize, 355 ) !struct { []const u8, bool } { 356 var message: std.ArrayList(u8) = .empty; 357 // a message past the limit keeps the bytes read so far 358 const truncated = if (commit_object.readMessage(aa, &message, .limited(limit))) |_| 359 false 360 else |err| switch (err) { 361 error.StreamTooLong => true, 362 else => |e| return e, 363 }; 364 // the cut lands wherever the limit falls, so a truncated message keeps 365 // only its whole lines: a line break can't fall inside a codepoint, and 366 // the widgets need valid utf-8. a first line past the limit is instead 367 // cut at the last codepoint boundary. 368 const text = if (truncated) 369 (if (std.mem.lastIndexOfScalar(u8, message.items, '\n')) |nl| message.items[0..nl] else trimIncompleteCodepoint(message.items)) 370 else 371 message.items; 372 return .{ std.mem.trim(u8, text, " \t\r\n"), truncated }; 373 } 374 375 /// drop any incomplete UTF data from the end of a byte array 376 fn trimIncompleteCodepoint(bytes: []const u8) []const u8 { 377 var i = bytes.len; 378 while (i > 0 and bytes.len - i < 4) { 379 i -= 1; 380 const byte = bytes[i]; 381 if (byte & 0b1100_0000 == 0b1000_0000) continue; // continuation byte 382 const seq_len = std.unicode.utf8ByteSequenceLength(byte) catch return bytes; 383 return if (i + seq_len > bytes.len) bytes[0..i] else bytes; 384 } 385 return bytes; 386 } 387 388 // a focusable, word-wrapping box holding a commit message. `bottom_label` 389 // marks a message the page only shows part of ("" when it's whole). 390 fn messageBox(allocator: std.mem.Allocator, message: []const u8, bottom_label: []const u8) !wgt.TextBox(ui.Widget) { 391 var tb = try wgt.TextBox(ui.Widget).init(allocator, message, .{ 392 .border_style = .single, 393 .rounded_corners = true, 394 .wrap_kind = .word, 395 .label = " message ", 396 .bottom_label = bottom_label, 397 }); 398 tb.getFocus().focusable = true; 399 return tb; 400 } 401 402 // the first line of a commit message, for the one-row list entries. 403 fn firstLine(message: []const u8) []const u8 { 404 const nl = std.mem.indexOfScalar(u8, message, '\n'); 405 return if (nl) |i| std.mem.trimEnd(u8, message[0..i], " \t\r") else message; 406 } 407 408 pub const View = struct { 409 // a vertical stack: the "viewing <ref>" banner on top, then a horizontal 410 // split with the commit list on the left and a diff pane on the right 411 // showing the selected commit's diff. 412 box: wgt.Box(ui.Widget), // vert: [header_index] = banner, [content_index] = split 413 data: *const Self, 414 session: *ui.Session, 415 // the commit whose diff the pane currently shows (index into data.commits). 416 diffed_index: ?usize, 417 418 const header_index: usize = 0; 419 const content_index: usize = 1; 420 // indices within the content box (the horizontal split). 421 const list_index: usize = 0; 422 const diff_index: usize = 1; 423 const list_max_width: usize = 40; 424 const diff_min_width: usize = 40; 425 426 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 427 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 428 errdefer outer.deinit(allocator); 429 430 // the ref banner at the top. 431 { 432 var header = try Header.View.init(allocator, &data.header, session); 433 errdefer header.deinit(allocator); 434 try outer.children.put(allocator, header.getFocus().id, .{ .widget = .{ .repo_commits_header = header }, .rect = null, .min_size = .{ .width = null, .height = 3 } }); 435 } 436 437 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 438 errdefer box.deinit(allocator); 439 440 // the commit list (one focusable row each), plus a "next" link 441 { 442 var list_scroll = blk: { 443 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert, .stretch = true }); 444 errdefer list_box.deinit(allocator); 445 for (data.commits) |commit| { 446 // an in-page "ai:" anchor so a commit row is clickable with 447 // js off (the browser follows it, rooting the list there); 448 // with wasm the click just selects it and swaps the diff pane. 449 try addRow(allocator, &list_box, firstLine(commit.message), try commitRowLink(session.page_arena, data.identity, commit.oid, "")); 450 } 451 if (data.next_start) |next| { 452 try addRow(allocator, &list_box, "next →", try commitsLink(session.page_arena, data.identity, next, 0, "")); 453 } 454 if (list_box.children.count() > 0) list_box.getFocus().child_id = list_box.children.keys()[0]; 455 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 456 }; 457 errdefer list_scroll.deinit(allocator); 458 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 } }); 459 } 460 461 // the diff pane — a frame around a scroll of the hunks 462 { 463 var diff_outer = blk: { 464 var diff_scroll = blk2: { 465 var diff_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 466 errdefer diff_inner.deinit(allocator); 467 // fill the pane (content top-left, scroll bars pinned to the 468 // edges) rather than shrinking to the diff content. 469 break :blk2 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = diff_inner }, .{ .direction = .both, .web_native = !session.is_terminal, .fill = true }); 470 }; 471 errdefer diff_scroll.deinit(allocator); 472 var frame = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = .hidden, .direction = .vert }); 473 errdefer frame.deinit(allocator); 474 // the frame's selected child is its scroll, so the focus chain 475 // reaches a hunk (populateDiff points the scroll's inner box at 476 // one), letting focus recovery descend into the diff pane after 477 // it's laid out beside a too-narrow list. 478 frame.getFocus().child_id = diff_scroll.getFocus().id; 479 try frame.children.put(allocator, diff_scroll.getFocus().id, .{ .widget = .{ .scroll = diff_scroll }, .rect = null, .min_size = null }); 480 break :blk frame; 481 }; 482 errdefer diff_outer.deinit(allocator); 483 try box.children.put(allocator, diff_outer.getFocus().id, .{ .widget = .{ .box = diff_outer }, .rect = null, .min_size = .{ .width = diff_min_width, .height = null } }); 484 } 485 486 box.getFocus().child_id = box.children.keys()[list_index]; 487 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 488 489 // focus lives in the split; the banner isn't focusable. 490 outer.getFocus().child_id = outer.children.keys()[content_index]; 491 492 return .{ 493 .box = outer, 494 .data = data, 495 .session = session, 496 .diffed_index = null, 497 }; 498 } 499 500 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !void { 501 var row = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 502 errdefer row.deinit(allocator); 503 row.getFocus().focusable = true; 504 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 505 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null, .max_size = .{ .width = null, .height = 5 } }); 506 } 507 508 // one hunk as a focusable multi-line text box. its lines sit flush (the 509 // inner Text rows have no border). `lines` are joined into the page arena 510 // (text_box borrows it). 511 fn addHunkBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), lines: []const []const u8) !void { 512 if (lines.len == 0) return; 513 const text = try std.mem.join(self.session.page_arena.allocator(), "\n", lines); 514 var tb = try wgt.TextBox(ui.Widget).init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 515 errdefer tb.deinit(allocator); 516 tb.getFocus().focusable = true; 517 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 518 } 519 520 // a focusable file-path label shown above the first hunk of each file. it 521 // links to this page filtered to that file, so activating it navigates 522 // there. 523 fn addPathBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), path: []const u8, oid: []const u8) !void { 524 const link = try commitsLink(self.session.page_arena, self.data.identity, oid, 0, path); 525 var tb = try wgt.TextBox(ui.Widget).init(allocator, path, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 526 errdefer tb.deinit(allocator); 527 tb.getFocus().focusable = true; 528 tb.getFocus().kind = .{ .custom = link }; 529 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 530 } 531 532 // a focusable window-navigation row ("previous"/"next"). it's a link to this 533 // commit's route at `target_start`, so activating it (the host follows the 534 // "a:" link) reloads the page on the adjacent window — same on TUI and web. 535 fn addNavLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, oid: []const u8, target_start: usize, path: []const u8) !void { 536 const link = try commitsLink(self.session.page_arena, self.data.identity, oid, target_start, path); 537 var tb = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 538 errdefer tb.deinit(allocator); 539 tb.getFocus().focusable = true; 540 tb.getFocus().kind = .{ .custom = link }; 541 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 542 } 543 544 // a focusable row for the top of the diff pane linking to the files tab at 545 // this commit's tree, so its files are always viewable as of this object. 546 fn addViewFilesLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), oid: []const u8) !void { 547 const link = try filesObjectLink(self.session.page_arena, self.data.identity, oid); 548 var tb = try wgt.TextBox(ui.Widget).init(allocator, "view files at this commit", .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 549 errdefer tb.deinit(allocator); 550 tb.getFocus().focusable = true; 551 tb.getFocus().kind = .{ .custom = link }; 552 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 553 } 554 555 // how much of the message a pane's box holds: a truncated preview links to 556 // the pane holding the whole thing, which is that link's destination. 557 const MessageBox = enum { preview, whole }; 558 559 // the selected commit's message. 560 fn addMessageBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), commit: Commit, kind: MessageBox) !void { 561 // a truncated message keeps its box even with no whole line to show, 562 // since the box is what links to the whole thing. 563 if (commit.message.len == 0 and !commit.message_truncated) return; 564 const cut_short = commit.message_truncated and kind == .preview; 565 var tb = try messageBox(allocator, commit.message, if (cut_short) " click or press enter to see more " else ""); 566 errdefer tb.deinit(allocator); 567 if (cut_short) tb.getFocus().kind = .{ .custom = try messageLink(self.session.page_arena, self.data.identity, commit.oid) }; 568 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 569 } 570 571 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 572 self.box.deinit(allocator); 573 } 574 575 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 576 return &self.box.children.values()[content_index].widget.box; 577 } 578 579 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 580 return &self.contentBox().children.values()[list_index].widget.scroll; 581 } 582 583 fn listBox(self: *View) *wgt.Box(ui.Widget) { 584 return &self.listScroll().child.box; 585 } 586 587 fn diffOuter(self: *View) *wgt.Box(ui.Widget) { 588 return &self.contentBox().children.values()[diff_index].widget.box; 589 } 590 591 fn diffScroll(self: *View) *wgt.Scroll(ui.Widget) { 592 return &self.diffOuter().children.values()[0].widget.scroll; 593 } 594 595 fn diffInner(self: *View) *wgt.Box(ui.Widget) { 596 return &self.diffScroll().child.box; 597 } 598 599 fn diffActive(self: *View) bool { 600 const content = self.contentBox(); 601 const cid = content.getFocus().child_id orelse return false; 602 return content.children.getIndex(cid) == diff_index; 603 } 604 605 // what the pane shows for the commit at `sel`. the page's content only 606 // applies to the commit it walks from; the rest show their plain diff. 607 fn paneContent(self: *View, sel: usize) Self.Content { 608 return if (sel == 0) self.data.content else .{ .diff = .{} }; 609 } 610 611 // the selected commit's index, or null when the "next" row is selected. 612 fn selectedCommitIndex(self: *View) ?usize { 613 const lb = self.listBox(); 614 const cid = lb.getFocus().child_id orelse return null; 615 const idx = lb.children.getIndex(cid) orelse return null; 616 if (idx >= self.data.commits.len) return null; 617 return idx; 618 } 619 620 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 621 self.clearGrid(); 622 623 // swap the diff pane to the selected commit when it changes. 624 try self.refreshDiff(allocator); 625 626 // mirror the focused commit into the url so it updates as the selection 627 // moves, but only while focus is inside this view (the list or diff). when 628 // focus sits on the header tab, use the page's base /commits route. 629 if (root_focus.grandchild_id) |g| { 630 if (self.box.getFocus().children.contains(g)) { 631 if (self.selectedCommitIndex()) |sel| { 632 const oid = self.data.commits[sel].oid; 633 const window_start = self.data.commits[sel].window_start; 634 // mirror the commit's current diff window so the url stays 635 // linkable (0 for any commit but the windowed start one). 636 // selecting another commit leaves the message behind, like 637 // it leaves the path filter behind. 638 const mirrored = switch (self.paneContent(sel)) { 639 .message => ui.RoutablePage.repoCommitMessageRoute(self.data.identity, .object, oid), 640 .diff => |d| ui.RoutablePage.repoCommitsRoute(self.data.identity, .object, oid, window_start, d.path), 641 }; 642 if (mirrored) |route| self.session.data.current_page = route; 643 } 644 } 645 } 646 647 // the selected list row shows a border (the focused TextBox upgrades it 648 // to a double border itself); the rest stay borderless. 649 const lb = self.listBox(); 650 for (lb.children.keys(), lb.children.values()) |id, *child| { 651 switch (child.widget) { 652 .text_box => |*tb| tb.options.border_style = if (lb.getFocus().child_id == id) .single else .hidden, 653 else => {}, 654 } 655 } 656 657 // cap the list at list_max_width only while the diff pane fits beside it. 658 // the box drops the diff when the width can't hold both minimums, so when 659 // it's that narrow we lift the cap and let the list fill the whole width. 660 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + diff_min_width else true; 661 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 662 663 // stretch the diff pane across the rest of the width so it fills the area 664 // rather than shrinking to its content; its scroll fills the pane. when 665 // too narrow for both, it fills the whole width. 666 const diff_width: usize = if (constraint.max_size.width) |w| 667 (if (both_panes_fit) w - list_max_width else w) 668 else 669 diff_min_width; 670 self.contentBox().children.values()[diff_index].min_size = .{ .width = diff_width, .height = null }; 671 672 // the message is the pane's only wrapping row, and wrapping needs a 673 // bounded width, which the pane's scroll doesn't grant (it scrolls 674 // horizontally too). cap it to the pane, leaving room for the border 675 // and the scrollbar column. re-capped each build so it tracks resizes. 676 for (self.diffInner().children.values()) |*child| switch (child.widget) { 677 .text_box => |text_box| if (text_box.options.wrap_kind == .word) { 678 child.max_size = .{ .width = diff_width -| 3, .height = null }; 679 }, 680 else => {}, 681 }; 682 683 // the web bounds the layout to the browser viewport like the terminal; 684 // each Scroll's web-native mode hands its full content to a real 685 // scrollable element, so we no longer build unbounded here. 686 // 687 // crossing panes only re-selects the content box's child (focusDiff / 688 // focusList); when the window is too narrow to show both, the pane that 689 // held focus is dropped here. the framework recovers focus after the 690 // top-level build by re-deriving it down the selected-child chain, so 691 // there's nothing to fix up afterward. 692 try self.box.build(allocator, constraint, root_focus); 693 } 694 695 fn refreshDiff(self: *View, allocator: std.mem.Allocator) !void { 696 const sel = self.selectedCommitIndex() orelse return; 697 if (self.diffed_index) |d| if (d == sel) return; 698 try self.populateDiff(allocator, sel); 699 self.diffed_index = sel; 700 } 701 702 fn populateDiff(self: *View, allocator: std.mem.Allocator, sel: usize) !void { 703 const commit = self.data.commits[sel]; 704 const inner = self.diffInner(); 705 706 for (inner.children.values()) |*child| child.widget.deinit(allocator); 707 inner.children.clearAndFree(allocator); 708 inner.getFocus().child_id = null; 709 710 switch (self.paneContent(sel)) { 711 .message => { 712 try self.addNavLink(allocator, inner, "← back to diff", commit.oid, 0, ""); 713 try self.addMessageBox(allocator, inner, commit, .whole); 714 }, 715 .diff => |d| { 716 if (d.path.len != 0) { 717 // the file's path, then a row returning to this commit's unfiltered diff. 718 var label = try wgt.TextBox(ui.Widget).init(allocator, d.path, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 719 errdefer label.deinit(allocator); 720 label.getFocus().focusable = true; 721 try inner.children.put(allocator, label.getFocus().id, .{ .widget = .{ .text_box = label }, .rect = null, .min_size = null }); 722 try self.addNavLink(allocator, inner, "← all files", commit.oid, 0, ""); 723 } else { 724 try self.addMessageBox(allocator, inner, commit, .preview); 725 if (commit.author != .unknown) { 726 var tb = try ui.authorBox(allocator, self.session.page_arena, commit.author); 727 errdefer tb.deinit(allocator); 728 try inner.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 729 } 730 try self.addViewFilesLink(allocator, inner, commit.oid); 731 } 732 733 // a "previous" row and a "next" row at the bottom reload the page 734 // on the adjacent diff window. 735 if (commit.has_prev) try self.addNavLink(allocator, inner, "← previous", commit.oid, commit.window_start -| diff_page, d.path); 736 for (commit.hunks) |hunk| { 737 if (d.path.len == 0) if (hunk.path) |hunk_path| try self.addPathBox(allocator, inner, hunk_path, commit.oid); 738 try self.addHunkBox(allocator, inner, hunk.lines); 739 } 740 if (commit.has_more) try self.addNavLink(allocator, inner, "next →", commit.oid, commit.window_start + diff_page, d.path); 741 }, 742 } 743 744 // point the pane at its first row so focus recovery can land here. 745 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 746 747 // reset the scroll to the top for the newly-shown commit: directly on the 748 // terminal (the wasm offset), and via a version bump on the web (so the 749 // renderer's scroll id changes and JS drops the preserved position). 750 const sc = self.diffScroll(); 751 sc.x = 0; 752 sc.y = 0; 753 sc.getFocus().version +%= 1; 754 } 755 756 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 757 _ = allocator; 758 if (self.diffActive()) { 759 try self.diffInput(key, root_focus); 760 } else { 761 try self.listInput(key, root_focus); 762 } 763 } 764 765 fn listInput(self: *View, key: Key, root_focus: *Focus) !void { 766 // up/down (and the scroll wheel) move the selection a row; page up/down 767 // jump a fixed amount. right/Enter cross into the diff pane. Enter/clicks 768 // on the "next" row become navigation in the host before reaching here. 769 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 770 ui.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 771 return; 772 } 773 switch (key) { 774 .enter => if (self.selectedCommitIndex() != null) 775 try self.focusDiff(root_focus) 776 else if (self.data.next_start) |next| { 777 if (ui.RoutablePage.repoCommitsRoute(self.data.identity, .object, next, 0, "")) |route| 778 try self.session.navigate(route); 779 }, 780 .arrow_right => try self.focusDiff(root_focus), 781 else => {}, 782 } 783 } 784 785 fn diffInput(self: *View, key: Key, root_focus: *Focus) !void { 786 const sc = self.diffScroll(); 787 switch (key) { 788 // left scrolls horizontally, then leaves for the list once flush left. 789 .arrow_left => { 790 if (sc.x > 0) { 791 sc.x -= 1; 792 self.diffScroll().clampToContent(); 793 } else try self.focusList(root_focus); 794 }, 795 .arrow_right => { 796 sc.x += 1; 797 self.diffScroll().clampToContent(); 798 }, 799 .arrow_up => try self.moveDiff(root_focus, -1), 800 .arrow_down => try self.moveDiff(root_focus, 1), 801 .page_up => try self.pageDiff(root_focus, -10), 802 .page_down => try self.pageDiff(root_focus, 10), 803 .home => try self.jumpDiff(root_focus, false), 804 .end => try self.jumpDiff(root_focus, true), 805 // Enter / a click on a "previous"/"next" row follow its "a:" link in 806 // the host (it reloads the adjacent window), so they don't reach here. 807 .mouse => |mouse| switch (mouse.action) { 808 .scroll => |dir| try self.moveDiff(root_focus, if (dir == .up) -1 else 1), 809 else => {}, 810 }, 811 else => {}, 812 } 813 } 814 815 // move one step in `delta` (+ down, - up). in the terminal, `delta` is a 816 // line count unless there is a new hunk visible (in which case it is a 817 // hunk count). on the web `delta` is always a hunk count. 818 fn moveDiff(self: *View, root_focus: *Focus, delta: isize) !void { 819 const inner = self.diffInner(); 820 const keys = inner.children.keys(); 821 if (keys.len == 0) return; 822 const cur: usize = if (root_focus.grandchild_id) |g| (inner.children.getIndex(g) orelse 0) else 0; 823 const target = @as(isize, @intCast(cur)) + delta; 824 const in_range = target >= 0 and target < @as(isize, @intCast(keys.len)); 825 826 if (self.session.is_terminal) { 827 if (in_range and self.hunkVisible(@intCast(target))) { 828 root_focus.setFocus(keys[@intCast(target)]); 829 return; 830 } 831 832 const sc = self.diffScroll(); 833 sc.y += delta * 5; // magnify because it's a line count 834 self.diffScroll().clampToContent(); 835 if (in_range and self.hunkVisible(@intCast(target))) { 836 root_focus.setFocus(keys[@intCast(target)]); 837 } 838 } else { 839 if (in_range) { 840 root_focus.setFocus(keys[@intCast(target)]); 841 } 842 } 843 } 844 845 // page a fixed number of lines, then focus the leading visible hunk 846 // (bottom-most when paging down, top-most when paging up). in the 847 // terminal, `delta` is a line count, and on the web it's a hunk count. 848 fn pageDiff(self: *View, root_focus: *Focus, delta: isize) !void { 849 if (self.session.is_terminal) { 850 const sc = self.diffScroll(); 851 sc.y += delta * 5; // magnify because it's a line count 852 self.diffScroll().clampToContent(); 853 try self.focusVisible(root_focus, delta > 0); 854 } else { 855 const inner = self.diffInner(); 856 const keys = inner.children.keys(); 857 if (keys.len == 0) return; 858 const cur: isize = if (root_focus.grandchild_id) |g| @intCast(inner.children.getIndex(g) orelse 0) else 0; 859 const target: usize = @intCast(std.math.clamp(cur + delta, 0, @as(isize, @intCast(keys.len - 1)))); 860 root_focus.setFocus(keys[target]); 861 } 862 } 863 864 // jump to the first or last hunk. on the web the browser scrolls to the 865 // focused hunk; on the terminal pin the scroll to the top/bottom too. 866 fn jumpDiff(self: *View, root_focus: *Focus, to_end: bool) !void { 867 const inner = self.diffInner(); 868 const keys = inner.children.keys(); 869 if (keys.len == 0) return; 870 if (self.session.is_terminal) { 871 const sc = self.diffScroll(); 872 sc.y = if (to_end) std.math.maxInt(isize) else 0; 873 self.diffScroll().clampToContent(); 874 } 875 root_focus.setFocus(if (to_end) keys[keys.len - 1] else keys[0]); 876 } 877 878 // whether hunk `index` is at least partly within the diff viewport, per the 879 // last build's layout rects (content space) and the current scroll offset. 880 fn hunkVisible(self: *View, index: usize) bool { 881 const inner = self.diffInner(); 882 const sc = self.diffScroll(); 883 const vp = sc.grid orelse return false; 884 const r = inner.children.values()[index].rect orelse return false; 885 const top = sc.y; 886 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 887 return (r.y + @as(isize, @intCast(r.size.height))) > top and r.y < bottom; 888 } 889 890 // focus the visible hunk at the scroll's leading edge. `prefer_last` picks 891 // the bottom-most visible (for downward motion), else the top-most. 892 fn focusVisible(self: *View, root_focus: *Focus, prefer_last: bool) !void { 893 const inner = self.diffInner(); 894 const sc = self.diffScroll(); 895 const vp = sc.grid orelse return; 896 const top = sc.y; 897 const bottom = sc.y + @as(isize, @intCast(vp.size.height)); 898 var chosen: ?usize = null; 899 for (inner.children.keys(), inner.children.values()) |id, *child| { 900 const r = child.rect orelse continue; // content-space layout rect 901 const r_top = r.y; 902 const r_bot = r.y + @as(isize, @intCast(r.size.height)); 903 if (r_bot <= top or r_top >= bottom) continue; // not visible 904 chosen = id; 905 if (!prefer_last) break; // first visible 906 } 907 if (chosen) |id| root_focus.setFocus(id); 908 } 909 910 // enter the diff pane. the host arrives here on right-arrow or Enter from the 911 // list. a diff with no rows can't be entered. setFocus handles the too-narrow 912 // case where the pane isn't laid out yet (it gets selected, then focused after 913 // the next build, landing on its remembered hunk). 914 fn focusDiff(self: *View, root_focus: *Focus) !void { 915 if (self.diffInner().children.count() == 0) return; 916 root_focus.setFocus(self.diffOuter().getFocus().id); 917 } 918 919 // return to the list. 920 fn focusList(self: *View, root_focus: *Focus) !void { 921 root_focus.setFocus(self.listScroll().getFocus().id); 922 } 923 924 pub fn clearGrid(self: *View) void { 925 self.box.clearGrid(); 926 } 927 928 pub fn getGrid(self: View) ?Grid { 929 return self.box.getGrid(); 930 } 931 932 pub fn getFocus(self: *View) *Focus { 933 return self.box.getFocus(); 934 } 935 936 // for the parent's "scroll up at the top jumps to the header" check. in the 937 // diff pane that means the first hunk is focused and the diff can't scroll up 938 // any further; otherwise up-arrow stays in the pane (scrolling or moving 939 // between hunks). when the list holds focus, report its selection directly. 940 pub fn getSelectedIndex(self: *View) ?usize { 941 if (self.diffActive()) { 942 const inner = self.diffInner(); 943 const cid = inner.getFocus().child_id orelse return 1; 944 const first_focused = inner.children.count() > 0 and cid == inner.children.keys()[0]; 945 return if (first_focused and self.diffScroll().y == 0) 0 else 1; 946 } 947 const lb = self.listBox(); 948 const cid = lb.getFocus().child_id orelse return null; 949 return lb.children.getIndex(cid); 950 } 951 }; 952 953 // the "a:" navigation link for the commits page walking from commit `oid` within 954 // `identity`, windowing the selected commit's diff from hunk `start`, filtered 955 // to `path` ("" = every file). 956 fn commitsLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8, start: usize, path: []const u8) ![]const u8 { 957 const route = ui.RoutablePage.repoCommitsRoute(identity, .object, oid, start, path) orelse return error.RouteTooLong; 958 const url = try route.toUrl(page_arena); 959 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 960 } 961 962 // the "a:" link to the files tab at commit `oid` (an object ref), at its root 963 // directory, within `identity` ("owner/name"). 964 fn filesObjectLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8) ![]const u8 { 965 const route = ui.RoutablePage.repoFilesRoute(identity, .object, oid, "", 0) orelse return error.RouteTooLong; 966 const url = try route.toUrl(page_arena); 967 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 968 } 969 970 // the in-page "ai:" anchor for selecting `oid` in `identity`'s commit list. it 971 // points at the same route as commitsLink but the "ai:" prefix keeps wasm clicks 972 // in-page (crossPageLink ignores it); the href is only followed with js off. 973 fn commitRowLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8, path: []const u8) ![]const u8 { 974 const route = ui.RoutablePage.repoCommitsRoute(identity, .object, oid, 0, path) orelse return error.RouteTooLong; 975 const url = try route.toUrl(page_arena); 976 return std.fmt.allocPrint(page_arena.allocator(), "ai:{s}", .{url}); 977 } 978 979 // the "a:" link to the page showing `oid`'s message on its own. 980 fn messageLink(page_arena: *std.heap.ArenaAllocator, identity: []const u8, oid: []const u8) ![]const u8 { 981 const route = ui.RoutablePage.repoCommitMessageRoute(identity, .object, oid) orelse return error.RouteTooLong; 982 const url = try route.toUrl(page_arena); 983 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 984 } 985 986 // the "viewing <ref_or_oid> <value>" banner shown above the log. 987 pub const Header = struct { 988 content: []const u8, 989 990 // `value` arrives url-encoded, so decode it for display. 991 pub fn init(aa: std.mem.Allocator, ref_or_oid: ui.RoutablePage.RefOrOid, value: []const u8) !Header { 992 const decoded = std.Uri.percentDecodeInPlace(try aa.dupe(u8, value)); 993 return .{ 994 .content = try std.fmt.allocPrint(aa, "viewing {s} {s}", .{ @tagName(ref_or_oid), decoded }), 995 }; 996 } 997 998 pub const View = struct { 999 box: wgt.Box(ui.Widget), 1000 data: *const Header, 1001 1002 pub fn init(allocator: std.mem.Allocator, data: *const Header, session: *ui.Session) !Header.View { 1003 _ = session; 1004 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 1005 errdefer box.deinit(allocator); 1006 1007 var text_box = try wgt.TextBox(ui.Widget).init(allocator, data.content, .{ .border_style = .hidden, .wrap_kind = .none }); 1008 errdefer text_box.deinit(allocator); 1009 try box.children.put(allocator, text_box.getFocus().id, .{ .widget = .{ .text_box = text_box }, .rect = null, .min_size = null }); 1010 1011 return .{ .box = box, .data = data }; 1012 } 1013 1014 pub fn deinit(self: *Header.View, allocator: std.mem.Allocator) void { 1015 self.box.deinit(allocator); 1016 } 1017 1018 pub fn build(self: *Header.View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1019 self.clearGrid(); 1020 try self.box.build(allocator, constraint, root_focus); 1021 } 1022 1023 pub fn input(self: *Header.View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1024 _ = self; 1025 _ = allocator; 1026 _ = key; 1027 _ = root_focus; 1028 } 1029 1030 pub fn clearGrid(self: *Header.View) void { 1031 self.box.clearGrid(); 1032 } 1033 1034 pub fn getGrid(self: Header.View) ?Grid { 1035 return self.box.getGrid(); 1036 } 1037 1038 pub fn getFocus(self: *Header.View) *Focus { 1039 return self.box.getFocus(); 1040 } 1041 }; 1042 }; 1043