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