╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
507 try out.appendSlice(alloc, ">"); 508 }, 509 .plain => { 510 try out.appendSlice(alloc, "<span"); 511 try out.appendSlice(alloc, style_attr); 512 try out.appendSlice(alloc, ">"); 513 }, 514 } 515 } 516 517 fn closeTag(self: @This()) []const u8 { 518 return switch (self) { 519 .span, .plain => "</span>", 520 .a => "</a>", 521 }; 522 } 523 }; 524 525 // emit this panel's grid as rows of text, coalescing adjacent cells that 526 // share a focus id and colors into one tag (a clickable span, a link, or a 527 // plain colored span). cells under a child scroll keep only their background. 528 for (0..grid.size.height) |y| { 529 var cur_id: ?usize = null; 530 var cur_fg: ?Grid.Color = null; 531 var cur_bg: ?Grid.Color = null; 532 var open_tag: ?CellTag = null; 533 var first = true; 534 for (0..grid.size.width) |x| { 535 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 536 // a cell covered by a child scroll's viewport is drawn by that scroll's 537 // own div, so blank its glyph and make it non-clickable here — but keep 538 // its background, so the backdrop still shows through the scroll's 539 // transparent div instead of a bare hole. 540 const covered_by_scroll = blk: { 541 for (direct.items) |id| { 542 const r = (focus.children.get(id) orelse continue).rect; 543 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; 544 } 545 break :blk false; 546 }; 547 // the focusable cell at (x, y) among this panel's own focusables (skipping 548 // any that belong to a child scroll, whose cells are drawn in their own 549 // panel); none for a covered cell. 550 const cell_id = if (covered_by_scroll) null else blk: { 551 var iter = focus.children.iterator(); 552 while (iter.next()) |entry| { 553 const child = entry.value_ptr.*; 554 if (!child.focus.focusable) continue; 555 if (excluded.contains(entry.key_ptr.*)) continue; 556 const r = child.rect; 557 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 558 break :blk entry.key_ptr.*; 559 } 560 } 561 break :blk null; 562 }; 563 const fg = if (covered_by_scroll) null else cell.style.fg; 564 const bg = cell.style.bg; 565 566 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 567 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 568 569 var new_tag: ?CellTag = null; 570 if (cell_id) |id| { 571 if (focus.children.get(id)) |child| { 572 new_tag = switch (child.focus.kind) { 573 .custom => |custom| CellTag.init(custom), 574 else => .span, 575 }; 576 } 577 } 578 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 579 580 if (new_tag) |t| { 581 var style_buf: [64]u8 = undefined; 582 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 583 } 584 585 open_tag = new_tag; 586 cur_id = cell_id; 587 cur_fg = fg; 588 cur_bg = bg; 589 first = false; 590 } 591 592 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 593 } 594 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 595 try output.append(allocator, '\n'); 596 } 597 598 // each child scroll becomes a natively-scrollable div positioned over its 599 // viewport, holding its full content rendered recursively. 600 for (direct.items) |id| { 601 const child = focus.children.get(id) orelse continue; 602 const info = child.focus.scroll orelse continue; 603 const r = child.rect; 604 // overflow only on the axes the widget scrolls; `auto` shows a bar only 605 // when that axis actually overflows. the other axis is clipped (hidden), 606 // matching how the terminal Scroll handles its non-scrolling axis. 607 const overflow = switch (info.direction) { 608 .vert => "overflow-x:hidden;overflow-y:auto", 609 .horiz => "overflow-x:auto;overflow-y:hidden", 610 .both => "overflow:auto", 611 }; 612 // the id carries a content version so JS preserves the native scroll 613 // position across re-renders of the same content but resets it (to the 614 // top) when the content is replaced — e.g. selecting a different commit. 615 var buf: [160]u8 = undefined; 616 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, r.x, r.y, r.size.width, r.size.height, overflow })); 617 try renderPanel(allocator, output, child.focus, info.content); 618 try output.appendSlice(allocator, "</div>"); 619 } 620 } 621 622 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 623 // widget tree, each wrapping the text inputs and submit button inside it, 624 // positioned absolutely over the matching grid cells. 625 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 626 const root_focus = root.getFocus(); 627 628 var out: std.ArrayList(u8) = .empty; 629 errdefer out.deinit(allocator); 630 631 const form_prefix = "form:"; 632 633 // Focus.children is an AutoArrayHashMap that preserves insertion order, 634 // which matches the order widgets were added in code 635 var iter = root_focus.children.iterator(); 636 while (iter.next()) |entry| { 637 const child = entry.value_ptr.*; 638 const action_url = switch (child.focus.kind) { 639 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 640 custom[form_prefix.len..] 641 else 642 continue, 643 else => continue, 644 }; 645 646 try out.appendSlice(allocator, "<form action=\""); 647 try appendEscapedHtml(allocator, &out, action_url); 648 try out.appendSlice(allocator, "\" method=\"post\""); 649 // an empty action must not POST — block it and send the input to the TUI instead 650 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 651 try out.appendSlice(allocator, ">"); 652 653 // form.focus.children was populated by addChild, which flattens the 654 // whole subtree into one map — so descendants (inputs + the submit 655 // button) all appear here. positions on form.focus are relative to 656 // the form, so we look up absolute rects via root_focus for layout. 657 var inner_iter = child.focus.children.iterator(); 658 while (inner_iter.next()) |inner_entry| { 659 const inner_id = inner_entry.key_ptr.*; 660 const root_child = root_focus.children.get(inner_id) orelse continue; 661 const r = root_child.rect; 662 switch (root_child.focus.kind) { 663 .text_input, .text_input_password => { 664 const ti = session.text_inputs.get(inner_id) orelse continue; 665 const inner_left = r.x + 1; 666 const inner_top = r.y + 1; 667 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 668 669 try out.appendSlice(allocator, "<input type=\""); 670 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 671 try out.appendSlice(allocator, "\" data-focus-id=\""); 672 var id_buf: [32]u8 = undefined; 673 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 674 if (ti.options.name.len > 0) { 675 try out.appendSlice(allocator, "\" name=\""); 676 try appendEscapedHtml(allocator, &out, ti.options.name); 677 } 678 // intentionally no `value` attribute: the browser tracks user input 679 // natively, and including the wasm-side value here would make the 680 // overlay HTML differ on every keystroke — that would trip the diff 681 // in _setOverlay and rebuild the <input>, eating the user's caret. 682 try out.appendSlice(allocator, "\" style=\"left:"); 683 var pos_buf: [64]u8 = undefined; 684 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 })); 685 try out.appendSlice(allocator, "\">"); 686 }, 687 .custom => |custom| { 688 if (std.mem.eql(u8, "submit", custom)) { 689 // inside the dashed border the TUI cells draw around the button. 690 const inner_left = r.x + 1; 691 const inner_top = r.y + 1; 692 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 693 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 694 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 695 var id_buf: [32]u8 = undefined; 696 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 697 try out.appendSlice(allocator, "\" style=\"left:"); 698 var pos_buf: [128]u8 = undefined; 699 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 })); 700 try out.appendSlice(allocator, "\"></button>"); 701 } 702 }, 703 else => {}, 704 } 705 } 706 707 try out.appendSlice(allocator, "</form>"); 708 } 709 710 return try out.toOwnedSlice(allocator); 711 } 712 713 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 714 if (a) |av| return if (b) |bv| av.eql(bv) else false; 715 return b == null; 716 } 717 718 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 719 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 720 // empty slice when neither is set. 721 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 722 if (fg == null and bg == null) return buf[0..0]; 723 const prefix = " style=\""; 724 @memcpy(buf[0..prefix.len], prefix); 725 var i: usize = prefix.len; 726 if (fg) |c| { 727 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]; 728 i += s.len; 729 } 730 if (bg) |c| { 731 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]; 732 i += s.len; 733 } 734 buf[i] = '"'; 735 i += 1; 736 return buf[0..i]; 737 } 738 739 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 740 for (input) |ch| { 741 switch (ch) { 742 '&' => try out.appendSlice(allocator, "&amp;"), 743 '<' => try out.appendSlice(allocator, "&lt;"), 744 '>' => try out.appendSlice(allocator, "&gt;"), 745 '"' => try out.appendSlice(allocator, "&quot;"), 746 '\'' => try out.appendSlice(allocator, "&#39;"), 747 else => try out.append(allocator, ch), 748 } 749 } 750 } 751 752 // --- helpers -------------------------------------------------------------- 753 754 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 755 var iter = request.iterateHeaders(); 756 while (iter.next()) |header| { 757 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 758 var pairs = std.mem.splitScalar(u8, header.value, ';'); 759 while (pairs.next()) |pair| { 760 const trimmed = std.mem.trim(u8, pair, " \t"); 761 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 762 if (std.mem.eql(u8, trimmed[0..eq], name)) { 763 return trimmed[eq + 1 ..]; 764 } 765 } 766 } 767 return null; 768 } 769 770 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 771 var iter = std.mem.splitScalar(u8, body, '&'); 772 while (iter.next()) |pair| { 773 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 774 if (std.mem.eql(u8, pair[0..eq], key)) { 775 return try decodeFormValue(allocator, pair[eq + 1 ..]); 776 } 777 } 778 return null; 779 } 780 781 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 782 var out: std.ArrayList(u8) = .empty; 783 errdefer out.deinit(allocator); 784 var i: usize = 0; 785 while (i < encoded.len) : (i += 1) { 786 switch (encoded[i]) { 787 '+' => try out.append(allocator, ' '), 788 '%' => { 789 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 790 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 791 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 792 try out.append(allocator, hi * 16 + lo); 793 i += 2; 794 }, 795 else => try out.append(allocator, encoded[i]), 796 } 797 } 798 return try out.toOwnedSlice(allocator); 799 } 800 801 // disk-backed web session store. each login mints a random, opaque token 802 // (not the user's id) that is stored as a file named by the token hex, whose 803 // contents are the raw user_id bytes. authenticating a request is a lookup of 804 // the cookie's token; logout deletes the file, revoking the session. there is 805 // deliberately no expiry — a session lives until logout. 806 pub const SessionStore = struct { 807 io: std.Io, 808 dir: std.Io.Dir, 809 810 pub const token_hex_len = evt.event_id_size * 2; 811 812 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 813 try data_dir.createDirPath(io, "sessions"); 814 const dir = try data_dir.openDir(io, "sessions", .{}); 815 return .{ .io = io, .dir = dir }; 816 } 817 818 pub fn deinit(self: SessionStore) void { 819 self.dir.close(self.io); 820 } 821 822 // mint a new session for user_id, returning the token hex to set as the 823 // cookie value. 824 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 825 var token: [evt.event_id_size]u8 = undefined; 826 self.io.random(&token); 827 const token_hex = std.fmt.bytesToHex(token, .lower); 828 const file = try self.dir.createFile(self.io, &token_hex, .{}); 829 defer file.close(self.io); 830 try file.writeStreamingAll(self.io, user_id); 831 return token_hex; 832 } 833 834 // resolve a cookie's token to its user_id. returns false (logged out) for a 835 // missing, malformed, or unknown token. 836 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 837 if (!isToken(token_hex)) return false; 838 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 839 defer file.close(self.io); 840 var storage: [evt.event_id_size]u8 = undefined; 841 var file_reader = file.reader(self.io, &storage); 842 file_reader.interface.readSliceAll(out) catch return false; 843 return true; 844 } 845 846 // revoke a session. a no-op for a missing or malformed token. 847 pub fn remove(self: SessionStore, token_hex: []const u8) void { 848 if (!isToken(token_hex)) return; 849 self.dir.deleteFile(self.io, token_hex) catch {}; 850 } 851 852 // a token is exactly token_hex_len hex chars. validating before using the 853 // value as a path keeps attacker-supplied cookies from escaping the 854 // sessions dir (e.g. via "/" or ".." bytes). 855 fn isToken(token_hex: []const u8) bool { 856 if (token_hex.len != token_hex_len) return false; 857 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 858 return true; 859 } 860 }; 861