╭ 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 inp = @import("../input.zig"); 6 const xit = @import("xit"); 7 const rp = xit.repo; 8 const hash = xit.hash; 9 const wgt = xit.xitui.widget; 10 const layout = xit.xitui.layout; 11 const Key = xit.xitui.input.Key; 12 const Grid = xit.xitui.grid.Grid; 13 const Focus = xit.xitui.focus.Focus; 14 const Self = @This(); 15 16 pub const page_size = 20; 17 18 // replaces the description for a transaction that wrote events 19 pub const EventsLink = struct { 20 label: []const u8, 21 link: []const u8, 22 }; 23 24 pub const Item = struct { 25 index: u64, 26 action: []const u8, 27 description: []const u8, 28 timestamp: []const u8, 29 link: []const u8, 30 form: []const u8, 31 events: ?EventsLink = null, 32 }; 33 34 identity: []const u8, 35 count: u64 = 0, 36 items: []const Item = &.{}, 37 next: ?u64 = null, 38 failure: ?[]const u8 = null, 39 can_undo: bool = false, 40 41 pub fn init(comptime opts: rp.RepoOpts(.xit), arena: *std.heap.ArenaAllocator, repo: *rp.Repo(.xit, opts), identity: []const u8, selected: ?u64) !Self { 42 const aa = arena.allocator(); 43 const DB = rp.Repo(.xit, opts).DB; 44 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 45 const count = try history.count(); 46 if (selected) |index| if (index >= count) return error.NotFound; 47 var items: std.ArrayList(Item) = .empty; 48 var remaining = if (selected) |index| index + 1 else count; 49 var buffer: [opts.max_read_size]u8 = undefined; 50 while (remaining > 0 and items.items.len < page_size) { 51 remaining -= 1; 52 const cursor = try history.getCursor(remaining) orelse return error.TransactionNotFound; 53 const moment = try DB.HashMap(.read_only).init(cursor); 54 const record = try xit.undo.read(opts, moment, &buffer); 55 var description: std.Io.Writer.Allocating = .init(aa); 56 const detail = if (record) |value| try eventDetail(opts, arena, identity, value, moment) else null; 57 if (detail) |value| { 58 try description.writer.writeAll(value.description); 59 } else if (record) |value| { 60 try xit.undo.format(opts, &repo.core.db, arena.child_allocator, value, &description.writer); 61 } else { 62 try description.writer.writeAll("no undo record"); 63 } 64 const route = ui.RoutablePage.repoUndoRoute(identity, remaining) orelse return error.RouteTooLong; 65 const url = try route.toUrl(arena); 66 try items.append(aa, .{ 67 .index = remaining, 68 .action = if (detail) |value| value.action else if (record) |value| try aa.dupe(u8, value.action) else "unknown", 69 .description = description.written(), 70 .events = if (detail) |value| value.events else null, 71 .timestamp = if (record) |value| try formatTimestamp(aa, value.timestamp) else "timestamp unavailable", 72 .link = try std.fmt.allocPrint(aa, "ai:{s}", .{url}), 73 .form = try std.fmt.allocPrint(aa, "form:{s}/undo", .{url}), 74 }); 75 } 76 return .{ .identity = try aa.dupe(u8, identity), .count = count, .items = items.items, .next = if (remaining > 0) remaining - 1 else null }; 77 } 78 79 const Detail = struct { 80 action: []const u8, 81 description: []const u8, 82 events: ?EventsLink = null, 83 }; 84 85 // every haxy event transaction shares one action, and the events it wrote are 86 // named by the moment's index rather than by the record 87 fn eventDetail( 88 comptime opts: rp.RepoOpts(.xit), 89 arena: *std.heap.ArenaAllocator, 90 identity: []const u8, 91 record: xit.undo.UndoRecord, 92 moment: rp.Repo(.xit, opts).DB.HashMap(.read_only), 93 ) !?Detail { 94 if (std.mem.eql(u8, record.action, evt.merge_undo_action)) return .{ .action = "merge events", .description = "merged the events ref from a remote" }; 95 if (!std.mem.eql(u8, record.action, evt.undo_action)) return null; 96 97 const description = "updated the event database"; 98 const batch = try momentBatch(opts, moment) orelse return .{ .action = "events", .description = description }; 99 100 const aa = arena.allocator(); 101 const route = ui.RoutablePage.repoEventsRoute(identity, .active, null, "", batch.index) orelse return error.RouteTooLong; 102 return .{ 103 .action = try std.fmt.allocPrint(aa, "events ({d})", .{batch.count}), 104 .description = description, 105 .events = .{ 106 .label = try std.fmt.allocPrint(aa, "view events ({d})", .{batch.count}), 107 .link = try std.fmt.allocPrint(aa, "a:{s}", .{try route.toUrl(arena)}), 108 }, 109 }; 110 } 111 112 const Batch = struct { index: u64, count: u64 }; 113 114 // the events the transaction's moment wrote, or null when it wrote none 115 fn momentBatch(comptime opts: rp.RepoOpts(.xit), moment: rp.Repo(.xit, opts).DB.HashMap(.read_only)) !?Batch { 116 const DB = rp.Repo(.xit, opts).DB; 117 const haxy_moment = evt.currentMomentFromRepoMoment(opts.hash, moment) catch return null; 118 const index_cursor = try haxy_moment.getCursor(hash.hashInt(opts.hash, evt.moment_index_key)) orelse return null; 119 const moment_index = try index_cursor.readUint(); 120 const ids = try evt.momentEventIds(DB, opts.hash, haxy_moment, moment_index) orelse return null; 121 return .{ .index = moment_index, .count = try ids.count() }; 122 } 123 124 pub fn formatTimestamp(aa: std.mem.Allocator, timestamp: i64) ![]const u8 { 125 if (timestamp < 0) return aa.dupe(u8, "timestamp unavailable"); 126 const seconds = std.time.epoch.EpochSeconds{ .secs = @intCast(timestamp) }; 127 const year = seconds.getEpochDay().calculateYearDay(); 128 const month = year.calculateMonthDay(); 129 const day = seconds.getDaySeconds(); 130 const months = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 131 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() }); 132 } 133 134 pub fn execute(io: std.Io, allocator: std.mem.Allocator, source: ui.RepoSource, index: u64) !void { 135 if (source.repo_kind != .xit) return error.NotFound; 136 var any_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, source.localInitOpts()); 137 defer any_repo.deinit(io, allocator); 138 switch (any_repo) { 139 inline else => |*repo| try repo.undo(io, index), 140 } 141 } 142 143 // keep action failures on the current tab without rebuilding a stale route. 144 pub fn handleRequest(allocator: std.mem.Allocator, session: *ui.Session, target: ui.RoutablePage.RepoUndoRoute) void { 145 perform(allocator, session, target) catch |err| { 146 session.data.undo_failure = @errorName(err); 147 return; 148 }; 149 session.data.undo_failure = null; 150 } 151 152 // both terminal hosts resolve and authorize the request afresh before opening 153 // the repository; the web handler uses its matching http authorization path. 154 pub fn perform(allocator: std.mem.Allocator, session: *ui.Session, target: ui.RoutablePage.RepoUndoRoute) !void { 155 const index = target.index orelse return error.InvalidHistoryIndex; 156 const identity = target.name.slice(); 157 if (try session.authorize(identity, .owner) == null) return error.Forbidden; 158 const io = session.io orelse return error.NotFound; 159 const source = session.local orelse blk: { 160 const admin_repo = session.admin_repo orelse return error.NotFound; 161 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 162 const pair = ui.RoutablePage.RepoIdentity.parse(identity) orelse return error.NotFound; 163 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; 164 const hex = std.fmt.bytesToHex(found.event_id, .lower); 165 break :blk ui.RepoSource{ .path = try std.fs.path.join(session.page_arena.allocator(), &.{ session.repos_dir orelse return error.NotFound, &hex }), .repo_kind = .xit }; 166 }; 167 try execute(io, allocator, source, index); 168 try session.navigate(ui.RoutablePage.repoUndoRoute(identity, null) orelse return error.RouteTooLong); 169 } 170 171 pub const View = struct { 172 box: wgt.Box(ui.Widget), 173 data: *const Self, 174 session: *ui.Session, 175 detailed_index: ?usize = null, 176 failure_id: ?usize = null, 177 shown_failure: ?[]const u8 = null, 178 179 const list_max_width = 20; 180 const detail_min_width = 40; 181 182 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 183 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 184 errdefer box.deinit(allocator); 185 { 186 var scroll = blk: { 187 var rows = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert, .stretch = true }); 188 errdefer rows.deinit(allocator); 189 for (data.items) |item| try addText(allocator, &rows, item.action, item.link, .hidden); 190 if (data.next) |next| { 191 const route = ui.RoutablePage.repoUndoRoute(data.identity, next) orelse return error.RouteTooLong; 192 try addText(allocator, &rows, "next →", try std.fmt.allocPrint(session.page_arena.allocator(), "a:{s}", .{try route.toUrl(session.page_arena)}), .hidden); 193 } 194 if (data.items.len == 0) try addText(allocator, &rows, "no undo history", null, .hidden); 195 if (rows.children.count() > 0) rows.getFocus().child_id = rows.children.keys()[0]; 196 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = rows }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 197 }; 198 errdefer scroll.deinit(allocator); 199 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 } }); 200 } 201 { 202 var scroll = blk: { 203 var details = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 204 errdefer details.deinit(allocator); 205 if (data.items.len > 0) { 206 try addText(allocator, &details, "", null, .single); 207 try addText(allocator, &details, "", null, .single); 208 details.children.values()[1].widget.text_box.options.label = " timestamp "; 209 try addText(allocator, &details, "", null, .single); 210 details.children.values()[2].widget.text_box.options.label = " description "; 211 details.getFocus().child_id = details.children.keys()[0]; 212 } 213 break :blk try wgt.Scroll(ui.Widget).init(allocator, .{ .box = details }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 214 }; 215 errdefer scroll.deinit(allocator); 216 scroll.getFocus().mode = .mouse; 217 try box.children.put(allocator, scroll.getFocus().id, .{ .widget = .{ .scroll = scroll }, .rect = null, .min_size = .{ .width = detail_min_width, .height = null } }); 218 } 219 box.getFocus().child_id = box.children.keys()[0]; 220 return .{ .box = box, .data = data, .session = session }; 221 } 222 223 fn addText(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), text: []const u8, link: ?[]const u8, border: wgt.BorderStyle) !void { 224 var row = try wgt.TextBox.init(allocator, text, .{ .border_style = border, .rounded_corners = true, .wrap_kind = .word }); 225 errdefer row.deinit(allocator); 226 row.getFocus().mode = .all; 227 if (link) |value| row.getFocus().kind = .{ .custom = value }; 228 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null }); 229 } 230 231 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 232 return &self.box.children.values()[0].widget.scroll; 233 } 234 fn detailScroll(self: *View) *wgt.Scroll(ui.Widget) { 235 return &self.box.children.values()[1].widget.scroll; 236 } 237 fn selected(self: *View) ?usize { 238 const rows = &self.listScroll().child.box; 239 const index = rows.children.getIndex(rows.getFocus().child_id orelse return null) orelse return null; 240 return if (index < self.data.items.len) index else null; 241 } 242 fn detailActive(self: *View) bool { 243 return self.box.getFocus().child_id == self.detailScroll().getFocus().id; 244 } 245 246 fn refreshDetail(self: *View, allocator: std.mem.Allocator) !void { 247 const index = self.selected() orelse return; 248 const failure = self.session.data.undo_failure orelse self.data.failure; 249 if (self.detailed_index == index and std.meta.eql(self.shown_failure, failure)) return; 250 const details = &self.detailScroll().child.box; 251 if (self.failure_id) |id| { 252 if (details.children.getPtr(id)) |child| child.widget.deinit(allocator); 253 _ = details.children.orderedRemove(id); 254 self.failure_id = null; 255 } 256 const item = self.data.items[index]; 257 const button = &details.children.values()[0].widget.text_box; 258 const description = &details.children.values()[2].widget.text_box; 259 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"); 260 // a transaction that wrote events links to them instead of describing itself 261 if (item.events) |events| { 262 try description.setContent(allocator, events.label); 263 description.options.label = " events "; 264 description.getFocus().kind = .{ .custom = events.link }; 265 } else { 266 try description.setContent(allocator, item.description); 267 description.options.label = " description "; 268 description.getFocus().kind = .text_box; 269 } 270 const enabled = self.data.can_undo and item.index > 0; 271 button.getFocus().kind = if (enabled) .{ .custom = "submit" } else .text_box; 272 try details.children.values()[1].widget.text_box.setContent(allocator, item.timestamp); 273 if (failure) |message| { 274 try addText(allocator, details, try std.fmt.allocPrint(self.session.page_arena.allocator(), "error: {s}", .{message}), null, .single); 275 self.failure_id = details.children.keys()[details.children.count() - 1]; 276 } 277 self.shown_failure = failure; 278 details.getFocus().kind = if (enabled) .{ .custom = item.form } else .container; 279 details.getFocus().child_id = details.children.keys()[0]; 280 self.detailScroll().x = 0; 281 self.detailScroll().y = 0; 282 self.detailScroll().getFocus().version +%= 1; 283 self.detailed_index = index; 284 } 285 286 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 287 self.clearGrid(); 288 try self.refreshDetail(allocator); 289 const rows = &self.listScroll().child.box; 290 if (self.data.items.len == 0) { 291 const failure = self.session.data.undo_failure orelse self.data.failure; 292 if (!std.meta.eql(self.shown_failure, failure)) { 293 const message = if (failure) |name| try std.fmt.allocPrint(self.session.page_arena.allocator(), "error: {s}", .{name}) else "no undo history"; 294 try rows.children.values()[0].widget.text_box.setContent(allocator, message); 295 self.shown_failure = failure; 296 } 297 } 298 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; 299 const both_fit = if (constraint.max_size.width) |width| width >= list_max_width + detail_min_width else true; 300 self.box.children.values()[0].max_size = if (both_fit) .{ .width = list_max_width, .height = null } else null; 301 const width = if (constraint.max_size.width) |value| if (both_fit) value - list_max_width else value else detail_min_width; 302 self.box.children.values()[1].min_size = .{ .width = width, .height = null }; 303 for (self.detailScroll().child.box.children.values()) |*child| child.max_size = .{ .width = width -| 2, .height = null }; 304 try self.box.build(allocator, constraint, root_focus); 305 } 306 307 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 308 try self.refreshDetail(allocator); 309 if (self.detailActive()) { 310 const details = &self.detailScroll().child.box; 311 if (self.selected()) |index| { 312 const button_id = details.children.keys()[0]; 313 const activated = switch (key) { 314 .enter => root_focus.grandchild_id == button_id, 315 .mouse => |mouse| inp.leftClickOn(root_focus, button_id, mouse), 316 else => false, 317 }; 318 if (activated and self.data.can_undo and self.data.items[index].index > 0) { 319 if (builtin.target.cpu.arch != .wasm32 and self.session.is_terminal and self.session.host_request == null) { 320 const route = ui.RoutablePage.repoUndoRoute(self.data.identity, self.data.items[index].index) orelse return error.RouteTooLong; 321 self.session.host_request = .{ .undo = route.repo_undo }; 322 } 323 return; 324 } 325 } 326 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); 327 } else if (inp.rowDelta(key, @intCast(self.listScroll().child.box.children.count()))) |delta| { 328 ui.widget.moveRowFocus(&self.listScroll().child.box, self.listScroll(), root_focus, delta); 329 } else switch (key) { 330 .arrow_right, .enter => if (self.selected() != null) { 331 root_focus.setFocus(self.detailScroll().getFocus().id); 332 }, 333 else => {}, 334 } 335 } 336 337 pub fn atTop(self: *View) bool { 338 const scroll = if (self.detailActive()) self.detailScroll() else self.listScroll(); 339 const rows = &scroll.child.box; 340 const id = rows.getFocus().child_id orelse return true; 341 return rows.children.getIndex(id) == 0 and scroll.y == 0; 342 } 343 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 344 self.box.deinit(allocator); 345 } 346 pub fn clearGrid(self: *View) void { 347 self.box.clearGrid(); 348 } 349 pub fn getGrid(self: View) ?Grid { 350 return self.box.getGrid(); 351 } 352 pub fn getFocus(self: *View) *Focus { 353 return self.box.getFocus(); 354 } 355 }; 356