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