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