╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
935 try appendEscapedHtml(allocator, output, rune); 936 try output.appendSlice(allocator, "</span>"); 937 } else { 938 try appendEscapedHtml(allocator, output, rune); 939 } 940 } else { 941 try appendEscapedHtml(allocator, output, " "); 942 } 943 } 944 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 945 try output.append(allocator, '\n'); 946 } 947 948 // each child scroll becomes a natively-scrollable div positioned over its 949 // viewport, holding its full content rendered recursively. 950 for (direct.items) |id| { 951 const child = focus.children.get(id) orelse continue; 952 const info = child.focus.scroll orelse continue; 953 const r = child.rect; 954 // overflow only on the axes the widget scrolls; `auto` shows a bar only 955 // when that axis actually overflows. the other axis is clipped (hidden), 956 // matching how the terminal Scroll handles its non-scrolling axis. 957 const overflow = switch (info.direction) { 958 .vert => "overflow-x:hidden;overflow-y:auto", 959 .horiz => "overflow-x:auto;overflow-y:hidden", 960 .both => "overflow:auto", 961 }; 962 // the id carries a content version so JS preserves the native scroll 963 // position across re-renders of the same content but resets it when the 964 // content is replaced — e.g. selecting a different commit. the widget's 965 // scroll offset (in cells) rides along so JS can apply it when it has no 966 // preserved position, letting a wasm-side scrollToRect (the files list 967 // scrolling to its selected row on page load) reach the browser. 968 var buf: [224]u8 = undefined; 969 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 })); 970 try renderPanel(allocator, output, child.focus, info.content); 971 try output.appendSlice(allocator, "</div>"); 972 } 973 } 974 975 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 976 // widget tree, each wrapping the text inputs and submit button inside it, 977 // positioned absolutely over the matching grid cells. 978 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 979 const root_focus = root.getFocus(); 980 981 var out: std.ArrayList(u8) = .empty; 982 errdefer out.deinit(allocator); 983 984 const form_prefix = "form:"; 985 986 // Focus.children is an AutoArrayHashMap that preserves insertion order, 987 // which matches the order widgets were added in code 988 var iter = root_focus.children.iterator(); 989 while (iter.next()) |entry| { 990 const child = entry.value_ptr.*; 991 const action_url = switch (child.focus.kind) { 992 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 993 custom[form_prefix.len..] 994 else 995 continue, 996 else => continue, 997 }; 998 999 try out.appendSlice(allocator, "<form action=\""); 1000 try appendEscapedHtml(allocator, &out, action_url); 1001 try out.appendSlice(allocator, "\" method=\"post\""); 1002 // an empty action must not POST — block it and send the input to the TUI instead 1003 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1004 try out.appendSlice(allocator, ">"); 1005 1006 // form.focus.children was populated by addChild, which flattens the 1007 // whole subtree into one map — so descendants (inputs + the submit 1008 // button) all appear here. positions on form.focus are relative to 1009 // the form, so we look up absolute rects via root_focus for layout. 1010 var inner_iter = child.focus.children.iterator(); 1011 while (inner_iter.next()) |inner_entry| { 1012 const inner_id = inner_entry.key_ptr.*; 1013 const root_child = root_focus.children.get(inner_id) orelse continue; 1014 const r = root_child.rect; 1015 switch (root_child.focus.kind) { 1016 .text_input, .text_input_password => { 1017 const ti = session.text_inputs.get(inner_id) orelse continue; 1018 const inner_left = r.x + 1; 1019 const inner_top = r.y + 1; 1020 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1021 1022 try out.appendSlice(allocator, "<input type=\""); 1023 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1024 try out.appendSlice(allocator, "\" data-focus-id=\""); 1025 var id_buf: [32]u8 = undefined; 1026 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1027 if (ti.options.name.len > 0) { 1028 try out.appendSlice(allocator, "\" name=\""); 1029 try appendEscapedHtml(allocator, &out, ti.options.name); 1030 } 1031 // never the live content as the `value`: the browser tracks user 1032 // input natively, and including the wasm-side value here would make 1033 // the overlay HTML differ on every keystroke — that would trip the 1034 // diff in _setOverlay and rebuild the <input>, eating the user's 1035 // caret. a page-constant initial value is safe. 1036 if (session.input_values.get(inner_id)) |value| { 1037 try out.appendSlice(allocator, "\" value=\""); 1038 try appendEscapedHtml(allocator, &out, value); 1039 } 1040 try out.appendSlice(allocator, "\" style=\"left:"); 1041 var pos_buf: [64]u8 = undefined; 1042 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 })); 1043 try out.appendSlice(allocator, "\">"); 1044 }, 1045 .text_area => { 1046 const ti = session.text_inputs.get(inner_id) orelse continue; 1047 const inner_left = r.x + 1; 1048 const inner_top = r.y + 1; 1049 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1050 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1051 1052 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1053 var id_buf: [32]u8 = undefined; 1054 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1055 if (ti.options.name.len > 0) { 1056 try out.appendSlice(allocator, "\" name=\""); 1057 try appendEscapedHtml(allocator, &out, ti.options.name); 1058 } 1059 // like the input above, only a page-constant initial value 1060 // inside: the browser tracks the live value and the 1061 // overlay diff must stay stable across keystrokes 1062 try out.appendSlice(allocator, "\" style=\"left:"); 1063 var pos_buf: [128]u8 = undefined; 1064 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 })); 1065 try out.appendSlice(allocator, "\">"); 1066 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1067 try out.appendSlice(allocator, "</textarea>"); 1068 }, 1069 .custom => |custom| { 1070 if (std.mem.eql(u8, "submit", custom)) { 1071 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1072 var id_buf: [32]u8 = undefined; 1073 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1074 try out.appendSlice(allocator, "\" style=\"left:"); 1075 var pos_buf: [128]u8 = undefined; 1076 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 })); 1077 try out.appendSlice(allocator, "\"></button>"); 1078 } 1079 }, 1080 else => {}, 1081 } 1082 } 1083 1084 try out.appendSlice(allocator, "</form>"); 1085 } 1086 1087 return try out.toOwnedSlice(allocator); 1088 } 1089 1090 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1091 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1092 return b == null; 1093 } 1094 1095 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1096 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1097 // empty slice when neither is set. 1098 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1099 if (fg == null and bg == null) return buf[0..0]; 1100 const prefix = " style=\""; 1101 @memcpy(buf[0..prefix.len], prefix); 1102 var i: usize = prefix.len; 1103 if (fg) |c| { 1104 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]; 1105 i += s.len; 1106 } 1107 if (bg) |c| { 1108 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]; 1109 i += s.len; 1110 } 1111 buf[i] = '"'; 1112 i += 1; 1113 return buf[0..i]; 1114 } 1115 1116 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1117 for (input) |ch| { 1118 switch (ch) { 1119 '&' => try out.appendSlice(allocator, "&amp;"), 1120 '<' => try out.appendSlice(allocator, "&lt;"), 1121 '>' => try out.appendSlice(allocator, "&gt;"), 1122 '"' => try out.appendSlice(allocator, "&quot;"), 1123 '\'' => try out.appendSlice(allocator, "&#39;"), 1124 else => try out.append(allocator, ch), 1125 } 1126 } 1127 } 1128 1129 // --- helpers -------------------------------------------------------------- 1130 1131 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1132 var iter = request.iterateHeaders(); 1133 while (iter.next()) |header| { 1134 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1135 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1136 while (pairs.next()) |pair| { 1137 const trimmed = std.mem.trim(u8, pair, " \t"); 1138 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1139 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1140 return trimmed[eq + 1 ..]; 1141 } 1142 } 1143 } 1144 return null; 1145 } 1146 1147 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1148 var iter = std.mem.splitScalar(u8, body, '&'); 1149 while (iter.next()) |pair| { 1150 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1151 if (std.mem.eql(u8, pair[0..eq], key)) { 1152 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1153 } 1154 } 1155 return null; 1156 } 1157 1158 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1159 var out: std.ArrayList(u8) = .empty; 1160 errdefer out.deinit(allocator); 1161 var i: usize = 0; 1162 while (i < encoded.len) : (i += 1) { 1163 switch (encoded[i]) { 1164 '+' => try out.append(allocator, ' '), 1165 '%' => { 1166 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1167 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1168 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1169 try out.append(allocator, hi * 16 + lo); 1170 i += 2; 1171 }, 1172 else => try out.append(allocator, encoded[i]), 1173 } 1174 } 1175 return try out.toOwnedSlice(allocator); 1176 } 1177 1178 // disk-backed web session store. each login mints a random, opaque token 1179 // (not the user's id) that is stored as a file named by the token hex, whose 1180 // contents are the raw user_id bytes. authenticating a request is a lookup of 1181 // the cookie's token; logout deletes the file, revoking the session. there is 1182 // deliberately no expiry — a session lives until logout. 1183 pub const SessionStore = struct { 1184 io: std.Io, 1185 dir: std.Io.Dir, 1186 1187 pub const token_hex_len = evt.event_id_size * 2; 1188 1189 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1190 try data_dir.createDirPath(io, "sessions"); 1191 const dir = try data_dir.openDir(io, "sessions", .{}); 1192 return .{ .io = io, .dir = dir }; 1193 } 1194 1195 pub fn deinit(self: SessionStore) void { 1196 self.dir.close(self.io); 1197 } 1198 1199 // mint a new session for user_id, returning the token hex to set as the 1200 // cookie value. 1201 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1202 var token: [evt.event_id_size]u8 = undefined; 1203 self.io.random(&token); 1204 const token_hex = std.fmt.bytesToHex(token, .lower); 1205 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1206 defer file.close(self.io); 1207 try file.writeStreamingAll(self.io, user_id); 1208 return token_hex; 1209 } 1210 1211 // resolve a cookie's token to its user_id. returns false (logged out) for a 1212 // missing, malformed, or unknown token. 1213 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1214 if (!isToken(token_hex)) return false; 1215 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1216 defer file.close(self.io); 1217 var storage: [evt.event_id_size]u8 = undefined; 1218 var file_reader = file.reader(self.io, &storage); 1219 file_reader.interface.readSliceAll(out) catch return false; 1220 return true; 1221 } 1222 1223 // revoke a session. a no-op for a missing or malformed token. 1224 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1225 if (!isToken(token_hex)) return; 1226 self.dir.deleteFile(self.io, token_hex) catch {}; 1227 } 1228 1229 // a token is exactly token_hex_len hex chars. validating before using the 1230 // value as a path keeps attacker-supplied cookies from escaping the 1231 // sessions dir (e.g. via "/" or ".." bytes). 1232 fn isToken(token_hex: []const u8) bool { 1233 if (token_hex.len != token_hex_len) return false; 1234 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1235 return true; 1236 } 1237 }; 1238