╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
622 } 623 }; 624 625 // emit this panel's grid as rows of text, coalescing adjacent cells that 626 // share a focus id and colors into one tag (a clickable span, a link, or a 627 // plain colored span). cells under a child scroll keep only their background. 628 for (0..grid.size.height) |y| { 629 var cur_id: ?usize = null; 630 var cur_fg: ?Grid.Color = null; 631 var cur_bg: ?Grid.Color = null; 632 var open_tag: ?CellTag = null; 633 var first = true; 634 for (0..grid.size.width) |x| { 635 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 636 // a cell covered by a child scroll's viewport is drawn by that scroll's 637 // own div, so blank its glyph and make it non-clickable here — but keep 638 // its background, so the backdrop still shows through the scroll's 639 // transparent div instead of a bare hole. 640 const covered_by_scroll = blk: { 641 for (direct.items) |id| { 642 const r = (focus.children.get(id) orelse continue).rect; 643 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; 644 } 645 break :blk false; 646 }; 647 // the focusable cell at (x, y) among this panel's own focusables (skipping 648 // any that belong to a child scroll, whose cells are drawn in their own 649 // panel); none for a covered cell. 650 const cell_id = if (covered_by_scroll) null else blk: { 651 var iter = focus.children.iterator(); 652 while (iter.next()) |entry| { 653 const child = entry.value_ptr.*; 654 if (!child.focus.focusable) continue; 655 if (excluded.contains(entry.key_ptr.*)) continue; 656 const r = child.rect; 657 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 658 break :blk entry.key_ptr.*; 659 } 660 } 661 break :blk null; 662 }; 663 const fg = if (covered_by_scroll) null else cell.style.fg; 664 const bg = cell.style.bg; 665 666 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 667 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 668 669 var new_tag: ?CellTag = null; 670 if (cell_id) |id| { 671 if (focus.children.get(id)) |child| { 672 new_tag = switch (child.focus.kind) { 673 .custom => |custom| CellTag.init(custom), 674 else => .span, 675 }; 676 } 677 } 678 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 679 680 if (new_tag) |t| { 681 var style_buf: [64]u8 = undefined; 682 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 683 } 684 685 open_tag = new_tag; 686 cur_id = cell_id; 687 cur_fg = fg; 688 cur_bg = bg; 689 first = false; 690 } 691 692 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 693 } 694 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 695 try output.append(allocator, '\n'); 696 } 697 698 // each child scroll becomes a natively-scrollable div positioned over its 699 // viewport, holding its full content rendered recursively. 700 for (direct.items) |id| { 701 const child = focus.children.get(id) orelse continue; 702 const info = child.focus.scroll orelse continue; 703 const r = child.rect; 704 // overflow only on the axes the widget scrolls; `auto` shows a bar only 705 // when that axis actually overflows. the other axis is clipped (hidden), 706 // matching how the terminal Scroll handles its non-scrolling axis. 707 const overflow = switch (info.direction) { 708 .vert => "overflow-x:hidden;overflow-y:auto", 709 .horiz => "overflow-x:auto;overflow-y:hidden", 710 .both => "overflow:auto", 711 }; 712 // the id carries a content version so JS preserves the native scroll 713 // position across re-renders of the same content but resets it when the 714 // content is replaced — e.g. selecting a different commit. the widget's 715 // scroll offset (in cells) rides along so JS can apply it when it has no 716 // preserved position, letting a wasm-side scrollToRect (the files list 717 // scrolling to its selected row on page load) reach the browser. 718 var buf: [224]u8 = undefined; 719 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 })); 720 try renderPanel(allocator, output, child.focus, info.content); 721 try output.appendSlice(allocator, "</div>"); 722 } 723 } 724 725 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 726 // widget tree, each wrapping the text inputs and submit button inside it, 727 // positioned absolutely over the matching grid cells. 728 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 729 const root_focus = root.getFocus(); 730 731 var out: std.ArrayList(u8) = .empty; 732 errdefer out.deinit(allocator); 733 734 const form_prefix = "form:"; 735 736 // Focus.children is an AutoArrayHashMap that preserves insertion order, 737 // which matches the order widgets were added in code 738 var iter = root_focus.children.iterator(); 739 while (iter.next()) |entry| { 740 const child = entry.value_ptr.*; 741 const action_url = switch (child.focus.kind) { 742 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 743 custom[form_prefix.len..] 744 else 745 continue, 746 else => continue, 747 }; 748 749 try out.appendSlice(allocator, "<form action=\""); 750 try appendEscapedHtml(allocator, &out, action_url); 751 try out.appendSlice(allocator, "\" method=\"post\""); 752 // an empty action must not POST — block it and send the input to the TUI instead 753 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 754 try out.appendSlice(allocator, ">"); 755 756 // form.focus.children was populated by addChild, which flattens the 757 // whole subtree into one map — so descendants (inputs + the submit 758 // button) all appear here. positions on form.focus are relative to 759 // the form, so we look up absolute rects via root_focus for layout. 760 var inner_iter = child.focus.children.iterator(); 761 while (inner_iter.next()) |inner_entry| { 762 const inner_id = inner_entry.key_ptr.*; 763 const root_child = root_focus.children.get(inner_id) orelse continue; 764 const r = root_child.rect; 765 switch (root_child.focus.kind) { 766 .text_input, .text_input_password => { 767 const ti = session.text_inputs.get(inner_id) orelse continue; 768 const inner_left = r.x + 1; 769 const inner_top = r.y + 1; 770 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 771 772 try out.appendSlice(allocator, "<input type=\""); 773 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 774 try out.appendSlice(allocator, "\" data-focus-id=\""); 775 var id_buf: [32]u8 = undefined; 776 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 777 if (ti.options.name.len > 0) { 778 try out.appendSlice(allocator, "\" name=\""); 779 try appendEscapedHtml(allocator, &out, ti.options.name); 780 } 781 // intentionally no `value` attribute: the browser tracks user input 782 // natively, and including the wasm-side value here would make the 783 // overlay HTML differ on every keystroke — that would trip the diff 784 // in _setOverlay and rebuild the <input>, eating the user's caret. 785 try out.appendSlice(allocator, "\" style=\"left:"); 786 var pos_buf: [64]u8 = undefined; 787 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 })); 788 try out.appendSlice(allocator, "\">"); 789 }, 790 .text_area => { 791 const ti = session.text_inputs.get(inner_id) orelse continue; 792 const inner_left = r.x + 1; 793 const inner_top = r.y + 1; 794 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 795 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 796 797 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 798 var id_buf: [32]u8 = undefined; 799 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 800 if (ti.options.name.len > 0) { 801 try out.appendSlice(allocator, "\" name=\""); 802 try appendEscapedHtml(allocator, &out, ti.options.name); 803 } 804 // like the input above, no content inside: the browser 805 // tracks the value and the overlay diff must stay stable 806 // across keystrokes 807 try out.appendSlice(allocator, "\" style=\"left:"); 808 var pos_buf: [128]u8 = undefined; 809 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 })); 810 try out.appendSlice(allocator, "\"></textarea>"); 811 }, 812 .custom => |custom| { 813 if (std.mem.eql(u8, "submit", custom)) { 814 // inside the dashed border the TUI cells draw around the button. 815 const inner_left = r.x + 1; 816 const inner_top = r.y + 1; 817 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 818 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 819 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 820 var id_buf: [32]u8 = undefined; 821 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 822 try out.appendSlice(allocator, "\" style=\"left:"); 823 var pos_buf: [128]u8 = undefined; 824 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 })); 825 try out.appendSlice(allocator, "\"></button>"); 826 } 827 }, 828 else => {}, 829 } 830 } 831 832 try out.appendSlice(allocator, "</form>"); 833 } 834 835 return try out.toOwnedSlice(allocator); 836 } 837 838 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 839 if (a) |av| return if (b) |bv| av.eql(bv) else false; 840 return b == null; 841 } 842 843 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 844 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 845 // empty slice when neither is set. 846 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 847 if (fg == null and bg == null) return buf[0..0]; 848 const prefix = " style=\""; 849 @memcpy(buf[0..prefix.len], prefix); 850 var i: usize = prefix.len; 851 if (fg) |c| { 852 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]; 853 i += s.len; 854 } 855 if (bg) |c| { 856 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]; 857 i += s.len; 858 } 859 buf[i] = '"'; 860 i += 1; 861 return buf[0..i]; 862 } 863 864 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 865 for (input) |ch| { 866 switch (ch) { 867 '&' => try out.appendSlice(allocator, "&amp;"), 868 '<' => try out.appendSlice(allocator, "&lt;"), 869 '>' => try out.appendSlice(allocator, "&gt;"), 870 '"' => try out.appendSlice(allocator, "&quot;"), 871 '\'' => try out.appendSlice(allocator, "&#39;"), 872 else => try out.append(allocator, ch), 873 } 874 } 875 } 876 877 // --- helpers -------------------------------------------------------------- 878 879 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 880 var iter = request.iterateHeaders(); 881 while (iter.next()) |header| { 882 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 883 var pairs = std.mem.splitScalar(u8, header.value, ';'); 884 while (pairs.next()) |pair| { 885 const trimmed = std.mem.trim(u8, pair, " \t"); 886 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 887 if (std.mem.eql(u8, trimmed[0..eq], name)) { 888 return trimmed[eq + 1 ..]; 889 } 890 } 891 } 892 return null; 893 } 894 895 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 896 var iter = std.mem.splitScalar(u8, body, '&'); 897 while (iter.next()) |pair| { 898 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 899 if (std.mem.eql(u8, pair[0..eq], key)) { 900 return try decodeFormValue(allocator, pair[eq + 1 ..]); 901 } 902 } 903 return null; 904 } 905 906 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 907 var out: std.ArrayList(u8) = .empty; 908 errdefer out.deinit(allocator); 909 var i: usize = 0; 910 while (i < encoded.len) : (i += 1) { 911 switch (encoded[i]) { 912 '+' => try out.append(allocator, ' '), 913 '%' => { 914 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 915 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 916 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 917 try out.append(allocator, hi * 16 + lo); 918 i += 2; 919 }, 920 else => try out.append(allocator, encoded[i]), 921 } 922 } 923 return try out.toOwnedSlice(allocator); 924 } 925 926 // disk-backed web session store. each login mints a random, opaque token 927 // (not the user's id) that is stored as a file named by the token hex, whose 928 // contents are the raw user_id bytes. authenticating a request is a lookup of 929 // the cookie's token; logout deletes the file, revoking the session. there is 930 // deliberately no expiry — a session lives until logout. 931 pub const SessionStore = struct { 932 io: std.Io, 933 dir: std.Io.Dir, 934 935 pub const token_hex_len = evt.event_id_size * 2; 936 937 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 938 try data_dir.createDirPath(io, "sessions"); 939 const dir = try data_dir.openDir(io, "sessions", .{}); 940 return .{ .io = io, .dir = dir }; 941 } 942 943 pub fn deinit(self: SessionStore) void { 944 self.dir.close(self.io); 945 } 946 947 // mint a new session for user_id, returning the token hex to set as the 948 // cookie value. 949 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 950 var token: [evt.event_id_size]u8 = undefined; 951 self.io.random(&token); 952 const token_hex = std.fmt.bytesToHex(token, .lower); 953 const file = try self.dir.createFile(self.io, &token_hex, .{}); 954 defer file.close(self.io); 955 try file.writeStreamingAll(self.io, user_id); 956 return token_hex; 957 } 958 959 // resolve a cookie's token to its user_id. returns false (logged out) for a 960 // missing, malformed, or unknown token. 961 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 962 if (!isToken(token_hex)) return false; 963 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 964 defer file.close(self.io); 965 var storage: [evt.event_id_size]u8 = undefined; 966 var file_reader = file.reader(self.io, &storage); 967 file_reader.interface.readSliceAll(out) catch return false; 968 return true; 969 } 970 971 // revoke a session. a no-op for a missing or malformed token. 972 pub fn remove(self: SessionStore, token_hex: []const u8) void { 973 if (!isToken(token_hex)) return; 974 self.dir.deleteFile(self.io, token_hex) catch {}; 975 } 976 977 // a token is exactly token_hex_len hex chars. validating before using the 978 // value as a path keeps attacker-supplied cookies from escaping the 979 // sessions dir (e.g. via "/" or ".." bytes). 980 fn isToken(token_hex: []const u8) bool { 981 if (token_hex.len != token_hex_len) return false; 982 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 983 return true; 984 } 985 }; 986