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