╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
793 try out.appendSlice(alloc, style_attr); 794 try out.appendSlice(alloc, ">"); 795 }, 796 .a => |href| { 797 // tabindex=-1 keeps these out of the browser's tab order 798 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 799 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 800 try out.appendSlice(alloc, "\" href=\""); 801 try appendEscapedHtml(alloc, out, href); 802 try out.appendSlice(alloc, "\""); 803 try out.appendSlice(alloc, style_attr); 804 try out.appendSlice(alloc, ">"); 805 }, 806 .plain => { 807 try out.appendSlice(alloc, "<span"); 808 try out.appendSlice(alloc, style_attr); 809 try out.appendSlice(alloc, ">"); 810 }, 811 } 812 } 813 814 fn closeTag(self: @This()) []const u8 { 815 return switch (self) { 816 .span, .plain => "</span>", 817 .a => "</a>", 818 }; 819 } 820 }; 821 822 // emit this panel's grid as rows of text, coalescing adjacent cells that 823 // share a focus id and colors into one tag (a clickable span, a link, or a 824 // plain colored span). cells under a child scroll keep only their background. 825 for (0..grid.size.height) |y| { 826 var cur_id: ?usize = null; 827 var cur_fg: ?Grid.Color = null; 828 var cur_bg: ?Grid.Color = null; 829 var open_tag: ?CellTag = null; 830 var first = true; 831 for (0..grid.size.width) |x| { 832 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 833 // a cell covered by a child scroll's viewport is drawn by that scroll's 834 // own div, so blank its glyph and make it non-clickable here — but keep 835 // its background, so the backdrop still shows through the scroll's 836 // transparent div instead of a bare hole. 837 const covered_by_scroll = blk: { 838 for (direct.items) |id| { 839 const r = (focus.children.get(id) orelse continue).rect; 840 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; 841 } 842 break :blk false; 843 }; 844 // the focusable cell at (x, y) among this panel's own focusables (skipping 845 // any that belong to a child scroll, whose cells are drawn in their own 846 // panel); none for a covered cell. 847 const cell_id = if (covered_by_scroll) null else blk: { 848 var iter = focus.children.iterator(); 849 while (iter.next()) |entry| { 850 const child = entry.value_ptr.*; 851 if (!child.focus.focusable) continue; 852 if (excluded.contains(entry.key_ptr.*)) continue; 853 const r = child.rect; 854 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 855 break :blk entry.key_ptr.*; 856 } 857 } 858 break :blk null; 859 }; 860 const fg = if (covered_by_scroll) null else cell.style.fg; 861 const bg = cell.style.bg; 862 863 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 864 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 865 866 var new_tag: ?CellTag = null; 867 if (cell_id) |id| { 868 if (focus.children.get(id)) |child| { 869 new_tag = switch (child.focus.kind) { 870 .custom => |custom| CellTag.init(custom), 871 else => .span, 872 }; 873 } 874 } 875 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 876 877 if (new_tag) |t| { 878 var style_buf: [64]u8 = undefined; 879 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 880 } 881 882 open_tag = new_tag; 883 cur_id = cell_id; 884 cur_fg = fg; 885 cur_bg = bg; 886 first = false; 887 } 888 889 if (covered_by_scroll) { 890 try appendEscapedHtml(allocator, output, " "); 891 } else if (cell.continuation) { 892 // the wide rune to the left was emitted 2ch wide, covering this column 893 } else if (cell.rune) |rune| { 894 // a double-width rune is pinned inside a 2ch span so the 895 // fallback glyph's advance width can't shift the rest of the row 896 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 897 if (wide) { 898 try output.appendSlice(allocator, "<span class=\"w2\">"); 899 try appendEscapedHtml(allocator, output, rune); 900 try output.appendSlice(allocator, "</span>"); 901 } else { 902 try appendEscapedHtml(allocator, output, rune); 903 } 904 } else { 905 try appendEscapedHtml(allocator, output, " "); 906 } 907 } 908 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 909 try output.append(allocator, '\n'); 910 } 911 912 // each child scroll becomes a natively-scrollable div positioned over its 913 // viewport, holding its full content rendered recursively. 914 for (direct.items) |id| { 915 const child = focus.children.get(id) orelse continue; 916 const info = child.focus.scroll orelse continue; 917 const r = child.rect; 918 // overflow only on the axes the widget scrolls; `auto` shows a bar only 919 // when that axis actually overflows. the other axis is clipped (hidden), 920 // matching how the terminal Scroll handles its non-scrolling axis. 921 const overflow = switch (info.direction) { 922 .vert => "overflow-x:hidden;overflow-y:auto", 923 .horiz => "overflow-x:auto;overflow-y:hidden", 924 .both => "overflow:auto", 925 }; 926 // the id carries a content version so JS preserves the native scroll 927 // position across re-renders of the same content but resets it when the 928 // content is replaced — e.g. selecting a different commit. the widget's 929 // scroll offset (in cells) rides along so JS can apply it when it has no 930 // preserved position, letting a wasm-side scrollToRect (the files list 931 // scrolling to its selected row on page load) reach the browser. 932 var buf: [224]u8 = undefined; 933 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 })); 934 try renderPanel(allocator, output, child.focus, info.content); 935 try output.appendSlice(allocator, "</div>"); 936 } 937 } 938 939 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 940 // widget tree, each wrapping the text inputs and submit button inside it, 941 // positioned absolutely over the matching grid cells. 942 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 943 const root_focus = root.getFocus(); 944 945 var out: std.ArrayList(u8) = .empty; 946 errdefer out.deinit(allocator); 947 948 const form_prefix = "form:"; 949 950 // Focus.children is an AutoArrayHashMap that preserves insertion order, 951 // which matches the order widgets were added in code 952 var iter = root_focus.children.iterator(); 953 while (iter.next()) |entry| { 954 const child = entry.value_ptr.*; 955 const action_url = switch (child.focus.kind) { 956 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 957 custom[form_prefix.len..] 958 else 959 continue, 960 else => continue, 961 }; 962 963 try out.appendSlice(allocator, "<form action=\""); 964 try appendEscapedHtml(allocator, &out, action_url); 965 try out.appendSlice(allocator, "\" method=\"post\""); 966 // an empty action must not POST — block it and send the input to the TUI instead 967 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 968 try out.appendSlice(allocator, ">"); 969 970 // form.focus.children was populated by addChild, which flattens the 971 // whole subtree into one map — so descendants (inputs + the submit 972 // button) all appear here. positions on form.focus are relative to 973 // the form, so we look up absolute rects via root_focus for layout. 974 var inner_iter = child.focus.children.iterator(); 975 while (inner_iter.next()) |inner_entry| { 976 const inner_id = inner_entry.key_ptr.*; 977 const root_child = root_focus.children.get(inner_id) orelse continue; 978 const r = root_child.rect; 979 switch (root_child.focus.kind) { 980 .text_input, .text_input_password => { 981 const ti = session.text_inputs.get(inner_id) orelse continue; 982 const inner_left = r.x + 1; 983 const inner_top = r.y + 1; 984 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 985 986 try out.appendSlice(allocator, "<input type=\""); 987 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 988 try out.appendSlice(allocator, "\" data-focus-id=\""); 989 var id_buf: [32]u8 = undefined; 990 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 991 if (ti.options.name.len > 0) { 992 try out.appendSlice(allocator, "\" name=\""); 993 try appendEscapedHtml(allocator, &out, ti.options.name); 994 } 995 // never the live content as the `value`: the browser tracks user 996 // input natively, and including the wasm-side value here would make 997 // the overlay HTML differ on every keystroke — that would trip the 998 // diff in _setOverlay and rebuild the <input>, eating the user's 999 // caret. a page-constant initial value is safe. 1000 if (session.input_values.get(inner_id)) |value| { 1001 try out.appendSlice(allocator, "\" value=\""); 1002 try appendEscapedHtml(allocator, &out, value); 1003 } 1004 try out.appendSlice(allocator, "\" style=\"left:"); 1005 var pos_buf: [64]u8 = undefined; 1006 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 })); 1007 try out.appendSlice(allocator, "\">"); 1008 }, 1009 .text_area => { 1010 const ti = session.text_inputs.get(inner_id) orelse continue; 1011 const inner_left = r.x + 1; 1012 const inner_top = r.y + 1; 1013 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1014 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1015 1016 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1017 var id_buf: [32]u8 = undefined; 1018 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1019 if (ti.options.name.len > 0) { 1020 try out.appendSlice(allocator, "\" name=\""); 1021 try appendEscapedHtml(allocator, &out, ti.options.name); 1022 } 1023 // like the input above, only a page-constant initial value 1024 // inside: the browser tracks the live value and the 1025 // overlay diff must stay stable across keystrokes 1026 try out.appendSlice(allocator, "\" style=\"left:"); 1027 var pos_buf: [128]u8 = undefined; 1028 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 })); 1029 try out.appendSlice(allocator, "\">"); 1030 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1031 try out.appendSlice(allocator, "</textarea>"); 1032 }, 1033 .custom => |custom| { 1034 if (std.mem.eql(u8, "submit", custom)) { 1035 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1036 var id_buf: [32]u8 = undefined; 1037 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1038 try out.appendSlice(allocator, "\" style=\"left:"); 1039 var pos_buf: [128]u8 = undefined; 1040 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 })); 1041 try out.appendSlice(allocator, "\"></button>"); 1042 } 1043 }, 1044 else => {}, 1045 } 1046 } 1047 1048 try out.appendSlice(allocator, "</form>"); 1049 } 1050 1051 return try out.toOwnedSlice(allocator); 1052 } 1053 1054 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1055 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1056 return b == null; 1057 } 1058 1059 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1060 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1061 // empty slice when neither is set. 1062 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1063 if (fg == null and bg == null) return buf[0..0]; 1064 const prefix = " style=\""; 1065 @memcpy(buf[0..prefix.len], prefix); 1066 var i: usize = prefix.len; 1067 if (fg) |c| { 1068 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]; 1069 i += s.len; 1070 } 1071 if (bg) |c| { 1072 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]; 1073 i += s.len; 1074 } 1075 buf[i] = '"'; 1076 i += 1; 1077 return buf[0..i]; 1078 } 1079 1080 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1081 for (input) |ch| { 1082 switch (ch) { 1083 '&' => try out.appendSlice(allocator, "&amp;"), 1084 '<' => try out.appendSlice(allocator, "&lt;"), 1085 '>' => try out.appendSlice(allocator, "&gt;"), 1086 '"' => try out.appendSlice(allocator, "&quot;"), 1087 '\'' => try out.appendSlice(allocator, "&#39;"), 1088 else => try out.append(allocator, ch), 1089 } 1090 } 1091 } 1092 1093 // --- helpers -------------------------------------------------------------- 1094 1095 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1096 var iter = request.iterateHeaders(); 1097 while (iter.next()) |header| { 1098 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1099 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1100 while (pairs.next()) |pair| { 1101 const trimmed = std.mem.trim(u8, pair, " \t"); 1102 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1103 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1104 return trimmed[eq + 1 ..]; 1105 } 1106 } 1107 } 1108 return null; 1109 } 1110 1111 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1112 var iter = std.mem.splitScalar(u8, body, '&'); 1113 while (iter.next()) |pair| { 1114 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1115 if (std.mem.eql(u8, pair[0..eq], key)) { 1116 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1117 } 1118 } 1119 return null; 1120 } 1121 1122 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1123 var out: std.ArrayList(u8) = .empty; 1124 errdefer out.deinit(allocator); 1125 var i: usize = 0; 1126 while (i < encoded.len) : (i += 1) { 1127 switch (encoded[i]) { 1128 '+' => try out.append(allocator, ' '), 1129 '%' => { 1130 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1131 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1132 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1133 try out.append(allocator, hi * 16 + lo); 1134 i += 2; 1135 }, 1136 else => try out.append(allocator, encoded[i]), 1137 } 1138 } 1139 return try out.toOwnedSlice(allocator); 1140 } 1141 1142 // disk-backed web session store. each login mints a random, opaque token 1143 // (not the user's id) that is stored as a file named by the token hex, whose 1144 // contents are the raw user_id bytes. authenticating a request is a lookup of 1145 // the cookie's token; logout deletes the file, revoking the session. there is 1146 // deliberately no expiry — a session lives until logout. 1147 pub const SessionStore = struct { 1148 io: std.Io, 1149 dir: std.Io.Dir, 1150 1151 pub const token_hex_len = evt.event_id_size * 2; 1152 1153 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1154 try data_dir.createDirPath(io, "sessions"); 1155 const dir = try data_dir.openDir(io, "sessions", .{}); 1156 return .{ .io = io, .dir = dir }; 1157 } 1158 1159 pub fn deinit(self: SessionStore) void { 1160 self.dir.close(self.io); 1161 } 1162 1163 // mint a new session for user_id, returning the token hex to set as the 1164 // cookie value. 1165 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1166 var token: [evt.event_id_size]u8 = undefined; 1167 self.io.random(&token); 1168 const token_hex = std.fmt.bytesToHex(token, .lower); 1169 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1170 defer file.close(self.io); 1171 try file.writeStreamingAll(self.io, user_id); 1172 return token_hex; 1173 } 1174 1175 // resolve a cookie's token to its user_id. returns false (logged out) for a 1176 // missing, malformed, or unknown token. 1177 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1178 if (!isToken(token_hex)) return false; 1179 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1180 defer file.close(self.io); 1181 var storage: [evt.event_id_size]u8 = undefined; 1182 var file_reader = file.reader(self.io, &storage); 1183 file_reader.interface.readSliceAll(out) catch return false; 1184 return true; 1185 } 1186 1187 // revoke a session. a no-op for a missing or malformed token. 1188 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1189 if (!isToken(token_hex)) return; 1190 self.dir.deleteFile(self.io, token_hex) catch {}; 1191 } 1192 1193 // a token is exactly token_hex_len hex chars. validating before using the 1194 // value as a path keeps attacker-supplied cookies from escaping the 1195 // sessions dir (e.g. via "/" or ".." bytes). 1196 fn isToken(token_hex: []const u8) bool { 1197 if (token_hex.len != token_hex_len) return false; 1198 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1199 return true; 1200 } 1201 }; 1202