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