╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1312 repo_kind: rp.RepoKind, 1313 // the user's global git config, so local mode picks up their identity and 1314 // their signing and ssh settings. null on the server paths, which must not 1315 // read whoever runs the server. 1316 global_config_path: ?[]const u8 = null, 1317 1318 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 1319 return .{ .path = self.path, .global_config_path = self.global_config_path }; 1320 } 1321 }; 1322 1323 // events created in local mode have no account behind them, so the commit 1324 // author comes from the repo's config, which the global config feeds into. 1325 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 1326 1327 pub fn localAuthor( 1328 src: RepoSource, 1329 io: std.Io, 1330 allocator: std.mem.Allocator, 1331 arena: *std.heap.ArenaAllocator, 1332 ) !evt.CommitAuthor { 1333 switch (src.repo_kind) { 1334 inline else => |repo_kind| { 1335 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 1336 defer any_repo.deinit(io, allocator); 1337 1338 switch (any_repo) { 1339 inline else => |*repo| { 1340 var config = try repo.listConfig(io, allocator); 1341 defer config.deinit(); 1342 1343 const user = config.sections.get("user") orelse return local_author_fallback; 1344 const name = user.get("name") orelse return local_author_fallback; 1345 const email = user.get("email") orelse return local_author_fallback; 1346 return .{ 1347 .name = try arena.allocator().dupe(u8, name), 1348 .email = try arena.allocator().dupe(u8, email), 1349 }; 1350 }, 1351 } 1352 }, 1353 } 1354 } 1355 1356 // per-connection mutable state. each SSH session / web session / local TUI 1357 // run gets its own. 1358 pub const Session = struct { 1359 data: Data = .{}, 1360 // session-lifetime allocations: login/user_id, persisted prefs, queued 1361 // actions. lives as long as the connection. 1362 arena: *std.heap.ArenaAllocator, 1363 // current page's allocations: page data and the page-scoped strings widgets 1364 // build (form actions, links). owned by Nav, swapped on each navigation, so 1365 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 1366 // where a render is one-shot, this points at the same arena as `arena`. 1367 page_arena: *std.heap.ArenaAllocator, 1368 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 1369 // filesystem io and the path to <server>/repos, for opening on-disk repos 1370 // during page construction. both null on wasm, which has no filesystem and 1371 // rebuilds pages from the serialized snapshot rather than from disk. 1372 io: ?std.Io = null, 1373 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 1374 repos_dir: ?[]const u8 = null, 1375 // the single on-disk repo this session views, when running in local mode 1376 // (haxy invoked with no arguments inside a repo). null on the server paths, 1377 // which resolve repos from the admin db instead. 1378 local: ?RepoSource = null, 1379 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 1380 // focus id -> the live TextInput, refreshed each frame by the views that own 1381 // inputs. web/wasm form handling looks widgets up here by focus id. 1382 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 1383 // focus id -> the page-constant text the web renderer puts in an input 1384 // initially, refreshed each frame alongside `text_inputs`. never an 1385 // editable input's live content: the overlay html must not change as the 1386 // user types, or the diff in _setOverlay would rebuild the element. 1387 input_values: std.AutoHashMapUnmanaged(usize, []const u8) = .empty, 1388 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 1389 refresh_requested: bool = false, // set by input (ctrl+r) 1390 // a requested forward navigation. set this (via navigate) to move to a new 1391 // page; Nav.sync builds it and then copies it into current_page, clearing 1392 // this back to null. setting current_page directly only updates the url and 1393 // does not navigate. 1394 next_page: ?RoutablePage = null, 1395 is_terminal: bool = false, // true on remote SSH and local TUI 1396 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 1397 // url. null on the web itself (no footer there). 1398 web_port: ?u16 = null, 1399 // a host operation requested by a widget 1400 host_request: ?HostRequest = null, 1401 quit_requested: bool = false, 1402 1403 pub const HostRequest = union(enum) { 1404 show_copyable_text: []const u8, 1405 sync_events, 1406 }; 1407 1408 const Self = @This(); 1409 1410 // serializable data sent down to web client 1411 pub const Data = struct { 1412 user_id: ?[]const u8 = null, 1413 // the logged-in user's name, for the views that show it 1414 user_name: ?[]const u8 = null, 1415 // a transient outcome to surface from the last /login POST attempt 1416 login_failure: ?Home.Auth.Login.Failure = null, 1417 // a transient local event-sync error 1418 sync_failure: ?[]const u8 = null, 1419 current_page: RoutablePage = .default, 1420 // whether to render the ANSI art backdrop 1421 enable_ansi: bool = true, 1422 // the selected ANSI art. the server serializes one image for WASM so 1423 // the browser does not need the whole build-generated collection. 1424 ansi_art: []const u8 = "", 1425 // the bound git-service ports. absent in local mode, where remote urls 1426 // are not shown. 1427 git_http_port: ?u16 = null, 1428 git_ssh_port: ?u16 = null, 1429 git_ssh_prefix: []const u8 = "", 1430 // true when this session views a single local repo. unlike `local` 1431 // (the host-side filesystem source) this travels in the snapshot, so 1432 // the wasm side also parses elided link urls and hides the multi-user 1433 // chrome. 1434 is_local: bool = false, 1435 }; 1436 1437 // a user-initiated state change. widgets enqueue these on the session during 1438 // input instead of mutating state or touching the DB themselves; the host 1439 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 1440 // side effects out of the widget tree and gives every render path one place to 1441 // turn a UI action into a state change + event. 1442 pub const Action = union(enum) { 1443 toggle_ansi, 1444 }; 1445 1446 pub fn init( 1447 arena: *std.heap.ArenaAllocator, 1448 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1449 data: Data, 1450 ) !Self { 1451 var session = Self{ 1452 .data = data, 1453 .arena = arena, 1454 // until a host swaps in a page-scoped arena (Nav does this), page 1455 // allocations land in the session arena. on the web path that's the 1456 // intended behavior, since the whole arena is per-request. 1457 .page_arena = arena, 1458 .admin_repo = repo, 1459 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 1460 }; 1461 try session.loadUser(); 1462 return session; 1463 } 1464 1465 // load the logged-in user's name and persisted preferences from the db 1466 pub fn loadUser(self: *Self) !void { 1467 const user_id = self.data.user_id orelse return; 1468 const moment = self.haxy_moment orelse return; 1469 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 1470 self.data.user_name = user.event.name; 1471 self.data.enable_ansi = user.event.enable_ansi; 1472 } 1473 } 1474 1475 // the commit author for an event this session creates, or null when it may 1476 // not create one 1477 pub fn eventAuthor(self: *Self) !?evt.CommitAuthor { 1478 if (self.data.is_local) { 1479 const src = self.local orelse return local_author_fallback; 1480 const io = self.io orelse return local_author_fallback; 1481 return try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 1482 } 1483 const user_id = self.data.user_id orelse return null; 1484 const moment = self.haxy_moment orelse return null; 1485 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 1486 return .{ .name = user.event.name, .email = user.event.email }; 1487 } 1488 1489 // queue an action for the host to drain this frame. 1490 pub fn push(self: *Self, action: Action) !void { 1491 try self.pending.append(self.arena.allocator(), action); 1492 } 1493 1494 // apply a single action's in-memory effect only (no persistence). 1495 fn apply(self: *Self, action: Action) void { 1496 switch (action) { 1497 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 1498 } 1499 } 1500 1501 // drain the session's queued actions by applying them to the session. 1502 // used on the wasm path, which has no repo to persist to. 1503 pub fn applyPending(self: *Self) void { 1504 for (self.pending.items) |action| self.apply(action); 1505 self.pending.clearRetainingCapacity(); 1506 } 1507 1508 // drain the session's queued actions by applying them to the session and 1509 // writing them to the db 1510 pub fn applyAndWritePending( 1511 self: *Self, 1512 io: std.Io, 1513 allocator: std.mem.Allocator, 1514 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1515 ) !void { 1516 defer self.pending.clearRetainingCapacity(); 1517 for (self.pending.items) |action| { 1518 self.apply(action); 1519 switch (action) { 1520 .toggle_ansi => if (self.data.user_id) |user_id| { 1521 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1522 }, 1523 } 1524 } 1525 } 1526 1527 // reload the moment from the admin repo and re-read user preferences 1528 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1529 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1530 self.haxy_moment = moment; 1531 1532 const user_id = self.data.user_id orelse return; 1533 var arena = std.heap.ArenaAllocator.init(allocator); 1534 defer arena.deinit(); 1535 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1536 self.data.enable_ansi = user.event.enable_ansi; 1537 } 1538 } 1539 1540 // request a forward navigation to `route`; the host consumes next_page 1541 // (Nav.sync on the terminal, the wasm tick on the web). 1542 pub fn navigate(self: *Session, route: RoutablePage) !void { 1543 self.next_page = route; 1544 } 1545 }; 1546 1547 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1548 var nav = try Nav.init(allocator, session); 1549 defer nav.deinit(allocator); 1550 1551 var terminal = try term.Terminal.init(io, allocator); 1552 var terminal_live = true; 1553 defer if (terminal_live) terminal.deinit(io); 1554 1555 // set term as active so it will be properly cooked 1556 // when a panic/segfault happens 1557 term.setActive(&terminal); 1558 defer term.setActive(null); 1559 1560 var last_size = layout.Size{ .width = 0, .height = 0 }; 1561 var last_grid = try Grid.init(allocator, last_size); 1562 defer last_grid.deinit(); 1563 1564 while (!terminal.shouldQuit()) { 1565 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 1566 1567 // process any inputs. 1568 // 1569 // if the grid didn't change, then first do a blocking 1570 // read, so the thread will sleep until further input. 1571 // after that, all remaining reads are non-blocking so 1572 // we can process the rest of the queued inputs. 1573 // 1574 // if the grid *did* change, then only do non-blocking 1575 // reads. we do not want to sleep the thread because 1576 // there may be an animation that requires more looping. 1577 var blocking = !grid_changed; 1578 while (try terminal.readKey(io, blocking)) |key| { 1579 blocking = false; 1580 try inputKey(allocator, &nav.root, key, session); 1581 } 1582 1583 if (session.host_request) |request| { 1584 session.host_request = null; 1585 switch (request) { 1586 .show_copyable_text => |copyable_text| { 1587 term.setActive(null); 1588 terminal.deinit(io); 1589 terminal_live = false; 1590 showCopyableText(io, copyable_text) catch |show_err| { 1591 terminal = try term.Terminal.init(io, allocator); 1592 terminal_live = true; 1593 term.setActive(&terminal); 1594 return show_err; 1595 }; 1596 terminal = try term.Terminal.init(io, allocator); 1597 terminal_live = true; 1598 term.setActive(&terminal); 1599 last_size = .{ .width = 0, .height = 0 }; 1600 }, 1601 .sync_events => { 1602 try nav.root.build(allocator, .{ 1603 .min_size = .{ .width = null, .height = null }, 1604 .max_size = .{ .width = last_size.width, .height = last_size.height }, 1605 }, nav.root.getFocus()); 1606 _ = try terminal.render(&nav.root, &last_grid, &last_size); 1607 try Repo.Events.performSync(allocator, session); 1608 }, 1609 } 1610 } 1611 1612 // persist queued actions when there's a repo; local mode has none, 1613 // so just apply in-memory 1614 if (repo_maybe) |repo| { 1615 try session.applyAndWritePending(io, allocator, repo); 1616 // reload so the next navigation builds its page from the current moment 1617 try session.reloadMoment(allocator, repo); 1618 } else { 1619 session.applyPending(); 1620 } 1621 1622 // reconcile navigation: forward to a new page, or back on escape. 1623 try nav.sync(allocator, session); 1624 1625 // the quit button (on the quit tab) asks the host to tear down. 1626 if (session.quit_requested) terminal.requestQuit(); 1627 1628 try nav.root.build(allocator, .{ 1629 .min_size = .{ .width = null, .height = null }, 1630 .max_size = .{ .width = last_size.width, .height = last_size.height }, 1631 }, nav.root.getFocus()); 1632 } 1633 } 1634 1635 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 1636 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 1637 null 1638 else 1639 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 1640 defer if (tty) |file| file.close(io); 1641 1642 const input = if (tty) |file| file else std.Io.File.stdin(); 1643 const output = if (tty) |file| file else std.Io.File.stdout(); 1644 1645 var write_buf: [1024]u8 = undefined; 1646 var writer = output.writer(io, &write_buf); 1647 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}); 1648 try writer.interface.flush(); 1649 1650 var read_buf: [1]u8 = undefined; 1651 var reader = input.reader(io, &read_buf); 1652 while (true) { 1653 const byte = try reader.interface.takeByte(); 1654 if (byte == '\r' or byte == '\n') return; 1655 } 1656 } 1657 1658 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 1659 const root_focus = root.getFocus(); 1660 const focused_before = root_focus.grandchild_id; 1661 var activate_in_page_link = false; 1662 switch (key) { 1663 // request a navigation pop; the host's Nav.sync goes back a page, or 1664 // quits when there's no history left. 1665 .escape => { 1666 session.nav_back = true; 1667 return; 1668 }, 1669 .ctrl => |letter| switch (letter) { 1670 'r' => { 1671 session.refresh_requested = true; 1672 return; 1673 }, 1674 else => try root.input(allocator, key, root_focus), 1675 }, 1676 .enter => { 1677 if (root_focus.grandchild_id) |gid| { 1678 // follow a cross-page link 1679 if (crossPageLink(root_focus, gid, session.data)) |route| { 1680 return session.navigate(route); 1681 } 1682 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 1683 } 1684 activate_in_page_link = true; 1685 try root.input(allocator, key, root_focus); 1686 }, 1687 .mouse => |mouse| { 1688 if (mouse.action == .press and mouse.action.press == .left) { 1689 var clicked: ?usize = null; 1690 var iter = root_focus.children.iterator(); 1691 while (iter.next()) |entry| { 1692 const child = entry.value_ptr.*; 1693 if (!child.focus.focusable) continue; 1694 const r = child.rect; 1695 if (mouse.x >= r.x and mouse.y >= r.y and 1696 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 1697 { 1698 clicked = entry.key_ptr.*; 1699 break; 1700 } 1701 } 1702 if (clicked) |focus_id| { 1703 // follow a cross-page link 1704 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 1705 return session.navigate(route); 1706 } 1707 if (rawLink(root_focus, focus_id)) |url| { 1708 if (!mouse.ctrl) try requestRawLink(session, url); 1709 return; 1710 } 1711 root_focus.setFocus(focus_id); 1712 activate_in_page_link = true; 1713 } 1714 // forward the press into the widget tree so buttons (and any 1715 // future click-aware widgets) can react. widgets that don't 1716 // care about presses ignore it. 1717 try root.input(allocator, key, root_focus); 1718 } else { 1719 try root.input(allocator, key, root_focus); 1720 } 1721 }, 1722 else => try root.input(allocator, key, root_focus), 1723 } 1724 1725 const focused_after = root_focus.grandchild_id; 1726 if (!activate_in_page_link and focused_before == focused_after) return; 1727 const focus_id = focused_after orelse return; 1728 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 1729 } 1730 1731 // a link to bytes the server serves directly rather than to a page route, so 1732 // it never resolves to a RoutablePage 1733 pub const raw_link_prefix = "ax:"; 1734 1735 // a route already loaded into the current page; focusing it changes the url 1736 // without rebuilding the page 1737 pub const in_page_link_prefix = "ai:"; 1738 1739 // an in-page tab's base route, or the exact current route when it is selected 1740 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 1741 const target = if (selected) session.data.current_page else route; 1742 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 1743 } 1744 1745 // a button the web overlay covers with a file picker that posts the chosen 1746 // file to the url after the prefix 1747 pub const file_input_prefix = "file:"; 1748 1749 // a submit button that overrides its enclosing form's action 1750 pub const submit_action_prefix = "submit:"; 1751 1752 // the url an `ax:` link points at, or null for anything else. a host that 1753 // suppresses the anchor's own navigation needs this to follow the link. 1754 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 1755 const child = root_focus.children.get(focus_id) orelse return null; 1756 const custom = switch (child.focus.kind) { 1757 .custom => |c| c, 1758 else => return null, 1759 }; 1760 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 1761 return custom[raw_link_prefix.len..]; 1762 } 1763 1764 fn requestRawLink(session: *Session, url: []const u8) !void { 1765 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 1766 } 1767 1768 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 1769 return if (session.web_port) |port| 1770 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 1771 else 1772 path; 1773 } 1774 1775 // if the focus target at focus_id is an `a:` link that should navigate (a 1776 // different parent page, or a different files directory within the repo page), 1777 // return its route; otherwise null. lets a host turn a click / enter on such a 1778 // link into a navigation rather than a focus change. 1779 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1780 const current = data.current_page; 1781 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 1782 // a link to a different parent page always navigates; within a page, a 1783 // files-directory / commits-page / list-window change navigates while tab 1784 // links stay in-page. 1785 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 1786 return null; 1787 } 1788 1789 // the route carried by an `ai:` focus target, or null for any other target 1790 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1791 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 1792 } 1793 1794 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 1795 const child = root_focus.children.get(focus_id) orelse return null; 1796 const custom = switch (child.focus.kind) { 1797 .custom => |c| c, 1798 else => return null, 1799 }; 1800 if (!std.mem.startsWith(u8, custom, prefix)) return null; 1801 const path = custom[prefix.len..]; 1802 // local sessions build (and parse) links with the repo identity elided 1803 return if (data.is_local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 1804 } 1805 1806 // a display author, resolved against the admin db at read time 1807 pub const Author = union(enum) { 1808 unknown, 1809 email: []const u8, // an email no user matches 1810 user_name: []const u8, 1811 1812 // the commit author line's email, resolved like initFromEmail 1813 pub fn init( 1814 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1815 arena: *std.heap.ArenaAllocator, 1816 author_line: []const u8, 1817 ) !Author { 1818 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 1819 } 1820 1821 // from a record's stored author email: it resolves to the user currently 1822 // holding it, else stays the email. the result is allocated in `arena`, 1823 // so the email may borrow transient memory. 1824 pub fn initFromEmail( 1825 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1826 arena: *std.heap.ArenaAllocator, 1827 author_email: ?[]const u8, 1828 ) !Author { 1829 const email = author_email orelse return .unknown; 1830 if (haxy_moment) |moment| { 1831 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 1832 return .{ .user_name = user.event.name }; 1833 } 1834 } 1835 return .{ .email = try arena.allocator().dupe(u8, email) }; 1836 } 1837 }; 1838 1839 // the "a:" link to user `name`'s page. 1840 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 1841 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 1842 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 1843 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 1844 } 1845 1846 // a focusable " author " box showing `author`, linking to their user page 1847 // when it is a known user 1848 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox(Widget) { 1849 const text = switch (author) { 1850 .unknown => "", 1851 .email, .user_name => |t| t, 1852 }; 1853 var tb = try wgt.TextBox(Widget).init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 1854 errdefer tb.deinit(allocator); 1855 tb.getFocus().focusable = true; 1856 switch (author) { 1857 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 1858 else => {}, 1859 } 1860 return tb; 1861 } 1862 1863 // native-TUI navigation 1864 pub const Nav = struct { 1865 root: Widget, 1866 route: RoutablePage, 1867 // backs the current page (its Page data and the page-scoped strings its 1868 // widgets build). owned here, swapped on each navigation. session.page_arena 1869 // tracks whichever of these is current so widgets allocate into it. 1870 arena: *std.heap.ArenaAllocator, 1871 history: std.ArrayList(Entry), 1872 1873 // each retained page keeps its own arena, freed when the page leaves the 1874 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 1875 // long-lived session from accumulating every page it ever visited. 1876 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 1877 1878 // cap on retained back-history so the chain can't grow memory without bound 1879 const max_history: usize = 16; 1880 1881 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 1882 const arena = try allocator.create(std.heap.ArenaAllocator); 1883 arena.* = std.heap.ArenaAllocator.init(allocator); 1884 errdefer { 1885 arena.deinit(); 1886 allocator.destroy(arena); 1887 } 1888 1889 session.page_arena = arena; 1890 const route = session.data.current_page; 1891 1892 const page = try arena.allocator().create(Page); 1893 page.* = try Page.init(arena, session, route); 1894 return .{ 1895 .root = try initRoot(allocator, page, session), 1896 .route = route, 1897 .arena = arena, 1898 .history = .empty, 1899 }; 1900 } 1901 1902 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 1903 self.root.deinit(allocator); 1904 freeArena(allocator, self.arena); 1905 for (self.history.items) |*entry| { 1906 entry.root.deinit(allocator); 1907 freeArena(allocator, entry.arena); 1908 } 1909 self.history.deinit(allocator); 1910 } 1911 1912 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 1913 arena.deinit(); 1914 allocator.destroy(arena); 1915 } 1916 1917 // reconcile the displayed root with the session's navigation state. a 1918 // forward nav (current_page moved to a different parent page) pushes the 1919 // current root and builds the new page in a fresh arena; a back request 1920 // frees the current page and restores the previous one. when escape is 1921 // pressed with no history left we switch to the quit tab instead of quitting. 1922 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 1923 // refresh: rebuild the current page in place from a current moment 1924 if (session.refresh_requested) { 1925 session.refresh_requested = false; 1926 if (session.haxy_moment != null or session.local != null) { 1927 const arena = try allocator.create(std.heap.ArenaAllocator); 1928 arena.* = std.heap.ArenaAllocator.init(allocator); 1929 errdefer freeArena(allocator, arena); 1930 1931 session.page_arena = arena; 1932 1933 const route = session.data.current_page; 1934 const page = try arena.allocator().create(Page); 1935 page.* = try Page.init(arena, session, route); 1936 const new_root = try initRoot(allocator, page, session); 1937 1938 self.root.deinit(allocator); 1939 freeArena(allocator, self.arena); 1940 self.root = new_root; 1941 self.route = route; 1942 self.arena = arena; 1943 } 1944 return; 1945 } 1946 1947 if (session.nav_back) { 1948 session.nav_back = false; 1949 if (self.history.pop()) |entry| { 1950 self.root.deinit(allocator); 1951 freeArena(allocator, self.arena); 1952 self.root = entry.root; 1953 self.route = entry.route; 1954 self.arena = entry.arena; 1955 session.page_arena = entry.arena; 1956 session.data.current_page = entry.route; 1957 chooseAnsiArtForNavigation(session); 1958 return; 1959 } 1960 // nothing to go back to; switch to the quit confirmation 1961 const root_focus = self.root.getFocus(); 1962 var iter = root_focus.children.iterator(); 1963 while (iter.next()) |entry| { 1964 switch (entry.value_ptr.focus.kind) { 1965 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 1966 root_focus.setFocus(entry.key_ptr.*); 1967 // a Stack only builds its selected child, so the quit 1968 // button isn't in the focus tree until a build runs with 1969 // the quit tab selected. build once, then send a 1970 // synthetic arrow_down to drop focus from the tab onto 1971 // the button so it's ready to confirm. 1972 try self.root.build(allocator, .{ 1973 .min_size = .{ .width = null, .height = 40 }, 1974 .max_size = .{ .width = 80, .height = null }, 1975 }, root_focus); 1976 try self.root.input(allocator, .arrow_down, root_focus); 1977 break; 1978 }, 1979 else => {}, 1980 } 1981 } 1982 return; 1983 } 1984 1985 // forward navigation: navigate() set next_page to the page to move to (a 1986 // cross-page link or tab change crossing pages) 1987 if (session.next_page) |route| { 1988 session.next_page = null; 1989 if (session.haxy_moment == null and session.local == null) return; 1990 // the page we navigated to becomes the current page 1991 session.data.current_page = route; 1992 1993 const arena = try allocator.create(std.heap.ArenaAllocator); 1994 arena.* = std.heap.ArenaAllocator.init(allocator); 1995 errdefer freeArena(allocator, arena); 1996 1997 session.page_arena = arena; 1998 1999 const page = try arena.allocator().create(Page); 2000 page.* = try Page.init(arena, session, route); 2001 const new_root = try initRoot(allocator, page, session); 2002 2003 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 2004 // drop the oldest entry (freeing its widget tree and arena) once over cap 2005 if (self.history.items.len > max_history) { 2006 var oldest = self.history.orderedRemove(0); 2007 oldest.root.deinit(allocator); 2008 freeArena(allocator, oldest.arena); 2009 } 2010 self.root = new_root; 2011 self.route = route; 2012 self.arena = arena; 2013 } 2014 } 2015 }; 2016 2017 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2018 const page_widget: Widget = switch (page.*) { 2019 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2020 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2021 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2022 }; 2023 2024 chooseAnsiArtForNavigation(session); 2025 2026 // on the TUI/SSH, the page sits above a one-row footer showing the url 2027 var root = if (session.is_terminal) blk: { 2028 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2029 errdefer box.deinit(allocator); 2030 const bg_id = bg_blk: { 2031 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2032 errdefer background.deinit(allocator); 2033 const id = background.getFocus().id; 2034 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2035 break :bg_blk id; 2036 }; 2037 { 2038 var footer = try widget.Footer.init(allocator, session); 2039 errdefer footer.deinit(allocator); 2040 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2041 } 2042 box.getFocus().child_id = bg_id; 2043 break :blk Widget{ .box = box }; 2044 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2045 errdefer root.deinit(allocator); 2046 2047 // input-owning views build their TextInputs in init, so reset their 2048 // registrations here 2049 session.text_inputs.clearRetainingCapacity(); 2050 session.input_values.clearRetainingCapacity(); 2051 2052 try root.build(allocator, .{ 2053 .min_size = .{ .width = null, .height = 40 }, 2054 .max_size = .{ .width = 100, .height = null }, 2055 }, root.getFocus()); 2056 2057 return root; 2058 } 2059 2060 // native and server-side sessions choose from the embedded collection. WASM 2061 // keeps the art serialized by the server instead. 2062 fn chooseAnsiArtForNavigation(session: *Session) void { 2063 if (comptime ansi_arts.len == 0) return; 2064 const io = session.io orelse return; 2065 var random: usize = undefined; 2066 io.random(std.mem.asBytes(&random)); 2067 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2068 } 2069