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