╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1505 // '<' appears solely inside string values, so escaping every '<' (and '>' 1506 // for good measure) to its \uXXXX form yields equivalent json that can't 1507 // break out of the tag. 1508 var json: std.Io.Writer.Allocating = .init(allocator); 1509 defer json.deinit(); 1510 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1511 1512 var json_escaped: std.ArrayList(u8) = .empty; 1513 defer json_escaped.deinit(allocator); 1514 for (json.written()) |c| switch (c) { 1515 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1516 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1517 else => try json_escaped.append(allocator, c), 1518 }; 1519 1520 var out: std.ArrayList(u8) = .empty; 1521 errdefer out.deinit(allocator); 1522 { 1523 var cursor: usize = 0; 1524 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1525 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1526 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1527 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1528 }) |sub| { 1529 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1530 try out.appendSlice(allocator, template[cursor..idx]); 1531 try out.appendSlice(allocator, sub.replacement); 1532 cursor = idx + sub.needle.len; 1533 } 1534 try out.appendSlice(allocator, template[cursor..]); 1535 } 1536 return try out.toOwnedSlice(allocator); 1537 } 1538 1539 fn findEmbed(request_path: []const u8) ?Embed { 1540 const path = if (std.mem.eql(u8, request_path, "/")) 1541 "index.html" 1542 else if (request_path.len > 1 and request_path[0] == '/') 1543 request_path[1..] 1544 else 1545 return null; 1546 1547 for (embeds) |embed| { 1548 if (std.mem.eql(u8, path, embed.path)) return embed; 1549 } 1550 return null; 1551 } 1552 1553 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1554 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1555 // rendered recursively so nested scrolls work. 1556 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1557 const grid = root.getGrid() orelse return error.MissingGrid; 1558 1559 var out: std.ArrayList(u8) = .empty; 1560 errdefer out.deinit(allocator); 1561 1562 try renderPanel(allocator, &out, root.getFocus(), grid); 1563 return try out.toOwnedSlice(allocator); 1564 } 1565 1566 // render one panel — a focus subtree and its content grid — as HTML, recursing 1567 // once per web-native Scroll inside it. the root panel is the whole page; each 1568 // Scroll becomes a nested, natively-scrollable div holding its full content. 1569 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1570 // then the child scroll divs over those holes. 1571 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1572 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1573 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1574 // plus their descendants, which the focus tree flattens into this panel's 1575 // children): the cell hit-test below skips them so this panel doesn't claim 1576 // cells that are really rendered inside a child scroll's own panel. 1577 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1578 var direct: std.ArrayList(usize) = .empty; 1579 defer direct.deinit(allocator); 1580 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1581 defer excluded.deinit(allocator); 1582 { 1583 var it = focus.children.iterator(); 1584 while (it.next()) |e| { 1585 if (e.value_ptr.focus.scroll == null) continue; 1586 try direct.append(allocator, e.key_ptr.*); 1587 try excluded.put(allocator, e.key_ptr.*, {}); 1588 var mit = e.value_ptr.focus.children.iterator(); 1589 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1590 } 1591 } 1592 1593 // the HTML element a run of cells is wrapped in, chosen from the cell's 1594 // focusable kind 1595 const CellTag = union(enum) { 1596 span, // clickable focusable cell 1597 a: []const u8, // clickable focusable link 1598 plain, // non-focusable, colored 1599 1600 const a_prefix = "a:"; 1601 // an "in-page" anchor: rendered as a real <a href> so it works with js 1602 // disabled, but crossPageLink ignores it, so with wasm the click just 1603 // moves focus rather than navigating. 1604 const inpage_prefix = "ai:"; 1605 1606 fn init(str: []const u8) @This() { 1607 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1608 return .{ .a = str[ui.raw_link_prefix.len..] }; 1609 } 1610 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1611 return .{ .a = str[inpage_prefix.len..] }; 1612 } 1613 if (std.mem.startsWith(u8, str, a_prefix)) { 1614 return .{ .a = str[a_prefix.len..] }; 1615 } 1616 return .span; 1617 } 1618 1619 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1620 var id_buf: [32]u8 = undefined; 1621 switch (self) { 1622 .span => { 1623 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1624 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1625 try out.appendSlice(alloc, "\""); 1626 try out.appendSlice(alloc, style_attr); 1627 try out.appendSlice(alloc, ">"); 1628 }, 1629 .a => |href| { 1630 // tabindex=-1 keeps these out of the browser's tab order 1631 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1632 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1633 try out.appendSlice(alloc, "\" href=\""); 1634 try appendEscapedHtml(alloc, out, href); 1635 try out.appendSlice(alloc, "\""); 1636 try out.appendSlice(alloc, style_attr); 1637 try out.appendSlice(alloc, ">"); 1638 }, 1639 .plain => { 1640 try out.appendSlice(alloc, "<span"); 1641 try out.appendSlice(alloc, style_attr); 1642 try out.appendSlice(alloc, ">"); 1643 }, 1644 } 1645 } 1646 1647 fn closeTag(self: @This()) []const u8 { 1648 return switch (self) { 1649 .span, .plain => "</span>", 1650 .a => "</a>", 1651 }; 1652 } 1653 }; 1654 1655 // emit this panel's grid as rows of text, coalescing adjacent cells that 1656 // share a focus id and colors into one tag (a clickable span, a link, or a 1657 // plain colored span). cells under a child scroll keep only their background. 1658 for (0..grid.size.height) |y| { 1659 var cur_id: ?usize = null; 1660 var cur_fg: ?Grid.Color = null; 1661 var cur_bg: ?Grid.Color = null; 1662 var open_tag: ?CellTag = null; 1663 var first = true; 1664 for (0..grid.size.width) |x| { 1665 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1666 // a cell covered by a child scroll's viewport is drawn by that scroll's 1667 // own div, so blank its glyph and make it non-clickable here — but keep 1668 // its background, so the backdrop still shows through the scroll's 1669 // transparent div instead of a bare hole. 1670 const covered_by_scroll = blk: { 1671 for (direct.items) |id| { 1672 const r = (focus.children.get(id) orelse continue).rect; 1673 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; 1674 } 1675 break :blk false; 1676 }; 1677 // the focusable cell at (x, y) among this panel's own focusables (skipping 1678 // any that belong to a child scroll, whose cells are drawn in their own 1679 // panel); none for a covered cell. 1680 const cell_id = if (covered_by_scroll) null else blk: { 1681 var iter = focus.children.iterator(); 1682 while (iter.next()) |entry| { 1683 const child = entry.value_ptr.*; 1684 if (!child.focus.focusable) continue; 1685 if (excluded.contains(entry.key_ptr.*)) continue; 1686 const r = child.rect; 1687 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1688 break :blk entry.key_ptr.*; 1689 } 1690 } 1691 break :blk null; 1692 }; 1693 const fg = if (covered_by_scroll) null else cell.style.fg; 1694 const bg = cell.style.bg; 1695 1696 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1697 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1698 1699 var new_tag: ?CellTag = null; 1700 if (cell_id) |id| { 1701 if (focus.children.get(id)) |child| { 1702 new_tag = switch (child.focus.kind) { 1703 .custom => |custom| CellTag.init(custom), 1704 else => .span, 1705 }; 1706 } 1707 } 1708 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1709 1710 if (new_tag) |t| { 1711 var style_buf: [64]u8 = undefined; 1712 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1713 } 1714 1715 open_tag = new_tag; 1716 cur_id = cell_id; 1717 cur_fg = fg; 1718 cur_bg = bg; 1719 first = false; 1720 } 1721 1722 if (covered_by_scroll) { 1723 try appendEscapedHtml(allocator, output, " "); 1724 } else if (cell.continuation) { 1725 // the wide rune to the left was emitted 2ch wide, covering this column 1726 } else if (cell.rune) |rune| { 1727 // a double-width rune is pinned inside a 2ch span so the 1728 // fallback glyph's advance width can't shift the rest of the row 1729 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1730 if (wide) { 1731 try output.appendSlice(allocator, "<span class=\"w2\">"); 1732 try appendEscapedHtml(allocator, output, rune); 1733 try output.appendSlice(allocator, "</span>"); 1734 } else { 1735 try appendEscapedHtml(allocator, output, rune); 1736 } 1737 } else { 1738 try appendEscapedHtml(allocator, output, " "); 1739 } 1740 } 1741 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1742 try output.append(allocator, '\n'); 1743 } 1744 1745 // each child scroll becomes a natively-scrollable div positioned over its 1746 // viewport, holding its full content rendered recursively. 1747 for (direct.items) |id| { 1748 const child = focus.children.get(id) orelse continue; 1749 const info = child.focus.scroll orelse continue; 1750 const r = child.rect; 1751 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1752 // when that axis actually overflows. the other axis is clipped (hidden), 1753 // matching how the terminal Scroll handles its non-scrolling axis. 1754 const overflow = switch (info.direction) { 1755 .vert => "overflow-x:hidden;overflow-y:auto", 1756 .horiz => "overflow-x:auto;overflow-y:hidden", 1757 .both => "overflow:auto", 1758 }; 1759 // the id carries a content version so JS preserves the native scroll 1760 // position across re-renders of the same content but resets it when the 1761 // content is replaced — e.g. selecting a different commit. the widget's 1762 // scroll offset (in cells) rides along so JS can apply it when it has no 1763 // preserved position, letting a wasm-side scrollToRect (the files list 1764 // scrolling to its selected row on page load) reach the browser. 1765 var buf: [256]u8 = undefined; 1766 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" 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, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 1767 try renderPanel(allocator, output, child.focus, info.content); 1768 try output.appendSlice(allocator, "</div>"); 1769 } 1770 } 1771 1772 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1773 // widget tree, each wrapping the text inputs and submit button inside it, 1774 // positioned absolutely over the matching grid cells. 1775 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1776 const root_focus = root.getFocus(); 1777 1778 var out: std.ArrayList(u8) = .empty; 1779 errdefer out.deinit(allocator); 1780 1781 const form_prefix = "form:"; 1782 1783 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1784 // which matches the order widgets were added in code 1785 var iter = root_focus.children.iterator(); 1786 while (iter.next()) |entry| { 1787 const child = entry.value_ptr.*; 1788 const action_url = switch (child.focus.kind) { 1789 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1790 custom[form_prefix.len..] 1791 else 1792 continue, 1793 else => continue, 1794 }; 1795 1796 try out.appendSlice(allocator, "<form action=\""); 1797 try appendEscapedHtml(allocator, &out, action_url); 1798 try out.appendSlice(allocator, "\" method=\"post\""); 1799 // an empty action must not POST — block it and send the input to the TUI instead 1800 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1801 try out.appendSlice(allocator, ">"); 1802 1803 // form.focus.children was populated by addChild, which flattens the 1804 // whole subtree into one map — so descendants (inputs + the submit 1805 // button) all appear here. positions on form.focus are relative to 1806 // the form, so we look up absolute rects via root_focus for layout. 1807 var inner_iter = child.focus.children.iterator(); 1808 while (inner_iter.next()) |inner_entry| { 1809 const inner_id = inner_entry.key_ptr.*; 1810 const root_child = root_focus.children.get(inner_id) orelse continue; 1811 const r = root_child.rect; 1812 switch (root_child.focus.kind) { 1813 .text_input, .text_input_password => { 1814 const ti = session.text_inputs.get(inner_id) orelse continue; 1815 const inner_left = r.x + 1; 1816 const inner_top = r.y + 1; 1817 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1818 1819 try out.appendSlice(allocator, "<input type=\""); 1820 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1821 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1822 var id_buf: [32]u8 = undefined; 1823 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1824 if (ti.options.name.len > 0) { 1825 try out.appendSlice(allocator, "\" name=\""); 1826 try appendEscapedHtml(allocator, &out, ti.options.name); 1827 } 1828 // never the live content as the `value`: the browser tracks user 1829 // input natively, and including the wasm-side value here would make 1830 // the overlay HTML differ on every keystroke — that would trip the 1831 // diff in _setOverlay and rebuild the <input>, eating the user's 1832 // caret. a page-constant initial value is safe. 1833 if (session.input_values.get(inner_id)) |value| { 1834 try out.appendSlice(allocator, "\" value=\""); 1835 try appendEscapedHtml(allocator, &out, value); 1836 } 1837 try out.appendSlice(allocator, "\" style=\"left:"); 1838 var pos_buf: [64]u8 = undefined; 1839 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 })); 1840 try out.appendSlice(allocator, "\">"); 1841 }, 1842 .text_area => { 1843 const ti = session.text_inputs.get(inner_id) orelse continue; 1844 const inner_left = r.x + 1; 1845 const inner_top = r.y + 1; 1846 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1847 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1848 1849 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1850 var id_buf: [32]u8 = undefined; 1851 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1852 if (ti.options.name.len > 0) { 1853 try out.appendSlice(allocator, "\" name=\""); 1854 try appendEscapedHtml(allocator, &out, ti.options.name); 1855 } 1856 // like the input above, only a page-constant initial value 1857 // inside: the browser tracks the live value and the 1858 // overlay diff must stay stable across keystrokes 1859 try out.appendSlice(allocator, "\" style=\"left:"); 1860 var pos_buf: [128]u8 = undefined; 1861 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 })); 1862 // textarea discards the first newline immediately following 1863 // its start tag, so add one of our own so text that begins 1864 // with a newline doesn't lose it 1865 try out.appendSlice(allocator, "\">\n"); 1866 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1867 try out.appendSlice(allocator, "</textarea>"); 1868 }, 1869 .custom => |custom| { 1870 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1871 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1872 var id_buf: [32]u8 = undefined; 1873 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1874 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1875 try out.appendSlice(allocator, "\" formaction=\""); 1876 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1877 } 1878 try out.appendSlice(allocator, "\" style=\"left:"); 1879 var pos_buf: [128]u8 = undefined; 1880 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1881 try out.appendSlice(allocator, "\"></button>"); 1882 } 1883 }, 1884 else => {}, 1885 } 1886 } 1887 1888 try out.appendSlice(allocator, "</form>"); 1889 } 1890 1891 // a file picker isn't part of a form: it posts its file straight to the url 1892 // in its marker. it sits transparent over the button the tui drew, so 1893 // clicking that button opens the browser's own dialog. 1894 var file_iter = root_focus.children.iterator(); 1895 while (file_iter.next()) |entry| { 1896 const child = entry.value_ptr.*; 1897 const action_url = switch (child.focus.kind) { 1898 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1899 custom[ui.file_input_prefix.len..] 1900 else 1901 continue, 1902 else => continue, 1903 }; 1904 const r = child.rect; 1905 1906 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1907 try appendEscapedHtml(allocator, &out, action_url); 1908 try out.appendSlice(allocator, "\" data-focus-id=\""); 1909 var id_buf: [32]u8 = undefined; 1910 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1911 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1912 var pos_buf: [128]u8 = undefined; 1913 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1914 try out.appendSlice(allocator, "\">"); 1915 } 1916 1917 return try out.toOwnedSlice(allocator); 1918 } 1919 1920 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1921 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1922 return b == null; 1923 } 1924 1925 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1926 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1927 // empty slice when neither is set. 1928 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1929 if (fg == null and bg == null) return buf[0..0]; 1930 const prefix = " style=\""; 1931 @memcpy(buf[0..prefix.len], prefix); 1932 var i: usize = prefix.len; 1933 if (fg) |c| { 1934 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]; 1935 i += s.len; 1936 } 1937 if (bg) |c| { 1938 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]; 1939 i += s.len; 1940 } 1941 buf[i] = '"'; 1942 i += 1; 1943 return buf[0..i]; 1944 } 1945 1946 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1947 for (input) |ch| { 1948 switch (ch) { 1949 '&' => try out.appendSlice(allocator, "&amp;"), 1950 '<' => try out.appendSlice(allocator, "&lt;"), 1951 '>' => try out.appendSlice(allocator, "&gt;"), 1952 '"' => try out.appendSlice(allocator, "&quot;"), 1953 '\'' => try out.appendSlice(allocator, "&#39;"), 1954 else => try out.append(allocator, ch), 1955 } 1956 } 1957 } 1958 1959 // --- helpers -------------------------------------------------------------- 1960 1961 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1962 var iter = request.iterateHeaders(); 1963 while (iter.next()) |header| { 1964 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1965 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1966 while (pairs.next()) |pair| { 1967 const trimmed = std.mem.trim(u8, pair, " \t"); 1968 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1969 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1970 return trimmed[eq + 1 ..]; 1971 } 1972 } 1973 } 1974 return null; 1975 } 1976 1977 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1978 var iter = std.mem.splitScalar(u8, body, '&'); 1979 while (iter.next()) |pair| { 1980 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1981 if (std.mem.eql(u8, pair[0..eq], key)) { 1982 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1983 } 1984 } 1985 return null; 1986 } 1987 1988 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 1989 var buffer: [256]u8 = undefined; 1990 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 1991 } 1992 1993 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1994 var out: std.ArrayList(u8) = .empty; 1995 errdefer out.deinit(allocator); 1996 var i: usize = 0; 1997 while (i < encoded.len) : (i += 1) { 1998 switch (encoded[i]) { 1999 '+' => try out.append(allocator, ' '), 2000 '%' => { 2001 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2002 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2003 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2004 try out.append(allocator, hi * 16 + lo); 2005 i += 2; 2006 }, 2007 else => try out.append(allocator, encoded[i]), 2008 } 2009 } 2010 return try out.toOwnedSlice(allocator); 2011 } 2012 2013 // disk-backed web session store. each login mints a random, opaque token 2014 // (not the user's id) that is stored as a file named by the token hex, whose 2015 // contents are the raw user_id bytes. authenticating a request is a lookup of 2016 // the cookie's token; logout deletes the file, revoking the session. there is 2017 // deliberately no expiry — a session lives until logout. 2018 pub const SessionStore = struct { 2019 io: std.Io, 2020 dir: std.Io.Dir, 2021 auto_login: ?[token_hex_len]u8, 2022 2023 pub const token_hex_len = evt.event_id_size * 2; 2024 2025 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2026 try data_dir.createDirPath(io, "sessions"); 2027 const dir = try data_dir.openDir(io, "sessions", .{}); 2028 const auto_login = blk: { 2029 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2030 defer file.close(io); 2031 var token: [token_hex_len]u8 = undefined; 2032 var storage: [token_hex_len]u8 = undefined; 2033 var reader = file.reader(io, &storage); 2034 reader.interface.readSliceAll(&token) catch break :blk null; 2035 break :blk token; 2036 }; 2037 return .{ .io = io, .dir = dir, .auto_login = auto_login }; 2038 } 2039 2040 pub fn deinit(self: SessionStore) void { 2041 self.dir.close(self.io); 2042 } 2043 2044 // mint a new session for user_id, returning the token hex to set as the 2045 // cookie value. 2046 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2047 var token: [evt.event_id_size]u8 = undefined; 2048 self.io.random(&token); 2049 const token_hex = std.fmt.bytesToHex(token, .lower); 2050 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2051 defer file.close(self.io); 2052 try file.writeStreamingAll(self.io, user_id); 2053 return token_hex; 2054 } 2055 2056 // resolve a cookie's token to its user_id. returns false (logged out) for a 2057 // missing, malformed, or unknown token. 2058 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2059 if (!isToken(token_hex)) return false; 2060 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2061 defer file.close(self.io); 2062 var storage: [evt.event_id_size]u8 = undefined; 2063 var file_reader = file.reader(self.io, &storage); 2064 file_reader.interface.readSliceAll(out) catch return false; 2065 return true; 2066 } 2067 2068 // revoke a session. a no-op for a missing or malformed token. 2069 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2070 if (!isToken(token_hex)) return; 2071 self.dir.deleteFile(self.io, token_hex) catch {}; 2072 } 2073 2074 // leave `token_hex`'s session for visitors arriving without one. only the 2075 // `try` fixture writes one. the name can't collide with a session token. 2076 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2077 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2078 defer file.close(self.io); 2079 try file.writeStreamingAll(self.io, token_hex); 2080 } 2081 2082 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2083 out.* = self.auto_login orelse return false; 2084 return true; 2085 } 2086 2087 const auto_login_name = "auto-login"; 2088 2089 // a token is exactly token_hex_len hex chars. validating before using the 2090 // value as a path keeps attacker-supplied cookies from escaping the 2091 // sessions dir (e.g. via "/" or ".." bytes). 2092 fn isToken(token_hex: []const u8) bool { 2093 if (token_hex.len != token_hex_len) return false; 2094 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2095 return true; 2096 } 2097 }; 2098