╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const evt = @import("./event.zig"); 6 const ui = @import("./ui.zig"); 7 const xitui = xit.xitui; 8 const wgt = xitui.widget; 9 const Focus = xitui.focus.Focus; 10 const Grid = xitui.grid.Grid; 11 12 const cookie_name = "haxy_user"; 13 // flash cookie for surfacing the outcome of the most recent /login POST. 14 // set on the failure redirect, read and immediately expired on the next 15 // GET / so refreshing the page doesn't keep showing the error. 16 const login_failure_cookie = "haxy_login_failure"; 17 18 const Embed = struct { 19 path: []const u8, 20 content_type: []const u8, 21 body: []const u8, 22 }; 23 24 const embeds = [_]Embed{ 25 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 26 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 27 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 28 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("embed/haxy.wasm") }, 29 }; 30 31 pub fn run( 32 io: std.Io, 33 allocator: std.mem.Allocator, 34 net_server: *std.Io.net.Server, 35 tasks: *std.Io.Group, 36 admin_repo_path: []const u8, 37 err: *std.Io.Writer, 38 ) void { 39 const Listener = struct { 40 io: std.Io, 41 allocator: std.mem.Allocator, 42 net_server: *std.Io.net.Server, 43 tasks: *std.Io.Group, 44 admin_repo_path: []const u8, 45 err: *std.Io.Writer, 46 47 fn run(ctx: @This()) void { 48 while (true) { 49 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 50 if (accept_err == error.Canceled) return; 51 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 52 continue; 53 }; 54 55 const Connection = struct { 56 io: std.Io, 57 allocator: std.mem.Allocator, 58 stream: std.Io.net.Stream, 59 admin_repo_path: []const u8, 60 err: *std.Io.Writer, 61 62 fn run(conn: @This()) void { 63 defer conn.stream.close(conn.io); 64 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.err) catch |request_err| { 65 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 66 }; 67 } 68 }; 69 70 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 71 .io = ctx.io, 72 .allocator = ctx.allocator, 73 .stream = stream, 74 .admin_repo_path = ctx.admin_repo_path, 75 .err = ctx.err, 76 }}); 77 } 78 } 79 }; 80 81 tasks.async(io, Listener.run, .{Listener{ 82 .io = io, 83 .allocator = allocator, 84 .net_server = net_server, 85 .tasks = tasks, 86 .admin_repo_path = admin_repo_path, 87 .err = err, 88 }}); 89 } 90 91 fn handleConnection( 92 io: std.Io, 93 allocator: std.mem.Allocator, 94 stream: std.Io.net.Stream, 95 admin_repo_path: []const u8, 96 err: *std.Io.Writer, 97 ) !void { 98 var send_buffer = [_]u8{0} ** 4096; 99 var recv_buffer = [_]u8{0} ** 4096; 100 var conn_br = stream.reader(io, &recv_buffer); 101 var conn_bw = stream.writer(io, &send_buffer); 102 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 103 104 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 105 // works — important for browser-native form POST: after the 303 the 106 // browser issues GET / on the same socket, and forcibly closing here 107 // would race the follow-up request into a "site can't be reached". 108 while (http_server.reader.state == .ready) { 109 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 110 error.HttpConnectionClosing => break, 111 error.ReadFailed => break, 112 else => |e| return e, 113 }; 114 115 handleRequest(io, &request, allocator, admin_repo_path) catch |request_err| { 116 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 117 try err.flush(); 118 // best-effort 500. if handleRequest already started writing a 119 // response before throwing, this respond may fail too, but at 120 // that point the connection is unrecoverable anyway. 121 request.respond(@errorName(request_err), .{ 122 .status = .internal_server_error, 123 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 124 }) catch {}; 125 }; 126 } 127 } 128 129 fn handleRequest( 130 io: std.Io, 131 request: *std.http.Server.Request, 132 allocator: std.mem.Allocator, 133 admin_repo_path: []const u8, 134 ) !void { 135 const method = request.head.method; 136 const uri = try std.Uri.parseAfterScheme("", request.head.target); 137 const path = uri.path.percent_encoded; 138 139 if (method == .POST and std.mem.eql(u8, path, "/login")) { 140 return handleLogin(io, request, allocator, admin_repo_path); 141 } 142 if (method == .POST and std.mem.eql(u8, path, "/logout")) { 143 return handleLogout(request); 144 } 145 146 const get_or_head = method == .GET or method == .HEAD; 147 if (!get_or_head) { 148 try request.respond("method not allowed", .{ 149 .status = .method_not_allowed, 150 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 151 }); 152 return; 153 } 154 155 if (std.mem.eql(u8, path, "/favicon.ico")) { 156 try request.respond("", .{ 157 .status = .no_content, 158 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 159 }); 160 return; 161 } 162 163 if (ui.RoutablePage.fromUrl(path)) |current_page| { 164 // decode the haxy_user cookie into raw bytes on the stack; the 165 // slice lives for the rest of handleRequest, which is plenty for 166 // renderIndexHtml to consume. 167 var user_id_buf: [evt.event_id_size]u8 = undefined; 168 const user_id: ?[]const u8 = blk: { 169 const hex = getCookieValue(request, cookie_name) orelse break :blk null; 170 if (hex.len != evt.event_id_size * 2) break :blk null; 171 _ = std.fmt.hexToBytes(&user_id_buf, hex) catch break :blk null; 172 break :blk user_id_buf[0..evt.event_id_size]; 173 }; 174 const login_failure: ?ui.Home.Auth.Login.Failure = 175 if (getCookieValue(request, login_failure_cookie)) |raw| 176 if (std.mem.eql(u8, raw, "unknown_user")) 177 .unknown_user 178 else if (std.mem.eql(u8, raw, "wrong_password")) 179 .wrong_password 180 else 181 null 182 else 183 null; 184 const html = try renderIndexHtml(io, allocator, admin_repo_path, .{ 185 .user_id = user_id, 186 .login_failure = login_failure, 187 .current_page = current_page, 188 }); 189 defer allocator.free(html); 190 // expire the flash cookie on the way out so a refresh doesn't keep 191 // showing the failure label. 192 var headers: [2]std.http.Header = undefined; 193 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 194 var headers_slice: []const std.http.Header = headers[0..1]; 195 if (login_failure != null) { 196 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 197 headers_slice = headers[0..2]; 198 } 199 try request.respond(html, .{ .extra_headers = headers_slice }); 200 return; 201 } 202 203 const embed = findEmbed(path) orelse { 204 try request.respond("not found", .{ 205 .status = .not_found, 206 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 207 }); 208 return; 209 }; 210 211 try request.respond(embed.body, .{ 212 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 213 }); 214 } 215 216 fn handleLogin( 217 io: std.Io, 218 request: *std.http.Server.Request, 219 allocator: std.mem.Allocator, 220 admin_repo_path: []const u8, 221 ) !void { 222 var body_buf: [256]u8 = undefined; 223 const reader = request.readerExpectNone(&body_buf); 224 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 225 defer allocator.free(body); 226 227 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 228 defer allocator.free(username); 229 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 230 defer allocator.free(password); 231 232 const repo_opts: rp.RepoOpts(.xit) = .{}; 233 const Repo = rp.Repo(.xit, repo_opts); 234 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 235 defer repo.deinit(io, allocator); 236 237 var arena = std.heap.ArenaAllocator.init(allocator); 238 defer arena.deinit(); 239 240 const haxy_moment = try openHaxyMoment(repo_opts, &repo); 241 const result = try evt.User.verifyCredentials(Repo.DB, repo_opts.hash, haxy_moment, &arena, username, password); 242 243 switch (result) { 244 .success => |user_id| { 245 const hex = std.fmt.bytesToHex(user_id, .lower); 246 var cookie_buf: [256]u8 = undefined; 247 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{hex}); 248 try request.respond("", .{ 249 .status = .see_other, 250 .extra_headers = &.{ 251 .{ .name = "location", .value = ui.RoutablePage.url(.default) }, 252 .{ .name = "set-cookie", .value = cookie }, 253 }, 254 }); 255 }, 256 .unknown_user => { 257 try request.respond("", .{ 258 .status = .see_other, 259 .extra_headers = &.{ 260 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 261 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 262 }, 263 }); 264 }, 265 .wrong_password => { 266 try request.respond("", .{ 267 .status = .see_other, 268 .extra_headers = &.{ 269 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 270 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 271 }, 272 }); 273 }, 274 } 275 } 276 277 fn handleLogout(request: *std.http.Server.Request) !void { 278 // request.respond's discardBody reads any unused body for us and lands 279 // the connection back in the .ready state for the next request on the 280 // same connection (keep_alive defaults to true). 281 try request.respond("", .{ 282 .status = .see_other, 283 .extra_headers = &.{ 284 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 285 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 286 }, 287 }); 288 } 289 290 fn renderIndexHtml( 291 io: std.Io, 292 allocator: std.mem.Allocator, 293 admin_repo_path: []const u8, 294 session_data: ui.Session.Data, 295 ) ![]const u8 { 296 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 297 298 // open the admin repo to read live user/repo data. 299 const repo_opts: rp.RepoOpts(.xit) = .{}; 300 const Repo = rp.Repo(.xit, repo_opts); 301 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 302 defer repo.deinit(io, allocator); 303 var page_arena = std.heap.ArenaAllocator.init(allocator); 304 defer page_arena.deinit(); 305 306 var session = try ui.Session.init(repo_opts, &page_arena, &repo, session_data); 307 308 const snapshot: ui.Snapshot = .{ 309 .page = .{ .home = try .init(repo_opts, session.arena, session.haxy_moment orelse unreachable) }, 310 .session = session.data, 311 }; 312 var root = try ui.initRoot(allocator, &snapshot.page, &session); 313 defer root.deinit(allocator); 314 315 const content = try generateHtml(allocator, &root); 316 defer allocator.free(content); 317 const overlay = try generateOverlay(allocator, &root); 318 defer allocator.free(overlay); 319 320 // serialize the snapshot so the wasm side can parse it back without 321 // making a second request. base64-encoded so the json can be embedded 322 // safely inside the host html. 323 var json: std.Io.Writer.Allocating = .init(allocator); 324 defer json.deinit(); 325 try std.json.Stringify.value(snapshot, .{}, &json.writer); 326 327 const b64 = std.base64.standard.Encoder; 328 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 329 defer allocator.free(json_b64); 330 _ = b64.encode(json_b64, json.written()); 331 332 var out: std.ArrayList(u8) = .empty; 333 errdefer out.deinit(allocator); 334 { 335 var cursor: usize = 0; 336 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 337 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 338 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 339 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 340 }) |sub| { 341 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 342 try out.appendSlice(allocator, template[cursor..idx]); 343 try out.appendSlice(allocator, sub.replacement); 344 cursor = idx + sub.needle.len; 345 } 346 try out.appendSlice(allocator, template[cursor..]); 347 } 348 return try out.toOwnedSlice(allocator); 349 } 350 351 fn findEmbed(request_path: []const u8) ?Embed { 352 const path = if (std.mem.eql(u8, request_path, "/")) 353 "index.html" 354 else if (request_path.len > 1 and request_path[0] == '/') 355 request_path[1..] 356 else 357 return null; 358 359 for (embeds) |embed| { 360 if (std.mem.eql(u8, path, embed.path)) return embed; 361 } 362 return null; 363 } 364 365 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 366 err.print(fmt, args) catch return; 367 err.flush() catch {}; 368 } 369 370 // emits the TUI grid cells as static HTML 371 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 372 const grid = root.getGrid() orelse return error.MissingGrid; 373 const root_focus = root.getFocus(); 374 375 const Tag = union(enum) { 376 span, // clickable focusable cell 377 a: []const u8, // clickable focusable link 378 plain, // non-focusable, colored 379 380 const a_prefix = "a:"; 381 382 fn init(str: []const u8) @This() { 383 if (std.mem.startsWith(u8, str, a_prefix)) { 384 return .{ .a = str[a_prefix.len..] }; 385 } 386 return .span; 387 } 388 389 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 390 var id_buf: [32]u8 = undefined; 391 switch (self) { 392 .span => { 393 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 394 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 395 try out.appendSlice(alloc, "\""); 396 try out.appendSlice(alloc, style_attr); 397 try out.appendSlice(alloc, ">"); 398 }, 399 .a => |href| { 400 try out.appendSlice(alloc, "<a class=\"clickable\" data-focus-id=\""); 401 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 402 try out.appendSlice(alloc, "\" href=\""); 403 try appendEscapedHtml(alloc, out, href); 404 try out.appendSlice(alloc, "\""); 405 try out.appendSlice(alloc, style_attr); 406 try out.appendSlice(alloc, ">"); 407 }, 408 .plain => { 409 try out.appendSlice(alloc, "<span"); 410 try out.appendSlice(alloc, style_attr); 411 try out.appendSlice(alloc, ">"); 412 }, 413 } 414 } 415 416 fn closeTag(self: @This()) []const u8 { 417 return switch (self) { 418 .span, .plain => "</span>", 419 .a => "</a>", 420 }; 421 } 422 }; 423 424 var out: std.ArrayList(u8) = .empty; 425 errdefer out.deinit(allocator); 426 427 for (0..grid.size.height) |y| { 428 var cur_id: ?usize = null; 429 var cur_fg: ?Grid.Color = null; 430 var cur_bg: ?Grid.Color = null; 431 var open_tag: ?Tag = null; 432 var first = true; 433 for (0..grid.size.width) |x| { 434 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 435 const cell_id = cellFocusId(root_focus, x, y); 436 const fg = cell.style.fg; 437 const bg = cell.style.bg; 438 439 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 440 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 441 442 var new_tag: ?Tag = null; 443 if (cell_id) |id| { 444 if (root_focus.children.get(id)) |child| { 445 new_tag = switch (child.focus.kind) { 446 .custom => |custom| Tag.init(custom), 447 else => .span, 448 }; 449 } 450 } 451 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 452 453 if (new_tag) |t| { 454 var style_buf: [64]u8 = undefined; 455 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 456 } 457 458 open_tag = new_tag; 459 cur_id = cell_id; 460 cur_fg = fg; 461 cur_bg = bg; 462 first = false; 463 } 464 465 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 466 } 467 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 468 try out.append(allocator, '\n'); 469 } 470 471 return try out.toOwnedSlice(allocator); 472 } 473 474 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 475 // widget tree, each wrapping the text inputs and submit button inside it, 476 // positioned absolutely over the matching grid cells. 477 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 478 const root_focus = root.getFocus(); 479 480 var out: std.ArrayList(u8) = .empty; 481 errdefer out.deinit(allocator); 482 483 const form_prefix = "form:"; 484 485 // Focus.children is an AutoArrayHashMap that preserves insertion order, 486 // which matches the order widgets were added in code 487 var iter = root_focus.children.iterator(); 488 while (iter.next()) |entry| { 489 const child = entry.value_ptr.*; 490 const action_url = switch (child.focus.kind) { 491 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 492 custom[form_prefix.len..] 493 else 494 continue, 495 else => continue, 496 }; 497 498 try out.appendSlice(allocator, "<form action=\""); 499 try appendEscapedHtml(allocator, &out, action_url); 500 try out.appendSlice(allocator, "\" method=\"post\">"); 501 502 // form.focus.children was populated by addChild, which flattens the 503 // whole subtree into one map — so descendants (inputs + the submit 504 // button) all appear here. positions on form.focus are relative to 505 // the form, so we look up absolute rects via root_focus for layout. 506 var inner_iter = child.focus.children.iterator(); 507 while (inner_iter.next()) |inner_entry| { 508 const inner_id = inner_entry.key_ptr.*; 509 const root_child = root_focus.children.get(inner_id) orelse continue; 510 const r = root_child.rect; 511 switch (root_child.focus.kind) { 512 .text_input, .text_input_password => { 513 const ti: *wgt.TextInput(ui.Widget) = @fieldParentPtr("focus", root_child.focus); 514 const inner_left = r.x + 1; 515 const inner_top = r.y + 1; 516 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 517 518 try out.appendSlice(allocator, "<input type=\""); 519 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 520 try out.appendSlice(allocator, "\" data-focus-id=\""); 521 var id_buf: [32]u8 = undefined; 522 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 523 if (ti.options.name.len > 0) { 524 try out.appendSlice(allocator, "\" name=\""); 525 try appendEscapedHtml(allocator, &out, ti.options.name); 526 } 527 // intentionally no `value` attribute: the browser tracks user input 528 // natively, and including the wasm-side value here would make the 529 // overlay HTML differ on every keystroke — that would trip the diff 530 // in _setOverlay and rebuild the <input>, eating the user's caret. 531 try out.appendSlice(allocator, "\" style=\"left:"); 532 var pos_buf: [64]u8 = undefined; 533 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 534 try out.appendSlice(allocator, "\">"); 535 }, 536 .custom => |custom| { 537 if (std.mem.eql(u8, "submit", custom)) { 538 // inside the dashed border the TUI cells draw around the button. 539 const inner_left = r.x + 1; 540 const inner_top = r.y + 1; 541 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 542 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 543 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 544 var id_buf: [32]u8 = undefined; 545 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 546 try out.appendSlice(allocator, "\" style=\"left:"); 547 var pos_buf: [128]u8 = undefined; 548 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 549 try out.appendSlice(allocator, "\"></button>"); 550 } 551 }, 552 else => {}, 553 } 554 } 555 556 try out.appendSlice(allocator, "</form>"); 557 } 558 559 return try out.toOwnedSlice(allocator); 560 } 561 562 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 563 if (a) |av| return if (b) |bv| av.eql(bv) else false; 564 return b == null; 565 } 566 567 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 568 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 569 // empty slice when neither is set. 570 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 571 if (fg == null and bg == null) return buf[0..0]; 572 const prefix = " style=\""; 573 @memcpy(buf[0..prefix.len], prefix); 574 var i: usize = prefix.len; 575 if (fg) |c| { 576 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]; 577 i += s.len; 578 } 579 if (bg) |c| { 580 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]; 581 i += s.len; 582 } 583 buf[i] = '"'; 584 i += 1; 585 return buf[0..i]; 586 } 587 588 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 589 var iter = focus.children.iterator(); 590 while (iter.next()) |entry| { 591 const child = entry.value_ptr.*; 592 if (!child.focus.focusable) continue; 593 const r = child.rect; 594 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 595 return entry.key_ptr.*; 596 } 597 } 598 return null; 599 } 600 601 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 602 for (input) |ch| { 603 switch (ch) { 604 '&' => try out.appendSlice(allocator, "&amp;"), 605 '<' => try out.appendSlice(allocator, "&lt;"), 606 '>' => try out.appendSlice(allocator, "&gt;"), 607 '"' => try out.appendSlice(allocator, "&quot;"), 608 '\'' => try out.appendSlice(allocator, "&#39;"), 609 else => try out.append(allocator, ch), 610 } 611 } 612 } 613 614 // --- helpers -------------------------------------------------------------- 615 616 fn openHaxyMoment( 617 comptime repo_opts: rp.RepoOpts(.xit), 618 repo: *rp.Repo(.xit, repo_opts), 619 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 620 const DB = rp.Repo(.xit, repo_opts).DB; 621 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 622 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 623 const moment = try DB.HashMap(.read_only).init(moment_cursor); 624 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 625 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 626 _ = try last_object_id_cursor.readBytes(&last_object_id); 627 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 628 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 629 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 630 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 631 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 632 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 633 } 634 635 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 636 var iter = request.iterateHeaders(); 637 while (iter.next()) |header| { 638 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 639 var pairs = std.mem.splitScalar(u8, header.value, ';'); 640 while (pairs.next()) |pair| { 641 const trimmed = std.mem.trim(u8, pair, " \t"); 642 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 643 if (std.mem.eql(u8, trimmed[0..eq], name)) { 644 return trimmed[eq + 1 ..]; 645 } 646 } 647 } 648 return null; 649 } 650 651 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 652 var iter = std.mem.splitScalar(u8, body, '&'); 653 while (iter.next()) |pair| { 654 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 655 if (std.mem.eql(u8, pair[0..eq], key)) { 656 return try decodeFormValue(allocator, pair[eq + 1 ..]); 657 } 658 } 659 return null; 660 } 661 662 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 663 var out: std.ArrayList(u8) = .empty; 664 errdefer out.deinit(allocator); 665 var i: usize = 0; 666 while (i < encoded.len) : (i += 1) { 667 switch (encoded[i]) { 668 '+' => try out.append(allocator, ' '), 669 '%' => { 670 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 671 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 672 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 673 try out.append(allocator, hi * 16 + lo); 674 i += 2; 675 }, 676 else => try out.append(allocator, encoded[i]), 677 } 678 } 679 return try out.toOwnedSlice(allocator); 680 } 681