╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2076 for (direct.items) |id| { 2077 const child = focus.children.get(id) orelse continue; 2078 const info = child.focus.scroll orelse continue; 2079 const r = child.rect; 2080 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2081 // when that axis actually overflows. the other axis is clipped (hidden), 2082 // matching how the terminal Scroll handles its non-scrolling axis. 2083 const overflow = switch (info.direction) { 2084 .vert => "overflow-x:hidden;overflow-y:auto", 2085 .horiz => "overflow-x:auto;overflow-y:hidden", 2086 .both => "overflow:auto", 2087 }; 2088 // the id carries a content version so JS preserves the native scroll 2089 // position across re-renders of the same content but resets it when the 2090 // content is replaced — e.g. selecting a different commit. the widget's 2091 // scroll offset (in cells) rides along so JS can apply it when it has no 2092 // preserved position, letting a wasm-side scrollToRect (the files list 2093 // scrolling to its selected row on page load) reach the browser. 2094 var buf: [256]u8 = undefined; 2095 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 2096 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2097 try output.appendSlice(allocator, "</div>"); 2098 } 2099 } 2100 2101 const form_prefix = "form:"; 2102 const form_id_prefix = "haxy-form-"; 2103 2104 fn formAction(focus: *const Focus) ?[]const u8 { 2105 return switch (focus.kind) { 2106 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2107 else => null, 2108 }; 2109 } 2110 2111 // find the form ancestor of a flattened focus-tree child. html's `form` 2112 // attribute then associates the control with that form without requiring the 2113 // form and control to share a DOM parent. 2114 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2115 var id = focus_id; 2116 while (root_focus.children.get(id)) |child| { 2117 const parent_id = child.parent_id; 2118 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2119 const parent = root_focus.children.get(parent_id) orelse return null; 2120 if (formAction(parent.focus) != null) return parent_id; 2121 id = parent_id; 2122 } 2123 return null; 2124 } 2125 2126 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2127 const form_id = formOwner(root_focus, focus_id) orelse return; 2128 var buf: [64]u8 = undefined; 2129 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2130 } 2131 2132 fn renderPanelControls( 2133 allocator: std.mem.Allocator, 2134 output: *std.ArrayList(u8), 2135 focus: *Focus, 2136 session: *ui.Session, 2137 root_focus: *Focus, 2138 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2139 ) !void { 2140 var iter = focus.children.iterator(); 2141 while (iter.next()) |entry| { 2142 const id = entry.key_ptr.*; 2143 if (excluded.contains(id)) continue; 2144 const child = entry.value_ptr.*; 2145 const r = child.rect; 2146 2147 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2148 2149 switch (child.focus.kind) { 2150 .text_input, .text_input_password, .text_area => { 2151 const ti = session.text_inputs.get(id) orelse continue; 2152 2153 const inner_left = r.x + 1; 2154 const inner_top = r.y + 1; 2155 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2156 const preserve = !ti.options.read_only; 2157 2158 if (child.focus.kind == .text_area) { 2159 const value = try ti.text(allocator); 2160 defer allocator.free(value); 2161 var id_buf: [128]u8 = undefined; 2162 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2163 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2164 try appendFormAttribute(allocator, output, root_focus, id); 2165 if (ti.options.name.len > 0) { 2166 try output.appendSlice(allocator, " name=\""); 2167 try appendEscapedHtml(allocator, output, ti.options.name); 2168 try output.append(allocator, '"'); 2169 } 2170 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2171 var pos_buf: [128]u8 = undefined; 2172 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2173 try appendEscapedHtml(allocator, output, value); 2174 try output.appendSlice(allocator, "</textarea>"); 2175 continue; 2176 } 2177 2178 var id_buf: [160]u8 = undefined; 2179 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2180 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2181 try appendFormAttribute(allocator, output, root_focus, id); 2182 if (ti.options.name.len > 0) { 2183 try output.appendSlice(allocator, " name=\""); 2184 try appendEscapedHtml(allocator, output, ti.options.name); 2185 try output.append(allocator, '"'); 2186 } 2187 if (child.focus.kind != .text_input_password) { 2188 const value = try ti.text(allocator); 2189 defer allocator.free(value); 2190 try output.appendSlice(allocator, " value=\""); 2191 try appendEscapedHtml(allocator, output, value); 2192 try output.append(allocator, '"'); 2193 } 2194 var pos_buf: [96]u8 = undefined; 2195 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2196 }, 2197 .custom => |custom| { 2198 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2199 if (formOwner(root_focus, id) == null) continue; 2200 var id_buf: [128]u8 = undefined; 2201 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2202 try appendFormAttribute(allocator, output, root_focus, id); 2203 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2204 try output.appendSlice(allocator, " formaction=\""); 2205 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2206 try output.append(allocator, '"'); 2207 } 2208 var pos_buf: [128]u8 = undefined; 2209 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2210 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2211 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2212 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2213 var id_buf: [128]u8 = undefined; 2214 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2215 } 2216 }, 2217 else => {}, 2218 } 2219 } 2220 } 2221 2222 // emit hidden form owners beside the rendered panels. their controls point 2223 // back here with the standard HTML `form` attribute. 2224 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2225 // the focus child map preserves insertion order, which matches the order 2226 // widgets were added in code 2227 var iter = root_focus.children.iterator(); 2228 while (iter.next()) |entry| { 2229 const child = entry.value_ptr.*; 2230 const action_url = formAction(child.focus) orelse continue; 2231 2232 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2233 var id_buf: [96]u8 = undefined; 2234 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2235 try appendEscapedHtml(allocator, output, action_url); 2236 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2237 } 2238 } 2239 2240 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2241 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2242 return b == null; 2243 } 2244 2245 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2246 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2247 // empty slice when neither is set. 2248 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2249 if (fg == null and bg == null) return buf[0..0]; 2250 const prefix = " style=\""; 2251 @memcpy(buf[0..prefix.len], prefix); 2252 var i: usize = prefix.len; 2253 if (fg) |c| { 2254 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]; 2255 i += s.len; 2256 } 2257 if (bg) |c| { 2258 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]; 2259 i += s.len; 2260 } 2261 buf[i] = '"'; 2262 i += 1; 2263 return buf[0..i]; 2264 } 2265 2266 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2267 for (input) |ch| { 2268 switch (ch) { 2269 '&' => try out.appendSlice(allocator, "&amp;"), 2270 '<' => try out.appendSlice(allocator, "&lt;"), 2271 '>' => try out.appendSlice(allocator, "&gt;"), 2272 '"' => try out.appendSlice(allocator, "&quot;"), 2273 '\'' => try out.appendSlice(allocator, "&#39;"), 2274 else => try out.append(allocator, ch), 2275 } 2276 } 2277 } 2278 2279 // --- helpers -------------------------------------------------------------- 2280 2281 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2282 var iter = request.iterateHeaders(); 2283 while (iter.next()) |header| { 2284 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2285 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2286 while (pairs.next()) |pair| { 2287 const trimmed = std.mem.trim(u8, pair, " \t"); 2288 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2289 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2290 return trimmed[eq + 1 ..]; 2291 } 2292 } 2293 } 2294 return null; 2295 } 2296 2297 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2298 var iter = std.mem.splitScalar(u8, body, '&'); 2299 while (iter.next()) |pair| { 2300 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2301 if (std.mem.eql(u8, pair[0..eq], key)) { 2302 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2303 } 2304 } 2305 return null; 2306 } 2307 2308 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2309 var buffer: [256]u8 = undefined; 2310 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2311 } 2312 2313 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2314 var out: std.ArrayList(u8) = .empty; 2315 errdefer out.deinit(allocator); 2316 var i: usize = 0; 2317 while (i < encoded.len) : (i += 1) { 2318 switch (encoded[i]) { 2319 '+' => try out.append(allocator, ' '), 2320 '%' => { 2321 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2322 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2323 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2324 try out.append(allocator, hi * 16 + lo); 2325 i += 2; 2326 }, 2327 else => try out.append(allocator, encoded[i]), 2328 } 2329 } 2330 return try out.toOwnedSlice(allocator); 2331 } 2332 2333 // disk-backed web session store. each login mints a random, opaque token 2334 // (not the user's id) that is stored as a file named by the token hex, whose 2335 // contents are the raw user_id bytes. authenticating a request is a lookup of 2336 // the cookie's token; logout deletes the file, revoking the session. there is 2337 // deliberately no expiry — a session lives until logout. form failures use 2338 // files in the flash subdirectory that the redirected GET consumes. the 2339 // directory is cleared whenever the server starts. 2340 pub const SessionStore = struct { 2341 io: std.Io, 2342 dir: std.Io.Dir, 2343 flash_dir: std.Io.Dir, 2344 auto_login: ?[token_hex_len]u8, 2345 2346 pub const token_hex_len = evt.event_id_size * 2; 2347 2348 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2349 try data_dir.createDirPath(io, "sessions"); 2350 const dir = try data_dir.openDir(io, "sessions", .{}); 2351 errdefer dir.close(io); 2352 try dir.deleteTree(io, "flash"); 2353 try dir.createDirPath(io, "flash"); 2354 const flash_dir = try dir.openDir(io, "flash", .{}); 2355 errdefer flash_dir.close(io); 2356 const auto_login = blk: { 2357 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2358 defer file.close(io); 2359 var token: [token_hex_len]u8 = undefined; 2360 var storage: [token_hex_len]u8 = undefined; 2361 var reader = file.reader(io, &storage); 2362 reader.interface.readSliceAll(&token) catch break :blk null; 2363 break :blk token; 2364 }; 2365 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2366 } 2367 2368 pub fn deinit(self: SessionStore) void { 2369 self.flash_dir.close(self.io); 2370 self.dir.close(self.io); 2371 } 2372 2373 // mint a new session for user_id, returning the token hex to set as the 2374 // cookie value. 2375 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2376 var token: [evt.event_id_size]u8 = undefined; 2377 self.io.random(&token); 2378 const token_hex = std.fmt.bytesToHex(token, .lower); 2379 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2380 defer file.close(self.io); 2381 try file.writeStreamingAll(self.io, user_id); 2382 return token_hex; 2383 } 2384 2385 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2386 var token: [evt.event_id_size]u8 = undefined; 2387 self.io.random(&token); 2388 const token_hex = std.fmt.bytesToHex(token, .lower); 2389 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2390 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2391 defer file.close(self.io); 2392 2393 var json: std.Io.Writer.Allocating = .init(allocator); 2394 defer json.deinit(); 2395 try std.json.Stringify.value(value, .{}, &json.writer); 2396 try file.writeStreamingAll(self.io, json.written()); 2397 return token_hex; 2398 } 2399 2400 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2401 if (!isToken(token_hex)) return null; 2402 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2403 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2404 defer file.close(self.io); 2405 2406 var storage: [4096]u8 = undefined; 2407 var reader = file.reader(self.io, &storage); 2408 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2409 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2410 } 2411 2412 // resolve a cookie's token to its user_id. returns false (logged out) for a 2413 // missing, malformed, or unknown token. 2414 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2415 if (!isToken(token_hex)) return false; 2416 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2417 defer file.close(self.io); 2418 var storage: [evt.event_id_size]u8 = undefined; 2419 var file_reader = file.reader(self.io, &storage); 2420 file_reader.interface.readSliceAll(out) catch return false; 2421 return true; 2422 } 2423 2424 // revoke a session. a no-op for a missing or malformed token. 2425 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2426 if (!isToken(token_hex)) return; 2427 self.dir.deleteFile(self.io, token_hex) catch {}; 2428 } 2429 2430 // leave `token_hex`'s session for visitors arriving without one. only the 2431 // `try` fixture writes one. the name can't collide with a session token. 2432 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2433 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2434 defer file.close(self.io); 2435 try file.writeStreamingAll(self.io, token_hex); 2436 } 2437 2438 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2439 out.* = self.auto_login orelse return false; 2440 return true; 2441 } 2442 2443 const auto_login_name = "auto-login"; 2444 2445 // a token is exactly token_hex_len hex chars. validating before using the 2446 // value as a path keeps attacker-supplied cookies from escaping the 2447 // sessions dir (e.g. via "/" or ".." bytes). 2448 fn isToken(token_hex: []const u8) bool { 2449 if (token_hex.len != token_hex_len) return false; 2450 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2451 return true; 2452 } 2453 }; 2454