1043 // focusable kind
1044 const CellTag = union(enum) {
1045 span, // clickable focusable cell
1046 a: []const u8, // clickable focusable link
1047 plain, // non-focusable, colored
1048
1049 const a_prefix = "a:";
1050 // an "in-page" anchor: rendered as a real <a href> so it works with js
1051 // disabled, but crossPageLink ignores it, so with wasm the click just
1052 // moves focus rather than navigating.
1053 const inpage_prefix = "ai:";
1054
1055 fn init(str: []const u8) @This() {
1056 if (std.mem.startsWith(u8, str, inpage_prefix)) {
1057 return .{ .a = str[inpage_prefix.len..] };
1058 }
1059 if (std.mem.startsWith(u8, str, a_prefix)) {
1060 return .{ .a = str[a_prefix.len..] };
1061 }
1062 return .span;
1063 }
1064
1065 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void {
1066 var id_buf: [32]u8 = undefined;
1067 switch (self) {
1068 .span => {
1069 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\"");
1070 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id}));
1071 try out.appendSlice(alloc, "\"");
1072 try out.appendSlice(alloc, style_attr);
1073 try out.appendSlice(alloc, ">");
1074 },
1075 .a => |href| {
1076 // tabindex=-1 keeps these out of the browser's tab order
1077 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\"");
1078 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id}));
1079 try out.appendSlice(alloc, "\" href=\"");
1080 try appendEscapedHtml(alloc, out, href);
1081 try out.appendSlice(alloc, "\"");
1082 try out.appendSlice(alloc, style_attr);
1083 try out.appendSlice(alloc, ">");
1084 },
1085 .plain => {
1086 try out.appendSlice(alloc, "<span");
1087 try out.appendSlice(alloc, style_attr);
1088 try out.appendSlice(alloc, ">");
1089 },
1090 }
1091 }
1092
1093 fn closeTag(self: @This()) []const u8 {
1094 return switch (self) {
1095 .span, .plain => "</span>",
1096 .a => "</a>",
1097 };
1098 }
1099 };
1100
1101 // emit this panel's grid as rows of text, coalescing adjacent cells that
1102 // share a focus id and colors into one tag (a clickable span, a link, or a
1103 // plain colored span). cells under a child scroll keep only their background.
1104 for (0..grid.size.height) |y| {
1105 var cur_id: ?usize = null;
1106 var cur_fg: ?Grid.Color = null;
1107 var cur_bg: ?Grid.Color = null;
1108 var open_tag: ?CellTag = null;
1109 var first = true;
1110 for (0..grid.size.width) |x| {
1111 const cell = grid.cells.items[try grid.cells.at(.{ y, x })];
1112 // a cell covered by a child scroll's viewport is drawn by that scroll's
1113 // own div, so blank its glyph and make it non-clickable here — but keep
1114 // its background, so the backdrop still shows through the scroll's
1115 // transparent div instead of a bare hole.
1116 const covered_by_scroll = blk: {
1117 for (direct.items) |id| {
1118 const r = (focus.children.get(id) orelse continue).rect;
1119 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;
1120 }
1121 break :blk false;
1122 };
1123 // the focusable cell at (x, y) among this panel's own focusables (skipping
1124 // any that belong to a child scroll, whose cells are drawn in their own
1125 // panel); none for a covered cell.
1126 const cell_id = if (covered_by_scroll) null else blk: {
1127 var iter = focus.children.iterator();
1128 while (iter.next()) |entry| {
1129 const child = entry.value_ptr.*;
1130 if (!child.focus.focusable) continue;
1131 if (excluded.contains(entry.key_ptr.*)) continue;
1132 const r = child.rect;
1133 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) {
1134 break :blk entry.key_ptr.*;
1135 }
1136 }
1137 break :blk null;
1138 };
1139 const fg = if (covered_by_scroll) null else cell.style.fg;
1140 const bg = cell.style.bg;
1141
1142 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) {
1143 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag());
1144
1145 var new_tag: ?CellTag = null;
1146 if (cell_id) |id| {
1147 if (focus.children.get(id)) |child| {
1148 new_tag = switch (child.focus.kind) {
1149 .custom => |custom| CellTag.init(custom),
1150 else => .span,
1151 };
1152 }
1153 }
1154 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain;
1155
1156 if (new_tag) |t| {
1157 var style_buf: [64]u8 = undefined;
1158 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg));
1159 }
1160
1161 open_tag = new_tag;
1162 cur_id = cell_id;
1163 cur_fg = fg;
1164 cur_bg = bg;
1165 first = false;
1166 }
1167
1168 if (covered_by_scroll) {
1169 try appendEscapedHtml(allocator, output, " ");
1170 } else if (cell.continuation) {
1171 // the wide rune to the left was emitted 2ch wide, covering this column
1172 } else if (cell.rune) |rune| {
1173 // a double-width rune is pinned inside a 2ch span so the
1174 // fallback glyph's advance width can't shift the rest of the row
1175 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation;
1176 if (wide) {
1177 try output.appendSlice(allocator, "<span class=\"w2\">");
1178 try appendEscapedHtml(allocator, output, rune);
1179 try output.appendSlice(allocator, "</span>");
1180 } else {
1181 try appendEscapedHtml(allocator, output, rune);
1182 }
1183 } else {
1184 try appendEscapedHtml(allocator, output, " ");
1185 }
1186 }
1187 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag());
1188 try output.append(allocator, '\n');
1189 }
1190
1191 // each child scroll becomes a natively-scrollable div positioned over its
1192 // viewport, holding its full content rendered recursively.
1193 for (direct.items) |id| {
1194 const child = focus.children.get(id) orelse continue;
1195 const info = child.focus.scroll orelse continue;
1196 const r = child.rect;
1197 // overflow only on the axes the widget scrolls; `auto` shows a bar only
1198 // when that axis actually overflows. the other axis is clipped (hidden),
1199 // matching how the terminal Scroll handles its non-scrolling axis.
1200 const overflow = switch (info.direction) {
1201 .vert => "overflow-x:hidden;overflow-y:auto",
1202 .horiz => "overflow-x:auto;overflow-y:hidden",
1203 .both => "overflow:auto",
1204 };
1205 // the id carries a content version so JS preserves the native scroll
1206 // position across re-renders of the same content but resets it when the
1207 // content is replaced — e.g. selecting a different commit. the widget's
1208 // scroll offset (in cells) rides along so JS can apply it when it has no
1209 // preserved position, letting a wasm-side scrollToRect (the files list
1210 // scrolling to its selected row on page load) reach the browser.
1211 var buf: [224]u8 = undefined;
1212 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 }));
1213 try renderPanel(allocator, output, child.focus, info.content);
1214 try output.appendSlice(allocator, "</div>");
1215 }
1216 }
1217
1218 // emits the form overlay — one <form> per "form:<url>" focus subtree in the
1219 // widget tree, each wrapping the text inputs and submit button inside it,
1220 // positioned absolutely over the matching grid cells.
1221 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 {
1222 const root_focus = root.getFocus();
1223
1224 var out: std.ArrayList(u8) = .empty;
1225 errdefer out.deinit(allocator);
1226
1227 const form_prefix = "form:";
1228
1229 // Focus.children is an AutoArrayHashMap that preserves insertion order,
1230 // which matches the order widgets were added in code
1231 var iter = root_focus.children.iterator();
1232 while (iter.next()) |entry| {
1233 const child = entry.value_ptr.*;
1234 const action_url = switch (child.focus.kind) {
1235 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix))
1236 custom[form_prefix.len..]
1237 else
1238 continue,
1239 else => continue,
1240 };
1241
1242 try out.appendSlice(allocator, "<form action=\"");
1243 try appendEscapedHtml(allocator, &out, action_url);
1244 try out.appendSlice(allocator, "\" method=\"post\"");
1245 // an empty action must not POST — block it and send the input to the TUI instead
1246 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\"");
1247 try out.appendSlice(allocator, ">");
1248
1249 // form.focus.children was populated by addChild, which flattens the
1250 // whole subtree into one map — so descendants (inputs + the submit
1251 // button) all appear here. positions on form.focus are relative to
1252 // the form, so we look up absolute rects via root_focus for layout.
1253 var inner_iter = child.focus.children.iterator();
1254 while (inner_iter.next()) |inner_entry| {
1255 const inner_id = inner_entry.key_ptr.*;
1256 const root_child = root_focus.children.get(inner_id) orelse continue;
1257 const r = root_child.rect;
1258 switch (root_child.focus.kind) {
1259 .text_input, .text_input_password => {
1260 const ti = session.text_inputs.get(inner_id) orelse continue;
1261 const inner_left = r.x + 1;
1262 const inner_top = r.y + 1;
1263 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0;
1264
1265 try out.appendSlice(allocator, "<input type=\"");
1266 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text");
1267 try out.appendSlice(allocator, "\" data-focus-id=\"");
1268 var id_buf: [32]u8 = undefined;
1269 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id}));
1270 if (ti.options.name.len > 0) {
1271 try out.appendSlice(allocator, "\" name=\"");
1272 try appendEscapedHtml(allocator, &out, ti.options.name);
1273 }
1274 // never the live content as the `value`: the browser tracks user
1275 // input natively, and including the wasm-side value here would make
1276 // the overlay HTML differ on every keystroke — that would trip the
1277 // diff in _setOverlay and rebuild the <input>, eating the user's
1278 // caret. a page-constant initial value is safe.
1279 if (session.input_values.get(inner_id)) |value| {
1280 try out.appendSlice(allocator, "\" value=\"");
1281 try appendEscapedHtml(allocator, &out, value);
1282 }
1283 try out.appendSlice(allocator, "\" style=\"left:");
1284 var pos_buf: [64]u8 = undefined;
1285 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 }));
1286 try out.appendSlice(allocator, "\">");
1287 },
1288 .text_area => {
1289 const ti = session.text_inputs.get(inner_id) orelse continue;
1290 const inner_left = r.x + 1;
1291 const inner_top = r.y + 1;
1292 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0;
1293 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0;
1294
1295 try out.appendSlice(allocator, "<textarea data-focus-id=\"");
1296 var id_buf: [32]u8 = undefined;
1297 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id}));
1298 if (ti.options.name.len > 0) {
1299 try out.appendSlice(allocator, "\" name=\"");
1300 try appendEscapedHtml(allocator, &out, ti.options.name);
1301 }
1302 // like the input above, only a page-constant initial value
1303 // inside: the browser tracks the live value and the
1304 // overlay diff must stay stable across keystrokes
1305 try out.appendSlice(allocator, "\" style=\"left:");
1306 var pos_buf: [128]u8 = undefined;
1307 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 }));
1308 // textarea discards the first newline immediately following
1309 // its start tag, so add one of our own so text that begins
1310 // with a newline doesn't lose it
1311 try out.appendSlice(allocator, "\">\n");
1312 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value);
1313 try out.appendSlice(allocator, "</textarea>");
1314 },
1315 .custom => |custom| {
1316 if (std.mem.eql(u8, "submit", custom)) {
1317 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\"");
1318 var id_buf: [32]u8 = undefined;
1319 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id}));
1320 try out.appendSlice(allocator, "\" style=\"left:");
1321 var pos_buf: [128]u8 = undefined;
1322 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 }));
1323 try out.appendSlice(allocator, "\"></button>");
1324 }
1325 },
1326 else => {},
1327 }
1328 }
1329
1330 try out.appendSlice(allocator, "</form>");
1331 }
1332
1333 return try out.toOwnedSlice(allocator);
1334 }
1335
1336 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool {
1337 if (a) |av| return if (b) |bv| av.eql(bv) else false;
1338 return b == null;
1339 }
1340
1341 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute
1342 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an
1343 // empty slice when neither is set.
1344 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 {
1345 if (fg == null and bg == null) return buf[0..0];
1346 const prefix = " style=\"";
1347 @memcpy(buf[0..prefix.len], prefix);
1348 var i: usize = prefix.len;
1349 if (fg) |c| {
1350 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];
1351 i += s.len;
1352 }
1353 if (bg) |c| {
1354 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];
1355 i += s.len;
1356 }
1357 buf[i] = '"';
1358 i += 1;
1359 return buf[0..i];
1360 }
1361
1362 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void {
1363 for (input) |ch| {
1364 switch (ch) {
1365 '&' => try out.appendSlice(allocator, "&"),
1366 '<' => try out.appendSlice(allocator, "<"),
1367 '>' => try out.appendSlice(allocator, ">"),
1368 '"' => try out.appendSlice(allocator, """),
1369 '\'' => try out.appendSlice(allocator, "'"),
1370 else => try out.append(allocator, ch),
1371 }
1372 }
1373 }
1374
1375 // --- helpers --------------------------------------------------------------
1376
1377 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 {
1378 var iter = request.iterateHeaders();
1379 while (iter.next()) |header| {
1380 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue;
1381 var pairs = std.mem.splitScalar(u8, header.value, ';');
1382 while (pairs.next()) |pair| {
1383 const trimmed = std.mem.trim(u8, pair, " \t");
1384 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue;
1385 if (std.mem.eql(u8, trimmed[0..eq], name)) {
1386 return trimmed[eq + 1 ..];
1387 }
1388 }
1389 }
1390 return null;
1391 }
1392
1393 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 {
1394 var iter = std.mem.splitScalar(u8, body, '&');
1395 while (iter.next()) |pair| {
1396 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
1397 if (std.mem.eql(u8, pair[0..eq], key)) {
1398 return try decodeFormValue(allocator, pair[eq + 1 ..]);
1399 }
1400 }
1401 return null;
1402 }
1403
1404 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 {
1405 var out: std.ArrayList(u8) = .empty;
1406 errdefer out.deinit(allocator);
1407 var i: usize = 0;
1408 while (i < encoded.len) : (i += 1) {
1409 switch (encoded[i]) {
1410 '+' => try out.append(allocator, ' '),
1411 '%' => {
1412 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding;
1413 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding;
1414 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding;
1415 try out.append(allocator, hi * 16 + lo);
1416 i += 2;
1417 },
1418 else => try out.append(allocator, encoded[i]),
1419 }
1420 }
1421 return try out.toOwnedSlice(allocator);
1422 }
1423
1424 // disk-backed web session store. each login mints a random, opaque token
1425 // (not the user's id) that is stored as a file named by the token hex, whose
1426 // contents are the raw user_id bytes. authenticating a request is a lookup of
1427 // the cookie's token; logout deletes the file, revoking the session. there is
1428 // deliberately no expiry — a session lives until logout.
1429 pub const SessionStore = struct {
1430 io: std.Io,
1431 dir: std.Io.Dir,
1432
1433 pub const token_hex_len = evt.event_id_size * 2;
1434
1435 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore {
1436 try data_dir.createDirPath(io, "sessions");
1437 const dir = try data_dir.openDir(io, "sessions", .{});
1438 return .{ .io = io, .dir = dir };
1439 }
1440
1441 pub fn deinit(self: SessionStore) void {
1442 self.dir.close(self.io);
1443 }
1444
1445 // mint a new session for user_id, returning the token hex to set as the
1446 // cookie value.
1447 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 {
1448 var token: [evt.event_id_size]u8 = undefined;
1449 self.io.random(&token);
1450 const token_hex = std.fmt.bytesToHex(token, .lower);
1451 const file = try self.dir.createFile(self.io, &token_hex, .{});
1452 defer file.close(self.io);
1453 try file.writeStreamingAll(self.io, user_id);
1454 return token_hex;
1455 }
1456
1457 // resolve a cookie's token to its user_id. returns false (logged out) for a
1458 // missing, malformed, or unknown token.
1459 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool {
1460 if (!isToken(token_hex)) return false;
1461 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false;
1462 defer file.close(self.io);
1463 var storage: [evt.event_id_size]u8 = undefined;
1464 var file_reader = file.reader(self.io, &storage);
1465 file_reader.interface.readSliceAll(out) catch return false;
1466 return true;
1467 }
1468
1469 // revoke a session. a no-op for a missing or malformed token.
1470 pub fn remove(self: SessionStore, token_hex: []const u8) void {
1471 if (!isToken(token_hex)) return;
1472 self.dir.deleteFile(self.io, token_hex) catch {};
1473 }
1474
1475 // leave `token_hex`'s session for the next visitor arriving without one.
1476 // only the `try` fixture writes one, and only a debug build honors it. the
1477 // name isn't token-shaped, so it can't collide with a session file.
1478 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void {
1479 const file = try self.dir.createFile(self.io, auto_login_name, .{});
1480 defer file.close(self.io);
1481 try file.writeStreamingAll(self.io, token_hex);
1482 }
1483
1484 // claim the offered session, if one is there. the delete picks the winner
1485 // of a race, so the offer is only ever taken once. a release build never
1486 // looks, because that would be an extra syscall for every GET request.
1487 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool {
1488 if (builtin.mode != .Debug) return false;
1489 {
1490 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false;
1491 defer file.close(self.io);
1492 var storage: [token_hex_len]u8 = undefined;
1493 var file_reader = file.reader(self.io, &storage);
1494 file_reader.interface.readSliceAll(out) catch return false;
1495 }
1496 self.dir.deleteFile(self.io, auto_login_name) catch return false;
1497 return true;
1498 }
1499
1500 const auto_login_name = "auto-login";
1501
1502 // a token is exactly token_hex_len hex chars. validating before using the
1503 // value as a path keeps attacker-supplied cookies from escaping the
1504 // sessions dir (e.g. via "/" or ".." bytes).
1505 fn isToken(token_hex: []const u8) bool {
1506 if (token_hex.len != token_hex_len) return false;
1507 for (token_hex) |c| if (!std.ascii.isHex(c)) return false;
1508 return true;
1509 }
1510 };
1511