╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1225 // form posts to "<base>/resolve") 1226 fn handleIssueResolve( 1227 io: std.Io, 1228 request: *std.http.Server.Request, 1229 allocator: std.mem.Allocator, 1230 base: []const u8, 1231 host: Host, 1232 ) !void { 1233 var author_arena = std.heap.ArenaAllocator.init(allocator); 1234 defer author_arena.deinit(); 1235 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1236 1237 var body_buf: [256]u8 = undefined; 1238 const reader = request.readerExpectNone(&body_buf); 1239 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 1240 defer allocator.free(body); 1241 1242 var field_arena = std.heap.ArenaAllocator.init(allocator); 1243 defer field_arena.deinit(); 1244 const aa = field_arena.allocator(); 1245 const title = try parseFormField(aa, body, "title"); 1246 const tags = try parseFormField(aa, body, "tags"); 1247 1248 // the hunk inputs post as d0, d1, ...; form submission normalizes their 1249 // textarea line breaks to CRLF 1250 var hunks: std.ArrayList([]const u8) = .empty; 1251 var hunk_index: usize = 0; 1252 while (true) : (hunk_index += 1) { 1253 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1254 const posted = (try parseFormField(aa, body, name)) orelse break; 1255 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 1256 } 1257 1258 const not_found = "issue not found"; 1259 const parts = issueBaseParts(base) orelse { 1260 try request.respond(not_found, .{ 1261 .status = .not_found, 1262 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1263 }); 1264 return; 1265 }; 1266 1267 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 1268 .title = title, 1269 .tags = tags, 1270 .hunks = hunks.items, 1271 } }, author) catch |err| switch (err) { 1272 error.NotFound => { 1273 try request.respond(not_found, .{ 1274 .status = .not_found, 1275 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1276 }); 1277 return; 1278 }, 1279 // invalid fields send the user back to the resolve form 1280 error.InvalidFields => { 1281 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1282 defer allocator.free(form_location); 1283 try request.respond("", .{ 1284 .status = .see_other, 1285 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1286 }); 1287 return; 1288 }, 1289 else => |e| return e, 1290 }; 1291 1292 try request.respond("", .{ 1293 .status = .see_other, 1294 .extra_headers = &.{.{ .name = "location", .value = base }}, 1295 }); 1296 } 1297 1298 fn handleSync( 1299 io: std.Io, 1300 request: *std.http.Server.Request, 1301 allocator: std.mem.Allocator, 1302 base: []const u8, 1303 source: ui.RepoSource, 1304 ) !void { 1305 if (base.len != 0) { 1306 try request.respond("not found", .{ 1307 .status = .not_found, 1308 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1309 }); 1310 return; 1311 } 1312 1313 var owned_failure: ?[]u8 = null; 1314 defer if (owned_failure) |message| allocator.free(message); 1315 const failure: ?[]const u8 = blk: { 1316 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1317 break :blk owned_failure; 1318 }; 1319 if (failure) |message| { 1320 var encoded: std.Io.Writer.Allocating = .init(allocator); 1321 defer encoded.deinit(); 1322 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1323 fn isUnreserved(c: u8) bool { 1324 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1325 } 1326 }.isUnreserved); 1327 const cookie = try std.fmt.allocPrint( 1328 allocator, 1329 sync_failure_cookie ++ "={s}; Path=/; HttpOnly; SameSite=Strict", 1330 .{encoded.written()}, 1331 ); 1332 defer allocator.free(cookie); 1333 try request.respond("", .{ 1334 .status = .see_other, 1335 .extra_headers = &.{ 1336 .{ .name = "location", .value = "/events" }, 1337 .{ .name = "set-cookie", .value = cookie }, 1338 }, 1339 }); 1340 return; 1341 } 1342 1343 try request.respond("", .{ 1344 .status = .see_other, 1345 .extra_headers = &.{ 1346 .{ .name = "location", .value = "/events" }, 1347 .{ .name = "set-cookie", .value = sync_failure_cookie ++ "=; Path=/; Max-Age=0" }, 1348 }, 1349 }); 1350 } 1351 1352 fn renderIndexHtml( 1353 io: std.Io, 1354 allocator: std.mem.Allocator, 1355 host: Host, 1356 session_data: ui.Session.Data, 1357 ) ![]const u8 { 1358 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1359 1360 var page_arena = std.heap.ArenaAllocator.init(allocator); 1361 defer page_arena.deinit(); 1362 1363 // the remote admin repo must outlive the page build, since the session's 1364 // moment reads from it. 1365 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1366 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1367 1368 var session = switch (host) { 1369 .remote => |remote| blk: { 1370 // open the admin repo to read live user/repo data. 1371 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1372 const repo = if (repo_maybe) |*repo| repo else unreachable; 1373 var session = try ui.Session.init(&page_arena, repo, session_data); 1374 // give the page builders filesystem access to the on-disk repos (a 1375 // sibling "repos" dir next to the admin repo) so the Repo page can 1376 // read its files. 1377 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1378 break :blk session; 1379 }, 1380 .local => |local| ui.Session{ 1381 .data = session_data, 1382 .arena = &page_arena, 1383 .page_arena = &page_arena, 1384 .local = local, 1385 }, 1386 }; 1387 session.io = io; 1388 1389 const snapshot: ui.Snapshot = .{ 1390 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 1391 .session = session.data, 1392 }; 1393 var root = try ui.initRoot(allocator, &snapshot.page, &session); 1394 defer root.deinit(allocator); 1395 1396 const content = try generateHtml(allocator, &root); 1397 defer allocator.free(content); 1398 const overlay = try generateOverlay(allocator, &root, &session); 1399 defer allocator.free(overlay); 1400 1401 // serialize the snapshot so the wasm side can parse it back without making 1402 // a second request. it's embedded raw in a <script type="application/json"> 1403 // block, whose content is raw text terminated only by "</script". in json, 1404 // '<' appears solely inside string values, so escaping every '<' (and '>' 1405 // for good measure) to its \uXXXX form yields equivalent json that can't 1406 // break out of the tag. 1407 var json: std.Io.Writer.Allocating = .init(allocator); 1408 defer json.deinit(); 1409 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1410 1411 var json_escaped: std.ArrayList(u8) = .empty; 1412 defer json_escaped.deinit(allocator); 1413 for (json.written()) |c| switch (c) { 1414 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1415 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1416 else => try json_escaped.append(allocator, c), 1417 }; 1418 1419 var out: std.ArrayList(u8) = .empty; 1420 errdefer out.deinit(allocator); 1421 { 1422 var cursor: usize = 0; 1423 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1424 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1425 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1426 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1427 }) |sub| { 1428 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1429 try out.appendSlice(allocator, template[cursor..idx]); 1430 try out.appendSlice(allocator, sub.replacement); 1431 cursor = idx + sub.needle.len; 1432 } 1433 try out.appendSlice(allocator, template[cursor..]); 1434 } 1435 return try out.toOwnedSlice(allocator); 1436 } 1437 1438 fn findEmbed(request_path: []const u8) ?Embed { 1439 const path = if (std.mem.eql(u8, request_path, "/")) 1440 "index.html" 1441 else if (request_path.len > 1 and request_path[0] == '/') 1442 request_path[1..] 1443 else 1444 return null; 1445 1446 for (embeds) |embed| { 1447 if (std.mem.eql(u8, path, embed.path)) return embed; 1448 } 1449 return null; 1450 } 1451 1452 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1453 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1454 // rendered recursively so nested scrolls work. 1455 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1456 const grid = root.getGrid() orelse return error.MissingGrid; 1457 1458 var out: std.ArrayList(u8) = .empty; 1459 errdefer out.deinit(allocator); 1460 1461 try renderPanel(allocator, &out, root.getFocus(), grid); 1462 return try out.toOwnedSlice(allocator); 1463 } 1464 1465 // render one panel — a focus subtree and its content grid — as HTML, recursing 1466 // once per web-native Scroll inside it. the root panel is the whole page; each 1467 // Scroll becomes a nested, natively-scrollable div holding its full content. 1468 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1469 // then the child scroll divs over those holes. 1470 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1471 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1472 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1473 // plus their descendants, which the focus tree flattens into this panel's 1474 // children): the cell hit-test below skips them so this panel doesn't claim 1475 // cells that are really rendered inside a child scroll's own panel. 1476 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1477 var direct: std.ArrayList(usize) = .empty; 1478 defer direct.deinit(allocator); 1479 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1480 defer excluded.deinit(allocator); 1481 { 1482 var it = focus.children.iterator(); 1483 while (it.next()) |e| { 1484 if (e.value_ptr.focus.scroll == null) continue; 1485 try direct.append(allocator, e.key_ptr.*); 1486 try excluded.put(allocator, e.key_ptr.*, {}); 1487 var mit = e.value_ptr.focus.children.iterator(); 1488 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1489 } 1490 } 1491 1492 // the HTML element a run of cells is wrapped in, chosen from the cell's 1493 // focusable kind 1494 const CellTag = union(enum) { 1495 span, // clickable focusable cell 1496 a: []const u8, // clickable focusable link 1497 plain, // non-focusable, colored 1498 1499 const a_prefix = "a:"; 1500 // an "in-page" anchor: rendered as a real <a href> so it works with js 1501 // disabled, but crossPageLink ignores it, so with wasm the click just 1502 // moves focus rather than navigating. 1503 const inpage_prefix = "ai:"; 1504 1505 fn init(str: []const u8) @This() { 1506 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1507 return .{ .a = str[ui.raw_link_prefix.len..] }; 1508 } 1509 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1510 return .{ .a = str[inpage_prefix.len..] }; 1511 } 1512 if (std.mem.startsWith(u8, str, a_prefix)) { 1513 return .{ .a = str[a_prefix.len..] }; 1514 } 1515 return .span; 1516 } 1517 1518 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1519 var id_buf: [32]u8 = undefined; 1520 switch (self) { 1521 .span => { 1522 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1523 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1524 try out.appendSlice(alloc, "\""); 1525 try out.appendSlice(alloc, style_attr); 1526 try out.appendSlice(alloc, ">"); 1527 }, 1528 .a => |href| { 1529 // tabindex=-1 keeps these out of the browser's tab order 1530 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1531 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1532 try out.appendSlice(alloc, "\" href=\""); 1533 try appendEscapedHtml(alloc, out, href); 1534 try out.appendSlice(alloc, "\""); 1535 try out.appendSlice(alloc, style_attr); 1536 try out.appendSlice(alloc, ">"); 1537 }, 1538 .plain => { 1539 try out.appendSlice(alloc, "<span"); 1540 try out.appendSlice(alloc, style_attr); 1541 try out.appendSlice(alloc, ">"); 1542 }, 1543 } 1544 } 1545 1546 fn closeTag(self: @This()) []const u8 { 1547 return switch (self) { 1548 .span, .plain => "</span>", 1549 .a => "</a>", 1550 }; 1551 } 1552 }; 1553 1554 // emit this panel's grid as rows of text, coalescing adjacent cells that 1555 // share a focus id and colors into one tag (a clickable span, a link, or a 1556 // plain colored span). cells under a child scroll keep only their background. 1557 for (0..grid.size.height) |y| { 1558 var cur_id: ?usize = null; 1559 var cur_fg: ?Grid.Color = null; 1560 var cur_bg: ?Grid.Color = null; 1561 var open_tag: ?CellTag = null; 1562 var first = true; 1563 for (0..grid.size.width) |x| { 1564 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1565 // a cell covered by a child scroll's viewport is drawn by that scroll's 1566 // own div, so blank its glyph and make it non-clickable here — but keep 1567 // its background, so the backdrop still shows through the scroll's 1568 // transparent div instead of a bare hole. 1569 const covered_by_scroll = blk: { 1570 for (direct.items) |id| { 1571 const r = (focus.children.get(id) orelse continue).rect; 1572 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; 1573 } 1574 break :blk false; 1575 }; 1576 // the focusable cell at (x, y) among this panel's own focusables (skipping 1577 // any that belong to a child scroll, whose cells are drawn in their own 1578 // panel); none for a covered cell. 1579 const cell_id = if (covered_by_scroll) null else blk: { 1580 var iter = focus.children.iterator(); 1581 while (iter.next()) |entry| { 1582 const child = entry.value_ptr.*; 1583 if (!child.focus.focusable) continue; 1584 if (excluded.contains(entry.key_ptr.*)) continue; 1585 const r = child.rect; 1586 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1587 break :blk entry.key_ptr.*; 1588 } 1589 } 1590 break :blk null; 1591 }; 1592 const fg = if (covered_by_scroll) null else cell.style.fg; 1593 const bg = cell.style.bg; 1594 1595 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1596 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1597 1598 var new_tag: ?CellTag = null; 1599 if (cell_id) |id| { 1600 if (focus.children.get(id)) |child| { 1601 new_tag = switch (child.focus.kind) { 1602 .custom => |custom| CellTag.init(custom), 1603 else => .span, 1604 }; 1605 } 1606 } 1607 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1608 1609 if (new_tag) |t| { 1610 var style_buf: [64]u8 = undefined; 1611 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1612 } 1613 1614 open_tag = new_tag; 1615 cur_id = cell_id; 1616 cur_fg = fg; 1617 cur_bg = bg; 1618 first = false; 1619 } 1620 1621 if (covered_by_scroll) { 1622 try appendEscapedHtml(allocator, output, " "); 1623 } else if (cell.continuation) { 1624 // the wide rune to the left was emitted 2ch wide, covering this column 1625 } else if (cell.rune) |rune| { 1626 // a double-width rune is pinned inside a 2ch span so the 1627 // fallback glyph's advance width can't shift the rest of the row 1628 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1629 if (wide) { 1630 try output.appendSlice(allocator, "<span class=\"w2\">"); 1631 try appendEscapedHtml(allocator, output, rune); 1632 try output.appendSlice(allocator, "</span>"); 1633 } else { 1634 try appendEscapedHtml(allocator, output, rune); 1635 } 1636 } else { 1637 try appendEscapedHtml(allocator, output, " "); 1638 } 1639 } 1640 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1641 try output.append(allocator, '\n'); 1642 } 1643 1644 // each child scroll becomes a natively-scrollable div positioned over its 1645 // viewport, holding its full content rendered recursively. 1646 for (direct.items) |id| { 1647 const child = focus.children.get(id) orelse continue; 1648 const info = child.focus.scroll orelse continue; 1649 const r = child.rect; 1650 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1651 // when that axis actually overflows. the other axis is clipped (hidden), 1652 // matching how the terminal Scroll handles its non-scrolling axis. 1653 const overflow = switch (info.direction) { 1654 .vert => "overflow-x:hidden;overflow-y:auto", 1655 .horiz => "overflow-x:auto;overflow-y:hidden", 1656 .both => "overflow:auto", 1657 }; 1658 // the id carries a content version so JS preserves the native scroll 1659 // position across re-renders of the same content but resets it when the 1660 // content is replaced — e.g. selecting a different commit. the widget's 1661 // scroll offset (in cells) rides along so JS can apply it when it has no 1662 // preserved position, letting a wasm-side scrollToRect (the files list 1663 // scrolling to its selected row on page load) reach the browser. 1664 var buf: [224]u8 = undefined; 1665 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 })); 1666 try renderPanel(allocator, output, child.focus, info.content); 1667 try output.appendSlice(allocator, "</div>"); 1668 } 1669 } 1670 1671 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1672 // widget tree, each wrapping the text inputs and submit button inside it, 1673 // positioned absolutely over the matching grid cells. 1674 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1675 const root_focus = root.getFocus(); 1676 1677 var out: std.ArrayList(u8) = .empty; 1678 errdefer out.deinit(allocator); 1679 1680 const form_prefix = "form:"; 1681 1682 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1683 // which matches the order widgets were added in code 1684 var iter = root_focus.children.iterator(); 1685 while (iter.next()) |entry| { 1686 const child = entry.value_ptr.*; 1687 const action_url = switch (child.focus.kind) { 1688 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1689 custom[form_prefix.len..] 1690 else 1691 continue, 1692 else => continue, 1693 }; 1694 1695 try out.appendSlice(allocator, "<form action=\""); 1696 try appendEscapedHtml(allocator, &out, action_url); 1697 try out.appendSlice(allocator, "\" method=\"post\""); 1698 // an empty action must not POST — block it and send the input to the TUI instead 1699 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1700 try out.appendSlice(allocator, ">"); 1701 1702 // form.focus.children was populated by addChild, which flattens the 1703 // whole subtree into one map — so descendants (inputs + the submit 1704 // button) all appear here. positions on form.focus are relative to 1705 // the form, so we look up absolute rects via root_focus for layout. 1706 var inner_iter = child.focus.children.iterator(); 1707 while (inner_iter.next()) |inner_entry| { 1708 const inner_id = inner_entry.key_ptr.*; 1709 const root_child = root_focus.children.get(inner_id) orelse continue; 1710 const r = root_child.rect; 1711 switch (root_child.focus.kind) { 1712 .text_input, .text_input_password => { 1713 const ti = session.text_inputs.get(inner_id) orelse continue; 1714 const inner_left = r.x + 1; 1715 const inner_top = r.y + 1; 1716 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1717 1718 try out.appendSlice(allocator, "<input type=\""); 1719 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1720 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1721 var id_buf: [32]u8 = undefined; 1722 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1723 if (ti.options.name.len > 0) { 1724 try out.appendSlice(allocator, "\" name=\""); 1725 try appendEscapedHtml(allocator, &out, ti.options.name); 1726 } 1727 // never the live content as the `value`: the browser tracks user 1728 // input natively, and including the wasm-side value here would make 1729 // the overlay HTML differ on every keystroke — that would trip the 1730 // diff in _setOverlay and rebuild the <input>, eating the user's 1731 // caret. a page-constant initial value is safe. 1732 if (session.input_values.get(inner_id)) |value| { 1733 try out.appendSlice(allocator, "\" value=\""); 1734 try appendEscapedHtml(allocator, &out, value); 1735 } 1736 try out.appendSlice(allocator, "\" style=\"left:"); 1737 var pos_buf: [64]u8 = undefined; 1738 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 })); 1739 try out.appendSlice(allocator, "\">"); 1740 }, 1741 .text_area => { 1742 const ti = session.text_inputs.get(inner_id) orelse continue; 1743 const inner_left = r.x + 1; 1744 const inner_top = r.y + 1; 1745 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1746 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1747 1748 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1749 var id_buf: [32]u8 = undefined; 1750 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1751 if (ti.options.name.len > 0) { 1752 try out.appendSlice(allocator, "\" name=\""); 1753 try appendEscapedHtml(allocator, &out, ti.options.name); 1754 } 1755 // like the input above, only a page-constant initial value 1756 // inside: the browser tracks the live value and the 1757 // overlay diff must stay stable across keystrokes 1758 try out.appendSlice(allocator, "\" style=\"left:"); 1759 var pos_buf: [128]u8 = undefined; 1760 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 })); 1761 // textarea discards the first newline immediately following 1762 // its start tag, so add one of our own so text that begins 1763 // with a newline doesn't lose it 1764 try out.appendSlice(allocator, "\">\n"); 1765 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1766 try out.appendSlice(allocator, "</textarea>"); 1767 }, 1768 .custom => |custom| { 1769 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1770 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1771 var id_buf: [32]u8 = undefined; 1772 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1773 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1774 try out.appendSlice(allocator, "\" formaction=\""); 1775 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1776 } 1777 try out.appendSlice(allocator, "\" style=\"left:"); 1778 var pos_buf: [128]u8 = undefined; 1779 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 })); 1780 try out.appendSlice(allocator, "\"></button>"); 1781 } 1782 }, 1783 else => {}, 1784 } 1785 } 1786 1787 try out.appendSlice(allocator, "</form>"); 1788 } 1789 1790 // a file picker isn't part of a form: it posts its file straight to the url 1791 // in its marker. it sits transparent over the button the tui drew, so 1792 // clicking that button opens the browser's own dialog. 1793 var file_iter = root_focus.children.iterator(); 1794 while (file_iter.next()) |entry| { 1795 const child = entry.value_ptr.*; 1796 const action_url = switch (child.focus.kind) { 1797 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1798 custom[ui.file_input_prefix.len..] 1799 else 1800 continue, 1801 else => continue, 1802 }; 1803 const r = child.rect; 1804 1805 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1806 try appendEscapedHtml(allocator, &out, action_url); 1807 try out.appendSlice(allocator, "\" data-focus-id=\""); 1808 var id_buf: [32]u8 = undefined; 1809 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1810 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1811 var pos_buf: [128]u8 = undefined; 1812 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 })); 1813 try out.appendSlice(allocator, "\">"); 1814 } 1815 1816 return try out.toOwnedSlice(allocator); 1817 } 1818 1819 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1820 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1821 return b == null; 1822 } 1823 1824 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1825 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1826 // empty slice when neither is set. 1827 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1828 if (fg == null and bg == null) return buf[0..0]; 1829 const prefix = " style=\""; 1830 @memcpy(buf[0..prefix.len], prefix); 1831 var i: usize = prefix.len; 1832 if (fg) |c| { 1833 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]; 1834 i += s.len; 1835 } 1836 if (bg) |c| { 1837 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]; 1838 i += s.len; 1839 } 1840 buf[i] = '"'; 1841 i += 1; 1842 return buf[0..i]; 1843 } 1844 1845 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1846 for (input) |ch| { 1847 switch (ch) { 1848 '&' => try out.appendSlice(allocator, "&amp;"), 1849 '<' => try out.appendSlice(allocator, "&lt;"), 1850 '>' => try out.appendSlice(allocator, "&gt;"), 1851 '"' => try out.appendSlice(allocator, "&quot;"), 1852 '\'' => try out.appendSlice(allocator, "&#39;"), 1853 else => try out.append(allocator, ch), 1854 } 1855 } 1856 } 1857 1858 // --- helpers -------------------------------------------------------------- 1859 1860 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1861 var iter = request.iterateHeaders(); 1862 while (iter.next()) |header| { 1863 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1864 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1865 while (pairs.next()) |pair| { 1866 const trimmed = std.mem.trim(u8, pair, " \t"); 1867 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1868 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1869 return trimmed[eq + 1 ..]; 1870 } 1871 } 1872 } 1873 return null; 1874 } 1875 1876 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1877 var iter = std.mem.splitScalar(u8, body, '&'); 1878 while (iter.next()) |pair| { 1879 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1880 if (std.mem.eql(u8, pair[0..eq], key)) { 1881 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1882 } 1883 } 1884 return null; 1885 } 1886 1887 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1888 var out: std.ArrayList(u8) = .empty; 1889 errdefer out.deinit(allocator); 1890 var i: usize = 0; 1891 while (i < encoded.len) : (i += 1) { 1892 switch (encoded[i]) { 1893 '+' => try out.append(allocator, ' '), 1894 '%' => { 1895 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1896 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1897 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1898 try out.append(allocator, hi * 16 + lo); 1899 i += 2; 1900 }, 1901 else => try out.append(allocator, encoded[i]), 1902 } 1903 } 1904 return try out.toOwnedSlice(allocator); 1905 } 1906 1907 // disk-backed web session store. each login mints a random, opaque token 1908 // (not the user's id) that is stored as a file named by the token hex, whose 1909 // contents are the raw user_id bytes. authenticating a request is a lookup of 1910 // the cookie's token; logout deletes the file, revoking the session. there is 1911 // deliberately no expiry — a session lives until logout. 1912 pub const SessionStore = struct { 1913 io: std.Io, 1914 dir: std.Io.Dir, 1915 1916 pub const token_hex_len = evt.event_id_size * 2; 1917 1918 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1919 try data_dir.createDirPath(io, "sessions"); 1920 const dir = try data_dir.openDir(io, "sessions", .{}); 1921 return .{ .io = io, .dir = dir }; 1922 } 1923 1924 pub fn deinit(self: SessionStore) void { 1925 self.dir.close(self.io); 1926 } 1927 1928 // mint a new session for user_id, returning the token hex to set as the 1929 // cookie value. 1930 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1931 var token: [evt.event_id_size]u8 = undefined; 1932 self.io.random(&token); 1933 const token_hex = std.fmt.bytesToHex(token, .lower); 1934 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1935 defer file.close(self.io); 1936 try file.writeStreamingAll(self.io, user_id); 1937 return token_hex; 1938 } 1939 1940 // resolve a cookie's token to its user_id. returns false (logged out) for a 1941 // missing, malformed, or unknown token. 1942 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1943 if (!isToken(token_hex)) return false; 1944 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1945 defer file.close(self.io); 1946 var storage: [evt.event_id_size]u8 = undefined; 1947 var file_reader = file.reader(self.io, &storage); 1948 file_reader.interface.readSliceAll(out) catch return false; 1949 return true; 1950 } 1951 1952 // revoke a session. a no-op for a missing or malformed token. 1953 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1954 if (!isToken(token_hex)) return; 1955 self.dir.deleteFile(self.io, token_hex) catch {}; 1956 } 1957 1958 // leave `token_hex`'s session for the next visitor arriving without one. 1959 // only the `try` fixture writes one, and only a debug build honors it. the 1960 // name isn't token-shaped, so it can't collide with a session file. 1961 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1962 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1963 defer file.close(self.io); 1964 try file.writeStreamingAll(self.io, token_hex); 1965 } 1966 1967 // claim the offered session, if one is there. the delete picks the winner 1968 // of a race, so the offer is only ever taken once. a release build never 1969 // looks, because that would be an extra syscall for every GET request. 1970 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1971 if (builtin.mode != .Debug) return false; 1972 { 1973 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1974 defer file.close(self.io); 1975 var storage: [token_hex_len]u8 = undefined; 1976 var file_reader = file.reader(self.io, &storage); 1977 file_reader.interface.readSliceAll(out) catch return false; 1978 } 1979 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1980 return true; 1981 } 1982 1983 const auto_login_name = "auto-login"; 1984 1985 // a token is exactly token_hex_len hex chars. validating before using the 1986 // value as a path keeps attacker-supplied cookies from escaping the 1987 // sessions dir (e.g. via "/" or ".." bytes). 1988 fn isToken(token_hex: []const u8) bool { 1989 if (token_hex.len != token_hex_len) return false; 1990 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1991 return true; 1992 } 1993 }; 1994