╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
401 }; 402 defer allocator.free(repo_path); 403 404 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 405 defer repo.deinit(io, allocator); 406 407 var id_bytes: [evt.event_id_size]u8 = undefined; 408 io.random(&id_bytes); 409 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 410 411 try evt.commitAndConsume(.xit, .{}, io, allocator, &repo, evt.events_ref, &[_]evt.EventWithId{.{ 412 .id = event_id_hex, 413 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 414 .event = .{ .issue = .{ 415 .title = title, 416 .description = description, 417 .tags = tags, 418 } }, 419 }}); 420 421 const location = try std.fmt.allocPrint(allocator, "{s}/issues/{s}", .{ base, &event_id_hex }); 422 defer allocator.free(location); 423 try request.respond("", .{ 424 .status = .see_other, 425 .extra_headers = &.{.{ .name = "location", .value = location }}, 426 }); 427 } 428 429 // set the status of the issue the url names (base is 430 // "/repo/<owner>/<name>/issues/<id>") by re-emitting its event, then 431 // redirect back to it 432 fn handleIssueStatus( 433 io: std.Io, 434 request: *std.http.Server.Request, 435 allocator: std.mem.Allocator, 436 base: []const u8, 437 admin_repo_path: []const u8, 438 status: evt.Issue.Status, 439 ) !void { 440 const repo_prefix = "/repo/"; 441 const issues_infix = "/issues/"; 442 const id_len = evt.event_id_size * 2; 443 444 var id_bytes: [evt.event_id_size]u8 = undefined; 445 const repo_base_maybe: ?[]const u8 = blk: { 446 if (base.len < repo_prefix.len + issues_infix.len + id_len) break :blk null; 447 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch break :blk null; 448 const head = base[0 .. base.len - id_len]; 449 if (!std.mem.endsWith(u8, head, issues_infix)) break :blk null; 450 const repo_base = head[0 .. head.len - issues_infix.len]; 451 if (!std.mem.startsWith(u8, repo_base, repo_prefix)) break :blk null; 452 break :blk repo_base; 453 }; 454 455 const not_found = "issue not found"; 456 const repo_base = repo_base_maybe orelse { 457 try request.respond(not_found, .{ 458 .status = .not_found, 459 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 460 }); 461 return; 462 }; 463 464 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(admin_repo_path) orelse ".", "repos" }); 465 defer allocator.free(repos_dir); 466 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, admin_repo_path, repo_base[repo_prefix.len..], false)) { 467 .ok => |p| p, 468 .invalid, .not_found => { 469 try request.respond(not_found, .{ 470 .status = .not_found, 471 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 472 }); 473 return; 474 }, 475 }; 476 defer allocator.free(repo_path); 477 478 const repo_opts: rp.RepoOpts(.xit) = .{}; 479 var repo = try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = repo_path }); 480 defer repo.deinit(io, allocator); 481 482 var arena = std.heap.ArenaAllocator.init(allocator); 483 defer arena.deinit(); 484 485 const issue_maybe: ?evt.Issue = blk: { 486 const DB = rp.Repo(.xit, repo_opts).DB; 487 const moment = evt.currentMoment(repo_opts, &repo) catch break :blk null; 488 const event_id_to_issue_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, "event-id->issue"))) orelse break :blk null; 489 const event_id_to_issue = try DB.HashMap(.read_only).init(event_id_to_issue_cursor); 490 const issue_cursor = (try event_id_to_issue.getCursor(hash.hashInt(repo_opts.hash, &id_bytes))) orelse break :blk null; 491 const issue_map = try DB.HashMap(.read_only).init(issue_cursor); 492 break :blk try evt.read(evt.Issue, DB, repo_opts.hash, &arena, issue_map); 493 }; 494 const issue = issue_maybe orelse { 495 try request.respond(not_found, .{ 496 .status = .not_found, 497 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 498 }); 499 return; 500 }; 501 502 if (issue.status != status) { 503 var updated = issue; 504 updated.status = status; 505 try evt.commitAndConsume(.xit, repo_opts, io, allocator, &repo, evt.events_ref, &[_]evt.EventWithId{.{ 506 .id = base[base.len - id_len ..][0..id_len].*, 507 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 508 .event = .{ .issue = updated }, 509 }}); 510 } 511 512 // like logout, this is a bodyless POST, so close the connection rather than 513 // letting the keep-alive path try to discard a body that isn't framed. 514 try request.respond("", .{ 515 .status = .see_other, 516 .keep_alive = false, 517 .extra_headers = &.{.{ .name = "location", .value = base }}, 518 }); 519 } 520 521 fn renderIndexHtml( 522 io: std.Io, 523 allocator: std.mem.Allocator, 524 host: Host, 525 session_data: ui.Session.Data, 526 ) ![]const u8 { 527 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 528 529 var page_arena = std.heap.ArenaAllocator.init(allocator); 530 defer page_arena.deinit(); 531 532 // the remote admin repo must outlive the page build, since the session's 533 // moment reads from it. 534 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 535 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 536 537 var session = switch (host) { 538 .remote => |remote| blk: { 539 // open the admin repo to read live user/repo data. 540 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 541 const repo = if (repo_maybe) |*repo| repo else unreachable; 542 var session = try ui.Session.init(&page_arena, repo, session_data); 543 // give the page builders filesystem access to the on-disk repos (a 544 // sibling "repos" dir next to the admin repo) so the Repo page can 545 // read its files. 546 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 547 break :blk session; 548 }, 549 .local => |local| ui.Session{ 550 .data = session_data, 551 .arena = &page_arena, 552 .page_arena = &page_arena, 553 .local = local, 554 }, 555 }; 556 session.io = io; 557 558 const snapshot: ui.Snapshot = .{ 559 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 560 .session = session.data, 561 }; 562 var root = try ui.initRoot(allocator, &snapshot.page, &session); 563 defer root.deinit(allocator); 564 565 const content = try generateHtml(allocator, &root); 566 defer allocator.free(content); 567 const overlay = try generateOverlay(allocator, &root, &session); 568 defer allocator.free(overlay); 569 570 // serialize the snapshot so the wasm side can parse it back without making 571 // a second request. it's embedded raw in a <script type="application/json"> 572 // block, whose content is raw text terminated only by "</script". in json, 573 // '<' appears solely inside string values, so escaping every '<' (and '>' 574 // for good measure) to its \uXXXX form yields equivalent json that can't 575 // break out of the tag. 576 var json: std.Io.Writer.Allocating = .init(allocator); 577 defer json.deinit(); 578 try std.json.Stringify.value(snapshot, .{}, &json.writer); 579 580 var json_escaped: std.ArrayList(u8) = .empty; 581 defer json_escaped.deinit(allocator); 582 for (json.written()) |c| switch (c) { 583 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 584 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 585 else => try json_escaped.append(allocator, c), 586 }; 587 588 var out: std.ArrayList(u8) = .empty; 589 errdefer out.deinit(allocator); 590 { 591 var cursor: usize = 0; 592 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 593 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 594 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 595 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 596 }) |sub| { 597 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 598 try out.appendSlice(allocator, template[cursor..idx]); 599 try out.appendSlice(allocator, sub.replacement); 600 cursor = idx + sub.needle.len; 601 } 602 try out.appendSlice(allocator, template[cursor..]); 603 } 604 return try out.toOwnedSlice(allocator); 605 } 606 607 fn findEmbed(request_path: []const u8) ?Embed { 608 const path = if (std.mem.eql(u8, request_path, "/")) 609 "index.html" 610 else if (request_path.len > 1 and request_path[0] == '/') 611 request_path[1..] 612 else 613 return null; 614 615 for (embeds) |embed| { 616 if (std.mem.eql(u8, path, embed.path)) return embed; 617 } 618 return null; 619 } 620 621 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 622 // own absolutely-positioned, natively-scrollable <div> holding its full content, 623 // rendered recursively so nested scrolls work. 624 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 625 const grid = root.getGrid() orelse return error.MissingGrid; 626 627 var out: std.ArrayList(u8) = .empty; 628 errdefer out.deinit(allocator); 629 630 try renderPanel(allocator, &out, root.getFocus(), grid); 631 return try out.toOwnedSlice(allocator); 632 } 633 634 // render one panel — a focus subtree and its content grid — as HTML, recursing 635 // once per web-native Scroll inside it. the root panel is the whole page; each 636 // Scroll becomes a nested, natively-scrollable div holding its full content. 637 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 638 // then the child scroll divs over those holes. 639 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 640 // `direct` is this panel's scroll children, each drawn as an overlaid div. 641 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 642 // plus their descendants, which the focus tree flattens into this panel's 643 // children): the cell hit-test below skips them so this panel doesn't claim 644 // cells that are really rendered inside a child scroll's own panel. 645 // (scrolls aren't nested in practice, so every scroll child is direct here.) 646 var direct: std.ArrayList(usize) = .empty; 647 defer direct.deinit(allocator); 648 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 649 defer excluded.deinit(allocator); 650 { 651 var it = focus.children.iterator(); 652 while (it.next()) |e| { 653 if (e.value_ptr.focus.scroll == null) continue; 654 try direct.append(allocator, e.key_ptr.*); 655 try excluded.put(allocator, e.key_ptr.*, {}); 656 var mit = e.value_ptr.focus.children.iterator(); 657 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 658 } 659 } 660 661 // the HTML element a run of cells is wrapped in, chosen from the cell's 662 // focusable kind 663 const CellTag = union(enum) { 664 span, // clickable focusable cell 665 a: []const u8, // clickable focusable link 666 plain, // non-focusable, colored 667 668 const a_prefix = "a:"; 669 // an "in-page" anchor: rendered as a real <a href> so it works with js 670 // disabled, but crossPageLink ignores it, so with wasm the click just 671 // moves focus rather than navigating. 672 const inpage_prefix = "ai:"; 673 674 fn init(str: []const u8) @This() { 675 if (std.mem.startsWith(u8, str, inpage_prefix)) { 676 return .{ .a = str[inpage_prefix.len..] }; 677 } 678 if (std.mem.startsWith(u8, str, a_prefix)) { 679 return .{ .a = str[a_prefix.len..] }; 680 } 681 return .span; 682 } 683 684 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 685 var id_buf: [32]u8 = undefined; 686 switch (self) { 687 .span => { 688 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 689 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 690 try out.appendSlice(alloc, "\""); 691 try out.appendSlice(alloc, style_attr); 692 try out.appendSlice(alloc, ">"); 693 }, 694 .a => |href| { 695 // tabindex=-1 keeps these out of the browser's tab order 696 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 697 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 698 try out.appendSlice(alloc, "\" href=\""); 699 try appendEscapedHtml(alloc, out, href); 700 try out.appendSlice(alloc, "\""); 701 try out.appendSlice(alloc, style_attr); 702 try out.appendSlice(alloc, ">"); 703 }, 704 .plain => { 705 try out.appendSlice(alloc, "<span"); 706 try out.appendSlice(alloc, style_attr); 707 try out.appendSlice(alloc, ">"); 708 }, 709 } 710 } 711 712 fn closeTag(self: @This()) []const u8 { 713 return switch (self) { 714 .span, .plain => "</span>", 715 .a => "</a>", 716 }; 717 } 718 }; 719 720 // emit this panel's grid as rows of text, coalescing adjacent cells that 721 // share a focus id and colors into one tag (a clickable span, a link, or a 722 // plain colored span). cells under a child scroll keep only their background. 723 for (0..grid.size.height) |y| { 724 var cur_id: ?usize = null; 725 var cur_fg: ?Grid.Color = null; 726 var cur_bg: ?Grid.Color = null; 727 var open_tag: ?CellTag = null; 728 var first = true; 729 for (0..grid.size.width) |x| { 730 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 731 // a cell covered by a child scroll's viewport is drawn by that scroll's 732 // own div, so blank its glyph and make it non-clickable here — but keep 733 // its background, so the backdrop still shows through the scroll's 734 // transparent div instead of a bare hole. 735 const covered_by_scroll = blk: { 736 for (direct.items) |id| { 737 const r = (focus.children.get(id) orelse continue).rect; 738 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; 739 } 740 break :blk false; 741 }; 742 // the focusable cell at (x, y) among this panel's own focusables (skipping 743 // any that belong to a child scroll, whose cells are drawn in their own 744 // panel); none for a covered cell. 745 const cell_id = if (covered_by_scroll) null else blk: { 746 var iter = focus.children.iterator(); 747 while (iter.next()) |entry| { 748 const child = entry.value_ptr.*; 749 if (!child.focus.focusable) continue; 750 if (excluded.contains(entry.key_ptr.*)) continue; 751 const r = child.rect; 752 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 753 break :blk entry.key_ptr.*; 754 } 755 } 756 break :blk null; 757 }; 758 const fg = if (covered_by_scroll) null else cell.style.fg; 759 const bg = cell.style.bg; 760 761 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 762 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 763 764 var new_tag: ?CellTag = null; 765 if (cell_id) |id| { 766 if (focus.children.get(id)) |child| { 767 new_tag = switch (child.focus.kind) { 768 .custom => |custom| CellTag.init(custom), 769 else => .span, 770 }; 771 } 772 } 773 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 774 775 if (new_tag) |t| { 776 var style_buf: [64]u8 = undefined; 777 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 778 } 779 780 open_tag = new_tag; 781 cur_id = cell_id; 782 cur_fg = fg; 783 cur_bg = bg; 784 first = false; 785 } 786 787 if (covered_by_scroll) { 788 try appendEscapedHtml(allocator, output, " "); 789 } else if (cell.continuation) { 790 // the wide rune to the left was emitted 2ch wide, covering this column 791 } else if (cell.rune) |rune| { 792 // a double-width rune is pinned inside a 2ch span so the 793 // fallback glyph's advance width can't shift the rest of the row 794 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 795 if (wide) { 796 try output.appendSlice(allocator, "<span class=\"w2\">"); 797 try appendEscapedHtml(allocator, output, rune); 798 try output.appendSlice(allocator, "</span>"); 799 } else { 800 try appendEscapedHtml(allocator, output, rune); 801 } 802 } else { 803 try appendEscapedHtml(allocator, output, " "); 804 } 805 } 806 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 807 try output.append(allocator, '\n'); 808 } 809 810 // each child scroll becomes a natively-scrollable div positioned over its 811 // viewport, holding its full content rendered recursively. 812 for (direct.items) |id| { 813 const child = focus.children.get(id) orelse continue; 814 const info = child.focus.scroll orelse continue; 815 const r = child.rect; 816 // overflow only on the axes the widget scrolls; `auto` shows a bar only 817 // when that axis actually overflows. the other axis is clipped (hidden), 818 // matching how the terminal Scroll handles its non-scrolling axis. 819 const overflow = switch (info.direction) { 820 .vert => "overflow-x:hidden;overflow-y:auto", 821 .horiz => "overflow-x:auto;overflow-y:hidden", 822 .both => "overflow:auto", 823 }; 824 // the id carries a content version so JS preserves the native scroll 825 // position across re-renders of the same content but resets it when the 826 // content is replaced — e.g. selecting a different commit. the widget's 827 // scroll offset (in cells) rides along so JS can apply it when it has no 828 // preserved position, letting a wasm-side scrollToRect (the files list 829 // scrolling to its selected row on page load) reach the browser. 830 var buf: [224]u8 = undefined; 831 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 })); 832 try renderPanel(allocator, output, child.focus, info.content); 833 try output.appendSlice(allocator, "</div>"); 834 } 835 } 836 837 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 838 // widget tree, each wrapping the text inputs and submit button inside it, 839 // positioned absolutely over the matching grid cells. 840 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 841 const root_focus = root.getFocus(); 842 843 var out: std.ArrayList(u8) = .empty; 844 errdefer out.deinit(allocator); 845 846 const form_prefix = "form:"; 847 848 // Focus.children is an AutoArrayHashMap that preserves insertion order, 849 // which matches the order widgets were added in code 850 var iter = root_focus.children.iterator(); 851 while (iter.next()) |entry| { 852 const child = entry.value_ptr.*; 853 const action_url = switch (child.focus.kind) { 854 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 855 custom[form_prefix.len..] 856 else 857 continue, 858 else => continue, 859 }; 860 861 try out.appendSlice(allocator, "<form action=\""); 862 try appendEscapedHtml(allocator, &out, action_url); 863 try out.appendSlice(allocator, "\" method=\"post\""); 864 // an empty action must not POST — block it and send the input to the TUI instead 865 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 866 try out.appendSlice(allocator, ">"); 867 868 // form.focus.children was populated by addChild, which flattens the 869 // whole subtree into one map — so descendants (inputs + the submit 870 // button) all appear here. positions on form.focus are relative to 871 // the form, so we look up absolute rects via root_focus for layout. 872 var inner_iter = child.focus.children.iterator(); 873 while (inner_iter.next()) |inner_entry| { 874 const inner_id = inner_entry.key_ptr.*; 875 const root_child = root_focus.children.get(inner_id) orelse continue; 876 const r = root_child.rect; 877 switch (root_child.focus.kind) { 878 .text_input, .text_input_password => { 879 const ti = session.text_inputs.get(inner_id) orelse continue; 880 const inner_left = r.x + 1; 881 const inner_top = r.y + 1; 882 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 883 884 try out.appendSlice(allocator, "<input type=\""); 885 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 886 try out.appendSlice(allocator, "\" data-focus-id=\""); 887 var id_buf: [32]u8 = undefined; 888 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 889 if (ti.options.name.len > 0) { 890 try out.appendSlice(allocator, "\" name=\""); 891 try appendEscapedHtml(allocator, &out, ti.options.name); 892 } 893 // intentionally no `value` attribute: the browser tracks user input 894 // natively, and including the wasm-side value here would make the 895 // overlay HTML differ on every keystroke — that would trip the diff 896 // in _setOverlay and rebuild the <input>, eating the user's caret. 897 try out.appendSlice(allocator, "\" style=\"left:"); 898 var pos_buf: [64]u8 = undefined; 899 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 })); 900 try out.appendSlice(allocator, "\">"); 901 }, 902 .text_area => { 903 const ti = session.text_inputs.get(inner_id) orelse continue; 904 const inner_left = r.x + 1; 905 const inner_top = r.y + 1; 906 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 907 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 908 909 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 910 var id_buf: [32]u8 = undefined; 911 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 912 if (ti.options.name.len > 0) { 913 try out.appendSlice(allocator, "\" name=\""); 914 try appendEscapedHtml(allocator, &out, ti.options.name); 915 } 916 // like the input above, no content inside: the browser 917 // tracks the value and the overlay diff must stay stable 918 // across keystrokes 919 try out.appendSlice(allocator, "\" style=\"left:"); 920 var pos_buf: [128]u8 = undefined; 921 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 })); 922 try out.appendSlice(allocator, "\"></textarea>"); 923 }, 924 .custom => |custom| { 925 if (std.mem.eql(u8, "submit", custom)) { 926 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 927 var id_buf: [32]u8 = undefined; 928 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 929 try out.appendSlice(allocator, "\" style=\"left:"); 930 var pos_buf: [128]u8 = undefined; 931 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 })); 932 try out.appendSlice(allocator, "\"></button>"); 933 } 934 }, 935 else => {}, 936 } 937 } 938 939 try out.appendSlice(allocator, "</form>"); 940 } 941 942 return try out.toOwnedSlice(allocator); 943 } 944 945 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 946 if (a) |av| return if (b) |bv| av.eql(bv) else false; 947 return b == null; 948 } 949 950 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 951 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 952 // empty slice when neither is set. 953 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 954 if (fg == null and bg == null) return buf[0..0]; 955 const prefix = " style=\""; 956 @memcpy(buf[0..prefix.len], prefix); 957 var i: usize = prefix.len; 958 if (fg) |c| { 959 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]; 960 i += s.len; 961 } 962 if (bg) |c| { 963 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]; 964 i += s.len; 965 } 966 buf[i] = '"'; 967 i += 1; 968 return buf[0..i]; 969 } 970 971 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 972 for (input) |ch| { 973 switch (ch) { 974 '&' => try out.appendSlice(allocator, "&amp;"), 975 '<' => try out.appendSlice(allocator, "&lt;"), 976 '>' => try out.appendSlice(allocator, "&gt;"), 977 '"' => try out.appendSlice(allocator, "&quot;"), 978 '\'' => try out.appendSlice(allocator, "&#39;"), 979 else => try out.append(allocator, ch), 980 } 981 } 982 } 983 984 // --- helpers -------------------------------------------------------------- 985 986 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 987 var iter = request.iterateHeaders(); 988 while (iter.next()) |header| { 989 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 990 var pairs = std.mem.splitScalar(u8, header.value, ';'); 991 while (pairs.next()) |pair| { 992 const trimmed = std.mem.trim(u8, pair, " \t"); 993 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 994 if (std.mem.eql(u8, trimmed[0..eq], name)) { 995 return trimmed[eq + 1 ..]; 996 } 997 } 998 } 999 return null; 1000 } 1001 1002 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1003 var iter = std.mem.splitScalar(u8, body, '&'); 1004 while (iter.next()) |pair| { 1005 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1006 if (std.mem.eql(u8, pair[0..eq], key)) { 1007 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1008 } 1009 } 1010 return null; 1011 } 1012 1013 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1014 var out: std.ArrayList(u8) = .empty; 1015 errdefer out.deinit(allocator); 1016 var i: usize = 0; 1017 while (i < encoded.len) : (i += 1) { 1018 switch (encoded[i]) { 1019 '+' => try out.append(allocator, ' '), 1020 '%' => { 1021 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1022 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1023 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1024 try out.append(allocator, hi * 16 + lo); 1025 i += 2; 1026 }, 1027 else => try out.append(allocator, encoded[i]), 1028 } 1029 } 1030 return try out.toOwnedSlice(allocator); 1031 } 1032 1033 // disk-backed web session store. each login mints a random, opaque token 1034 // (not the user's id) that is stored as a file named by the token hex, whose 1035 // contents are the raw user_id bytes. authenticating a request is a lookup of 1036 // the cookie's token; logout deletes the file, revoking the session. there is 1037 // deliberately no expiry — a session lives until logout. 1038 pub const SessionStore = struct { 1039 io: std.Io, 1040 dir: std.Io.Dir, 1041 1042 pub const token_hex_len = evt.event_id_size * 2; 1043 1044 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1045 try data_dir.createDirPath(io, "sessions"); 1046 const dir = try data_dir.openDir(io, "sessions", .{}); 1047 return .{ .io = io, .dir = dir }; 1048 } 1049 1050 pub fn deinit(self: SessionStore) void { 1051 self.dir.close(self.io); 1052 } 1053 1054 // mint a new session for user_id, returning the token hex to set as the 1055 // cookie value. 1056 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1057 var token: [evt.event_id_size]u8 = undefined; 1058 self.io.random(&token); 1059 const token_hex = std.fmt.bytesToHex(token, .lower); 1060 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1061 defer file.close(self.io); 1062 try file.writeStreamingAll(self.io, user_id); 1063 return token_hex; 1064 } 1065 1066 // resolve a cookie's token to its user_id. returns false (logged out) for a 1067 // missing, malformed, or unknown token. 1068 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1069 if (!isToken(token_hex)) return false; 1070 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1071 defer file.close(self.io); 1072 var storage: [evt.event_id_size]u8 = undefined; 1073 var file_reader = file.reader(self.io, &storage); 1074 file_reader.interface.readSliceAll(out) catch return false; 1075 return true; 1076 } 1077 1078 // revoke a session. a no-op for a missing or malformed token. 1079 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1080 if (!isToken(token_hex)) return; 1081 self.dir.deleteFile(self.io, token_hex) catch {}; 1082 } 1083 1084 // a token is exactly token_hex_len hex chars. validating before using the 1085 // value as a path keeps attacker-supplied cookies from escaping the 1086 // sessions dir (e.g. via "/" or ".." bytes). 1087 fn isToken(token_hex: []const u8) bool { 1088 if (token_hex.len != token_hex_len) return false; 1089 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1090 return true; 1091 } 1092 }; 1093