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