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