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