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