╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
2077 // newlines so the text renders the same on every host 2078 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 2079 defer allocator.free(description); 2080 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 2081 defer allocator.free(target_branch); 2082 2083 // invalid fields send the user back to the edit form 2084 const valid = switch (parts.thread_kind) { 2085 .issue => evt.Issue.fieldsValid(title, labels), 2086 .patch => evt.Patch.fieldsValid(title, labels), 2087 .discuss => evt.Discussion.fieldsValid(title, labels), 2088 else => unreachable, 2089 }; 2090 if (!valid) { 2091 const form_location = try allocator.print("{s}/edit", .{base}); 2092 defer allocator.free(form_location); 2093 if (!evt.titleValid(title)) { 2094 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, labels, description, target_branch, null)); 2095 } 2096 try request.respond("", .{ 2097 .status = .see_other, 2098 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2099 }); 2100 return; 2101 } 2102 2103 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 2104 defer request_repo.deinit(allocator); 2105 2106 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 2107 if (draft_user_id) |user_id| { 2108 const server = switch (host) { 2109 .server => |server| server, 2110 .local => unreachable, 2111 }; 2112 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 2113 const form_location = try allocator.print("{s}/edit", .{base}); 2114 defer allocator.free(form_location); 2115 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 2116 } 2117 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 2118 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2119 defer admin_repo.deinit(io, allocator); 2120 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 2121 if (try pch.editDraft(.{}, io, allocator, server.users_dir, &admin_repo, .{ 2122 .id = id, 2123 .user_id = user_id, 2124 .repo_id = repo_id, 2125 .title = title, 2126 .labels = labels, 2127 .description = description, 2128 .target_branch = target_branch, 2129 .author = author, 2130 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2131 })) { 2132 try request.respond("", .{ 2133 .status = .see_other, 2134 .extra_headers = &.{.{ .name = "location", .value = base }}, 2135 }); 2136 return; 2137 } 2138 } 2139 2140 // a draft is its author's alone, which its edit above checks 2141 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 2142 2143 const not_found = switch (parts.thread_kind) { 2144 .issue => "issue not found", 2145 .patch => "patch not found", 2146 .discuss => "discussion not found", 2147 else => unreachable, 2148 }; 2149 (switch (parts.thread_kind) { 2150 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2151 .title = title, 2152 .labels = labels, 2153 .description = description, 2154 } }, author), 2155 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2156 .title = title, 2157 .labels = labels, 2158 .description = description, 2159 .target_branch = target_branch, 2160 } }, author), 2161 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, labels, description, author), 2162 else => unreachable, 2163 }) catch |err| switch (err) { 2164 error.NotFound => { 2165 try request.respond(not_found, .{ 2166 .status = .not_found, 2167 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2168 }); 2169 return; 2170 }, 2171 else => { 2172 if (parts.thread_kind != .patch) return err; 2173 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 2174 const form_location = try allocator.print("{s}/edit", .{base}); 2175 defer allocator.free(form_location); 2176 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, null)); 2177 }, 2178 }; 2179 2180 try request.respond("", .{ 2181 .status = .see_other, 2182 .extra_headers = &.{.{ .name = "location", .value = base }}, 2183 }); 2184 } 2185 2186 // resolve every conflicted field of the thread the url names 2187 fn handleThreadResolve( 2188 io: std.Io, 2189 request: *std.http.Server.Request, 2190 allocator: std.mem.Allocator, 2191 base: []const u8, 2192 host: Host, 2193 ) !void { 2194 const parts = commentBaseParts(host, base) orelse { 2195 try request.respond("thread not found", .{ 2196 .status = .not_found, 2197 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2198 }); 2199 return; 2200 }; 2201 2202 var author_arena = std.heap.ArenaAllocator.init(allocator); 2203 defer author_arena.deinit(); 2204 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write, parts.thread_kind)) orelse return).author; 2205 2206 const body = try readFormBody(request, allocator); 2207 defer allocator.free(body); 2208 2209 var field_arena = std.heap.ArenaAllocator.init(allocator); 2210 defer field_arena.deinit(); 2211 const aa = field_arena.allocator(); 2212 const title = try parseFormField(aa, body, "title"); 2213 const labels = try parseFormField(aa, body, "labels"); 2214 2215 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 2216 // textarea line breaks to CRLF 2217 var hunks: std.ArrayList([]const u8) = .empty; 2218 var hunk_index: usize = 0; 2219 while (true) : (hunk_index += 1) { 2220 const name = try aa.print("d{d}", .{hunk_index}); 2221 const submitted = (try parseFormField(aa, body, name)) orelse break; 2222 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 2223 } 2224 2225 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 2226 try request.respond("thread not found", .{ 2227 .status = .not_found, 2228 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2229 }); 2230 return; 2231 } 2232 const route = routeFromUrl(host, base) orelse { 2233 try request.respond("thread not found", .{ 2234 .status = .not_found, 2235 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2236 }); 2237 return; 2238 }; 2239 const theirs: []const u8 = switch (route) { 2240 .repo_patches => |*patch| patch.theirs.slice(), 2241 .repo_issues => "", 2242 else => unreachable, 2243 }; 2244 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 2245 2246 (switch (parts.thread_kind) { 2247 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2248 .title = title, 2249 .labels = labels, 2250 .hunks = hunks.items, 2251 } }, author), 2252 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2253 .title = title, 2254 .labels = labels, 2255 .hunks = hunks.items, 2256 .theirs = theirs, 2257 } }, author), 2258 else => unreachable, 2259 }) catch |err| switch (err) { 2260 error.NotFound => { 2261 try request.respond(not_found, .{ 2262 .status = .not_found, 2263 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2264 }); 2265 return; 2266 }, 2267 // invalid fields send the user back to the resolve form 2268 error.InvalidFields => { 2269 const form_location = try allocator.print("{s}/resolve", .{base}); 2270 defer allocator.free(form_location); 2271 try request.respond("", .{ 2272 .status = .see_other, 2273 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2274 }); 2275 return; 2276 }, 2277 else => |e| return e, 2278 }; 2279 2280 try request.respond("", .{ 2281 .status = .see_other, 2282 .extra_headers = &.{.{ .name = "location", .value = base }}, 2283 }); 2284 } 2285 2286 // the posted path drops the action's own segment, so the route it parses is 2287 // the undo page the action applies to 2288 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host) !void { 2289 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 2290 if (route != .repo_undo) return respondRepoNotFound(request); 2291 const target = route.repo_undo; 2292 var arena = std.heap.ArenaAllocator.init(allocator); 2293 defer arena.deinit(); 2294 const repo_base = if (target.name.len == 0) "" else try arena.allocator().print("/{s}", .{target.name.slice()}); 2295 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner, null)) orelse return; 2296 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 2297 defer resolved.deinit(allocator); 2298 ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)) catch |err| switch (err) { 2299 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 2300 else => return err, 2301 }; 2302 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 2303 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 2304 } 2305 2306 fn handleSync( 2307 io: std.Io, 2308 request: *std.http.Server.Request, 2309 allocator: std.mem.Allocator, 2310 base: []const u8, 2311 source: ui.RepoSource, 2312 ) !void { 2313 if (base.len != 0) { 2314 try request.respond("not found", .{ 2315 .status = .not_found, 2316 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2317 }); 2318 return; 2319 } 2320 2321 var owned_failure: ?[]u8 = null; 2322 defer if (owned_failure) |message| allocator.free(message); 2323 const failure: ?[]const u8 = blk: { 2324 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 2325 break :blk owned_failure; 2326 }; 2327 if (failure) |message| { 2328 var encoded: std.Io.Writer.Allocating = .init(allocator); 2329 defer encoded.deinit(); 2330 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 2331 fn isUnreserved(c: u8) bool { 2332 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2333 } 2334 }.isUnreserved); 2335 const cookie = try allocator.print( 2336 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 2337 .{encoded.written()}, 2338 ); 2339 defer allocator.free(cookie); 2340 try request.respond("", .{ 2341 .status = .see_other, 2342 .extra_headers = &.{ 2343 .{ .name = "location", .value = "/events" }, 2344 .{ .name = "set-cookie", .value = cookie }, 2345 }, 2346 }); 2347 return; 2348 } 2349 2350 try request.respond("", .{ 2351 .status = .see_other, 2352 .extra_headers = &.{ 2353 .{ .name = "location", .value = "/events" }, 2354 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 2355 }, 2356 }); 2357 } 2358 2359 fn renderIndexHtml( 2360 io: std.Io, 2361 allocator: std.mem.Allocator, 2362 host: Host, 2363 session_token: ?[]const u8, 2364 session_data: ui.Session.Data, 2365 ) ![]const u8 { 2366 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 2367 2368 var page_arena = std.heap.ArenaAllocator.init(allocator); 2369 defer page_arena.deinit(); 2370 2371 // the server admin repo must outlive the page build, since the session's 2372 // moment reads from it. 2373 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 2374 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 2375 2376 var session = switch (host) { 2377 .server => |server| blk: { 2378 // open the admin repo to read live user/repo data. 2379 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2380 const repo = if (repo_maybe) |*repo| repo else unreachable; 2381 var session = try ui.Session.init(&page_arena, repo, session_data); 2382 // the session dropped a user whose account was removed, so revoke 2383 // the token that named them 2384 if (session_token) |token| { 2385 if (session.data.user_id == null) server.session_store.remove(token); 2386 } 2387 // give the page builders filesystem access to the on-disk repos (a 2388 // sibling "users" dir next to the admin repo) so the Repo page can 2389 // read its files. 2390 session.users_dir = server.users_dir; 2391 break :blk session; 2392 }, 2393 .local => |local| ui.Session{ 2394 .data = session_data, 2395 .arena = &page_arena, 2396 .page_arena = &page_arena, 2397 .local = local, 2398 }, 2399 }; 2400 session.io = io; 2401 session.data.now = std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse return error.TimestampOutOfRange; 2402 2403 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 2404 var root = try ui.initRoot(allocator, &page, &session); 2405 defer root.deinit(allocator); 2406 2407 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 2408 2409 const content = try generateHtml(allocator, &root, &session); 2410 defer allocator.free(content); 2411 2412 // serialize the snapshot so the wasm side can parse it back without making 2413 // a second request. it's embedded raw in a <script type="application/json"> 2414 // block, whose content is raw text terminated only by "</script". in json, 2415 // '<' appears solely inside string values, so escaping every '<' (and '>' 2416 // for good measure) to its \uXXXX form yields equivalent json that can't 2417 // break out of the tag. 2418 var json: std.Io.Writer.Allocating = .init(allocator); 2419 defer json.deinit(); 2420 try std.json.Stringify.value(snapshot, .{}, &json.writer); 2421 2422 var json_escaped: std.ArrayList(u8) = .empty; 2423 defer json_escaped.deinit(allocator); 2424 for (json.written()) |c| switch (c) { 2425 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 2426 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 2427 else => try json_escaped.append(allocator, c), 2428 }; 2429 2430 var out: std.ArrayList(u8) = .empty; 2431 errdefer out.deinit(allocator); 2432 { 2433 var cursor: usize = 0; 2434 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 2435 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 2436 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 2437 }) |sub| { 2438 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 2439 try out.appendSlice(allocator, template[cursor..idx]); 2440 try out.appendSlice(allocator, sub.replacement); 2441 cursor = idx + sub.needle.len; 2442 } 2443 try out.appendSlice(allocator, template[cursor..]); 2444 } 2445 return try out.toOwnedSlice(allocator); 2446 } 2447 2448 fn findEmbed(request_path: []const u8) ?Embed { 2449 // embeds are matched before pages, so a dot keeps them from claiming a username or tab 2450 comptime for (embeds) |embed| { 2451 if (std.mem.indexOfScalar(u8, embed.path, '.') == null) @compileError("embed path needs a '.' so it can't shadow a page: " ++ embed.path); 2452 }; 2453 if (request_path.len < 2 or request_path[0] != '/') return null; 2454 const path = request_path[1..]; 2455 2456 for (embeds) |embed| { 2457 if (std.mem.eql(u8, path, embed.path)) return embed; 2458 } 2459 return null; 2460 } 2461 2462 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 2463 // own absolutely-positioned, natively-scrollable <div> holding its full content, 2464 // rendered recursively so nested scrolls work. 2465 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 2466 const grid = root.getGrid() orelse return error.MissingGrid; 2467 const root_focus = root.getFocus(); 2468 2469 var out: std.ArrayList(u8) = .empty; 2470 errdefer out.deinit(allocator); 2471 2472 switch (root.*) { 2473 .background => |*background| { 2474 if (background.art.getGrid()) |art| { 2475 try out.print(allocator, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch;opacity:{d}%\">", .{ grid.size.width -| art.size.width, ui.widget.AnsiBackground.art_opacity }); 2476 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 2477 try out.appendSlice(allocator, "</div>"); 2478 } 2479 }, 2480 else => {}, 2481 } 2482 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 2483 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 2484 try out.appendSlice(allocator, "</div>"); 2485 try renderForms(allocator, &out, root_focus); 2486 return try out.toOwnedSlice(allocator); 2487 } 2488 2489 // render one panel — a focus subtree and its content grid — as HTML, recursing 2490 // once per web-native Scroll inside it. the root panel is the whole page; each 2491 // Scroll becomes a nested, natively-scrollable div holding its full content. 2492 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 2493 // then the child scroll divs over those holes. 2494 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 2495 // `direct` is this panel's scroll children, each drawn as an overlaid div. 2496 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 2497 // plus their descendants, which the focus tree flattens into this panel's 2498 // children): the cell hit-test below skips them so this panel doesn't claim 2499 // cells that are really rendered inside a child scroll's own panel. 2500 // (scrolls aren't nested in practice, so every scroll child is direct here.) 2501 var direct: std.ArrayList(usize) = .empty; 2502 defer direct.deinit(allocator); 2503 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 2504 defer excluded.deinit(allocator); 2505 { 2506 var it = focus.children.iterator(); 2507 while (it.next()) |e| { 2508 if (e.value_ptr.focus.scroll == null) continue; 2509 try direct.append(allocator, e.key_ptr.*); 2510 try excluded.put(allocator, e.key_ptr.*, {}); 2511 var mit = e.value_ptr.focus.children.iterator(); 2512 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 2513 } 2514 } 2515 2516 // the HTML element a run of cells is wrapped in, chosen from the cell's 2517 // focusable kind 2518 const CellTag = union(enum) { 2519 span, // clickable focusable cell 2520 a: []const u8, // clickable focusable link 2521 plain, // non-focusable, colored 2522 2523 const a_prefix = "a:"; 2524 // an "in-page" anchor: rendered as a real <a href> so it works with js 2525 // disabled, but wasm handles it without navigating. 2526 fn init(str: []const u8) @This() { 2527 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 2528 return .{ .a = str[ui.raw_link_prefix.len..] }; 2529 } 2530 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 2531 return .{ .a = str[ui.in_page_link_prefix.len..] }; 2532 } 2533 if (std.mem.startsWith(u8, str, a_prefix)) { 2534 return .{ .a = str[a_prefix.len..] }; 2535 } 2536 return .span; 2537 } 2538 2539 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 2540 var id_buf: [32]u8 = undefined; 2541 switch (self) { 2542 .span => { 2543 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 2544 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2545 try out.appendSlice(alloc, "\""); 2546 try out.appendSlice(alloc, style_attr); 2547 try out.appendSlice(alloc, ">"); 2548 }, 2549 .a => |href| { 2550 // tabindex=-1 keeps these out of the browser's tab order 2551 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 2552 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2553 try out.appendSlice(alloc, "\" href=\""); 2554 try appendEscapedHtml(alloc, out, href); 2555 try out.appendSlice(alloc, "\""); 2556 try out.appendSlice(alloc, style_attr); 2557 try out.appendSlice(alloc, ">"); 2558 }, 2559 .plain => { 2560 try out.appendSlice(alloc, "<span"); 2561 try out.appendSlice(alloc, style_attr); 2562 try out.appendSlice(alloc, ">"); 2563 }, 2564 } 2565 } 2566 2567 fn closeTag(self: @This()) []const u8 { 2568 return switch (self) { 2569 .span, .plain => "</span>", 2570 .a => "</a>", 2571 }; 2572 } 2573 }; 2574 2575 // the focusable owning each cell, among this panel's own (skipping any 2576 // that belong to a child scroll, whose cells are drawn in their own panel). 2577 // claimed in focus order, so the first focusable over a cell keeps it. 2578 // looking every focusable up for every cell is quadratic in a long list. 2579 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2580 defer allocator.free(owners); 2581 @memset(owners, null); 2582 { 2583 var it = focus.children.iterator(); 2584 while (it.next()) |entry| { 2585 const child = entry.value_ptr.*; 2586 if (child.focus.mode != .all) continue; 2587 if (excluded.contains(entry.key_ptr.*)) continue; 2588 const r = child.rect; 2589 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2590 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2591 const owner = &owners[y * grid.size.width + x]; 2592 if (owner.* == null) owner.* = entry.key_ptr.*; 2593 } 2594 } 2595 } 2596 } 2597 2598 // the cells are the volatile part of a panel. js replaces this one subtree 2599 // wholesale while retaining the panel's native controls and scroll shells. 2600 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2601 2602 // emit this panel's grid as rows of text, coalescing adjacent cells that 2603 // share a focus id and style into one tag (a clickable span, a link, or a 2604 // plain styled span). cells under a child scroll keep only their background. 2605 // a cell's own link is an anchor nested in that tag. 2606 for (0..grid.size.height) |y| { 2607 var cur_id: ?usize = null; 2608 var cur_style: Grid.Style = .{}; 2609 var open_tag: ?CellTag = null; 2610 var open_link: ?[]const u8 = null; 2611 var first = true; 2612 for (0..grid.size.width) |x| { 2613 const cell = (try grid.cell(x, y)).*; 2614 // a cell covered by a child scroll's viewport is drawn by that scroll's 2615 // own div, so blank its glyph and make it non-clickable here — but keep 2616 // its background, so the backdrop still shows through the scroll's 2617 // transparent div instead of a bare hole. 2618 const covered_by_scroll = blk: { 2619 for (direct.items) |id| { 2620 const r = (focus.children.get(id) orelse continue).rect; 2621 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; 2622 } 2623 break :blk false; 2624 }; 2625 // the focusable owning the cell at (x, y); none for a covered cell. 2626 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2627 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2628 2629 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2630 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2631 open_link = null; 2632 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2633 2634 var new_tag: ?CellTag = null; 2635 if (cell_id) |id| { 2636 if (focus.children.get(id)) |child| { 2637 new_tag = switch (child.focus.kind) { 2638 .custom => |custom| CellTag.init(custom), 2639 else => .span, 2640 }; 2641 } 2642 } 2643 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2644 2645 if (new_tag) |t| { 2646 var style_buf: [192]u8 = undefined; 2647 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2648 } 2649 2650 open_tag = new_tag; 2651 cur_id = cell_id; 2652 cur_style = style; 2653 first = false; 2654 } 2655 2656 // an anchor can't nest in another, so a link tag's cells skip theirs 2657 const in_anchor = if (open_tag) |t| t == .a else false; 2658 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2659 if (!sameLink(link, open_link)) { 2660 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2661 if (link) |url| { 2662 // a page path opens in this tab, any other url in a new one 2663 try output.appendSlice(allocator, if (url[0] == '/') 2664 "<a class=\"cell-link\" tabindex=\"-1\" href=\"" 2665 else 2666 "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2667 try appendEscapedHtml(allocator, output, url); 2668 try output.appendSlice(allocator, "\">"); 2669 } 2670 open_link = link; 2671 } 2672 2673 if (covered_by_scroll) { 2674 try appendEscapedHtml(allocator, output, " "); 2675 } else if (cell.continuation) { 2676 // the wide rune to the left was emitted 2ch wide, covering this column 2677 } else if (cell.rune) |rune| { 2678 var encoded: [4]u8 = undefined; 2679 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2680 const rune_text = encoded[0..encoded_len]; 2681 // a double-width rune is pinned inside a 2ch span so the 2682 // fallback glyph's advance width can't shift the rest of the row 2683 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2684 if (wide) { 2685 try output.appendSlice(allocator, "<span class=\"w2\">"); 2686 try appendEscapedHtml(allocator, output, rune_text); 2687 try output.appendSlice(allocator, "</span>"); 2688 } else { 2689 try appendEscapedHtml(allocator, output, rune_text); 2690 } 2691 } else { 2692 try appendEscapedHtml(allocator, output, " "); 2693 } 2694 } 2695 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2696 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2697 try output.append(allocator, '\n'); 2698 } 2699 try output.appendSlice(allocator, "</div>"); 2700 2701 // native controls live in their panel, beside the replaceable cells. their 2702 // stable keys let JS update layout without recreating their DOM nodes, and 2703 // being actual descendants of a scroll gives them native movement/clipping. 2704 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2705 2706 // each child scroll becomes a natively-scrollable div positioned over its 2707 // viewport, holding its full content rendered recursively. 2708 for (direct.items) |id| { 2709 const child = focus.children.get(id) orelse continue; 2710 const info = child.focus.scroll orelse continue; 2711 const r = child.rect; 2712 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2713 // when that axis actually overflows. the other axis is clipped (hidden), 2714 // matching how the terminal Scroll handles its non-scrolling axis. 2715 const overflow = switch (info.direction) { 2716 .vert => "overflow-x:hidden;overflow-y:auto", 2717 .horiz => "overflow-x:auto;overflow-y:hidden", 2718 .both => "overflow:auto", 2719 }; 2720 // the id carries a content version so JS preserves the native scroll 2721 // position across re-renders of the same content but resets it when the 2722 // content is replaced — e.g. selecting a different commit. the widget's 2723 // scroll offset (in cells) rides along so JS can apply it when it has no 2724 // preserved position, letting a wasm-side scrollToRect (the files list 2725 // scrolling to its selected row on page load) reach the browser. 2726 var buf: [256]u8 = undefined; 2727 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 })); 2728 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2729 try output.appendSlice(allocator, "</div>"); 2730 } 2731 } 2732 2733 const form_prefix = "form:"; 2734 const form_id_prefix = "haxy-form-"; 2735 2736 fn formAction(focus: *const Focus) ?[]const u8 { 2737 return switch (focus.kind) { 2738 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2739 else => null, 2740 }; 2741 } 2742 2743 // find the form ancestor of a flattened focus-tree child. html's `form` 2744 // attribute then associates the control with that form without requiring the 2745 // form and control to share a DOM parent. 2746 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2747 var id = focus_id; 2748 while (root_focus.children.get(id)) |child| { 2749 const parent_id = child.parent_id; 2750 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2751 const parent = root_focus.children.get(parent_id) orelse return null; 2752 if (formAction(parent.focus) != null) return parent_id; 2753 id = parent_id; 2754 } 2755 return null; 2756 } 2757 2758 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2759 const form_id = formOwner(root_focus, focus_id) orelse return; 2760 var buf: [64]u8 = undefined; 2761 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2762 } 2763 2764 fn renderPanelControls( 2765 allocator: std.mem.Allocator, 2766 output: *std.ArrayList(u8), 2767 focus: *Focus, 2768 session: *ui.Session, 2769 root_focus: *Focus, 2770 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2771 ) !void { 2772 var iter = focus.children.iterator(); 2773 while (iter.next()) |entry| { 2774 const id = entry.key_ptr.*; 2775 if (excluded.contains(id)) continue; 2776 const child = entry.value_ptr.*; 2777 const r = child.rect; 2778 2779 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2780 2781 switch (child.focus.kind) { 2782 .text_input, .text_input_password, .text_area => { 2783 const ti = session.text_inputs.get(id) orelse continue; 2784 2785 const inner_left = r.x + 1; 2786 const inner_top = r.y + 1; 2787 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2788 const preserve = !ti.options.read_only; 2789 2790 if (child.focus.kind == .text_area) { 2791 const value = try ti.text(allocator); 2792 defer allocator.free(value); 2793 var id_buf: [128]u8 = undefined; 2794 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2795 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2796 try appendFormAttribute(allocator, output, root_focus, id); 2797 if (ti.options.name.len > 0) { 2798 try output.appendSlice(allocator, " name=\""); 2799 try appendEscapedHtml(allocator, output, ti.options.name); 2800 try output.append(allocator, '"'); 2801 } 2802 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2803 var pos_buf: [128]u8 = undefined; 2804 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 })); 2805 try appendEscapedHtml(allocator, output, value); 2806 try output.appendSlice(allocator, "</textarea>"); 2807 continue; 2808 } 2809 2810 var id_buf: [160]u8 = undefined; 2811 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 })); 2812 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2813 try appendFormAttribute(allocator, output, root_focus, id); 2814 if (ti.options.name.len > 0) { 2815 try output.appendSlice(allocator, " name=\""); 2816 try appendEscapedHtml(allocator, output, ti.options.name); 2817 try output.append(allocator, '"'); 2818 } 2819 if (child.focus.kind != .text_input_password) { 2820 const value = try ti.text(allocator); 2821 defer allocator.free(value); 2822 try output.appendSlice(allocator, " value=\""); 2823 try appendEscapedHtml(allocator, output, value); 2824 try output.append(allocator, '"'); 2825 } 2826 var pos_buf: [96]u8 = undefined; 2827 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 })); 2828 }, 2829 .custom => |custom| { 2830 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2831 if (formOwner(root_focus, id) == null) continue; 2832 var id_buf: [128]u8 = undefined; 2833 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2834 try appendFormAttribute(allocator, output, root_focus, id); 2835 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2836 try output.appendSlice(allocator, " formaction=\""); 2837 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2838 try output.append(allocator, '"'); 2839 } 2840 var pos_buf: [128]u8 = undefined; 2841 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 })); 2842 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2843 // an invisible native radio over the option, checked when the option is its row's selection 2844 const field = custom[ui.radio_prefix.len..]; 2845 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2846 const row = root_focus.children.get(child.parent_id) orelse continue; 2847 var id_buf: [128]u8 = undefined; 2848 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2849 try appendFormAttribute(allocator, output, root_focus, id); 2850 try output.appendSlice(allocator, " name=\""); 2851 try appendEscapedHtml(allocator, output, field[0..separator]); 2852 try output.appendSlice(allocator, "\" value=\""); 2853 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2854 try output.append(allocator, '"'); 2855 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2856 var pos_buf: [128]u8 = undefined; 2857 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2858 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2859 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2860 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2861 var id_buf: [128]u8 = undefined; 2862 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 })); 2863 } 2864 }, 2865 else => {}, 2866 } 2867 } 2868 } 2869 2870 // emit hidden form owners beside the rendered panels. their controls point 2871 // back here with the standard HTML `form` attribute. 2872 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2873 // the focus child map preserves insertion order, which matches the order 2874 // widgets were added in code 2875 var iter = root_focus.children.iterator(); 2876 while (iter.next()) |entry| { 2877 const child = entry.value_ptr.*; 2878 const action_url = formAction(child.focus) orelse continue; 2879 2880 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2881 var id_buf: [96]u8 = undefined; 2882 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2883 try appendEscapedHtml(allocator, output, action_url); 2884 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2885 } 2886 } 2887 2888 // the 16 ansi colors as the browser shows them (xterm's defaults) 2889 const ansi_palette = [16]Grid.Color.Rgb{ 2890 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2891 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2892 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2893 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2894 }; 2895 2896 // resolve any color to rgb: palette colors through the ansi table and the 2897 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2898 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2899 return switch (color) { 2900 .rgb => |c| c, 2901 .ansi => |a| ansi_palette[@backingInt(a)], 2902 .indexed => |n| if (n < 16) 2903 ansi_palette[n] 2904 else if (n < 232) blk: { 2905 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2906 const i = n - 16; 2907 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2908 } else blk: { 2909 const v: u8 = 8 + (n - 232) * 10; 2910 break :blk .{ .r = v, .g = v, .b = v }; 2911 }, 2912 }; 2913 } 2914 2915 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2916 // cell's style into `buf`, omitting whichever color is unset. an inverted 2917 // cell swaps the two, falling back to the page's --fg/--bg variables for 2918 // whichever side is unset. text attributes follow the colors. returns an 2919 // empty slice when nothing is set. 2920 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2921 if (style.eql(.{})) return buf[0..0]; 2922 const prefix = " style=\""; 2923 @memcpy(buf[0..prefix.len], prefix); 2924 var i: usize = prefix.len; 2925 const inverted = style.inverted; 2926 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2927 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2928 const decoration: []const u8 = if (style.underline and style.strikethrough) 2929 "text-decoration:underline line-through;" 2930 else if (style.underline) 2931 "text-decoration:underline;" 2932 else if (style.strikethrough) 2933 "text-decoration:line-through;" 2934 else 2935 ""; 2936 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2937 if (style.bold) "font-weight:bold;" else "", 2938 if (style.italic) "font-style:italic;" else "", 2939 decoration, 2940 if (style.dim) "opacity:.6;" else "", 2941 }) catch return buf[0..0]; 2942 i += attributes.len; 2943 if (i >= buf.len) return buf[0..0]; 2944 buf[i] = '"'; 2945 return buf[0 .. i + 1]; 2946 } 2947 2948 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2949 // the color is unset (nothing when both are). returns the new end, or null 2950 // when it doesn't fit. 2951 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2952 const s = if (color) |c| blk: { 2953 const v = colorRgb(c); 2954 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2955 } else if (fallback) |f| 2956 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2957 else 2958 return i; 2959 return i + s.len; 2960 } 2961 2962 // a cell's link as an href, when it's a page path or a web or mail url 2963 fn webLink(link: ?[]const u8) ?[]const u8 { 2964 const url = link orelse return null; 2965 // a page path, not a protocol-relative url 2966 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2967 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2968 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2969 } 2970 return null; 2971 } 2972 2973 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2974 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2975 return b == null; 2976 } 2977 2978 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2979 for (input) |ch| { 2980 switch (ch) { 2981 '&' => try out.appendSlice(allocator, "&amp;"), 2982 '<' => try out.appendSlice(allocator, "&lt;"), 2983 '>' => try out.appendSlice(allocator, "&gt;"), 2984 '"' => try out.appendSlice(allocator, "&quot;"), 2985 '\'' => try out.appendSlice(allocator, "&#39;"), 2986 else => try out.append(allocator, ch), 2987 } 2988 } 2989 } 2990 2991 // --- helpers -------------------------------------------------------------- 2992 2993 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2994 var iter = request.iterateHeaders(); 2995 while (iter.next()) |header| { 2996 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2997 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2998 while (pairs.next()) |pair| { 2999 const trimmed = std.mem.trim(u8, pair, " \t"); 3000 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 3001 if (std.mem.eql(u8, trimmed[0..eq], name)) { 3002 return trimmed[eq + 1 ..]; 3003 } 3004 } 3005 } 3006 return null; 3007 } 3008 3009 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 3010 var iter = std.mem.splitScalar(u8, body, '&'); 3011 while (iter.next()) |pair| { 3012 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 3013 if (std.mem.eql(u8, pair[0..eq], key)) { 3014 return try decodeFormValue(allocator, pair[eq + 1 ..]); 3015 } 3016 } 3017 return null; 3018 } 3019 3020 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 3021 var buffer: [256]u8 = undefined; 3022 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 3023 } 3024 3025 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 3026 var out: std.ArrayList(u8) = .empty; 3027 errdefer out.deinit(allocator); 3028 var i: usize = 0; 3029 while (i < encoded.len) : (i += 1) { 3030 switch (encoded[i]) { 3031 '+' => try out.append(allocator, ' '), 3032 '%' => { 3033 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 3034 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 3035 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 3036 try out.append(allocator, hi * 16 + lo); 3037 i += 2; 3038 }, 3039 else => try out.append(allocator, encoded[i]), 3040 } 3041 } 3042 return try out.toOwnedSlice(allocator); 3043 } 3044 3045 // disk-backed web session store. each login mints a random, opaque token 3046 // (not the user's id) that is stored as a file named by the token hex, whose 3047 // contents are the raw user_id bytes. authenticating a request is a lookup of 3048 // the cookie's token; logout deletes the file, revoking the session. there is 3049 // deliberately no expiry — a session lives until logout. form failures use 3050 // files in the flash subdirectory that the redirected GET consumes. the 3051 // directory is cleared whenever the server starts. 3052 pub const SessionStore = struct { 3053 io: std.Io, 3054 dir: std.Io.Dir, 3055 flash_dir: std.Io.Dir, 3056 auto_login: ?[token_hex_len]u8, 3057 3058 pub const token_hex_len = evt.event_id_size * 2; 3059 3060 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3061 try data_dir.createDirPath(io, "sessions"); 3062 const dir = try data_dir.openDir(io, "sessions", .{}); 3063 errdefer dir.close(io); 3064 try dir.deleteTree(io, "flash"); 3065 try dir.createDirPath(io, "flash"); 3066 const flash_dir = try dir.openDir(io, "flash", .{}); 3067 errdefer flash_dir.close(io); 3068 const auto_login = blk: { 3069 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3070 defer file.close(io); 3071 var token: [token_hex_len]u8 = undefined; 3072 var storage: [token_hex_len]u8 = undefined; 3073 var reader = file.reader(io, &storage); 3074 reader.interface.readSliceAll(&token) catch break :blk null; 3075 break :blk token; 3076 }; 3077 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3078 } 3079 3080 pub fn deinit(self: SessionStore) void { 3081 self.flash_dir.close(self.io); 3082 self.dir.close(self.io); 3083 } 3084 3085 // mint a new session for user_id, returning the token hex to set as the 3086 // cookie value. 3087 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3088 var token: [evt.event_id_size]u8 = undefined; 3089 self.io.random(&token); 3090 const token_hex = std.fmt.bytesToHex(token, .lower); 3091 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3092 defer file.close(self.io); 3093 try file.writeStreamingAll(self.io, user_id); 3094 return token_hex; 3095 } 3096 3097 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3098 var token: [evt.event_id_size]u8 = undefined; 3099 self.io.random(&token); 3100 const token_hex = std.fmt.bytesToHex(token, .lower); 3101 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3102 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3103 defer file.close(self.io); 3104 3105 var json: std.Io.Writer.Allocating = .init(allocator); 3106 defer json.deinit(); 3107 try std.json.Stringify.value(value, .{}, &json.writer); 3108 try file.writeStreamingAll(self.io, json.written()); 3109 return token_hex; 3110 } 3111 3112 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3113 if (!isToken(token_hex)) return null; 3114 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3115 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3116 defer file.close(self.io); 3117 3118 var storage: [4096]u8 = undefined; 3119 var reader = file.reader(self.io, &storage); 3120 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3121 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3122 } 3123 3124 // resolve a cookie's token to its user_id. returns false (logged out) for a 3125 // missing, malformed, or unknown token. 3126 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3127 if (!isToken(token_hex)) return false; 3128 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3129 defer file.close(self.io); 3130 var storage: [evt.event_id_size]u8 = undefined; 3131 var file_reader = file.reader(self.io, &storage); 3132 file_reader.interface.readSliceAll(out) catch return false; 3133 return true; 3134 } 3135 3136 // revoke a session. a no-op for a missing or malformed token. 3137 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3138 if (!isToken(token_hex)) return; 3139 self.dir.deleteFile(self.io, token_hex) catch {}; 3140 } 3141 3142 // leave `token_hex`'s session for visitors arriving without one. only the 3143 // `try` fixture writes one. the name can't collide with a session token. 3144 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3145 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3146 defer file.close(self.io); 3147 try file.writeStreamingAll(self.io, token_hex); 3148 } 3149 3150 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3151 out.* = self.auto_login orelse return false; 3152 return true; 3153 } 3154 3155 const auto_login_name = "auto-login"; 3156 3157 // a token is exactly token_hex_len hex chars. validating before using the 3158 // value as a path keeps attacker-supplied cookies from escaping the 3159 // sessions dir (e.g. via "/" or ".." bytes). 3160 fn isToken(token_hex: []const u8) bool { 3161 if (token_hex.len != token_hex_len) return false; 3162 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3163 return true; 3164 } 3165 }; 3166