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