╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
311 var root = try ui.initRoot(allocator, &snapshot.page, &session); 312 defer root.deinit(allocator); 313 314 const content = try generateHtml(allocator, &root, &session); 315 defer allocator.free(content); 316 const overlay = try generateOverlay(allocator, &root, &session); 317 defer allocator.free(overlay); 318 319 // serialize the snapshot so the wasm side can parse it back without 320 // making a second request. base64-encoded so the json can be embedded 321 // safely inside the host html. 322 var json: std.Io.Writer.Allocating = .init(allocator); 323 defer json.deinit(); 324 try std.json.Stringify.value(snapshot, .{}, &json.writer); 325 326 const b64 = std.base64.standard.Encoder; 327 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 328 defer allocator.free(json_b64); 329 _ = b64.encode(json_b64, json.written()); 330 331 var out: std.ArrayList(u8) = .empty; 332 errdefer out.deinit(allocator); 333 { 334 var cursor: usize = 0; 335 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 336 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 337 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 338 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 339 }) |sub| { 340 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 341 try out.appendSlice(allocator, template[cursor..idx]); 342 try out.appendSlice(allocator, sub.replacement); 343 cursor = idx + sub.needle.len; 344 } 345 try out.appendSlice(allocator, template[cursor..]); 346 } 347 return try out.toOwnedSlice(allocator); 348 } 349 350 fn findEmbed(request_path: []const u8) ?Embed { 351 const path = if (std.mem.eql(u8, request_path, "/")) 352 "index.html" 353 else if (request_path.len > 1 and request_path[0] == '/') 354 request_path[1..] 355 else 356 return null; 357 358 for (embeds) |embed| { 359 if (std.mem.eql(u8, path, embed.path)) return embed; 360 } 361 return null; 362 } 363 364 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 365 err.print(fmt, args) catch return; 366 err.flush() catch {}; 367 } 368 369 // emits the TUI grid cells (one <span> run per focusable widget) 370 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 371 _ = session; 372 const grid = root.getGrid() orelse return error.MissingGrid; 373 const root_focus = root.getFocus(); 374 375 var out: std.ArrayList(u8) = .empty; 376 errdefer out.deinit(allocator); 377 378 for (0..grid.size.height) |y| { 379 var current_id: ?usize = null; 380 for (0..grid.size.width) |x| { 381 const cell_id = cellFocusId(root_focus, x, y); 382 if (cell_id != current_id) { 383 if (current_id != null) try out.appendSlice(allocator, "</span>"); 384 if (cell_id) |id| { 385 var buf: [128]u8 = undefined; 386 const tag = try std.fmt.bufPrint(&buf, "<span class=\"clickable\" data-focus-id=\"{d}\">", .{id}); 387 try out.appendSlice(allocator, tag); 388 } 389 current_id = cell_id; 390 } 391 const rune = grid.cells.items[try grid.cells.at(.{ y, x })].rune orelse " "; 392 try appendEscapedHtml(allocator, &out, rune); 393 } 394 if (current_id != null) try out.appendSlice(allocator, "</span>"); 395 try out.append(allocator, '\n'); 396 } 397 398 return try out.toOwnedSlice(allocator); 399 } 400 401 // emits the form overlay — a <form> wrapping the text inputs and submit 402 // button, positioned absolutely over the matching grid cells 403 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 404 const root_focus = root.getFocus(); 405 406 var out: std.ArrayList(u8) = .empty; 407 errdefer out.deinit(allocator); 408 409 const InputEntry = struct { 410 focus_id: usize, 411 x: usize, 412 y: usize, 413 width: usize, 414 is_password: bool, 415 ti: *wgt.TextInput(ui.Widget), 416 }; 417 const SubmitButton = struct { 418 focus_id: usize, 419 x: usize, 420 y: usize, 421 width: usize, 422 height: usize, 423 }; 424 var inputs: std.ArrayList(InputEntry) = .empty; 425 defer inputs.deinit(allocator); 426 var submit: ?SubmitButton = null; 427 428 var iter = root_focus.children.iterator(); 429 while (iter.next()) |entry| { 430 const child = entry.value_ptr.*; 431 switch (child.focus.kind) { 432 .text_input, .text_input_password => { 433 try inputs.append(allocator, .{ 434 .focus_id = entry.key_ptr.*, 435 .x = child.rect.x, 436 .y = child.rect.y, 437 .width = child.rect.size.width, 438 .is_password = child.focus.kind == .text_input_password, 439 .ti = @fieldParentPtr("focus", child.focus), 440 }); 441 }, 442 .submit_button => { 443 submit = .{ 444 .focus_id = entry.key_ptr.*, 445 .x = child.rect.x, 446 .y = child.rect.y, 447 .width = child.rect.size.width, 448 .height = child.rect.size.height, 449 }; 450 }, 451 else => {}, 452 } 453 } 454 455 if (submit == null and inputs.items.len == 0) return try out.toOwnedSlice(allocator); 456 457 // top-to-bottom, left-to-right order so the natural tab cycle matches 458 // visual layout (username -> password -> submit button). 459 std.mem.sort(InputEntry, inputs.items, {}, struct { 460 fn lt(_: void, a: InputEntry, b: InputEntry) bool { 461 if (a.y != b.y) return a.y < b.y; 462 return a.x < b.x; 463 } 464 }.lt); 465 466 // only the auth page hosts a form right now; on any other page we 467 // emit nothing. on auth, the URL depends on whether there's already 468 // an active session. 469 const action_url: []const u8 = switch (session.data.current_page) { 470 .home_auth => if (session.data.user_id != null) "/logout" else "/login", 471 .home_users, .home_repos => return try out.toOwnedSlice(allocator), 472 }; 473 474 try out.appendSlice(allocator, "<form action=\""); 475 try out.appendSlice(allocator, action_url); 476 try out.appendSlice(allocator, "\" method=\"post\">"); 477 478 for (inputs.items) |entry| { 479 const inner_left = entry.x + 1; 480 const inner_top = entry.y + 1; 481 const inner_width = if (entry.width > 2) entry.width - 2 else 0; 482 483 try out.appendSlice(allocator, "<input type=\""); 484 try out.appendSlice(allocator, if (entry.is_password) "password" else "text"); 485 try out.appendSlice(allocator, "\" data-focus-id=\""); 486 var id_buf: [32]u8 = undefined; 487 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.focus_id})); 488 if (entry.ti.options.name.len > 0) { 489 try out.appendSlice(allocator, "\" name=\""); 490 try appendEscapedHtml(allocator, &out, entry.ti.options.name); 491 } 492 // intentionally no `value` attribute: the browser tracks user input 493 // natively, and including the wasm-side value here would make the 494 // overlay HTML differ on every keystroke — that would trip the diff 495 // in _setOverlay and rebuild the <input>, eating the user's caret. 496 try out.appendSlice(allocator, "\" style=\"left:"); 497 var pos_buf: [64]u8 = undefined; 498 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 })); 499 try out.appendSlice(allocator, "\">"); 500 } 501 502 if (submit) |btn| { 503 // inside the dashed border the TUI cells draw around the button. 504 const inner_left = btn.x + 1; 505 const inner_top = btn.y + 1; 506 const inner_width = if (btn.width > 2) btn.width - 2 else 0; 507 const inner_height = if (btn.height > 2) btn.height - 2 else 0; 508 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 509 var id_buf: [32]u8 = undefined; 510 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{btn.focus_id})); 511 try out.appendSlice(allocator, "\" style=\"left:"); 512 var pos_buf: [128]u8 = undefined; 513 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 })); 514 try out.appendSlice(allocator, "\"></button>"); 515 } 516 517 try out.appendSlice(allocator, "</form>"); 518 519 return try out.toOwnedSlice(allocator); 520 } 521 522 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 523 var iter = focus.children.iterator(); 524 while (iter.next()) |entry| { 525 const child = entry.value_ptr.*; 526 if (!child.focus.focusable) continue; 527 const r = child.rect; 528 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 529 return entry.key_ptr.*; 530 } 531 } 532 return null; 533 } 534 535 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 536 for (input) |ch| { 537 switch (ch) { 538 '&' => try out.appendSlice(allocator, "&amp;"), 539 '<' => try out.appendSlice(allocator, "&lt;"), 540 '>' => try out.appendSlice(allocator, "&gt;"), 541 '"' => try out.appendSlice(allocator, "&quot;"), 542 '\'' => try out.appendSlice(allocator, "&#39;"), 543 else => try out.append(allocator, ch), 544 } 545 } 546 } 547 548 // --- helpers -------------------------------------------------------------- 549 550 fn openHaxyMoment( 551 comptime repo_opts: rp.RepoOpts(.xit), 552 repo: *rp.Repo(.xit, repo_opts), 553 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 554 const DB = rp.Repo(.xit, repo_opts).DB; 555 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 556 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 557 const moment = try DB.HashMap(.read_only).init(moment_cursor); 558 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 559 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 560 _ = try last_object_id_cursor.readBytes(&last_object_id); 561 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 562 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 563 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 564 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 565 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 566 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 567 } 568 569 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 570 var iter = request.iterateHeaders(); 571 while (iter.next()) |header| { 572 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 573 var pairs = std.mem.splitScalar(u8, header.value, ';'); 574 while (pairs.next()) |pair| { 575 const trimmed = std.mem.trim(u8, pair, " \t"); 576 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 577 if (std.mem.eql(u8, trimmed[0..eq], name)) { 578 return trimmed[eq + 1 ..]; 579 } 580 } 581 } 582 return null; 583 } 584 585 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 586 var iter = std.mem.splitScalar(u8, body, '&'); 587 while (iter.next()) |pair| { 588 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 589 if (std.mem.eql(u8, pair[0..eq], key)) { 590 return try decodeFormValue(allocator, pair[eq + 1 ..]); 591 } 592 } 593 return null; 594 } 595 596 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 597 var out: std.ArrayList(u8) = .empty; 598 errdefer out.deinit(allocator); 599 var i: usize = 0; 600 while (i < encoded.len) : (i += 1) { 601 switch (encoded[i]) { 602 '+' => try out.append(allocator, ' '), 603 '%' => { 604 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 605 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 606 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 607 try out.append(allocator, hi * 16 + lo); 608 i += 2; 609 }, 610 else => try out.append(allocator, encoded[i]), 611 } 612 } 613 return try out.toOwnedSlice(allocator); 614 } 615