╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
264 .home_users, .home_repos, .home_settings, .home_auth => .home, 265 .user_repos, .user_settings, .user_auth => .user, 266 .repo_files, .repo_commits, .repo_refs, .repo_settings, .repo_auth => .repo, 267 }; 268 } 269 270 // parse a path plus its raw query string 271 pub fn fromUrl(path: []const u8, query: ?[]const u8) ?RoutablePage { 272 const after = uintParam(query, "after") orelse 0; 273 if (std.mem.eql(u8, path, "/")) return default; 274 if (std.mem.eql(u8, path, "/users")) return .{ .home_users = after }; 275 if (std.mem.eql(u8, path, "/repos")) return .{ .home_repos = after }; 276 if (std.mem.eql(u8, path, "/settings")) return .home_settings; 277 if (std.mem.eql(u8, path, "/auth")) return .home_auth; 278 // /user/<name>[/repos|/settings|/auth] 279 if (std.mem.startsWith(u8, path, user_segment)) { 280 const rest = path[user_segment.len..]; 281 const slash = std.mem.indexOfScalar(u8, rest, '/'); 282 const name = if (slash) |s| rest[0..s] else rest; 283 if (name.len == 0) return null; 284 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 285 if (slash) |s| { 286 const sub = rest[s + 1 ..]; 287 if (std.mem.eql(u8, sub, "repos")) return .{ .user_repos = .{ .name = parsed, .after = after } }; 288 if (std.mem.eql(u8, sub, "settings")) return .{ .user_settings = parsed }; 289 if (std.mem.eql(u8, sub, "auth")) return .{ .user_auth = parsed }; 290 return null; // unknown sub-path 291 } 292 return .{ .user_repos = .{ .name = parsed, .after = after } }; 293 } 294 // /repo/<username>/<reponame> (files root), then optionally /settings, 295 // /auth, or /files/<dir> for a directory in the files tab. the `repo` 296 // variant stores "username/reponame" (root) or 297 // "username/reponame/files/<dir>"; settings/auth store just the pair. 298 if (std.mem.startsWith(u8, path, repo_segment)) { 299 const rest = path[repo_segment.len..]; 300 const user_slash = std.mem.indexOfScalar(u8, rest, '/') orelse return null; 301 const after_user = rest[user_slash + 1 ..]; 302 const repo_slash = std.mem.indexOfScalar(u8, after_user, '/'); 303 const repo_name = if (repo_slash) |s| after_user[0..s] else after_user; 304 // reject an empty username or reponame 305 if (user_slash == 0 or repo_name.len == 0) return null; 306 const pair = rest[0 .. user_slash + 1 + repo_name.len]; // "username/reponame" 307 if (repo_slash) |s| { 308 const sub = after_user[s + 1 ..]; 309 if (std.mem.eql(u8, sub, "refs")) return .{ .repo_refs = .{ 310 .name = Array(repo_route_max_len).from(pair) orelse return null, 311 .kind = refsKind(query), 312 .after = after, 313 } }; 314 if (std.mem.eql(u8, sub, "settings")) return .{ .repo_settings = Array(repo_route_max_len).from(pair) orelse return null }; 315 if (std.mem.eql(u8, sub, "auth")) return .{ .repo_auth = Array(repo_route_max_len).from(pair) orelse return null }; 316 if (std.mem.eql(u8, sub, files_seg)) return repoFilesRoute(pair, null, "", "", after); // trailing /files == default-branch root 317 if (std.mem.startsWith(u8, sub, files_seg ++ "/")) { 318 // "files/<refkind>/<refvalue>[/<dir>]" 319 const ref_part = sub[files_seg.len + 1 ..]; 320 const k1 = std.mem.indexOfScalar(u8, ref_part, '/') orelse return null; 321 const kind = RefOrOid.fromSeg(ref_part[0..k1]) orelse return null; 322 const after_kind = ref_part[k1 + 1 ..]; 323 const k2 = std.mem.indexOfScalar(u8, after_kind, '/'); 324 const value = if (k2) |i| after_kind[0..i] else after_kind; 325 if (value.len == 0) return null; 326 const dir = if (k2) |i| after_kind[i + 1 ..] else ""; 327 return repoFilesRoute(pair, kind, value, dir, after); 328 } 329 if (std.mem.eql(u8, sub, commits_seg)) return repoCommitsRoute(pair, null, "", after); // trailing /commits == default branch 330 if (std.mem.startsWith(u8, sub, commits_seg ++ "/")) { 331 // "commits/<refkind>/<refvalue>" 332 const ref_part = sub[commits_seg.len + 1 ..]; 333 const k1 = std.mem.indexOfScalar(u8, ref_part, '/') orelse return null; 334 const kind = RefOrOid.fromSeg(ref_part[0..k1]) orelse return null; 335 const value = ref_part[k1 + 1 ..]; 336 if (value.len == 0) return null; 337 return repoCommitsRoute(pair, kind, value, after); 338 } 339 return null; // unknown sub-path 340 } 341 return repoFilesRoute(pair, null, "", "", after); 342 } 343 return null; 344 } 345 346 // the refs column a "kind=" query param names; absent or unrecognized reads 347 // as the branches column. 348 fn refsKind(query: ?[]const u8) RefKind { 349 const qs = query orelse return .branch; 350 var it = std.mem.splitScalar(u8, qs, '&'); 351 while (it.next()) |pair| { 352 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 353 if (std.mem.eql(u8, pair[0..eq], "kind") and std.mem.eql(u8, pair[eq + 1 ..], "tag")) return .tag; 354 } 355 return .branch; 356 } 357 358 // read a "key=<uint>" value from a raw "a=1&b=2" query string. 359 fn uintParam(query: ?[]const u8, key: []const u8) ?usize { 360 const qs = query orelse return null; 361 var it = std.mem.splitScalar(u8, qs, '&'); 362 while (it.next()) |pair| { 363 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 364 if (std.mem.eql(u8, pair[0..eq], key)) 365 return std.fmt.parseInt(usize, pair[eq + 1 ..], 10) catch null; 366 } 367 return null; 368 } 369 370 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 371 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 372 return switch (a) { 373 .home_users => |a_after| a_after == b.home_users, 374 .home_repos => |a_after| a_after == b.home_repos, 375 .user_repos => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_repos.name.slice()) and a_u.after == b.user_repos.after, 376 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 377 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 378 .repo_files => |a_f| std.mem.eql(u8, a_f.name.slice(), b.repo_files.name.slice()) and a_f.after == b.repo_files.after, 379 .repo_commits => |a_c| std.mem.eql(u8, a_c.name.slice(), b.repo_commits.name.slice()) and a_c.after == b.repo_commits.after, 380 .repo_refs => |a_r| std.mem.eql(u8, a_r.name.slice(), b.repo_refs.name.slice()) and a_r.kind == b.repo_refs.kind and a_r.after == b.repo_refs.after, 381 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 382 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 383 else => true, 384 }; 385 } 386 387 // true when following a link from `b` to `a` (both repo routes) should reload 388 // rather than stay in page 389 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 390 if (a.parent() != .repo or b.parent() != .repo) return false; 391 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 392 a.repo_refs.after == 0 and b.repo_refs.after == 0) 393 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 394 return !a.eql(b); 395 } 396 397 // true when `a` and `b` are the same user paginated to a different repos 398 // window. switching between a user's tabs is in-page (header-handled), so 399 // only a changed `after` on the repos list navigates. 400 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 401 return switch (a) { 402 .user_repos => |aa| switch (b) { 403 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.after != bb.after, 404 else => false, 405 }, 406 else => false, 407 }; 408 } 409 410 // true when `a` and `b` are the same home list tab paginated to a different 411 // window. switching between the users/repos tabs is in-page (the home page 412 // holds both lists), so only a changed `after` on the same tab navigates. 413 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 414 return switch (a) { 415 .home_users => |aa| switch (b) { 416 .home_users => |bb| aa != bb, 417 else => false, 418 }, 419 .home_repos => |aa| switch (b) { 420 .home_repos => |bb| aa != bb, 421 else => false, 422 }, 423 else => false, 424 }; 425 } 426 427 // serialize as { "kind": <tag>, "name"?: <name>, "after"?: <n> }. the default 428 // union(enum) codec doesn't round-trip here: Stringify emits a void 429 // variant as a bare tag string, but the parser expects an object — so the 430 // server->wasm Snapshot JSON would fail to parse. 431 pub fn jsonStringify(self: RoutablePage, jw: anytype) !void { 432 try jw.beginObject(); 433 try jw.objectField("kind"); 434 try jw.write(@tagName(self)); 435 switch (self) { 436 .user_repos => |u| { 437 try jw.objectField("name"); 438 try jw.write(u.name.slice()); 439 try jw.objectField("after"); 440 try jw.write(u.after); 441 }, 442 .user_settings, .user_auth => |name| { 443 try jw.objectField("name"); 444 try jw.write(name.slice()); 445 }, 446 .repo_settings, .repo_auth => |name| { 447 try jw.objectField("name"); 448 try jw.write(name.slice()); 449 }, 450 .repo_files => |f| { 451 try jw.objectField("name"); 452 try jw.write(f.name.slice()); 453 try jw.objectField("after"); 454 try jw.write(f.after); 455 }, 456 .repo_commits => |c| { 457 try jw.objectField("name"); 458 try jw.write(c.name.slice()); 459 try jw.objectField("after"); 460 try jw.write(c.after); 461 }, 462 .repo_refs => |r| { 463 try jw.objectField("name"); 464 try jw.write(r.name.slice()); 465 // "kind" already holds the union tag, so the paginated column 466 // travels under a distinct field. 467 try jw.objectField("ref_kind"); 468 try jw.write(@tagName(r.kind)); 469 try jw.objectField("after"); 470 try jw.write(r.after); 471 }, 472 .home_users, .home_repos => |after| { 473 try jw.objectField("after"); 474 try jw.write(after); 475 }, 476 else => {}, 477 } 478 try jw.endObject(); 479 } 480 481 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !RoutablePage { 482 const Helper = struct { kind: std.meta.Tag(RoutablePage), name: ?[]const u8 = null, after: usize = 0, ref_kind: ?[]const u8 = null }; 483 const helper = try std.json.innerParse(Helper, allocator, source, options); 484 const parseName = struct { 485 // errors must stay within std.json's ParseError set; ValueTooLong 486 // is its member for an over-long field. 487 fn f(comptime max_len: usize, maybe: ?[]const u8) !Array(max_len) { 488 return Array(max_len).from(maybe orelse return error.MissingField) orelse error.ValueTooLong; 489 } 490 }.f; 491 return switch (helper.kind) { 492 .home_users => .{ .home_users = helper.after }, 493 .home_repos => .{ .home_repos = helper.after }, 494 .home_settings => .home_settings, 495 .home_auth => .home_auth, 496 .user_repos => .{ .user_repos = .{ .name = try parseName(evt.User.name_max_len, helper.name), .after = helper.after } }, 497 .user_settings => .{ .user_settings = try parseName(evt.User.name_max_len, helper.name) }, 498 .user_auth => .{ .user_auth = try parseName(evt.User.name_max_len, helper.name) }, 499 .repo_files => .{ .repo_files = .{ .name = try parseName(repo_route_max_len, helper.name), .after = helper.after } }, 500 .repo_commits => .{ .repo_commits = .{ .name = try parseName(repo_route_max_len, helper.name), .after = helper.after } }, 501 .repo_refs => .{ .repo_refs = .{ 502 .name = try parseName(repo_route_max_len, helper.name), 503 .kind = if (helper.ref_kind) |k| (if (std.mem.eql(u8, k, "tag")) .tag else .branch) else .branch, 504 .after = helper.after, 505 } }, 506 .repo_settings => .{ .repo_settings = try parseName(repo_route_max_len, helper.name) }, 507 .repo_auth => .{ .repo_auth = try parseName(repo_route_max_len, helper.name) }, 508 }; 509 } 510 }; 511 512 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 513 fn isUnreserved(c: u8) bool { 514 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 515 } 516 517 // percent-encode a ref name for use as a single url path segment. 518 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 519 var out: std.Io.Writer.Allocating = .init(aa); 520 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 521 return out.written(); 522 } 523 524 // a resolved ref/oid for a repo opened with `repo_opts` 525 pub fn ResolvedRefOrOid(comptime repo_opts: rp.RepoOpts(.xit)) type { 526 return struct { 527 pub const hex_len = hash.hexLen(repo_opts.hash); 528 529 // the concrete ref/oid (a null request resolves to the default branch) 530 ref_or_oid: RoutablePage.RefOrOid, 531 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 532 // the route layer — which splits on '/' — stores them encoded). duped 533 // into `aa`. 534 value: []const u8, 535 // the commit oid it points at 536 oid: [hex_len]u8, 537 538 const Self = @This(); 539 540 // resolve a requested ref/oid (null = the repo's default branch) to a 541 // concrete ref/oid plus the commit oid it points at. `requested_value` is 542 // the url-encoded form (as it appears in the route). null when it doesn't 543 // resolve (an unknown branch/tag, or a malformed/unknown oid). 544 pub fn init( 545 repo: *rp.Repo(.xit, repo_opts), 546 io: std.Io, 547 aa: std.mem.Allocator, 548 requested_ref_or_oid: ?RoutablePage.RefOrOid, 549 requested_value: []const u8, 550 ) !?Self { 551 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 552 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 553 var value: []const u8 = if (requested_ref_or_oid == null) 554 requested_value 555 else 556 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 557 // no ref named: fall back to HEAD's branch (or its oid when detached). 558 if (requested_ref_or_oid == null) { 559 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 560 if (repo.head(io, &head_buf)) |head| switch (head) { 561 .ref => |r| { 562 ref_or_oid = .branch; 563 value = r.name; 564 }, 565 .oid => |o| { 566 ref_or_oid = .object; 567 value = o; 568 }, 569 } else |_| {} 570 } 571 572 var oid: [hex_len]u8 = undefined; 573 switch (ref_or_oid) { 574 .object => { 575 if (value.len != hex_len) return null; 576 @memcpy(&oid, value); 577 }, 578 .branch, .tag => { 579 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 580 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 581 }, 582 } 583 // store url-encoded so the route layer can hold the value verbatim. 584 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 585 } 586 }; 587 } 588 589 // per-connection mutable state. each SSH session / web session / local TUI 590 // run gets its own. 591 pub const Session = struct { 592 data: Data = .{}, 593 // session-lifetime allocations: login/user_id, persisted prefs, queued 594 // actions. lives as long as the connection. 595 arena: *std.heap.ArenaAllocator, 596 // current page's allocations: page data and the page-scoped strings widgets 597 // build (form actions, links). owned by Nav, swapped on each navigation, so 598 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 599 // where a render is one-shot, this points at the same arena as `arena`. 600 page_arena: *std.heap.ArenaAllocator, 601 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 602 // filesystem io and the path to <server>/repos, for opening on-disk repos 603 // during page construction. both null on wasm, which has no filesystem and 604 // rebuilds pages from the serialized snapshot rather than from disk. 605 io: ?std.Io = null, 606 repos_dir: ?[]const u8 = null, 607 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 608 // focus id -> the live TextInput, refreshed each frame by the views that own 609 // inputs. web/wasm form handling looks widgets up here by focus id. 610 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 611 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 612 // a requested forward navigation. set this (via navigate) to move to a new 613 // page; Nav.sync builds it and then copies it into current_page, clearing 614 // this back to null. setting current_page directly only updates the url and 615 // does not navigate. 616 next_page: ?RoutablePage = null, 617 is_terminal: bool = false, // true on remote SSH and local TUI 618 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 619 // url. null on the web itself (no footer there). 620 web_port: ?u16 = null, 621 quit_requested: bool = false, 622 623 const Self = @This(); 624 625 // serializable data sent down to web client 626 pub const Data = struct { 627 user_id: ?[]const u8 = null, 628 // a transient outcome to surface from the last /login POST attempt 629 login_failure: ?Home.Auth.Login.Failure = null, 630 current_page: RoutablePage = .default, 631 // whether to render the ANSI art backdrop 632 enable_ansi: bool = true, 633 }; 634 635 // a user-initiated state change. widgets enqueue these on the session during 636 // input instead of mutating state or touching the DB themselves; the host 637 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 638 // side effects out of the widget tree and gives every render path one place to 639 // turn a UI action into a state change + event. 640 pub const Action = union(enum) { 641 toggle_ansi, 642 }; 643 644 pub fn init( 645 arena: *std.heap.ArenaAllocator, 646 repo: *rp.Repo(.xit, evt.admin_repo_opts), 647 data: Data, 648 ) !Self { 649 var session = Self{ 650 .data = data, 651 .arena = arena, 652 // until a host swaps in a page-scoped arena (Nav does this), page 653 // allocations land in the session arena. on the web path that's the 654 // intended behavior, since the whole arena is per-request. 655 .page_arena = arena, 656 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 657 }; 658 try session.loadUserPrefs(); 659 return session; 660 } 661 662 // load the logged-in user's persisted preferences from the db 663 pub fn loadUserPrefs(self: *Self) !void { 664 const user_id = self.data.user_id orelse return; 665 const moment = self.haxy_moment orelse return; 666 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 667 self.data.enable_ansi = user.enable_ansi; 668 } 669 } 670 671 // queue an action for the host to drain this frame. 672 pub fn push(self: *Self, action: Action) !void { 673 try self.pending.append(self.arena.allocator(), action); 674 } 675 676 // apply a single action's in-memory effect only (no persistence). 677 fn apply(self: *Self, action: Action) void { 678 switch (action) { 679 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 680 } 681 } 682 683 // drain the session's queued actions by applying them to the session. 684 // used on the wasm path, which has no repo to persist to. 685 pub fn applyPending(self: *Self) void { 686 for (self.pending.items) |action| self.apply(action); 687 self.pending.clearRetainingCapacity(); 688 } 689 690 // drain the session's queued actions by applying them to the session and 691 // writing them to the db 692 pub fn applyAndWritePending( 693 self: *Self, 694 io: std.Io, 695 allocator: std.mem.Allocator, 696 repo: *rp.Repo(.xit, evt.admin_repo_opts), 697 ) !void { 698 defer self.pending.clearRetainingCapacity(); 699 for (self.pending.items) |action| { 700 self.apply(action); 701 switch (action) { 702 .toggle_ansi => if (self.data.user_id) |user_id| { 703 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 704 }, 705 } 706 } 707 } 708 709 // reload the moment from the admin repo 710 pub fn reloadMoment(self: *Self, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 711 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo); 712 } 713 714 // request a forward navigation to `route`; the host consumes next_page 715 // (Nav.sync on the terminal, the wasm tick on the web). 716 pub fn navigate(self: *Session, route: RoutablePage) !void { 717 self.next_page = route; 718 } 719 }; 720 721 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 722 var nav = try Nav.init(allocator, session); 723 defer nav.deinit(allocator); 724 725 var terminal = try term.Terminal.init(io, allocator); 726 defer terminal.deinit(io); 727 728 // set term as active so it will be properly cooked 729 // when a panic/segfault happens 730 term.setActive(&terminal); 731 defer term.setActive(null); 732 733 var last_size = layout.Size{ .width = 0, .height = 0 }; 734 var last_grid = try Grid.init(allocator, last_size); 735 defer last_grid.deinit(); 736 737 while (!terminal.shouldQuit()) { 738 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 739 740 // process any inputs. 741 // 742 // if the grid didn't change, then first do a blocking 743 // read, so the thread will sleep until further input. 744 // after that, all remaining reads are non-blocking so 745 // we can process the rest of the queued inputs. 746 // 747 // if the grid *did* change, then only do non-blocking 748 // reads. we do not want to sleep the thread because 749 // there may be an animation that requires more looping. 750 var blocking = !grid_changed; 751 while (try terminal.readKey(io, blocking)) |key| { 752 blocking = false; 753 try inputKey(allocator, &nav.root, key, session); 754 } 755 756 // local run has no repo to persist to, so just apply in-memory 757 session.applyPending(); 758 759 // pick up data written by other handles so the next navigation 760 // builds its page from a current moment 761 try session.reloadMoment(repo); 762 763 // reconcile navigation: forward to a new page, or back on escape. 764 try nav.sync(allocator, session); 765 766 // the quit button (on the quit tab) asks the host to tear down. 767 if (session.quit_requested) terminal.requestQuit(); 768 769 try nav.root.build(allocator, .{ 770 .min_size = .{ .width = null, .height = null }, 771 .max_size = .{ .width = last_size.width, .height = last_size.height }, 772 }, nav.root.getFocus()); 773 } 774 } 775 776 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: inp.Key, session: *Session) !void { 777 switch (key) { 778 // request a navigation pop; the host's Nav.sync goes back a page, or 779 // quits when there's no history left. 780 .escape => session.nav_back = true, 781 .enter => { 782 const root_focus = root.getFocus(); 783 if (root_focus.grandchild_id) |gid| { 784 // follow a cross-page link 785 if (crossPageLink(root_focus, gid, session.data.current_page)) |route| { 786 return session.navigate(route); 787 } 788 } 789 try root.input(allocator, key, root_focus); 790 }, 791 .mouse => |mouse| { 792 if (mouse.action == .press and mouse.action.press == .left) { 793 const root_focus = root.getFocus(); 794 var clicked: ?usize = null; 795 var iter = root_focus.children.iterator(); 796 while (iter.next()) |entry| { 797 const child = entry.value_ptr.*; 798 if (!child.focus.focusable) continue; 799 const r = child.rect; 800 if (mouse.x >= r.x and mouse.y >= r.y and 801 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 802 { 803 clicked = entry.key_ptr.*; 804 break; 805 } 806 } 807 if (clicked) |focus_id| { 808 // follow a cross-page link 809 if (crossPageLink(root_focus, focus_id, session.data.current_page)) |route| { 810 return session.navigate(route); 811 } 812 root_focus.setFocus(focus_id); 813 } 814 // forward the press into the widget tree so buttons (and any 815 // future click-aware widgets) can react. widgets that don't 816 // care about presses ignore it. 817 try root.input(allocator, key, root.getFocus()); 818 } else { 819 try root.input(allocator, key, root.getFocus()); 820 } 821 }, 822 else => try root.input(allocator, key, root.getFocus()), 823 } 824 } 825 826 // if the focus target at focus_id is an `a:` link that should navigate (a 827 // different parent page, or a different files directory within the repo page), 828 // return its route; otherwise null. lets a host turn a click / enter on such a 829 // link into a navigation rather than a focus change. 830 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, current: RoutablePage) ?RoutablePage { 831 const child = root_focus.children.get(focus_id) orelse return null; 832 const custom = switch (child.focus.kind) { 833 .custom => |c| c, 834 else => return null, 835 }; 836 const a_prefix = "a:"; 837 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 838 const url = custom[a_prefix.len..]; 839 const q = std.mem.indexOfScalar(u8, url, '?'); 840 const route = RoutablePage.fromUrl(if (q) |i| url[0..i] else url, if (q) |i| url[i + 1 ..] else null) orelse return null; 841 // a link to a different parent page always navigates; within a page, a 842 // files-directory / commits-page / list-window change navigates while tab 843 // links stay in-page (header-handled). 844 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 845 return null; 846 } 847 848 // native-TUI navigation 849 pub const Nav = struct { 850 root: Widget, 851 route: RoutablePage, 852 // backs the current page (its Page data and the page-scoped strings its 853 // widgets build). owned here, swapped on each navigation. session.page_arena 854 // tracks whichever of these is current so widgets allocate into it. 855 arena: *std.heap.ArenaAllocator, 856 history: std.ArrayList(Entry), 857 858 // each retained page keeps its own arena, freed when the page leaves the 859 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 860 // long-lived session from accumulating every page it ever visited. 861 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 862 863 // cap on retained back-history so the chain can't grow memory without bound 864 const max_history: usize = 16; 865 866 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 867 const arena = try allocator.create(std.heap.ArenaAllocator); 868 arena.* = std.heap.ArenaAllocator.init(allocator); 869 errdefer { 870 arena.deinit(); 871 allocator.destroy(arena); 872 } 873 874 session.page_arena = arena; 875 const route = session.data.current_page; 876 877 const page = try arena.allocator().create(Page); 878 page.* = try Page.init(arena, session, route); 879 return .{ 880 .root = try initRoot(allocator, page, session), 881 .route = route, 882 .arena = arena, 883 .history = .empty, 884 }; 885 } 886 887 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 888 self.root.deinit(allocator); 889 freeArena(allocator, self.arena); 890 for (self.history.items) |*entry| { 891 entry.root.deinit(allocator); 892 freeArena(allocator, entry.arena); 893 } 894 self.history.deinit(allocator); 895 } 896 897 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 898 arena.deinit(); 899 allocator.destroy(arena); 900 } 901 902 // reconcile the displayed root with the session's navigation state. a 903 // forward nav (current_page moved to a different parent page) pushes the 904 // current root and builds the new page in a fresh arena; a back request 905 // frees the current page and restores the previous one. when escape is 906 // pressed with no history left we switch to the quit tab instead of quitting. 907 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 908 if (session.nav_back) { 909 session.nav_back = false; 910 if (self.history.pop()) |entry| { 911 self.root.deinit(allocator); 912 freeArena(allocator, self.arena); 913 self.root = entry.root; 914 self.route = entry.route; 915 self.arena = entry.arena; 916 session.page_arena = entry.arena; 917 session.data.current_page = entry.route; 918 return; 919 } 920 // nothing to go back to; switch to the quit confirmation 921 const root_focus = self.root.getFocus(); 922 var iter = root_focus.children.iterator(); 923 while (iter.next()) |entry| { 924 switch (entry.value_ptr.focus.kind) { 925 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 926 root_focus.setFocus(entry.key_ptr.*); 927 // a Stack only builds its selected child, so the quit 928 // button isn't in the focus tree until a build runs with 929 // the quit tab selected. build once, then send a 930 // synthetic arrow_down to drop focus from the tab onto 931 // the button so it's ready to confirm. 932 try self.root.build(allocator, .{ 933 .min_size = .{ .width = null, .height = 40 }, 934 .max_size = .{ .width = 80, .height = null }, 935 }, root_focus); 936 try self.root.input(allocator, .arrow_down, root_focus); 937 break; 938 }, 939 else => {}, 940 } 941 } 942 return; 943 } 944 945 // forward navigation: navigate() set next_page to the page to move to (a 946 // cross-page link or tab change crossing pages) 947 if (session.next_page) |route| { 948 session.next_page = null; 949 if (session.haxy_moment == null) return; 950 // the page we navigated to becomes the current page 951 session.data.current_page = route; 952 953 const arena = try allocator.create(std.heap.ArenaAllocator); 954 arena.* = std.heap.ArenaAllocator.init(allocator); 955 errdefer freeArena(allocator, arena); 956 957 session.page_arena = arena; 958 959 const page = try arena.allocator().create(Page); 960 page.* = try Page.init(arena, session, route); 961 const new_root = try initRoot(allocator, page, session); 962 963 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 964 // drop the oldest entry (freeing its widget tree and arena) once over cap 965 if (self.history.items.len > max_history) { 966 var oldest = self.history.orderedRemove(0); 967 oldest.root.deinit(allocator); 968 freeArena(allocator, oldest.arena); 969 } 970 self.root = new_root; 971 self.route = route; 972 self.arena = arena; 973 } 974 } 975 }; 976 977 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 978 const page_widget: Widget = switch (page.*) { 979 .home => |*p| .{ .home = try .init(allocator, p, session) }, 980 .user => |*p| .{ .user = try .init(allocator, p, session) }, 981 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 982 }; 983 984 const demon_art = @embedFile("embed/demon.ans"); 985 986 // on the TUI/SSH, the page sits above a one-row footer showing the url 987 var root = if (session.is_terminal) blk: { 988 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 989 errdefer box.deinit(allocator); 990 const bg_id = bg_blk: { 991 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 992 errdefer background.deinit(allocator); 993 const id = background.getFocus().id; 994 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 995 break :bg_blk id; 996 }; 997 { 998 var footer = try Footer.init(allocator, session); 999 errdefer footer.deinit(allocator); 1000 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 1001 } 1002 box.getFocus().child_id = bg_id; 1003 break :blk Widget{ .box = box }; 1004 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 1005 errdefer root.deinit(allocator); 1006 1007 // input-owning views build their TextInputs in init — so reset the 1008 // focus-id -> *TextInput map here 1009 session.text_inputs.clearRetainingCapacity(); 1010 1011 try root.build(allocator, .{ 1012 .min_size = .{ .width = null, .height = 40 }, 1013 .max_size = .{ .width = 100, .height = null }, 1014 }, root.getFocus()); 1015 1016 return root; 1017 } 1018 1019 pub const Widget = union(enum) { 1020 text: wgt.Text(Widget), 1021 box: wgt.Box(Widget), 1022 text_box: wgt.TextBox(Widget), 1023 text_input: wgt.TextInput(Widget), 1024 scroll: wgt.Scroll(Widget), 1025 stack: wgt.Stack(Widget), 1026 flow_box: FlowBox, 1027 flow_box_scroll: FlowBox.Scroll, 1028 spacer: Spacer, 1029 center: Center, 1030 ansi_art: AnsiArt, 1031 background: AnsiBackground, 1032 home: Home.View, 1033 user: User.View, 1034 repo: Repo.View, 1035 quit: Quit.View, 1036 title: Title.View, 1037 sub_title: SubTitle.View, 1038 home_header: Home.Header.View, 1039 user_header: User.Header.View, 1040 repo_header: Repo.Header.View, 1041 repo_sub_header: Repo.SubHeader.View, 1042 repo_files: Repo.Files.View, 1043 repo_commits: Repo.Commits.View, 1044 repo_refs: Repo.Refs.View, 1045 home_users: Home.Users.View, 1046 home_repos: Home.Repos.View, 1047 auth_tab: Home.Header.AuthTab.View, 1048 home_settings: Home.Settings.View, 1049 home_auth: Home.Auth.View, 1050 footer: Footer, 1051 1052 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 1053 switch (self.*) { 1054 inline else => |*case| case.deinit(allocator), 1055 } 1056 } 1057 1058 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 1059 switch (self.*) { 1060 inline else => |*case| try case.build(allocator, constraint, root_focus), 1061 } 1062 } 1063 1064 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 1065 switch (self.*) { 1066 inline else => |*case| try case.input(allocator, key, root_focus), 1067 } 1068 } 1069 1070 pub fn clearGrid(self: *Widget) void { 1071 switch (self.*) { 1072 inline else => |*case| case.clearGrid(), 1073 } 1074 } 1075 1076 pub fn getGrid(self: Widget) ?Grid { 1077 switch (self) { 1078 inline else => |*case| return case.getGrid(), 1079 } 1080 } 1081 1082 pub fn getFocus(self: *Widget) *Focus { 1083 switch (self.*) { 1084 inline else => |*case| return case.getFocus(), 1085 } 1086 } 1087 }; 1088 1089 pub const FlowBox = struct { 1090 focus: *Focus, 1091 grid: ?Grid, 1092 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1093 // backs the per-item strings the text boxes borrow: each box's `content` 1094 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 1095 // wholesale on each setItems so there's no per-string ownership to track. 1096 arena: std.heap.ArenaAllocator, 1097 // column count from the last build — FlowBox.Scroll.input uses it so arrow 1098 // up/down can step by a row's worth of items. 1099 last_cols: usize, 1100 options: Options, 1101 1102 const border_rows: usize = 2; 1103 1104 pub const Options = struct { 1105 cell_width: usize = 40, 1106 cell_height: usize = 3, 1107 }; 1108 1109 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 1110 return .{ 1111 .focus = try Focus.create(allocator, .container), 1112 .grid = null, 1113 .text_boxes = .empty, 1114 .arena = std.heap.ArenaAllocator.init(allocator), 1115 .last_cols = 1, 1116 .options = options, 1117 }; 1118 } 1119 1120 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 1121 self.focus.destroy(allocator); 1122 if (self.grid) |*grid| { 1123 grid.deinit(); 1124 self.grid = null; 1125 } 1126 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1127 self.text_boxes.deinit(allocator); 1128 self.arena.deinit(); 1129 } 1130 1131 // one flow item: its display text plus an optional link. a non-empty `link` 1132 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 1133 // the web renderer turns into an anchor. 1134 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1135 1136 // both the item text and the link are copied into the arena, so the caller's 1137 // slices needn't outlive this call. 1138 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 1139 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1140 self.text_boxes.clearAndFree(allocator); 1141 1142 // the old text boxes (and their borrowed content/links) are gone now, so 1143 // the arena that backed those strings can be reclaimed. 1144 _ = self.arena.reset(.retain_capacity); 1145 const aa = self.arena.allocator(); 1146 1147 self.focus.clear(); 1148 self.focus.child_id = null; 1149 1150 for (items) |item| { 1151 const line = try aa.dupe(u8, item.text); 1152 1153 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 1154 errdefer text_box.deinit(allocator); 1155 text_box.getFocus().focusable = true; 1156 1157 if (item.link.len > 0) { 1158 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1159 } 1160 1161 try self.text_boxes.append(allocator, text_box); 1162 } 1163 1164 if (self.text_boxes.items.len > 0) { 1165 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1166 } 1167 } 1168 1169 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1170 self.clearGrid(); 1171 self.focus.clear(); 1172 1173 const cell_width = self.options.cell_width; 1174 const max_width = constraint.max_size.width orelse cell_width; 1175 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 1176 self.last_cols = cols; 1177 1178 const count = self.text_boxes.items.len; 1179 if (count == 0) return; 1180 const slot_height = self.options.cell_height + border_rows; 1181 if (slot_height == 0) return; 1182 1183 // build at the slot size so every text box fits a single grid cell 1184 for (self.text_boxes.items) |*tb| { 1185 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1186 try tb.build(allocator, .{ 1187 .min_size = .{ .width = cell_width, .height = null }, 1188 .max_size = .{ .width = cell_width, .height = slot_height }, 1189 }, root_focus); 1190 } 1191 1192 const rows = (count + cols - 1) / cols; 1193 const content_height = rows * slot_height; 1194 const total_width = cols * cell_width; 1195 if (total_width == 0 or content_height == 0) return; 1196 1197 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 1198 errdefer grid.deinit(); 1199 1200 for (self.text_boxes.items, 0..) |*tb, i| { 1201 const tb_grid = tb.getGrid() orelse continue; 1202 const col = i % cols; 1203 const row = i / cols; 1204 const cell_x = col * cell_width; 1205 const cell_y = row * slot_height; 1206 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 1207 try grid.drawGrid(tb_grid, cell_x, cell_y); 1208 } 1209 1210 self.grid = grid; 1211 } 1212 1213 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1214 _ = self; 1215 _ = allocator; 1216 _ = key; 1217 _ = root_focus; 1218 } 1219 1220 pub fn clearGrid(self: *FlowBox) void { 1221 if (self.grid) |*grid| { 1222 grid.deinit(); 1223 self.grid = null; 1224 } 1225 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1226 } 1227 1228 pub fn getGrid(self: FlowBox) ?Grid { 1229 return self.grid; 1230 } 1231 1232 pub fn getFocus(self: *FlowBox) *Focus { 1233 return self.focus; 1234 } 1235 1236 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 1237 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 1238 const slot_height = self.options.cell_height + border_rows; 1239 const col = index % self.last_cols; 1240 const row = index / self.last_cols; 1241 return .{ 1242 .x = @intCast(col * self.options.cell_width), 1243 .y = @intCast(row * slot_height), 1244 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1245 }; 1246 } 1247 1248 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1249 for (self.text_boxes.items, 0..) |tb, i| { 1250 if (tb.box.focus.id == focus_id) return i; 1251 } 1252 return null; 1253 } 1254 1255 pub const Scroll = struct { 1256 scroll: wgt.Scroll(Widget), 1257 1258 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 1259 var layout_inner = try FlowBox.init(allocator, options); 1260 errdefer layout_inner.deinit(allocator); 1261 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 1262 errdefer scroll.deinit(allocator); 1263 return .{ .scroll = scroll }; 1264 } 1265 1266 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1267 self.scroll.deinit(allocator); 1268 } 1269 1270 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 1271 self.scroll.x = 0; 1272 self.scroll.y = 0; 1273 try self.inner().setItems(allocator, items); 1274 } 1275 1276 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1277 try self.scroll.build(allocator, constraint, root_focus); 1278 } 1279 1280 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1281 _ = allocator; 1282 const in = self.inner(); 1283 const child_id = in.focus.child_id orelse return; 1284 const current_index = in.indexOfFocusId(child_id) orelse return; 1285 const count = in.text_boxes.items.len; 1286 if (count == 0) return; 1287 const cols = in.last_cols; 1288 const slot_height = in.options.cell_height + FlowBox.border_rows; 1289 1290 var index = current_index; 1291 switch (key) { 1292 .arrow_up => index -|= cols, 1293 .arrow_down => if (index + cols < count) { 1294 index += cols; 1295 }, 1296 .arrow_left => index -|= 1, 1297 .arrow_right => if (index + 1 < count) { 1298 index += 1; 1299 }, 1300 .home => index = 0, 1301 .end => index = count - 1, 1302 .page_up => { 1303 if (self.scroll.grid) |grid| if (slot_height > 0) { 1304 const rows_per_page = grid.size.height / slot_height; 1305 index -|= rows_per_page * cols; 1306 }; 1307 }, 1308 .page_down => { 1309 if (self.scroll.grid) |grid| if (slot_height > 0) { 1310 const rows_per_page = grid.size.height / slot_height; 1311 index = @min(index + rows_per_page * cols, count - 1); 1312 }; 1313 }, 1314 // scroll wheel moves the focused cell by a full row so the 1315 // viewport (via scrollToRect) follows in row-sized steps, 1316 // matching how a scroll wheel feels in a grid view. 1317 .mouse => |mouse| switch (mouse.action) { 1318 .scroll => |dir| switch (dir) { 1319 .up => index -|= cols, 1320 .down => if (index + cols < count) { 1321 index += cols; 1322 }, 1323 }, 1324 else => {}, 1325 }, 1326 else => {}, 1327 } 1328 1329 if (index != current_index) { 1330 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1331 if (in.cellRect(index)) |rect| { 1332 self.scroll.scrollToRect(rect); 1333 } 1334 } 1335 } 1336 1337 pub fn clearGrid(self: *Scroll) void { 1338 self.scroll.clearGrid(); 1339 } 1340 1341 pub fn getGrid(self: Scroll) ?Grid { 1342 return self.scroll.getGrid(); 1343 } 1344 1345 pub fn getFocus(self: *Scroll) *Focus { 1346 return self.scroll.getFocus(); 1347 } 1348 1349 pub fn getSelectedIndex(self: Scroll) ?usize { 1350 const in = self.scroll.child.flow_box; 1351 const child_id = in.focus.child_id orelse return null; 1352 return in.indexOfFocusId(child_id); 1353 } 1354 1355 fn inner(self: *Scroll) *FlowBox { 1356 return &self.scroll.child.flow_box; 1357 } 1358 }; 1359 }; 1360 1361 // an invisible widget that fills the horizontal space granted by its parent. 1362 // used inside Box(horiz) with a min_size so the box reserves space for the 1363 // children that follow, pushing them to the right. 1364 pub const Spacer = struct { 1365 focus: *Focus, 1366 grid: ?Grid, 1367 1368 pub fn init(allocator: std.mem.Allocator) !Spacer { 1369 return .{ 1370 .focus = try Focus.create(allocator, .container), 1371 .grid = null, 1372 }; 1373 } 1374 1375 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1376 self.focus.destroy(allocator); 1377 if (self.grid) |*grid| { 1378 grid.deinit(); 1379 self.grid = null; 1380 } 1381 } 1382 1383 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1384 _ = root_focus; 1385 self.clearGrid(); 1386 const width = constraint.max_size.width orelse return; 1387 if (width == 0) return; 1388 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1389 } 1390 1391 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1392 _ = self; 1393 _ = allocator; 1394 _ = key; 1395 _ = root_focus; 1396 } 1397 1398 pub fn clearGrid(self: *Spacer) void { 1399 if (self.grid) |*grid| { 1400 grid.deinit(); 1401 self.grid = null; 1402 } 1403 } 1404 1405 pub fn getGrid(self: Spacer) ?Grid { 1406 return self.grid; 1407 } 1408 1409 pub fn getFocus(self: *Spacer) *Focus { 1410 return self.focus; 1411 } 1412 }; 1413 1414 // a one-row, non-focusable status bar showing the current page's url 1415 pub const Footer = struct { 1416 focus: *Focus, 1417 grid: ?Grid, 1418 session: *Session, 1419 arena: std.heap.ArenaAllocator, 1420 1421 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 1422 return .{ 1423 .focus = try Focus.create(allocator, .container), 1424 .grid = null, 1425 .session = session, 1426 .arena = std.heap.ArenaAllocator.init(allocator), 1427 }; 1428 } 1429 1430 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 1431 self.focus.destroy(allocator); 1432 if (self.grid) |*grid| grid.deinit(); 1433 self.arena.deinit(); 1434 } 1435 1436 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1437 _ = root_focus; 1438 self.clearGrid(); 1439 const width = constraint.max_size.width orelse return; 1440 if (width == 0) return; 1441 1442 _ = self.arena.reset(.retain_capacity); 1443 const aa = self.arena.allocator(); 1444 const path = self.session.data.current_page.urlAlloc(&self.arena) catch return; 1445 const text = if (self.session.web_port) |port| 1446 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 1447 else 1448 path; 1449 1450 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1451 errdefer grid.deinit(); 1452 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 1453 var i: usize = 0; 1454 while (utf8.nextCodepointSlice()) |ch| { 1455 if (i == width) break; 1456 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 1457 i += 1; 1458 } 1459 self.grid = grid; 1460 } 1461 1462 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1463 _ = self; 1464 _ = allocator; 1465 _ = key; 1466 _ = root_focus; 1467 } 1468 1469 pub fn clearGrid(self: *Footer) void { 1470 if (self.grid) |*grid| { 1471 grid.deinit(); 1472 self.grid = null; 1473 } 1474 } 1475 1476 pub fn getGrid(self: Footer) ?Grid { 1477 return self.grid; 1478 } 1479 1480 pub fn getFocus(self: *Footer) *Focus { 1481 return self.focus; 1482 } 1483 }; 1484 1485 // a single-child wrapper that builds the child at its natural size and 1486 // positions its grid in the middle of the area granted by the parent 1487 pub const Center = struct { 1488 focus: *Focus, 1489 grid: ?Grid, 1490 child: *Widget, 1491 direction: Direction, 1492 1493 pub const Direction = enum { both, horiz, vert }; 1494 1495 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, direction: Direction) !Center { 1496 const child = try allocator.create(Widget); 1497 errdefer allocator.destroy(child); 1498 child.* = child_widget; 1499 return .{ 1500 .focus = try Focus.create(allocator, .container), 1501 .grid = null, 1502 .child = child, 1503 .direction = direction, 1504 }; 1505 } 1506 1507 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 1508 self.focus.destroy(allocator); 1509 if (self.grid) |*grid| { 1510 grid.deinit(); 1511 self.grid = null; 1512 } 1513 self.child.deinit(allocator); 1514 allocator.destroy(self.child); 1515 } 1516 1517 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1518 self.clearGrid(); 1519 self.getFocus().clear(); 1520 1521 // build the child without forcing it to fill min_size; it sizes 1522 // itself to its content within the available max. 1523 try self.child.build(allocator, .{ 1524 .min_size = .{ .width = null, .height = null }, 1525 .max_size = constraint.max_size, 1526 }, root_focus); 1527 1528 const child_grid = self.child.getGrid() orelse return; 1529 1530 // prefer max when given; otherwise grow to max(min, child) so that 1531 // when only a min is set (e.g. the wasm path passes viewport rows 1532 // as min_height with no max), we can still vertically center while 1533 // letting taller content extend past the min. 1534 const width = if (constraint.max_size.width) |w| w else if (constraint.min_size.width) |min_w| @max(min_w, child_grid.size.width) else child_grid.size.width; 1535 const height = if (constraint.max_size.height) |h| h else if (constraint.min_size.height) |min_h| @max(min_h, child_grid.size.height) else child_grid.size.height; 1536 if (width == 0 or height == 0) return; 1537 1538 const offset_x: usize = if (self.direction == .horiz or self.direction == .both) 1539 (width -| child_grid.size.width) / 2 1540 else 1541 0; 1542 const offset_y: usize = if (self.direction == .vert or self.direction == .both) 1543 (height -| child_grid.size.height) / 2 1544 else 1545 0; 1546 1547 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 1548 errdefer grid.deinit(); 1549 try grid.drawGrid(child_grid, offset_x, offset_y); 1550 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 1551 self.getFocus().child_id = self.child.getFocus().id; 1552 1553 self.grid = grid; 1554 } 1555 1556 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1557 try self.child.input(allocator, key, root_focus); 1558 } 1559 1560 pub fn clearGrid(self: *Center) void { 1561 if (self.grid) |*grid| { 1562 grid.deinit(); 1563 self.grid = null; 1564 } 1565 self.child.clearGrid(); 1566 } 1567 1568 pub fn getGrid(self: Center) ?Grid { 1569 return self.grid; 1570 } 1571 1572 pub fn getFocus(self: *Center) *Focus { 1573 return self.focus; 1574 } 1575 }; 1576 1577 // renders truecolor ANSI art 1578 pub const AnsiArt = struct { 1579 focus: *Focus, 1580 grid: ?Grid, 1581 content: []const u8, 1582 1583 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 1584 return .{ 1585 .focus = try Focus.create(allocator, .container), 1586 .grid = null, 1587 .content = content, 1588 }; 1589 } 1590 1591 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1592 self.focus.destroy(allocator); 1593 if (self.grid) |*grid| { 1594 grid.deinit(); 1595 self.grid = null; 1596 } 1597 } 1598 1599 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1600 _ = root_focus; 1601 self.clearGrid(); 1602 1603 // parse into rows of cells, then copy into a rectangular grid 1604 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1605 defer { 1606 for (rows.items) |*row| row.deinit(allocator); 1607 rows.deinit(allocator); 1608 } 1609 var row: std.ArrayList(Grid.Cell) = .empty; 1610 errdefer row.deinit(allocator); 1611 1612 var style: Grid.Style = .{}; 1613 var width: usize = 0; 1614 const content = self.content; 1615 var i: usize = 0; 1616 while (i < content.len) { 1617 const byte = content[i]; 1618 if (byte == '\n') { 1619 width = @max(width, row.items.len); 1620 try rows.append(allocator, row); 1621 row = .empty; 1622 i += 1; 1623 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1624 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1625 var j = i + 2; 1626 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1627 if (j >= content.len) { 1628 i = content.len; // malformed trailing escape; stop 1629 } else { 1630 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1631 i = j + 1; 1632 } 1633 } else { 1634 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1635 const end = @min(content.len, i + len); 1636 const rune = content[i..end]; 1637 const transparent = end - i == 1 and rune[0] == ' ' and 1638 style.fg == null and style.bg == null and !style.inverted; 1639 try row.append(allocator, .{ 1640 .rune = if (transparent) null else rune, 1641 .style = style, 1642 }); 1643 i = end; 1644 } 1645 } 1646 // a trailing row with content but no closing newline 1647 if (row.items.len > 0) { 1648 width = @max(width, row.items.len); 1649 try rows.append(allocator, row); 1650 } else { 1651 row.deinit(allocator); 1652 } 1653 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1654 1655 const height = rows.items.len; 1656 if (width == 0 or height == 0) return; 1657 1658 const clamped_w = @min(width, constraint.max_size.width orelse width); 1659 const clamped_h = @min(height, constraint.max_size.height orelse height); 1660 1661 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1662 errdefer grid.deinit(); 1663 for (rows.items[0..clamped_h], 0..) |r, y| { 1664 const n = @min(r.items.len, clamped_w); 1665 for (r.items[0..n], 0..) |cell, x| { 1666 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1667 } 1668 } 1669 self.grid = grid; 1670 } 1671 1672 pub fn input(self: *AnsiArt, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1673 _ = self; 1674 _ = allocator; 1675 _ = key; 1676 _ = root_focus; 1677 } 1678 1679 pub fn clearGrid(self: *AnsiArt) void { 1680 if (self.grid) |*grid| { 1681 grid.deinit(); 1682 self.grid = null; 1683 } 1684 } 1685 1686 pub fn getGrid(self: AnsiArt) ?Grid { 1687 return self.grid; 1688 } 1689 1690 pub fn getFocus(self: *AnsiArt) *Focus { 1691 return self.focus; 1692 } 1693 1694 fn applySgr(style: *Grid.Style, params: []const u8) void { 1695 var nums: [16]u32 = undefined; 1696 var n: usize = 0; 1697 var it = std.mem.splitScalar(u8, params, ';'); 1698 while (it.next()) |tok| { 1699 if (n >= nums.len) break; 1700 // an empty parameter (e.g. bare "\x1b[m") means 0 1701 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1702 n += 1; 1703 } 1704 if (n == 0) { 1705 style.* = .{}; 1706 return; 1707 } 1708 var i: usize = 0; 1709 while (i < n) : (i += 1) { 1710 switch (nums[i]) { 1711 0 => style.* = .{}, 1712 7 => style.inverted = true, 1713 27 => style.inverted = false, 1714 39 => style.fg = null, 1715 49 => style.bg = null, 1716 38, 48 => { 1717 // truecolor form: 38;2;r;g;b — anything else is ignored 1718 if (i + 4 < n and nums[i + 1] == 2) { 1719 const c = Grid.Color{ 1720 .r = @truncate(nums[i + 2]), 1721 .g = @truncate(nums[i + 3]), 1722 .b = @truncate(nums[i + 4]), 1723 }; 1724 if (nums[i] == 38) style.fg = c else style.bg = c; 1725 i += 4; 1726 } 1727 }, 1728 else => {}, 1729 } 1730 } 1731 } 1732 }; 1733 1734 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1735 pub const AnsiBackground = struct { 1736 grid: ?Grid, 1737 child: *Widget, 1738 art: AnsiArt, 1739 session: *Session, 1740 1741 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1742 var cw = child_widget; 1743 const child = allocator.create(Widget) catch |e| { 1744 cw.deinit(allocator); 1745 return e; 1746 }; 1747 child.* = cw; 1748 errdefer { 1749 child.deinit(allocator); 1750 allocator.destroy(child); 1751 } 1752 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 1753 } 1754 1755 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1756 if (self.grid) |*grid| grid.deinit(); 1757 self.art.deinit(allocator); 1758 self.child.deinit(allocator); 1759 allocator.destroy(self.child); 1760 } 1761 1762 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1763 self.clearGrid(); 1764 1765 // make the wrapped page fill the whole available area 1766 try self.child.build(allocator, .{ 1767 .min_size = .{ 1768 .width = constraint.max_size.width orelse constraint.min_size.width, 1769 .height = constraint.max_size.height orelse constraint.min_size.height, 1770 }, 1771 .max_size = constraint.max_size, 1772 }, root_focus); 1773 1774 if (self.session.data.enable_ansi) { 1775 if (self.child.getGrid()) |fg| { 1776 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1777 } 1778 } 1779 } 1780 1781 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1782 try self.child.input(allocator, key, root_focus); 1783 } 1784 1785 pub fn clearGrid(self: *AnsiBackground) void { 1786 if (self.grid) |*grid| { 1787 grid.deinit(); 1788 self.grid = null; 1789 } 1790 self.child.clearGrid(); 1791 self.art.clearGrid(); 1792 } 1793 1794 pub fn getGrid(self: AnsiBackground) ?Grid { 1795 return self.grid orelse self.child.getGrid(); 1796 } 1797 1798 pub fn getFocus(self: *AnsiBackground) *Focus { 1799 return self.child.getFocus(); 1800 } 1801 1802 // which top corner the art hugs. 1803 const ArtAnchor = enum { top_left, top_right }; 1804 1805 // a foreground cell counts as blank if it's empty or a bare space without styling 1806 fn cellIsBlank(cell: Grid.Cell) bool { 1807 if (cell.rune) |rune| { 1808 return std.mem.eql(u8, rune, " ") and 1809 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1810 } 1811 return true; 1812 } 1813 1814 // the art is dimmed to this fraction of its brightness so foreground text 1815 // stays legible over it 1816 const art_brightness = 45; // percent 1817 1818 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1819 const c = color orelse return null; 1820 return .{ 1821 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 1822 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 1823 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 1824 }; 1825 } 1826 1827 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1828 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1829 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1830 // snap such channels clear of that range so the backdrop doesn't blink or 1831 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1832 // actually render truecolor. 1833 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1834 const c = color orelse return null; 1835 const snap = struct { 1836 fn f(v: u8) u8 { 1837 return if (v >= 1 and v <= 9) 10 else v; 1838 } 1839 }.f; 1840 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1841 } 1842 1843 // composites ANSI art behind a foreground grid 1844 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1845 art.clearGrid(); 1846 try art.build(allocator, .{ 1847 .min_size = .{ .width = null, .height = null }, 1848 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1849 }, root_focus); 1850 1851 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1852 errdefer out.deinit(); 1853 1854 if (art.getGrid()) |art_grid| { 1855 const anchor_x = switch (anchor) { 1856 .top_left => 0, 1857 .top_right => foreground.size.width -| art_grid.size.width, 1858 }; 1859 for (0..art_grid.size.height) |y| { 1860 for (0..art_grid.size.width) |x| { 1861 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1862 if (src.rune == null) continue; 1863 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1864 const dst = &out.cells.items[idx]; 1865 // composite the dimmed art behind every cell so it shows 1866 // through the whole UI: a blank cell becomes the art, while a 1867 // cell with a glyph keeps the glyph but takes the dimmed art as 1868 // its background (replacing whatever background it had, which 1869 // would otherwise obscure the art). 1870 if (cellIsBlank(dst.*)) { 1871 dst.* = src; 1872 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 1873 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 1874 } else { 1875 dst.style.bg = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 1876 } 1877 } 1878 } 1879 } 1880 return out; 1881 } 1882 }; 1883