╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const term = xitui.terminal; 6 const wgt = xitui.widget; 7 const layout = xitui.layout; 8 const inp = xitui.input; 9 const Grid = xitui.grid.Grid; 10 const Focus = xitui.focus.Focus; 11 const evt = @import("./event.zig"); 12 13 pub const Home = @import("./ui/Home.zig"); 14 pub const User = @import("./ui/User.zig"); 15 pub const Title = @import("./ui/Title.zig"); 16 17 pub const PageKind = enum { 18 home, 19 user, 20 }; 21 22 pub const Page = union(PageKind) { 23 home: Home, 24 user: User, 25 26 pub fn init(arena: *std.heap.ArenaAllocator, haxy_moment: evt.AdminDB.HashMap(.read_only), route: RoutablePage) !Page { 27 return switch (route.parent()) { 28 .home => .{ .home = try Home.init(arena, haxy_moment) }, 29 .user => switch (route) { 30 .user, .user_settings, .user_auth => |name| .{ .user = try User.init(arena, haxy_moment, name) }, 31 else => return error.UnexpectedRoute, 32 }, 33 }; 34 } 35 }; 36 37 // what the server hands to the client (and what main_wasm parses on _start). 38 // keeps Page free of any per-request session state. 39 pub const Snapshot = struct { 40 page: Page, 41 session: Session.Data = .{}, 42 }; 43 44 // a top-level "page" the user can navigate to. the user_* variants are the 45 // tabs of a user page; they each carry the user's name and all map to the 46 // .user parent page, so switching between them stays on that page (and just 47 // updates the url) rather than navigating away. 48 pub const RoutablePage = union(enum) { 49 home_users, 50 home_repos, 51 home_settings, 52 home_auth, 53 user: []const u8, 54 user_settings: []const u8, 55 user_auth: []const u8, 56 57 pub const default: RoutablePage = .home_users; 58 59 const user_segment = "/user/"; 60 61 pub fn url(comptime self: RoutablePage) []const u8 { 62 return switch (self) { 63 .home_users => "/users", 64 .home_repos => "/repos", 65 .home_settings => "/settings", 66 .home_auth => "/auth", 67 // user routes carry a runtime name; build them with urlAlloc. 68 .user, .user_settings, .user_auth => @compileError("user routes are dynamic; use urlAlloc"), 69 }; 70 } 71 72 pub fn urlAlloc(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 73 return switch (self) { 74 .user => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}", .{name}), 75 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name}), 76 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name}), 77 inline else => |_, tag| url(tag), 78 }; 79 } 80 81 pub fn parent(self: RoutablePage) PageKind { 82 return switch (self) { 83 .home_users, .home_repos, .home_settings, .home_auth => .home, 84 .user, .user_settings, .user_auth => .user, 85 }; 86 } 87 88 pub fn fromUrl(path: []const u8) ?RoutablePage { 89 if (std.mem.eql(u8, path, "/")) return default; 90 if (std.mem.eql(u8, path, "/users")) return .home_users; 91 if (std.mem.eql(u8, path, "/repos")) return .home_repos; 92 if (std.mem.eql(u8, path, "/settings")) return .home_settings; 93 if (std.mem.eql(u8, path, "/auth")) return .home_auth; 94 if (std.mem.startsWith(u8, path, user_segment)) { 95 const rest = path[user_segment.len..]; 96 const slash = std.mem.indexOfScalar(u8, rest, '/'); 97 const name = if (slash) |s| rest[0..s] else rest; 98 if (name.len == 0) return null; 99 if (slash) |s| { 100 const sub = rest[s + 1 ..]; 101 if (std.mem.eql(u8, sub, "settings")) return .{ .user_settings = name }; 102 if (std.mem.eql(u8, sub, "auth")) return .{ .user_auth = name }; 103 return null; // unknown user sub-path 104 } 105 return .{ .user = name }; 106 } 107 return null; 108 } 109 110 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 111 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 112 return switch (a) { 113 .user => |a_name| std.mem.eql(u8, a_name, b.user), 114 .user_settings => |a_name| std.mem.eql(u8, a_name, b.user_settings), 115 .user_auth => |a_name| std.mem.eql(u8, a_name, b.user_auth), 116 else => true, 117 }; 118 } 119 120 // serialize as { "kind": <tag>, "name"?: <user name> }. the default 121 // union(enum) codec doesn't round-trip here: Stringify emits a void 122 // variant as a bare tag string, but the parser expects an object — so the 123 // server->wasm Snapshot JSON would fail to parse. 124 pub fn jsonStringify(self: RoutablePage, jw: anytype) !void { 125 try jw.beginObject(); 126 try jw.objectField("kind"); 127 try jw.write(@tagName(self)); 128 switch (self) { 129 .user, .user_settings, .user_auth => |name| { 130 try jw.objectField("name"); 131 try jw.write(name); 132 }, 133 else => {}, 134 } 135 try jw.endObject(); 136 } 137 138 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !RoutablePage { 139 const Helper = struct { kind: std.meta.Tag(RoutablePage), name: ?[]const u8 = null }; 140 const helper = try std.json.innerParse(Helper, allocator, source, options); 141 return switch (helper.kind) { 142 .home_users => .home_users, 143 .home_repos => .home_repos, 144 .home_settings => .home_settings, 145 .home_auth => .home_auth, 146 .user => .{ .user = helper.name orelse return error.MissingField }, 147 .user_settings => .{ .user_settings = helper.name orelse return error.MissingField }, 148 .user_auth => .{ .user_auth = helper.name orelse return error.MissingField }, 149 }; 150 } 151 }; 152 153 // per-connection mutable state. each SSH session / web session / local TUI 154 // run gets its own. 155 pub const Session = struct { 156 data: Data = .{}, 157 arena: *std.heap.ArenaAllocator, 158 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 159 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 160 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 161 162 const Self = @This(); 163 164 // serializable data sent down to web client 165 pub const Data = struct { 166 user_id: ?[]const u8 = null, 167 // a transient outcome to surface from the last /login POST attempt 168 login_failure: ?Home.Auth.Login.Failure = null, 169 current_page: RoutablePage = .default, 170 // whether to render the ANSI art backdrop 171 enable_ansi: bool = false, 172 }; 173 174 // a user-initiated state change. widgets enqueue these on the session during 175 // input instead of mutating state or touching the DB themselves; the host 176 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 177 // side effects out of the widget tree and gives every render path one place to 178 // turn a UI action into a state change + event. 179 pub const Action = union(enum) { 180 toggle_ansi, 181 }; 182 183 pub fn init( 184 arena: *std.heap.ArenaAllocator, 185 repo: *rp.Repo(.xit, evt.admin_repo_opts), 186 data: Data, 187 ) !Self { 188 var session = Self{ 189 .data = data, 190 .arena = arena, 191 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 192 }; 193 try session.loadUserPrefs(); 194 return session; 195 } 196 197 // load the logged-in user's persisted preferences from the db 198 pub fn loadUserPrefs(self: *Self) !void { 199 const user_id = self.data.user_id orelse return; 200 const moment = self.haxy_moment orelse return; 201 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 202 self.data.enable_ansi = user.enable_ansi; 203 } 204 } 205 206 // queue an action for the host to drain this frame. 207 pub fn push(self: *Self, action: Action) !void { 208 try self.pending.append(self.arena.allocator(), action); 209 } 210 211 // apply a single action's in-memory effect only (no persistence). 212 fn apply(self: *Self, action: Action) void { 213 switch (action) { 214 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 215 } 216 } 217 218 // drain the session's queued actions by applying them to the session. 219 // used on the wasm path, which has no repo to persist to. 220 pub fn applyPending(self: *Self) void { 221 for (self.pending.items) |action| self.apply(action); 222 self.pending.clearRetainingCapacity(); 223 } 224 225 // drain the session's queued actions by applying them to the session and 226 // writing them to the db 227 pub fn applyAndWritePending( 228 self: *Self, 229 io: std.Io, 230 allocator: std.mem.Allocator, 231 repo: *rp.Repo(.xit, evt.admin_repo_opts), 232 ) !void { 233 defer self.pending.clearRetainingCapacity(); 234 for (self.pending.items) |action| { 235 self.apply(action); 236 switch (action) { 237 .toggle_ansi => if (self.data.user_id) |user_id| { 238 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 239 }, 240 } 241 } 242 } 243 244 fn navigate(self: *Session, route: RoutablePage) !void { 245 const aa = self.arena.allocator(); 246 self.data.current_page = switch (route) { 247 .user => |name| .{ .user = try aa.dupe(u8, name) }, 248 .user_settings => |name| .{ .user_settings = try aa.dupe(u8, name) }, 249 .user_auth => |name| .{ .user_auth = try aa.dupe(u8, name) }, 250 else => route, 251 }; 252 } 253 }; 254 255 pub fn run(io: std.Io, allocator: std.mem.Allocator, page: *const Page, session: *Session) !void { 256 var nav = try Nav.init(allocator, page, session); 257 defer nav.deinit(allocator); 258 259 var terminal = try term.Terminal.init(io, allocator); 260 defer terminal.deinit(io); 261 262 var last_size = layout.Size{ .width = 0, .height = 0 }; 263 var last_grid = try Grid.init(allocator, last_size); 264 defer last_grid.deinit(); 265 266 while (!terminal.shouldQuit()) { 267 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 268 269 // process any inputs. 270 // 271 // if the grid didn't change, then first do a blocking 272 // read, so the thread will sleep until further input. 273 // after that, all remaining reads are non-blocking so 274 // we can process the rest of the queued inputs. 275 // 276 // if the grid *did* change, then only do non-blocking 277 // reads. we do not want to sleep the thread because 278 // there may be an animation that requires more looping. 279 var blocking = !grid_changed; 280 while (try terminal.readKey(io, blocking)) |key| { 281 try inputKey(allocator, &nav.root, key, session); 282 blocking = false; 283 } 284 285 // local run has no repo to persist to, so just apply in-memory 286 session.applyPending(); 287 288 // reconcile navigation: forward to a new page, or back on escape (and 289 // quit when there's nothing left to go back to). 290 if (!try nav.sync(allocator, session)) terminal.requestQuit(); 291 292 try nav.root.build(allocator, .{ 293 .min_size = .{ .width = null, .height = null }, 294 .max_size = .{ .width = last_size.width, .height = last_size.height }, 295 }, nav.root.getFocus()); 296 } 297 } 298 299 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: inp.Key, session: *Session) !void { 300 switch (key) { 301 // request a navigation pop; the host's Nav.sync goes back a page, or 302 // quits when there's no history left. 303 .escape => session.nav_back = true, 304 .enter => { 305 const root_focus = root.getFocus(); 306 if (root_focus.grandchild_id) |gid| { 307 // follow a cross-page link 308 if (crossPageLink(root_focus, gid, session.data.current_page)) |route| { 309 return session.navigate(route); 310 } 311 } 312 try root.input(allocator, key, root_focus); 313 }, 314 .mouse => |mouse| { 315 if (mouse.action == .press and mouse.action.press == .left) { 316 const root_focus = root.getFocus(); 317 var clicked: ?usize = null; 318 var iter = root_focus.children.iterator(); 319 while (iter.next()) |entry| { 320 const child = entry.value_ptr.*; 321 if (!child.focus.focusable) continue; 322 const r = child.rect; 323 if (mouse.x >= r.x and mouse.y >= r.y and 324 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 325 { 326 clicked = entry.key_ptr.*; 327 break; 328 } 329 } 330 if (clicked) |focus_id| { 331 // follow a cross-page link 332 if (crossPageLink(root_focus, focus_id, session.data.current_page)) |route| { 333 return session.navigate(route); 334 } 335 try root_focus.setFocus(focus_id); 336 } 337 // forward the press into the widget tree so buttons (and any 338 // future click-aware widgets) can react. widgets that don't 339 // care about presses ignore it. 340 try root.input(allocator, key, root.getFocus()); 341 } else { 342 try root.input(allocator, key, root.getFocus()); 343 } 344 }, 345 else => try root.input(allocator, key, root.getFocus()), 346 } 347 } 348 349 // if the focus target at focus_id is an `a:` link to a different top-level page 350 // than `current`, return its route; otherwise null. lets a host turn a click / 351 // enter on such a link into a navigation rather than a focus change. 352 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, current: RoutablePage) ?RoutablePage { 353 const child = root_focus.children.get(focus_id) orelse return null; 354 const custom = switch (child.focus.kind) { 355 .custom => |c| c, 356 else => return null, 357 }; 358 const a_prefix = "a:"; 359 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 360 const route = RoutablePage.fromUrl(custom[a_prefix.len..]) orelse return null; 361 if (route.parent() == current.parent()) return null; 362 return route; 363 } 364 365 // native-TUI navigation 366 pub const Nav = struct { 367 root: Widget, 368 route: RoutablePage, 369 history: std.ArrayList(Entry), 370 371 const Entry = struct { root: Widget, route: RoutablePage }; 372 373 // cap on retained back-history so chain can't grow memory without bound 374 const max_history: usize = 16; 375 376 pub fn init(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Nav { 377 return .{ 378 .root = try initRoot(allocator, page, session), 379 .route = session.data.current_page, 380 .history = .empty, 381 }; 382 } 383 384 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 385 self.root.deinit(allocator); 386 for (self.history.items) |*entry| entry.root.deinit(allocator); 387 self.history.deinit(allocator); 388 } 389 390 // reconcile the displayed root with the session's navigation state. returns 391 // false when escape was pressed with no history left, so the caller can quit. 392 // a forward nav (current_page moved to a different parent page) pushes the 393 // current root and builds the new page; a back request pops and restores the 394 // previous root. the new Page is allocated in the session arena so the widget 395 // tree's data pointers stay valid for the life of the session. 396 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 397 if (session.nav_back) { 398 session.nav_back = false; 399 const entry = self.history.pop() orelse return false; 400 self.root.deinit(allocator); 401 self.root = entry.root; 402 self.route = entry.route; 403 session.data.current_page = entry.route; 404 return true; 405 } 406 407 if (session.data.current_page.parent() != self.route.parent()) { 408 const moment = session.haxy_moment orelse return true; 409 const page = try session.arena.allocator().create(Page); 410 page.* = try Page.init(session.arena, moment, session.data.current_page); 411 const new_root = try initRoot(allocator, page, session); 412 try self.history.append(allocator, .{ .root = self.root, .route = self.route }); 413 // drop the oldest entry (freeing its widget tree) once we're over cap 414 if (self.history.items.len > max_history) { 415 var oldest = self.history.orderedRemove(0); 416 oldest.root.deinit(allocator); 417 } 418 self.root = new_root; 419 self.route = session.data.current_page; 420 } 421 return true; 422 } 423 }; 424 425 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 426 const page_widget: Widget = switch (page.*) { 427 .home => |*p| .{ .home = try .init(allocator, p, session) }, 428 .user => |*p| .{ .user = try .init(allocator, p, session) }, 429 }; 430 431 const demon_art = @embedFile("embed/demon.ans"); 432 433 var root = Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 434 errdefer root.deinit(allocator); 435 436 try root.build(allocator, .{ 437 .min_size = .{ .width = null, .height = 40 }, 438 .max_size = .{ .width = 80, .height = null }, 439 }, root.getFocus()); 440 if (root.getFocus().child_id) |child_id| { 441 try root.getFocus().setFocus(child_id); 442 } 443 444 return root; 445 } 446 447 pub const Widget = union(enum) { 448 text: wgt.Text(Widget), 449 box: wgt.Box(Widget), 450 text_box: wgt.TextBox(Widget), 451 text_input: wgt.TextInput(Widget), 452 scroll: wgt.Scroll(Widget), 453 stack: wgt.Stack(Widget), 454 flow_box: FlowBox, 455 flow_box_scroll: FlowBox.Scroll, 456 spacer: Spacer, 457 center: Center, 458 ansi_art: AnsiArt, 459 background: AnsiBackground, 460 home: Home.View, 461 user: User.View, 462 title: Title.View, 463 home_header: Home.Header.View, 464 user_header: User.Header.View, 465 home_users: Home.Users.View, 466 home_repos: Home.Repos.View, 467 auth_tab: Home.Header.AuthTab.View, 468 home_settings: Home.Settings.View, 469 home_auth: Home.Auth.View, 470 471 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 472 switch (self.*) { 473 inline else => |*case| case.deinit(allocator), 474 } 475 } 476 477 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 478 switch (self.*) { 479 inline else => |*case| try case.build(allocator, constraint, root_focus), 480 } 481 } 482 483 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 484 switch (self.*) { 485 inline else => |*case| try case.input(allocator, key, root_focus), 486 } 487 } 488 489 pub fn clearGrid(self: *Widget) void { 490 switch (self.*) { 491 inline else => |*case| case.clearGrid(), 492 } 493 } 494 495 pub fn getGrid(self: Widget) ?Grid { 496 switch (self) { 497 inline else => |*case| return case.getGrid(), 498 } 499 } 500 501 pub fn getFocus(self: *Widget) *Focus { 502 switch (self.*) { 503 inline else => |*case| return case.getFocus(), 504 } 505 } 506 }; 507 508 pub const FlowBox = struct { 509 focus: Focus, 510 grid: ?Grid, 511 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 512 // backs the per-item strings the text boxes borrow: each box's `content` 513 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 514 // wholesale on each setItems so there's no per-string ownership to track. 515 arena: std.heap.ArenaAllocator, 516 // column count from the last build — FlowBox.Scroll.input uses it so arrow 517 // up/down can step by a row's worth of items. 518 last_cols: usize, 519 options: Options, 520 521 const border_rows: usize = 2; 522 523 pub const Options = struct { 524 cell_width: usize = 40, 525 cell_height: usize = 3, 526 }; 527 528 pub fn init(allocator: std.mem.Allocator, options: Options) FlowBox { 529 return .{ 530 .focus = Focus.init(.container), 531 .grid = null, 532 .text_boxes = .empty, 533 .arena = std.heap.ArenaAllocator.init(allocator), 534 .last_cols = 1, 535 .options = options, 536 }; 537 } 538 539 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 540 self.focus.deinit(allocator); 541 if (self.grid) |*grid| { 542 grid.deinit(); 543 self.grid = null; 544 } 545 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 546 self.text_boxes.deinit(allocator); 547 self.arena.deinit(); 548 } 549 550 // `links`, when given, is parallel to `items`: a non-empty entry sets that 551 // item's focus kind to `.{ .custom = link }` (e.g. "a:/user/foo"), which the 552 // web renderer turns into an anchor. pass null when items aren't links. 553 // both the item text and the link are copied into the arena, so the caller's 554 // slices needn't outlive this call. 555 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 556 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 557 self.text_boxes.clearAndFree(allocator); 558 559 // the old text boxes (and their borrowed content/links) are gone now, so 560 // the arena that backed those strings can be reclaimed. 561 _ = self.arena.reset(.retain_capacity); 562 const aa = self.arena.allocator(); 563 564 self.focus.clear(); 565 self.focus.child_id = null; 566 567 for (items, 0..) |item, i| { 568 const line = try aa.dupe(u8, item); 569 570 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 571 errdefer text_box.deinit(allocator); 572 text_box.getFocus().focusable = true; 573 574 if (links) |link_items| { 575 if (i < link_items.len and link_items[i].len > 0) { 576 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, link_items[i]) }; 577 } 578 } 579 580 try self.text_boxes.append(allocator, text_box); 581 } 582 583 if (self.text_boxes.items.len > 0) { 584 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 585 } 586 } 587 588 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 589 self.clearGrid(); 590 self.focus.clear(); 591 592 const cell_width = self.options.cell_width; 593 const max_width = constraint.max_size.width orelse cell_width; 594 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 595 self.last_cols = cols; 596 597 const count = self.text_boxes.items.len; 598 if (count == 0) return; 599 const slot_height = self.options.cell_height + border_rows; 600 if (slot_height == 0) return; 601 602 // build at the slot size so every text box fits a single grid cell 603 for (self.text_boxes.items) |*tb| { 604 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 605 try tb.build(allocator, .{ 606 .min_size = .{ .width = cell_width, .height = null }, 607 .max_size = .{ .width = cell_width, .height = slot_height }, 608 }, root_focus); 609 } 610 611 const rows = (count + cols - 1) / cols; 612 const content_height = rows * slot_height; 613 const total_width = cols * cell_width; 614 if (total_width == 0 or content_height == 0) return; 615 616 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 617 errdefer grid.deinit(); 618 619 for (self.text_boxes.items, 0..) |*tb, i| { 620 const tb_grid = tb.getGrid() orelse continue; 621 const col = i % cols; 622 const row = i / cols; 623 const cell_x = col * cell_width; 624 const cell_y = row * slot_height; 625 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 626 try grid.drawGrid(tb_grid, cell_x, cell_y); 627 } 628 629 self.grid = grid; 630 } 631 632 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 633 _ = self; 634 _ = allocator; 635 _ = key; 636 _ = root_focus; 637 } 638 639 pub fn clearGrid(self: *FlowBox) void { 640 if (self.grid) |*grid| { 641 grid.deinit(); 642 self.grid = null; 643 } 644 for (self.text_boxes.items) |*tb| tb.clearGrid(); 645 } 646 647 pub fn getGrid(self: FlowBox) ?Grid { 648 return self.grid; 649 } 650 651 pub fn getFocus(self: *FlowBox) *Focus { 652 return &self.focus; 653 } 654 655 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 656 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 657 const slot_height = self.options.cell_height + border_rows; 658 const col = index % self.last_cols; 659 const row = index / self.last_cols; 660 return .{ 661 .x = @intCast(col * self.options.cell_width), 662 .y = @intCast(row * slot_height), 663 .size = .{ .width = self.options.cell_width, .height = slot_height }, 664 }; 665 } 666 667 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 668 for (self.text_boxes.items, 0..) |tb, i| { 669 if (tb.box.focus.id == focus_id) return i; 670 } 671 return null; 672 } 673 674 pub const Scroll = struct { 675 scroll: wgt.Scroll(Widget), 676 677 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options) !Scroll { 678 var layout_inner = FlowBox.init(allocator, options); 679 errdefer layout_inner.deinit(allocator); 680 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .vert); 681 errdefer scroll.deinit(allocator); 682 return .{ .scroll = scroll }; 683 } 684 685 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 686 self.scroll.deinit(allocator); 687 } 688 689 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 690 self.scroll.x = 0; 691 self.scroll.y = 0; 692 try self.inner().setItems(allocator, items, links); 693 } 694 695 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 696 try self.scroll.build(allocator, constraint, root_focus); 697 } 698 699 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 700 _ = allocator; 701 const in = self.inner(); 702 const child_id = in.focus.child_id orelse return; 703 const current_index = in.indexOfFocusId(child_id) orelse return; 704 const count = in.text_boxes.items.len; 705 if (count == 0) return; 706 const cols = in.last_cols; 707 const slot_height = in.options.cell_height + FlowBox.border_rows; 708 709 var index = current_index; 710 switch (key) { 711 .arrow_up => index -|= cols, 712 .arrow_down => if (index + cols < count) { 713 index += cols; 714 }, 715 .arrow_left => index -|= 1, 716 .arrow_right => if (index + 1 < count) { 717 index += 1; 718 }, 719 .home => index = 0, 720 .end => index = count - 1, 721 .page_up => { 722 if (self.scroll.grid) |grid| if (slot_height > 0) { 723 const rows_per_page = grid.size.height / slot_height; 724 index -|= rows_per_page * cols; 725 }; 726 }, 727 .page_down => { 728 if (self.scroll.grid) |grid| if (slot_height > 0) { 729 const rows_per_page = grid.size.height / slot_height; 730 index = @min(index + rows_per_page * cols, count - 1); 731 }; 732 }, 733 // scroll wheel moves the focused cell by a full row so the 734 // viewport (via scrollToRect) follows in row-sized steps, 735 // matching how a scroll wheel feels in a grid view. 736 .mouse => |mouse| switch (mouse.action) { 737 .scroll => |dir| switch (dir) { 738 .up => index -|= cols, 739 .down => if (index + cols < count) { 740 index += cols; 741 }, 742 }, 743 else => {}, 744 }, 745 else => {}, 746 } 747 748 if (index != current_index) { 749 try root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 750 if (in.cellRect(index)) |rect| { 751 self.scroll.scrollToRect(rect); 752 } 753 } 754 } 755 756 pub fn clearGrid(self: *Scroll) void { 757 self.scroll.clearGrid(); 758 } 759 760 pub fn getGrid(self: Scroll) ?Grid { 761 return self.scroll.getGrid(); 762 } 763 764 pub fn getFocus(self: *Scroll) *Focus { 765 return self.scroll.getFocus(); 766 } 767 768 pub fn getSelectedIndex(self: Scroll) ?usize { 769 const in = self.scroll.child.flow_box; 770 const child_id = in.focus.child_id orelse return null; 771 return in.indexOfFocusId(child_id); 772 } 773 774 fn inner(self: *Scroll) *FlowBox { 775 return &self.scroll.child.flow_box; 776 } 777 }; 778 }; 779 780 // an invisible widget that fills the horizontal space granted by its parent. 781 // used inside Box(horiz) with a min_size so the box reserves space for the 782 // children that follow, pushing them to the right. 783 pub const Spacer = struct { 784 focus: Focus, 785 grid: ?Grid, 786 787 pub fn init() Spacer { 788 return .{ 789 .focus = Focus.init(.container), 790 .grid = null, 791 }; 792 } 793 794 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 795 self.focus.deinit(allocator); 796 if (self.grid) |*grid| { 797 grid.deinit(); 798 self.grid = null; 799 } 800 } 801 802 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 803 _ = root_focus; 804 self.clearGrid(); 805 const width = constraint.max_size.width orelse return; 806 if (width == 0) return; 807 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 808 } 809 810 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 811 _ = self; 812 _ = allocator; 813 _ = key; 814 _ = root_focus; 815 } 816 817 pub fn clearGrid(self: *Spacer) void { 818 if (self.grid) |*grid| { 819 grid.deinit(); 820 self.grid = null; 821 } 822 } 823 824 pub fn getGrid(self: Spacer) ?Grid { 825 return self.grid; 826 } 827 828 pub fn getFocus(self: *Spacer) *Focus { 829 return &self.focus; 830 } 831 }; 832 833 // a single-child wrapper that builds the child at its natural size and 834 // positions its grid in the middle of the area granted by the parent 835 pub const Center = struct { 836 focus: Focus, 837 grid: ?Grid, 838 child: *Widget, 839 direction: Direction, 840 841 pub const Direction = enum { both, horiz, vert }; 842 843 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, direction: Direction) !Center { 844 const child = try allocator.create(Widget); 845 errdefer allocator.destroy(child); 846 child.* = child_widget; 847 return .{ 848 .focus = Focus.init(.container), 849 .grid = null, 850 .child = child, 851 .direction = direction, 852 }; 853 } 854 855 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 856 self.focus.deinit(allocator); 857 if (self.grid) |*grid| { 858 grid.deinit(); 859 self.grid = null; 860 } 861 self.child.deinit(allocator); 862 allocator.destroy(self.child); 863 } 864 865 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 866 self.clearGrid(); 867 self.getFocus().clear(); 868 869 // build the child without forcing it to fill min_size; it sizes 870 // itself to its content within the available max. 871 try self.child.build(allocator, .{ 872 .min_size = .{ .width = null, .height = null }, 873 .max_size = constraint.max_size, 874 }, root_focus); 875 876 const child_grid = self.child.getGrid() orelse return; 877 878 // prefer max when given; otherwise grow to max(min, child) so that 879 // when only a min is set (e.g. the wasm path passes viewport rows 880 // as min_height with no max), we can still vertically center while 881 // letting taller content extend past the min. 882 const width = if (constraint.max_size.width) |w| w else if (constraint.min_size.width) |min_w| @max(min_w, child_grid.size.width) else child_grid.size.width; 883 const height = if (constraint.max_size.height) |h| h else if (constraint.min_size.height) |min_h| @max(min_h, child_grid.size.height) else child_grid.size.height; 884 if (width == 0 or height == 0) return; 885 886 const offset_x: usize = if (self.direction == .horiz or self.direction == .both) 887 (width -| child_grid.size.width) / 2 888 else 889 0; 890 const offset_y: usize = if (self.direction == .vert or self.direction == .both) 891 (height -| child_grid.size.height) / 2 892 else 893 0; 894 895 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 896 errdefer grid.deinit(); 897 try grid.drawGrid(child_grid, offset_x, offset_y); 898 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 899 self.getFocus().child_id = self.child.getFocus().id; 900 901 self.grid = grid; 902 } 903 904 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 905 try self.child.input(allocator, key, root_focus); 906 } 907 908 pub fn clearGrid(self: *Center) void { 909 if (self.grid) |*grid| { 910 grid.deinit(); 911 self.grid = null; 912 } 913 self.child.clearGrid(); 914 } 915 916 pub fn getGrid(self: Center) ?Grid { 917 return self.grid; 918 } 919 920 pub fn getFocus(self: *Center) *Focus { 921 return &self.focus; 922 } 923 }; 924 925 // renders truecolor ANSI art 926 pub const AnsiArt = struct { 927 focus: Focus, 928 grid: ?Grid, 929 content: []const u8, 930 931 pub fn init(content: []const u8) AnsiArt { 932 return .{ 933 .focus = Focus.init(.container), 934 .grid = null, 935 .content = content, 936 }; 937 } 938 939 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 940 self.focus.deinit(allocator); 941 if (self.grid) |*grid| { 942 grid.deinit(); 943 self.grid = null; 944 } 945 } 946 947 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 948 _ = root_focus; 949 self.clearGrid(); 950 951 // parse into rows of cells, then copy into a rectangular grid 952 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 953 defer { 954 for (rows.items) |*row| row.deinit(allocator); 955 rows.deinit(allocator); 956 } 957 var row: std.ArrayList(Grid.Cell) = .empty; 958 errdefer row.deinit(allocator); 959 960 var style: Grid.Style = .{}; 961 var width: usize = 0; 962 const content = self.content; 963 var i: usize = 0; 964 while (i < content.len) { 965 const byte = content[i]; 966 if (byte == '\n') { 967 width = @max(width, row.items.len); 968 try rows.append(allocator, row); 969 row = .empty; 970 i += 1; 971 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 972 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 973 var j = i + 2; 974 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 975 if (j >= content.len) { 976 i = content.len; // malformed trailing escape; stop 977 } else { 978 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 979 i = j + 1; 980 } 981 } else { 982 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 983 const end = @min(content.len, i + len); 984 const rune = content[i..end]; 985 const transparent = end - i == 1 and rune[0] == ' ' and 986 style.fg == null and style.bg == null and !style.inverted; 987 try row.append(allocator, .{ 988 .rune = if (transparent) null else rune, 989 .style = style, 990 }); 991 i = end; 992 } 993 } 994 // a trailing row with content but no closing newline 995 if (row.items.len > 0) { 996 width = @max(width, row.items.len); 997 try rows.append(allocator, row); 998 } else { 999 row.deinit(allocator); 1000 } 1001 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1002 1003 const height = rows.items.len; 1004 if (width == 0 or height == 0) return; 1005 1006 const clamped_w = @min(width, constraint.max_size.width orelse width); 1007 const clamped_h = @min(height, constraint.max_size.height orelse height); 1008 1009 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1010 errdefer grid.deinit(); 1011 for (rows.items[0..clamped_h], 0..) |r, y| { 1012 const n = @min(r.items.len, clamped_w); 1013 for (r.items[0..n], 0..) |cell, x| { 1014 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1015 } 1016 } 1017 self.grid = grid; 1018 } 1019 1020 pub fn input(self: *AnsiArt, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1021 _ = self; 1022 _ = allocator; 1023 _ = key; 1024 _ = root_focus; 1025 } 1026 1027 pub fn clearGrid(self: *AnsiArt) void { 1028 if (self.grid) |*grid| { 1029 grid.deinit(); 1030 self.grid = null; 1031 } 1032 } 1033 1034 pub fn getGrid(self: AnsiArt) ?Grid { 1035 return self.grid; 1036 } 1037 1038 pub fn getFocus(self: *AnsiArt) *Focus { 1039 return &self.focus; 1040 } 1041 1042 fn applySgr(style: *Grid.Style, params: []const u8) void { 1043 var nums: [16]u32 = undefined; 1044 var n: usize = 0; 1045 var it = std.mem.splitScalar(u8, params, ';'); 1046 while (it.next()) |tok| { 1047 if (n >= nums.len) break; 1048 // an empty parameter (e.g. bare "\x1b[m") means 0 1049 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1050 n += 1; 1051 } 1052 if (n == 0) { 1053 style.* = .{}; 1054 return; 1055 } 1056 var i: usize = 0; 1057 while (i < n) : (i += 1) { 1058 switch (nums[i]) { 1059 0 => style.* = .{}, 1060 7 => style.inverted = true, 1061 27 => style.inverted = false, 1062 39 => style.fg = null, 1063 49 => style.bg = null, 1064 38, 48 => { 1065 // truecolor form: 38;2;r;g;b — anything else is ignored 1066 if (i + 4 < n and nums[i + 1] == 2) { 1067 const c = Grid.Color{ 1068 .r = @truncate(nums[i + 2]), 1069 .g = @truncate(nums[i + 3]), 1070 .b = @truncate(nums[i + 4]), 1071 }; 1072 if (nums[i] == 38) style.fg = c else style.bg = c; 1073 i += 4; 1074 } 1075 }, 1076 else => {}, 1077 } 1078 } 1079 } 1080 }; 1081 1082 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1083 pub const AnsiBackground = struct { 1084 grid: ?Grid, 1085 child: *Widget, 1086 art: AnsiArt, 1087 session: *Session, 1088 1089 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1090 var cw = child_widget; 1091 const child = allocator.create(Widget) catch |e| { 1092 cw.deinit(allocator); 1093 return e; 1094 }; 1095 child.* = cw; 1096 return .{ .grid = null, .child = child, .art = AnsiArt.init(art_content), .session = session }; 1097 } 1098 1099 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1100 if (self.grid) |*grid| grid.deinit(); 1101 self.art.deinit(allocator); 1102 self.child.deinit(allocator); 1103 allocator.destroy(self.child); 1104 } 1105 1106 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1107 self.clearGrid(); 1108 1109 // make the wrapped page fill the whole available area 1110 try self.child.build(allocator, .{ 1111 .min_size = .{ 1112 .width = constraint.max_size.width orelse constraint.min_size.width, 1113 .height = constraint.max_size.height orelse constraint.min_size.height, 1114 }, 1115 .max_size = constraint.max_size, 1116 }, root_focus); 1117 1118 if (self.session.data.enable_ansi) { 1119 if (self.child.getGrid()) |fg| { 1120 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1121 } 1122 } 1123 } 1124 1125 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1126 try self.child.input(allocator, key, root_focus); 1127 } 1128 1129 pub fn clearGrid(self: *AnsiBackground) void { 1130 if (self.grid) |*grid| { 1131 grid.deinit(); 1132 self.grid = null; 1133 } 1134 self.child.clearGrid(); 1135 self.art.clearGrid(); 1136 } 1137 1138 pub fn getGrid(self: AnsiBackground) ?Grid { 1139 return self.grid orelse self.child.getGrid(); 1140 } 1141 1142 pub fn getFocus(self: *AnsiBackground) *Focus { 1143 return self.child.getFocus(); 1144 } 1145 1146 // which top corner the art hugs. 1147 const ArtAnchor = enum { top_left, top_right }; 1148 1149 // a foreground cell counts as blank if it's empty or a bare space without styling 1150 fn cellIsBlank(cell: Grid.Cell) bool { 1151 if (cell.rune) |rune| { 1152 return std.mem.eql(u8, rune, " ") and 1153 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1154 } 1155 return true; 1156 } 1157 1158 // a single representative color for an art cell 1159 fn artCellColor(style: Grid.Style) ?Grid.Color { 1160 const f = style.fg orelse return style.bg; 1161 const b = style.bg orelse return f; 1162 return .{ 1163 .r = @intCast((@as(u16, f.r) + b.r) / 2), 1164 .g = @intCast((@as(u16, f.g) + b.g) / 2), 1165 .b = @intCast((@as(u16, f.b) + b.b) / 2), 1166 }; 1167 } 1168 1169 // behind a visible glyph the art color is dimmed to this fraction of its 1170 // brightness so light terminal text stays legible on top of it 1171 const glyph_bg_brightness = 45; // percent 1172 1173 // a glyph sitting over the art also gets its foreground pinned to this color 1174 // (unless it set its own), so the text stays legible 1175 const glyph_fg_over_art = Grid.Color{ .r = 235, .g = 235, .b = 235 }; 1176 1177 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1178 const c = color orelse return null; 1179 return .{ 1180 .r = @intCast(@as(u16, c.r) * glyph_bg_brightness / 100), 1181 .g = @intCast(@as(u16, c.g) * glyph_bg_brightness / 100), 1182 .b = @intCast(@as(u16, c.b) * glyph_bg_brightness / 100), 1183 }; 1184 } 1185 1186 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1187 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1188 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1189 // snap such channels clear of that range so the backdrop doesn't blink or 1190 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1191 // actually render truecolor. 1192 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1193 const c = color orelse return null; 1194 const snap = struct { 1195 fn f(v: u8) u8 { 1196 return if (v >= 1 and v <= 9) 10 else v; 1197 } 1198 }.f; 1199 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1200 } 1201 1202 // composites ANSI art behind a foreground grid 1203 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1204 art.clearGrid(); 1205 try art.build(allocator, .{ 1206 .min_size = .{ .width = null, .height = null }, 1207 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1208 }, root_focus); 1209 1210 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1211 errdefer out.deinit(); 1212 1213 if (art.getGrid()) |art_grid| { 1214 const anchor_x = switch (anchor) { 1215 .top_left => 0, 1216 .top_right => foreground.size.width -| art_grid.size.width, 1217 }; 1218 for (0..art_grid.size.height) |y| { 1219 for (0..art_grid.size.width) |x| { 1220 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1221 if (src.rune == null) continue; 1222 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1223 const dst = &out.cells.items[idx]; 1224 if (cellIsBlank(dst.*)) { 1225 dst.* = src; 1226 dst.style.fg = sgrSafe(dst.style.fg); 1227 dst.style.bg = sgrSafe(dst.style.bg); 1228 } else if (dst.style.bg == null) { 1229 dst.style.bg = sgrSafe(dimColor(artCellColor(src.style))); 1230 if (dst.style.fg == null) dst.style.fg = glyph_fg_over_art; 1231 } 1232 } 1233 } 1234 } 1235 return out; 1236 } 1237 }; 1238