╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1646 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1647 .{encoded.written()}, 1648 ); 1649 defer allocator.free(cookie); 1650 try request.respond("", .{ 1651 .status = .see_other, 1652 .extra_headers = &.{ 1653 .{ .name = "location", .value = "/events" }, 1654 .{ .name = "set-cookie", .value = cookie }, 1655 }, 1656 }); 1657 return; 1658 } 1659 1660 try request.respond("", .{ 1661 .status = .see_other, 1662 .extra_headers = &.{ 1663 .{ .name = "location", .value = "/events" }, 1664 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1665 }, 1666 }); 1667 } 1668 1669 fn renderIndexHtml( 1670 io: std.Io, 1671 allocator: std.mem.Allocator, 1672 host: Host, 1673 session_data: ui.Session.Data, 1674 ) ![]const u8 { 1675 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1676 1677 var page_arena = std.heap.ArenaAllocator.init(allocator); 1678 defer page_arena.deinit(); 1679 1680 // the remote admin repo must outlive the page build, since the session's 1681 // moment reads from it. 1682 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1683 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1684 1685 var session = switch (host) { 1686 .remote => |remote| blk: { 1687 // open the admin repo to read live user/repo data. 1688 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1689 const repo = if (repo_maybe) |*repo| repo else unreachable; 1690 var session = try ui.Session.init(&page_arena, repo, session_data); 1691 // give the page builders filesystem access to the on-disk repos (a 1692 // sibling "repos" dir next to the admin repo) so the Repo page can 1693 // read its files. 1694 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1695 break :blk session; 1696 }, 1697 .local => |local| ui.Session{ 1698 .data = session_data, 1699 .arena = &page_arena, 1700 .page_arena = &page_arena, 1701 .local = local, 1702 }, 1703 }; 1704 session.io = io; 1705 1706 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1707 var root = try ui.initRoot(allocator, &page, &session); 1708 defer root.deinit(allocator); 1709 1710 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1711 1712 const content = try generateHtml(allocator, &root, &session); 1713 defer allocator.free(content); 1714 1715 // serialize the snapshot so the wasm side can parse it back without making 1716 // a second request. it's embedded raw in a <script type="application/json"> 1717 // block, whose content is raw text terminated only by "</script". in json, 1718 // '<' appears solely inside string values, so escaping every '<' (and '>' 1719 // for good measure) to its \uXXXX form yields equivalent json that can't 1720 // break out of the tag. 1721 var json: std.Io.Writer.Allocating = .init(allocator); 1722 defer json.deinit(); 1723 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1724 1725 var json_escaped: std.ArrayList(u8) = .empty; 1726 defer json_escaped.deinit(allocator); 1727 for (json.written()) |c| switch (c) { 1728 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1729 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1730 else => try json_escaped.append(allocator, c), 1731 }; 1732 1733 var out: std.ArrayList(u8) = .empty; 1734 errdefer out.deinit(allocator); 1735 { 1736 var cursor: usize = 0; 1737 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1738 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1739 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1740 }) |sub| { 1741 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1742 try out.appendSlice(allocator, template[cursor..idx]); 1743 try out.appendSlice(allocator, sub.replacement); 1744 cursor = idx + sub.needle.len; 1745 } 1746 try out.appendSlice(allocator, template[cursor..]); 1747 } 1748 return try out.toOwnedSlice(allocator); 1749 } 1750 1751 fn findEmbed(request_path: []const u8) ?Embed { 1752 const path = if (std.mem.eql(u8, request_path, "/")) 1753 "index.html" 1754 else if (request_path.len > 1 and request_path[0] == '/') 1755 request_path[1..] 1756 else 1757 return null; 1758 1759 for (embeds) |embed| { 1760 if (std.mem.eql(u8, path, embed.path)) return embed; 1761 } 1762 return null; 1763 } 1764 1765 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1766 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1767 // rendered recursively so nested scrolls work. 1768 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1769 const grid = root.getGrid() orelse return error.MissingGrid; 1770 const root_focus = root.getFocus(); 1771 1772 var out: std.ArrayList(u8) = .empty; 1773 errdefer out.deinit(allocator); 1774 1775 switch (root.*) { 1776 .background => |*background| { 1777 if (background.art.getGrid()) |art| { 1778 var position_buf: [64]u8 = undefined; 1779 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})); 1780 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1781 try out.appendSlice(allocator, "</div>"); 1782 } 1783 }, 1784 else => {}, 1785 } 1786 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1787 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1788 try out.appendSlice(allocator, "</div>"); 1789 try renderForms(allocator, &out, root_focus); 1790 return try out.toOwnedSlice(allocator); 1791 } 1792 1793 // render one panel — a focus subtree and its content grid — as HTML, recursing 1794 // once per web-native Scroll inside it. the root panel is the whole page; each 1795 // Scroll becomes a nested, natively-scrollable div holding its full content. 1796 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1797 // then the child scroll divs over those holes. 1798 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1799 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1800 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1801 // plus their descendants, which the focus tree flattens into this panel's 1802 // children): the cell hit-test below skips them so this panel doesn't claim 1803 // cells that are really rendered inside a child scroll's own panel. 1804 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1805 var direct: std.ArrayList(usize) = .empty; 1806 defer direct.deinit(allocator); 1807 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1808 defer excluded.deinit(allocator); 1809 { 1810 var it = focus.children.iterator(); 1811 while (it.next()) |e| { 1812 if (e.value_ptr.focus.scroll == null) continue; 1813 try direct.append(allocator, e.key_ptr.*); 1814 try excluded.put(allocator, e.key_ptr.*, {}); 1815 var mit = e.value_ptr.focus.children.iterator(); 1816 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1817 } 1818 } 1819 1820 // the HTML element a run of cells is wrapped in, chosen from the cell's 1821 // focusable kind 1822 const CellTag = union(enum) { 1823 span, // clickable focusable cell 1824 a: []const u8, // clickable focusable link 1825 plain, // non-focusable, colored 1826 1827 const a_prefix = "a:"; 1828 // an "in-page" anchor: rendered as a real <a href> so it works with js 1829 // disabled, but wasm handles it without navigating. 1830 fn init(str: []const u8) @This() { 1831 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1832 return .{ .a = str[ui.raw_link_prefix.len..] }; 1833 } 1834 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1835 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1836 } 1837 if (std.mem.startsWith(u8, str, a_prefix)) { 1838 return .{ .a = str[a_prefix.len..] }; 1839 } 1840 return .span; 1841 } 1842 1843 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1844 var id_buf: [32]u8 = undefined; 1845 switch (self) { 1846 .span => { 1847 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1848 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1849 try out.appendSlice(alloc, "\""); 1850 try out.appendSlice(alloc, style_attr); 1851 try out.appendSlice(alloc, ">"); 1852 }, 1853 .a => |href| { 1854 // tabindex=-1 keeps these out of the browser's tab order 1855 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1856 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1857 try out.appendSlice(alloc, "\" href=\""); 1858 try appendEscapedHtml(alloc, out, href); 1859 try out.appendSlice(alloc, "\""); 1860 try out.appendSlice(alloc, style_attr); 1861 try out.appendSlice(alloc, ">"); 1862 }, 1863 .plain => { 1864 try out.appendSlice(alloc, "<span"); 1865 try out.appendSlice(alloc, style_attr); 1866 try out.appendSlice(alloc, ">"); 1867 }, 1868 } 1869 } 1870 1871 fn closeTag(self: @This()) []const u8 { 1872 return switch (self) { 1873 .span, .plain => "</span>", 1874 .a => "</a>", 1875 }; 1876 } 1877 }; 1878 1879 // the cells are the volatile part of a panel. js replaces this one subtree 1880 // wholesale while retaining the panel's native controls and scroll shells. 1881 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 1882 1883 // emit this panel's grid as rows of text, coalescing adjacent cells that 1884 // share a focus id and colors into one tag (a clickable span, a link, or a 1885 // plain colored span). cells under a child scroll keep only their background. 1886 for (0..grid.size.height) |y| { 1887 var cur_id: ?usize = null; 1888 var cur_fg: ?Grid.Color = null; 1889 var cur_bg: ?Grid.Color = null; 1890 var open_tag: ?CellTag = null; 1891 var first = true; 1892 for (0..grid.size.width) |x| { 1893 const cell = (try grid.cell(x, y)).*; 1894 // a cell covered by a child scroll's viewport is drawn by that scroll's 1895 // own div, so blank its glyph and make it non-clickable here — but keep 1896 // its background, so the backdrop still shows through the scroll's 1897 // transparent div instead of a bare hole. 1898 const covered_by_scroll = blk: { 1899 for (direct.items) |id| { 1900 const r = (focus.children.get(id) orelse continue).rect; 1901 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; 1902 } 1903 break :blk false; 1904 }; 1905 // the focusable cell at (x, y) among this panel's own focusables (skipping 1906 // any that belong to a child scroll, whose cells are drawn in their own 1907 // panel); none for a covered cell. 1908 const cell_id = if (covered_by_scroll) null else blk: { 1909 var iter = focus.children.iterator(); 1910 while (iter.next()) |entry| { 1911 const child = entry.value_ptr.*; 1912 if (child.focus.mode != .all) continue; 1913 if (excluded.contains(entry.key_ptr.*)) continue; 1914 const r = child.rect; 1915 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1916 break :blk entry.key_ptr.*; 1917 } 1918 } 1919 break :blk null; 1920 }; 1921 const fg = if (covered_by_scroll) null else cell.style.fg; 1922 const bg = cell.style.bg; 1923 1924 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1925 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1926 1927 var new_tag: ?CellTag = null; 1928 if (cell_id) |id| { 1929 if (focus.children.get(id)) |child| { 1930 new_tag = switch (child.focus.kind) { 1931 .custom => |custom| CellTag.init(custom), 1932 else => .span, 1933 }; 1934 } 1935 } 1936 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1937 1938 if (new_tag) |t| { 1939 var style_buf: [64]u8 = undefined; 1940 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1941 } 1942 1943 open_tag = new_tag; 1944 cur_id = cell_id; 1945 cur_fg = fg; 1946 cur_bg = bg; 1947 first = false; 1948 } 1949 1950 if (covered_by_scroll) { 1951 try appendEscapedHtml(allocator, output, " "); 1952 } else if (cell.continuation) { 1953 // the wide rune to the left was emitted 2ch wide, covering this column 1954 } else if (cell.rune) |rune| { 1955 var encoded: [4]u8 = undefined; 1956 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 1957 const rune_text = encoded[0..encoded_len]; 1958 // a double-width rune is pinned inside a 2ch span so the 1959 // fallback glyph's advance width can't shift the rest of the row 1960 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 1961 if (wide) { 1962 try output.appendSlice(allocator, "<span class=\"w2\">"); 1963 try appendEscapedHtml(allocator, output, rune_text); 1964 try output.appendSlice(allocator, "</span>"); 1965 } else { 1966 try appendEscapedHtml(allocator, output, rune_text); 1967 } 1968 } else { 1969 try appendEscapedHtml(allocator, output, " "); 1970 } 1971 } 1972 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1973 try output.append(allocator, '\n'); 1974 } 1975 try output.appendSlice(allocator, "</div>"); 1976 1977 // native controls live in their panel, beside the replaceable cells. their 1978 // stable keys let JS update layout without recreating their DOM nodes, and 1979 // being actual descendants of a scroll gives them native movement/clipping. 1980 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 1981 1982 // each child scroll becomes a natively-scrollable div positioned over its 1983 // viewport, holding its full content rendered recursively. 1984 for (direct.items) |id| { 1985 const child = focus.children.get(id) orelse continue; 1986 const info = child.focus.scroll orelse continue; 1987 const r = child.rect; 1988 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1989 // when that axis actually overflows. the other axis is clipped (hidden), 1990 // matching how the terminal Scroll handles its non-scrolling axis. 1991 const overflow = switch (info.direction) { 1992 .vert => "overflow-x:hidden;overflow-y:auto", 1993 .horiz => "overflow-x:auto;overflow-y:hidden", 1994 .both => "overflow:auto", 1995 }; 1996 // the id carries a content version so JS preserves the native scroll 1997 // position across re-renders of the same content but resets it when the 1998 // content is replaced — e.g. selecting a different commit. the widget's 1999 // scroll offset (in cells) rides along so JS can apply it when it has no 2000 // preserved position, letting a wasm-side scrollToRect (the files list 2001 // scrolling to its selected row on page load) reach the browser. 2002 var buf: [256]u8 = undefined; 2003 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 })); 2004 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2005 try output.appendSlice(allocator, "</div>"); 2006 } 2007 } 2008 2009 const form_prefix = "form:"; 2010 const form_id_prefix = "haxy-form-"; 2011 2012 fn formAction(focus: *const Focus) ?[]const u8 { 2013 return switch (focus.kind) { 2014 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2015 else => null, 2016 }; 2017 } 2018 2019 // find the form ancestor of a flattened focus-tree child. html's `form` 2020 // attribute then associates the control with that form without requiring the 2021 // form and control to share a DOM parent. 2022 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2023 var id = focus_id; 2024 while (root_focus.children.get(id)) |child| { 2025 const parent_id = child.parent_id; 2026 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2027 const parent = root_focus.children.get(parent_id) orelse return null; 2028 if (formAction(parent.focus) != null) return parent_id; 2029 id = parent_id; 2030 } 2031 return null; 2032 } 2033 2034 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2035 const form_id = formOwner(root_focus, focus_id) orelse return; 2036 var buf: [64]u8 = undefined; 2037 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2038 } 2039 2040 fn renderPanelControls( 2041 allocator: std.mem.Allocator, 2042 output: *std.ArrayList(u8), 2043 focus: *Focus, 2044 session: *ui.Session, 2045 root_focus: *Focus, 2046 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2047 ) !void { 2048 var iter = focus.children.iterator(); 2049 while (iter.next()) |entry| { 2050 const id = entry.key_ptr.*; 2051 if (excluded.contains(id)) continue; 2052 const child = entry.value_ptr.*; 2053 const r = child.rect; 2054 2055 switch (child.focus.kind) { 2056 .text_input, .text_input_password, .text_area => { 2057 const ti = session.text_inputs.get(id) orelse continue; 2058 2059 const inner_left = r.x + 1; 2060 const inner_top = r.y + 1; 2061 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2062 const preserve = !ti.options.read_only; 2063 2064 if (child.focus.kind == .text_area) { 2065 const value = try ti.text(allocator); 2066 defer allocator.free(value); 2067 var id_buf: [128]u8 = undefined; 2068 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2069 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2070 try appendFormAttribute(allocator, output, root_focus, id); 2071 if (ti.options.name.len > 0) { 2072 try output.appendSlice(allocator, " name=\""); 2073 try appendEscapedHtml(allocator, output, ti.options.name); 2074 try output.append(allocator, '"'); 2075 } 2076 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2077 var pos_buf: [128]u8 = undefined; 2078 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 })); 2079 try appendEscapedHtml(allocator, output, value); 2080 try output.appendSlice(allocator, "</textarea>"); 2081 continue; 2082 } 2083 2084 var id_buf: [160]u8 = undefined; 2085 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 })); 2086 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2087 try appendFormAttribute(allocator, output, root_focus, id); 2088 if (ti.options.name.len > 0) { 2089 try output.appendSlice(allocator, " name=\""); 2090 try appendEscapedHtml(allocator, output, ti.options.name); 2091 try output.append(allocator, '"'); 2092 } 2093 if (child.focus.kind != .text_input_password) { 2094 const value = try ti.text(allocator); 2095 defer allocator.free(value); 2096 try output.appendSlice(allocator, " value=\""); 2097 try appendEscapedHtml(allocator, output, value); 2098 try output.append(allocator, '"'); 2099 } 2100 var pos_buf: [96]u8 = undefined; 2101 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 })); 2102 }, 2103 .custom => |custom| { 2104 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2105 if (formOwner(root_focus, id) == null) continue; 2106 var id_buf: [128]u8 = undefined; 2107 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2108 try appendFormAttribute(allocator, output, root_focus, id); 2109 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2110 try output.appendSlice(allocator, " formaction=\""); 2111 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2112 try output.append(allocator, '"'); 2113 } 2114 var pos_buf: [128]u8 = undefined; 2115 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 })); 2116 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2117 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2118 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2119 var id_buf: [128]u8 = undefined; 2120 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 })); 2121 } 2122 }, 2123 else => {}, 2124 } 2125 } 2126 } 2127 2128 // emit hidden form owners beside the rendered panels. their controls point 2129 // back here with the standard HTML `form` attribute. 2130 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2131 // the focus child map preserves insertion order, which matches the order 2132 // widgets were added in code 2133 var iter = root_focus.children.iterator(); 2134 while (iter.next()) |entry| { 2135 const child = entry.value_ptr.*; 2136 const action_url = formAction(child.focus) orelse continue; 2137 2138 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2139 var id_buf: [96]u8 = undefined; 2140 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2141 try appendEscapedHtml(allocator, output, action_url); 2142 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2143 } 2144 } 2145 2146 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2147 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2148 return b == null; 2149 } 2150 2151 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2152 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2153 // empty slice when neither is set. 2154 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2155 if (fg == null and bg == null) return buf[0..0]; 2156 const prefix = " style=\""; 2157 @memcpy(buf[0..prefix.len], prefix); 2158 var i: usize = prefix.len; 2159 if (fg) |c| { 2160 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]; 2161 i += s.len; 2162 } 2163 if (bg) |c| { 2164 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]; 2165 i += s.len; 2166 } 2167 buf[i] = '"'; 2168 i += 1; 2169 return buf[0..i]; 2170 } 2171 2172 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2173 for (input) |ch| { 2174 switch (ch) { 2175 '&' => try out.appendSlice(allocator, "&amp;"), 2176 '<' => try out.appendSlice(allocator, "&lt;"), 2177 '>' => try out.appendSlice(allocator, "&gt;"), 2178 '"' => try out.appendSlice(allocator, "&quot;"), 2179 '\'' => try out.appendSlice(allocator, "&#39;"), 2180 else => try out.append(allocator, ch), 2181 } 2182 } 2183 } 2184 2185 // --- helpers -------------------------------------------------------------- 2186 2187 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2188 var iter = request.iterateHeaders(); 2189 while (iter.next()) |header| { 2190 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2191 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2192 while (pairs.next()) |pair| { 2193 const trimmed = std.mem.trim(u8, pair, " \t"); 2194 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2195 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2196 return trimmed[eq + 1 ..]; 2197 } 2198 } 2199 } 2200 return null; 2201 } 2202 2203 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2204 var iter = std.mem.splitScalar(u8, body, '&'); 2205 while (iter.next()) |pair| { 2206 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2207 if (std.mem.eql(u8, pair[0..eq], key)) { 2208 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2209 } 2210 } 2211 return null; 2212 } 2213 2214 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2215 var buffer: [256]u8 = undefined; 2216 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2217 } 2218 2219 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2220 var out: std.ArrayList(u8) = .empty; 2221 errdefer out.deinit(allocator); 2222 var i: usize = 0; 2223 while (i < encoded.len) : (i += 1) { 2224 switch (encoded[i]) { 2225 '+' => try out.append(allocator, ' '), 2226 '%' => { 2227 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2228 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2229 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2230 try out.append(allocator, hi * 16 + lo); 2231 i += 2; 2232 }, 2233 else => try out.append(allocator, encoded[i]), 2234 } 2235 } 2236 return try out.toOwnedSlice(allocator); 2237 } 2238 2239 // disk-backed web session store. each login mints a random, opaque token 2240 // (not the user's id) that is stored as a file named by the token hex, whose 2241 // contents are the raw user_id bytes. authenticating a request is a lookup of 2242 // the cookie's token; logout deletes the file, revoking the session. there is 2243 // deliberately no expiry — a session lives until logout. form failures use 2244 // files in the flash subdirectory that the redirected GET consumes. the 2245 // directory is cleared whenever the server starts. 2246 pub const SessionStore = struct { 2247 io: std.Io, 2248 dir: std.Io.Dir, 2249 flash_dir: std.Io.Dir, 2250 auto_login: ?[token_hex_len]u8, 2251 2252 pub const token_hex_len = evt.event_id_size * 2; 2253 2254 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2255 try data_dir.createDirPath(io, "sessions"); 2256 const dir = try data_dir.openDir(io, "sessions", .{}); 2257 errdefer dir.close(io); 2258 try dir.deleteTree(io, "flash"); 2259 try dir.createDirPath(io, "flash"); 2260 const flash_dir = try dir.openDir(io, "flash", .{}); 2261 errdefer flash_dir.close(io); 2262 const auto_login = blk: { 2263 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2264 defer file.close(io); 2265 var token: [token_hex_len]u8 = undefined; 2266 var storage: [token_hex_len]u8 = undefined; 2267 var reader = file.reader(io, &storage); 2268 reader.interface.readSliceAll(&token) catch break :blk null; 2269 break :blk token; 2270 }; 2271 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2272 } 2273 2274 pub fn deinit(self: SessionStore) void { 2275 self.flash_dir.close(self.io); 2276 self.dir.close(self.io); 2277 } 2278 2279 // mint a new session for user_id, returning the token hex to set as the 2280 // cookie value. 2281 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2282 var token: [evt.event_id_size]u8 = undefined; 2283 self.io.random(&token); 2284 const token_hex = std.fmt.bytesToHex(token, .lower); 2285 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2286 defer file.close(self.io); 2287 try file.writeStreamingAll(self.io, user_id); 2288 return token_hex; 2289 } 2290 2291 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2292 var token: [evt.event_id_size]u8 = undefined; 2293 self.io.random(&token); 2294 const token_hex = std.fmt.bytesToHex(token, .lower); 2295 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2296 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2297 defer file.close(self.io); 2298 2299 var json: std.Io.Writer.Allocating = .init(allocator); 2300 defer json.deinit(); 2301 try std.json.Stringify.value(value, .{}, &json.writer); 2302 try file.writeStreamingAll(self.io, json.written()); 2303 return token_hex; 2304 } 2305 2306 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2307 if (!isToken(token_hex)) return null; 2308 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2309 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2310 defer file.close(self.io); 2311 2312 var storage: [4096]u8 = undefined; 2313 var reader = file.reader(self.io, &storage); 2314 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2315 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2316 } 2317 2318 // resolve a cookie's token to its user_id. returns false (logged out) for a 2319 // missing, malformed, or unknown token. 2320 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2321 if (!isToken(token_hex)) return false; 2322 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2323 defer file.close(self.io); 2324 var storage: [evt.event_id_size]u8 = undefined; 2325 var file_reader = file.reader(self.io, &storage); 2326 file_reader.interface.readSliceAll(out) catch return false; 2327 return true; 2328 } 2329 2330 // revoke a session. a no-op for a missing or malformed token. 2331 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2332 if (!isToken(token_hex)) return; 2333 self.dir.deleteFile(self.io, token_hex) catch {}; 2334 } 2335 2336 // leave `token_hex`'s session for visitors arriving without one. only the 2337 // `try` fixture writes one. the name can't collide with a session token. 2338 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2339 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2340 defer file.close(self.io); 2341 try file.writeStreamingAll(self.io, token_hex); 2342 } 2343 2344 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2345 out.* = self.auto_login orelse return false; 2346 return true; 2347 } 2348 2349 const auto_login_name = "auto-login"; 2350 2351 // a token is exactly token_hex_len hex chars. validating before using the 2352 // value as a path keeps attacker-supplied cookies from escaping the 2353 // sessions dir (e.g. via "/" or ".." bytes). 2354 fn isToken(token_hex: []const u8) bool { 2355 if (token_hex.len != token_hex_len) return false; 2356 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2357 return true; 2358 } 2359 }; 2360