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