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