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