╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2232 const labels = try parseFormField(aa, body, "labels"); 2233 2234 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 2235 // textarea line breaks to CRLF 2236 var hunks: std.ArrayList([]const u8) = .empty; 2237 var hunk_index: usize = 0; 2238 while (true) : (hunk_index += 1) { 2239 const name = try aa.print("d{d}", .{hunk_index}); 2240 const submitted = (try parseFormField(aa, body, name)) orelse break; 2241 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 2242 } 2243 2244 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 2245 try request.respond("thread not found", .{ 2246 .status = .not_found, 2247 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2248 }); 2249 return; 2250 } 2251 const route = routeFromUrl(host, base) orelse { 2252 try request.respond("thread not found", .{ 2253 .status = .not_found, 2254 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2255 }); 2256 return; 2257 }; 2258 const theirs: []const u8 = switch (route) { 2259 .repo_patches => |*patch| patch.theirs.slice(), 2260 .repo_issues => "", 2261 else => unreachable, 2262 }; 2263 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 2264 2265 (switch (parts.thread_kind) { 2266 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2267 .title = title, 2268 .labels = labels, 2269 .hunks = hunks.items, 2270 } }, author), 2271 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2272 .title = title, 2273 .labels = labels, 2274 .hunks = hunks.items, 2275 .theirs = theirs, 2276 } }, author), 2277 else => unreachable, 2278 }) catch |err| switch (err) { 2279 error.NotFound => { 2280 try request.respond(not_found, .{ 2281 .status = .not_found, 2282 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2283 }); 2284 return; 2285 }, 2286 // invalid fields send the user back to the resolve form 2287 error.InvalidFields => { 2288 const form_location = try allocator.print("{s}/resolve", .{base}); 2289 defer allocator.free(form_location); 2290 try request.respond("", .{ 2291 .status = .see_other, 2292 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2293 }); 2294 return; 2295 }, 2296 else => |e| return e, 2297 }; 2298 2299 try request.respond("", .{ 2300 .status = .see_other, 2301 .extra_headers = &.{.{ .name = "location", .value = base }}, 2302 }); 2303 } 2304 2305 // the posted path drops the action's own segment, so the route it parses is 2306 // the undo page the action applies to 2307 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host) !void { 2308 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 2309 if (route != .repo_undo) return respondRepoNotFound(request); 2310 const target = route.repo_undo; 2311 var arena = std.heap.ArenaAllocator.init(allocator); 2312 defer arena.deinit(); 2313 const repo_base = if (target.name.len == 0) "" else try arena.allocator().print("/{s}", .{target.name.slice()}); 2314 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner, null)) orelse return; 2315 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 2316 defer resolved.deinit(allocator); 2317 ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)) catch |err| switch (err) { 2318 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 2319 else => return err, 2320 }; 2321 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 2322 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 2323 } 2324 2325 fn handleSync( 2326 io: std.Io, 2327 request: *std.http.Server.Request, 2328 allocator: std.mem.Allocator, 2329 base: []const u8, 2330 source: ui.RepoSource, 2331 ) !void { 2332 if (base.len != 0) { 2333 try request.respond("not found", .{ 2334 .status = .not_found, 2335 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2336 }); 2337 return; 2338 } 2339 2340 var owned_failure: ?[]u8 = null; 2341 defer if (owned_failure) |message| allocator.free(message); 2342 const failure: ?[]const u8 = blk: { 2343 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 2344 break :blk owned_failure; 2345 }; 2346 if (failure) |message| { 2347 var encoded: std.Io.Writer.Allocating = .init(allocator); 2348 defer encoded.deinit(); 2349 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 2350 fn isUnreserved(c: u8) bool { 2351 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2352 } 2353 }.isUnreserved); 2354 const cookie = try allocator.print( 2355 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 2356 .{encoded.written()}, 2357 ); 2358 defer allocator.free(cookie); 2359 try request.respond("", .{ 2360 .status = .see_other, 2361 .extra_headers = &.{ 2362 .{ .name = "location", .value = "/events" }, 2363 .{ .name = "set-cookie", .value = cookie }, 2364 }, 2365 }); 2366 return; 2367 } 2368 2369 try request.respond("", .{ 2370 .status = .see_other, 2371 .extra_headers = &.{ 2372 .{ .name = "location", .value = "/events" }, 2373 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 2374 }, 2375 }); 2376 } 2377 2378 fn renderIndexHtml( 2379 io: std.Io, 2380 allocator: std.mem.Allocator, 2381 host: Host, 2382 session_token: ?[]const u8, 2383 session_data: ui.Session.Data, 2384 ) ![]const u8 { 2385 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 2386 2387 var page_arena = std.heap.ArenaAllocator.init(allocator); 2388 defer page_arena.deinit(); 2389 2390 // the server admin repo must outlive the page build, since the session's 2391 // moment reads from it. 2392 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 2393 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 2394 2395 var session = switch (host) { 2396 .server => |server| blk: { 2397 // open the admin repo to read live user/repo data. 2398 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2399 const repo = if (repo_maybe) |*repo| repo else unreachable; 2400 var session = try ui.Session.init(&page_arena, repo, session_data); 2401 // the session dropped a user whose account was removed, so revoke 2402 // the token that named them 2403 if (session_token) |token| { 2404 if (session.data.user_id == null) server.session_store.remove(token); 2405 } 2406 // give the page builders filesystem access to the on-disk repos (a 2407 // sibling "users" dir next to the admin repo) so the Repo page can 2408 // read its files. 2409 session.users_dir = server.users_dir; 2410 break :blk session; 2411 }, 2412 .local => |local| ui.Session{ 2413 .data = session_data, 2414 .arena = &page_arena, 2415 .page_arena = &page_arena, 2416 .local = local, 2417 }, 2418 }; 2419 session.io = io; 2420 session.data.now = std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse return error.TimestampOutOfRange; 2421 2422 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 2423 var root = try ui.initRoot(allocator, &page, &session); 2424 defer root.deinit(allocator); 2425 2426 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 2427 2428 const content = try generateHtml(allocator, &root, &session); 2429 defer allocator.free(content); 2430 2431 // serialize the snapshot so the wasm side can parse it back without making 2432 // a second request. it's embedded raw in a <script type="application/json"> 2433 // block, whose content is raw text terminated only by "</script". in json, 2434 // '<' appears solely inside string values, so escaping every '<' (and '>' 2435 // for good measure) to its \uXXXX form yields equivalent json that can't 2436 // break out of the tag. 2437 var json: std.Io.Writer.Allocating = .init(allocator); 2438 defer json.deinit(); 2439 try std.json.Stringify.value(snapshot, .{}, &json.writer); 2440 2441 var json_escaped: std.ArrayList(u8) = .empty; 2442 defer json_escaped.deinit(allocator); 2443 for (json.written()) |c| switch (c) { 2444 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 2445 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 2446 else => try json_escaped.append(allocator, c), 2447 }; 2448 2449 var out: std.ArrayList(u8) = .empty; 2450 errdefer out.deinit(allocator); 2451 { 2452 var cursor: usize = 0; 2453 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 2454 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 2455 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 2456 }) |sub| { 2457 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 2458 try out.appendSlice(allocator, template[cursor..idx]); 2459 try out.appendSlice(allocator, sub.replacement); 2460 cursor = idx + sub.needle.len; 2461 } 2462 try out.appendSlice(allocator, template[cursor..]); 2463 } 2464 return try out.toOwnedSlice(allocator); 2465 } 2466 2467 fn findEmbed(request_path: []const u8) ?Embed { 2468 // embeds are matched before pages, so a dot keeps them from claiming a username or tab 2469 comptime for (embeds) |embed| { 2470 if (std.mem.indexOfScalar(u8, embed.path, '.') == null) @compileError("embed path needs a '.' so it can't shadow a page: " ++ embed.path); 2471 }; 2472 if (request_path.len < 2 or request_path[0] != '/') return null; 2473 const path = request_path[1..]; 2474 2475 for (embeds) |embed| { 2476 if (std.mem.eql(u8, path, embed.path)) return embed; 2477 } 2478 return null; 2479 } 2480 2481 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 2482 // own absolutely-positioned, natively-scrollable <div> holding its full content, 2483 // rendered recursively so nested scrolls work. 2484 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 2485 const grid = root.getGrid() orelse return error.MissingGrid; 2486 const root_focus = root.getFocus(); 2487 2488 var out: std.ArrayList(u8) = .empty; 2489 errdefer out.deinit(allocator); 2490 2491 switch (root.*) { 2492 .background => |*background| { 2493 if (background.art.getGrid()) |art| { 2494 try out.print(allocator, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch;opacity:{d}%\">", .{ grid.size.width -| art.size.width, ui.widget.AnsiBackground.art_opacity }); 2495 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 2496 try out.appendSlice(allocator, "</div>"); 2497 } 2498 }, 2499 else => {}, 2500 } 2501 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 2502 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 2503 try out.appendSlice(allocator, "</div>"); 2504 try renderForms(allocator, &out, root_focus); 2505 return try out.toOwnedSlice(allocator); 2506 } 2507 2508 // render one panel — a focus subtree and its content grid — as HTML, recursing 2509 // once per web-native Scroll inside it. the root panel is the whole page; each 2510 // Scroll becomes a nested, natively-scrollable div holding its full content. 2511 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 2512 // then the child scroll divs over those holes. 2513 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 2514 // `direct` is this panel's scroll children, each drawn as an overlaid div. 2515 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 2516 // plus their descendants, which the focus tree flattens into this panel's 2517 // children): the cell hit-test below skips them so this panel doesn't claim 2518 // cells that are really rendered inside a child scroll's own panel. 2519 // (scrolls aren't nested in practice, so every scroll child is direct here.) 2520 var direct: std.ArrayList(usize) = .empty; 2521 defer direct.deinit(allocator); 2522 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 2523 defer excluded.deinit(allocator); 2524 { 2525 var it = focus.children.iterator(); 2526 while (it.next()) |e| { 2527 if (e.value_ptr.focus.scroll == null) continue; 2528 try direct.append(allocator, e.key_ptr.*); 2529 try excluded.put(allocator, e.key_ptr.*, {}); 2530 var mit = e.value_ptr.focus.children.iterator(); 2531 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 2532 } 2533 } 2534 2535 // the HTML element a run of cells is wrapped in, chosen from the cell's 2536 // focusable kind 2537 const CellTag = union(enum) { 2538 span, // clickable focusable cell 2539 a: []const u8, // clickable focusable link 2540 plain, // non-focusable, colored 2541 2542 const a_prefix = "a:"; 2543 // an "in-page" anchor: rendered as a real <a href> so it works with js 2544 // disabled, but wasm handles it without navigating. 2545 fn init(str: []const u8) @This() { 2546 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 2547 return .{ .a = str[ui.raw_link_prefix.len..] }; 2548 } 2549 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 2550 return .{ .a = str[ui.in_page_link_prefix.len..] }; 2551 } 2552 if (std.mem.startsWith(u8, str, a_prefix)) { 2553 return .{ .a = str[a_prefix.len..] }; 2554 } 2555 return .span; 2556 } 2557 2558 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 2559 var id_buf: [32]u8 = undefined; 2560 switch (self) { 2561 .span => { 2562 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 2563 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2564 try out.appendSlice(alloc, "\""); 2565 try out.appendSlice(alloc, style_attr); 2566 try out.appendSlice(alloc, ">"); 2567 }, 2568 .a => |href| { 2569 // tabindex=-1 keeps these out of the browser's tab order 2570 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 2571 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2572 try out.appendSlice(alloc, "\" href=\""); 2573 try appendEscapedHtml(alloc, out, href); 2574 try out.appendSlice(alloc, "\""); 2575 try out.appendSlice(alloc, style_attr); 2576 try out.appendSlice(alloc, ">"); 2577 }, 2578 .plain => { 2579 try out.appendSlice(alloc, "<span"); 2580 try out.appendSlice(alloc, style_attr); 2581 try out.appendSlice(alloc, ">"); 2582 }, 2583 } 2584 } 2585 2586 fn closeTag(self: @This()) []const u8 { 2587 return switch (self) { 2588 .span, .plain => "</span>", 2589 .a => "</a>", 2590 }; 2591 } 2592 }; 2593 2594 // the focusable owning each cell, among this panel's own (skipping any 2595 // that belong to a child scroll, whose cells are drawn in their own panel). 2596 // claimed in focus order, so the first focusable over a cell keeps it. 2597 // looking every focusable up for every cell is quadratic in a long list. 2598 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2599 defer allocator.free(owners); 2600 @memset(owners, null); 2601 { 2602 var it = focus.children.iterator(); 2603 while (it.next()) |entry| { 2604 const child = entry.value_ptr.*; 2605 if (child.focus.mode != .all) continue; 2606 if (excluded.contains(entry.key_ptr.*)) continue; 2607 const r = child.rect; 2608 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2609 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2610 const owner = &owners[y * grid.size.width + x]; 2611 if (owner.* == null) owner.* = entry.key_ptr.*; 2612 } 2613 } 2614 } 2615 } 2616 2617 // the cells are the volatile part of a panel. js replaces this one subtree 2618 // wholesale while retaining the panel's native controls and scroll shells. 2619 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2620 2621 // emit this panel's grid as rows of text, coalescing adjacent cells that 2622 // share a focus id and style into one tag (a clickable span, a link, or a 2623 // plain styled span). cells under a child scroll keep only their background. 2624 // a cell's own link is an anchor nested in that tag. 2625 for (0..grid.size.height) |y| { 2626 var cur_id: ?usize = null; 2627 var cur_style: Grid.Style = .{}; 2628 var open_tag: ?CellTag = null; 2629 var open_link: ?[]const u8 = null; 2630 var first = true; 2631 for (0..grid.size.width) |x| { 2632 const cell = (try grid.cell(x, y)).*; 2633 // a cell covered by a child scroll's viewport is drawn by that scroll's 2634 // own div, so blank its glyph and make it non-clickable here — but keep 2635 // its background, so the backdrop still shows through the scroll's 2636 // transparent div instead of a bare hole. 2637 const covered_by_scroll = blk: { 2638 for (direct.items) |id| { 2639 const r = (focus.children.get(id) orelse continue).rect; 2640 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; 2641 } 2642 break :blk false; 2643 }; 2644 // the focusable owning the cell at (x, y); none for a covered cell. 2645 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2646 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2647 2648 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2649 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2650 open_link = null; 2651 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2652 2653 var new_tag: ?CellTag = null; 2654 if (cell_id) |id| { 2655 if (focus.children.get(id)) |child| { 2656 new_tag = switch (child.focus.kind) { 2657 .custom => |custom| CellTag.init(custom), 2658 else => .span, 2659 }; 2660 } 2661 } 2662 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2663 2664 if (new_tag) |t| { 2665 var style_buf: [192]u8 = undefined; 2666 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2667 } 2668 2669 open_tag = new_tag; 2670 cur_id = cell_id; 2671 cur_style = style; 2672 first = false; 2673 } 2674 2675 // an anchor can't nest in another, so a link tag's cells skip theirs 2676 const in_anchor = if (open_tag) |t| t == .a else false; 2677 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2678 if (!sameLink(link, open_link)) { 2679 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2680 if (link) |url| { 2681 // a page path opens in this tab, any other url in a new one 2682 try output.appendSlice(allocator, if (url[0] == '/') 2683 "<a class=\"cell-link\" tabindex=\"-1\" href=\"" 2684 else 2685 "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2686 try appendEscapedHtml(allocator, output, url); 2687 try output.appendSlice(allocator, "\">"); 2688 } 2689 open_link = link; 2690 } 2691 2692 if (covered_by_scroll) { 2693 try appendEscapedHtml(allocator, output, " "); 2694 } else if (cell.continuation) { 2695 // the wide rune to the left was emitted 2ch wide, covering this column 2696 } else if (cell.rune) |rune| { 2697 var encoded: [4]u8 = undefined; 2698 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2699 const rune_text = encoded[0..encoded_len]; 2700 // a double-width rune is pinned inside a 2ch span so the 2701 // fallback glyph's advance width can't shift the rest of the row 2702 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2703 if (wide) { 2704 try output.appendSlice(allocator, "<span class=\"w2\">"); 2705 try appendEscapedHtml(allocator, output, rune_text); 2706 try output.appendSlice(allocator, "</span>"); 2707 } else { 2708 try appendEscapedHtml(allocator, output, rune_text); 2709 } 2710 } else { 2711 try appendEscapedHtml(allocator, output, " "); 2712 } 2713 } 2714 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2715 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2716 try output.append(allocator, '\n'); 2717 } 2718 try output.appendSlice(allocator, "</div>"); 2719 2720 // native controls live in their panel, beside the replaceable cells. their 2721 // stable keys let JS update layout without recreating their DOM nodes, and 2722 // being actual descendants of a scroll gives them native movement/clipping. 2723 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2724 2725 // each child scroll becomes a natively-scrollable div positioned over its 2726 // viewport, holding its full content rendered recursively. 2727 for (direct.items) |id| { 2728 const child = focus.children.get(id) orelse continue; 2729 const info = child.focus.scroll orelse continue; 2730 const r = child.rect; 2731 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2732 // when that axis actually overflows. the other axis is clipped (hidden), 2733 // matching how the terminal Scroll handles its non-scrolling axis. 2734 const overflow = switch (info.direction) { 2735 .vert => "overflow-x:hidden;overflow-y:auto", 2736 .horiz => "overflow-x:auto;overflow-y:hidden", 2737 .both => "overflow:auto", 2738 }; 2739 // the id carries a content version so JS preserves the native scroll 2740 // position across re-renders of the same content but resets it when the 2741 // content is replaced — e.g. selecting a different commit. the widget's 2742 // scroll offset (in cells) rides along so JS can apply it when it has no 2743 // preserved position, letting a wasm-side scrollToRect (the files list 2744 // scrolling to its selected row on page load) reach the browser. 2745 var buf: [256]u8 = undefined; 2746 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 })); 2747 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2748 try output.appendSlice(allocator, "</div>"); 2749 } 2750 } 2751 2752 const form_prefix = "form:"; 2753 const form_id_prefix = "haxy-form-"; 2754 2755 fn formAction(focus: *const Focus) ?[]const u8 { 2756 return switch (focus.kind) { 2757 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2758 else => null, 2759 }; 2760 } 2761 2762 // find the form ancestor of a flattened focus-tree child. html's `form` 2763 // attribute then associates the control with that form without requiring the 2764 // form and control to share a DOM parent. 2765 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2766 var id = focus_id; 2767 while (root_focus.children.get(id)) |child| { 2768 const parent_id = child.parent_id; 2769 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2770 const parent = root_focus.children.get(parent_id) orelse return null; 2771 if (formAction(parent.focus) != null) return parent_id; 2772 id = parent_id; 2773 } 2774 return null; 2775 } 2776 2777 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2778 const form_id = formOwner(root_focus, focus_id) orelse return; 2779 var buf: [64]u8 = undefined; 2780 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2781 } 2782 2783 fn renderPanelControls( 2784 allocator: std.mem.Allocator, 2785 output: *std.ArrayList(u8), 2786 focus: *Focus, 2787 session: *ui.Session, 2788 root_focus: *Focus, 2789 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2790 ) !void { 2791 var iter = focus.children.iterator(); 2792 while (iter.next()) |entry| { 2793 const id = entry.key_ptr.*; 2794 if (excluded.contains(id)) continue; 2795 const child = entry.value_ptr.*; 2796 const r = child.rect; 2797 2798 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2799 2800 switch (child.focus.kind) { 2801 .text_input, .text_input_password, .text_area => { 2802 const ti = session.text_inputs.get(id) orelse continue; 2803 2804 const inner_left = r.x + 1; 2805 const inner_top = r.y + 1; 2806 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2807 const preserve = !ti.options.read_only; 2808 2809 if (child.focus.kind == .text_area) { 2810 const value = try ti.text(allocator); 2811 defer allocator.free(value); 2812 var id_buf: [128]u8 = undefined; 2813 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2814 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2815 try appendFormAttribute(allocator, output, root_focus, id); 2816 if (ti.options.name.len > 0) { 2817 try output.appendSlice(allocator, " name=\""); 2818 try appendEscapedHtml(allocator, output, ti.options.name); 2819 try output.append(allocator, '"'); 2820 } 2821 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2822 var pos_buf: [128]u8 = undefined; 2823 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 })); 2824 try appendEscapedHtml(allocator, output, value); 2825 try output.appendSlice(allocator, "</textarea>"); 2826 continue; 2827 } 2828 2829 var id_buf: [160]u8 = undefined; 2830 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 })); 2831 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2832 try appendFormAttribute(allocator, output, root_focus, id); 2833 if (ti.options.name.len > 0) { 2834 try output.appendSlice(allocator, " name=\""); 2835 try appendEscapedHtml(allocator, output, ti.options.name); 2836 try output.append(allocator, '"'); 2837 } 2838 if (child.focus.kind != .text_input_password) { 2839 const value = try ti.text(allocator); 2840 defer allocator.free(value); 2841 try output.appendSlice(allocator, " value=\""); 2842 try appendEscapedHtml(allocator, output, value); 2843 try output.append(allocator, '"'); 2844 } 2845 var pos_buf: [96]u8 = undefined; 2846 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 })); 2847 }, 2848 .custom => |custom| { 2849 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2850 if (formOwner(root_focus, id) == null) continue; 2851 var id_buf: [128]u8 = undefined; 2852 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2853 try appendFormAttribute(allocator, output, root_focus, id); 2854 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2855 try output.appendSlice(allocator, " formaction=\""); 2856 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2857 try output.append(allocator, '"'); 2858 } 2859 var pos_buf: [128]u8 = undefined; 2860 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 })); 2861 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2862 // an invisible native radio over the option, checked when the option is its row's selection 2863 const field = custom[ui.radio_prefix.len..]; 2864 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2865 const row = root_focus.children.get(child.parent_id) orelse continue; 2866 var id_buf: [128]u8 = undefined; 2867 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2868 try appendFormAttribute(allocator, output, root_focus, id); 2869 try output.appendSlice(allocator, " name=\""); 2870 try appendEscapedHtml(allocator, output, field[0..separator]); 2871 try output.appendSlice(allocator, "\" value=\""); 2872 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2873 try output.append(allocator, '"'); 2874 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2875 var pos_buf: [128]u8 = undefined; 2876 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2877 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2878 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2879 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2880 var id_buf: [128]u8 = undefined; 2881 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 })); 2882 } 2883 }, 2884 else => {}, 2885 } 2886 } 2887 } 2888 2889 // emit hidden form owners beside the rendered panels. their controls point 2890 // back here with the standard HTML `form` attribute. 2891 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2892 // the focus child map preserves insertion order, which matches the order 2893 // widgets were added in code 2894 var iter = root_focus.children.iterator(); 2895 while (iter.next()) |entry| { 2896 const child = entry.value_ptr.*; 2897 const action_url = formAction(child.focus) orelse continue; 2898 2899 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2900 var id_buf: [96]u8 = undefined; 2901 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2902 try appendEscapedHtml(allocator, output, action_url); 2903 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2904 } 2905 } 2906 2907 // the 16 ansi colors as the browser shows them (xterm's defaults) 2908 const ansi_palette = [16]Grid.Color.Rgb{ 2909 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2910 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2911 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2912 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2913 }; 2914 2915 // resolve any color to rgb: palette colors through the ansi table and the 2916 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2917 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2918 return switch (color) { 2919 .rgb => |c| c, 2920 .ansi => |a| ansi_palette[@backingInt(a)], 2921 .indexed => |n| if (n < 16) 2922 ansi_palette[n] 2923 else if (n < 232) blk: { 2924 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2925 const i = n - 16; 2926 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2927 } else blk: { 2928 const v: u8 = 8 + (n - 232) * 10; 2929 break :blk .{ .r = v, .g = v, .b = v }; 2930 }, 2931 }; 2932 } 2933 2934 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2935 // cell's style into `buf`, omitting whichever color is unset. an inverted 2936 // cell swaps the two, falling back to the page's --fg/--bg variables for 2937 // whichever side is unset. text attributes follow the colors. returns an 2938 // empty slice when nothing is set. 2939 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2940 if (style.eql(.{})) return buf[0..0]; 2941 const prefix = " style=\""; 2942 @memcpy(buf[0..prefix.len], prefix); 2943 var i: usize = prefix.len; 2944 const inverted = style.inverted; 2945 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2946 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2947 const decoration: []const u8 = if (style.underline and style.strikethrough) 2948 "text-decoration:underline line-through;" 2949 else if (style.underline) 2950 "text-decoration:underline;" 2951 else if (style.strikethrough) 2952 "text-decoration:line-through;" 2953 else 2954 ""; 2955 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2956 if (style.bold) "font-weight:bold;" else "", 2957 if (style.italic) "font-style:italic;" else "", 2958 decoration, 2959 if (style.dim) "opacity:.6;" else "", 2960 }) catch return buf[0..0]; 2961 i += attributes.len; 2962 if (i >= buf.len) return buf[0..0]; 2963 buf[i] = '"'; 2964 return buf[0 .. i + 1]; 2965 } 2966 2967 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2968 // the color is unset (nothing when both are). returns the new end, or null 2969 // when it doesn't fit. 2970 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2971 const s = if (color) |c| blk: { 2972 const v = colorRgb(c); 2973 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2974 } else if (fallback) |f| 2975 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2976 else 2977 return i; 2978 return i + s.len; 2979 } 2980 2981 // a cell's link as an href, when it's a page path or a web or mail url 2982 fn webLink(link: ?[]const u8) ?[]const u8 { 2983 const url = link orelse return null; 2984 // a page path, not a protocol-relative url 2985 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2986 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2987 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2988 } 2989 return null; 2990 } 2991 2992 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2993 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2994 return b == null; 2995 } 2996 2997 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2998 for (input) |ch| { 2999 switch (ch) { 3000 '&' => try out.appendSlice(allocator, "&amp;"), 3001 '<' => try out.appendSlice(allocator, "&lt;"), 3002 '>' => try out.appendSlice(allocator, "&gt;"), 3003 '"' => try out.appendSlice(allocator, "&quot;"), 3004 '\'' => try out.appendSlice(allocator, "&#39;"), 3005 else => try out.append(allocator, ch), 3006 } 3007 } 3008 } 3009 3010 // --- helpers -------------------------------------------------------------- 3011 3012 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 3013 var iter = request.iterateHeaders(); 3014 while (iter.next()) |header| { 3015 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 3016 var pairs = std.mem.splitScalar(u8, header.value, ';'); 3017 while (pairs.next()) |pair| { 3018 const trimmed = std.mem.trim(u8, pair, " \t"); 3019 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 3020 if (std.mem.eql(u8, trimmed[0..eq], name)) { 3021 return trimmed[eq + 1 ..]; 3022 } 3023 } 3024 } 3025 return null; 3026 } 3027 3028 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 3029 var iter = std.mem.splitScalar(u8, body, '&'); 3030 while (iter.next()) |pair| { 3031 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 3032 if (std.mem.eql(u8, pair[0..eq], key)) { 3033 return try decodeFormValue(allocator, pair[eq + 1 ..]); 3034 } 3035 } 3036 return null; 3037 } 3038 3039 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 3040 var buffer: [256]u8 = undefined; 3041 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 3042 } 3043 3044 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 3045 var out: std.ArrayList(u8) = .empty; 3046 errdefer out.deinit(allocator); 3047 var i: usize = 0; 3048 while (i < encoded.len) : (i += 1) { 3049 switch (encoded[i]) { 3050 '+' => try out.append(allocator, ' '), 3051 '%' => { 3052 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 3053 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 3054 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 3055 try out.append(allocator, hi * 16 + lo); 3056 i += 2; 3057 }, 3058 else => try out.append(allocator, encoded[i]), 3059 } 3060 } 3061 return try out.toOwnedSlice(allocator); 3062 } 3063 3064 // disk-backed web session store. each login mints a random, opaque token 3065 // (not the user's id) that is stored as a file named by the token hex, whose 3066 // contents are the raw user_id bytes. authenticating a request is a lookup of 3067 // the cookie's token; logout deletes the file, revoking the session. there is 3068 // deliberately no expiry — a session lives until logout. form failures use 3069 // files in the flash subdirectory that the redirected GET consumes. the 3070 // directory is cleared whenever the server starts. 3071 pub const SessionStore = struct { 3072 io: std.Io, 3073 dir: std.Io.Dir, 3074 flash_dir: std.Io.Dir, 3075 auto_login: ?[token_hex_len]u8, 3076 3077 pub const token_hex_len = evt.event_id_size * 2; 3078 3079 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3080 try data_dir.createDirPath(io, "sessions"); 3081 const dir = try data_dir.openDir(io, "sessions", .{}); 3082 errdefer dir.close(io); 3083 try dir.deleteTree(io, "flash"); 3084 try dir.createDirPath(io, "flash"); 3085 const flash_dir = try dir.openDir(io, "flash", .{}); 3086 errdefer flash_dir.close(io); 3087 const auto_login = blk: { 3088 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3089 defer file.close(io); 3090 var token: [token_hex_len]u8 = undefined; 3091 var storage: [token_hex_len]u8 = undefined; 3092 var reader = file.reader(io, &storage); 3093 reader.interface.readSliceAll(&token) catch break :blk null; 3094 break :blk token; 3095 }; 3096 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3097 } 3098 3099 pub fn deinit(self: SessionStore) void { 3100 self.flash_dir.close(self.io); 3101 self.dir.close(self.io); 3102 } 3103 3104 // mint a new session for user_id, returning the token hex to set as the 3105 // cookie value. 3106 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3107 var token: [evt.event_id_size]u8 = undefined; 3108 self.io.random(&token); 3109 const token_hex = std.fmt.bytesToHex(token, .lower); 3110 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3111 defer file.close(self.io); 3112 try file.writeStreamingAll(self.io, user_id); 3113 return token_hex; 3114 } 3115 3116 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3117 var token: [evt.event_id_size]u8 = undefined; 3118 self.io.random(&token); 3119 const token_hex = std.fmt.bytesToHex(token, .lower); 3120 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3121 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3122 defer file.close(self.io); 3123 3124 var json: std.Io.Writer.Allocating = .init(allocator); 3125 defer json.deinit(); 3126 try std.json.Stringify.value(value, .{}, &json.writer); 3127 try file.writeStreamingAll(self.io, json.written()); 3128 return token_hex; 3129 } 3130 3131 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3132 if (!isToken(token_hex)) return null; 3133 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3134 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3135 defer file.close(self.io); 3136 3137 var storage: [4096]u8 = undefined; 3138 var reader = file.reader(self.io, &storage); 3139 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3140 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3141 } 3142 3143 // resolve a cookie's token to its user_id. returns false (logged out) for a 3144 // missing, malformed, or unknown token. 3145 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3146 if (!isToken(token_hex)) return false; 3147 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3148 defer file.close(self.io); 3149 var storage: [evt.event_id_size]u8 = undefined; 3150 var file_reader = file.reader(self.io, &storage); 3151 file_reader.interface.readSliceAll(out) catch return false; 3152 return true; 3153 } 3154 3155 // revoke a session. a no-op for a missing or malformed token. 3156 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3157 if (!isToken(token_hex)) return; 3158 self.dir.deleteFile(self.io, token_hex) catch {}; 3159 } 3160 3161 // leave `token_hex`'s session for visitors arriving without one. only the 3162 // `try` fixture writes one. the name can't collide with a session token. 3163 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3164 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3165 defer file.close(self.io); 3166 try file.writeStreamingAll(self.io, token_hex); 3167 } 3168 3169 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3170 out.* = self.auto_login orelse return false; 3171 return true; 3172 } 3173 3174 const auto_login_name = "auto-login"; 3175 3176 // a token is exactly token_hex_len hex chars. validating before using the 3177 // value as a path keeps attacker-supplied cookies from escaping the 3178 // sessions dir (e.g. via "/" or ".." bytes). 3179 fn isToken(token_hex: []const u8) bool { 3180 if (token_hex.len != token_hex_len) return false; 3181 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3182 return true; 3183 } 3184 }; 3185