╭ 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 // close the connection instead of keeping it alive: we don't read the 279 // request body, and respond()'s keep-alive path would otherwise try to 280 // discard it — which asserts on a bodyless POST that carries no 281 // content-length, and would block on one with no framing at all. a logout 282 // is just a redirect, so the browser reconnects for the follow-up GET. 283 try request.respond("", .{ 284 .status = .see_other, 285 .keep_alive = false, 286 .extra_headers = &.{ 287 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 288 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 289 }, 290 }); 291 } 292 293 fn renderIndexHtml( 294 io: std.Io, 295 allocator: std.mem.Allocator, 296 admin_repo_path: []const u8, 297 session_data: ui.Session.Data, 298 ) ![]const u8 { 299 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 300 301 // open the admin repo to read live user/repo data. 302 const repo_opts: rp.RepoOpts(.xit) = .{}; 303 const Repo = rp.Repo(.xit, repo_opts); 304 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 305 defer repo.deinit(io, allocator); 306 var page_arena = std.heap.ArenaAllocator.init(allocator); 307 defer page_arena.deinit(); 308 309 var session = try ui.Session.init(repo_opts, &page_arena, &repo, session_data); 310 311 const snapshot: ui.Snapshot = .{ 312 .page = .{ .home = try .init(repo_opts, session.arena, session.haxy_moment orelse unreachable) }, 313 .session = session.data, 314 }; 315 var root = try ui.initRoot(allocator, &snapshot.page, &session); 316 defer root.deinit(allocator); 317 318 const content = try generateHtml(allocator, &root); 319 defer allocator.free(content); 320 const overlay = try generateOverlay(allocator, &root); 321 defer allocator.free(overlay); 322 323 // serialize the snapshot so the wasm side can parse it back without 324 // making a second request. base64-encoded so the json can be embedded 325 // safely inside the host html. 326 var json: std.Io.Writer.Allocating = .init(allocator); 327 defer json.deinit(); 328 try std.json.Stringify.value(snapshot, .{}, &json.writer); 329 330 const b64 = std.base64.standard.Encoder; 331 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 332 defer allocator.free(json_b64); 333 _ = b64.encode(json_b64, json.written()); 334 335 var out: std.ArrayList(u8) = .empty; 336 errdefer out.deinit(allocator); 337 { 338 var cursor: usize = 0; 339 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 340 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 341 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 342 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 343 }) |sub| { 344 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 345 try out.appendSlice(allocator, template[cursor..idx]); 346 try out.appendSlice(allocator, sub.replacement); 347 cursor = idx + sub.needle.len; 348 } 349 try out.appendSlice(allocator, template[cursor..]); 350 } 351 return try out.toOwnedSlice(allocator); 352 } 353 354 fn findEmbed(request_path: []const u8) ?Embed { 355 const path = if (std.mem.eql(u8, request_path, "/")) 356 "index.html" 357 else if (request_path.len > 1 and request_path[0] == '/') 358 request_path[1..] 359 else 360 return null; 361 362 for (embeds) |embed| { 363 if (std.mem.eql(u8, path, embed.path)) return embed; 364 } 365 return null; 366 } 367 368 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 369 err.print(fmt, args) catch return; 370 err.flush() catch {}; 371 } 372 373 // emits the TUI grid cells as static HTML 374 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 375 const grid = root.getGrid() orelse return error.MissingGrid; 376 const root_focus = root.getFocus(); 377 378 const Tag = union(enum) { 379 span, // clickable focusable cell 380 a: []const u8, // clickable focusable link 381 plain, // non-focusable, colored 382 383 const a_prefix = "a:"; 384 385 fn init(str: []const u8) @This() { 386 if (std.mem.startsWith(u8, str, a_prefix)) { 387 return .{ .a = str[a_prefix.len..] }; 388 } 389 return .span; 390 } 391 392 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 393 var id_buf: [32]u8 = undefined; 394 switch (self) { 395 .span => { 396 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 397 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 398 try out.appendSlice(alloc, "\""); 399 try out.appendSlice(alloc, style_attr); 400 try out.appendSlice(alloc, ">"); 401 }, 402 .a => |href| { 403 try out.appendSlice(alloc, "<a class=\"clickable\" data-focus-id=\""); 404 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 405 try out.appendSlice(alloc, "\" href=\""); 406 try appendEscapedHtml(alloc, out, href); 407 try out.appendSlice(alloc, "\""); 408 try out.appendSlice(alloc, style_attr); 409 try out.appendSlice(alloc, ">"); 410 }, 411 .plain => { 412 try out.appendSlice(alloc, "<span"); 413 try out.appendSlice(alloc, style_attr); 414 try out.appendSlice(alloc, ">"); 415 }, 416 } 417 } 418 419 fn closeTag(self: @This()) []const u8 { 420 return switch (self) { 421 .span, .plain => "</span>", 422 .a => "</a>", 423 }; 424 } 425 }; 426 427 var out: std.ArrayList(u8) = .empty; 428 errdefer out.deinit(allocator); 429 430 for (0..grid.size.height) |y| { 431 var cur_id: ?usize = null; 432 var cur_fg: ?Grid.Color = null; 433 var cur_bg: ?Grid.Color = null; 434 var open_tag: ?Tag = null; 435 var first = true; 436 for (0..grid.size.width) |x| { 437 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 438 const cell_id = cellFocusId(root_focus, x, y); 439 const fg = cell.style.fg; 440 const bg = cell.style.bg; 441 442 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 443 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 444 445 var new_tag: ?Tag = null; 446 if (cell_id) |id| { 447 if (root_focus.children.get(id)) |child| { 448 new_tag = switch (child.focus.kind) { 449 .custom => |custom| Tag.init(custom), 450 else => .span, 451 }; 452 } 453 } 454 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 455 456 if (new_tag) |t| { 457 var style_buf: [64]u8 = undefined; 458 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 459 } 460 461 open_tag = new_tag; 462 cur_id = cell_id; 463 cur_fg = fg; 464 cur_bg = bg; 465 first = false; 466 } 467 468 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 469 } 470 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 471 try out.append(allocator, '\n'); 472 } 473 474 return try out.toOwnedSlice(allocator); 475 } 476 477 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 478 // widget tree, each wrapping the text inputs and submit button inside it, 479 // positioned absolutely over the matching grid cells. 480 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 481 const root_focus = root.getFocus(); 482 483 var out: std.ArrayList(u8) = .empty; 484 errdefer out.deinit(allocator); 485 486 const form_prefix = "form:"; 487 488 // Focus.children is an AutoArrayHashMap that preserves insertion order, 489 // which matches the order widgets were added in code 490 var iter = root_focus.children.iterator(); 491 while (iter.next()) |entry| { 492 const child = entry.value_ptr.*; 493 const action_url = switch (child.focus.kind) { 494 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 495 custom[form_prefix.len..] 496 else 497 continue, 498 else => continue, 499 }; 500 501 try out.appendSlice(allocator, "<form action=\""); 502 try appendEscapedHtml(allocator, &out, action_url); 503 try out.appendSlice(allocator, "\" method=\"post\">"); 504 505 // form.focus.children was populated by addChild, which flattens the 506 // whole subtree into one map — so descendants (inputs + the submit 507 // button) all appear here. positions on form.focus are relative to 508 // the form, so we look up absolute rects via root_focus for layout. 509 var inner_iter = child.focus.children.iterator(); 510 while (inner_iter.next()) |inner_entry| { 511 const inner_id = inner_entry.key_ptr.*; 512 const root_child = root_focus.children.get(inner_id) orelse continue; 513 const r = root_child.rect; 514 switch (root_child.focus.kind) { 515 .text_input, .text_input_password => { 516 const ti: *wgt.TextInput(ui.Widget) = @fieldParentPtr("focus", root_child.focus); 517 const inner_left = r.x + 1; 518 const inner_top = r.y + 1; 519 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 520 521 try out.appendSlice(allocator, "<input type=\""); 522 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 523 try out.appendSlice(allocator, "\" data-focus-id=\""); 524 var id_buf: [32]u8 = undefined; 525 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 526 if (ti.options.name.len > 0) { 527 try out.appendSlice(allocator, "\" name=\""); 528 try appendEscapedHtml(allocator, &out, ti.options.name); 529 } 530 // intentionally no `value` attribute: the browser tracks user input 531 // natively, and including the wasm-side value here would make the 532 // overlay HTML differ on every keystroke — that would trip the diff 533 // in _setOverlay and rebuild the <input>, eating the user's caret. 534 try out.appendSlice(allocator, "\" style=\"left:"); 535 var pos_buf: [64]u8 = undefined; 536 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 })); 537 try out.appendSlice(allocator, "\">"); 538 }, 539 .custom => |custom| { 540 if (std.mem.eql(u8, "submit", custom)) { 541 // inside the dashed border the TUI cells draw around the button. 542 const inner_left = r.x + 1; 543 const inner_top = r.y + 1; 544 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 545 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 546 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 547 var id_buf: [32]u8 = undefined; 548 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 549 try out.appendSlice(allocator, "\" style=\"left:"); 550 var pos_buf: [128]u8 = undefined; 551 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 })); 552 try out.appendSlice(allocator, "\"></button>"); 553 } 554 }, 555 else => {}, 556 } 557 } 558 559 try out.appendSlice(allocator, "</form>"); 560 } 561 562 return try out.toOwnedSlice(allocator); 563 } 564 565 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 566 if (a) |av| return if (b) |bv| av.eql(bv) else false; 567 return b == null; 568 } 569 570 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 571 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 572 // empty slice when neither is set. 573 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 574 if (fg == null and bg == null) return buf[0..0]; 575 const prefix = " style=\""; 576 @memcpy(buf[0..prefix.len], prefix); 577 var i: usize = prefix.len; 578 if (fg) |c| { 579 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]; 580 i += s.len; 581 } 582 if (bg) |c| { 583 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]; 584 i += s.len; 585 } 586 buf[i] = '"'; 587 i += 1; 588 return buf[0..i]; 589 } 590 591 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 592 var iter = focus.children.iterator(); 593 while (iter.next()) |entry| { 594 const child = entry.value_ptr.*; 595 if (!child.focus.focusable) continue; 596 const r = child.rect; 597 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 598 return entry.key_ptr.*; 599 } 600 } 601 return null; 602 } 603 604 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 605 for (input) |ch| { 606 switch (ch) { 607 '&' => try out.appendSlice(allocator, "&amp;"), 608 '<' => try out.appendSlice(allocator, "&lt;"), 609 '>' => try out.appendSlice(allocator, "&gt;"), 610 '"' => try out.appendSlice(allocator, "&quot;"), 611 '\'' => try out.appendSlice(allocator, "&#39;"), 612 else => try out.append(allocator, ch), 613 } 614 } 615 } 616 617 // --- helpers -------------------------------------------------------------- 618 619 fn openHaxyMoment( 620 comptime repo_opts: rp.RepoOpts(.xit), 621 repo: *rp.Repo(.xit, repo_opts), 622 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 623 const DB = rp.Repo(.xit, repo_opts).DB; 624 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 625 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 626 const moment = try DB.HashMap(.read_only).init(moment_cursor); 627 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 628 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 629 _ = try last_object_id_cursor.readBytes(&last_object_id); 630 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 631 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 632 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 633 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 634 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 635 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 636 } 637 638 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 639 var iter = request.iterateHeaders(); 640 while (iter.next()) |header| { 641 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 642 var pairs = std.mem.splitScalar(u8, header.value, ';'); 643 while (pairs.next()) |pair| { 644 const trimmed = std.mem.trim(u8, pair, " \t"); 645 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 646 if (std.mem.eql(u8, trimmed[0..eq], name)) { 647 return trimmed[eq + 1 ..]; 648 } 649 } 650 } 651 return null; 652 } 653 654 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 655 var iter = std.mem.splitScalar(u8, body, '&'); 656 while (iter.next()) |pair| { 657 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 658 if (std.mem.eql(u8, pair[0..eq], key)) { 659 return try decodeFormValue(allocator, pair[eq + 1 ..]); 660 } 661 } 662 return null; 663 } 664 665 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 666 var out: std.ArrayList(u8) = .empty; 667 errdefer out.deinit(allocator); 668 var i: usize = 0; 669 while (i < encoded.len) : (i += 1) { 670 switch (encoded[i]) { 671 '+' => try out.append(allocator, ' '), 672 '%' => { 673 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 674 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 675 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 676 try out.append(allocator, hi * 16 + lo); 677 i += 2; 678 }, 679 else => try out.append(allocator, encoded[i]), 680 } 681 } 682 return try out.toOwnedSlice(allocator); 683 } 684