╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
201 }); 202 } 203 204 fn handleLogin( 205 io: std.Io, 206 request: *std.http.Server.Request, 207 allocator: std.mem.Allocator, 208 base: []const u8, 209 admin_repo_path: []const u8, 210 session_store: SessionStore, 211 ) !void { 212 var body_buf: [256]u8 = undefined; 213 const reader = request.readerExpectNone(&body_buf); 214 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 215 defer allocator.free(body); 216 217 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 218 defer allocator.free(username); 219 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 220 defer allocator.free(password); 221 222 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 223 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 224 defer repo.deinit(io, allocator); 225 226 var arena = std.heap.ArenaAllocator.init(allocator); 227 defer arena.deinit(); 228 229 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 230 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 231 232 // on success, return to the page the login came from (base, or "/" at the 233 // root); on failure, stay on its auth tab to surface the error. 234 const success_location: []const u8 = if (base.len == 0) "/" else base; 235 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{base}); 236 237 switch (result) { 238 .success => |user_id| { 239 const token = try session_store.create(&user_id); 240 var cookie_buf: [256]u8 = undefined; 241 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 242 try request.respond("", .{ 243 .status = .see_other, 244 .extra_headers = &.{ 245 .{ .name = "location", .value = success_location }, 246 .{ .name = "set-cookie", .value = cookie }, 247 }, 248 }); 249 }, 250 .unknown_user => { 251 try request.respond("", .{ 252 .status = .see_other, 253 .extra_headers = &.{ 254 .{ .name = "location", .value = failure_location }, 255 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 256 }, 257 }); 258 }, 259 .wrong_password => { 260 try request.respond("", .{ 261 .status = .see_other, 262 .extra_headers = &.{ 263 .{ .name = "location", .value = failure_location }, 264 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 265 }, 266 }); 267 }, 268 } 269 } 270 271 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 272 // revoke the session server-side so the cookie is dead for anyone holding 273 // a copy, not just this browser. 274 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 275 // return to the page the logout came from (base, or "/" at the root). 276 const location: []const u8 = if (base.len == 0) "/" else base; 277 // close the connection instead of keeping it alive: we don't read the 278 // request body, and respond()'s keep-alive path would otherwise try to 279 // discard it — which asserts on a bodyless POST that carries no 280 // content-length, and would block on one with no framing at all. a logout 281 // is just a redirect, so the browser reconnects for the follow-up GET. 282 try request.respond("", .{ 283 .status = .see_other, 284 .keep_alive = false, 285 .extra_headers = &.{ 286 .{ .name = "location", .value = location }, 287 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 288 }, 289 }); 290 } 291 292 fn handleAnsi( 293 io: std.Io, 294 request: *std.http.Server.Request, 295 allocator: std.mem.Allocator, 296 base: []const u8, 297 admin_repo_path: []const u8, 298 session_store: SessionStore, 299 ) !void { 300 var user_id: [evt.event_id_size]u8 = undefined; 301 if (getCookieValue(request, cookie_name)) |token| { 302 if (session_store.lookup(token, &user_id)) { 303 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 304 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 305 defer repo.deinit(io, allocator); 306 307 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 308 } 309 } 310 311 // return to the settings tab the toggle came from so the change is visible. 312 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 313 defer allocator.free(location); 314 315 // like logout, this is a bodyless POST, so close the connection rather than 316 // letting the keep-alive path try to discard a body that isn't framed. 317 try request.respond("", .{ 318 .status = .see_other, 319 .keep_alive = false, 320 .extra_headers = &.{ 321 .{ .name = "location", .value = location }, 322 }, 323 }); 324 } 325 326 fn renderIndexHtml( 327 io: std.Io, 328 allocator: std.mem.Allocator, 329 host: Host, 330 session_data: ui.Session.Data, 331 ) ![]const u8 { 332 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 333 334 var page_arena = std.heap.ArenaAllocator.init(allocator); 335 defer page_arena.deinit(); 336 337 // the remote admin repo must outlive the page build, since the session's 338 // moment reads from it. 339 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 340 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 341 342 var session = switch (host) { 343 .remote => |remote| blk: { 344 // open the admin repo to read live user/repo data. 345 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 346 const repo = if (repo_maybe) |*repo| repo else unreachable; 347 var session = try ui.Session.init(&page_arena, repo, session_data); 348 // give the page builders filesystem access to the on-disk repos (a 349 // sibling "repos" dir next to the admin repo) so the Repo page can 350 // read its files. 351 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 352 break :blk session; 353 }, 354 .local => |local| ui.Session{ 355 .data = session_data, 356 .arena = &page_arena, 357 .page_arena = &page_arena, 358 .local = local, 359 }, 360 }; 361 session.io = io; 362 363 const snapshot: ui.Snapshot = .{ 364 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 365 .session = session.data, 366 }; 367 var root = try ui.initRoot(allocator, &snapshot.page, &session); 368 defer root.deinit(allocator); 369 370 const content = try generateHtml(allocator, &root); 371 defer allocator.free(content); 372 const overlay = try generateOverlay(allocator, &root, &session); 373 defer allocator.free(overlay); 374 375 // serialize the snapshot so the wasm side can parse it back without making 376 // a second request. it's embedded raw in a <script type="application/json"> 377 // block, whose content is raw text terminated only by "</script". in json, 378 // '<' appears solely inside string values, so escaping every '<' (and '>' 379 // for good measure) to its \uXXXX form yields equivalent json that can't 380 // break out of the tag. 381 var json: std.Io.Writer.Allocating = .init(allocator); 382 defer json.deinit(); 383 try std.json.Stringify.value(snapshot, .{}, &json.writer); 384 385 var json_escaped: std.ArrayList(u8) = .empty; 386 defer json_escaped.deinit(allocator); 387 for (json.written()) |c| switch (c) { 388 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 389 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 390 else => try json_escaped.append(allocator, c), 391 }; 392 393 var out: std.ArrayList(u8) = .empty; 394 errdefer out.deinit(allocator); 395 { 396 var cursor: usize = 0; 397 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 398 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 399 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 400 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 401 }) |sub| { 402 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 403 try out.appendSlice(allocator, template[cursor..idx]); 404 try out.appendSlice(allocator, sub.replacement); 405 cursor = idx + sub.needle.len; 406 } 407 try out.appendSlice(allocator, template[cursor..]); 408 } 409 return try out.toOwnedSlice(allocator); 410 } 411 412 fn findEmbed(request_path: []const u8) ?Embed { 413 const path = if (std.mem.eql(u8, request_path, "/")) 414 "index.html" 415 else if (request_path.len > 1 and request_path[0] == '/') 416 request_path[1..] 417 else 418 return null; 419 420 for (embeds) |embed| { 421 if (std.mem.eql(u8, path, embed.path)) return embed; 422 } 423 return null; 424 } 425 426 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 427 // own absolutely-positioned, natively-scrollable <div> holding its full content, 428 // rendered recursively so nested scrolls work. 429 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 430 const grid = root.getGrid() orelse return error.MissingGrid; 431 432 var out: std.ArrayList(u8) = .empty; 433 errdefer out.deinit(allocator); 434 435 try renderPanel(allocator, &out, root.getFocus(), grid); 436 return try out.toOwnedSlice(allocator); 437 } 438 439 // render one panel — a focus subtree and its content grid — as HTML, recursing 440 // once per web-native Scroll inside it. the root panel is the whole page; each 441 // Scroll becomes a nested, natively-scrollable div holding its full content. 442 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 443 // then the child scroll divs over those holes. 444 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 445 // `direct` is this panel's scroll children, each drawn as an overlaid div. 446 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 447 // plus their descendants, which the focus tree flattens into this panel's 448 // children): the cell hit-test below skips them so this panel doesn't claim 449 // cells that are really rendered inside a child scroll's own panel. 450 // (scrolls aren't nested in practice, so every scroll child is direct here.) 451 var direct: std.ArrayList(usize) = .empty; 452 defer direct.deinit(allocator); 453 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 454 defer excluded.deinit(allocator); 455 { 456 var it = focus.children.iterator(); 457 while (it.next()) |e| { 458 if (e.value_ptr.focus.scroll == null) continue; 459 try direct.append(allocator, e.key_ptr.*); 460 try excluded.put(allocator, e.key_ptr.*, {}); 461 var mit = e.value_ptr.focus.children.iterator(); 462 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 463 } 464 } 465 466 // the HTML element a run of cells is wrapped in, chosen from the cell's 467 // focusable kind 468 const CellTag = union(enum) { 469 span, // clickable focusable cell 470 a: []const u8, // clickable focusable link 471 plain, // non-focusable, colored 472 473 const a_prefix = "a:"; 474 // an "in-page" anchor: rendered as a real <a href> so it works with js 475 // disabled, but crossPageLink ignores it, so with wasm the click just 476 // moves focus rather than navigating. 477 const inpage_prefix = "ai:"; 478 479 fn init(str: []const u8) @This() { 480 if (std.mem.startsWith(u8, str, inpage_prefix)) { 481 return .{ .a = str[inpage_prefix.len..] }; 482 } 483 if (std.mem.startsWith(u8, str, a_prefix)) { 484 return .{ .a = str[a_prefix.len..] }; 485 } 486 return .span; 487 } 488 489 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 490 var id_buf: [32]u8 = undefined; 491 switch (self) { 492 .span => { 493 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 494 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 495 try out.appendSlice(alloc, "\""); 496 try out.appendSlice(alloc, style_attr); 497 try out.appendSlice(alloc, ">"); 498 }, 499 .a => |href| { 500 // tabindex=-1 keeps these out of the browser's tab order 501 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 502 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 503 try out.appendSlice(alloc, "\" href=\""); 504 try appendEscapedHtml(alloc, out, href); 505 try out.appendSlice(alloc, "\""); 506 try out.appendSlice(alloc, style_attr); 507 try out.appendSlice(alloc, ">"); 508 }, 509 .plain => { 510 try out.appendSlice(alloc, "<span"); 511 try out.appendSlice(alloc, style_attr); 512 try out.appendSlice(alloc, ">"); 513 }, 514 } 515 } 516 517 fn closeTag(self: @This()) []const u8 { 518 return switch (self) { 519 .span, .plain => "</span>", 520 .a => "</a>", 521 }; 522 } 523 }; 524 525 // emit this panel's grid as rows of text, coalescing adjacent cells that 526 // share a focus id and colors into one tag (a clickable span, a link, or a 527 // plain colored span). cells under a child scroll keep only their background. 528 for (0..grid.size.height) |y| { 529 var cur_id: ?usize = null; 530 var cur_fg: ?Grid.Color = null; 531 var cur_bg: ?Grid.Color = null; 532 var open_tag: ?CellTag = null; 533 var first = true; 534 for (0..grid.size.width) |x| { 535 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 536 // a cell covered by a child scroll's viewport is drawn by that scroll's 537 // own div, so blank its glyph and make it non-clickable here — but keep 538 // its background, so the backdrop still shows through the scroll's 539 // transparent div instead of a bare hole. 540 const covered_by_scroll = blk: { 541 for (direct.items) |id| { 542 const r = (focus.children.get(id) orelse continue).rect; 543 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; 544 } 545 break :blk false; 546 }; 547 // the focusable cell at (x, y) among this panel's own focusables (skipping 548 // any that belong to a child scroll, whose cells are drawn in their own 549 // panel); none for a covered cell. 550 const cell_id = if (covered_by_scroll) null else blk: { 551 var iter = focus.children.iterator(); 552 while (iter.next()) |entry| { 553 const child = entry.value_ptr.*; 554 if (!child.focus.focusable) continue; 555 if (excluded.contains(entry.key_ptr.*)) continue; 556 const r = child.rect; 557 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 558 break :blk entry.key_ptr.*; 559 } 560 } 561 break :blk null; 562 }; 563 const fg = if (covered_by_scroll) null else cell.style.fg; 564 const bg = cell.style.bg; 565 566 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 567 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 568 569 var new_tag: ?CellTag = null; 570 if (cell_id) |id| { 571 if (focus.children.get(id)) |child| { 572 new_tag = switch (child.focus.kind) { 573 .custom => |custom| CellTag.init(custom), 574 else => .span, 575 }; 576 } 577 } 578 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 579 580 if (new_tag) |t| { 581 var style_buf: [64]u8 = undefined; 582 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 583 } 584 585 open_tag = new_tag; 586 cur_id = cell_id; 587 cur_fg = fg; 588 cur_bg = bg; 589 first = false; 590 } 591 592 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 593 } 594 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 595 try output.append(allocator, '\n'); 596 } 597 598 // each child scroll becomes a natively-scrollable div positioned over its 599 // viewport, holding its full content rendered recursively. 600 for (direct.items) |id| { 601 const child = focus.children.get(id) orelse continue; 602 const info = child.focus.scroll orelse continue; 603 const r = child.rect; 604 // overflow only on the axes the widget scrolls; `auto` shows a bar only 605 // when that axis actually overflows. the other axis is clipped (hidden), 606 // matching how the terminal Scroll handles its non-scrolling axis. 607 const overflow = switch (info.direction) { 608 .vert => "overflow-x:hidden;overflow-y:auto", 609 .horiz => "overflow-x:auto;overflow-y:hidden", 610 .both => "overflow:auto", 611 }; 612 // the id carries a content version so JS preserves the native scroll 613 // position across re-renders of the same content but resets it (to the 614 // top) when the content is replaced — e.g. selecting a different commit. 615 var buf: [160]u8 = undefined; 616 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, r.x, r.y, r.size.width, r.size.height, overflow })); 617 try renderPanel(allocator, output, child.focus, info.content); 618 try output.appendSlice(allocator, "</div>"); 619 } 620 } 621 622 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 623 // widget tree, each wrapping the text inputs and submit button inside it, 624 // positioned absolutely over the matching grid cells. 625 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 626 const root_focus = root.getFocus(); 627 628 var out: std.ArrayList(u8) = .empty; 629 errdefer out.deinit(allocator); 630 631 const form_prefix = "form:"; 632 633 // Focus.children is an AutoArrayHashMap that preserves insertion order, 634 // which matches the order widgets were added in code 635 var iter = root_focus.children.iterator(); 636 while (iter.next()) |entry| { 637 const child = entry.value_ptr.*; 638 const action_url = switch (child.focus.kind) { 639 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 640 custom[form_prefix.len..] 641 else 642 continue, 643 else => continue, 644 }; 645 646 try out.appendSlice(allocator, "<form action=\""); 647 try appendEscapedHtml(allocator, &out, action_url); 648 try out.appendSlice(allocator, "\" method=\"post\""); 649 // an empty action must not POST — block it and send the input to the TUI instead 650 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 651 try out.appendSlice(allocator, ">"); 652 653 // form.focus.children was populated by addChild, which flattens the 654 // whole subtree into one map — so descendants (inputs + the submit 655 // button) all appear here. positions on form.focus are relative to 656 // the form, so we look up absolute rects via root_focus for layout. 657 var inner_iter = child.focus.children.iterator(); 658 while (inner_iter.next()) |inner_entry| { 659 const inner_id = inner_entry.key_ptr.*; 660 const root_child = root_focus.children.get(inner_id) orelse continue; 661 const r = root_child.rect; 662 switch (root_child.focus.kind) { 663 .text_input, .text_input_password => { 664 const ti = session.text_inputs.get(inner_id) orelse continue; 665 const inner_left = r.x + 1; 666 const inner_top = r.y + 1; 667 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 668 669 try out.appendSlice(allocator, "<input type=\""); 670 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 671 try out.appendSlice(allocator, "\" data-focus-id=\""); 672 var id_buf: [32]u8 = undefined; 673 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 674 if (ti.options.name.len > 0) { 675 try out.appendSlice(allocator, "\" name=\""); 676 try appendEscapedHtml(allocator, &out, ti.options.name); 677 } 678 // intentionally no `value` attribute: the browser tracks user input 679 // natively, and including the wasm-side value here would make the 680 // overlay HTML differ on every keystroke — that would trip the diff 681 // in _setOverlay and rebuild the <input>, eating the user's caret. 682 try out.appendSlice(allocator, "\" style=\"left:"); 683 var pos_buf: [64]u8 = undefined; 684 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 })); 685 try out.appendSlice(allocator, "\">"); 686 }, 687 .custom => |custom| { 688 if (std.mem.eql(u8, "submit", custom)) { 689 // inside the dashed border the TUI cells draw around the button. 690 const inner_left = r.x + 1; 691 const inner_top = r.y + 1; 692 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 693 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 694 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 695 var id_buf: [32]u8 = undefined; 696 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 697 try out.appendSlice(allocator, "\" style=\"left:"); 698 var pos_buf: [128]u8 = undefined; 699 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 })); 700 try out.appendSlice(allocator, "\"></button>"); 701 } 702 }, 703 else => {}, 704 } 705 } 706 707 try out.appendSlice(allocator, "</form>"); 708 } 709 710 return try out.toOwnedSlice(allocator); 711 } 712 713 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 714 if (a) |av| return if (b) |bv| av.eql(bv) else false; 715 return b == null; 716 } 717 718 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 719 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 720 // empty slice when neither is set. 721 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 722 if (fg == null and bg == null) return buf[0..0]; 723 const prefix = " style=\""; 724 @memcpy(buf[0..prefix.len], prefix); 725 var i: usize = prefix.len; 726 if (fg) |c| { 727 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]; 728 i += s.len; 729 } 730 if (bg) |c| { 731 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]; 732 i += s.len; 733 } 734 buf[i] = '"'; 735 i += 1; 736 return buf[0..i]; 737 } 738 739 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 740 for (input) |ch| { 741 switch (ch) { 742 '&' => try out.appendSlice(allocator, "&amp;"), 743 '<' => try out.appendSlice(allocator, "&lt;"), 744 '>' => try out.appendSlice(allocator, "&gt;"), 745 '"' => try out.appendSlice(allocator, "&quot;"), 746 '\'' => try out.appendSlice(allocator, "&#39;"), 747 else => try out.append(allocator, ch), 748 } 749 } 750 } 751 752 // --- helpers -------------------------------------------------------------- 753 754 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 755 var iter = request.iterateHeaders(); 756 while (iter.next()) |header| { 757 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 758 var pairs = std.mem.splitScalar(u8, header.value, ';'); 759 while (pairs.next()) |pair| { 760 const trimmed = std.mem.trim(u8, pair, " \t"); 761 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 762 if (std.mem.eql(u8, trimmed[0..eq], name)) { 763 return trimmed[eq + 1 ..]; 764 } 765 } 766 } 767 return null; 768 } 769 770 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 771 var iter = std.mem.splitScalar(u8, body, '&'); 772 while (iter.next()) |pair| { 773 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 774 if (std.mem.eql(u8, pair[0..eq], key)) { 775 return try decodeFormValue(allocator, pair[eq + 1 ..]); 776 } 777 } 778 return null; 779 } 780 781 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 782 var out: std.ArrayList(u8) = .empty; 783 errdefer out.deinit(allocator); 784 var i: usize = 0; 785 while (i < encoded.len) : (i += 1) { 786 switch (encoded[i]) { 787 '+' => try out.append(allocator, ' '), 788 '%' => { 789 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 790 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 791 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 792 try out.append(allocator, hi * 16 + lo); 793 i += 2; 794 }, 795 else => try out.append(allocator, encoded[i]), 796 } 797 } 798 return try out.toOwnedSlice(allocator); 799 } 800 801 // disk-backed web session store. each login mints a random, opaque token 802 // (not the user's id) that is stored as a file named by the token hex, whose 803 // contents are the raw user_id bytes. authenticating a request is a lookup of 804 // the cookie's token; logout deletes the file, revoking the session. there is 805 // deliberately no expiry — a session lives until logout. 806 pub const SessionStore = struct { 807 io: std.Io, 808 dir: std.Io.Dir, 809 810 pub const token_hex_len = evt.event_id_size * 2; 811 812 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 813 try data_dir.createDirPath(io, "sessions"); 814 const dir = try data_dir.openDir(io, "sessions", .{}); 815 return .{ .io = io, .dir = dir }; 816 } 817 818 pub fn deinit(self: SessionStore) void { 819 self.dir.close(self.io); 820 } 821 822 // mint a new session for user_id, returning the token hex to set as the 823 // cookie value. 824 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 825 var token: [evt.event_id_size]u8 = undefined; 826 self.io.random(&token); 827 const token_hex = std.fmt.bytesToHex(token, .lower); 828 const file = try self.dir.createFile(self.io, &token_hex, .{}); 829 defer file.close(self.io); 830 try file.writeStreamingAll(self.io, user_id); 831 return token_hex; 832 } 833 834 // resolve a cookie's token to its user_id. returns false (logged out) for a 835 // missing, malformed, or unknown token. 836 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 837 if (!isToken(token_hex)) return false; 838 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 839 defer file.close(self.io); 840 var storage: [evt.event_id_size]u8 = undefined; 841 var file_reader = file.reader(self.io, &storage); 842 file_reader.interface.readSliceAll(out) catch return false; 843 return true; 844 } 845 846 // revoke a session. a no-op for a missing or malformed token. 847 pub fn remove(self: SessionStore, token_hex: []const u8) void { 848 if (!isToken(token_hex)) return; 849 self.dir.deleteFile(self.io, token_hex) catch {}; 850 } 851 852 // a token is exactly token_hex_len hex chars. validating before using the 853 // value as a path keeps attacker-supplied cookies from escaping the 854 // sessions dir (e.g. via "/" or ".." bytes). 855 fn isToken(token_hex: []const u8) bool { 856 if (token_hex.len != token_hex_len) return false; 857 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 858 return true; 859 } 860 }; 861