╭ 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().focusable = true; 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 try box.children.put(allocator, diff_outer.getFocus().id, .{ .widget = .{ .box = diff_outer }, .rect = null, .min_size = .{ .width = diff_min_width, .height = null } }); 495 } 496 497 box.getFocus().child_id = box.children.keys()[list_index]; 498 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 499 500 // focus lives in the split; the banner isn't focusable. 501 outer.getFocus().child_id = outer.children.keys()[content_index]; 502 503 return .{ 504 .box = outer, 505 .data = data, 506 .session = session, 507 .diffed_index = null, 508 }; 509 } 510 511 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !void { 512 var row = try wgt.TextBox.init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 513 errdefer row.deinit(allocator); 514 row.getFocus().focusable = true; 515 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 516 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null, .max_size = .{ .width = null, .height = 5 } }); 517 } 518 519 // one hunk as a focusable multi-line text box. its lines sit flush (the 520 // inner Text rows have no border). `lines` are joined into the page arena 521 // (text_box borrows it). 522 fn addHunkBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), lines: []const []const u8) !void { 523 if (lines.len == 0) return; 524 const text = try std.mem.join(self.session.page_arena.allocator(), "\n", lines); 525 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 526 errdefer tb.deinit(allocator); 527 tb.getFocus().focusable = true; 528 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 529 } 530 531 // a focusable file-path label shown above the first hunk of each file. it 532 // links to this page filtered to that file, so activating it navigates 533 // there. 534 fn addPathBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), path: []const u8, oid: []const u8) !void { 535 const link = try commitsLink(self.session.page_arena, self.data.location, oid, 0, path); 536 var tb = try wgt.TextBox.init(allocator, path, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 537 errdefer tb.deinit(allocator); 538 tb.getFocus().focusable = true; 539 tb.getFocus().kind = .{ .custom = link }; 540 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 541 } 542 543 // a focusable window-navigation row ("previous"/"next"). it's a link to this 544 // commit's route at `target_start`, so activating it (the host follows the 545 // "a:" link) reloads the page on the adjacent window — same on TUI and web. 546 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 { 547 const link = try commitsLink(self.session.page_arena, self.data.location, oid, target_start, path); 548 var tb = try wgt.TextBox.init(allocator, label, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 549 errdefer tb.deinit(allocator); 550 tb.getFocus().focusable = true; 551 tb.getFocus().kind = .{ .custom = link }; 552 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 553 } 554 555 // a focusable row for the top of the diff pane linking to the files tab at 556 // this commit's tree, so its files are always viewable as of this object. 557 fn addViewFilesLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), oid: []const u8) !void { 558 const link = try filesObjectLink(self.session.page_arena, self.data.location, oid); 559 var tb = try wgt.TextBox.init(allocator, "view files at this commit", .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 560 errdefer tb.deinit(allocator); 561 tb.getFocus().focusable = true; 562 tb.getFocus().kind = .{ .custom = link }; 563 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 564 } 565 566 // how much of the message a pane's box holds: a truncated preview links to 567 // the pane holding the whole thing, which is that link's destination. 568 const MessageBox = enum { preview, whole }; 569 570 // the selected commit's message. 571 fn addMessageBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), commit: Commit, kind: MessageBox) !void { 572 // a truncated message keeps its box even with no whole line to show, 573 // since the box is what links to the whole thing. 574 if (commit.message.len == 0 and !commit.message_truncated) return; 575 const cut_short = commit.message_truncated and kind == .preview; 576 var tb = try messageBox(allocator, commit.message, if (cut_short) " click or press enter to see more " else ""); 577 errdefer tb.deinit(allocator); 578 if (cut_short) tb.getFocus().kind = .{ .custom = try messageLink(self.session.page_arena, self.data.location, commit.oid) }; 579 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 580 } 581 582 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 583 self.box.deinit(allocator); 584 } 585 586 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 587 return &self.box.children.values()[content_index].widget.box; 588 } 589 590 fn header(self: *View) *Header.View { 591 return &self.box.children.values()[header_index].widget.repo_commits_header; 592 } 593 594 fn headerActive(self: *View) bool { 595 return self.box.getFocus().child_id == self.header().getFocus().id; 596 } 597 598 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 599 return &self.contentBox().children.values()[list_index].widget.scroll; 600 } 601 602 fn listBox(self: *View) *wgt.Box(ui.Widget) { 603 return &self.listScroll().child.box; 604 } 605 606 fn diffOuter(self: *View) *wgt.Box(ui.Widget) { 607 return &self.contentBox().children.values()[diff_index].widget.box; 608 } 609 610 fn diffScroll(self: *View) *wgt.Scroll(ui.Widget) { 611 return &self.diffOuter().children.values()[0].widget.scroll; 612 } 613 614 fn diffInner(self: *View) *wgt.Box(ui.Widget) { 615 return &self.diffScroll().child.box; 616 } 617 618 fn diffActive(self: *View) bool { 619 const content = self.contentBox(); 620 const cid = content.getFocus().child_id orelse return false; 621 return content.children.getIndex(cid) == diff_index; 622 } 623 624 // what the pane shows for the commit at `sel`. the page's content only 625 // applies to the commit it walks from; the rest show their plain diff. 626 fn paneContent(self: *View, sel: usize) Self.Content { 627 return if (sel == 0) self.data.content else .{ .diff = .{} }; 628 } 629 630 // the selected commit's index, or null when the "next" row is selected. 631 fn selectedCommitIndex(self: *View) ?usize { 632 const lb = self.listBox(); 633 const cid = lb.getFocus().child_id orelse return null; 634 const idx = lb.children.getIndex(cid) orelse return null; 635 if (idx >= self.data.commits.len) return null; 636 return idx; 637 } 638 639 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 640 self.clearGrid(); 641 642 // swap the diff pane to the selected commit when it changes. 643 try self.refreshDiff(allocator); 644 645 // the selected list row shows a border (the focused TextBox upgrades it 646 // to a double border itself); the rest stay borderless. 647 const lb = self.listBox(); 648 for (lb.children.keys(), lb.children.values()) |id, *child| { 649 switch (child.widget) { 650 .text_box => |*tb| tb.options.border_style = if (lb.getFocus().child_id == id) .single else .hidden, 651 else => {}, 652 } 653 } 654 655 // cap the list at list_max_width only while the diff pane fits beside it. 656 // the box drops the diff when the width can't hold both minimums, so when 657 // it's that narrow we lift the cap and let the list fill the whole width. 658 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + diff_min_width else true; 659 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 660 661 // stretch the diff pane across the rest of the width so it fills the area 662 // rather than shrinking to its content; its scroll fills the pane. when 663 // too narrow for both, it fills the whole width. 664 const diff_width: usize = if (constraint.max_size.width) |w| 665 (if (both_panes_fit) w - list_max_width else w) 666 else 667 diff_min_width; 668 self.contentBox().children.values()[diff_index].min_size = .{ .width = diff_width, .height = null }; 669 670 // the message is the pane's only wrapping row, and wrapping needs a 671 // bounded width, which the pane's scroll doesn't grant (it scrolls 672 // horizontally too). cap it to the pane, leaving room for the border 673 // and the scrollbar column. re-capped each build so it tracks resizes. 674 for (self.diffInner().children.values()) |*child| switch (child.widget) { 675 .text_box => |text_box| if (text_box.options.wrap_kind == .word) { 676 child.max_size = .{ .width = diff_width -| 3, .height = null }; 677 }, 678 else => {}, 679 }; 680 681 // the web bounds the layout to the browser viewport like the terminal; 682 // each Scroll's web-native mode hands its full content to a real 683 // scrollable element, so we no longer build unbounded here. 684 // 685 // crossing panes only re-selects the content box's child (focusDiff / 686 // focusList); when the window is too narrow to show both, the pane that 687 // held focus is dropped here. the framework recovers focus after the 688 // top-level build by re-deriving it down the selected-child chain, so 689 // there's nothing to fix up afterward. 690 try self.box.build(allocator, constraint, root_focus); 691 } 692 693 fn refreshDiff(self: *View, allocator: std.mem.Allocator) !void { 694 const sel = self.selectedCommitIndex() orelse return; 695 if (self.diffed_index) |d| if (d == sel) return; 696 try self.populateDiff(allocator, sel); 697 self.diffed_index = sel; 698 } 699 700 fn populateDiff(self: *View, allocator: std.mem.Allocator, sel: usize) !void { 701 const commit = self.data.commits[sel]; 702 const inner = self.diffInner(); 703 704 for (inner.children.values()) |*child| child.widget.deinit(allocator); 705 inner.children.clearAndFree(allocator); 706 inner.getFocus().child_id = null; 707 708 switch (self.paneContent(sel)) { 709 .message => { 710 try self.addNavLink(allocator, inner, "← back to diff", commit.oid, 0, ""); 711 try self.addMessageBox(allocator, inner, commit, .whole); 712 }, 713 .diff => |d| { 714 if (d.path.len != 0) { 715 // the file's path, then a row returning to this commit's unfiltered diff. 716 var label = try wgt.TextBox.init(allocator, d.path, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 717 errdefer label.deinit(allocator); 718 label.getFocus().focusable = true; 719 try inner.children.put(allocator, label.getFocus().id, .{ .widget = .{ .text_box = label }, .rect = null, .min_size = null }); 720 try self.addNavLink(allocator, inner, "← all files", commit.oid, 0, ""); 721 } else { 722 try self.addMessageBox(allocator, inner, commit, .preview); 723 if (commit.author != .unknown) { 724 var tb = try ui.authorBox(allocator, self.session.page_arena, commit.author); 725 errdefer tb.deinit(allocator); 726 try inner.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 727 } 728 try self.addViewFilesLink(allocator, inner, commit.oid); 729 } 730 731 // a "previous" row and a "next" row at the bottom reload the page 732 // on the adjacent diff window. 733 if (commit.has_prev) try self.addNavLink(allocator, inner, "← previous", commit.oid, commit.window_start -| diff_page, d.path); 734 for (commit.hunks) |hunk| { 735 if (d.path.len == 0) if (hunk.path) |hunk_path| try self.addPathBox(allocator, inner, hunk_path, commit.oid); 736 try self.addHunkBox(allocator, inner, hunk.lines); 737 } 738 if (commit.has_more) try self.addNavLink(allocator, inner, "next →", commit.oid, commit.window_start + diff_page, d.path); 739 }, 740 } 741 742 // point the pane at its first row so focus recovery can land here. 743 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 744 745 // reset the scroll to the top for the newly-shown commit: directly on the 746 // terminal (the wasm offset), and via a version bump on the web (so the 747 // renderer's scroll id changes and JS drops the preserved position). 748 const sc = self.diffScroll(); 749 sc.x = 0; 750 sc.y = 0; 751 sc.getFocus().version +%= 1; 752 } 753 754 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 755 if (self.headerActive()) { 756 if (key == .arrow_down) { 757 root_focus.setFocus(self.contentBox().getFocus().id); 758 } else { 759 try self.header().input(allocator, key, root_focus); 760 } 761 return; 762 } 763 if (key == .arrow_up and self.contentAtTop() and self.header().focusCloneUrl(root_focus)) return; 764 if (self.diffActive()) { 765 try self.diffInput(key, root_focus); 766 } else { 767 try self.listInput(key, root_focus); 768 } 769 } 770 771 fn listInput(self: *View, key: Key, root_focus: *Focus) !void { 772 // up/down (and the scroll wheel) move the selection a row; page up/down 773 // jump a fixed amount. right/Enter cross into the diff pane. Enter/clicks 774 // on the "next" row become navigation in the host before reaching here. 775 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 776 ui.widget.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 777 return; 778 } 779 switch (key) { 780 .enter => if (self.selectedCommitIndex() != null) 781 try self.focusDiff(root_focus) 782 else if (self.data.next_start) |next| { 783 if (self.data.location.commitsRoute(.object, next, 0, "")) |route| 784 try self.session.navigate(route); 785 }, 786 .arrow_right => try self.focusDiff(root_focus), 787 else => {}, 788 } 789 } 790 791 fn diffInput(self: *View, key: Key, root_focus: *Focus) !void { 792 const sc = self.diffScroll(); 793 switch (key) { 794 // left scrolls horizontally, then leaves for the list once flush left. 795 .arrow_left => { 796 if (sc.x > 0) { 797 sc.x -= 1; 798 self.diffScroll().clampToContent(); 799 } else try self.focusList(root_focus); 800 }, 801 .arrow_right => { 802 sc.x += 1; 803 self.diffScroll().clampToContent(); 804 }, 805 .arrow_up => try self.moveDiff(root_focus, -1), 806 .arrow_down => try self.moveDiff(root_focus, 1), 807 .page_up => try self.pageDiff(root_focus, -10), 808 .page_down => try self.pageDiff(root_focus, 10), 809 .home => try self.jumpDiff(root_focus, false), 810 .end => try self.jumpDiff(root_focus, true), 811 // Enter / a click on a "previous"/"next" row follow its "a:" link in 812 // the host (it reloads the adjacent window), so they don't reach here. 813 .mouse => |mouse| switch (mouse.action) { 814 .scroll => |dir| try self.moveDiff(root_focus, if (dir == .up) -1 else 1), 815 else => {}, 816 }, 817 else => {}, 818 } 819 } 820 821 // move one step in `delta` (+ down, - up). in the terminal, `delta` is a 822 // line count unless there is a new hunk visible (in which case it is a 823 // hunk count). on the web `delta` is always a hunk count. 824 fn moveDiff(self: *View, root_focus: *Focus, delta: isize) !void { 825 const inner = self.diffInner(); 826 const keys = inner.children.keys(); 827 if (keys.len == 0) return; 828 const cur: usize = if (root_focus.grandchild_id) |g| (inner.children.getIndex(g) orelse 0) else 0; 829 const target = @as(isize, @intCast(cur)) + delta; 830 const in_range = target >= 0 and target < @as(isize, @intCast(keys.len)); 831 832 if (self.session.is_terminal) { 833 if (in_range and self.hunkVisible(@intCast(target))) { 834 root_focus.setFocus(keys[@intCast(target)]); 835 return; 836 } 837 838 const sc = self.diffScroll(); 839 sc.y += delta * 5; // magnify because it's a line count 840 self.diffScroll().clampToContent(); 841 if (in_range and self.hunkVisible(@intCast(target))) { 842 root_focus.setFocus(keys[@intCast(target)]); 843 } 844 } else { 845 if (in_range) { 846 root_focus.setFocus(keys[@intCast(target)]); 847 } 848 } 849 } 850 851 // page a fixed number of lines, then focus the leading visible hunk 852 // (bottom-most when paging down, top-most when paging up). in the 853 // terminal, `delta` is a line count, and on the web it's a hunk count. 854 fn pageDiff(self: *View, root_focus: *Focus, delta: isize) !void { 855 if (self.session.is_terminal) { 856 const sc = self.diffScroll(); 857 sc.y += delta * 5; // magnify because it's a line count 858 self.diffScroll().clampToContent(); 859 try self.focusVisible(root_focus, delta > 0); 860 } else { 861 const inner = self.diffInner(); 862 const keys = inner.children.keys(); 863 if (keys.len == 0) return; 864 const cur: isize = if (root_focus.grandchild_id) |g| @intCast(inner.children.getIndex(g) orelse 0) else 0; 865 const target: usize = @intCast(std.math.clamp(cur + delta, 0, @as(isize, @intCast(keys.len - 1)))); 866 root_focus.setFocus(keys[target]); 867 } 868 } 869 870 // jump to the first or last hunk. on the web the browser scrolls to the 871 // focused hunk; on the terminal pin the scroll to the top/bottom too. 872 fn jumpDiff(self: *View, root_focus: *Focus, to_end: bool) !void { 873 const inner = self.diffInner(); 874 const keys = inner.children.keys(); 875 if (keys.len == 0) return; 876 if (self.session.is_terminal) { 877 const sc = self.diffScroll(); 878 sc.y = if (to_end) std.math.maxInt(isize) else 0; 879 self.diffScroll().clampToContent(); 880 } 881 root_focus.setFocus(if (to_end) keys[keys.len - 1] else keys[0]); 882 } 883 884 // whether hunk `index` is at least partly within the diff viewport, per the 885 // last build's layout rects (content space) and the current scroll offset. 886 fn hunkVisible(self: *View, index: usize) bool { 887 const inner = self.diffInner(); 888 const sc = self.diffScroll(); 889 const vp = sc.grid orelse return false; 890 const r = inner.children.values()[index].rect orelse return false; 891 const top = sc.y; 892 const bottom = sc.y + @as(isize, @intCast(vp.size.height - sc.bar_h)); 893 return (r.y + @as(isize, @intCast(r.size.height))) > top and r.y < bottom; 894 } 895 896 // focus the visible hunk at the scroll's leading edge. `prefer_last` picks 897 // the bottom-most visible (for downward motion), else the top-most. 898 fn focusVisible(self: *View, root_focus: *Focus, prefer_last: bool) !void { 899 const inner = self.diffInner(); 900 const sc = self.diffScroll(); 901 const vp = sc.grid orelse return; 902 const top = sc.y; 903 const bottom = sc.y + @as(isize, @intCast(vp.size.height - sc.bar_h)); 904 var chosen: ?usize = null; 905 for (inner.children.keys(), inner.children.values()) |id, *child| { 906 const r = child.rect orelse continue; // content-space layout rect 907 const r_top = r.y; 908 const r_bot = r.y + @as(isize, @intCast(r.size.height)); 909 if (r_bot <= top or r_top >= bottom) continue; // not visible 910 chosen = id; 911 if (!prefer_last) break; // first visible 912 } 913 if (chosen) |id| root_focus.setFocus(id); 914 } 915 916 // enter the diff pane. the host arrives here on right-arrow or Enter from the 917 // list. a diff with no rows can't be entered. setFocus handles the too-narrow 918 // case where the pane isn't laid out yet (it gets selected, then focused after 919 // the next build, landing on its remembered hunk). 920 fn focusDiff(self: *View, root_focus: *Focus) !void { 921 if (self.diffInner().children.count() == 0) return; 922 root_focus.setFocus(self.diffOuter().getFocus().id); 923 } 924 925 // return to the list. 926 fn focusList(self: *View, root_focus: *Focus) !void { 927 root_focus.setFocus(self.listScroll().getFocus().id); 928 } 929 930 pub fn clearGrid(self: *View) void { 931 self.box.clearGrid(); 932 } 933 934 pub fn getGrid(self: View) ?Grid { 935 return self.box.getGrid(); 936 } 937 938 pub fn getFocus(self: *View) *Focus { 939 return self.box.getFocus(); 940 } 941 942 fn contentAtTop(self: *View) bool { 943 if (self.diffActive()) { 944 const inner = self.diffInner(); 945 const cid = inner.getFocus().child_id orelse return true; 946 const first_focused = inner.children.count() > 0 and cid == inner.children.keys()[0]; 947 return first_focused and self.diffScroll().y == 0; 948 } 949 const lb = self.listBox(); 950 const cid = lb.getFocus().child_id orelse return true; 951 return lb.children.getIndex(cid) == 0; 952 } 953 954 // only the clone-url row sits directly below the repository header. 955 pub fn getSelectedIndex(self: *View) ?usize { 956 if (self.headerActive()) return 0; 957 return if (self.header().hasCloneUrl() or !self.contentAtTop()) 1 else 0; 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