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