╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
467 .plain => { 468 try out.appendSlice(alloc, "<span"); 469 try out.appendSlice(alloc, style_attr); 470 try out.appendSlice(alloc, ">"); 471 }, 472 } 473 } 474 475 fn closeTag(self: @This()) []const u8 { 476 return switch (self) { 477 .span, .plain => "</span>", 478 .a => "</a>", 479 }; 480 } 481 }; 482 483 // emit this panel's grid as rows of text, coalescing adjacent cells that 484 // share a focus id and colors into one tag (a clickable span, a link, or a 485 // plain colored span). cells under a child scroll keep only their background. 486 for (0..grid.size.height) |y| { 487 var cur_id: ?usize = null; 488 var cur_fg: ?Grid.Color = null; 489 var cur_bg: ?Grid.Color = null; 490 var open_tag: ?CellTag = null; 491 var first = true; 492 for (0..grid.size.width) |x| { 493 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 494 // a cell covered by a child scroll's viewport is drawn by that scroll's 495 // own div, so blank its glyph and make it non-clickable here — but keep 496 // its background, so the backdrop still shows through the scroll's 497 // transparent div instead of a bare hole. 498 const covered_by_scroll = blk: { 499 for (direct.items) |id| { 500 const r = (focus.children.get(id) orelse continue).rect; 501 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; 502 } 503 break :blk false; 504 }; 505 // the focusable cell at (x, y) among this panel's own focusables (skipping 506 // any that belong to a child scroll, whose cells are drawn in their own 507 // panel); none for a covered cell. 508 const cell_id = if (covered_by_scroll) null else blk: { 509 var iter = focus.children.iterator(); 510 while (iter.next()) |entry| { 511 const child = entry.value_ptr.*; 512 if (!child.focus.focusable) continue; 513 if (excluded.contains(entry.key_ptr.*)) continue; 514 const r = child.rect; 515 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 516 break :blk entry.key_ptr.*; 517 } 518 } 519 break :blk null; 520 }; 521 const fg = if (covered_by_scroll) null else cell.style.fg; 522 const bg = cell.style.bg; 523 524 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 525 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 526 527 var new_tag: ?CellTag = null; 528 if (cell_id) |id| { 529 if (focus.children.get(id)) |child| { 530 new_tag = switch (child.focus.kind) { 531 .custom => |custom| CellTag.init(custom), 532 else => .span, 533 }; 534 } 535 } 536 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 537 538 if (new_tag) |t| { 539 var style_buf: [64]u8 = undefined; 540 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 541 } 542 543 open_tag = new_tag; 544 cur_id = cell_id; 545 cur_fg = fg; 546 cur_bg = bg; 547 first = false; 548 } 549 550 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 551 } 552 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 553 try output.append(allocator, '\n'); 554 } 555 556 // each child scroll becomes a natively-scrollable div positioned over its 557 // viewport, holding its full content rendered recursively. 558 for (direct.items) |id| { 559 const child = focus.children.get(id) orelse continue; 560 const info = child.focus.scroll orelse continue; 561 const r = child.rect; 562 // overflow only on the axes the widget scrolls; `auto` shows a bar only 563 // when that axis actually overflows. the other axis is clipped (hidden), 564 // matching how the terminal Scroll handles its non-scrolling axis. 565 const overflow = switch (info.direction) { 566 .vert => "overflow-x:hidden;overflow-y:auto", 567 .horiz => "overflow-x:auto;overflow-y:hidden", 568 .both => "overflow:auto", 569 }; 570 // the id carries a content version so JS preserves the native scroll 571 // position across re-renders of the same content but resets it (to the 572 // top) when the content is replaced — e.g. selecting a different commit. 573 var buf: [160]u8 = undefined; 574 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 })); 575 try renderPanel(allocator, output, child.focus, info.content); 576 try output.appendSlice(allocator, "</div>"); 577 } 578 } 579 580 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 581 // widget tree, each wrapping the text inputs and submit button inside it, 582 // positioned absolutely over the matching grid cells. 583 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 584 const root_focus = root.getFocus(); 585 586 var out: std.ArrayList(u8) = .empty; 587 errdefer out.deinit(allocator); 588 589 const form_prefix = "form:"; 590 591 // Focus.children is an AutoArrayHashMap that preserves insertion order, 592 // which matches the order widgets were added in code 593 var iter = root_focus.children.iterator(); 594 while (iter.next()) |entry| { 595 const child = entry.value_ptr.*; 596 const action_url = switch (child.focus.kind) { 597 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 598 custom[form_prefix.len..] 599 else 600 continue, 601 else => continue, 602 }; 603 604 try out.appendSlice(allocator, "<form action=\""); 605 try appendEscapedHtml(allocator, &out, action_url); 606 try out.appendSlice(allocator, "\" method=\"post\""); 607 // an empty action must not POST — block it and send the input to the TUI instead 608 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 609 try out.appendSlice(allocator, ">"); 610 611 // form.focus.children was populated by addChild, which flattens the 612 // whole subtree into one map — so descendants (inputs + the submit 613 // button) all appear here. positions on form.focus are relative to 614 // the form, so we look up absolute rects via root_focus for layout. 615 var inner_iter = child.focus.children.iterator(); 616 while (inner_iter.next()) |inner_entry| { 617 const inner_id = inner_entry.key_ptr.*; 618 const root_child = root_focus.children.get(inner_id) orelse continue; 619 const r = root_child.rect; 620 switch (root_child.focus.kind) { 621 .text_input, .text_input_password => { 622 const ti = session.text_inputs.get(inner_id) orelse continue; 623 const inner_left = r.x + 1; 624 const inner_top = r.y + 1; 625 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 626 627 try out.appendSlice(allocator, "<input type=\""); 628 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 629 try out.appendSlice(allocator, "\" data-focus-id=\""); 630 var id_buf: [32]u8 = undefined; 631 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 632 if (ti.options.name.len > 0) { 633 try out.appendSlice(allocator, "\" name=\""); 634 try appendEscapedHtml(allocator, &out, ti.options.name); 635 } 636 // intentionally no `value` attribute: the browser tracks user input 637 // natively, and including the wasm-side value here would make the 638 // overlay HTML differ on every keystroke — that would trip the diff 639 // in _setOverlay and rebuild the <input>, eating the user's caret. 640 try out.appendSlice(allocator, "\" style=\"left:"); 641 var pos_buf: [64]u8 = undefined; 642 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 })); 643 try out.appendSlice(allocator, "\">"); 644 }, 645 .custom => |custom| { 646 if (std.mem.eql(u8, "submit", custom)) { 647 // inside the dashed border the TUI cells draw around the button. 648 const inner_left = r.x + 1; 649 const inner_top = r.y + 1; 650 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 651 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 652 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 653 var id_buf: [32]u8 = undefined; 654 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 655 try out.appendSlice(allocator, "\" style=\"left:"); 656 var pos_buf: [128]u8 = undefined; 657 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 })); 658 try out.appendSlice(allocator, "\"></button>"); 659 } 660 }, 661 else => {}, 662 } 663 } 664 665 try out.appendSlice(allocator, "</form>"); 666 } 667 668 return try out.toOwnedSlice(allocator); 669 } 670 671 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 672 if (a) |av| return if (b) |bv| av.eql(bv) else false; 673 return b == null; 674 } 675 676 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 677 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 678 // empty slice when neither is set. 679 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 680 if (fg == null and bg == null) return buf[0..0]; 681 const prefix = " style=\""; 682 @memcpy(buf[0..prefix.len], prefix); 683 var i: usize = prefix.len; 684 if (fg) |c| { 685 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]; 686 i += s.len; 687 } 688 if (bg) |c| { 689 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]; 690 i += s.len; 691 } 692 buf[i] = '"'; 693 i += 1; 694 return buf[0..i]; 695 } 696 697 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 698 for (input) |ch| { 699 switch (ch) { 700 '&' => try out.appendSlice(allocator, "&amp;"), 701 '<' => try out.appendSlice(allocator, "&lt;"), 702 '>' => try out.appendSlice(allocator, "&gt;"), 703 '"' => try out.appendSlice(allocator, "&quot;"), 704 '\'' => try out.appendSlice(allocator, "&#39;"), 705 else => try out.append(allocator, ch), 706 } 707 } 708 } 709 710 // --- helpers -------------------------------------------------------------- 711 712 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 713 var iter = request.iterateHeaders(); 714 while (iter.next()) |header| { 715 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 716 var pairs = std.mem.splitScalar(u8, header.value, ';'); 717 while (pairs.next()) |pair| { 718 const trimmed = std.mem.trim(u8, pair, " \t"); 719 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 720 if (std.mem.eql(u8, trimmed[0..eq], name)) { 721 return trimmed[eq + 1 ..]; 722 } 723 } 724 } 725 return null; 726 } 727 728 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 729 var iter = std.mem.splitScalar(u8, body, '&'); 730 while (iter.next()) |pair| { 731 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 732 if (std.mem.eql(u8, pair[0..eq], key)) { 733 return try decodeFormValue(allocator, pair[eq + 1 ..]); 734 } 735 } 736 return null; 737 } 738 739 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 740 var out: std.ArrayList(u8) = .empty; 741 errdefer out.deinit(allocator); 742 var i: usize = 0; 743 while (i < encoded.len) : (i += 1) { 744 switch (encoded[i]) { 745 '+' => try out.append(allocator, ' '), 746 '%' => { 747 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 748 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 749 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 750 try out.append(allocator, hi * 16 + lo); 751 i += 2; 752 }, 753 else => try out.append(allocator, encoded[i]), 754 } 755 } 756 return try out.toOwnedSlice(allocator); 757 } 758 759 // disk-backed web session store. each login mints a random, opaque token 760 // (not the user's id) that is stored as a file named by the token hex, whose 761 // contents are the raw user_id bytes. authenticating a request is a lookup of 762 // the cookie's token; logout deletes the file, revoking the session. there is 763 // deliberately no expiry — a session lives until logout. 764 pub const SessionStore = struct { 765 io: std.Io, 766 dir: std.Io.Dir, 767 768 pub const token_hex_len = evt.event_id_size * 2; 769 770 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 771 try data_dir.createDirPath(io, "sessions"); 772 const dir = try data_dir.openDir(io, "sessions", .{}); 773 return .{ .io = io, .dir = dir }; 774 } 775 776 pub fn deinit(self: SessionStore) void { 777 self.dir.close(self.io); 778 } 779 780 // mint a new session for user_id, returning the token hex to set as the 781 // cookie value. 782 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 783 var token: [evt.event_id_size]u8 = undefined; 784 self.io.random(&token); 785 const token_hex = std.fmt.bytesToHex(token, .lower); 786 const file = try self.dir.createFile(self.io, &token_hex, .{}); 787 defer file.close(self.io); 788 try file.writeStreamingAll(self.io, user_id); 789 return token_hex; 790 } 791 792 // resolve a cookie's token to its user_id. returns false (logged out) for a 793 // missing, malformed, or unknown token. 794 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 795 if (!isToken(token_hex)) return false; 796 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 797 defer file.close(self.io); 798 var storage: [evt.event_id_size]u8 = undefined; 799 var file_reader = file.reader(self.io, &storage); 800 file_reader.interface.readSliceAll(out) catch return false; 801 return true; 802 } 803 804 // revoke a session. a no-op for a missing or malformed token. 805 pub fn remove(self: SessionStore, token_hex: []const u8) void { 806 if (!isToken(token_hex)) return; 807 self.dir.deleteFile(self.io, token_hex) catch {}; 808 } 809 810 // a token is exactly token_hex_len hex chars. validating before using the 811 // value as a path keeps attacker-supplied cookies from escaping the 812 // sessions dir (e.g. via "/" or ".." bytes). 813 fn isToken(token_hex: []const u8) bool { 814 if (token_hex.len != token_hex_len) return false; 815 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 816 return true; 817 } 818 }; 819