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