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