╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
780 // open the admin repo to read live user/repo data. 781 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 782 const repo = if (repo_maybe) |*repo| repo else unreachable; 783 var session = try ui.Session.init(&page_arena, repo, session_data); 784 // give the page builders filesystem access to the on-disk repos (a 785 // sibling "repos" dir next to the admin repo) so the Repo page can 786 // read its files. 787 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 788 break :blk session; 789 }, 790 .local => |local| ui.Session{ 791 .data = session_data, 792 .arena = &page_arena, 793 .page_arena = &page_arena, 794 .local = local, 795 }, 796 }; 797 session.io = io; 798 799 const snapshot: ui.Snapshot = .{ 800 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 801 .session = session.data, 802 }; 803 var root = try ui.initRoot(allocator, &snapshot.page, &session); 804 defer root.deinit(allocator); 805 806 const content = try generateHtml(allocator, &root); 807 defer allocator.free(content); 808 const overlay = try generateOverlay(allocator, &root, &session); 809 defer allocator.free(overlay); 810 811 // serialize the snapshot so the wasm side can parse it back without making 812 // a second request. it's embedded raw in a <script type="application/json"> 813 // block, whose content is raw text terminated only by "</script". in json, 814 // '<' appears solely inside string values, so escaping every '<' (and '>' 815 // for good measure) to its \uXXXX form yields equivalent json that can't 816 // break out of the tag. 817 var json: std.Io.Writer.Allocating = .init(allocator); 818 defer json.deinit(); 819 try std.json.Stringify.value(snapshot, .{}, &json.writer); 820 821 var json_escaped: std.ArrayList(u8) = .empty; 822 defer json_escaped.deinit(allocator); 823 for (json.written()) |c| switch (c) { 824 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 825 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 826 else => try json_escaped.append(allocator, c), 827 }; 828 829 var out: std.ArrayList(u8) = .empty; 830 errdefer out.deinit(allocator); 831 { 832 var cursor: usize = 0; 833 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 834 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 835 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 836 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 837 }) |sub| { 838 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 839 try out.appendSlice(allocator, template[cursor..idx]); 840 try out.appendSlice(allocator, sub.replacement); 841 cursor = idx + sub.needle.len; 842 } 843 try out.appendSlice(allocator, template[cursor..]); 844 } 845 return try out.toOwnedSlice(allocator); 846 } 847 848 fn findEmbed(request_path: []const u8) ?Embed { 849 const path = if (std.mem.eql(u8, request_path, "/")) 850 "index.html" 851 else if (request_path.len > 1 and request_path[0] == '/') 852 request_path[1..] 853 else 854 return null; 855 856 for (embeds) |embed| { 857 if (std.mem.eql(u8, path, embed.path)) return embed; 858 } 859 return null; 860 } 861 862 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 863 // own absolutely-positioned, natively-scrollable <div> holding its full content, 864 // rendered recursively so nested scrolls work. 865 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 866 const grid = root.getGrid() orelse return error.MissingGrid; 867 868 var out: std.ArrayList(u8) = .empty; 869 errdefer out.deinit(allocator); 870 871 try renderPanel(allocator, &out, root.getFocus(), grid); 872 return try out.toOwnedSlice(allocator); 873 } 874 875 // render one panel — a focus subtree and its content grid — as HTML, recursing 876 // once per web-native Scroll inside it. the root panel is the whole page; each 877 // Scroll becomes a nested, natively-scrollable div holding its full content. 878 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 879 // then the child scroll divs over those holes. 880 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 881 // `direct` is this panel's scroll children, each drawn as an overlaid div. 882 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 883 // plus their descendants, which the focus tree flattens into this panel's 884 // children): the cell hit-test below skips them so this panel doesn't claim 885 // cells that are really rendered inside a child scroll's own panel. 886 // (scrolls aren't nested in practice, so every scroll child is direct here.) 887 var direct: std.ArrayList(usize) = .empty; 888 defer direct.deinit(allocator); 889 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 890 defer excluded.deinit(allocator); 891 { 892 var it = focus.children.iterator(); 893 while (it.next()) |e| { 894 if (e.value_ptr.focus.scroll == null) continue; 895 try direct.append(allocator, e.key_ptr.*); 896 try excluded.put(allocator, e.key_ptr.*, {}); 897 var mit = e.value_ptr.focus.children.iterator(); 898 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 899 } 900 } 901 902 // the HTML element a run of cells is wrapped in, chosen from the cell's 903 // focusable kind 904 const CellTag = union(enum) { 905 span, // clickable focusable cell 906 a: []const u8, // clickable focusable link 907 plain, // non-focusable, colored 908 909 const a_prefix = "a:"; 910 // an "in-page" anchor: rendered as a real <a href> so it works with js 911 // disabled, but crossPageLink ignores it, so with wasm the click just 912 // moves focus rather than navigating. 913 const inpage_prefix = "ai:"; 914 915 fn init(str: []const u8) @This() { 916 if (std.mem.startsWith(u8, str, inpage_prefix)) { 917 return .{ .a = str[inpage_prefix.len..] }; 918 } 919 if (std.mem.startsWith(u8, str, a_prefix)) { 920 return .{ .a = str[a_prefix.len..] }; 921 } 922 return .span; 923 } 924 925 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 926 var id_buf: [32]u8 = undefined; 927 switch (self) { 928 .span => { 929 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 930 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 931 try out.appendSlice(alloc, "\""); 932 try out.appendSlice(alloc, style_attr); 933 try out.appendSlice(alloc, ">"); 934 }, 935 .a => |href| { 936 // tabindex=-1 keeps these out of the browser's tab order 937 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 938 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 939 try out.appendSlice(alloc, "\" href=\""); 940 try appendEscapedHtml(alloc, out, href); 941 try out.appendSlice(alloc, "\""); 942 try out.appendSlice(alloc, style_attr); 943 try out.appendSlice(alloc, ">"); 944 }, 945 .plain => { 946 try out.appendSlice(alloc, "<span"); 947 try out.appendSlice(alloc, style_attr); 948 try out.appendSlice(alloc, ">"); 949 }, 950 } 951 } 952 953 fn closeTag(self: @This()) []const u8 { 954 return switch (self) { 955 .span, .plain => "</span>", 956 .a => "</a>", 957 }; 958 } 959 }; 960 961 // emit this panel's grid as rows of text, coalescing adjacent cells that 962 // share a focus id and colors into one tag (a clickable span, a link, or a 963 // plain colored span). cells under a child scroll keep only their background. 964 for (0..grid.size.height) |y| { 965 var cur_id: ?usize = null; 966 var cur_fg: ?Grid.Color = null; 967 var cur_bg: ?Grid.Color = null; 968 var open_tag: ?CellTag = null; 969 var first = true; 970 for (0..grid.size.width) |x| { 971 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 972 // a cell covered by a child scroll's viewport is drawn by that scroll's 973 // own div, so blank its glyph and make it non-clickable here — but keep 974 // its background, so the backdrop still shows through the scroll's 975 // transparent div instead of a bare hole. 976 const covered_by_scroll = blk: { 977 for (direct.items) |id| { 978 const r = (focus.children.get(id) orelse continue).rect; 979 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; 980 } 981 break :blk false; 982 }; 983 // the focusable cell at (x, y) among this panel's own focusables (skipping 984 // any that belong to a child scroll, whose cells are drawn in their own 985 // panel); none for a covered cell. 986 const cell_id = if (covered_by_scroll) null else blk: { 987 var iter = focus.children.iterator(); 988 while (iter.next()) |entry| { 989 const child = entry.value_ptr.*; 990 if (!child.focus.focusable) continue; 991 if (excluded.contains(entry.key_ptr.*)) continue; 992 const r = child.rect; 993 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 994 break :blk entry.key_ptr.*; 995 } 996 } 997 break :blk null; 998 }; 999 const fg = if (covered_by_scroll) null else cell.style.fg; 1000 const bg = cell.style.bg; 1001 1002 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1003 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1004 1005 var new_tag: ?CellTag = null; 1006 if (cell_id) |id| { 1007 if (focus.children.get(id)) |child| { 1008 new_tag = switch (child.focus.kind) { 1009 .custom => |custom| CellTag.init(custom), 1010 else => .span, 1011 }; 1012 } 1013 } 1014 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1015 1016 if (new_tag) |t| { 1017 var style_buf: [64]u8 = undefined; 1018 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1019 } 1020 1021 open_tag = new_tag; 1022 cur_id = cell_id; 1023 cur_fg = fg; 1024 cur_bg = bg; 1025 first = false; 1026 } 1027 1028 if (covered_by_scroll) { 1029 try appendEscapedHtml(allocator, output, " "); 1030 } else if (cell.continuation) { 1031 // the wide rune to the left was emitted 2ch wide, covering this column 1032 } else if (cell.rune) |rune| { 1033 // a double-width rune is pinned inside a 2ch span so the 1034 // fallback glyph's advance width can't shift the rest of the row 1035 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1036 if (wide) { 1037 try output.appendSlice(allocator, "<span class=\"w2\">"); 1038 try appendEscapedHtml(allocator, output, rune); 1039 try output.appendSlice(allocator, "</span>"); 1040 } else { 1041 try appendEscapedHtml(allocator, output, rune); 1042 } 1043 } else { 1044 try appendEscapedHtml(allocator, output, " "); 1045 } 1046 } 1047 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1048 try output.append(allocator, '\n'); 1049 } 1050 1051 // each child scroll becomes a natively-scrollable div positioned over its 1052 // viewport, holding its full content rendered recursively. 1053 for (direct.items) |id| { 1054 const child = focus.children.get(id) orelse continue; 1055 const info = child.focus.scroll orelse continue; 1056 const r = child.rect; 1057 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1058 // when that axis actually overflows. the other axis is clipped (hidden), 1059 // matching how the terminal Scroll handles its non-scrolling axis. 1060 const overflow = switch (info.direction) { 1061 .vert => "overflow-x:hidden;overflow-y:auto", 1062 .horiz => "overflow-x:auto;overflow-y:hidden", 1063 .both => "overflow:auto", 1064 }; 1065 // the id carries a content version so JS preserves the native scroll 1066 // position across re-renders of the same content but resets it when the 1067 // content is replaced — e.g. selecting a different commit. the widget's 1068 // scroll offset (in cells) rides along so JS can apply it when it has no 1069 // preserved position, letting a wasm-side scrollToRect (the files list 1070 // scrolling to its selected row on page load) reach the browser. 1071 var buf: [224]u8 = undefined; 1072 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 })); 1073 try renderPanel(allocator, output, child.focus, info.content); 1074 try output.appendSlice(allocator, "</div>"); 1075 } 1076 } 1077 1078 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1079 // widget tree, each wrapping the text inputs and submit button inside it, 1080 // positioned absolutely over the matching grid cells. 1081 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1082 const root_focus = root.getFocus(); 1083 1084 var out: std.ArrayList(u8) = .empty; 1085 errdefer out.deinit(allocator); 1086 1087 const form_prefix = "form:"; 1088 1089 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1090 // which matches the order widgets were added in code 1091 var iter = root_focus.children.iterator(); 1092 while (iter.next()) |entry| { 1093 const child = entry.value_ptr.*; 1094 const action_url = switch (child.focus.kind) { 1095 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1096 custom[form_prefix.len..] 1097 else 1098 continue, 1099 else => continue, 1100 }; 1101 1102 try out.appendSlice(allocator, "<form action=\""); 1103 try appendEscapedHtml(allocator, &out, action_url); 1104 try out.appendSlice(allocator, "\" method=\"post\""); 1105 // an empty action must not POST — block it and send the input to the TUI instead 1106 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1107 try out.appendSlice(allocator, ">"); 1108 1109 // form.focus.children was populated by addChild, which flattens the 1110 // whole subtree into one map — so descendants (inputs + the submit 1111 // button) all appear here. positions on form.focus are relative to 1112 // the form, so we look up absolute rects via root_focus for layout. 1113 var inner_iter = child.focus.children.iterator(); 1114 while (inner_iter.next()) |inner_entry| { 1115 const inner_id = inner_entry.key_ptr.*; 1116 const root_child = root_focus.children.get(inner_id) orelse continue; 1117 const r = root_child.rect; 1118 switch (root_child.focus.kind) { 1119 .text_input, .text_input_password => { 1120 const ti = session.text_inputs.get(inner_id) orelse continue; 1121 const inner_left = r.x + 1; 1122 const inner_top = r.y + 1; 1123 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1124 1125 try out.appendSlice(allocator, "<input type=\""); 1126 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1127 try out.appendSlice(allocator, "\" data-focus-id=\""); 1128 var id_buf: [32]u8 = undefined; 1129 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1130 if (ti.options.name.len > 0) { 1131 try out.appendSlice(allocator, "\" name=\""); 1132 try appendEscapedHtml(allocator, &out, ti.options.name); 1133 } 1134 // never the live content as the `value`: the browser tracks user 1135 // input natively, and including the wasm-side value here would make 1136 // the overlay HTML differ on every keystroke — that would trip the 1137 // diff in _setOverlay and rebuild the <input>, eating the user's 1138 // caret. a page-constant initial value is safe. 1139 if (session.input_values.get(inner_id)) |value| { 1140 try out.appendSlice(allocator, "\" value=\""); 1141 try appendEscapedHtml(allocator, &out, value); 1142 } 1143 try out.appendSlice(allocator, "\" style=\"left:"); 1144 var pos_buf: [64]u8 = undefined; 1145 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 })); 1146 try out.appendSlice(allocator, "\">"); 1147 }, 1148 .text_area => { 1149 const ti = session.text_inputs.get(inner_id) orelse continue; 1150 const inner_left = r.x + 1; 1151 const inner_top = r.y + 1; 1152 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1153 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1154 1155 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1156 var id_buf: [32]u8 = undefined; 1157 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1158 if (ti.options.name.len > 0) { 1159 try out.appendSlice(allocator, "\" name=\""); 1160 try appendEscapedHtml(allocator, &out, ti.options.name); 1161 } 1162 // like the input above, only a page-constant initial value 1163 // inside: the browser tracks the live value and the 1164 // overlay diff must stay stable across keystrokes 1165 try out.appendSlice(allocator, "\" style=\"left:"); 1166 var pos_buf: [128]u8 = undefined; 1167 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 })); 1168 try out.appendSlice(allocator, "\">"); 1169 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1170 try out.appendSlice(allocator, "</textarea>"); 1171 }, 1172 .custom => |custom| { 1173 if (std.mem.eql(u8, "submit", custom)) { 1174 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1175 var id_buf: [32]u8 = undefined; 1176 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1177 try out.appendSlice(allocator, "\" style=\"left:"); 1178 var pos_buf: [128]u8 = undefined; 1179 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 })); 1180 try out.appendSlice(allocator, "\"></button>"); 1181 } 1182 }, 1183 else => {}, 1184 } 1185 } 1186 1187 try out.appendSlice(allocator, "</form>"); 1188 } 1189 1190 return try out.toOwnedSlice(allocator); 1191 } 1192 1193 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1194 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1195 return b == null; 1196 } 1197 1198 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1199 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1200 // empty slice when neither is set. 1201 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1202 if (fg == null and bg == null) return buf[0..0]; 1203 const prefix = " style=\""; 1204 @memcpy(buf[0..prefix.len], prefix); 1205 var i: usize = prefix.len; 1206 if (fg) |c| { 1207 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]; 1208 i += s.len; 1209 } 1210 if (bg) |c| { 1211 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]; 1212 i += s.len; 1213 } 1214 buf[i] = '"'; 1215 i += 1; 1216 return buf[0..i]; 1217 } 1218 1219 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1220 for (input) |ch| { 1221 switch (ch) { 1222 '&' => try out.appendSlice(allocator, "&amp;"), 1223 '<' => try out.appendSlice(allocator, "&lt;"), 1224 '>' => try out.appendSlice(allocator, "&gt;"), 1225 '"' => try out.appendSlice(allocator, "&quot;"), 1226 '\'' => try out.appendSlice(allocator, "&#39;"), 1227 else => try out.append(allocator, ch), 1228 } 1229 } 1230 } 1231 1232 // --- helpers -------------------------------------------------------------- 1233 1234 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1235 var iter = request.iterateHeaders(); 1236 while (iter.next()) |header| { 1237 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1238 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1239 while (pairs.next()) |pair| { 1240 const trimmed = std.mem.trim(u8, pair, " \t"); 1241 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1242 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1243 return trimmed[eq + 1 ..]; 1244 } 1245 } 1246 } 1247 return null; 1248 } 1249 1250 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1251 var iter = std.mem.splitScalar(u8, body, '&'); 1252 while (iter.next()) |pair| { 1253 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1254 if (std.mem.eql(u8, pair[0..eq], key)) { 1255 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1256 } 1257 } 1258 return null; 1259 } 1260 1261 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1262 var out: std.ArrayList(u8) = .empty; 1263 errdefer out.deinit(allocator); 1264 var i: usize = 0; 1265 while (i < encoded.len) : (i += 1) { 1266 switch (encoded[i]) { 1267 '+' => try out.append(allocator, ' '), 1268 '%' => { 1269 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1270 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1271 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1272 try out.append(allocator, hi * 16 + lo); 1273 i += 2; 1274 }, 1275 else => try out.append(allocator, encoded[i]), 1276 } 1277 } 1278 return try out.toOwnedSlice(allocator); 1279 } 1280 1281 // disk-backed web session store. each login mints a random, opaque token 1282 // (not the user's id) that is stored as a file named by the token hex, whose 1283 // contents are the raw user_id bytes. authenticating a request is a lookup of 1284 // the cookie's token; logout deletes the file, revoking the session. there is 1285 // deliberately no expiry — a session lives until logout. 1286 pub const SessionStore = struct { 1287 io: std.Io, 1288 dir: std.Io.Dir, 1289 1290 pub const token_hex_len = evt.event_id_size * 2; 1291 1292 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1293 try data_dir.createDirPath(io, "sessions"); 1294 const dir = try data_dir.openDir(io, "sessions", .{}); 1295 return .{ .io = io, .dir = dir }; 1296 } 1297 1298 pub fn deinit(self: SessionStore) void { 1299 self.dir.close(self.io); 1300 } 1301 1302 // mint a new session for user_id, returning the token hex to set as the 1303 // cookie value. 1304 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1305 var token: [evt.event_id_size]u8 = undefined; 1306 self.io.random(&token); 1307 const token_hex = std.fmt.bytesToHex(token, .lower); 1308 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1309 defer file.close(self.io); 1310 try file.writeStreamingAll(self.io, user_id); 1311 return token_hex; 1312 } 1313 1314 // resolve a cookie's token to its user_id. returns false (logged out) for a 1315 // missing, malformed, or unknown token. 1316 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1317 if (!isToken(token_hex)) return false; 1318 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1319 defer file.close(self.io); 1320 var storage: [evt.event_id_size]u8 = undefined; 1321 var file_reader = file.reader(self.io, &storage); 1322 file_reader.interface.readSliceAll(out) catch return false; 1323 return true; 1324 } 1325 1326 // revoke a session. a no-op for a missing or malformed token. 1327 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1328 if (!isToken(token_hex)) return; 1329 self.dir.deleteFile(self.io, token_hex) catch {}; 1330 } 1331 1332 // leave `token_hex`'s session for the next visitor arriving without one. 1333 // only the `try` fixture writes one, and only a debug build honors it. the 1334 // name isn't token-shaped, so it can't collide with a session file. 1335 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1336 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1337 defer file.close(self.io); 1338 try file.writeStreamingAll(self.io, token_hex); 1339 } 1340 1341 // claim the offered session, if one is there. the delete picks the winner 1342 // of a race, so the offer is only ever taken once. a release build never 1343 // looks, because that would be an extra syscall for every GET request. 1344 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1345 if (builtin.mode != .Debug) return false; 1346 { 1347 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1348 defer file.close(self.io); 1349 var storage: [token_hex_len]u8 = undefined; 1350 var file_reader = file.reader(self.io, &storage); 1351 file_reader.interface.readSliceAll(out) catch return false; 1352 } 1353 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1354 return true; 1355 } 1356 1357 const auto_login_name = "auto-login"; 1358 1359 // a token is exactly token_hex_len hex chars. validating before using the 1360 // value as a path keeps attacker-supplied cookies from escaping the 1361 // sessions dir (e.g. via "/" or ".." bytes). 1362 fn isToken(token_hex: []const u8) bool { 1363 if (token_hex.len != token_hex_len) return false; 1364 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1365 return true; 1366 } 1367 }; 1368