╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
770 }; 771 } 772 } 773 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 774 775 if (new_tag) |t| { 776 var style_buf: [64]u8 = undefined; 777 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 778 } 779 780 open_tag = new_tag; 781 cur_id = cell_id; 782 cur_fg = fg; 783 cur_bg = bg; 784 first = false; 785 } 786 787 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 788 } 789 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 790 try output.append(allocator, '\n'); 791 } 792 793 // each child scroll becomes a natively-scrollable div positioned over its 794 // viewport, holding its full content rendered recursively. 795 for (direct.items) |id| { 796 const child = focus.children.get(id) orelse continue; 797 const info = child.focus.scroll orelse continue; 798 const r = child.rect; 799 // overflow only on the axes the widget scrolls; `auto` shows a bar only 800 // when that axis actually overflows. the other axis is clipped (hidden), 801 // matching how the terminal Scroll handles its non-scrolling axis. 802 const overflow = switch (info.direction) { 803 .vert => "overflow-x:hidden;overflow-y:auto", 804 .horiz => "overflow-x:auto;overflow-y:hidden", 805 .both => "overflow:auto", 806 }; 807 // the id carries a content version so JS preserves the native scroll 808 // position across re-renders of the same content but resets it when the 809 // content is replaced — e.g. selecting a different commit. the widget's 810 // scroll offset (in cells) rides along so JS can apply it when it has no 811 // preserved position, letting a wasm-side scrollToRect (the files list 812 // scrolling to its selected row on page load) reach the browser. 813 var buf: [224]u8 = undefined; 814 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 })); 815 try renderPanel(allocator, output, child.focus, info.content); 816 try output.appendSlice(allocator, "</div>"); 817 } 818 } 819 820 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 821 // widget tree, each wrapping the text inputs and submit button inside it, 822 // positioned absolutely over the matching grid cells. 823 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 824 const root_focus = root.getFocus(); 825 826 var out: std.ArrayList(u8) = .empty; 827 errdefer out.deinit(allocator); 828 829 const form_prefix = "form:"; 830 831 // Focus.children is an AutoArrayHashMap that preserves insertion order, 832 // which matches the order widgets were added in code 833 var iter = root_focus.children.iterator(); 834 while (iter.next()) |entry| { 835 const child = entry.value_ptr.*; 836 const action_url = switch (child.focus.kind) { 837 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 838 custom[form_prefix.len..] 839 else 840 continue, 841 else => continue, 842 }; 843 844 try out.appendSlice(allocator, "<form action=\""); 845 try appendEscapedHtml(allocator, &out, action_url); 846 try out.appendSlice(allocator, "\" method=\"post\""); 847 // an empty action must not POST — block it and send the input to the TUI instead 848 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 849 try out.appendSlice(allocator, ">"); 850 851 // form.focus.children was populated by addChild, which flattens the 852 // whole subtree into one map — so descendants (inputs + the submit 853 // button) all appear here. positions on form.focus are relative to 854 // the form, so we look up absolute rects via root_focus for layout. 855 var inner_iter = child.focus.children.iterator(); 856 while (inner_iter.next()) |inner_entry| { 857 const inner_id = inner_entry.key_ptr.*; 858 const root_child = root_focus.children.get(inner_id) orelse continue; 859 const r = root_child.rect; 860 switch (root_child.focus.kind) { 861 .text_input, .text_input_password => { 862 const ti = session.text_inputs.get(inner_id) orelse continue; 863 const inner_left = r.x + 1; 864 const inner_top = r.y + 1; 865 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 866 867 try out.appendSlice(allocator, "<input type=\""); 868 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 869 try out.appendSlice(allocator, "\" data-focus-id=\""); 870 var id_buf: [32]u8 = undefined; 871 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 872 if (ti.options.name.len > 0) { 873 try out.appendSlice(allocator, "\" name=\""); 874 try appendEscapedHtml(allocator, &out, ti.options.name); 875 } 876 // intentionally no `value` attribute: the browser tracks user input 877 // natively, and including the wasm-side value here would make the 878 // overlay HTML differ on every keystroke — that would trip the diff 879 // in _setOverlay and rebuild the <input>, eating the user's caret. 880 try out.appendSlice(allocator, "\" style=\"left:"); 881 var pos_buf: [64]u8 = undefined; 882 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 })); 883 try out.appendSlice(allocator, "\">"); 884 }, 885 .text_area => { 886 const ti = session.text_inputs.get(inner_id) orelse continue; 887 const inner_left = r.x + 1; 888 const inner_top = r.y + 1; 889 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 890 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 891 892 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 893 var id_buf: [32]u8 = undefined; 894 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 895 if (ti.options.name.len > 0) { 896 try out.appendSlice(allocator, "\" name=\""); 897 try appendEscapedHtml(allocator, &out, ti.options.name); 898 } 899 // like the input above, no content inside: the browser 900 // tracks the value and the overlay diff must stay stable 901 // across keystrokes 902 try out.appendSlice(allocator, "\" style=\"left:"); 903 var pos_buf: [128]u8 = undefined; 904 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 })); 905 try out.appendSlice(allocator, "\"></textarea>"); 906 }, 907 .custom => |custom| { 908 if (std.mem.eql(u8, "submit", custom)) { 909 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 910 var id_buf: [32]u8 = undefined; 911 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 912 try out.appendSlice(allocator, "\" style=\"left:"); 913 var pos_buf: [128]u8 = undefined; 914 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 })); 915 try out.appendSlice(allocator, "\"></button>"); 916 } 917 }, 918 else => {}, 919 } 920 } 921 922 try out.appendSlice(allocator, "</form>"); 923 } 924 925 return try out.toOwnedSlice(allocator); 926 } 927 928 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 929 if (a) |av| return if (b) |bv| av.eql(bv) else false; 930 return b == null; 931 } 932 933 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 934 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 935 // empty slice when neither is set. 936 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 937 if (fg == null and bg == null) return buf[0..0]; 938 const prefix = " style=\""; 939 @memcpy(buf[0..prefix.len], prefix); 940 var i: usize = prefix.len; 941 if (fg) |c| { 942 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]; 943 i += s.len; 944 } 945 if (bg) |c| { 946 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]; 947 i += s.len; 948 } 949 buf[i] = '"'; 950 i += 1; 951 return buf[0..i]; 952 } 953 954 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 955 for (input) |ch| { 956 switch (ch) { 957 '&' => try out.appendSlice(allocator, "&amp;"), 958 '<' => try out.appendSlice(allocator, "&lt;"), 959 '>' => try out.appendSlice(allocator, "&gt;"), 960 '"' => try out.appendSlice(allocator, "&quot;"), 961 '\'' => try out.appendSlice(allocator, "&#39;"), 962 else => try out.append(allocator, ch), 963 } 964 } 965 } 966 967 // --- helpers -------------------------------------------------------------- 968 969 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 970 var iter = request.iterateHeaders(); 971 while (iter.next()) |header| { 972 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 973 var pairs = std.mem.splitScalar(u8, header.value, ';'); 974 while (pairs.next()) |pair| { 975 const trimmed = std.mem.trim(u8, pair, " \t"); 976 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 977 if (std.mem.eql(u8, trimmed[0..eq], name)) { 978 return trimmed[eq + 1 ..]; 979 } 980 } 981 } 982 return null; 983 } 984 985 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 986 var iter = std.mem.splitScalar(u8, body, '&'); 987 while (iter.next()) |pair| { 988 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 989 if (std.mem.eql(u8, pair[0..eq], key)) { 990 return try decodeFormValue(allocator, pair[eq + 1 ..]); 991 } 992 } 993 return null; 994 } 995 996 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 997 var out: std.ArrayList(u8) = .empty; 998 errdefer out.deinit(allocator); 999 var i: usize = 0; 1000 while (i < encoded.len) : (i += 1) { 1001 switch (encoded[i]) { 1002 '+' => try out.append(allocator, ' '), 1003 '%' => { 1004 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1005 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1006 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1007 try out.append(allocator, hi * 16 + lo); 1008 i += 2; 1009 }, 1010 else => try out.append(allocator, encoded[i]), 1011 } 1012 } 1013 return try out.toOwnedSlice(allocator); 1014 } 1015 1016 // disk-backed web session store. each login mints a random, opaque token 1017 // (not the user's id) that is stored as a file named by the token hex, whose 1018 // contents are the raw user_id bytes. authenticating a request is a lookup of 1019 // the cookie's token; logout deletes the file, revoking the session. there is 1020 // deliberately no expiry — a session lives until logout. 1021 pub const SessionStore = struct { 1022 io: std.Io, 1023 dir: std.Io.Dir, 1024 1025 pub const token_hex_len = evt.event_id_size * 2; 1026 1027 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1028 try data_dir.createDirPath(io, "sessions"); 1029 const dir = try data_dir.openDir(io, "sessions", .{}); 1030 return .{ .io = io, .dir = dir }; 1031 } 1032 1033 pub fn deinit(self: SessionStore) void { 1034 self.dir.close(self.io); 1035 } 1036 1037 // mint a new session for user_id, returning the token hex to set as the 1038 // cookie value. 1039 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1040 var token: [evt.event_id_size]u8 = undefined; 1041 self.io.random(&token); 1042 const token_hex = std.fmt.bytesToHex(token, .lower); 1043 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1044 defer file.close(self.io); 1045 try file.writeStreamingAll(self.io, user_id); 1046 return token_hex; 1047 } 1048 1049 // resolve a cookie's token to its user_id. returns false (logged out) for a 1050 // missing, malformed, or unknown token. 1051 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1052 if (!isToken(token_hex)) return false; 1053 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1054 defer file.close(self.io); 1055 var storage: [evt.event_id_size]u8 = undefined; 1056 var file_reader = file.reader(self.io, &storage); 1057 file_reader.interface.readSliceAll(out) catch return false; 1058 return true; 1059 } 1060 1061 // revoke a session. a no-op for a missing or malformed token. 1062 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1063 if (!isToken(token_hex)) return; 1064 self.dir.deleteFile(self.io, token_hex) catch {}; 1065 } 1066 1067 // a token is exactly token_hex_len hex chars. validating before using the 1068 // value as a path keeps attacker-supplied cookies from escaping the 1069 // sessions dir (e.g. via "/" or ".." bytes). 1070 fn isToken(token_hex: []const u8) bool { 1071 if (token_hex.len != token_hex_len) return false; 1072 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1073 return true; 1074 } 1075 }; 1076