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