╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const ui = @import("./ui.zig"); 5 const xitui = xit.xitui; 6 const Focus = xitui.focus.Focus; 7 8 const Embed = struct { 9 path: []const u8, 10 content_type: []const u8, 11 body: []const u8, 12 }; 13 14 const embeds = [_]Embed{ 15 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 16 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 17 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 18 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("embed/haxy.wasm") }, 19 }; 20 21 pub fn run( 22 io: std.Io, 23 allocator: std.mem.Allocator, 24 net_server: *std.Io.net.Server, 25 tasks: *std.Io.Group, 26 admin_repo_path: []const u8, 27 err: *std.Io.Writer, 28 ) void { 29 const Listener = struct { 30 io: std.Io, 31 allocator: std.mem.Allocator, 32 net_server: *std.Io.net.Server, 33 tasks: *std.Io.Group, 34 admin_repo_path: []const u8, 35 err: *std.Io.Writer, 36 37 fn run(ctx: @This()) void { 38 while (true) { 39 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 40 if (accept_err == error.Canceled) return; 41 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 42 continue; 43 }; 44 45 const Connection = struct { 46 io: std.Io, 47 allocator: std.mem.Allocator, 48 stream: std.Io.net.Stream, 49 admin_repo_path: []const u8, 50 err: *std.Io.Writer, 51 52 fn run(conn: @This()) void { 53 defer conn.stream.close(conn.io); 54 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.err) catch |request_err| { 55 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 56 }; 57 } 58 }; 59 60 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 61 .io = ctx.io, 62 .allocator = ctx.allocator, 63 .stream = stream, 64 .admin_repo_path = ctx.admin_repo_path, 65 .err = ctx.err, 66 }}); 67 } 68 } 69 }; 70 71 tasks.async(io, Listener.run, .{Listener{ 72 .io = io, 73 .allocator = allocator, 74 .net_server = net_server, 75 .tasks = tasks, 76 .admin_repo_path = admin_repo_path, 77 .err = err, 78 }}); 79 } 80 81 fn renderIndexHtml(io: std.Io, allocator: std.mem.Allocator, admin_repo_path: []const u8) ![]const u8 { 82 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 83 84 // open the admin repo to read live user/repo data; if it doesn't exist 85 // yet (e.g. a fresh `haxy serve` with no admin repo) fall back to empty. 86 const repo_opts: rp.RepoOpts(.xit) = .{}; 87 const Repo = rp.Repo(.xit, repo_opts); 88 var repo_or_err = Repo.open(io, allocator, .{ .path = admin_repo_path }); 89 var page_arena = std.heap.ArenaAllocator.init(allocator); 90 defer page_arena.deinit(); 91 const page: ui.Page = if (repo_or_err) |*repo| blk: { 92 defer repo.deinit(io, allocator); 93 break :blk .{ .users_and_repos = try .init(repo_opts, &page_arena, repo) }; 94 } else |_| .{ .users_and_repos = .empty() }; 95 96 var root = try ui.initRoot(allocator, &page); 97 defer root.deinit(); 98 99 const content = try generateHtml(allocator, &root); 100 defer allocator.free(content); 101 102 // serialize the page so the wasm side can parse it back without making 103 // a second request. base64-encoded so the json can be embedded in html. 104 var json: std.Io.Writer.Allocating = .init(allocator); 105 defer json.deinit(); 106 try std.json.Stringify.value(page, .{}, &json.writer); 107 108 const b64 = std.base64.standard.Encoder; 109 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 110 defer allocator.free(json_b64); 111 _ = b64.encode(json_b64, json.written()); 112 113 var out: std.ArrayList(u8) = .empty; 114 errdefer out.deinit(allocator); 115 { 116 var cursor: usize = 0; 117 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 118 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 119 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 120 }) |sub| { 121 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 122 try out.appendSlice(allocator, template[cursor..idx]); 123 try out.appendSlice(allocator, sub.replacement); 124 cursor = idx + sub.needle.len; 125 } 126 try out.appendSlice(allocator, template[cursor..]); 127 } 128 return try out.toOwnedSlice(allocator); 129 } 130 131 fn handleConnection( 132 io: std.Io, 133 allocator: std.mem.Allocator, 134 stream: std.Io.net.Stream, 135 admin_repo_path: []const u8, 136 err: *std.Io.Writer, 137 ) !void { 138 var send_buffer = [_]u8{0} ** 4096; 139 var recv_buffer = [_]u8{0} ** 4096; 140 var conn_br = stream.reader(io, &recv_buffer); 141 var conn_bw = stream.writer(io, &send_buffer); 142 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 143 144 while (http_server.reader.state == .ready) { 145 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 146 error.HttpConnectionClosing => break, 147 error.ReadFailed => break, 148 else => |e| return e, 149 }; 150 151 handleRequest(io, &http_server, &request, allocator, admin_repo_path) catch |request_err| { 152 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 153 try err.flush(); 154 if (http_server.reader.state == .received_head) { 155 http_server.reader.state = .ready; 156 } 157 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 158 }; 159 try http_server.out.flush(); 160 break; 161 } 162 } 163 164 fn handleRequest( 165 io: std.Io, 166 http_server: *std.http.Server, 167 request: *std.http.Server.Request, 168 allocator: std.mem.Allocator, 169 admin_repo_path: []const u8, 170 ) !void { 171 const method = if (request.head.method == .HEAD) .GET else request.head.method; 172 if (method != .GET) { 173 if (http_server.reader.state == .received_head) { 174 http_server.reader.state = .ready; 175 } 176 try writeSimpleResponse(http_server, 405, "Method Not Allowed", "text/plain", "method not allowed"); 177 return; 178 } 179 180 const uri = try std.Uri.parseAfterScheme("", request.head.target); 181 const path = uri.path.percent_encoded; 182 183 if (std.mem.eql(u8, path, "/favicon.ico")) { 184 if (http_server.reader.state == .received_head) { 185 http_server.reader.state = .ready; 186 } 187 try writeStaticResponse(http_server, 204, "No Content", "image/x-icon", "", true); 188 return; 189 } 190 191 const embed = findEmbed(path) orelse { 192 if (http_server.reader.state == .received_head) { 193 http_server.reader.state = .ready; 194 } 195 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 196 return; 197 }; 198 199 if (http_server.reader.state == .received_head) { 200 http_server.reader.state = .ready; 201 } 202 203 if (std.mem.eql(u8, embed.path, "index.html")) { 204 const index_html = try renderIndexHtml(io, allocator, admin_repo_path); 205 defer allocator.free(index_html); 206 try writeStaticResponse(http_server, 200, "OK", embed.content_type, index_html, request.head.method == .HEAD); 207 } else { 208 try writeStaticResponse(http_server, 200, "OK", embed.content_type, embed.body, request.head.method == .HEAD); 209 } 210 } 211 212 fn findEmbed(request_path: []const u8) ?Embed { 213 const path = if (std.mem.eql(u8, request_path, "/")) 214 "index.html" 215 else if (request_path.len > 1 and request_path[0] == '/') 216 request_path[1..] 217 else 218 return null; 219 220 for (embeds) |embed| { 221 if (std.mem.eql(u8, path, embed.path)) return embed; 222 } 223 return null; 224 } 225 226 fn writeSimpleResponse( 227 http_server: *std.http.Server, 228 code: u16, 229 message: []const u8, 230 content_type: []const u8, 231 body: []const u8, 232 ) !void { 233 try http_server.out.print( 234 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 235 .{ code, message, content_type, body.len, body }, 236 ); 237 } 238 239 fn writeStaticResponse( 240 http_server: *std.http.Server, 241 code: u16, 242 message: []const u8, 243 content_type: []const u8, 244 body: []const u8, 245 head_only: bool, 246 ) !void { 247 try http_server.out.print( 248 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n", 249 .{ code, message, content_type, body.len }, 250 ); 251 if (!head_only) { 252 try http_server.out.writeAll(body); 253 } 254 } 255 256 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 257 err.print(fmt, args) catch return; 258 err.flush() catch {}; 259 } 260 261 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 262 const grid = root.getGrid() orelse return error.MissingGrid; 263 const root_focus = root.getFocus(); 264 265 var out: std.ArrayList(u8) = .empty; 266 errdefer out.deinit(allocator); 267 268 for (0..grid.size.height) |y| { 269 // wrap runs of cells belonging to a focusable widget in a span tagged 270 // with that widget's focus id. CSS paints them with a pointer cursor; 271 // JS reads the id on click and dispatches focus directly. 272 var current_id: ?usize = null; 273 for (0..grid.size.width) |x| { 274 const cell_id = cellFocusId(root_focus, x, y); 275 if (cell_id != current_id) { 276 if (current_id != null) try out.appendSlice(allocator, "</span>"); 277 if (cell_id) |id| { 278 var buf: [64]u8 = undefined; 279 const tag = try std.fmt.bufPrint(&buf, "<span class=\"clickable\" data-focus-id=\"{}\">", .{id}); 280 try out.appendSlice(allocator, tag); 281 } 282 current_id = cell_id; 283 } 284 const rune = grid.cells.items[try grid.cells.at(.{ y, x })].rune orelse " "; 285 try appendEscapedHtml(allocator, &out, rune); 286 } 287 if (current_id != null) try out.appendSlice(allocator, "</span>"); 288 try out.append(allocator, '\n'); 289 } 290 291 return try out.toOwnedSlice(allocator); 292 } 293 294 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 295 var iter = focus.children.iterator(); 296 while (iter.next()) |entry| { 297 const child = entry.value_ptr.*; 298 if (!child.focus.focusable) continue; 299 const r = child.rect; 300 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 301 return entry.key_ptr.*; 302 } 303 } 304 return null; 305 } 306 307 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 308 for (input) |ch| { 309 switch (ch) { 310 '&' => try out.appendSlice(allocator, "&amp;"), 311 '<' => try out.appendSlice(allocator, "&lt;"), 312 '>' => try out.appendSlice(allocator, "&gt;"), 313 '"' => try out.appendSlice(allocator, "&quot;"), 314 '\'' => try out.appendSlice(allocator, "&#39;"), 315 else => try out.append(allocator, ch), 316 } 317 } 318 } 319