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