╭ Undo.zig ─────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const ui = @import("../../ui.zig"); 4 const evt = @import("../../event.zig"); 5 const pch = @import("../../patch.zig"); 6 const push = @import("../../push.zig"); 7 const fork = @import("../../fork.zig"); 8 const inp = @import("../input.zig"); 9 const xit = @import("xit"); 10 const rp = xit.repo; 11 const hash = xit.hash; 12 const wgt = xit.xitui.widget; 13 const layout = xit.xitui.layout; 14 const Key = xit.xitui.input.Key; 15 const Grid = xit.xitui.grid.Grid; 16 const Focus = xit.xitui.focus.Focus; 17 const Self = @This(); 18 19 pub const page_size = 20; 20 21 // stands in for the description, as a focusable box that may link somewhere 22 pub const DetailButton = struct { 23 label: []const u8, 24 text: []const u8, 25 link: ?[]const u8 = null, 26 }; 27 28 pub const Item = struct { 29 index: u64, 30 action: []const u8, 31 description: []const u8, 32 timestamp: []const u8, 33 link: []const u8, 34 form: []const u8, 35 buttons: []const DetailButton = &.{}, 36 }; 37 38 identity: []const u8, 39 count: u64 = 0, 40 items: []const Item = &.{}, 41 next: ?u64 = null, 42 failure: ?[]const u8 = null, 43 can_undo: bool = false, 44 // the clear-history confirmation stands in for the list 45 clear: bool = false, 46 47 pub fn init(comptime opts: rp.RepoOpts(.xit), arena: *std.heap.ArenaAllocator, repo: *rp.Repo(.xit, opts), haxy_moment: ?evt.AdminDB.HashMap(.read_only), identity: []const u8, selected: ?u64) !Self { 48 const aa = arena.allocator(); 49 const DB = rp.Repo(.xit, opts).DB; 50 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 51 const count = try history.count(); 52 if (selected) |index| if (index >= count) return error.NotFound; 53 var items: std.ArrayList(Item) = .empty; 54 var remaining = if (selected) |index| index + 1 else count; 55 var buffer: [opts.max_read_size]u8 = undefined; 56 while (remaining > 0 and items.items.len < page_size) { 57 remaining -= 1; 58 const cursor = try history.getCursor(remaining) orelse return error.TransactionNotFound; 59 const moment = try DB.HashMap(.read_only).init(cursor); 60 const record = try xit.undo.read(opts, moment, &buffer); 61 var description: std.Io.Writer.Allocating = .init(aa); 62 const detail = if (record) |value| try eventDetail(opts, arena, haxy_moment, identity, value, moment, remaining) else null; 63 if (detail) |value| { 64 try description.writer.writeAll(value.description); 65 } else if (record) |value| { 66 try xit.undo.format(opts, &repo.core.db, arena.child_allocator, value, &description.writer); 67 } else { 68 try description.writer.writeAll("no undo record"); 69 } 70 const route = ui.RoutablePage.repoUndoRoute(identity, remaining) orelse return error.RouteTooLong; 71 const url = try route.toUrl(arena); 72 try items.append(aa, .{ 73 .index = remaining, 74 .action = if (detail) |value| value.action else if (record) |value| try aa.dupe(u8, value.action) else "unknown", 75 .description = description.written(), 76 .buttons = if (detail) |value| value.buttons else &.{}, 77 .timestamp = if (record) |value| try formatTimestamp(aa, value.timestamp) else "timestamp unavailable", 78 .link = try std.fmt.allocPrint(aa, "ai:{s}", .{url}), 79 .form = try std.fmt.allocPrint(aa, "form:{s}/undo", .{url}), 80 }); 81 } 82 return .{ .identity = try aa.dupe(u8, identity), .count = count, .items = items.items, .next = if (remaining > 0) remaining - 1 else null }; 83 } 84 85 const Detail = struct { 86 action: []const u8, 87 description: []const u8, 88 buttons: []const DetailButton = &.{}, 89 }; 90 91 // every haxy event transaction shares one action, and the events it wrote are 92 // named by the moment's index rather than by the record 93 fn eventDetail( 94 comptime opts: rp.RepoOpts(.xit), 95 arena: *std.heap.ArenaAllocator, 96 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 97 identity: []const u8, 98 record: xit.undo.UndoRecord, 99 moment: rp.Repo(.xit, opts).DB.HashMap(.read_only), 100 history_index: u64, 101 ) !?Detail { 102 const aa = arena.allocator(); 103 if (std.mem.eql(u8, record.action, evt.merge_undo_action)) return .{ .action = "merge events", .description = "merged the events ref from a remote" }; 104 if (std.mem.eql(u8, record.action, pch.merge_undo_action)) return .{ .action = "merge patch", .description = "merged a patch into its target branch" }; 105 if (std.mem.eql(u8, record.action, fork.undo_action)) return .{ .action = "fork", .description = "created a fork to draft a patch in" }; 106 if (std.mem.eql(u8, record.action, push.undo_action)) { 107 // a push consumes the events it carried in its own transaction 108 var buttons: std.ArrayList(DetailButton) = .empty; 109 if (try pushUser(arena, haxy_moment, record.payload)) |button| try buttons.append(aa, button); 110 const count = try momentEventCount(opts, moment) orelse 0; 111 if (count > 0) try buttons.append(aa, try eventsButton(arena, identity, history_index, count)); 112 return .{ .action = "push", .description = "received a push", .buttons = buttons.items }; 113 } 114 if (!std.mem.eql(u8, record.action, evt.undo_action)) return null; 115 116 const count = try momentEventCount(opts, moment) orelse return .{ .action = "events", .description = "updated the event database" }; 117 // a transaction that consumed only merge commits indexed no events of its own 118 if (count == 0) return .{ .action = "events", .description = "merged the event history" }; 119 const buttons = try aa.dupe(DetailButton, &.{try eventsButton(arena, identity, history_index, count)}); 120 return .{ 121 .action = try std.fmt.allocPrint(aa, "events ({d})", .{count}), 122 .description = "updated the event database", 123 .buttons = buttons, 124 }; 125 } 126 127 // the page reads the transaction's own moment, so the url names the 128 // transaction rather than the state it produced 129 fn eventsButton(arena: *std.heap.ArenaAllocator, identity: []const u8, history_index: u64, count: u64) !DetailButton { 130 const aa = arena.allocator(); 131 const route = ui.RoutablePage.repoEventsRoute(identity, .active, null, "", history_index) orelse return error.RouteTooLong; 132 return .{ 133 .label = " events ", 134 .text = try std.fmt.allocPrint(aa, "view events ({d})", .{count}), 135 .link = try std.fmt.allocPrint(aa, "a:{s}", .{try route.toUrl(arena)}), 136 }; 137 } 138 139 // the push record stores the email of the user whose key the server accepted. 140 // resolving it names them as they are now, and leaves the email when no user 141 // holds it, which is also what local mode sees with no admin db to read 142 fn pushUser(arena: *std.heap.ArenaAllocator, haxy_moment: ?evt.AdminDB.HashMap(.read_only), payload: []const u8) !?DetailButton { 143 const Payload = struct { author: ?struct { email: []const u8 } = null }; 144 const parsed = std.json.parseFromSlice(Payload, arena.child_allocator, payload, .{ .ignore_unknown_fields = true }) catch |err| switch (err) { 145 error.OutOfMemory => return err, 146 else => return null, 147 }; 148 defer parsed.deinit(); 149 const author = parsed.value.author orelse return null; 150 return switch (try ui.Author.initFromEmail(haxy_moment, arena, author.email)) { 151 .unknown => null, 152 .email => |email| .{ .label = " user ", .text = email }, 153 .user_name => |name| .{ .label = " user ", .text = name, .link = try ui.userLink(arena, name) }, 154 }; 155 } 156 157 // how many events the transaction's moment wrote: zero when it named a moment 158 // but indexed nothing, null when its state cannot be read at all 159 fn momentEventCount(comptime opts: rp.RepoOpts(.xit), moment: rp.Repo(.xit, opts).DB.HashMap(.read_only)) !?u64 { 160 const DB = rp.Repo(.xit, opts).DB; 161 const haxy_moment = evt.currentMomentFromRepoMoment(opts.hash, moment) catch return null; 162 const index_cursor = try haxy_moment.getCursor(hash.hashInt(opts.hash, evt.moment_index_key)) orelse return null; 163 const ids = try evt.momentEventIds(DB, opts.hash, haxy_moment, try index_cursor.readUint()) orelse return 0; 164 return try ids.count(); 165 } 166 167 pub fn formatTimestamp(aa: std.mem.Allocator, timestamp: i64) ![]const u8 { 168 if (timestamp < 0) return aa.dupe(u8, "timestamp unavailable"); 169 const seconds = std.time.epoch.EpochSeconds{ .secs = @intCast(timestamp) }; 170 const year = seconds.getEpochDay().calculateYearDay(); 171 const month = year.calculateMonthDay(); 172 const day = seconds.getDaySeconds(); 173 const months = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 174 return std.fmt.allocPrint(aa, "{s} {d}, {d}, {d:0>2}:{d:0>2}:{d:0>2} UTC", .{ months[month.month.numeric() - 1], month.day_index + 1, year.year, day.getHoursIntoDay(), day.getMinutesIntoHour(), day.getSecondsIntoMinute() }); 175 } 176 177 pub fn execute(io: std.Io, allocator: std.mem.Allocator, source: ui.RepoSource, index: u64) !void { 178 if (source.repo_kind != .xit) return error.NotFound; 179 var any_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, source.localInitOpts()); 180 defer any_repo.deinit(io, allocator); 181 switch (any_repo) { 182 inline else => |*repo| try repo.undo(io, index), 183 } 184 } 185 186 // discard every earlier transaction by compacting the database. the patch 187 // revisions events point at are unreachable from the refs, so they are named 188 // as extra roots to survive the collection. 189 pub fn clearHistory(io: std.Io, allocator: std.mem.Allocator, source: ui.RepoSource) !void { 190 if (source.repo_kind != .xit) return error.NotFound; 191 var any_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, source.localInitOpts()); 192 defer any_repo.deinit(io, allocator); 193 switch (any_repo) { 194 inline else => |*repo| { 195 const opts = repo.self_repo_opts; 196 // a repo that has consumed no events has no revisions to protect 197 const roots = if (evt.currentMoment(opts, repo)) |moment| 198 try evt.PatchRev.gcRoots(rp.Repo(.xit, opts).DB, opts.hash, allocator, moment) 199 else |_| 200 &.{}; 201 defer allocator.free(roots); 202 _ = try repo.garbageCollect(io, allocator, .{ .extra_roots = roots }); 203 }, 204 } 205 } 206 207 // keep action failures on the current tab without rebuilding a stale route. 208 pub fn handleRequest(allocator: std.mem.Allocator, session: *ui.Session, target: ui.RoutablePage.RepoUndoRoute) void { 209 perform(allocator, session, target) catch |err| { 210 session.data.undo_failure = @errorName(err); 211 return; 212 }; 213 session.data.undo_failure = null; 214 } 215 216 // both terminal hosts resolve and authorize the request afresh before opening 217 // the repository; the web handler uses its matching http authorization path. 218 pub fn perform(allocator: std.mem.Allocator, session: *ui.Session, target: ui.RoutablePage.RepoUndoRoute) !void { 219 const identity = target.name.slice(); 220 const index = if (target.clear) null else target.index orelse return error.InvalidHistoryIndex; 221 const source = try authorizedSource(session, identity) orelse return error.Forbidden; 222 const io = session.io orelse return error.NotFound; 223 if (index) |value| try execute(io, allocator, source, value) else try clearHistory(io, allocator, source); 224 try session.navigate(ui.RoutablePage.repoUndoRoute(identity, null) orelse return error.RouteTooLong); 225 } 226 227 // the repo an owner may act on, or null when they may not 228 fn authorizedSource(session: *ui.Session, identity: []const u8) !?ui.RepoSource { 229 if (try session.authorize(identity, .owner) == null) return null; 230 if (session.local) |local| return local; 231 const admin_repo = session.admin_repo orelse return error.NotFound; 232 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 233 const pair = ui.RoutablePage.RepoIdentity.parse(identity) orelse return error.NotFound; 234 const found = try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, session.page_arena, pair.owner, pair.name) orelse return error.NotFound; 235 const hex = std.fmt.bytesToHex(found.event_id, .lower); 236 return .{ .path = try std.fs.path.join(session.page_arena.allocator(), &.{ session.repos_dir orelse return error.NotFound, &hex }), .repo_kind = .xit }; 237 } 238 239 pub const View = struct { 240 box: wgt.Box(ui.Widget), 241 data: *const Self, 242 session: *ui.Session, 243 detailed_index: ?usize = null, 244 shown_failure: ?[]const u8 = null, 245 246 const list_max_width = 20; 247 const detail_min_width = 40; 248 const header_index = 0; 249 const content_index = 1; 250 // the undo button and the timestamp; everything below them is rebuilt 251 const fixed_rows = 2; 252 253 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 254 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 255 errdefer outer.deinit(allocator); 256 257 // the sub header carries the tab's only action 258 { 259 var header = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 260 errdefer header.deinit(allocator); 261 const route = ui.RoutablePage.repoUndoClearRoute(data.identity) orelse return error.RouteTooLong; 262 const link = try std.fmt.allocPrint(session.page_arena.allocator(), "a:{s}", .{try route.toUrl(session.page_arena)}); 263 try addText(allocator, &header, "clear undo history", link, .single); 264 header.getFocus().child_id = header.children.keys()[0]; 265 try outer.children.put(allocator, header.getFocus().id, .{ .widget = .{ .box = header }, .rect = null, .min_size = .{ .width = null, .height = 3 } }); 266 } 267 268 if (data.clear) { 269 var center = try initClearForm(allocator, data, session); 270 errdefer center.deinit(allocator); 271 try outer.children.put(allocator, center.getFocus().id, .{ .widget = .{ .center = center }, .rect = null, .min_size = null }); 272 outer.getFocus().child_id = outer.children.keys()[content_index]; 273 return .{ .box = outer, .data = data, .session = session }; 274 } 275 276 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 277 errdefer box.deinit(allocator); 278 { 279 var scroll = blk: { 280 var rows = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert, .stretch = true }); 281 errdefer rows.deinit(allocator); 282 for (data.items) |item| try addText(allocator, &rows, item.action, item.link, .hidden); 283 if (data.next) |next| { 284 const route = ui.RoutablePage.repoUndoRoute(data.identity, next) orelse return error.RouteTooLong; 285 try addText(allocator, &rows, "next →", try std.fmt.allocPrint(session.page_arena.allocator(), "a:{s}", .{try route.toUrl(session.page_arena)}), .hidden); 286 } 287 if (data.items.len == 0) try addText(allocator, &rows, "no undo history", null, .hidden); 288 rows.getFocus().child_id = rows.children.keys()[0]; 289 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = rows }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 290 }; 291 errdefer scroll.deinit(allocator); 292 try box.children.put(allocator, scroll.getFocus().id, .{ .widget = .{ .scroll = scroll }, .rect = null, .min_size = .{ .width = list_max_width, .height = null }, .max_size = .{ .width = list_max_width, .height = null } }); 293 } 294 { 295 var scroll = blk: { 296 var details = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 297 errdefer details.deinit(allocator); 298 if (data.items.len > 0) { 299 try addText(allocator, &details, "", null, .single); 300 try addLabeled(allocator, &details, " timestamp ", "", null); 301 details.getFocus().child_id = details.children.keys()[0]; 302 } 303 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = details }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 304 }; 305 errdefer scroll.deinit(allocator); 306 scroll.getFocus().mode = .mouse; 307 try box.children.put(allocator, scroll.getFocus().id, .{ .widget = .{ .scroll = scroll }, .rect = null, .min_size = .{ .width = detail_min_width, .height = null } }); 308 } 309 box.getFocus().child_id = box.children.keys()[0]; 310 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 311 outer.getFocus().child_id = outer.children.keys()[content_index]; 312 return .{ .box = outer, .data = data, .session = session }; 313 } 314 315 // the same shape the thread views use to confirm a removal 316 fn initClearForm(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !ui.widget.Center { 317 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .rounded_corners = true, .direction = .vert }); 318 errdefer box.deinit(allocator); 319 const route = ui.RoutablePage.repoUndoClearRoute(data.identity) orelse return error.RouteTooLong; 320 box.getFocus().kind = .{ .custom = try std.fmt.allocPrint(session.page_arena.allocator(), "form:{s}", .{try route.toUrl(session.page_arena)}) }; 321 322 var prompt = try wgt.Text.init(allocator, "are you sure?"); 323 errdefer prompt.deinit(allocator); 324 try box.children.put(allocator, prompt.getFocus().id, .{ .widget = .{ .text = prompt }, .rect = null, .min_size = null }); 325 326 var button = try wgt.TextBox.init(allocator, "clear undo history", .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 327 errdefer button.deinit(allocator); 328 button.getFocus().mode = .all; 329 button.getFocus().kind = if (data.can_undo) .{ .custom = "submit" } else .text_box; 330 try box.children.put(allocator, button.getFocus().id, .{ .widget = .{ .text_box = button }, .rect = null, .min_size = null }); 331 box.getFocus().child_id = button.getFocus().id; 332 333 return ui.widget.Center.init(allocator, .{ .box = box }); 334 } 335 336 fn addText(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), text: []const u8, link: ?[]const u8, border: wgt.BorderStyle) !void { 337 var row = try wgt.TextBox.init(allocator, text, .{ .border_style = border, .rounded_corners = true, .wrap_kind = .word }); 338 errdefer row.deinit(allocator); 339 row.getFocus().mode = .all; 340 if (link) |value| row.getFocus().kind = .{ .custom = value }; 341 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null }); 342 } 343 344 // a labeled row below the timestamp, added as the selected action needs it 345 fn addLabeled(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, text: []const u8, link: ?[]const u8) !void { 346 try addText(allocator, box, text, link, .single); 347 box.children.values()[box.children.count() - 1].widget.text_box.options.label = label; 348 } 349 350 // enter counts only on the focused button; a click counts anywhere on it 351 fn activated(root_focus: *Focus, button_id: usize, key: Key) bool { 352 return switch (key) { 353 .enter => root_focus.grandchild_id == button_id, 354 .mouse => |mouse| inp.leftClickOn(root_focus, button_id, mouse), 355 else => false, 356 }; 357 } 358 359 // the terminal hosts run the action after rendering; the web renderer 360 // posts the form instead, and wasm has no repository to act on 361 fn requestUndo(self: *View, route: ui.RoutablePage) void { 362 if (builtin.target.cpu.arch == .wasm32) return; 363 if (!self.session.is_terminal or self.session.host_request != null) return; 364 self.session.host_request = .{ .undo = route.repo_undo }; 365 } 366 367 fn headerBox(self: *View) *wgt.Box(ui.Widget) { 368 return &self.box.children.values()[header_index].widget.box; 369 } 370 fn headerActive(self: *View) bool { 371 return self.box.getFocus().child_id == self.headerBox().getFocus().id; 372 } 373 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 374 return &self.box.children.values()[content_index].widget.box; 375 } 376 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 377 return &self.contentBox().children.values()[0].widget.scroll; 378 } 379 fn detailScroll(self: *View) *wgt.Scroll(ui.Widget) { 380 return &self.contentBox().children.values()[1].widget.scroll; 381 } 382 fn selected(self: *View) ?usize { 383 const rows = &self.listScroll().child.box; 384 const index = rows.children.getIndex(rows.getFocus().child_id orelse return null) orelse return null; 385 return if (index < self.data.items.len) index else null; 386 } 387 fn detailActive(self: *View) bool { 388 return self.contentBox().getFocus().child_id == self.detailScroll().getFocus().id; 389 } 390 391 fn refreshDetail(self: *View, allocator: std.mem.Allocator) !void { 392 const index = self.selected() orelse return; 393 const failure = self.session.data.undo_failure orelse self.data.failure; 394 if (self.detailed_index == index and std.meta.eql(self.shown_failure, failure)) return; 395 const details = &self.detailScroll().child.box; 396 while (details.children.count() > fixed_rows) { 397 var entry = details.children.pop() orelse break; 398 entry.value.widget.deinit(allocator); 399 } 400 const item = self.data.items[index]; 401 const enabled = self.data.can_undo and item.index > 0; 402 403 // the fixed rows are filled first, since adding the ones below 404 // invalidates every pointer into the box 405 { 406 const button = &details.children.values()[0].widget.text_box; 407 try button.setContent(allocator, if (item.index == 0) "initial state cannot be undone" else if (item.index == self.data.count - 1) "undo this" else "undo this and all above it"); 408 button.getFocus().kind = if (enabled) .{ .custom = "submit" } else .text_box; 409 } 410 try details.children.values()[1].widget.text_box.setContent(allocator, item.timestamp); 411 412 // some actions put buttons where the description would go 413 if (item.buttons.len == 0) { 414 try addLabeled(allocator, details, " description ", item.description, null); 415 } else for (item.buttons) |detail_button| { 416 try addLabeled(allocator, details, detail_button.label, detail_button.text, detail_button.link); 417 } 418 if (failure) |message| try addText(allocator, details, try std.fmt.allocPrint(self.session.page_arena.allocator(), "error: {s}", .{message}), null, .single); 419 self.shown_failure = failure; 420 details.getFocus().kind = if (enabled) .{ .custom = item.form } else .container; 421 details.getFocus().child_id = details.children.keys()[0]; 422 self.detailScroll().x = 0; 423 self.detailScroll().y = 0; 424 self.detailScroll().getFocus().version +%= 1; 425 self.detailed_index = index; 426 } 427 428 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 429 self.clearGrid(); 430 if (self.data.clear) return try self.box.build(allocator, constraint, root_focus); 431 try self.refreshDetail(allocator); 432 const rows = &self.listScroll().child.box; 433 if (self.data.items.len == 0) { 434 const failure = self.session.data.undo_failure orelse self.data.failure; 435 if (!std.meta.eql(self.shown_failure, failure)) { 436 const message = if (failure) |name| try std.fmt.allocPrint(self.session.page_arena.allocator(), "error: {s}", .{name}) else "no undo history"; 437 try rows.children.values()[0].widget.text_box.setContent(allocator, message); 438 self.shown_failure = failure; 439 } 440 } 441 for (rows.children.keys(), rows.children.values()) |id, *child| child.widget.text_box.options.border_style = if (rows.getFocus().child_id == id) .single else .hidden; 442 const both_fit = if (constraint.max_size.width) |width| width >= list_max_width + detail_min_width else true; 443 self.contentBox().children.values()[0].max_size = if (both_fit) .{ .width = list_max_width, .height = null } else null; 444 const width = if (constraint.max_size.width) |value| if (both_fit) value - list_max_width else value else detail_min_width; 445 self.contentBox().children.values()[1].min_size = .{ .width = width, .height = null }; 446 for (self.detailScroll().child.box.children.values()) |*child| child.max_size = .{ .width = width -| 2, .height = null }; 447 try self.box.build(allocator, constraint, root_focus); 448 } 449 450 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 451 // the sub header sits above whichever content the route selects. 452 // scrolling crosses the boundary the same way the arrow keys do 453 const direction = inp.vertDirection(key); 454 if (self.headerActive()) { 455 if (direction == .down) root_focus.setFocus(self.box.children.values()[content_index].widget.getFocus().id); 456 return; 457 } 458 if (self.data.clear) { 459 if (direction == .up) root_focus.setFocus(self.headerBox().getFocus().id) else try self.clearInput(key, root_focus); 460 return; 461 } 462 if (direction == .up and self.contentAtTop()) { 463 root_focus.setFocus(self.headerBox().getFocus().id); 464 return; 465 } 466 try self.refreshDetail(allocator); 467 if (self.detailActive()) { 468 const details = &self.detailScroll().child.box; 469 if (self.selected()) |index| { 470 if (activated(root_focus, details.children.keys()[0], key) and self.data.can_undo and self.data.items[index].index > 0) { 471 self.requestUndo(ui.RoutablePage.repoUndoRoute(self.data.identity, self.data.items[index].index) orelse return error.RouteTooLong); 472 return; 473 } 474 } 475 if (key == .arrow_left) root_focus.setFocus(self.listScroll().getFocus().id) else if (inp.rowDelta(key, @intCast(details.children.count()))) |delta| ui.widget.moveRowFocus(details, self.detailScroll(), root_focus, delta); 476 } else if (inp.rowDelta(key, @intCast(self.listScroll().child.box.children.count()))) |delta| { 477 ui.widget.moveRowFocus(&self.listScroll().child.box, self.listScroll(), root_focus, delta); 478 } else switch (key) { 479 .arrow_right, .enter => if (self.selected() != null) { 480 root_focus.setFocus(self.detailScroll().getFocus().id); 481 }, 482 else => {}, 483 } 484 } 485 486 // the confirm button submits the form the web renderer posts 487 fn clearInput(self: *View, key: Key, root_focus: *Focus) !void { 488 const center = &self.box.children.values()[content_index].widget.center; 489 const button_id = center.child.box.getFocus().child_id orelse return; 490 if (!activated(root_focus, button_id, key) or !self.data.can_undo) return; 491 self.requestUndo(ui.RoutablePage.repoUndoClearRoute(self.data.identity) orelse return error.RouteTooLong); 492 } 493 494 fn contentAtTop(self: *View) bool { 495 const scroll = if (self.detailActive()) self.detailScroll() else self.listScroll(); 496 const rows = &scroll.child.box; 497 const id = rows.getFocus().child_id orelse return true; 498 return rows.children.getIndex(id) == 0 and scroll.y == 0; 499 } 500 501 // moving up from the sub header returns to the page's tabs 502 pub fn atTop(self: *View) bool { 503 return self.headerActive(); 504 } 505 506 // arriving from the page's tabs lands on the sub header, not the content 507 pub fn focusHeader(self: *View, root_focus: *Focus) bool { 508 root_focus.setFocus(self.headerBox().getFocus().id); 509 return true; 510 } 511 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 512 self.box.deinit(allocator); 513 } 514 pub fn clearGrid(self: *View) void { 515 self.box.clearGrid(); 516 } 517 pub fn getGrid(self: View) ?Grid { 518 return self.box.getGrid(); 519 } 520 pub fn getFocus(self: *View) *Focus { 521 return self.box.getFocus(); 522 } 523 }; 524