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