╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1647 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1648 } 1649 1650 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1651 try request.respond("thread not found", .{ 1652 .status = .not_found, 1653 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1654 }); 1655 return; 1656 } 1657 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1658 try request.respond("thread not found", .{ 1659 .status = .not_found, 1660 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1661 }); 1662 return; 1663 }; 1664 const theirs: []const u8 = switch (route) { 1665 .repo_patches => |*patch| patch.theirs.slice(), 1666 .repo_issues => "", 1667 else => unreachable, 1668 }; 1669 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1670 1671 (switch (parts.thread_kind) { 1672 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1673 .title = title, 1674 .tags = tags, 1675 .hunks = hunks.items, 1676 } }, author), 1677 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1678 .title = title, 1679 .tags = tags, 1680 .hunks = hunks.items, 1681 .theirs = theirs, 1682 } }, author), 1683 else => unreachable, 1684 }) catch |err| switch (err) { 1685 error.NotFound => { 1686 try request.respond(not_found, .{ 1687 .status = .not_found, 1688 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1689 }); 1690 return; 1691 }, 1692 // invalid fields send the user back to the resolve form 1693 error.InvalidFields => { 1694 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1695 defer allocator.free(form_location); 1696 try request.respond("", .{ 1697 .status = .see_other, 1698 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1699 }); 1700 return; 1701 }, 1702 else => |e| return e, 1703 }; 1704 1705 try request.respond("", .{ 1706 .status = .see_other, 1707 .extra_headers = &.{.{ .name = "location", .value = base }}, 1708 }); 1709 } 1710 1711 fn handleSync( 1712 io: std.Io, 1713 request: *std.http.Server.Request, 1714 allocator: std.mem.Allocator, 1715 base: []const u8, 1716 source: ui.RepoSource, 1717 ) !void { 1718 if (base.len != 0) { 1719 try request.respond("not found", .{ 1720 .status = .not_found, 1721 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1722 }); 1723 return; 1724 } 1725 1726 var owned_failure: ?[]u8 = null; 1727 defer if (owned_failure) |message| allocator.free(message); 1728 const failure: ?[]const u8 = blk: { 1729 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1730 break :blk owned_failure; 1731 }; 1732 if (failure) |message| { 1733 var encoded: std.Io.Writer.Allocating = .init(allocator); 1734 defer encoded.deinit(); 1735 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1736 fn isUnreserved(c: u8) bool { 1737 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1738 } 1739 }.isUnreserved); 1740 const cookie = try std.fmt.allocPrint( 1741 allocator, 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 cells are the volatile part of a panel. js replaces this one subtree 1982 // wholesale while retaining the panel's native controls and scroll shells. 1983 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 1984 1985 // emit this panel's grid as rows of text, coalescing adjacent cells that 1986 // share a focus id and colors into one tag (a clickable span, a link, or a 1987 // plain colored span). cells under a child scroll keep only their background. 1988 for (0..grid.size.height) |y| { 1989 var cur_id: ?usize = null; 1990 var cur_fg: ?Grid.Color = null; 1991 var cur_bg: ?Grid.Color = null; 1992 var open_tag: ?CellTag = null; 1993 var first = true; 1994 for (0..grid.size.width) |x| { 1995 const cell = (try grid.cell(x, y)).*; 1996 // a cell covered by a child scroll's viewport is drawn by that scroll's 1997 // own div, so blank its glyph and make it non-clickable here — but keep 1998 // its background, so the backdrop still shows through the scroll's 1999 // transparent div instead of a bare hole. 2000 const covered_by_scroll = blk: { 2001 for (direct.items) |id| { 2002 const r = (focus.children.get(id) orelse continue).rect; 2003 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; 2004 } 2005 break :blk false; 2006 }; 2007 // the focusable cell at (x, y) among this panel's own focusables (skipping 2008 // any that belong to a child scroll, whose cells are drawn in their own 2009 // panel); none for a covered cell. 2010 const cell_id = if (covered_by_scroll) null else blk: { 2011 var iter = focus.children.iterator(); 2012 while (iter.next()) |entry| { 2013 const child = entry.value_ptr.*; 2014 if (child.focus.mode != .all) continue; 2015 if (excluded.contains(entry.key_ptr.*)) continue; 2016 const r = child.rect; 2017 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 2018 break :blk entry.key_ptr.*; 2019 } 2020 } 2021 break :blk null; 2022 }; 2023 const fg = if (covered_by_scroll) null else cell.style.fg; 2024 const bg = cell.style.bg; 2025 2026 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 2027 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2028 2029 var new_tag: ?CellTag = null; 2030 if (cell_id) |id| { 2031 if (focus.children.get(id)) |child| { 2032 new_tag = switch (child.focus.kind) { 2033 .custom => |custom| CellTag.init(custom), 2034 else => .span, 2035 }; 2036 } 2037 } 2038 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 2039 2040 if (new_tag) |t| { 2041 var style_buf: [64]u8 = undefined; 2042 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 2043 } 2044 2045 open_tag = new_tag; 2046 cur_id = cell_id; 2047 cur_fg = fg; 2048 cur_bg = bg; 2049 first = false; 2050 } 2051 2052 if (covered_by_scroll) { 2053 try appendEscapedHtml(allocator, output, " "); 2054 } else if (cell.continuation) { 2055 // the wide rune to the left was emitted 2ch wide, covering this column 2056 } else if (cell.rune) |rune| { 2057 var encoded: [4]u8 = undefined; 2058 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2059 const rune_text = encoded[0..encoded_len]; 2060 // a double-width rune is pinned inside a 2ch span so the 2061 // fallback glyph's advance width can't shift the rest of the row 2062 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2063 if (wide) { 2064 try output.appendSlice(allocator, "<span class=\"w2\">"); 2065 try appendEscapedHtml(allocator, output, rune_text); 2066 try output.appendSlice(allocator, "</span>"); 2067 } else { 2068 try appendEscapedHtml(allocator, output, rune_text); 2069 } 2070 } else { 2071 try appendEscapedHtml(allocator, output, " "); 2072 } 2073 } 2074 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2075 try output.append(allocator, '\n'); 2076 } 2077 try output.appendSlice(allocator, "</div>"); 2078 2079 // native controls live in their panel, beside the replaceable cells. their 2080 // stable keys let JS update layout without recreating their DOM nodes, and 2081 // being actual descendants of a scroll gives them native movement/clipping. 2082 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2083 2084 // each child scroll becomes a natively-scrollable div positioned over its 2085 // viewport, holding its full content rendered recursively. 2086 for (direct.items) |id| { 2087 const child = focus.children.get(id) orelse continue; 2088 const info = child.focus.scroll orelse continue; 2089 const r = child.rect; 2090 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2091 // when that axis actually overflows. the other axis is clipped (hidden), 2092 // matching how the terminal Scroll handles its non-scrolling axis. 2093 const overflow = switch (info.direction) { 2094 .vert => "overflow-x:hidden;overflow-y:auto", 2095 .horiz => "overflow-x:auto;overflow-y:hidden", 2096 .both => "overflow:auto", 2097 }; 2098 // the id carries a content version so JS preserves the native scroll 2099 // position across re-renders of the same content but resets it when the 2100 // content is replaced — e.g. selecting a different commit. the widget's 2101 // scroll offset (in cells) rides along so JS can apply it when it has no 2102 // preserved position, letting a wasm-side scrollToRect (the files list 2103 // scrolling to its selected row on page load) reach the browser. 2104 var buf: [256]u8 = undefined; 2105 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 })); 2106 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2107 try output.appendSlice(allocator, "</div>"); 2108 } 2109 } 2110 2111 const form_prefix = "form:"; 2112 const form_id_prefix = "haxy-form-"; 2113 2114 fn formAction(focus: *const Focus) ?[]const u8 { 2115 return switch (focus.kind) { 2116 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2117 else => null, 2118 }; 2119 } 2120 2121 // find the form ancestor of a flattened focus-tree child. html's `form` 2122 // attribute then associates the control with that form without requiring the 2123 // form and control to share a DOM parent. 2124 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2125 var id = focus_id; 2126 while (root_focus.children.get(id)) |child| { 2127 const parent_id = child.parent_id; 2128 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2129 const parent = root_focus.children.get(parent_id) orelse return null; 2130 if (formAction(parent.focus) != null) return parent_id; 2131 id = parent_id; 2132 } 2133 return null; 2134 } 2135 2136 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2137 const form_id = formOwner(root_focus, focus_id) orelse return; 2138 var buf: [64]u8 = undefined; 2139 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2140 } 2141 2142 fn renderPanelControls( 2143 allocator: std.mem.Allocator, 2144 output: *std.ArrayList(u8), 2145 focus: *Focus, 2146 session: *ui.Session, 2147 root_focus: *Focus, 2148 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2149 ) !void { 2150 var iter = focus.children.iterator(); 2151 while (iter.next()) |entry| { 2152 const id = entry.key_ptr.*; 2153 if (excluded.contains(id)) continue; 2154 const child = entry.value_ptr.*; 2155 const r = child.rect; 2156 2157 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2158 2159 switch (child.focus.kind) { 2160 .text_input, .text_input_password, .text_area => { 2161 const ti = session.text_inputs.get(id) orelse continue; 2162 2163 const inner_left = r.x + 1; 2164 const inner_top = r.y + 1; 2165 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2166 const preserve = !ti.options.read_only; 2167 2168 if (child.focus.kind == .text_area) { 2169 const value = try ti.text(allocator); 2170 defer allocator.free(value); 2171 var id_buf: [128]u8 = undefined; 2172 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2173 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2174 try appendFormAttribute(allocator, output, root_focus, id); 2175 if (ti.options.name.len > 0) { 2176 try output.appendSlice(allocator, " name=\""); 2177 try appendEscapedHtml(allocator, output, ti.options.name); 2178 try output.append(allocator, '"'); 2179 } 2180 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2181 var pos_buf: [128]u8 = undefined; 2182 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 })); 2183 try appendEscapedHtml(allocator, output, value); 2184 try output.appendSlice(allocator, "</textarea>"); 2185 continue; 2186 } 2187 2188 var id_buf: [160]u8 = undefined; 2189 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 })); 2190 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2191 try appendFormAttribute(allocator, output, root_focus, id); 2192 if (ti.options.name.len > 0) { 2193 try output.appendSlice(allocator, " name=\""); 2194 try appendEscapedHtml(allocator, output, ti.options.name); 2195 try output.append(allocator, '"'); 2196 } 2197 if (child.focus.kind != .text_input_password) { 2198 const value = try ti.text(allocator); 2199 defer allocator.free(value); 2200 try output.appendSlice(allocator, " value=\""); 2201 try appendEscapedHtml(allocator, output, value); 2202 try output.append(allocator, '"'); 2203 } 2204 var pos_buf: [96]u8 = undefined; 2205 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 })); 2206 }, 2207 .custom => |custom| { 2208 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2209 if (formOwner(root_focus, id) == null) continue; 2210 var id_buf: [128]u8 = undefined; 2211 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2212 try appendFormAttribute(allocator, output, root_focus, id); 2213 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2214 try output.appendSlice(allocator, " formaction=\""); 2215 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2216 try output.append(allocator, '"'); 2217 } 2218 var pos_buf: [128]u8 = undefined; 2219 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 })); 2220 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2221 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2222 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2223 var id_buf: [128]u8 = undefined; 2224 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 })); 2225 } 2226 }, 2227 else => {}, 2228 } 2229 } 2230 } 2231 2232 // emit hidden form owners beside the rendered panels. their controls point 2233 // back here with the standard HTML `form` attribute. 2234 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2235 // the focus child map preserves insertion order, which matches the order 2236 // widgets were added in code 2237 var iter = root_focus.children.iterator(); 2238 while (iter.next()) |entry| { 2239 const child = entry.value_ptr.*; 2240 const action_url = formAction(child.focus) orelse continue; 2241 2242 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2243 var id_buf: [96]u8 = undefined; 2244 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2245 try appendEscapedHtml(allocator, output, action_url); 2246 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2247 } 2248 } 2249 2250 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2251 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2252 return b == null; 2253 } 2254 2255 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2256 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2257 // empty slice when neither is set. 2258 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2259 if (fg == null and bg == null) return buf[0..0]; 2260 const prefix = " style=\""; 2261 @memcpy(buf[0..prefix.len], prefix); 2262 var i: usize = prefix.len; 2263 if (fg) |c| { 2264 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]; 2265 i += s.len; 2266 } 2267 if (bg) |c| { 2268 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]; 2269 i += s.len; 2270 } 2271 buf[i] = '"'; 2272 i += 1; 2273 return buf[0..i]; 2274 } 2275 2276 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2277 for (input) |ch| { 2278 switch (ch) { 2279 '&' => try out.appendSlice(allocator, "&amp;"), 2280 '<' => try out.appendSlice(allocator, "&lt;"), 2281 '>' => try out.appendSlice(allocator, "&gt;"), 2282 '"' => try out.appendSlice(allocator, "&quot;"), 2283 '\'' => try out.appendSlice(allocator, "&#39;"), 2284 else => try out.append(allocator, ch), 2285 } 2286 } 2287 } 2288 2289 // --- helpers -------------------------------------------------------------- 2290 2291 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2292 var iter = request.iterateHeaders(); 2293 while (iter.next()) |header| { 2294 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2295 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2296 while (pairs.next()) |pair| { 2297 const trimmed = std.mem.trim(u8, pair, " \t"); 2298 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2299 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2300 return trimmed[eq + 1 ..]; 2301 } 2302 } 2303 } 2304 return null; 2305 } 2306 2307 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2308 var iter = std.mem.splitScalar(u8, body, '&'); 2309 while (iter.next()) |pair| { 2310 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2311 if (std.mem.eql(u8, pair[0..eq], key)) { 2312 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2313 } 2314 } 2315 return null; 2316 } 2317 2318 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2319 var buffer: [256]u8 = undefined; 2320 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2321 } 2322 2323 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2324 var out: std.ArrayList(u8) = .empty; 2325 errdefer out.deinit(allocator); 2326 var i: usize = 0; 2327 while (i < encoded.len) : (i += 1) { 2328 switch (encoded[i]) { 2329 '+' => try out.append(allocator, ' '), 2330 '%' => { 2331 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2332 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2333 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2334 try out.append(allocator, hi * 16 + lo); 2335 i += 2; 2336 }, 2337 else => try out.append(allocator, encoded[i]), 2338 } 2339 } 2340 return try out.toOwnedSlice(allocator); 2341 } 2342 2343 // disk-backed web session store. each login mints a random, opaque token 2344 // (not the user's id) that is stored as a file named by the token hex, whose 2345 // contents are the raw user_id bytes. authenticating a request is a lookup of 2346 // the cookie's token; logout deletes the file, revoking the session. there is 2347 // deliberately no expiry — a session lives until logout. form failures use 2348 // files in the flash subdirectory that the redirected GET consumes. the 2349 // directory is cleared whenever the server starts. 2350 pub const SessionStore = struct { 2351 io: std.Io, 2352 dir: std.Io.Dir, 2353 flash_dir: std.Io.Dir, 2354 auto_login: ?[token_hex_len]u8, 2355 2356 pub const token_hex_len = evt.event_id_size * 2; 2357 2358 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2359 try data_dir.createDirPath(io, "sessions"); 2360 const dir = try data_dir.openDir(io, "sessions", .{}); 2361 errdefer dir.close(io); 2362 try dir.deleteTree(io, "flash"); 2363 try dir.createDirPath(io, "flash"); 2364 const flash_dir = try dir.openDir(io, "flash", .{}); 2365 errdefer flash_dir.close(io); 2366 const auto_login = blk: { 2367 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2368 defer file.close(io); 2369 var token: [token_hex_len]u8 = undefined; 2370 var storage: [token_hex_len]u8 = undefined; 2371 var reader = file.reader(io, &storage); 2372 reader.interface.readSliceAll(&token) catch break :blk null; 2373 break :blk token; 2374 }; 2375 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2376 } 2377 2378 pub fn deinit(self: SessionStore) void { 2379 self.flash_dir.close(self.io); 2380 self.dir.close(self.io); 2381 } 2382 2383 // mint a new session for user_id, returning the token hex to set as the 2384 // cookie value. 2385 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2386 var token: [evt.event_id_size]u8 = undefined; 2387 self.io.random(&token); 2388 const token_hex = std.fmt.bytesToHex(token, .lower); 2389 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2390 defer file.close(self.io); 2391 try file.writeStreamingAll(self.io, user_id); 2392 return token_hex; 2393 } 2394 2395 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2396 var token: [evt.event_id_size]u8 = undefined; 2397 self.io.random(&token); 2398 const token_hex = std.fmt.bytesToHex(token, .lower); 2399 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2400 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2401 defer file.close(self.io); 2402 2403 var json: std.Io.Writer.Allocating = .init(allocator); 2404 defer json.deinit(); 2405 try std.json.Stringify.value(value, .{}, &json.writer); 2406 try file.writeStreamingAll(self.io, json.written()); 2407 return token_hex; 2408 } 2409 2410 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2411 if (!isToken(token_hex)) return null; 2412 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2413 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2414 defer file.close(self.io); 2415 2416 var storage: [4096]u8 = undefined; 2417 var reader = file.reader(self.io, &storage); 2418 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2419 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2420 } 2421 2422 // resolve a cookie's token to its user_id. returns false (logged out) for a 2423 // missing, malformed, or unknown token. 2424 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2425 if (!isToken(token_hex)) return false; 2426 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2427 defer file.close(self.io); 2428 var storage: [evt.event_id_size]u8 = undefined; 2429 var file_reader = file.reader(self.io, &storage); 2430 file_reader.interface.readSliceAll(out) catch return false; 2431 return true; 2432 } 2433 2434 // revoke a session. a no-op for a missing or malformed token. 2435 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2436 if (!isToken(token_hex)) return; 2437 self.dir.deleteFile(self.io, token_hex) catch {}; 2438 } 2439 2440 // leave `token_hex`'s session for visitors arriving without one. only the 2441 // `try` fixture writes one. the name can't collide with a session token. 2442 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2443 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2444 defer file.close(self.io); 2445 try file.writeStreamingAll(self.io, token_hex); 2446 } 2447 2448 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2449 out.* = self.auto_login orelse return false; 2450 return true; 2451 } 2452 2453 const auto_login_name = "auto-login"; 2454 2455 // a token is exactly token_hex_len hex chars. validating before using the 2456 // value as a path keeps attacker-supplied cookies from escaping the 2457 // sessions dir (e.g. via "/" or ".." bytes). 2458 fn isToken(token_hex: []const u8) bool { 2459 if (token_hex.len != token_hex_len) return false; 2460 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2461 return true; 2462 } 2463 }; 2464