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