╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
477 allocator: std.mem.Allocator, 478 host: Host, 479 parts: IssueBaseParts, 480 update: evt.Issue.Update, 481 ) !void { 482 switch (host) { 483 .remote => |remote| { 484 const repo_prefix = "/repo/"; 485 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 486 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 487 defer allocator.free(repos_dir); 488 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 489 .ok => |p| p, 490 .invalid, .not_found => return error.NotFound, 491 }; 492 defer allocator.free(repo_path); 493 494 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 495 defer repo.deinit(io, allocator); 496 try evt.Issue.update(.xit, .{}, io, allocator, &repo, &parts.id_bytes, update); 497 }, 498 .local => |src| { 499 // the local forms post to "/issues/<id>/...", so the repo base 500 // is empty 501 if (parts.repo_base.len != 0) return error.NotFound; 502 switch (src.repo_kind) { 503 inline else => |repo_kind| { 504 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 505 defer any_repo.deinit(io, allocator); 506 switch (any_repo) { 507 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update), 508 } 509 }, 510 } 511 }, 512 } 513 } 514 515 // set the status of the issue the url names (base is 516 // "/repo/<owner>/<name>/issues/<id>", identity elided in local mode) by 517 // re-emitting its event, then redirect back to it 518 fn handleIssueStatus( 519 io: std.Io, 520 request: *std.http.Server.Request, 521 allocator: std.mem.Allocator, 522 base: []const u8, 523 host: Host, 524 status: evt.Issue.Status, 525 ) !void { 526 const not_found = "issue not found"; 527 const parts = issueBaseParts(base) orelse { 528 try request.respond(not_found, .{ 529 .status = .not_found, 530 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 531 }); 532 return; 533 }; 534 535 updateIssue(io, allocator, host, parts, .{ .status = status }) catch |err| switch (err) { 536 error.NotFound => { 537 try request.respond(not_found, .{ 538 .status = .not_found, 539 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 540 }); 541 return; 542 }, 543 else => |e| return e, 544 }; 545 546 // like logout, this is a bodyless POST, so close the connection rather than 547 // letting the keep-alive path try to discard a body that isn't framed. 548 try request.respond("", .{ 549 .status = .see_other, 550 .keep_alive = false, 551 .extra_headers = &.{.{ .name = "location", .value = base }}, 552 }); 553 } 554 555 // replace the title/tags/description of the issue the url names (base is 556 // "/repo/<owner>/<name>/issues/<id>", identity elided in local mode; the 557 // form posts to "<base>/edit") by re-emitting its event with its status 558 // preserved, then redirect back to it 559 fn handleIssueEdit( 560 io: std.Io, 561 request: *std.http.Server.Request, 562 allocator: std.mem.Allocator, 563 base: []const u8, 564 host: Host, 565 ) !void { 566 var body_buf: [256]u8 = undefined; 567 const reader = request.readerExpectNone(&body_buf); 568 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 569 defer allocator.free(body); 570 571 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 572 defer allocator.free(title); 573 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 574 defer allocator.free(tags); 575 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 576 defer allocator.free(description_crlf); 577 // form submission normalizes textarea line breaks to CRLF; store plain 578 // newlines so the text renders the same on every host 579 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 580 defer allocator.free(description); 581 582 // invalid fields send the user back to the edit form 583 if (!evt.Issue.fieldsValid(title, tags)) { 584 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 585 defer allocator.free(form_location); 586 try request.respond("", .{ 587 .status = .see_other, 588 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 589 }); 590 return; 591 } 592 593 const not_found = "issue not found"; 594 const parts = issueBaseParts(base) orelse { 595 try request.respond(not_found, .{ 596 .status = .not_found, 597 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 598 }); 599 return; 600 }; 601 602 updateIssue(io, allocator, host, parts, .{ .fields = .{ 603 .title = title, 604 .tags = tags, 605 .description = description, 606 } }) catch |err| switch (err) { 607 error.NotFound => { 608 try request.respond(not_found, .{ 609 .status = .not_found, 610 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 611 }); 612 return; 613 }, 614 else => |e| return e, 615 }; 616 617 try request.respond("", .{ 618 .status = .see_other, 619 .extra_headers = &.{.{ .name = "location", .value = base }}, 620 }); 621 } 622 623 fn renderIndexHtml( 624 io: std.Io, 625 allocator: std.mem.Allocator, 626 host: Host, 627 session_data: ui.Session.Data, 628 ) ![]const u8 { 629 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 630 631 var page_arena = std.heap.ArenaAllocator.init(allocator); 632 defer page_arena.deinit(); 633 634 // the remote admin repo must outlive the page build, since the session's 635 // moment reads from it. 636 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 637 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 638 639 var session = switch (host) { 640 .remote => |remote| blk: { 641 // open the admin repo to read live user/repo data. 642 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 643 const repo = if (repo_maybe) |*repo| repo else unreachable; 644 var session = try ui.Session.init(&page_arena, repo, session_data); 645 // give the page builders filesystem access to the on-disk repos (a 646 // sibling "repos" dir next to the admin repo) so the Repo page can 647 // read its files. 648 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 649 break :blk session; 650 }, 651 .local => |local| ui.Session{ 652 .data = session_data, 653 .arena = &page_arena, 654 .page_arena = &page_arena, 655 .local = local, 656 }, 657 }; 658 session.io = io; 659 660 const snapshot: ui.Snapshot = .{ 661 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 662 .session = session.data, 663 }; 664 var root = try ui.initRoot(allocator, &snapshot.page, &session); 665 defer root.deinit(allocator); 666 667 const content = try generateHtml(allocator, &root); 668 defer allocator.free(content); 669 const overlay = try generateOverlay(allocator, &root, &session); 670 defer allocator.free(overlay); 671 672 // serialize the snapshot so the wasm side can parse it back without making 673 // a second request. it's embedded raw in a <script type="application/json"> 674 // block, whose content is raw text terminated only by "</script". in json, 675 // '<' appears solely inside string values, so escaping every '<' (and '>' 676 // for good measure) to its \uXXXX form yields equivalent json that can't 677 // break out of the tag. 678 var json: std.Io.Writer.Allocating = .init(allocator); 679 defer json.deinit(); 680 try std.json.Stringify.value(snapshot, .{}, &json.writer); 681 682 var json_escaped: std.ArrayList(u8) = .empty; 683 defer json_escaped.deinit(allocator); 684 for (json.written()) |c| switch (c) { 685 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 686 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 687 else => try json_escaped.append(allocator, c), 688 }; 689 690 var out: std.ArrayList(u8) = .empty; 691 errdefer out.deinit(allocator); 692 { 693 var cursor: usize = 0; 694 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 695 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 696 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 697 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 698 }) |sub| { 699 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 700 try out.appendSlice(allocator, template[cursor..idx]); 701 try out.appendSlice(allocator, sub.replacement); 702 cursor = idx + sub.needle.len; 703 } 704 try out.appendSlice(allocator, template[cursor..]); 705 } 706 return try out.toOwnedSlice(allocator); 707 } 708 709 fn findEmbed(request_path: []const u8) ?Embed { 710 const path = if (std.mem.eql(u8, request_path, "/")) 711 "index.html" 712 else if (request_path.len > 1 and request_path[0] == '/') 713 request_path[1..] 714 else 715 return null; 716 717 for (embeds) |embed| { 718 if (std.mem.eql(u8, path, embed.path)) return embed; 719 } 720 return null; 721 } 722 723 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 724 // own absolutely-positioned, natively-scrollable <div> holding its full content, 725 // rendered recursively so nested scrolls work. 726 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 727 const grid = root.getGrid() orelse return error.MissingGrid; 728 729 var out: std.ArrayList(u8) = .empty; 730 errdefer out.deinit(allocator); 731 732 try renderPanel(allocator, &out, root.getFocus(), grid); 733 return try out.toOwnedSlice(allocator); 734 } 735 736 // render one panel — a focus subtree and its content grid — as HTML, recursing 737 // once per web-native Scroll inside it. the root panel is the whole page; each 738 // Scroll becomes a nested, natively-scrollable div holding its full content. 739 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 740 // then the child scroll divs over those holes. 741 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 742 // `direct` is this panel's scroll children, each drawn as an overlaid div. 743 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 744 // plus their descendants, which the focus tree flattens into this panel's 745 // children): the cell hit-test below skips them so this panel doesn't claim 746 // cells that are really rendered inside a child scroll's own panel. 747 // (scrolls aren't nested in practice, so every scroll child is direct here.) 748 var direct: std.ArrayList(usize) = .empty; 749 defer direct.deinit(allocator); 750 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 751 defer excluded.deinit(allocator); 752 { 753 var it = focus.children.iterator(); 754 while (it.next()) |e| { 755 if (e.value_ptr.focus.scroll == null) continue; 756 try direct.append(allocator, e.key_ptr.*); 757 try excluded.put(allocator, e.key_ptr.*, {}); 758 var mit = e.value_ptr.focus.children.iterator(); 759 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 760 } 761 } 762 763 // the HTML element a run of cells is wrapped in, chosen from the cell's 764 // focusable kind 765 const CellTag = union(enum) { 766 span, // clickable focusable cell 767 a: []const u8, // clickable focusable link 768 plain, // non-focusable, colored 769 770 const a_prefix = "a:"; 771 // an "in-page" anchor: rendered as a real <a href> so it works with js 772 // disabled, but crossPageLink ignores it, so with wasm the click just 773 // moves focus rather than navigating. 774 const inpage_prefix = "ai:"; 775 776 fn init(str: []const u8) @This() { 777 if (std.mem.startsWith(u8, str, inpage_prefix)) { 778 return .{ .a = str[inpage_prefix.len..] }; 779 } 780 if (std.mem.startsWith(u8, str, a_prefix)) { 781 return .{ .a = str[a_prefix.len..] }; 782 } 783 return .span; 784 } 785 786 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 787 var id_buf: [32]u8 = undefined; 788 switch (self) { 789 .span => { 790 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 791 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 792 try out.appendSlice(alloc, "\""); 793 try out.appendSlice(alloc, style_attr); 794 try out.appendSlice(alloc, ">"); 795 }, 796 .a => |href| { 797 // tabindex=-1 keeps these out of the browser's tab order 798 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 799 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 800 try out.appendSlice(alloc, "\" href=\""); 801 try appendEscapedHtml(alloc, out, href); 802 try out.appendSlice(alloc, "\""); 803 try out.appendSlice(alloc, style_attr); 804 try out.appendSlice(alloc, ">"); 805 }, 806 .plain => { 807 try out.appendSlice(alloc, "<span"); 808 try out.appendSlice(alloc, style_attr); 809 try out.appendSlice(alloc, ">"); 810 }, 811 } 812 } 813 814 fn closeTag(self: @This()) []const u8 { 815 return switch (self) { 816 .span, .plain => "</span>", 817 .a => "</a>", 818 }; 819 } 820 }; 821 822 // emit this panel's grid as rows of text, coalescing adjacent cells that 823 // share a focus id and colors into one tag (a clickable span, a link, or a 824 // plain colored span). cells under a child scroll keep only their background. 825 for (0..grid.size.height) |y| { 826 var cur_id: ?usize = null; 827 var cur_fg: ?Grid.Color = null; 828 var cur_bg: ?Grid.Color = null; 829 var open_tag: ?CellTag = null; 830 var first = true; 831 for (0..grid.size.width) |x| { 832 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 833 // a cell covered by a child scroll's viewport is drawn by that scroll's 834 // own div, so blank its glyph and make it non-clickable here — but keep 835 // its background, so the backdrop still shows through the scroll's 836 // transparent div instead of a bare hole. 837 const covered_by_scroll = blk: { 838 for (direct.items) |id| { 839 const r = (focus.children.get(id) orelse continue).rect; 840 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 841 } 842 break :blk false; 843 }; 844 // the focusable cell at (x, y) among this panel's own focusables (skipping 845 // any that belong to a child scroll, whose cells are drawn in their own 846 // panel); none for a covered cell. 847 const cell_id = if (covered_by_scroll) null else blk: { 848 var iter = focus.children.iterator(); 849 while (iter.next()) |entry| { 850 const child = entry.value_ptr.*; 851 if (!child.focus.focusable) continue; 852 if (excluded.contains(entry.key_ptr.*)) continue; 853 const r = child.rect; 854 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 855 break :blk entry.key_ptr.*; 856 } 857 } 858 break :blk null; 859 }; 860 const fg = if (covered_by_scroll) null else cell.style.fg; 861 const bg = cell.style.bg; 862 863 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 864 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 865 866 var new_tag: ?CellTag = null; 867 if (cell_id) |id| { 868 if (focus.children.get(id)) |child| { 869 new_tag = switch (child.focus.kind) { 870 .custom => |custom| CellTag.init(custom), 871 else => .span, 872 }; 873 } 874 } 875 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 876 877 if (new_tag) |t| { 878 var style_buf: [64]u8 = undefined; 879 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 880 } 881 882 open_tag = new_tag; 883 cur_id = cell_id; 884 cur_fg = fg; 885 cur_bg = bg; 886 first = false; 887 } 888 889 if (covered_by_scroll) { 890 try appendEscapedHtml(allocator, output, " "); 891 } else if (cell.continuation) { 892 // the wide rune to the left was emitted 2ch wide, covering this column 893 } else if (cell.rune) |rune| { 894 // a double-width rune is pinned inside a 2ch span so the 895 // fallback glyph's advance width can't shift the rest of the row 896 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 897 if (wide) { 898 try output.appendSlice(allocator, "<span class=\"w2\">"); 899 try appendEscapedHtml(allocator, output, rune); 900 try output.appendSlice(allocator, "</span>"); 901 } else { 902 try appendEscapedHtml(allocator, output, rune); 903 } 904 } else { 905 try appendEscapedHtml(allocator, output, " "); 906 } 907 } 908 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 909 try output.append(allocator, '\n'); 910 } 911 912 // each child scroll becomes a natively-scrollable div positioned over its 913 // viewport, holding its full content rendered recursively. 914 for (direct.items) |id| { 915 const child = focus.children.get(id) orelse continue; 916 const info = child.focus.scroll orelse continue; 917 const r = child.rect; 918 // overflow only on the axes the widget scrolls; `auto` shows a bar only 919 // when that axis actually overflows. the other axis is clipped (hidden), 920 // matching how the terminal Scroll handles its non-scrolling axis. 921 const overflow = switch (info.direction) { 922 .vert => "overflow-x:hidden;overflow-y:auto", 923 .horiz => "overflow-x:auto;overflow-y:hidden", 924 .both => "overflow:auto", 925 }; 926 // the id carries a content version so JS preserves the native scroll 927 // position across re-renders of the same content but resets it when the 928 // content is replaced — e.g. selecting a different commit. the widget's 929 // scroll offset (in cells) rides along so JS can apply it when it has no 930 // preserved position, letting a wasm-side scrollToRect (the files list 931 // scrolling to its selected row on page load) reach the browser. 932 var buf: [224]u8 = undefined; 933 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 934 try renderPanel(allocator, output, child.focus, info.content); 935 try output.appendSlice(allocator, "</div>"); 936 } 937 } 938 939 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 940 // widget tree, each wrapping the text inputs and submit button inside it, 941 // positioned absolutely over the matching grid cells. 942 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 943 const root_focus = root.getFocus(); 944 945 var out: std.ArrayList(u8) = .empty; 946 errdefer out.deinit(allocator); 947 948 const form_prefix = "form:"; 949 950 // Focus.children is an AutoArrayHashMap that preserves insertion order, 951 // which matches the order widgets were added in code 952 var iter = root_focus.children.iterator(); 953 while (iter.next()) |entry| { 954 const child = entry.value_ptr.*; 955 const action_url = switch (child.focus.kind) { 956 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 957 custom[form_prefix.len..] 958 else 959 continue, 960 else => continue, 961 }; 962 963 try out.appendSlice(allocator, "<form action=\""); 964 try appendEscapedHtml(allocator, &out, action_url); 965 try out.appendSlice(allocator, "\" method=\"post\""); 966 // an empty action must not POST — block it and send the input to the TUI instead 967 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 968 try out.appendSlice(allocator, ">"); 969 970 // form.focus.children was populated by addChild, which flattens the 971 // whole subtree into one map — so descendants (inputs + the submit 972 // button) all appear here. positions on form.focus are relative to 973 // the form, so we look up absolute rects via root_focus for layout. 974 var inner_iter = child.focus.children.iterator(); 975 while (inner_iter.next()) |inner_entry| { 976 const inner_id = inner_entry.key_ptr.*; 977 const root_child = root_focus.children.get(inner_id) orelse continue; 978 const r = root_child.rect; 979 switch (root_child.focus.kind) { 980 .text_input, .text_input_password => { 981 const ti = session.text_inputs.get(inner_id) orelse continue; 982 const inner_left = r.x + 1; 983 const inner_top = r.y + 1; 984 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 985 986 try out.appendSlice(allocator, "<input type=\""); 987 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 988 try out.appendSlice(allocator, "\" data-focus-id=\""); 989 var id_buf: [32]u8 = undefined; 990 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 991 if (ti.options.name.len > 0) { 992 try out.appendSlice(allocator, "\" name=\""); 993 try appendEscapedHtml(allocator, &out, ti.options.name); 994 } 995 // never the live content as the `value`: the browser tracks user 996 // input natively, and including the wasm-side value here would make 997 // the overlay HTML differ on every keystroke — that would trip the 998 // diff in _setOverlay and rebuild the <input>, eating the user's 999 // caret. a page-constant initial value is safe. 1000 if (session.input_values.get(inner_id)) |value| { 1001 try out.appendSlice(allocator, "\" value=\""); 1002 try appendEscapedHtml(allocator, &out, value); 1003 } 1004 try out.appendSlice(allocator, "\" style=\"left:"); 1005 var pos_buf: [64]u8 = undefined; 1006 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 1007 try out.appendSlice(allocator, "\">"); 1008 }, 1009 .text_area => { 1010 const ti = session.text_inputs.get(inner_id) orelse continue; 1011 const inner_left = r.x + 1; 1012 const inner_top = r.y + 1; 1013 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1014 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1015 1016 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1017 var id_buf: [32]u8 = undefined; 1018 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1019 if (ti.options.name.len > 0) { 1020 try out.appendSlice(allocator, "\" name=\""); 1021 try appendEscapedHtml(allocator, &out, ti.options.name); 1022 } 1023 // like the input above, only a page-constant initial value 1024 // inside: the browser tracks the live value and the 1025 // overlay diff must stay stable across keystrokes 1026 try out.appendSlice(allocator, "\" style=\"left:"); 1027 var pos_buf: [128]u8 = undefined; 1028 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 1029 try out.appendSlice(allocator, "\">"); 1030 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1031 try out.appendSlice(allocator, "</textarea>"); 1032 }, 1033 .custom => |custom| { 1034 if (std.mem.eql(u8, "submit", custom)) { 1035 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1036 var id_buf: [32]u8 = undefined; 1037 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1038 try out.appendSlice(allocator, "\" style=\"left:"); 1039 var pos_buf: [128]u8 = undefined; 1040 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1041 try out.appendSlice(allocator, "\"></button>"); 1042 } 1043 }, 1044 else => {}, 1045 } 1046 } 1047 1048 try out.appendSlice(allocator, "</form>"); 1049 } 1050 1051 return try out.toOwnedSlice(allocator); 1052 } 1053 1054 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1055 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1056 return b == null; 1057 } 1058 1059 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1060 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1061 // empty slice when neither is set. 1062 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1063 if (fg == null and bg == null) return buf[0..0]; 1064 const prefix = " style=\""; 1065 @memcpy(buf[0..prefix.len], prefix); 1066 var i: usize = prefix.len; 1067 if (fg) |c| { 1068 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1069 i += s.len; 1070 } 1071 if (bg) |c| { 1072 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1073 i += s.len; 1074 } 1075 buf[i] = '"'; 1076 i += 1; 1077 return buf[0..i]; 1078 } 1079 1080 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1081 for (input) |ch| { 1082 switch (ch) { 1083 '&' => try out.appendSlice(allocator, "&amp;"), 1084 '<' => try out.appendSlice(allocator, "&lt;"), 1085 '>' => try out.appendSlice(allocator, "&gt;"), 1086 '"' => try out.appendSlice(allocator, "&quot;"), 1087 '\'' => try out.appendSlice(allocator, "&#39;"), 1088 else => try out.append(allocator, ch), 1089 } 1090 } 1091 } 1092 1093 // --- helpers -------------------------------------------------------------- 1094 1095 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1096 var iter = request.iterateHeaders(); 1097 while (iter.next()) |header| { 1098 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1099 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1100 while (pairs.next()) |pair| { 1101 const trimmed = std.mem.trim(u8, pair, " \t"); 1102 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1103 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1104 return trimmed[eq + 1 ..]; 1105 } 1106 } 1107 } 1108 return null; 1109 } 1110 1111 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1112 var iter = std.mem.splitScalar(u8, body, '&'); 1113 while (iter.next()) |pair| { 1114 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1115 if (std.mem.eql(u8, pair[0..eq], key)) { 1116 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1117 } 1118 } 1119 return null; 1120 } 1121 1122 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1123 var out: std.ArrayList(u8) = .empty; 1124 errdefer out.deinit(allocator); 1125 var i: usize = 0; 1126 while (i < encoded.len) : (i += 1) { 1127 switch (encoded[i]) { 1128 '+' => try out.append(allocator, ' '), 1129 '%' => { 1130 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1131 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1132 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1133 try out.append(allocator, hi * 16 + lo); 1134 i += 2; 1135 }, 1136 else => try out.append(allocator, encoded[i]), 1137 } 1138 } 1139 return try out.toOwnedSlice(allocator); 1140 } 1141 1142 // disk-backed web session store. each login mints a random, opaque token 1143 // (not the user's id) that is stored as a file named by the token hex, whose 1144 // contents are the raw user_id bytes. authenticating a request is a lookup of 1145 // the cookie's token; logout deletes the file, revoking the session. there is 1146 // deliberately no expiry — a session lives until logout. 1147 pub const SessionStore = struct { 1148 io: std.Io, 1149 dir: std.Io.Dir, 1150 1151 pub const token_hex_len = evt.event_id_size * 2; 1152 1153 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1154 try data_dir.createDirPath(io, "sessions"); 1155 const dir = try data_dir.openDir(io, "sessions", .{}); 1156 return .{ .io = io, .dir = dir }; 1157 } 1158 1159 pub fn deinit(self: SessionStore) void { 1160 self.dir.close(self.io); 1161 } 1162 1163 // mint a new session for user_id, returning the token hex to set as the 1164 // cookie value. 1165 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1166 var token: [evt.event_id_size]u8 = undefined; 1167 self.io.random(&token); 1168 const token_hex = std.fmt.bytesToHex(token, .lower); 1169 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1170 defer file.close(self.io); 1171 try file.writeStreamingAll(self.io, user_id); 1172 return token_hex; 1173 } 1174 1175 // resolve a cookie's token to its user_id. returns false (logged out) for a 1176 // missing, malformed, or unknown token. 1177 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1178 if (!isToken(token_hex)) return false; 1179 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1180 defer file.close(self.io); 1181 var storage: [evt.event_id_size]u8 = undefined; 1182 var file_reader = file.reader(self.io, &storage); 1183 file_reader.interface.readSliceAll(out) catch return false; 1184 return true; 1185 } 1186 1187 // revoke a session. a no-op for a missing or malformed token. 1188 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1189 if (!isToken(token_hex)) return; 1190 self.dir.deleteFile(self.io, token_hex) catch {}; 1191 } 1192 1193 // a token is exactly token_hex_len hex chars. validating before using the 1194 // value as a path keeps attacker-supplied cookies from escaping the 1195 // sessions dir (e.g. via "/" or ".." bytes). 1196 fn isToken(token_hex: []const u8) bool { 1197 if (token_hex.len != token_hex_len) return false; 1198 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1199 return true; 1200 } 1201 }; 1202