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