╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1983 try out.appendSlice(alloc, ">"); 1984 }, 1985 .a => |href| { 1986 // tabindex=-1 keeps these out of the browser's tab order 1987 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1988 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1989 try out.appendSlice(alloc, "\" href=\""); 1990 try appendEscapedHtml(alloc, out, href); 1991 try out.appendSlice(alloc, "\""); 1992 try out.appendSlice(alloc, style_attr); 1993 try out.appendSlice(alloc, ">"); 1994 }, 1995 .plain => { 1996 try out.appendSlice(alloc, "<span"); 1997 try out.appendSlice(alloc, style_attr); 1998 try out.appendSlice(alloc, ">"); 1999 }, 2000 } 2001 } 2002 2003 fn closeTag(self: @This()) []const u8 { 2004 return switch (self) { 2005 .span, .plain => "</span>", 2006 .a => "</a>", 2007 }; 2008 } 2009 }; 2010 2011 // the focusable owning each cell, among this panel's own (skipping any 2012 // that belong to a child scroll, whose cells are drawn in their own panel). 2013 // claimed in focus order, so the first focusable over a cell keeps it. 2014 // looking every focusable up for every cell is quadratic in a long list. 2015 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2016 defer allocator.free(owners); 2017 @memset(owners, null); 2018 { 2019 var it = focus.children.iterator(); 2020 while (it.next()) |entry| { 2021 const child = entry.value_ptr.*; 2022 if (child.focus.mode != .all) continue; 2023 if (excluded.contains(entry.key_ptr.*)) continue; 2024 const r = child.rect; 2025 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2026 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2027 const owner = &owners[y * grid.size.width + x]; 2028 if (owner.* == null) owner.* = entry.key_ptr.*; 2029 } 2030 } 2031 } 2032 } 2033 2034 // the cells are the volatile part of a panel. js replaces this one subtree 2035 // wholesale while retaining the panel's native controls and scroll shells. 2036 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2037 2038 // emit this panel's grid as rows of text, coalescing adjacent cells that 2039 // share a focus id and colors into one tag (a clickable span, a link, or a 2040 // plain colored span). cells under a child scroll keep only their background. 2041 for (0..grid.size.height) |y| { 2042 var cur_id: ?usize = null; 2043 var cur_fg: ?Grid.Color = null; 2044 var cur_bg: ?Grid.Color = null; 2045 var cur_inverted = false; 2046 var open_tag: ?CellTag = null; 2047 var first = true; 2048 for (0..grid.size.width) |x| { 2049 const cell = (try grid.cell(x, y)).*; 2050 // a cell covered by a child scroll's viewport is drawn by that scroll's 2051 // own div, so blank its glyph and make it non-clickable here — but keep 2052 // its background, so the backdrop still shows through the scroll's 2053 // transparent div instead of a bare hole. 2054 const covered_by_scroll = blk: { 2055 for (direct.items) |id| { 2056 const r = (focus.children.get(id) orelse continue).rect; 2057 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; 2058 } 2059 break :blk false; 2060 }; 2061 // the focusable owning the cell at (x, y); none for a covered cell. 2062 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2063 const fg = if (covered_by_scroll) null else cell.style.fg; 2064 const bg = cell.style.bg; 2065 const inverted = !covered_by_scroll and cell.style.inverted; 2066 2067 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg) or inverted != cur_inverted) { 2068 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2069 2070 var new_tag: ?CellTag = null; 2071 if (cell_id) |id| { 2072 if (focus.children.get(id)) |child| { 2073 new_tag = switch (child.focus.kind) { 2074 .custom => |custom| CellTag.init(custom), 2075 else => .span, 2076 }; 2077 } 2078 } 2079 if (new_tag == null and (fg != null or bg != null or inverted)) new_tag = .plain; 2080 2081 if (new_tag) |t| { 2082 var style_buf: [64]u8 = undefined; 2083 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg, inverted)); 2084 } 2085 2086 open_tag = new_tag; 2087 cur_id = cell_id; 2088 cur_fg = fg; 2089 cur_bg = bg; 2090 cur_inverted = inverted; 2091 first = false; 2092 } 2093 2094 if (covered_by_scroll) { 2095 try appendEscapedHtml(allocator, output, " "); 2096 } else if (cell.continuation) { 2097 // the wide rune to the left was emitted 2ch wide, covering this column 2098 } else if (cell.rune) |rune| { 2099 var encoded: [4]u8 = undefined; 2100 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2101 const rune_text = encoded[0..encoded_len]; 2102 // a double-width rune is pinned inside a 2ch span so the 2103 // fallback glyph's advance width can't shift the rest of the row 2104 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2105 if (wide) { 2106 try output.appendSlice(allocator, "<span class=\"w2\">"); 2107 try appendEscapedHtml(allocator, output, rune_text); 2108 try output.appendSlice(allocator, "</span>"); 2109 } else { 2110 try appendEscapedHtml(allocator, output, rune_text); 2111 } 2112 } else { 2113 try appendEscapedHtml(allocator, output, " "); 2114 } 2115 } 2116 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2117 try output.append(allocator, '\n'); 2118 } 2119 try output.appendSlice(allocator, "</div>"); 2120 2121 // native controls live in their panel, beside the replaceable cells. their 2122 // stable keys let JS update layout without recreating their DOM nodes, and 2123 // being actual descendants of a scroll gives them native movement/clipping. 2124 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2125 2126 // each child scroll becomes a natively-scrollable div positioned over its 2127 // viewport, holding its full content rendered recursively. 2128 for (direct.items) |id| { 2129 const child = focus.children.get(id) orelse continue; 2130 const info = child.focus.scroll orelse continue; 2131 const r = child.rect; 2132 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2133 // when that axis actually overflows. the other axis is clipped (hidden), 2134 // matching how the terminal Scroll handles its non-scrolling axis. 2135 const overflow = switch (info.direction) { 2136 .vert => "overflow-x:hidden;overflow-y:auto", 2137 .horiz => "overflow-x:auto;overflow-y:hidden", 2138 .both => "overflow:auto", 2139 }; 2140 // the id carries a content version so JS preserves the native scroll 2141 // position across re-renders of the same content but resets it when the 2142 // content is replaced — e.g. selecting a different commit. the widget's 2143 // scroll offset (in cells) rides along so JS can apply it when it has no 2144 // preserved position, letting a wasm-side scrollToRect (the files list 2145 // scrolling to its selected row on page load) reach the browser. 2146 var buf: [256]u8 = undefined; 2147 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 })); 2148 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2149 try output.appendSlice(allocator, "</div>"); 2150 } 2151 } 2152 2153 const form_prefix = "form:"; 2154 const form_id_prefix = "haxy-form-"; 2155 2156 fn formAction(focus: *const Focus) ?[]const u8 { 2157 return switch (focus.kind) { 2158 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2159 else => null, 2160 }; 2161 } 2162 2163 // find the form ancestor of a flattened focus-tree child. html's `form` 2164 // attribute then associates the control with that form without requiring the 2165 // form and control to share a DOM parent. 2166 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2167 var id = focus_id; 2168 while (root_focus.children.get(id)) |child| { 2169 const parent_id = child.parent_id; 2170 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2171 const parent = root_focus.children.get(parent_id) orelse return null; 2172 if (formAction(parent.focus) != null) return parent_id; 2173 id = parent_id; 2174 } 2175 return null; 2176 } 2177 2178 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2179 const form_id = formOwner(root_focus, focus_id) orelse return; 2180 var buf: [64]u8 = undefined; 2181 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2182 } 2183 2184 fn renderPanelControls( 2185 allocator: std.mem.Allocator, 2186 output: *std.ArrayList(u8), 2187 focus: *Focus, 2188 session: *ui.Session, 2189 root_focus: *Focus, 2190 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2191 ) !void { 2192 var iter = focus.children.iterator(); 2193 while (iter.next()) |entry| { 2194 const id = entry.key_ptr.*; 2195 if (excluded.contains(id)) continue; 2196 const child = entry.value_ptr.*; 2197 const r = child.rect; 2198 2199 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2200 2201 switch (child.focus.kind) { 2202 .text_input, .text_input_password, .text_area => { 2203 const ti = session.text_inputs.get(id) orelse continue; 2204 2205 const inner_left = r.x + 1; 2206 const inner_top = r.y + 1; 2207 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2208 const preserve = !ti.options.read_only; 2209 2210 if (child.focus.kind == .text_area) { 2211 const value = try ti.text(allocator); 2212 defer allocator.free(value); 2213 var id_buf: [128]u8 = undefined; 2214 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2215 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2216 try appendFormAttribute(allocator, output, root_focus, id); 2217 if (ti.options.name.len > 0) { 2218 try output.appendSlice(allocator, " name=\""); 2219 try appendEscapedHtml(allocator, output, ti.options.name); 2220 try output.append(allocator, '"'); 2221 } 2222 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2223 var pos_buf: [128]u8 = undefined; 2224 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 })); 2225 try appendEscapedHtml(allocator, output, value); 2226 try output.appendSlice(allocator, "</textarea>"); 2227 continue; 2228 } 2229 2230 var id_buf: [160]u8 = undefined; 2231 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 })); 2232 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2233 try appendFormAttribute(allocator, output, root_focus, id); 2234 if (ti.options.name.len > 0) { 2235 try output.appendSlice(allocator, " name=\""); 2236 try appendEscapedHtml(allocator, output, ti.options.name); 2237 try output.append(allocator, '"'); 2238 } 2239 if (child.focus.kind != .text_input_password) { 2240 const value = try ti.text(allocator); 2241 defer allocator.free(value); 2242 try output.appendSlice(allocator, " value=\""); 2243 try appendEscapedHtml(allocator, output, value); 2244 try output.append(allocator, '"'); 2245 } 2246 var pos_buf: [96]u8 = undefined; 2247 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 })); 2248 }, 2249 .custom => |custom| { 2250 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2251 if (formOwner(root_focus, id) == null) continue; 2252 var id_buf: [128]u8 = undefined; 2253 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2254 try appendFormAttribute(allocator, output, root_focus, id); 2255 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2256 try output.appendSlice(allocator, " formaction=\""); 2257 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2258 try output.append(allocator, '"'); 2259 } 2260 var pos_buf: [128]u8 = undefined; 2261 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 })); 2262 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2263 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2264 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2265 var id_buf: [128]u8 = undefined; 2266 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 })); 2267 } 2268 }, 2269 else => {}, 2270 } 2271 } 2272 } 2273 2274 // emit hidden form owners beside the rendered panels. their controls point 2275 // back here with the standard HTML `form` attribute. 2276 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2277 // the focus child map preserves insertion order, which matches the order 2278 // widgets were added in code 2279 var iter = root_focus.children.iterator(); 2280 while (iter.next()) |entry| { 2281 const child = entry.value_ptr.*; 2282 const action_url = formAction(child.focus) orelse continue; 2283 2284 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2285 var id_buf: [96]u8 = undefined; 2286 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2287 try appendEscapedHtml(allocator, output, action_url); 2288 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2289 } 2290 } 2291 2292 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2293 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2294 return b == null; 2295 } 2296 2297 // the 16 ansi colors as the browser shows them (xterm's defaults) 2298 const ansi_palette = [16]Grid.Color.Rgb{ 2299 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2300 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2301 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2302 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2303 }; 2304 2305 // resolve any color to rgb: palette colors through the ansi table and the 2306 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2307 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2308 return switch (color) { 2309 .rgb => |c| c, 2310 .ansi => |a| ansi_palette[@intFromEnum(a)], 2311 .indexed => |n| if (n < 16) 2312 ansi_palette[n] 2313 else if (n < 232) blk: { 2314 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2315 const i = n - 16; 2316 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2317 } else blk: { 2318 const v: u8 = 8 + (n - 232) * 10; 2319 break :blk .{ .r = v, .g = v, .b = v }; 2320 }, 2321 }; 2322 } 2323 2324 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2325 // cell's fg/bg into `buf`, omitting whichever color is unset. an inverted 2326 // cell swaps the two, falling back to the page's --fg/--bg variables for 2327 // whichever side is unset. returns an empty slice when nothing is set. 2328 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color, inverted: bool) []const u8 { 2329 if (fg == null and bg == null and !inverted) return buf[0..0]; 2330 const prefix = " style=\""; 2331 @memcpy(buf[0..prefix.len], prefix); 2332 var i: usize = prefix.len; 2333 const text = if (inverted) bg else fg; 2334 const back = if (inverted) fg else bg; 2335 if (text) |c| { 2336 const v = colorRgb(c); 2337 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ v.r, v.g, v.b }) catch return buf[0..0]; 2338 i += s.len; 2339 } else if (inverted) { 2340 const s = std.fmt.bufPrint(buf[i..], "color:var(--bg);", .{}) catch return buf[0..0]; 2341 i += s.len; 2342 } 2343 if (back) |c| { 2344 const v = colorRgb(c); 2345 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ v.r, v.g, v.b }) catch return buf[0..0]; 2346 i += s.len; 2347 } else if (inverted) { 2348 const s = std.fmt.bufPrint(buf[i..], "background-color:var(--fg);", .{}) catch return buf[0..0]; 2349 i += s.len; 2350 } 2351 buf[i] = '"'; 2352 i += 1; 2353 return buf[0..i]; 2354 } 2355 2356 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2357 for (input) |ch| { 2358 switch (ch) { 2359 '&' => try out.appendSlice(allocator, "&amp;"), 2360 '<' => try out.appendSlice(allocator, "&lt;"), 2361 '>' => try out.appendSlice(allocator, "&gt;"), 2362 '"' => try out.appendSlice(allocator, "&quot;"), 2363 '\'' => try out.appendSlice(allocator, "&#39;"), 2364 else => try out.append(allocator, ch), 2365 } 2366 } 2367 } 2368 2369 // --- helpers -------------------------------------------------------------- 2370 2371 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2372 var iter = request.iterateHeaders(); 2373 while (iter.next()) |header| { 2374 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2375 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2376 while (pairs.next()) |pair| { 2377 const trimmed = std.mem.trim(u8, pair, " \t"); 2378 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2379 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2380 return trimmed[eq + 1 ..]; 2381 } 2382 } 2383 } 2384 return null; 2385 } 2386 2387 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2388 var iter = std.mem.splitScalar(u8, body, '&'); 2389 while (iter.next()) |pair| { 2390 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2391 if (std.mem.eql(u8, pair[0..eq], key)) { 2392 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2393 } 2394 } 2395 return null; 2396 } 2397 2398 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2399 var buffer: [256]u8 = undefined; 2400 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2401 } 2402 2403 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2404 var out: std.ArrayList(u8) = .empty; 2405 errdefer out.deinit(allocator); 2406 var i: usize = 0; 2407 while (i < encoded.len) : (i += 1) { 2408 switch (encoded[i]) { 2409 '+' => try out.append(allocator, ' '), 2410 '%' => { 2411 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2412 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2413 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2414 try out.append(allocator, hi * 16 + lo); 2415 i += 2; 2416 }, 2417 else => try out.append(allocator, encoded[i]), 2418 } 2419 } 2420 return try out.toOwnedSlice(allocator); 2421 } 2422 2423 // disk-backed web session store. each login mints a random, opaque token 2424 // (not the user's id) that is stored as a file named by the token hex, whose 2425 // contents are the raw user_id bytes. authenticating a request is a lookup of 2426 // the cookie's token; logout deletes the file, revoking the session. there is 2427 // deliberately no expiry — a session lives until logout. form failures use 2428 // files in the flash subdirectory that the redirected GET consumes. the 2429 // directory is cleared whenever the server starts. 2430 pub const SessionStore = struct { 2431 io: std.Io, 2432 dir: std.Io.Dir, 2433 flash_dir: std.Io.Dir, 2434 auto_login: ?[token_hex_len]u8, 2435 2436 pub const token_hex_len = evt.event_id_size * 2; 2437 2438 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2439 try data_dir.createDirPath(io, "sessions"); 2440 const dir = try data_dir.openDir(io, "sessions", .{}); 2441 errdefer dir.close(io); 2442 try dir.deleteTree(io, "flash"); 2443 try dir.createDirPath(io, "flash"); 2444 const flash_dir = try dir.openDir(io, "flash", .{}); 2445 errdefer flash_dir.close(io); 2446 const auto_login = blk: { 2447 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2448 defer file.close(io); 2449 var token: [token_hex_len]u8 = undefined; 2450 var storage: [token_hex_len]u8 = undefined; 2451 var reader = file.reader(io, &storage); 2452 reader.interface.readSliceAll(&token) catch break :blk null; 2453 break :blk token; 2454 }; 2455 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2456 } 2457 2458 pub fn deinit(self: SessionStore) void { 2459 self.flash_dir.close(self.io); 2460 self.dir.close(self.io); 2461 } 2462 2463 // mint a new session for user_id, returning the token hex to set as the 2464 // cookie value. 2465 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2466 var token: [evt.event_id_size]u8 = undefined; 2467 self.io.random(&token); 2468 const token_hex = std.fmt.bytesToHex(token, .lower); 2469 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2470 defer file.close(self.io); 2471 try file.writeStreamingAll(self.io, user_id); 2472 return token_hex; 2473 } 2474 2475 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2476 var token: [evt.event_id_size]u8 = undefined; 2477 self.io.random(&token); 2478 const token_hex = std.fmt.bytesToHex(token, .lower); 2479 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2480 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2481 defer file.close(self.io); 2482 2483 var json: std.Io.Writer.Allocating = .init(allocator); 2484 defer json.deinit(); 2485 try std.json.Stringify.value(value, .{}, &json.writer); 2486 try file.writeStreamingAll(self.io, json.written()); 2487 return token_hex; 2488 } 2489 2490 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2491 if (!isToken(token_hex)) return null; 2492 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2493 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2494 defer file.close(self.io); 2495 2496 var storage: [4096]u8 = undefined; 2497 var reader = file.reader(self.io, &storage); 2498 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2499 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2500 } 2501 2502 // resolve a cookie's token to its user_id. returns false (logged out) for a 2503 // missing, malformed, or unknown token. 2504 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2505 if (!isToken(token_hex)) return false; 2506 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2507 defer file.close(self.io); 2508 var storage: [evt.event_id_size]u8 = undefined; 2509 var file_reader = file.reader(self.io, &storage); 2510 file_reader.interface.readSliceAll(out) catch return false; 2511 return true; 2512 } 2513 2514 // revoke a session. a no-op for a missing or malformed token. 2515 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2516 if (!isToken(token_hex)) return; 2517 self.dir.deleteFile(self.io, token_hex) catch {}; 2518 } 2519 2520 // leave `token_hex`'s session for visitors arriving without one. only the 2521 // `try` fixture writes one. the name can't collide with a session token. 2522 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2523 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2524 defer file.close(self.io); 2525 try file.writeStreamingAll(self.io, token_hex); 2526 } 2527 2528 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2529 out.* = self.auto_login orelse return false; 2530 return true; 2531 } 2532 2533 const auto_login_name = "auto-login"; 2534 2535 // a token is exactly token_hex_len hex chars. validating before using the 2536 // value as a path keeps attacker-supplied cookies from escaping the 2537 // sessions dir (e.g. via "/" or ".." bytes). 2538 fn isToken(token_hex: []const u8) bool { 2539 if (token_hex.len != token_hex_len) return false; 2540 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2541 return true; 2542 } 2543 }; 2544