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