╭ 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 (std.mem.eql(u8, path, "/") or std.mem.eql(u8, path, "/index.html")) { 163 const user_id_hex = getCookieValue(request, cookie_name); 164 const login_failure: ?ui.Home.Auth.Login.Failure = 165 if (getCookieValue(request, login_failure_cookie)) |raw| 166 if (std.mem.eql(u8, raw, "unknown_user")) 167 .unknown_user 168 else if (std.mem.eql(u8, raw, "wrong_password")) 169 .wrong_password 170 else 171 null 172 else 173 null; 174 const html = try renderIndexHtml(io, allocator, admin_repo_path, user_id_hex, login_failure); 175 defer allocator.free(html); 176 // expire the flash cookie on the way out so a refresh doesn't keep 177 // showing the failure label. 178 var headers: [2]std.http.Header = undefined; 179 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 180 var headers_slice: []const std.http.Header = headers[0..1]; 181 if (login_failure != null) { 182 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 183 headers_slice = headers[0..2]; 184 } 185 try request.respond(html, .{ .extra_headers = headers_slice }); 186 return; 187 } 188 189 const embed = findEmbed(path) orelse { 190 try request.respond("not found", .{ 191 .status = .not_found, 192 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 193 }); 194 return; 195 }; 196 197 try request.respond(embed.body, .{ 198 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 199 }); 200 } 201 202 fn handleLogin( 203 io: std.Io, 204 request: *std.http.Server.Request, 205 allocator: std.mem.Allocator, 206 admin_repo_path: []const u8, 207 ) !void { 208 var body_buf: [256]u8 = undefined; 209 const reader = request.readerExpectNone(&body_buf); 210 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 211 defer allocator.free(body); 212 213 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 214 defer allocator.free(username); 215 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 216 defer allocator.free(password); 217 218 const repo_opts: rp.RepoOpts(.xit) = .{}; 219 const Repo = rp.Repo(.xit, repo_opts); 220 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 221 defer repo.deinit(io, allocator); 222 223 var arena = std.heap.ArenaAllocator.init(allocator); 224 defer arena.deinit(); 225 226 const haxy_moment = try openHaxyMoment(repo_opts, &repo); 227 const result = try evt.User.verifyCredentials(Repo.DB, repo_opts.hash, haxy_moment, &arena, username, password); 228 229 switch (result) { 230 .success => |user_id| { 231 const hex = std.fmt.bytesToHex(user_id, .lower); 232 var cookie_buf: [256]u8 = undefined; 233 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{hex}); 234 try request.respond("", .{ 235 .status = .see_other, 236 .extra_headers = &.{ 237 .{ .name = "location", .value = "/" }, 238 .{ .name = "set-cookie", .value = cookie }, 239 }, 240 }); 241 }, 242 .unknown_user => { 243 try request.respond("", .{ 244 .status = .see_other, 245 .extra_headers = &.{ 246 .{ .name = "location", .value = "/" }, 247 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 248 }, 249 }); 250 }, 251 .wrong_password => { 252 try request.respond("", .{ 253 .status = .see_other, 254 .extra_headers = &.{ 255 .{ .name = "location", .value = "/" }, 256 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 257 }, 258 }); 259 }, 260 } 261 } 262 263 fn handleLogout(request: *std.http.Server.Request) !void { 264 // request.respond's discardBody reads any unused body for us and lands 265 // the connection back in the .ready state for the next request on the 266 // same connection (keep_alive defaults to true). 267 try request.respond("", .{ 268 .status = .see_other, 269 .extra_headers = &.{ 270 .{ .name = "location", .value = "/" }, 271 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 272 }, 273 }); 274 } 275 276 fn renderIndexHtml( 277 io: std.Io, 278 allocator: std.mem.Allocator, 279 admin_repo_path: []const u8, 280 user_id_hex_opt: ?[]const u8, 281 login_failure: ?ui.Home.Auth.Login.Failure, 282 ) ![]const u8 { 283 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 284 285 // open the admin repo to read live user/repo data. 286 const repo_opts: rp.RepoOpts(.xit) = .{}; 287 const Repo = rp.Repo(.xit, repo_opts); 288 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 289 defer repo.deinit(io, allocator); 290 var page_arena = std.heap.ArenaAllocator.init(allocator); 291 defer page_arena.deinit(); 292 293 var session: ui.Session = .{}; 294 if (user_id_hex_opt) |hex| { 295 if (decodeHexAlloc(page_arena.allocator(), hex)) |bytes| { 296 session.data.user_id = bytes; 297 } else |_| {} 298 } 299 session.data.login_failure = login_failure; 300 301 const snapshot: ui.Snapshot = .{ 302 .page = .{ .home = try .init(repo_opts, &page_arena, &repo, &session) }, 303 .session = session.data, 304 }; 305 var root = try ui.initRoot(allocator, &snapshot.page, &session); 306 defer root.deinit(allocator); 307 308 const content = try generateHtml(allocator, &root, &session); 309 defer allocator.free(content); 310 const overlay = try generateOverlay(allocator, &root, &session); 311 defer allocator.free(overlay); 312 313 // serialize the snapshot so the wasm side can parse it back without 314 // making a second request. base64-encoded so the json can be embedded 315 // safely inside the host html. 316 var json: std.Io.Writer.Allocating = .init(allocator); 317 defer json.deinit(); 318 try std.json.Stringify.value(snapshot, .{}, &json.writer); 319 320 const b64 = std.base64.standard.Encoder; 321 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 322 defer allocator.free(json_b64); 323 _ = b64.encode(json_b64, json.written()); 324 325 var out: std.ArrayList(u8) = .empty; 326 errdefer out.deinit(allocator); 327 { 328 var cursor: usize = 0; 329 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 330 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 331 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 332 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 333 }) |sub| { 334 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 335 try out.appendSlice(allocator, template[cursor..idx]); 336 try out.appendSlice(allocator, sub.replacement); 337 cursor = idx + sub.needle.len; 338 } 339 try out.appendSlice(allocator, template[cursor..]); 340 } 341 return try out.toOwnedSlice(allocator); 342 } 343 344 fn findEmbed(request_path: []const u8) ?Embed { 345 const path = if (std.mem.eql(u8, request_path, "/")) 346 "index.html" 347 else if (request_path.len > 1 and request_path[0] == '/') 348 request_path[1..] 349 else 350 return null; 351 352 for (embeds) |embed| { 353 if (std.mem.eql(u8, path, embed.path)) return embed; 354 } 355 return null; 356 } 357 358 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 359 err.print(fmt, args) catch return; 360 err.flush() catch {}; 361 } 362 363 // emits the TUI grid cells (one <span> run per focusable widget) 364 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 365 _ = session; 366 const grid = root.getGrid() orelse return error.MissingGrid; 367 const root_focus = root.getFocus(); 368 369 var out: std.ArrayList(u8) = .empty; 370 errdefer out.deinit(allocator); 371 372 for (0..grid.size.height) |y| { 373 var current_id: ?usize = null; 374 for (0..grid.size.width) |x| { 375 const cell_id = cellFocusId(root_focus, x, y); 376 if (cell_id != current_id) { 377 if (current_id != null) try out.appendSlice(allocator, "</span>"); 378 if (cell_id) |id| { 379 var buf: [128]u8 = undefined; 380 const tag = try std.fmt.bufPrint(&buf, "<span class=\"clickable\" data-focus-id=\"{d}\">", .{id}); 381 try out.appendSlice(allocator, tag); 382 } 383 current_id = cell_id; 384 } 385 const rune = grid.cells.items[try grid.cells.at(.{ y, x })].rune orelse " "; 386 try appendEscapedHtml(allocator, &out, rune); 387 } 388 if (current_id != null) try out.appendSlice(allocator, "</span>"); 389 try out.append(allocator, '\n'); 390 } 391 392 return try out.toOwnedSlice(allocator); 393 } 394 395 // emits the form overlay — a <form> wrapping the text inputs and submit 396 // button, positioned absolutely over the matching grid cells 397 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 398 const root_focus = root.getFocus(); 399 400 var out: std.ArrayList(u8) = .empty; 401 errdefer out.deinit(allocator); 402 403 const InputEntry = struct { 404 focus_id: usize, 405 x: usize, 406 y: usize, 407 width: usize, 408 is_password: bool, 409 ti: *wgt.TextInput(ui.Widget), 410 }; 411 const SubmitButton = struct { 412 focus_id: usize, 413 x: usize, 414 y: usize, 415 width: usize, 416 height: usize, 417 }; 418 var inputs: std.ArrayList(InputEntry) = .empty; 419 defer inputs.deinit(allocator); 420 var submit: ?SubmitButton = null; 421 422 var iter = root_focus.children.iterator(); 423 while (iter.next()) |entry| { 424 const child = entry.value_ptr.*; 425 switch (child.focus.kind) { 426 .text_input, .text_input_password => { 427 try inputs.append(allocator, .{ 428 .focus_id = entry.key_ptr.*, 429 .x = child.rect.x, 430 .y = child.rect.y, 431 .width = child.rect.size.width, 432 .is_password = child.focus.kind == .text_input_password, 433 .ti = @fieldParentPtr("focus", child.focus), 434 }); 435 }, 436 .submit_button => { 437 submit = .{ 438 .focus_id = entry.key_ptr.*, 439 .x = child.rect.x, 440 .y = child.rect.y, 441 .width = child.rect.size.width, 442 .height = child.rect.size.height, 443 }; 444 }, 445 else => {}, 446 } 447 } 448 449 if (submit == null and inputs.items.len == 0) return try out.toOwnedSlice(allocator); 450 451 // top-to-bottom, left-to-right order so the natural tab cycle matches 452 // visual layout (username -> password -> submit button). 453 std.mem.sort(InputEntry, inputs.items, {}, struct { 454 fn lt(_: void, a: InputEntry, b: InputEntry) bool { 455 if (a.y != b.y) return a.y < b.y; 456 return a.x < b.x; 457 } 458 }.lt); 459 460 const action_url: []const u8 = if (session.data.user_id != null) "/logout" else "/login"; 461 462 try out.appendSlice(allocator, "<form action=\""); 463 try out.appendSlice(allocator, action_url); 464 try out.appendSlice(allocator, "\" method=\"post\">"); 465 466 for (inputs.items) |entry| { 467 const inner_left = entry.x + 1; 468 const inner_top = entry.y + 1; 469 const inner_width = if (entry.width > 2) entry.width - 2 else 0; 470 471 try out.appendSlice(allocator, "<input type=\""); 472 try out.appendSlice(allocator, if (entry.is_password) "password" else "text"); 473 try out.appendSlice(allocator, "\" data-focus-id=\""); 474 var id_buf: [32]u8 = undefined; 475 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.focus_id})); 476 if (entry.ti.options.name.len > 0) { 477 try out.appendSlice(allocator, "\" name=\""); 478 try appendEscapedHtml(allocator, &out, entry.ti.options.name); 479 } 480 // intentionally no `value` attribute: the browser tracks user input 481 // natively, and including the wasm-side value here would make the 482 // overlay HTML differ on every keystroke — that would trip the diff 483 // in _setOverlay and rebuild the <input>, eating the user's caret. 484 try out.appendSlice(allocator, "\" style=\"left:"); 485 var pos_buf: [64]u8 = undefined; 486 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 })); 487 try out.appendSlice(allocator, "\">"); 488 } 489 490 if (submit) |btn| { 491 // inside the dashed border the TUI cells draw around the button. 492 const inner_left = btn.x + 1; 493 const inner_top = btn.y + 1; 494 const inner_width = if (btn.width > 2) btn.width - 2 else 0; 495 const inner_height = if (btn.height > 2) btn.height - 2 else 0; 496 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 497 var id_buf: [32]u8 = undefined; 498 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{btn.focus_id})); 499 try out.appendSlice(allocator, "\" style=\"left:"); 500 var pos_buf: [128]u8 = undefined; 501 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 })); 502 try out.appendSlice(allocator, "\"></button>"); 503 } 504 505 try out.appendSlice(allocator, "</form>"); 506 507 return try out.toOwnedSlice(allocator); 508 } 509 510 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 511 var iter = focus.children.iterator(); 512 while (iter.next()) |entry| { 513 const child = entry.value_ptr.*; 514 if (!child.focus.focusable) continue; 515 const r = child.rect; 516 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 517 return entry.key_ptr.*; 518 } 519 } 520 return null; 521 } 522 523 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 524 for (input) |ch| { 525 switch (ch) { 526 '&' => try out.appendSlice(allocator, "&amp;"), 527 '<' => try out.appendSlice(allocator, "&lt;"), 528 '>' => try out.appendSlice(allocator, "&gt;"), 529 '"' => try out.appendSlice(allocator, "&quot;"), 530 '\'' => try out.appendSlice(allocator, "&#39;"), 531 else => try out.append(allocator, ch), 532 } 533 } 534 } 535 536 // --- helpers -------------------------------------------------------------- 537 538 fn openHaxyMoment( 539 comptime repo_opts: rp.RepoOpts(.xit), 540 repo: *rp.Repo(.xit, repo_opts), 541 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 542 const DB = rp.Repo(.xit, repo_opts).DB; 543 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 544 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 545 const moment = try DB.HashMap(.read_only).init(moment_cursor); 546 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 547 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 548 _ = try last_object_id_cursor.readBytes(&last_object_id); 549 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 550 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 551 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 552 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 553 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 554 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 555 } 556 557 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 558 var iter = request.iterateHeaders(); 559 while (iter.next()) |header| { 560 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 561 var pairs = std.mem.splitScalar(u8, header.value, ';'); 562 while (pairs.next()) |pair| { 563 const trimmed = std.mem.trim(u8, pair, " \t"); 564 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 565 if (std.mem.eql(u8, trimmed[0..eq], name)) { 566 return trimmed[eq + 1 ..]; 567 } 568 } 569 } 570 return null; 571 } 572 573 fn decodeHexAlloc(allocator: std.mem.Allocator, hex: []const u8) ![]u8 { 574 if (hex.len % 2 != 0) return error.InvalidHex; 575 const bytes = try allocator.alloc(u8, hex.len / 2); 576 errdefer allocator.free(bytes); 577 _ = std.fmt.hexToBytes(bytes, hex) catch return error.InvalidHex; 578 return bytes; 579 } 580 581 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 582 var iter = std.mem.splitScalar(u8, body, '&'); 583 while (iter.next()) |pair| { 584 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 585 if (std.mem.eql(u8, pair[0..eq], key)) { 586 return try decodeFormValue(allocator, pair[eq + 1 ..]); 587 } 588 } 589 return null; 590 } 591 592 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 593 var out: std.ArrayList(u8) = .empty; 594 errdefer out.deinit(allocator); 595 var i: usize = 0; 596 while (i < encoded.len) : (i += 1) { 597 switch (encoded[i]) { 598 '+' => try out.append(allocator, ' '), 599 '%' => { 600 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 601 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 602 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 603 try out.append(allocator, hi * 16 + lo); 604 i += 2; 605 }, 606 else => try out.append(allocator, encoded[i]), 607 } 608 } 609 return try out.toOwnedSlice(allocator); 610 } 611