╭ Files.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1 const std = @import("std"); 2 const evt = @import("../../event.zig"); 3 const ui = @import("../../ui.zig"); 4 const xit = @import("xit"); 5 const rp = xit.repo; 6 const tr = xit.tree; 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 const fnd = @import("../../find.zig"); 16 const md = @import("../../markdown.zig"); 17 const Markdown = @import("Markdown.zig"); 18 19 // how many lines of a file's content one window shows before a "next" link. 20 const file_page = 5000; 21 22 // a longer markdown file shows as numbered source rather than rendered. 23 const max_markdown_lines = 2000; 24 25 // budget for the total bytes of file content preloaded (windowed) per page, 26 // so selecting a preloaded file shows its contents without a reload. 27 const max_preloaded_bytes = 2 * 1024 * 1024; 28 29 // how many rows a listing holds, for a directory and for search results alike. 30 const max_list_entries = 1000; 31 32 // one entry in the directory currently being viewed. 33 pub const Entry = struct { 34 name: []const u8, 35 is_dir: bool, 36 // a file's content window split into lines (each without its trailing 37 // newline); empty for directories and for binary or empty files. 38 lines: []const []const u8 = &.{}, 39 // true when xit's line iterator flagged the file as binary, so the detail 40 // pane shows a placeholder rather than its bytes. 41 is_binary: bool = false, 42 // the line index this window starts at (0 = the first window). non-zero only 43 // for the route's selected file, paginated by the url's `line`. 44 window_start: usize = 0, 45 // whether more lines exist after this window. 46 has_more: bool = false, 47 // whether this file's content was read; unloaded files load via their 48 // "a:" link. 49 loaded: bool = false, 50 }; 51 52 // where links and clone commands for this repository are rooted, and who views it. 53 handle: ui.RepoHandle, 54 // the resolved ref this listing is read at (the default branch when the route 55 // didn't name one), so the view's directory links stay pinned to it. 56 ref_or_oid: ui.RoutablePage.RefOrOid, 57 ref_or_oid_value: []const u8, 58 patchrev_id: ?[]const u8 = null, 59 // the directory being viewed, relative to the repo root ("" at the root). 60 dir: []const u8, 61 // a file within `dir` to start selected (so its contents show and the url 62 // carries it), or null to fall back to a README / the first row. set when the 63 // route's path named a file rather than a directory. 64 selected_file: ?[]const u8 = null, 65 entries: []const Entry, 66 // true when the listing stopped at max_list_entries. 67 capped: bool = false, 68 // the decoded search term this listing holds the results of, or null for a 69 // plain directory listing. 70 find: ?[]const u8 = null, 71 // whether the viewed tree has a file index, so the search box shows and a 72 // find: route resolves. travels in the page json for the wasm view. 73 find_available: bool = false, 74 // the repo's default branch has no commit yet, so the tab shows a placeholder 75 no_commits: bool = false, 76 77 const Self = @This(); 78 79 pub fn initPatchRev( 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 handle: ui.RepoHandle, 87 id_hex: []const u8, 88 path: []const u8, 89 line: usize, 90 ) !Self { 91 const id = evt.parseEventId(id_hex) catch return error.NotFound; 92 const record = (try evt.readFromRepo(evt.PatchRev, repo_kind, repo_opts, io, gpa, arena, repo, &id)) orelse return error.NotFound; 93 if (record.removed) return error.NotFound; 94 var data = try init(repo_kind, repo_opts, arena, repo, io, gpa, handle, .object, record.head_tree_oid, path, line, ""); 95 data.patchrev_id = try arena.allocator().dupe(u8, id_hex); 96 return data; 97 } 98 99 pub fn filesRoute(self: *const Self, path: []const u8, line: usize) ?ui.RoutablePage { 100 if (self.patchrev_id) |id| return switch (self.handle.location) { 101 .repo => |identity| ui.RoutablePage.repoPatchRevFilesRoute(identity, id, path, line), 102 .fork => null, 103 }; 104 const route = self.handle.location.filesRoute(self.ref_or_oid, self.ref_or_oid_value, path, line) orelse return null; 105 return route.withFind(self.find orelse return route); 106 } 107 108 // an empty root listing, which shows the empty message 109 fn isEmpty(self: *const Self) bool { 110 return self.entries.len == 0 and self.dir.len == 0; 111 } 112 113 // build the listing for an opened repo. generic over the repo's backend and 114 // hash kind so the tree/diff types it threads through match the repo's opts. 115 // reads with the arena's backing allocator (transient); the listing is built 116 // into the page arena so it outlives the repo handle. 117 pub fn init( 118 comptime repo_kind: rp.RepoKind, 119 comptime repo_opts: rp.RepoOpts(repo_kind), 120 arena: *std.heap.ArenaAllocator, 121 repo: *rp.Repo(repo_kind, repo_opts), 122 io: std.Io, 123 gpa: std.mem.Allocator, 124 handle: ui.RepoHandle, 125 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 126 requested_value: []const u8, 127 path: []const u8, 128 line: usize, 129 find: []const u8, 130 ) !Self { 131 const aa = arena.allocator(); 132 const term: ?[]const u8 = if (find.len == 0) null else std.Uri.percentDecodeInPlace(try aa.dupe(u8, find)); 133 134 // resolve the requested ref (or the default branch) to the object oid whose 135 // tree we list. a ref the route named explicitly that doesn't resolve is a 136 // bad url (NotFound -> 404); the default-branch path falls through to empty. 137 const resolved = (try ui.ResolvedRefOrOid(repo_kind, repo_opts).init(repo, io, aa, requested_ref_or_oid, requested_value)) orelse { 138 if (requested_ref_or_oid != null or term != null) return error.NotFound; 139 var data = try emptyResult(aa, handle, .branch, requested_value, path); 140 data.no_commits = true; 141 return data; 142 }; 143 144 // read just the viewed directory of that tree or commit. building the 145 // read-only state mirrors what repo.status does internally, but for an 146 // arbitrary commit rather than HEAD. a path that doesn't exist in the tree 147 // is a bad url (404). 148 var moment = repo.core.latestMoment() catch return emptyResult(aa, handle, resolved.ref_or_oid, resolved.value, path); 149 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 150 151 var entries: std.ArrayList(Entry) = .empty; 152 var capped = false; 153 var preloaded_bytes: usize = 0; 154 var find_available = false; 155 156 // the index covers branch tips only, so any other view gets no search box 157 // and refuses a find: url. 158 if (comptime repo_kind == .xit) index: { 159 if (resolved.ref_or_oid != .branch) break :index; 160 const branch = std.Uri.percentDecodeInPlace(try aa.dupe(u8, resolved.value)); 161 const files = (try fnd.lookup(repo_opts, moment, branch, &resolved.oid)) orelse break :index; 162 find_available = true; 163 const value = term orelse break :index; 164 // a result's name is its full path, so the listing has no directory and 165 // the selected row is named in full. 166 const selected: ?[]const u8 = if (path.len == 0) null else try aa.dupe(u8, path); 167 const results = try fnd.search(repo_opts, files, aa, value, max_list_entries); 168 capped = results.capped; 169 var found = false; 170 for (results.matches) |match| { 171 if (selected) |sf| found = found or std.mem.eql(u8, sf, match.path); 172 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, "", match.path, &match.oid, null, selected, line, &preloaded_bytes)); 173 } 174 // the cap can cut off the row the url names, so bring it back 175 if (capped and !found) { 176 if (selected) |sf| if (try fnd.get(repo_opts, files, aa, sf)) |*oid| { 177 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, "", sf, oid, null, selected, line, &preloaded_bytes)); 178 }; 179 } 180 return .{ 181 .handle = try handle.dupe(aa), 182 .ref_or_oid = resolved.ref_or_oid, 183 .ref_or_oid_value = resolved.value, 184 .dir = "", 185 .selected_file = selected, 186 .entries = entries.items, 187 .capped = capped, 188 .find = value, 189 .find_available = true, 190 }; 191 } 192 if (term != null) return error.NotFound; 193 194 var tree_dir = tr.TreeDir(repo_kind, repo_opts).init(state, io, gpa, &resolved.oid, path) catch |err| switch (err) { 195 error.TreeEntryNotFound => return error.NotFound, 196 else => return emptyResult(aa, handle, resolved.ref_or_oid, resolved.value, path), 197 }; 198 defer tree_dir.deinit(); 199 200 // when `path` named a file, the listing is its parent directory with that 201 // file selected. 202 var dir = path; 203 var selected_file: ?[]const u8 = null; 204 if (tree_dir.file_name != null) { 205 const slash = std.mem.lastIndexOfScalar(u8, path, '/'); 206 selected_file = try aa.dupe(u8, if (slash) |s| path[s + 1 ..] else path); 207 dir = if (slash) |s| path[0..s] else ""; 208 } 209 210 // tree objects store their entries in name order, so the listing is 211 // already sorted. group directories before files, keeping that order 212 // within each group, and dupe into the page arena. file contents are read 213 // here (into the page arena) so the detail pane can show them without 214 // another lookup. 215 try entries.ensureTotalCapacity(aa, @min(tree_dir.entries.count(), max_list_entries)); 216 for ([_]bool{ true, false }) |want_dir| { 217 for (tree_dir.entries.keys(), tree_dir.entries.values()) |name, tree_entry| { 218 if (tree_entry.isTree() != want_dir) continue; 219 if (want_dir) { 220 if (entries.items.len >= max_list_entries) { 221 capped = true; 222 continue; 223 } 224 try entries.append(aa, .{ .name = try aa.dupe(u8, name), .is_dir = true }); 225 } else { 226 // the rows the route and the default selection need are exempt 227 // from the cap, so a url naming a file always gets its row. 228 const exempt = isReadme(name) or (if (selected_file) |sf| std.mem.eql(u8, sf, name) else false); 229 if (entries.items.len >= max_list_entries and !exempt) { 230 capped = true; 231 continue; 232 } 233 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, dir, name, &tree_entry.oid, tree_entry.mode, selected_file, line, &preloaded_bytes)); 234 } 235 } 236 } 237 238 return .{ 239 .handle = try handle.dupe(aa), 240 .ref_or_oid = resolved.ref_or_oid, 241 .ref_or_oid_value = resolved.value, 242 .dir = try aa.dupe(u8, dir), 243 .selected_file = selected_file, 244 .entries = entries.items, 245 .capped = capped, 246 .find_available = find_available, 247 }; 248 } 249 250 // build one file's row, reading its content window when the preload budget (or 251 // the route) calls for it. only the route's selected file paginates; the rest 252 // show their first window, for the in-page detail when selected. 253 fn fileEntry( 254 comptime repo_kind: rp.RepoKind, 255 comptime repo_opts: rp.RepoOpts(repo_kind), 256 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 257 io: std.Io, 258 gpa: std.mem.Allocator, 259 aa: std.mem.Allocator, 260 dir: []const u8, 261 name: []const u8, 262 oid: *const [xit.hash.byteLen(repo_opts.hash)]u8, 263 // null for a search result, which the index only holds files for 264 mode: ?xit.fs.Mode, 265 selected_file: ?[]const u8, 266 line: usize, 267 preloaded_bytes: *usize, 268 ) !Entry { 269 var entry: Entry = .{ .name = try aa.dupe(u8, name), .is_dir = false }; 270 const is_selected = if (selected_file) |sf| std.mem.eql(u8, sf, name) else false; 271 // the README always loads because it's the default selection. 272 if (preloaded_bytes.* >= max_preloaded_bytes and !is_selected and !isReadme(name)) return entry; 273 const file_path = try childDir(aa, dir, name); 274 // the url's `line` is 1-based (0 = unset); the window index is 0-based. 275 const window_start = if (is_selected) line -| 1 else 0; 276 const content = readFileContent(repo_kind, repo_opts, state, io, gpa, aa, file_path, oid, mode, window_start) catch 277 FileContent{ .lines = &.{} }; 278 for (content.lines) |l| preloaded_bytes.* += l.len; 279 entry.lines = content.lines; 280 entry.is_binary = content.is_binary; 281 entry.window_start = window_start; 282 entry.has_more = content.has_more; 283 entry.loaded = true; 284 return entry; 285 } 286 287 const FileContent = struct { 288 lines: []const []const u8, 289 is_binary: bool = false, 290 has_more: bool = false, 291 }; 292 293 // read the window [start, start+file_page) of a committed file's contents at 294 // `oid` into `arena`-owned lines, flagging whether more follow. xit's 295 // line iterator flags binary files (its source becomes `.binary`), in which case 296 // we report no lines and let the view show a placeholder. 297 fn readFileContent( 298 comptime repo_kind: rp.RepoKind, 299 comptime repo_opts: rp.RepoOpts(repo_kind), 300 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 301 io: std.Io, 302 gpa: std.mem.Allocator, 303 arena: std.mem.Allocator, 304 path: []const u8, 305 oid: *const [xit.hash.byteLen(repo_opts.hash)]u8, 306 mode: ?xit.fs.Mode, 307 start: usize, 308 ) !FileContent { 309 var line_iter = try df.LineIterator(repo_kind, repo_opts).initFromOid(state, io, gpa, path, oid, mode); 310 defer line_iter.deinit(); 311 if (line_iter.source == .binary) return .{ .lines = &.{}, .is_binary = true }; 312 313 // init reads through the file to validate it (and buffer it in memory), so 314 // the line count is known and a window can be sliced out of the buffer. 315 const total = line_iter.count(); 316 const end = @min(start +| file_page, total); 317 318 var lines: std.ArrayList([]const u8) = .empty; 319 var i = start; 320 while (i < end) : (i += 1) { 321 const line = try line_iter.get(i); 322 try lines.append(arena, try arena.dupe(u8, line)); 323 } 324 return .{ 325 .lines = try lines.toOwnedSlice(arena), 326 .has_more = end < total, 327 }; 328 } 329 330 // an empty listing pinned to a ref, for the wasm / no-repo / unresolved paths. 331 pub fn emptyResult(aa: std.mem.Allocator, handle: ui.RepoHandle, ref_or_oid: ui.RoutablePage.RefOrOid, ref_or_oid_value: []const u8, dir: []const u8) !Self { 332 return .{ 333 .handle = try handle.dupe(aa), 334 .ref_or_oid = ref_or_oid, 335 .ref_or_oid_value = try aa.dupe(u8, ref_or_oid_value), 336 .dir = try aa.dupe(u8, dir), 337 .entries = &.{}, 338 }; 339 } 340 341 pub const View = struct { 342 // a vertical stack: the search box and clone url on top, then a horizontal 343 // split with the file/directory list on the left and a detail pane on the 344 // right showing the selected file's contents. 345 box: wgt.Box(ui.Widget), // vert: [header_index] = header row, [content_index] = split 346 data: *const Self, 347 session: *ui.Session, 348 // what the detail pane was last filled for: the selected list row, and 349 // whether the window was too narrow to show the list beside it 350 shown: Shown = .{ .index = null, .narrow = false }, 351 // the detail's way back to a list that isn't shown beside it 352 back_id: ?usize = null, 353 354 const Shown = struct { index: ?usize, narrow: bool }; 355 356 // the sub-header leads the box where there is one; local mode has none 357 const header_index: usize = 0; 358 // indices within the content box (the horizontal split). 359 const list_index: usize = 0; 360 const detail_index: usize = 1; 361 // indices within the detail pane frame (nav box above the content scroll). 362 const detail_nav_index: usize = 0; 363 const detail_scroll_index: usize = 1; 364 const list_max_width: usize = 35; 365 const detail_min_width: usize = 40; 366 // a list row's height: one text line inside its (hidden) border. 367 const row_height: usize = 3; 368 369 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 370 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .vert }); 371 errdefer outer.deinit(allocator); 372 373 if (data.no_commits) { 374 var center = try ui.widget.initNoCommits(allocator, session, data.handle); 375 errdefer center.deinit(allocator); 376 outer.getFocus().child_id = center.getFocus().id; 377 try outer.children.put(allocator, center.getFocus().id, .{ .widget = .{ .center = center }, .rect = null, .min_size = null }); 378 return .{ .box = outer, .data = data, .session = session }; 379 } 380 381 // the search box and the clone url at the top. local mode has neither. 382 if (session.data.host_kind == .server) { 383 var header_view = try ui.widget.SearchHeader.init(allocator, session, data.handle, " find file ", "find", data.find, data.find_available); 384 errdefer header_view.deinit(allocator); 385 // a row taller than the header, leaving a blank line beneath it 386 try outer.children.put(allocator, header_view.getFocus().id, .{ .widget = .{ .search_header = header_view }, .rect = null, .min_size = .{ .width = null, .height = 4 } }); 387 } 388 389 // an empty root listing shows the empty message in place of the split 390 if (data.isEmpty()) { 391 var center = try ui.widget.initEmpty(allocator); 392 errdefer center.deinit(allocator); 393 try outer.children.put(allocator, center.getFocus().id, .{ .widget = .{ .center = center }, .rect = null, .min_size = null }); 394 // with nothing below to focus, focus rests on the sub-header 395 outer.getFocus().child_id = outer.children.keys()[header_index]; 396 return .{ .box = outer, .data = data, .session = session }; 397 } 398 399 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .horiz }); 400 errdefer box.deinit(allocator); 401 402 var shows_file = false; 403 404 // the directory listing on the left (one focusable row each). 405 { 406 var list_scroll = blk: { 407 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .vert, .stretch = true }); 408 errdefer list_box.deinit(allocator); 409 410 // link kinds are borrowed by the rows, so they live in the page 411 // arena (as long as this page's widget tree). row labels are 412 // copied by their text boxes. 413 const aa = session.page_arena.allocator(); 414 if (data.dir.len != 0) { 415 try addRow(allocator, &list_box, "..", "", try dirLink(session.page_arena, data, parentDir(data.dir))); 416 } 417 for (data.entries) |entry| { 418 const path = try childDir(aa, data.dir, entry.name); 419 // a search result shows its file name, with its directory 420 // in the bottom label. 421 const label = if (data.find != null) 422 std.Io.Dir.path.basenamePosix(entry.name) 423 else if (entry.is_dir) 424 try aa.print("{s}/", .{entry.name}) 425 else 426 entry.name; 427 const bottom_label = if (data.find != null) try resultDirLabel(aa, entry.name) else ""; 428 const link = if (entry.is_dir) 429 try dirLink(session.page_arena, data, path) 430 else 431 try fileLink(session.page_arena, data, path, entry.loaded, lineNumber(entry.window_start)); 432 try addRow(allocator, &list_box, label, bottom_label, link); 433 } 434 if (data.capped) try addRow(allocator, &list_box, "(list truncated)", "", ""); 435 // select the file the route named, else prefer a README so its 436 // contents greet the visitor in the detail pane, else the first 437 // row. a non-root directory has a leading ".." row, so the entry 438 // index is offset by one there. search results have no README 439 // default: the term decides what matters. 440 var sel: usize = 0; 441 if (list_box.children.count() > 0) { 442 const base: usize = if (data.dir.len != 0) 1 else 0; 443 const entry_idx = selectedFileIndex(data) orelse if (data.find == null) readmeIndex(data.entries) else null; 444 sel = if (entry_idx) |i| i + base else 0; 445 list_box.getFocus().child_id = list_box.children.keys()[sel]; 446 shows_file = sel >= base and sel - base < data.entries.len and !data.entries[sel - base].is_dir; 447 } 448 var sc = try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 449 // start scrolled so the selected row begins at the top of the 450 // viewport. rows are a fixed height, so no layout pass is 451 // needed; a too-far offset near the end of the list is clamped 452 // in build (the browser clamps its own scrolling natively). 453 sc.y = @intCast(sel * row_height); 454 break :blk sc; 455 }; 456 errdefer list_scroll.deinit(allocator); 457 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 } }); 458 } 459 460 // the detail pane on the right — a "next" nav box above a scroll of the 461 // selected file's content window. both are repopulated per selection by 462 // populateDetail. 463 { 464 var detail_outer = blk: { 465 var frame = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .vert }); 466 errdefer frame.deinit(allocator); 467 468 { 469 var nav_box = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .horiz }); 470 errdefer nav_box.deinit(allocator); 471 try frame.children.put(allocator, nav_box.getFocus().id, .{ .widget = .{ .box = nav_box }, .rect = null, .min_size = null }); 472 } 473 { 474 // the content scroll wrapped in a bordered box; build sets the 475 // border single normally and double when the content is focused 476 // (the content box itself is borderless). 477 var scroll_frame = blk2: { 478 var detail_scroll = blk3: { 479 var detail_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border = null, .direction = .vert }); 480 errdefer detail_inner.deinit(allocator); 481 break :blk3 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = detail_inner }, .{ .direction = .both, .web_native = !session.is_terminal, .fill = true }); 482 }; 483 errdefer detail_scroll.deinit(allocator); 484 var sf = try wgt.Box(ui.Widget).init(allocator, .{ .border = .single, .round_corners = true, .direction = .vert }); 485 errdefer sf.deinit(allocator); 486 // the wrapper's selected child is its scroll, so the focus 487 // chain reaches the content box (populateDetail points the 488 // scroll's inner box at it). 489 sf.getFocus().child_id = detail_scroll.getFocus().id; 490 try sf.children.put(allocator, detail_scroll.getFocus().id, .{ .widget = .{ .scroll = detail_scroll }, .rect = null, .min_size = null }); 491 break :blk2 sf; 492 }; 493 errdefer scroll_frame.deinit(allocator); 494 // entering the detail pane lands on the content scroll (focus 495 // recovery descends the frame's selected child). the nav links 496 // above are reached by scrolling to the top, then up. 497 frame.getFocus().child_id = scroll_frame.getFocus().id; 498 // shrink, so the fill scroll yields the nav box's row 499 // instead of consuming the frame's whole height. 500 try frame.children.put(allocator, scroll_frame.getFocus().id, .{ .widget = .{ .box = scroll_frame }, .rect = null, .min_size = null, .flex = .shrink }); 501 } 502 break :blk frame; 503 }; 504 errdefer detail_outer.deinit(allocator); 505 detail_outer.getFocus().mode = .mouse; 506 try box.children.put(allocator, detail_outer.getFocus().id, .{ .widget = .{ .box = detail_outer }, .rect = null, .min_size = .{ .width = detail_min_width, .height = null } }); 507 } 508 509 box.getFocus().child_id = box.children.keys()[if (shows_file) detail_index else list_index]; 510 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 511 512 // focus lives in the split, except that search results start in the 513 // search box so the term can be refined right away. 514 outer.getFocus().child_id = outer.children.keys()[if (data.find != null) header_index else outer.children.count() - 1]; 515 return .{ .box = outer, .data = data, .session = session }; 516 } 517 518 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, bottom_label: []const u8, link: []const u8) !void { 519 var row = try wgt.TextBox.init(allocator, label, .{ .border = .hidden, .round_corners = true, .wrap_kind = .none, .bottom_label = .{ .text = bottom_label } }); 520 errdefer row.deinit(allocator); 521 row.getFocus().mode = .all; 522 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 523 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null }); 524 } 525 526 // the selected file's contents as a single focusable multi-line text box. 527 // it's borderless — the border lives on the surrounding scroll frame, which 528 // doubles when this content is focused. a non-empty `link` makes activating 529 // the box follow it, like addRow. 530 fn addContentBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), spans: []const wgt.Span, link: []const u8) !void { 531 _ = self; 532 var tb = try wgt.TextBox.initSpans(allocator, spans, .{ .border = null, .wrap_kind = .none }); 533 errdefer tb.deinit(allocator); 534 tb.getFocus().mode = .all; 535 if (link.len != 0) tb.getFocus().kind = .{ .custom = link }; 536 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 537 } 538 539 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 540 self.box.deinit(allocator); 541 } 542 543 // the split is last, after the sub-header where there is one 544 fn contentIndex(self: *View) usize { 545 return self.box.children.count() - 1; 546 } 547 548 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 549 return &self.box.children.values()[self.contentIndex()].widget.box; 550 } 551 552 fn header(self: *View) ?*ui.widget.SearchHeader { 553 switch (self.box.children.values()[header_index].widget) { 554 .search_header => |*header_view| return header_view, 555 else => return null, 556 } 557 } 558 559 fn headerActive(self: *View) bool { 560 const header_view = self.header() orelse return false; 561 return self.box.getFocus().child_id == header_view.getFocus().id; 562 } 563 564 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 565 return &self.contentBox().children.values()[list_index].widget.scroll; 566 } 567 568 fn listBox(self: *View) *wgt.Box(ui.Widget) { 569 return &self.listScroll().child.box; 570 } 571 572 fn detailOuter(self: *View) *wgt.Box(ui.Widget) { 573 return &self.contentBox().children.values()[detail_index].widget.box; 574 } 575 576 fn navBox(self: *View) *wgt.Box(ui.Widget) { 577 return &self.detailOuter().children.values()[detail_nav_index].widget.box; 578 } 579 580 // the bordered box wrapping the content scroll (border toggles with focus). 581 fn detailScrollFrame(self: *View) *wgt.Box(ui.Widget) { 582 return &self.detailOuter().children.values()[detail_scroll_index].widget.box; 583 } 584 585 fn detailScroll(self: *View) *wgt.Scroll(ui.Widget) { 586 return &self.detailScrollFrame().children.values()[0].widget.scroll; 587 } 588 589 fn detailInner(self: *View) *wgt.Box(ui.Widget) { 590 return &self.detailScroll().child.box; 591 } 592 593 fn detailActive(self: *View) bool { 594 const content = self.contentBox(); 595 const cid = content.getFocus().child_id orelse return false; 596 return content.children.getIndex(cid) == detail_index; 597 } 598 599 // the selected list row's index, or null when nothing is focused. 600 fn selectedRowIndex(self: *View) ?usize { 601 const lb = self.listBox(); 602 const cid = lb.getFocus().child_id orelse return null; 603 return lb.children.getIndex(cid); 604 } 605 606 // the entry the selected row points at, or null for the ".." row (which 607 // isn't an entry). directory rows return their entry too, though they carry 608 // no contents. 609 fn selectedEntry(self: *View) ?Entry { 610 const idx = self.selectedRowIndex() orelse return null; 611 const base: usize = if (self.data.dir.len != 0) 1 else 0; // skip the ".." row 612 if (idx < base) return null; 613 const e = idx - base; 614 if (e >= self.data.entries.len) return null; 615 return self.data.entries[e]; 616 } 617 618 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 619 self.clearGrid(); 620 if (self.data.no_commits or self.data.isEmpty()) return self.box.build(allocator, constraint, root_focus); 621 622 // whether the detail pane fits beside the list, which decides the list 623 // cap below and whether the detail carries a way back to the list 624 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + detail_min_width else true; 625 626 // swap the detail pane to the selected entry when the selection changes. 627 try self.refreshDetail(allocator, !both_panes_fit); 628 629 // the selected list row shows a border (the focused TextBox upgrades it 630 // to a double border itself); the rest stay borderless. 631 const lb = self.listBox(); 632 for (lb.children.keys(), lb.children.values()) |id, *child| { 633 switch (child.widget) { 634 .text_box => |*tb| ui.widget.markSelected(tb, lb.getFocus().child_id == id), 635 else => {}, 636 } 637 } 638 639 // the content scroll's border is single normally and double when the 640 // content is focused (the content box itself is borderless). 641 const has_content = self.detailInner().children.count() > 0; 642 self.detailScrollFrame().options.border = if (!has_content) null else if (self.focusOnContent(root_focus)) .double else .single; 643 644 // cap the list at list_max_width only while the detail pane fits beside 645 // it. the box drops the detail pane when the width can't hold both 646 // minimums, so when it's that narrow we lift the cap and let the list 647 // fill the whole width. 648 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 649 650 // stretch the detail pane and its bordered scroll frame across the rest 651 // of the width so the pane fills the area rather than shrinking to its 652 // content, like the refs view's columns. the content scroll inside keeps 653 // its natural width: forcing it to the full inner width would make it one 654 // column too wide whenever the vertical scrollbar appears, leaving a 655 // phantom horizontal scroll. (height fills via the scroll clipping to the 656 // viewport.) 657 if (constraint.max_size.width) |w| { 658 const detail_w = if (both_panes_fit) w - list_max_width else w; 659 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_w, .height = null }; 660 self.detailOuter().children.values()[detail_scroll_index].min_size = .{ .width = detail_w, .height = null }; 661 } else { 662 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_min_width, .height = null }; 663 self.detailOuter().children.values()[detail_scroll_index].min_size = null; 664 } 665 666 // crossing panes only re-selects the content box's child (focusList / 667 // focusDetail); when the window is too narrow to show both, the pane that 668 // was holding focus is dropped here. the framework recovers focus after 669 // the top-level build by re-deriving it down the selected-child chain, so 670 // there's nothing to fix up afterward. 671 try self.box.build(allocator, constraint, root_focus); 672 673 // clamp the list's initial offset (a selected row near the end of the 674 // list) against this build's grids, for the next frame. initRoot's 675 // pre-sizing build is unbounded — its full-content "viewport" would 676 // clamp the offset to zero, so only a bounded build counts. 677 if (constraint.max_size.height != null) self.listScroll().clampToContent(); 678 } 679 680 fn refreshDetail(self: *View, allocator: std.mem.Allocator, narrow: bool) !void { 681 const next: Shown = .{ .index = self.selectedRowIndex(), .narrow = narrow }; 682 if (std.meta.eql(next, self.shown)) return; 683 try self.populateDetail(allocator, narrow); 684 self.shown = next; 685 } 686 687 fn populateDetail(self: *View, allocator: std.mem.Allocator, narrow: bool) !void { 688 const nav_box = self.navBox(); 689 const inner = self.detailInner(); 690 691 for (nav_box.children.values()) |*child| child.widget.deinit(allocator); 692 nav_box.children.clearAndFree(allocator); 693 nav_box.getFocus().child_id = null; 694 for (inner.children.values()) |*child| child.widget.deinit(allocator); 695 inner.children.clearAndFree(allocator); 696 inner.getFocus().child_id = null; 697 self.back_id = null; 698 699 // only files have contents to show; directories and the ".." row leave 700 // the pane empty. 701 var markdown = false; 702 if (self.selectedEntry()) |entry| { 703 if (!entry.is_dir) { 704 const path = try childDir(self.session.page_arena.allocator(), self.data.dir, entry.name); 705 // with the list hidden beside it, the detail leads with the way 706 // back. an in-page link to this very page, so both hosts hand 707 // its press and enter to detailInput instead of navigating. 708 if (narrow) { 709 const page_arena = self.session.page_arena; 710 const link = try page_arena.allocator().print("ai:{s}", .{try self.session.data.current_page.toUrl(page_arena)}); 711 self.back_id = try addNavButton(allocator, nav_box, "← back to file list", link); 712 } 713 // the window links sit above the scroll, so they stay put 714 // while the content scrolls. 715 if (entry.window_start > 0) try self.addNavLink(allocator, nav_box, "scroll to top", entry, 0); 716 if (entry.has_more) try self.addNavLink(allocator, nav_box, "next lines →", entry, lineNumber(entry.window_start + file_page)); 717 if (!entry.loaded) { 718 // the placeholder carries the file's "a:" link, so enter 719 // (or a click) here loads the file like on its list row. 720 const link = try fileLink(self.session.page_arena, self.data, path, false, 0); 721 try self.addContentBox(allocator, inner, &.{.{ .text = "(press enter to load this file)" }}, link); 722 } else if (entry.is_binary) { 723 try self.addContentBox(allocator, inner, &.{.{ .text = "(binary file)" }}, ""); 724 } else if (isMarkdown(entry.name) and entry.window_start == 0 and !entry.has_more and entry.lines.len <= max_markdown_lines) { 725 const page_arena = self.session.page_arena; 726 const doc = try md.parse(page_arena.allocator(), entry.lines); 727 var view = try Markdown.View.init(allocator, doc, self.data, path, page_arena); 728 errdefer view.deinit(allocator); 729 try inner.children.put(allocator, view.getFocus().id, .{ .widget = .{ .markdown = view }, .rect = null, .min_size = null }); 730 markdown = true; 731 } else { 732 try self.addContentBox(allocator, inner, try numberedContent(self.session.page_arena, self.data, path, entry.lines, entry.window_start), ""); 733 } 734 } 735 } 736 // point each box at its first child so focus can descend into it, and 737 // the pane at its nav row when it has one, else at the content 738 if (nav_box.children.count() > 0) nav_box.getFocus().child_id = nav_box.children.keys()[0]; 739 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 740 self.detailOuter().getFocus().child_id = if (nav_box.children.count() > 0) nav_box.getFocus().id else self.detailScrollFrame().getFocus().id; 741 742 // reserve the nav row's height (the shrink scroll frame yields it). 743 self.detailOuter().children.values()[detail_nav_index].min_size = 744 if (nav_box.children.count() > 0) .{ .width = null, .height = row_height } else null; 745 746 // rendered markdown wraps to the pane's width, so it only scrolls down 747 const sc = self.detailScroll(); 748 sc.options.direction = if (markdown) .vert else .both; 749 750 // reset the scroll to the top for the newly-shown file: directly on the 751 // terminal (the wasm offset), and via a version bump on the web (so the 752 // renderer's scroll id changes and JS drops the preserved position). 753 sc.x = 0; 754 sc.y = 0; 755 sc.getFocus().version +%= 1; 756 } 757 758 // a focusable "next" link above the content. it's an `a:` link to the 759 // selected file at `target_start`, so activating it (the host follows the 760 // link) reloads the page on the next window. 761 fn addNavLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, entry: Entry, target_start: usize) !void { 762 const page_arena = self.session.page_arena; 763 const path = try childDir(page_arena.allocator(), self.data.dir, entry.name); 764 const route = self.data.filesRoute(path, target_start) orelse return error.RouteTooLong; 765 const link = try page_arena.allocator().print("a:{s}", .{try route.toUrl(page_arena)}); 766 _ = try addNavButton(allocator, box, label, link); 767 } 768 769 // a bordered button in the nav row carrying `link`, returning its focus id 770 fn addNavButton(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !usize { 771 var tb = try wgt.TextBox.init(allocator, label, .{ .border = .single, .round_corners = true, .wrap_kind = .none }); 772 errdefer tb.deinit(allocator); 773 tb.getFocus().mode = .all; 774 tb.getFocus().kind = .{ .custom = link }; 775 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 776 return tb.getFocus().id; 777 } 778 779 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 780 if (self.data.no_commits) return self.box.input(allocator, key, root_focus); 781 // scrolling crosses the sub header boundary the same way arrows do 782 const direction = inp.vertDirection(key); 783 if (self.headerActive()) { 784 // active means there is one 785 const header_view = self.header() orelse unreachable; 786 if (direction == .down) { 787 // the empty message has nothing to focus 788 if (!self.data.isEmpty()) root_focus.setFocus(self.contentBox().getFocus().id); 789 return; 790 } 791 if (key == .enter) if (try header_view.submittedText(allocator)) |term| { 792 defer allocator.free(term); 793 return self.submit(term); 794 }; 795 return header_view.input(allocator, key, root_focus); 796 } 797 if (direction == .up and self.contentAtTop() and self.focusHeader(root_focus)) return; 798 if (self.detailActive()) { 799 try self.detailInput(allocator, key, root_focus); 800 } else { 801 try self.listInput(allocator, key, root_focus); 802 } 803 } 804 805 // navigate to the typed term's results, pinned to the listing's ref. an 806 // empty term leaves the results for the plain listing. 807 fn submit(self: *View, term: []const u8) !void { 808 if (term.len == 0 and self.data.find == null) return; 809 const route = self.data.filesRoute("", 0) orelse return; 810 try self.session.navigate(route.withFind(term) orelse return); 811 } 812 813 fn listInput(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 814 // up/down (and the scroll wheel) move the selection; page up/down jump a 815 // fixed amount. right/Enter cross into the detail pane. Enter/clicks on a 816 // directory (or "..") row are turned into navigation by the host 817 // (crossPageLink) before reaching here. 818 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 819 ui.widget.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 820 return; 821 } 822 switch (key) { 823 .enter, .arrow_right => try self.focusDetail(root_focus), 824 // when the window is too narrow to lay out the detail pane beside 825 // the list, a click on a row opens it like enter. the row was just 826 // selected, so the detail is swapped to it ahead of the build. 827 .mouse => |mouse| if (self.contentBox().children.values()[detail_index].rect == null and ui.widget.clickOnSelectedRow(self.listBox(), root_focus, mouse)) { 828 try self.refreshDetail(allocator, true); 829 try self.focusDetail(root_focus); 830 }, 831 else => {}, 832 } 833 } 834 835 // whether focus is on the content box (vs. a "previous"/"next" nav link). 836 fn focusOnContent(self: *View, root_focus: *Focus) bool { 837 const g = root_focus.grandchild_id orelse return false; 838 if (self.markdownView()) |view| return view.owns(g); 839 return self.detailInner().children.contains(g); 840 } 841 842 // the rendered markdown in the detail pane, if that's what it shows 843 fn markdownView(self: *View) ?*Markdown.View { 844 const inner = self.detailInner(); 845 if (inner.children.count() == 0) return null; 846 return switch (inner.children.values()[0].widget) { 847 .markdown => |*view| view, 848 else => null, 849 }; 850 } 851 852 fn detailInput(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 853 // the way back to the list, by enter or a click 854 if (self.back_id) |id| { 855 if (inp.activated(root_focus, id, key)) return self.focusList(root_focus); 856 } 857 const sc = self.detailScroll(); 858 const on_content = self.focusOnContent(root_focus); 859 // the "next" link sits above the content scroll. on the link, left returns 860 // to the file list and down drops into the content. in the content, the 861 // terminal scrolls by offset (the wheel five rows at a time) and reaching 862 // the top then pressing up crosses back up to the link; on the web 863 // vertical scrolling is the browser's job so up just crosses to the link. 864 const step: isize = switch (key) { 865 .scroll_up, .scroll_down => 5, 866 else => 1, 867 }; 868 switch (inp.vertDirection(key)) { 869 .up => { 870 if (!on_content) return; 871 if (self.session.is_terminal and sc.y > 0) { 872 sc.y -= step; 873 self.detailScroll().clampToContent(); 874 } else self.focusNav(root_focus); 875 return; 876 }, 877 .down => { 878 if (!on_content) return self.focusContent(root_focus); 879 if (self.session.is_terminal) { 880 sc.y += step; 881 self.detailScroll().clampToContent(); 882 } 883 return; 884 }, 885 .none => {}, 886 } 887 switch (key) { 888 .arrow_left => { 889 if (on_content) { 890 if (sc.x > 0) { 891 sc.x -= 1; 892 self.detailScroll().clampToContent(); 893 } else try self.focusList(root_focus); 894 } else if (!self.moveNav(root_focus, -1)) { 895 try self.focusList(root_focus); 896 } 897 }, 898 .arrow_right => { 899 if (on_content) { 900 sc.x += 1; 901 self.detailScroll().clampToContent(); 902 } else _ = self.moveNav(root_focus, 1); 903 }, 904 .page_up => if (on_content and self.session.is_terminal) { 905 sc.y -= 10; 906 self.detailScroll().clampToContent(); 907 }, 908 .page_down => if (on_content and self.session.is_terminal) { 909 sc.y += 10; 910 self.detailScroll().clampToContent(); 911 }, 912 .home => if (on_content and self.session.is_terminal) { 913 sc.y = 0; 914 self.detailScroll().clampToContent(); 915 }, 916 .end => if (on_content and self.session.is_terminal) { 917 sc.y = std.math.maxInt(isize); 918 self.detailScroll().clampToContent(); 919 }, 920 // step between the rendered markdown's links; the web leaves tab to the browser 921 .tab, .back_tab => if (on_content and self.session.is_terminal) if (self.markdownView()) |view| { 922 try view.stepLink(allocator, root_focus, sc, 0, 0, key == .tab); 923 }, 924 else => {}, 925 } 926 } 927 928 // focus the first (left-most) nav link; a no-op when there are none, leaving 929 // focus on the content. 930 fn focusNav(self: *View, root_focus: *Focus) void { 931 const nav_box = self.navBox(); 932 if (nav_box.children.count() == 0) return; 933 root_focus.setFocus(nav_box.children.keys()[0]); 934 } 935 936 fn focusContent(self: *View, root_focus: *Focus) void { 937 if (self.markdownView()) |view| return root_focus.setFocus(view.body.id); 938 const inner = self.detailInner(); 939 const id = inner.getFocus().child_id orelse (if (inner.children.count() > 0) inner.children.keys()[0] else return); 940 root_focus.setFocus(id); 941 } 942 943 // move focus `delta` rows within the nav box; returns false (without moving) 944 // when that would step off either end. 945 fn moveNav(self: *View, root_focus: *Focus, delta: isize) bool { 946 const nav_box = self.navBox(); 947 const keys = nav_box.children.keys(); 948 const cur_id = nav_box.getFocus().child_id orelse return false; 949 const cur: isize = @intCast(nav_box.children.getIndex(cur_id) orelse return false); 950 const target = cur + delta; 951 if (target < 0 or target >= @as(isize, @intCast(keys.len))) return false; 952 root_focus.setFocus(keys[@intCast(target)]); 953 return true; 954 } 955 956 // enter the detail pane, landing on the "next" link when there is one (so 957 // right-arrow reaches it), else on the content. a directory or ".." row has 958 // neither, so there's nothing to enter. selecting the frame's child (then 959 // focusing the frame) also handles the too-narrow case where the pane isn't 960 // laid out yet — focus lands inside it after the next build. 961 fn focusDetail(self: *View, root_focus: *Focus) !void { 962 const frame = self.detailOuter(); 963 if (self.navBox().children.count() > 0) { 964 frame.getFocus().child_id = self.navBox().getFocus().id; 965 } else if (self.detailInner().children.count() > 0) { 966 frame.getFocus().child_id = self.detailScrollFrame().getFocus().id; 967 } else return; 968 root_focus.setFocus(frame.getFocus().id); 969 } 970 971 // return to the list. 972 fn focusList(self: *View, root_focus: *Focus) !void { 973 root_focus.setFocus(self.listScroll().getFocus().id); 974 } 975 976 pub fn clearGrid(self: *View) void { 977 self.box.clearGrid(); 978 } 979 980 pub fn getGrid(self: View) ?Grid { 981 return self.box.getGrid(); 982 } 983 984 pub fn getFocus(self: *View) *Focus { 985 return self.box.getFocus(); 986 } 987 988 fn contentAtTop(self: *View) bool { 989 if (self.detailActive()) { 990 if (self.detailOuter().getFocus().child_id == self.navBox().getFocus().id) return true; 991 return self.navBox().children.count() == 0 and 992 (!self.session.is_terminal or self.detailScroll().y == 0); 993 } 994 const lb = self.listBox(); 995 const cid = lb.getFocus().child_id orelse return true; 996 return lb.children.getIndex(cid) == 0; 997 } 998 999 // only the header's own row sits directly below the repository header. 1000 pub fn atTop(self: *View) bool { 1001 if (self.data.no_commits or self.data.isEmpty()) return true; 1002 const focusable = if (self.header()) |header_view| header_view.hasFocusable() else false; 1003 return self.headerActive() or (!focusable and self.contentAtTop()); 1004 } 1005 1006 pub fn focusHeader(self: *View, root_focus: *Focus) bool { 1007 const header_view = self.header() orelse return false; 1008 return header_view.focusHeader(root_focus); 1009 } 1010 }; 1011 1012 // `lines` as spans, each prefixed with its 1-based file line number 1013 // (right-aligned in a column wide enough for the last number, then a space), 1014 // like the diffs view. each number links to the window starting at its line. 1015 // `start` is the window's 0-based first line, so numbers continue across 1016 // paginated windows. 1017 fn numberedContent(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8, lines: []const []const u8, start: usize) ![]const wgt.Span { 1018 const arena = page_arena.allocator(); 1019 const width = std.fmt.count("{d}", .{start + lines.len}); 1020 var spans: std.ArrayList(wgt.Span) = .empty; 1021 for (lines, 0..) |line, i| { 1022 const number = start + i + 1; 1023 const route = data.filesRoute(path, number) orelse return error.RouteTooLong; 1024 try spans.append(arena, .{ .text = try arena.print("{d: >[1]}", .{ number, width }), .link = try route.toUrl(page_arena) }); 1025 try spans.append(arena, .{ .text = try arena.print(" {s}{s}", .{ line, if (i + 1 < lines.len) "\n" else "" }) }); 1026 } 1027 return spans.toOwnedSlice(arena); 1028 } 1029 1030 // the index of the "README"/"README.md" file entry (case-insensitive), or null 1031 // if none. used to pick the default selection at the repo root. 1032 fn readmeIndex(entries: []const Entry) ?usize { 1033 for (entries, 0..) |entry, i| { 1034 if (!entry.is_dir and isReadme(entry.name)) return i; 1035 } 1036 return null; 1037 } 1038 1039 fn isMarkdown(name: []const u8) bool { 1040 const extension = std.Io.Dir.path.extension(name); 1041 return std.ascii.eqlIgnoreCase(extension, ".md") or std.ascii.eqlIgnoreCase(extension, ".markdown"); 1042 } 1043 1044 fn isReadme(name: []const u8) bool { 1045 return std.ascii.eqlIgnoreCase(name, "README") or std.ascii.eqlIgnoreCase(name, "README.md"); 1046 } 1047 1048 // the index of the entry the route named (data.selected_file), or null if none. 1049 fn selectedFileIndex(data: *const Self) ?usize { 1050 const name = data.selected_file orelse return null; 1051 for (data.entries, 0..) |entry, i| { 1052 if (!entry.is_dir and std.mem.eql(u8, entry.name, name)) return i; 1053 } 1054 return null; 1055 } 1056 1057 // an "a:" link to the files route at `path`, pinned to the listing's ref, so 1058 // following it navigates to that directory's listing. 1059 fn dirLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8) ![]const u8 { 1060 const route = data.filesRoute(path, 0) orelse return error.RouteTooLong; 1061 return page_arena.allocator().print("a:{s}", .{try route.toUrl(page_arena)}); 1062 } 1063 1064 // a link to the file's route. a preloaded file gets an "ai:" link 1065 // (crossPageLink ignores it, so a click selects the row in place and shows its 1066 // contents); an unloaded file gets an "a:" link, so activating it reloads the 1067 // page with that file selected and its content read. 1068 fn fileLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8, loaded: bool, line: usize) ![]const u8 { 1069 const route = data.filesRoute(path, line) orelse return error.RouteTooLong; 1070 const prefix = if (loaded) "ai:" else "a:"; 1071 return page_arena.allocator().print("{s}{s}", .{ prefix, try route.toUrl(page_arena) }); 1072 } 1073 1074 // the url `line` value for a content window: its first line's 1-based number, 1075 // except the first window, which serializes as unset (0). 1076 fn lineNumber(window_start: usize) usize { 1077 return if (window_start == 0) 0 else window_start + 1; 1078 } 1079 1080 // `dir`/`name`, or just `name` at the root. 1081 pub fn childDir(arena: std.mem.Allocator, dir: []const u8, name: []const u8) ![]const u8 { 1082 return if (dir.len == 0) name else arena.print("{s}/{s}", .{ dir, name }); 1083 } 1084 1085 // `dir` with its last segment removed ("" when `dir` has a single segment). 1086 fn parentDir(dir: []const u8) []const u8 { 1087 const slash = std.mem.lastIndexOfScalar(u8, dir, '/') orelse return ""; 1088 return dir[0..slash]; 1089 } 1090 1091 // a search result's bottom label: the directory it sits in, empty at the root. 1092 // a directory too wide for the list column is clipped from the left. 1093 fn resultDirLabel(aa: std.mem.Allocator, path: []const u8) ![]const u8 { 1094 const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return ""; 1095 const dir = path[0..slash]; 1096 // the row's border and the label's padding take two columns each 1097 const max_width = View.list_max_width - 4; 1098 var width = try xitui.width.displayWidth(dir); 1099 if (width <= max_width) return aa.print(" {s} ", .{dir}); 1100 1101 const ellipsis = ".."; 1102 var iter = (try std.unicode.Utf8View.init(dir)).iterator(); 1103 var start: usize = 0; 1104 while (width > max_width - ellipsis.len) { 1105 const slice = iter.nextCodepointSlice() orelse break; 1106 width -= xitui.width.cellWidth(try std.unicode.utf8Decode(slice)); 1107 start += slice.len; 1108 } 1109 return aa.print(" " ++ ellipsis ++ "{s} ", .{dir[start..]}); 1110 } 1111