╭ 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 16 const SubHeader = @import("SubHeader.zig"); 17 18 // how many lines of a file's content one window shows before a "next" link. 19 const file_page = 2000; 20 21 // the most directory entries (files + dirs) we read from a tree and display. 22 // each file's content is also loaded (windowed), so an unbounded directory could 23 // add up to a lot of memory; entries past this limit are ignored. 24 // 25 // TODO: this caps what we keep, but `tr.Tree.init` still flattens the entire 26 // repo tree (every path) into memory before we ever apply the cap. read the 27 // directory level-by-level instead, using `obj.Object` to load one tree object 28 // at a time: initCommit -> root tree, then descend each `dir` segment, reading 29 // only the immediate entries of the target tree (and applying max_entries 30 // there). that bounds the work to O(depth) tree objects rather than the whole 31 // repo. it's doable entirely in haxy (no xit change) — `obj.Object(...).init` 32 // on a tree oid already returns just that tree's immediate children. 33 const max_entries = 100; 34 35 // one entry in the directory currently being viewed. 36 pub const Entry = struct { 37 name: []const u8, 38 is_dir: bool, 39 // a file's content window split into lines (each without its trailing 40 // newline); empty for directories and for binary or empty files. 41 lines: []const []const u8 = &.{}, 42 // true when xit's line iterator flagged the file as binary, so the detail 43 // pane shows a placeholder rather than its bytes. 44 is_binary: bool = false, 45 // the line index this window starts at (0 = the first window). non-zero only 46 // for the route's selected file, paginated by the url's `after`. 47 window_start: usize = 0, 48 // whether more lines exist after this window. 49 has_more: bool = false, 50 }; 51 52 // "owner/name", so the view can build /repo/owner/name/files/... links. 53 identity: []const u8, 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 // the directory being viewed, relative to the repo root ("" at the root). 59 dir: []const u8, 60 // a file within `dir` to start selected (so its contents show and the url 61 // carries it), or null to fall back to a README / the first row. set when the 62 // route's path named a file rather than a directory. 63 selected_file: ?[]const u8 = null, 64 entries: []const Entry, 65 // the "viewing <ref> <value>" banner shown above the listing. 66 sub_header: SubHeader, 67 68 const Self = @This(); 69 70 pub fn init( 71 arena: *std.heap.ArenaAllocator, 72 session: *ui.Session, 73 source_maybe: ?ui.RepoSource, 74 identity: []const u8, 75 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 76 requested_value: []const u8, 77 path: []const u8, 78 // the line offset the selected file's content window starts at (0 = first). 79 after: usize, 80 ) !Self { 81 const aa = arena.allocator(); 82 83 // no filesystem (wasm) or nowhere to look: empty listing pinned to whatever 84 // ref the route asked for. the wasm path never calls init anyway — it 85 // rebuilds from the serialized snapshot. 86 const io = session.io orelse return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value, path); 87 const source = source_maybe orelse return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value, path); 88 89 // open + read the committed file list with the arena's backing allocator 90 // (transient; freed before init returns); the listing is built into the 91 // page arena so it outlives them. AnyRepo opens both sha1 and sha256 repos. 92 const gpa = arena.child_allocator; 93 switch (source.repo_kind) { 94 inline else => |repo_kind| { 95 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, gpa, .{ .path = source.path }) catch return emptyResult(aa, identity, requested_ref_or_oid orelse .branch, requested_value, path); 96 defer any_repo.deinit(io, gpa); 97 98 return switch (any_repo) { 99 inline else => |*repo| listing(repo_kind, repo.self_repo_opts, arena, repo, io, gpa, identity, requested_ref_or_oid, requested_value, path, after), 100 }; 101 }, 102 } 103 } 104 105 // build the listing for an opened repo. generic over the repo's backend and 106 // hash kind so the tree/diff types it threads through match the repo's opts. 107 fn listing( 108 comptime repo_kind: rp.RepoKind, 109 comptime repo_opts: rp.RepoOpts(repo_kind), 110 arena: *std.heap.ArenaAllocator, 111 repo: *rp.Repo(repo_kind, repo_opts), 112 io: std.Io, 113 gpa: std.mem.Allocator, 114 identity: []const u8, 115 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 116 requested_value: []const u8, 117 path: []const u8, 118 after: usize, 119 ) !Self { 120 const aa = arena.allocator(); 121 122 // resolve the requested ref (or the default branch) to the commit oid whose 123 // tree we list. a ref the route named explicitly that doesn't resolve is a 124 // bad url (NotFound -> 404); the default-branch path falls through to empty. 125 const resolved = (try ui.ResolvedRefOrOid(repo_kind, repo_opts).init(repo, io, aa, requested_ref_or_oid, requested_value)) orelse { 126 if (requested_ref_or_oid != null) return error.NotFound; 127 return emptyResult(aa, identity, .branch, requested_value, path); 128 }; 129 130 // read the tree at that commit. building the read-only state mirrors what 131 // repo.status does internally, but for an arbitrary commit rather than HEAD. 132 var moment = repo.core.latestMoment() catch return emptyResult(aa, identity, resolved.ref_or_oid, resolved.value, path); 133 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 134 var tree = tr.Tree(repo_kind, repo_opts).init(state, io, gpa, &resolved.oid) catch return emptyResult(aa, identity, resolved.ref_or_oid, resolved.value, path); 135 defer tree.deinit(); 136 137 // `path` names a file when it's an exact tree entry: list its parent 138 // directory and start that file selected. otherwise `path` is the directory. 139 var dir = path; 140 var selected_file: ?[]const u8 = null; 141 if (path.len != 0 and tree.entries.get(path) != null) { 142 const slash = std.mem.lastIndexOfScalar(u8, path, '/'); 143 selected_file = try aa.dupe(u8, if (slash) |s| path[s + 1 ..] else path); 144 dir = if (slash) |s| path[0..s] else ""; 145 } 146 147 // collect the immediate children of `dir`. each committed path is a full 148 // file path; a child is a directory when more path follows its first 149 // segment under `dir`. 150 var children: std.StringArrayHashMapUnmanaged(bool) = .empty; // name -> is_dir 151 defer children.deinit(gpa); 152 const prefix_len = if (dir.len == 0) 0 else dir.len + 1; // skip "dir/" 153 for (tree.entries.keys()) |entry_path| { 154 if (dir.len != 0) { 155 if (!std.mem.startsWith(u8, entry_path, dir) or entry_path.len <= dir.len or entry_path[dir.len] != '/') continue; 156 } 157 const rel = entry_path[prefix_len..]; 158 const slash = std.mem.indexOfScalar(u8, rel, '/'); 159 const name = if (slash) |s| rel[0..s] else rel; 160 const is_dir = slash != null; 161 // stop taking new entries once we hit the cap; the rest are ignored. 162 if (children.count() >= max_entries and !children.contains(name)) continue; 163 const gop = try children.getOrPut(gpa, name); 164 if (!gop.found_existing) gop.value_ptr.* = is_dir else if (is_dir) gop.value_ptr.* = true; 165 } 166 167 // trees hold no empty directories, so a non-root `dir` with no children 168 // doesn't exist in this ref — a bad url (404). 169 if (dir.len != 0 and children.count() == 0) return error.NotFound; 170 171 // committed paths come out sorted (tree objects are written in sorted 172 // order), so the deduped children are already in name order. just group 173 // directories before files, keeping that order within each group, and dupe 174 // into the page arena. each file's contents are read here (into the page 175 // arena) so the detail pane can show them without another lookup. 176 const entries = try aa.alloc(Entry, children.count()); 177 var i: usize = 0; 178 for ([_]bool{ true, false }) |want_dir| { 179 for (children.keys(), children.values()) |name, is_dir| { 180 if (is_dir != want_dir) continue; 181 var entry: Entry = .{ .name = try aa.dupe(u8, name), .is_dir = is_dir }; 182 if (!is_dir) { 183 const file_path = try childDir(aa, dir, name); 184 if (tree.entries.get(file_path)) |tree_entry| { 185 // only the route's selected file paginates; the rest show 186 // their first window (for the in-page detail when selected). 187 const is_selected = if (selected_file) |sf| std.mem.eql(u8, sf, name) else false; 188 const window_start = if (is_selected) after else 0; 189 const content = readFileContent(repo_kind, repo_opts, state, io, gpa, aa, file_path, tree_entry, window_start) catch 190 FileContent{ .lines = &.{} }; 191 entry.lines = content.lines; 192 entry.is_binary = content.is_binary; 193 entry.window_start = window_start; 194 entry.has_more = content.has_more; 195 } 196 } 197 entries[i] = entry; 198 i += 1; 199 } 200 } 201 202 return .{ 203 .identity = try aa.dupe(u8, identity), 204 .ref_or_oid = resolved.ref_or_oid, 205 .ref_or_oid_value = resolved.value, 206 .dir = try aa.dupe(u8, dir), 207 .selected_file = selected_file, 208 .entries = entries, 209 .sub_header = try SubHeader.init(aa, resolved.ref_or_oid, resolved.value), 210 }; 211 } 212 213 const FileContent = struct { 214 lines: []const []const u8, 215 is_binary: bool = false, 216 has_more: bool = false, 217 }; 218 219 // read the window [start, start+file_page) of a committed file's contents at 220 // `tree_entry` into `arena`-owned lines, flagging whether more follow. xit's 221 // line iterator flags binary files (its source becomes `.binary`), in which case 222 // we report no lines and let the view show a placeholder. 223 fn readFileContent( 224 comptime repo_kind: rp.RepoKind, 225 comptime repo_opts: rp.RepoOpts(repo_kind), 226 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 227 io: std.Io, 228 gpa: std.mem.Allocator, 229 arena: std.mem.Allocator, 230 path: []const u8, 231 tree_entry: tr.TreeEntry(repo_opts.hash), 232 start: usize, 233 ) !FileContent { 234 var line_iter = try df.LineIterator(repo_kind, repo_opts).initFromTree(state, io, gpa, path, tree_entry); 235 defer line_iter.deinit(); 236 if (line_iter.source == .binary) return .{ .lines = &.{}, .is_binary = true }; 237 238 // init reads through the file to validate it (and buffer it in memory), so 239 // the line count is known and a window can be sliced out of the buffer. 240 const total = line_iter.count(); 241 const end = @min(start + file_page, total); 242 243 var lines: std.ArrayList([]const u8) = .empty; 244 var i = start; 245 while (i < end) : (i += 1) { 246 const line = try line_iter.get(i); 247 defer line_iter.free(line); 248 try lines.append(arena, try arena.dupe(u8, line)); 249 } 250 return .{ 251 .lines = try lines.toOwnedSlice(arena), 252 .has_more = end < total, 253 }; 254 } 255 256 // an empty listing pinned to a ref, for the wasm / no-repo / unresolved paths. 257 fn emptyResult(aa: std.mem.Allocator, identity: []const u8, ref_or_oid: ui.RoutablePage.RefOrOid, ref_or_oid_value: []const u8, dir: []const u8) !Self { 258 return .{ 259 .identity = try aa.dupe(u8, identity), 260 .ref_or_oid = ref_or_oid, 261 .ref_or_oid_value = try aa.dupe(u8, ref_or_oid_value), 262 .dir = try aa.dupe(u8, dir), 263 .entries = &.{}, 264 .sub_header = try SubHeader.init(aa, ref_or_oid, ref_or_oid_value), 265 }; 266 } 267 268 pub const View = struct { 269 // a vertical stack: the "viewing <ref>" banner on top, then a horizontal 270 // split with the file/directory list on the left and a detail pane on the 271 // right showing the selected file's contents. 272 box: wgt.Box(ui.Widget), // vert: [sub_header_index] = banner, [content_index] = split 273 data: *const Self, 274 session: *ui.Session, 275 // the list row whose contents the detail pane currently shows. 276 shown_index: ?usize, 277 278 const sub_header_index: usize = 0; 279 const content_index: usize = 1; 280 // indices within the content box (the horizontal split). 281 const list_index: usize = 0; 282 const detail_index: usize = 1; 283 // indices within the detail pane frame (nav box above the content scroll). 284 const detail_nav_index: usize = 0; 285 const detail_scroll_index: usize = 1; 286 const list_max_width: usize = 40; 287 const detail_min_width: usize = 40; 288 289 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 290 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 291 errdefer outer.deinit(allocator); 292 293 // the ref banner at the top. 294 { 295 var sub_header = try SubHeader.View.init(allocator, &data.sub_header, session); 296 errdefer sub_header.deinit(allocator); 297 try outer.children.put(allocator, sub_header.getFocus().id, .{ .widget = .{ .repo_sub_header = sub_header }, .rect = null, .min_size = .{ .width = null, .height = 3 } }); 298 } 299 300 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 301 errdefer box.deinit(allocator); 302 303 // the directory listing on the left (one focusable row each). 304 { 305 var list_scroll = blk: { 306 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 307 errdefer list_box.deinit(allocator); 308 309 // labels and link kinds are borrowed by the rows, so they live in 310 // the page arena (as long as this page's widget tree). 311 const aa = session.page_arena.allocator(); 312 if (data.dir.len != 0) { 313 try addRow(allocator, &list_box, "..", try dirLink(session.page_arena, data, parentDir(data.dir))); 314 } 315 for (data.entries) |entry| { 316 const path = try childDir(aa, data.dir, entry.name); 317 const label = if (entry.is_dir) try std.fmt.allocPrint(aa, "{s}/", .{entry.name}) else entry.name; 318 const link = if (entry.is_dir) 319 try dirLink(session.page_arena, data, path) 320 else 321 try fileLink(session.page_arena, data, path); 322 try addRow(allocator, &list_box, label, link); 323 } 324 // select the file the route named, else prefer a README so its 325 // contents greet the visitor in the detail pane, else the first 326 // row. a non-root directory has a leading ".." row, so the entry 327 // index is offset by one there. 328 if (list_box.children.count() > 0) { 329 const base: usize = if (data.dir.len != 0) 1 else 0; 330 const entry_idx = selectedFileIndex(data) orelse readmeIndex(data.entries); 331 const sel = if (entry_idx) |i| i + base else 0; 332 list_box.getFocus().child_id = list_box.children.keys()[sel]; 333 } 334 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert, .web_native = !session.is_terminal }); 335 }; 336 errdefer list_scroll.deinit(allocator); 337 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 } }); 338 } 339 340 // the detail pane on the right — a "next" nav box above a scroll of the 341 // selected file's content window. both are repopulated per selection by 342 // populateDetail. 343 { 344 var detail_outer = blk: { 345 var frame = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 346 errdefer frame.deinit(allocator); 347 348 { 349 var nav_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 350 errdefer nav_box.deinit(allocator); 351 try frame.children.put(allocator, nav_box.getFocus().id, .{ .widget = .{ .box = nav_box }, .rect = null, .min_size = null }); 352 } 353 { 354 // the content scroll wrapped in a bordered box; build sets the 355 // border single normally and double when the content is focused 356 // (the content box itself is borderless). 357 var scroll_frame = blk2: { 358 var detail_scroll = blk3: { 359 var detail_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 360 errdefer detail_inner.deinit(allocator); 361 break :blk3 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = detail_inner }, .{ .direction = .both, .web_native = !session.is_terminal, .fill = true }); 362 }; 363 errdefer detail_scroll.deinit(allocator); 364 var sf = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = .single, .rounded_corners = true, .direction = .vert }); 365 errdefer sf.deinit(allocator); 366 // the wrapper's selected child is its scroll, so the focus 367 // chain reaches the content box (populateDetail points the 368 // scroll's inner box at it). 369 sf.getFocus().child_id = detail_scroll.getFocus().id; 370 try sf.children.put(allocator, detail_scroll.getFocus().id, .{ .widget = .{ .scroll = detail_scroll }, .rect = null, .min_size = null }); 371 break :blk2 sf; 372 }; 373 errdefer scroll_frame.deinit(allocator); 374 // entering the detail pane lands on the content scroll (focus 375 // recovery descends the frame's selected child). the nav links 376 // above are reached by scrolling to the top, then up. 377 frame.getFocus().child_id = scroll_frame.getFocus().id; 378 try frame.children.put(allocator, scroll_frame.getFocus().id, .{ .widget = .{ .box = scroll_frame }, .rect = null, .min_size = null }); 379 } 380 break :blk frame; 381 }; 382 errdefer detail_outer.deinit(allocator); 383 try box.children.put(allocator, detail_outer.getFocus().id, .{ .widget = .{ .box = detail_outer }, .rect = null, .min_size = .{ .width = detail_min_width, .height = null } }); 384 } 385 386 box.getFocus().child_id = box.children.keys()[list_index]; 387 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 388 389 // focus lives in the split; the banner isn't focusable. 390 outer.getFocus().child_id = outer.children.keys()[content_index]; 391 return .{ .box = outer, .data = data, .session = session, .shown_index = null }; 392 } 393 394 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, link: []const u8) !void { 395 var row = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 396 errdefer row.deinit(allocator); 397 row.getFocus().focusable = true; 398 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 399 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null }); 400 } 401 402 // the selected file's contents as a single focusable multi-line text box. 403 // it's borderless — the border lives on the surrounding scroll frame, which 404 // doubles when this content is focused. `text` lives in the page arena. 405 fn addContentBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), text: []const u8) !void { 406 _ = self; 407 var tb = try wgt.TextBox(ui.Widget).init(allocator, text, .{ .border_style = null, .wrap_kind = .none }); 408 errdefer tb.deinit(allocator); 409 tb.getFocus().focusable = true; 410 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 411 } 412 413 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 414 self.box.deinit(allocator); 415 } 416 417 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 418 return &self.box.children.values()[content_index].widget.box; 419 } 420 421 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 422 return &self.contentBox().children.values()[list_index].widget.scroll; 423 } 424 425 fn listBox(self: *View) *wgt.Box(ui.Widget) { 426 return &self.listScroll().child.box; 427 } 428 429 fn detailOuter(self: *View) *wgt.Box(ui.Widget) { 430 return &self.contentBox().children.values()[detail_index].widget.box; 431 } 432 433 fn navBox(self: *View) *wgt.Box(ui.Widget) { 434 return &self.detailOuter().children.values()[detail_nav_index].widget.box; 435 } 436 437 // the bordered box wrapping the content scroll (border toggles with focus). 438 fn detailScrollFrame(self: *View) *wgt.Box(ui.Widget) { 439 return &self.detailOuter().children.values()[detail_scroll_index].widget.box; 440 } 441 442 fn detailScroll(self: *View) *wgt.Scroll(ui.Widget) { 443 return &self.detailScrollFrame().children.values()[0].widget.scroll; 444 } 445 446 fn detailInner(self: *View) *wgt.Box(ui.Widget) { 447 return &self.detailScroll().child.box; 448 } 449 450 fn detailActive(self: *View) bool { 451 const content = self.contentBox(); 452 const cid = content.getFocus().child_id orelse return false; 453 return content.children.getIndex(cid) == detail_index; 454 } 455 456 // the selected list row's index, or null when nothing is focused. 457 fn selectedRowIndex(self: *View) ?usize { 458 const lb = self.listBox(); 459 const cid = lb.getFocus().child_id orelse return null; 460 return lb.children.getIndex(cid); 461 } 462 463 // the entry the selected row points at, or null for the ".." row (which 464 // isn't an entry). directory rows return their entry too, though they carry 465 // no contents. 466 fn selectedEntry(self: *View) ?Entry { 467 const idx = self.selectedRowIndex() orelse return null; 468 const base: usize = if (self.data.dir.len != 0) 1 else 0; // skip the ".." row 469 if (idx < base) return null; 470 const e = idx - base; 471 if (e >= self.data.entries.len) return null; 472 return self.data.entries[e]; 473 } 474 475 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 476 self.clearGrid(); 477 478 // swap the detail pane to the selected entry when the selection changes. 479 try self.refreshDetail(allocator); 480 481 // mirror the selected file into the url so it updates as the selection 482 // moves, but only while focus is inside this view (so landing on the tab 483 // keeps the page's base route). a file selection carries the file path and 484 // its content window offset; a directory / ".." row (or no selection) 485 // stays at the directory with no offset. the path is joined in a stack 486 // buffer since build runs every frame on the web. 487 if (root_focus.grandchild_id) |g| { 488 if (self.box.getFocus().children.contains(g)) { 489 var buf: [ui.RoutablePage.repo_route_max_len]u8 = undefined; 490 var sel_path = self.data.dir; 491 var sel_after: usize = 0; 492 if (self.selectedEntry()) |entry| { 493 if (!entry.is_dir) { 494 sel_path = if (self.data.dir.len == 0) 495 entry.name 496 else 497 std.fmt.bufPrint(&buf, "{s}/{s}", .{ self.data.dir, entry.name }) catch self.data.dir; 498 sel_after = entry.window_start; 499 } 500 } 501 if (ui.RoutablePage.repoFilesRoute(self.data.identity, self.data.ref_or_oid, self.data.ref_or_oid_value, sel_path, sel_after)) |route| 502 self.session.data.current_page = route; 503 } 504 } 505 506 // the selected list row shows a border (the focused TextBox upgrades it 507 // to a double border itself); the rest stay borderless. 508 const lb = self.listBox(); 509 for (lb.children.keys(), lb.children.values()) |id, *child| { 510 switch (child.widget) { 511 .text_box => |*tb| tb.options.border_style = if (lb.getFocus().child_id == id) .single else .hidden, 512 else => {}, 513 } 514 } 515 516 // the content scroll's border is single normally and double when the 517 // content is focused (the content box itself is borderless). 518 const has_content = self.detailInner().children.count() > 0; 519 const content_focused = if (root_focus.grandchild_id) |g| self.detailInner().children.contains(g) else false; 520 self.detailScrollFrame().options.border_style = if (!has_content) null else if (content_focused) .double else .single; 521 522 // same for the "next" link above the content. 523 const nav_box = self.navBox(); 524 for (nav_box.children.keys(), nav_box.children.values()) |id, *child| { 525 switch (child.widget) { 526 .text_box => |*tb| tb.options.border_style = if (nav_box.getFocus().child_id == id) .single else .hidden, 527 else => {}, 528 } 529 } 530 531 // cap the list at list_max_width only while the detail pane fits beside 532 // it. the box drops the detail pane when the width can't hold both 533 // minimums, so when it's that narrow we lift the cap and let the list 534 // fill the whole width. 535 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + detail_min_width else true; 536 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 537 538 // stretch the detail pane and its bordered scroll frame across the rest 539 // of the width so the pane fills the area rather than shrinking to its 540 // content, like the refs view's columns. the content scroll inside keeps 541 // its natural width: forcing it to the full inner width would make it one 542 // column too wide whenever the vertical scrollbar appears, leaving a 543 // phantom horizontal scroll. (height fills via the scroll clipping to the 544 // viewport.) 545 if (constraint.max_size.width) |w| { 546 const detail_w = if (both_panes_fit) w - list_max_width else w; 547 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_w, .height = null }; 548 self.detailOuter().children.values()[detail_scroll_index].min_size = .{ .width = detail_w, .height = null }; 549 } else { 550 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_min_width, .height = null }; 551 self.detailOuter().children.values()[detail_scroll_index].min_size = null; 552 } 553 554 // crossing panes only re-selects the content box's child (focusList / 555 // focusDetail); when the window is too narrow to show both, the pane that 556 // was holding focus is dropped here. the framework recovers focus after 557 // the top-level build by re-deriving it down the selected-child chain, so 558 // there's nothing to fix up afterward. 559 try self.box.build(allocator, constraint, root_focus); 560 } 561 562 fn refreshDetail(self: *View, allocator: std.mem.Allocator) !void { 563 const cur = self.selectedRowIndex(); 564 if (std.meta.eql(cur, self.shown_index)) return; 565 try self.populateDetail(allocator); 566 self.shown_index = cur; 567 } 568 569 fn populateDetail(self: *View, allocator: std.mem.Allocator) !void { 570 const nav_box = self.navBox(); 571 const inner = self.detailInner(); 572 573 for (nav_box.children.values()) |*child| child.widget.deinit(allocator); 574 nav_box.children.clearAndFree(allocator); 575 nav_box.getFocus().child_id = null; 576 for (inner.children.values()) |*child| child.widget.deinit(allocator); 577 inner.children.clearAndFree(allocator); 578 inner.getFocus().child_id = null; 579 580 // only files have contents to show; directories and the ".." row leave 581 // the pane empty. 582 if (self.selectedEntry()) |entry| { 583 if (!entry.is_dir) { 584 // the "next" window link sits above the scroll, so it stays put 585 // while the content scrolls. 586 if (entry.has_more) try self.addNavLink(allocator, nav_box, "next lines →", entry, entry.window_start + file_page); 587 if (entry.is_binary) { 588 try self.addContentBox(allocator, inner, "(binary file)"); 589 } else { 590 const text = try numberedContent(self.session.page_arena.allocator(), entry.lines, entry.window_start); 591 try self.addContentBox(allocator, inner, text); 592 } 593 } 594 } 595 // point each box at its first child so focus can descend into it. 596 if (nav_box.children.count() > 0) nav_box.getFocus().child_id = nav_box.children.keys()[0]; 597 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 598 599 // reset the scroll to the top for the newly-shown file: directly on the 600 // terminal (the wasm offset), and via a version bump on the web (so the 601 // renderer's scroll id changes and JS drops the preserved position). 602 const sc = self.detailScroll(); 603 sc.x = 0; 604 sc.y = 0; 605 sc.getFocus().version +%= 1; 606 } 607 608 // a focusable "next" link above the content. it's an `a:` link to the 609 // selected file at `target_after`, so activating it (the host follows the 610 // link) reloads the page on the next window. 611 fn addNavLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, entry: Entry, target_after: usize) !void { 612 const page_arena = self.session.page_arena; 613 const path = try childDir(page_arena.allocator(), self.data.dir, entry.name); 614 const route = ui.RoutablePage.repoFilesRoute(self.data.identity, self.data.ref_or_oid, self.data.ref_or_oid_value, path, target_after) orelse return error.RouteTooLong; 615 const link = try std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{try route.urlAlloc(page_arena)}); 616 var tb = try wgt.TextBox(ui.Widget).init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 617 errdefer tb.deinit(allocator); 618 tb.getFocus().focusable = true; 619 tb.getFocus().kind = .{ .custom = link }; 620 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 621 } 622 623 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 624 _ = allocator; 625 if (self.detailActive()) { 626 try self.detailInput(key, root_focus); 627 } else { 628 try self.listInput(key, root_focus); 629 } 630 } 631 632 fn listInput(self: *View, key: Key, root_focus: *Focus) !void { 633 // up/down (and the scroll wheel) move the selection; page up/down jump a 634 // fixed amount. right/Enter cross into the detail pane. Enter/clicks on a 635 // directory (or "..") row are turned into navigation by the host 636 // (crossPageLink) before reaching here. 637 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 638 ui.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 639 return; 640 } 641 switch (key) { 642 .enter, .arrow_right => try self.focusDetail(root_focus), 643 else => {}, 644 } 645 } 646 647 // whether focus is on the content box (vs. a "previous"/"next" nav link). 648 fn focusOnContent(self: *View, root_focus: *Focus) bool { 649 const g = root_focus.grandchild_id orelse return false; 650 return self.detailInner().children.contains(g); 651 } 652 653 fn detailInput(self: *View, key: Key, root_focus: *Focus) !void { 654 const sc = self.detailScroll(); 655 const on_content = self.focusOnContent(root_focus); 656 // the "next" link sits above the content scroll. on the link, left returns 657 // to the file list and down drops into the content. in the content, the 658 // terminal scrolls by offset and reaching the top then pressing up crosses 659 // back up to the link; on the web vertical scrolling is the browser's job 660 // so up just crosses to the link. 661 switch (key) { 662 .arrow_left => { 663 if (on_content) { 664 if (sc.x > 0) { 665 sc.x -= 1; 666 self.detailScroll().clampToContent(); 667 } else try self.focusList(root_focus); 668 } else if (!self.moveNav(root_focus, -1)) { 669 try self.focusList(root_focus); 670 } 671 }, 672 .arrow_right => { 673 if (on_content) { 674 sc.x += 1; 675 self.detailScroll().clampToContent(); 676 } else _ = self.moveNav(root_focus, 1); 677 }, 678 .arrow_up => { 679 if (on_content) { 680 if (self.session.is_terminal and sc.y > 0) { 681 sc.y -= 1; 682 self.detailScroll().clampToContent(); 683 } else self.focusNav(root_focus); // cross up to the links 684 } 685 }, 686 .arrow_down => { 687 if (on_content) { 688 if (self.session.is_terminal) { 689 sc.y += 1; 690 self.detailScroll().clampToContent(); 691 } 692 } else self.focusContent(root_focus); // links -> content 693 }, 694 .page_up => if (on_content and self.session.is_terminal) { 695 sc.y -= 10; 696 self.detailScroll().clampToContent(); 697 }, 698 .page_down => if (on_content and self.session.is_terminal) { 699 sc.y += 10; 700 self.detailScroll().clampToContent(); 701 }, 702 .home => if (on_content and self.session.is_terminal) { 703 sc.y = 0; 704 self.detailScroll().clampToContent(); 705 }, 706 .end => if (on_content and self.session.is_terminal) { 707 sc.y = std.math.maxInt(isize); 708 self.detailScroll().clampToContent(); 709 }, 710 .mouse => |mouse| switch (mouse.action) { 711 .scroll => |dir| if (on_content and self.session.is_terminal) { 712 sc.y += if (dir == .up) -5 else 5; 713 self.detailScroll().clampToContent(); 714 }, 715 else => {}, 716 }, 717 else => {}, 718 } 719 } 720 721 // focus the first (left-most) nav link; a no-op when there are none, leaving 722 // focus on the content. 723 fn focusNav(self: *View, root_focus: *Focus) void { 724 const nav_box = self.navBox(); 725 if (nav_box.children.count() == 0) return; 726 root_focus.setFocus(nav_box.children.keys()[0]); 727 } 728 729 fn focusContent(self: *View, root_focus: *Focus) void { 730 const inner = self.detailInner(); 731 const id = inner.getFocus().child_id orelse (if (inner.children.count() > 0) inner.children.keys()[0] else return); 732 root_focus.setFocus(id); 733 } 734 735 // move focus `delta` rows within the nav box; returns false (without moving) 736 // when that would step off either end. 737 fn moveNav(self: *View, root_focus: *Focus, delta: isize) bool { 738 const nav_box = self.navBox(); 739 const keys = nav_box.children.keys(); 740 const cur_id = nav_box.getFocus().child_id orelse return false; 741 const cur: isize = @intCast(nav_box.children.getIndex(cur_id) orelse return false); 742 const target = cur + delta; 743 if (target < 0 or target >= @as(isize, @intCast(keys.len))) return false; 744 root_focus.setFocus(keys[@intCast(target)]); 745 return true; 746 } 747 748 // enter the detail pane, landing on the "next" link when there is one (so 749 // right-arrow reaches it), else on the content. a directory or ".." row has 750 // neither, so there's nothing to enter. selecting the frame's child (then 751 // focusing the frame) also handles the too-narrow case where the pane isn't 752 // laid out yet — focus lands inside it after the next build. 753 fn focusDetail(self: *View, root_focus: *Focus) !void { 754 const frame = self.detailOuter(); 755 if (self.navBox().children.count() > 0) { 756 frame.getFocus().child_id = self.navBox().getFocus().id; 757 } else if (self.detailInner().children.count() > 0) { 758 frame.getFocus().child_id = self.detailScrollFrame().getFocus().id; 759 } else return; 760 root_focus.setFocus(frame.getFocus().id); 761 } 762 763 // return to the list. 764 fn focusList(self: *View, root_focus: *Focus) !void { 765 root_focus.setFocus(self.listScroll().getFocus().id); 766 } 767 768 pub fn clearGrid(self: *View) void { 769 self.box.clearGrid(); 770 } 771 772 pub fn getGrid(self: View) ?Grid { 773 return self.box.getGrid(); 774 } 775 776 pub fn getFocus(self: *View) *Focus { 777 return self.box.getFocus(); 778 } 779 780 // for the parent's "scroll up at the top jumps to the header" check. inside 781 // the detail pane up-arrow stays in the pane (scrolling); when the list holds 782 // focus, report its selection directly so up-arrow at the top row ascends. 783 pub fn getSelectedIndex(self: *View) ?usize { 784 if (self.detailActive()) return 1; 785 const lb = self.listBox(); 786 const cid = lb.getFocus().child_id orelse return null; 787 return lb.children.getIndex(cid); 788 } 789 }; 790 791 // join `lines` into one string, each prefixed with its 1-based file line number 792 // (right-aligned in a column wide enough for the last number, then a space), 793 // like the diffs view. `start` is the window's 0-based first line, so numbers 794 // continue across paginated windows. 795 fn numberedContent(arena: std.mem.Allocator, lines: []const []const u8, start: usize) ![]const u8 { 796 if (lines.len == 0) return ""; 797 const width = std.fmt.count("{d}", .{start + lines.len}); 798 const indent = try arena.alloc(u8, width); 799 @memset(indent, ' '); 800 801 var out: std.ArrayList(u8) = .empty; 802 for (lines, 0..) |line, i| { 803 if (i != 0) try out.append(arena, '\n'); 804 const num_str = try std.fmt.allocPrint(arena, "{d}", .{start + i + 1}); 805 try out.appendSlice(arena, indent[0 .. width - num_str.len]); 806 try out.appendSlice(arena, num_str); 807 try out.append(arena, ' '); 808 try out.appendSlice(arena, line); 809 } 810 return out.toOwnedSlice(arena); 811 } 812 813 // the index of the "README"/"README.md" file entry (case-insensitive), or null 814 // if none. used to pick the default selection at the repo root. 815 fn readmeIndex(entries: []const Entry) ?usize { 816 for (entries, 0..) |entry, i| { 817 if (entry.is_dir) continue; 818 if (std.ascii.eqlIgnoreCase(entry.name, "README") or std.ascii.eqlIgnoreCase(entry.name, "README.md")) 819 return i; 820 } 821 return null; 822 } 823 824 // the index of the entry the route named (data.selected_file), or null if none. 825 fn selectedFileIndex(data: *const Self) ?usize { 826 const name = data.selected_file orelse return null; 827 for (data.entries, 0..) |entry, i| { 828 if (!entry.is_dir and std.mem.eql(u8, entry.name, name)) return i; 829 } 830 return null; 831 } 832 833 // an "a:" link to the files route at `path`, pinned to the listing's ref, so 834 // following it navigates to that directory's listing. 835 fn dirLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8) ![]const u8 { 836 const route = ui.RoutablePage.repoFilesRoute(data.identity, data.ref_or_oid, data.ref_or_oid_value, path, 0) orelse return error.RouteTooLong; 837 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{try route.urlAlloc(page_arena)}); 838 } 839 840 // an "ai:" link to the file's route: crossPageLink ignores it, so a wasm click 841 // selects the row in place and shows its contents in the detail pane. 842 fn fileLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8) ![]const u8 { 843 const route = ui.RoutablePage.repoFilesRoute(data.identity, data.ref_or_oid, data.ref_or_oid_value, path, 0) orelse return error.RouteTooLong; 844 return std.fmt.allocPrint(page_arena.allocator(), "ai:{s}", .{try route.urlAlloc(page_arena)}); 845 } 846 847 // `dir`/`name`, or just `name` at the root. 848 pub fn childDir(arena: std.mem.Allocator, dir: []const u8, name: []const u8) ![]const u8 { 849 return if (dir.len == 0) name else std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, name }); 850 } 851 852 // `dir` with its last segment removed ("" when `dir` has a single segment). 853 fn parentDir(dir: []const u8) []const u8 { 854 const slash = std.mem.lastIndexOfScalar(u8, dir, '/') orelse return ""; 855 return dir[0..slash]; 856 } 857