╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2263 error.NameTaken => .name_taken, 2264 else => null, 2265 }; 2266 } 2267 }; 2268 2269 pub const RolesFailure = enum { not_found, already_added }; 2270 2271 pub const AssignmentFailure = enum { not_found, not_an_email, already_assigned }; 2272 2273 pub const UserFailure = enum { 2274 required_name, 2275 invalid_name, 2276 name_taken, 2277 required_email, 2278 email_taken, 2279 required_password, 2280 password_mismatch, 2281 wrong_password, 2282 2283 pub fn fromError(err: anyerror) ?UserFailure { 2284 return switch (err) { 2285 error.NameEmpty => .required_name, 2286 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2287 error.NameTaken => .name_taken, 2288 error.EmailEmpty => .required_email, 2289 error.EmailTaken => .email_taken, 2290 error.PasswordEmpty => .required_password, 2291 error.PasswordMismatch => .password_mismatch, 2292 error.WrongPassword => .wrong_password, 2293 else => null, 2294 }; 2295 } 2296 }; 2297 2298 login: struct { 2299 failure: LoginFailure, 2300 username: []const u8, 2301 }, 2302 user: struct { 2303 failure: UserFailure, 2304 // passwords are never retained 2305 fields: struct { 2306 name: []const u8, 2307 email: []const u8, 2308 }, 2309 }, 2310 user_settings: struct { 2311 failure: UserFailure, 2312 // passwords are never retained 2313 fields: struct { email: []const u8 }, 2314 }, 2315 repo: struct { 2316 failure: RepoFailure, 2317 fields: struct { 2318 name: []const u8, 2319 description: []const u8, 2320 hash: hash.HashKind, 2321 access: evt.Repo.Access, 2322 }, 2323 }, 2324 repo_settings: struct { 2325 failure: RepoFailure, 2326 fields: struct { 2327 name: []const u8, 2328 description: []const u8, 2329 access: evt.Repo.Access, 2330 discuss_role: ?evt.Repo.Role, 2331 issue_role: ?evt.Repo.Role, 2332 patch_role: ?evt.Repo.Role, 2333 }, 2334 }, 2335 repo_roles: struct { 2336 failure: RolesFailure, 2337 name: []const u8, 2338 }, 2339 assignment: struct { 2340 failure: AssignmentFailure, 2341 text: []const u8, 2342 }, 2343 issue: struct { 2344 failure: ThreadFailure, 2345 fields: ?struct { 2346 title: []const u8, 2347 labels: []const u8, 2348 description: []const u8, 2349 } = null, 2350 }, 2351 patch: struct { 2352 failure: PatchFailure, 2353 fields: ?struct { 2354 title: []const u8, 2355 labels: []const u8, 2356 description: []const u8, 2357 target_branch: []const u8, 2358 source_branch: []const u8 = "", 2359 source_kind: Repo.Patches.Source.Kind = .fork, 2360 } = null, 2361 }, 2362 discussion: struct { 2363 failure: ThreadFailure, 2364 fields: ?struct { 2365 title: []const u8, 2366 labels: []const u8, 2367 description: []const u8, 2368 } = null, 2369 }, 2370 }; 2371 2372 const Self = @This(); 2373 2374 // serializable data sent down to web client 2375 pub const Data = struct { 2376 user_id: ?[]const u8 = null, 2377 // the logged-in user's name and email, for the views that show them 2378 user_name: ?[]const u8 = null, 2379 user_email: ?[]const u8 = null, 2380 // a failed form retained long enough to render it for correction 2381 form_feedback: ?FormFeedback = null, 2382 // a transient local event-sync error 2383 sync_failure: ?[]const u8 = null, 2384 // a failed terminal undo retained on the current tab 2385 undo_failure: ?[]const u8 = null, 2386 current_page: RoutablePage = .default, 2387 // the selected ANSI art. the server serializes one image for WASM so 2388 // the browser does not need the whole build-generated collection. 2389 ansi_art: []const u8 = "", 2390 // the bound git-service ports. absent in local mode, where remote urls 2391 // are not shown. 2392 git_http_port: ?u16 = null, 2393 git_ssh_port: ?u16 = null, 2394 git_ssh_prefix: []const u8 = "", 2395 // whether this session views a local repo or the server. unlike `local` 2396 // (the host-side filesystem source) this travels in the snapshot, so 2397 // the wasm side also parses elided link urls and hides the multi-user 2398 // chrome. 2399 host_kind: evt.HostKind = .server, 2400 }; 2401 2402 pub fn init( 2403 arena: *std.heap.ArenaAllocator, 2404 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2405 data: Data, 2406 ) !Self { 2407 var session = Self{ 2408 .data = data, 2409 .arena = arena, 2410 // until a host swaps in a page-scoped arena (Nav does this), page 2411 // allocations land in the session arena. on the web path that's the 2412 // intended behavior, since the whole arena is per-request. 2413 .page_arena = arena, 2414 .admin_repo = repo, 2415 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2416 }; 2417 try session.loadUser(); 2418 return session; 2419 } 2420 2421 // load the logged-in user's name and persisted preferences from the db 2422 pub fn loadUser(self: *Self) !void { 2423 const user_id = self.userId() orelse return; 2424 const moment = self.haxy_moment orelse return; 2425 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2426 self.data.user_name = user.event.name; 2427 self.data.user_email = user.event.email; 2428 } 2429 2430 // forget the logged-in user, on a logout or once their account is removed 2431 pub fn logOut(self: *Self) void { 2432 self.data.user_id = null; 2433 self.data.user_name = null; 2434 self.data.user_email = null; 2435 } 2436 2437 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2438 const bytes = self.data.user_id orelse return null; 2439 if (bytes.len != evt.event_id_size) return null; 2440 var id: [evt.event_id_size]u8 = undefined; 2441 @memcpy(&id, bytes); 2442 return id; 2443 } 2444 2445 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2446 const feedback = self.data.form_feedback orelse return null; 2447 if (std.meta.activeTag(feedback) != tag) return null; 2448 return @field(feedback, @tagName(tag)); 2449 } 2450 2451 pub fn clearFormFeedback(self: *Self) void { 2452 self.data.form_feedback = null; 2453 } 2454 2455 // the actor for a write to the repo `identity` names, or null when the 2456 // session may not write there with at least `min_role` or in the 2457 // `thread_kind` tab. local mode always writes. 2458 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2459 if (self.data.host_kind == .local) { 2460 const author = blk: { 2461 const src = self.local orelse break :blk local_author_fallback; 2462 const io = self.io orelse break :blk local_author_fallback; 2463 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2464 }; 2465 return .{ .author = author, .role = .owner }; 2466 } 2467 const user_id = self.userId() orelse return null; 2468 // the session's moment predates this input, so read the roles afresh 2469 const admin_repo = self.admin_repo orelse return null; 2470 const io = self.io orelse return null; 2471 const users_dir = self.users_dir orelse return null; 2472 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2473 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2474 .actor => |actor| actor, 2475 .login_required, .repo_not_found, .forbidden => null, 2476 }; 2477 } 2478 2479 // where this session's event writes go. a server session always has a users dir 2480 pub fn eventHost(self: *const Self) evt.Host { 2481 return switch (self.data.host_kind) { 2482 .local => .local, 2483 .server => .{ .server = .{ .users_dir = self.users_dir orelse unreachable } }, 2484 }; 2485 } 2486 2487 // reload the moment from the admin repo and log out a removed user 2488 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2489 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2490 self.haxy_moment = moment; 2491 2492 const user_id = self.userId() orelse return; 2493 var arena = std.heap.ArenaAllocator.init(allocator); 2494 defer arena.deinit(); 2495 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2496 } 2497 2498 // request a forward navigation to `route`; the host consumes next_page 2499 // (Nav.sync on the terminal, the wasm tick on the web). 2500 pub fn navigate(self: *Session, route: RoutablePage) !void { 2501 self.clearFormFeedback(); 2502 self.next_page = route; 2503 } 2504 }; 2505 2506 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2507 var nav = try Nav.init(allocator, session); 2508 defer nav.deinit(allocator); 2509 2510 var terminal = try term.Terminal.init(io, allocator); 2511 terminal.render_state.no_color = !session.color; 2512 var terminal_live = true; 2513 defer if (terminal_live) terminal.deinit(io); 2514 2515 // set term as active so it will be properly cooked 2516 // when a panic/segfault happens 2517 term.setActive(&terminal); 2518 defer term.setActive(null); 2519 2520 try terminal.queryBackground(); 2521 2522 while (!terminal.shouldQuit()) { 2523 const grid_changed = try terminal.render(&nav.root); 2524 2525 // process any inputs. 2526 // 2527 // if the grid didn't change, then first do a blocking 2528 // read, so the thread will sleep until further input. 2529 // after that, all remaining reads are non-blocking so 2530 // we can process the rest of the queued inputs. 2531 // 2532 // if the grid *did* change, then only do non-blocking 2533 // reads. we do not want to sleep the thread because 2534 // there may be an animation that requires more looping. 2535 var blocking = !grid_changed; 2536 while (try terminal.readKey(io, blocking)) |key| { 2537 blocking = false; 2538 try inputKey(allocator, &nav.root, key, session); 2539 } 2540 2541 if (session.host_request) |request| { 2542 session.host_request = null; 2543 switch (request) { 2544 .show_copyable_text => |copyable_text| { 2545 term.setActive(null); 2546 terminal.deinit(io); 2547 terminal_live = false; 2548 showCopyableText(io, copyable_text) catch |show_err| { 2549 terminal = try term.Terminal.init(io, allocator); 2550 terminal_live = true; 2551 term.setActive(&terminal); 2552 return show_err; 2553 }; 2554 terminal = try term.Terminal.init(io, allocator); 2555 terminal.render_state.no_color = !session.color; 2556 terminal_live = true; 2557 term.setActive(&terminal); 2558 }, 2559 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2560 .sync_events => { 2561 try nav.root.build(allocator, .{ 2562 .min_size = .{ .width = null, .height = null }, 2563 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2564 }, nav.root.getFocus()); 2565 _ = try terminal.render(&nav.root); 2566 try Repo.Events.performSync(allocator, session); 2567 }, 2568 } 2569 } 2570 2571 // reload so the next navigation builds its page from the current moment 2572 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2573 2574 // reconcile navigation: forward to a new page, or back on escape. 2575 // the terminal background can change at any time, so recheck it on each page 2576 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2577 2578 // the quit button (on the quit tab) asks the host to tear down. 2579 if (session.quit_requested) terminal.requestQuit(); 2580 2581 try nav.root.build(allocator, .{ 2582 .min_size = .{ .width = null, .height = null }, 2583 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2584 }, nav.root.getFocus()); 2585 } 2586 } 2587 2588 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2589 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2590 null 2591 else 2592 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2593 defer if (tty) |file| file.close(io); 2594 2595 const input = if (tty) |file| file else std.Io.File.stdin(); 2596 const output = if (tty) |file| file else std.Io.File.stdout(); 2597 2598 var write_buf: [1024]u8 = undefined; 2599 var writer = output.writer(io, &write_buf); 2600 try writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 2601 try writer.interface.flush(); 2602 2603 var read_buf: [1]u8 = undefined; 2604 var reader = input.reader(io, &read_buf); 2605 while (true) { 2606 const byte = try reader.interface.takeByte(); 2607 if (byte == '\r' or byte == '\n') return; 2608 } 2609 } 2610 2611 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2612 const root_focus = root.getFocus(); 2613 const focused_before = root_focus.grandchild_id; 2614 var activate_in_page_link = false; 2615 switch (key) { 2616 // request a navigation pop; the host's Nav.sync goes back a page, or 2617 // quits when there's no history left. 2618 .escape => { 2619 session.back = .requested; 2620 return; 2621 }, 2622 .ctrl => |letter| switch (letter) { 2623 'r' => { 2624 session.refresh_requested = true; 2625 return; 2626 }, 2627 else => try root.input(allocator, key, root_focus), 2628 }, 2629 .enter => { 2630 if (root_focus.grandchild_id) |gid| { 2631 // follow a cross-page link 2632 if (crossPageLink(root_focus, gid, session.data)) |route| { 2633 return session.navigate(route); 2634 } 2635 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2636 } 2637 activate_in_page_link = true; 2638 try root.input(allocator, key, root_focus); 2639 }, 2640 .mouse => |mouse| { 2641 if (mouse.action == .press and mouse.action.press == .left) { 2642 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2643 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2644 const focus_id = hit.id; 2645 if (hit.kind == .background) { 2646 root_focus.setFocus(focus_id); 2647 return; 2648 } 2649 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2650 if (session.back == .available) session.back = .requested; 2651 return; 2652 } 2653 // follow a cross-page link 2654 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2655 return session.navigate(route); 2656 } 2657 if (currentPageLink(root_focus, focus_id, session.data)) return; 2658 if (rawLink(root_focus, focus_id)) |url| { 2659 if (!mouse.ctrl) try requestRawLink(session, url); 2660 return; 2661 } 2662 root_focus.setFocus(focus_id); 2663 activate_in_page_link = true; 2664 } 2665 // forward the press into the widget tree so buttons (and any 2666 // future click-aware widgets) can react. widgets that don't 2667 // care about presses ignore it. 2668 try root.input(allocator, key, root_focus); 2669 } else { 2670 try root.input(allocator, key, root_focus); 2671 } 2672 }, 2673 .event => |event| switch (event) { 2674 .background => |rgb| session.terminal_background = rgb, 2675 .resize => try root.input(allocator, key, root_focus), 2676 }, 2677 else => try root.input(allocator, key, root_focus), 2678 } 2679 2680 const focused_after = root_focus.grandchild_id; 2681 if (!activate_in_page_link and focused_before == focused_after) return; 2682 const focus_id = focused_after orelse return; 2683 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2684 } 2685 2686 // a link to bytes the server serves directly rather than to a page route, so 2687 // it never resolves to a RoutablePage 2688 pub const raw_link_prefix = "ax:"; 2689 2690 // a route already loaded into the current page; focusing it changes the url 2691 // without rebuilding the page 2692 pub const in_page_link_prefix = "ai:"; 2693 2694 // an in-page tab's base route, or the exact current route when it is selected 2695 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2696 const target = if (selected) session.data.current_page else route; 2697 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2698 } 2699 2700 // a button the web renderer covers with a file picker that posts the chosen 2701 // file to the url after the prefix 2702 pub const file_input_prefix = "file:"; 2703 2704 // a submit button that overrides its enclosing form's action 2705 pub const submit_action_prefix = "submit:"; 2706 2707 // one option of a radio field, as `radio:<name>=<value>` 2708 pub const radio_prefix = "radio:"; 2709 2710 // the url an `ax:` link points at, or null for anything else. a host that 2711 // suppresses the anchor's own navigation needs this to follow the link. 2712 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2713 const child = root_focus.children.get(focus_id) orelse return null; 2714 const custom = switch (child.focus.kind) { 2715 .custom => |c| c, 2716 else => return null, 2717 }; 2718 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2719 return custom[raw_link_prefix.len..]; 2720 } 2721 2722 fn requestRawLink(session: *Session, url: []const u8) !void { 2723 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2724 } 2725 2726 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2727 // an absolute url is already complete 2728 if (!std.mem.startsWith(u8, path, "/")) return path; 2729 return if (session.web_port) |port| 2730 try allocator.print("http://localhost:{d}{s}", .{ port, path }) 2731 else 2732 path; 2733 } 2734 2735 // if the focus target at focus_id is an `a:` link that should navigate (a 2736 // different parent page, or a different files directory within the repo page), 2737 // return its route; otherwise null. lets a host turn a click / enter on such a 2738 // link into a navigation rather than a focus change. 2739 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2740 const current = data.current_page; 2741 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2742 // a link to a different parent page always navigates; within a page, a 2743 // files-directory / commits-page / list-window change navigates while tab 2744 // links stay in-page. 2745 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.forkPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 2746 return null; 2747 } 2748 2749 // the page the clicked cell links to, from a link inside a text box's content 2750 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 2751 const grid = root.getGrid() orelse return null; 2752 const cell = grid.cell(x, y) catch return null; 2753 const link = cell.link orelse return null; 2754 if (link.len == 0 or link[0] != '/') return null; 2755 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 2756 } 2757 2758 // whether the `a:` focus target links to the page already shown, which a click 2759 // leaves alone rather than focusing 2760 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 2761 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 2762 return route.eql(data.current_page); 2763 } 2764 2765 // the route carried by an `ai:` focus target, or null for any other target 2766 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2767 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2768 } 2769 2770 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2771 const child = root_focus.children.get(focus_id) orelse return null; 2772 const custom = switch (child.focus.kind) { 2773 .custom => |c| c, 2774 else => return null, 2775 }; 2776 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2777 const path = custom[prefix.len..]; 2778 // local sessions build (and parse) links with the repo identity elided 2779 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2780 } 2781 2782 // a display author, resolved against the admin db at read time 2783 pub const Author = union(enum) { 2784 unknown, 2785 email: []const u8, // an email no user matches 2786 user_name: []const u8, 2787 2788 // the commit author line's email, resolved like initFromEmail 2789 pub fn init( 2790 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2791 arena: *std.heap.ArenaAllocator, 2792 author_line: []const u8, 2793 ) !Author { 2794 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2795 } 2796 2797 // from a record's stored author email: it resolves to the user currently 2798 // holding it, else stays the email. the result is allocated in `arena`, 2799 // so the email may borrow transient memory. 2800 pub fn initFromEmail( 2801 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2802 arena: *std.heap.ArenaAllocator, 2803 author_email: ?[]const u8, 2804 ) !Author { 2805 const email = author_email orelse return .unknown; 2806 if (haxy_moment) |moment| { 2807 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2808 return .{ .user_name = user.name }; 2809 } 2810 } 2811 return .{ .email = try arena.allocator().dupe(u8, email) }; 2812 } 2813 }; 2814 2815 // the "a:" link to user `name`'s page. 2816 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2817 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2818 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2819 return page_arena.allocator().print("a:{s}", .{url}); 2820 } 2821 2822 // a focusable " author " box showing `author`, linking to their user page 2823 // when it is a known user 2824 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2825 const text = switch (author) { 2826 .unknown => "", 2827 .email, .user_name => |t| t, 2828 }; 2829 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 2830 errdefer tb.deinit(allocator); 2831 tb.getFocus().mode = .all; 2832 switch (author) { 2833 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2834 else => {}, 2835 } 2836 return tb; 2837 } 2838 2839 // native-TUI navigation 2840 pub const Nav = struct { 2841 root: Widget, 2842 // backs the current page (its Page data and the page-scoped strings its 2843 // widgets build). owned here, swapped on each navigation. session.page_arena 2844 // tracks whichever of these is current so widgets allocate into it. 2845 arena: *std.heap.ArenaAllocator, 2846 // the login the current root was built for 2847 user_id: ?[evt.event_id_size]u8, 2848 history: std.ArrayList(Entry), 2849 2850 // each retained page keeps its own arena, freed when the page leaves the 2851 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2852 // long-lived session from accumulating every page it ever visited. 2853 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 2854 2855 // cap on retained back-history so the chain can't grow memory without bound 2856 const max_history: usize = 16; 2857 2858 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2859 session.back = .unavailable; 2860 const arena = try allocator.create(std.heap.ArenaAllocator); 2861 arena.* = std.heap.ArenaAllocator.init(allocator); 2862 errdefer { 2863 arena.deinit(); 2864 allocator.destroy(arena); 2865 } 2866 2867 return .{ 2868 .root = try initCurrentRoot(allocator, arena, session), 2869 .arena = arena, 2870 .user_id = session.userId(), 2871 .history = .empty, 2872 }; 2873 } 2874 2875 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2876 self.root.deinit(allocator); 2877 freeArena(allocator, self.arena); 2878 for (self.history.items) |*entry| { 2879 entry.root.deinit(allocator); 2880 freeArena(allocator, entry.arena); 2881 } 2882 self.history.deinit(allocator); 2883 } 2884 2885 // rebuild the current page in place from a current moment 2886 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2887 if (session.haxy_moment == null and session.local == null) return; 2888 const arena = try allocator.create(std.heap.ArenaAllocator); 2889 arena.* = std.heap.ArenaAllocator.init(allocator); 2890 errdefer freeArena(allocator, arena); 2891 2892 const new_root = try initCurrentRoot(allocator, arena, session); 2893 2894 self.root.deinit(allocator); 2895 freeArena(allocator, self.arena); 2896 self.root = new_root; 2897 self.arena = arena; 2898 self.user_id = session.userId(); 2899 } 2900 2901 // build the current page's root in `arena`, or the not-found page's when 2902 // the route names nothing 2903 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 2904 session.page_arena = arena; 2905 const page = try arena.allocator().create(Page); 2906 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 2907 error.NotFound => blk: { 2908 session.data.current_page = .not_found; 2909 break :blk .not_found; 2910 }, 2911 else => |e| return e, 2912 }; 2913 return initRoot(allocator, page, session); 2914 } 2915 2916 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2917 arena.deinit(); 2918 allocator.destroy(arena); 2919 } 2920 2921 // reconcile the displayed root with the session's navigation state. a 2922 // forward nav (current_page moved to a different parent page) pushes the 2923 // current root and builds the new page in a fresh arena; a back request 2924 // frees the current page and restores the previous one. when escape is 2925 // pressed with no history left we switch to the quit tab instead of quitting. 2926 // returns whether the root was replaced. 2927 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 2928 // refresh: rebuild the current page in place from a current moment 2929 if (session.refresh_requested) { 2930 session.refresh_requested = false; 2931 try self.rebuild(allocator, session); 2932 return true; 2933 } 2934 2935 if (session.back == .requested) { 2936 if (self.history.pop()) |entry| { 2937 session.back = if (self.history.items.len == 0) .unavailable else .available; 2938 self.root.deinit(allocator); 2939 freeArena(allocator, self.arena); 2940 self.root = entry.root; 2941 self.arena = entry.arena; 2942 self.user_id = entry.user_id; 2943 session.page_arena = entry.arena; 2944 session.data.current_page = entry.route; 2945 // a page built under another login is rebuilt rather than restored 2946 if (!std.meta.eql(entry.user_id, session.userId())) { 2947 try self.rebuild(allocator, session); 2948 return true; 2949 } 2950 chooseAnsiArtForNavigation(session); 2951 return true; 2952 } 2953 session.back = .unavailable; 2954 // nothing to go back to; switch to the quit confirmation 2955 const root_focus = self.root.getFocus(); 2956 var iter = root_focus.children.iterator(); 2957 while (iter.next()) |entry| { 2958 switch (entry.value_ptr.focus.kind) { 2959 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2960 root_focus.setFocus(entry.key_ptr.*); 2961 // a Stack only builds its selected child, so the quit 2962 // button isn't in the focus tree until a build runs with 2963 // the quit tab selected. build once, then send a 2964 // synthetic arrow_down to drop focus from the tab onto 2965 // the button so it's ready to confirm. 2966 try self.root.build(allocator, .{ 2967 .min_size = .{ .width = null, .height = 40 }, 2968 .max_size = .{ .width = 80, .height = null }, 2969 }, root_focus); 2970 try self.root.input(allocator, .arrow_down, root_focus); 2971 break; 2972 }, 2973 else => {}, 2974 } 2975 } 2976 return false; 2977 } 2978 2979 // forward navigation: navigate() set next_page to the page to move to (a 2980 // cross-page link or tab change crossing pages) 2981 if (session.next_page) |route| { 2982 session.next_page = null; 2983 if (session.haxy_moment == null and session.local == null) return false; 2984 const previous_route = session.data.current_page; 2985 // the page we navigated to becomes the current page 2986 session.data.current_page = route; 2987 session.back = .available; 2988 2989 const arena = try allocator.create(std.heap.ArenaAllocator); 2990 arena.* = std.heap.ArenaAllocator.init(allocator); 2991 errdefer freeArena(allocator, arena); 2992 2993 const new_root = try initCurrentRoot(allocator, arena, session); 2994 2995 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 2996 // drop the oldest entry (freeing its widget tree and arena) once over cap 2997 if (self.history.items.len > max_history) { 2998 var oldest = self.history.orderedRemove(0); 2999 oldest.root.deinit(allocator); 3000 freeArena(allocator, oldest.arena); 3001 } 3002 self.root = new_root; 3003 self.arena = arena; 3004 self.user_id = session.userId(); 3005 return true; 3006 } 3007 return false; 3008 } 3009 }; 3010 3011 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3012 const page_widget: Widget = switch (page.*) { 3013 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3014 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3015 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3016 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3017 .not_found => .{ .not_found = try .init(allocator, session) }, 3018 }; 3019 3020 chooseAnsiArtForNavigation(session); 3021 3022 // on the TUI/SSH, the page sits above a one-row footer showing its web 3023 // url, when there's a web UI to point at 3024 var root = if (session.is_terminal) blk: { 3025 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3026 errdefer box.deinit(allocator); 3027 const bg_id = bg_blk: { 3028 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3029 errdefer background.deinit(allocator); 3030 const id = background.getFocus().id; 3031 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3032 break :bg_blk id; 3033 }; 3034 if (session.web_port != null) { 3035 var footer = try widget.Footer.init(allocator, session); 3036 errdefer footer.deinit(allocator); 3037 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3038 } 3039 box.getFocus().child_id = bg_id; 3040 break :blk Widget{ .box = box }; 3041 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3042 errdefer root.deinit(allocator); 3043 3044 // input-owning views build their TextInputs in init, so reset their 3045 // registrations here 3046 session.text_inputs.clearRetainingCapacity(); 3047 3048 try root.build(allocator, .{ 3049 .min_size = .{ .width = null, .height = 40 }, 3050 .max_size = .{ .width = 100, .height = null }, 3051 }, root.getFocus()); 3052 3053 return root; 3054 } 3055 3056 // native and server-side sessions choose from the embedded collection. WASM 3057 // keeps the art serialized by the server instead. 3058 fn chooseAnsiArtForNavigation(session: *Session) void { 3059 if (comptime ansi_art.art.len == 0) return; 3060 if (session.data.current_page == .not_found) { 3061 session.data.ansi_art = ansi_art.not_found; 3062 return; 3063 } 3064 const io = session.io orelse return; 3065 var random: usize = undefined; 3066 io.random(std.mem.asBytes(&random)); 3067 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3068 } 3069