╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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