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