feat(undo): multi-level structural undo/redo for rig edits

Add UndoCoordinator: 50-deep undo/redo of structural edits (add/insert/
remove/move pedals in any lane, stereo-split/parallel/merge/unzip routing,
add/remove/move boards, Clear Board). Each edit records a named checkpoint
via a perform(label:) wrapper threaded through the builder, board-flow,
board-bar, and boards-sheet views (injected through the SwiftUI environment,
re-injected onto the boards sheet).

Restore is surgical, not a whole-rig reload: it reconciles board-by-board
(remove added / re-add removed / rebuild changed / reorder) using the same
per-board rebuild path as an ordinary edit, so undo never tears the rig down
— recording, looper buffers, other boards' reverb/delay tails, and
bypass/solo state all survive. It also merges live parameter values by pedal
id, so undoing a topology edit never reverts a knob turned afterwards; a
pedal the edit removed returns with its snapshot values. No-op edits record
nothing (compared via hasSameRigContent). History clears on rig load / new /
switch.

UI: macOS Edit menu (Undo ⌘Z / Redo ⇧⌘Z with dynamic "Undo <action>" titles,
deferring to a text field's own editor while typing); iOS visible ↶/↷ buttons
+ ⌘Z/⇧⌘Z. Rig mute moves from ⌘Z to ⌘M. Help text updated.

Fix: every pedal edit rebuilt the board via BoardState(label:segments:)
without id:, regenerating the board UUID and breaking MIDI board bindings
after any edit. Thread id: board.id through all 10 rebuild sites; add
editingPreservesBoardIdentity regression test.

Tests: 12 UndoCoordinator tests (restore correctness, param preservation,
untouched-board identity, multi-board re-add, depth cap, no-op, throwing
action). Full suite 830 green; both demo schemes build (macOS + iPad).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 10:22:51 -08:00
parent 4c09825c2e
commit a8bd0242a3
14 changed files with 924 additions and 69 deletions
@@ -79,6 +79,9 @@ public struct BoardBarView: View {
private let onAddBoard: () -> Void
private let onClearBoards: (() -> Void)?
/// Undo coordinator injected by the host; `nil` outside the builder (edits run directly).
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
@State private var mode: PlayMode = .solo
// MARK: - Init
@@ -248,7 +251,11 @@ public struct BoardBarView: View {
}
Divider()
Button("Delete Board", role: .destructive) {
shoeGaze.removeBoard(board)
if let undo: UndoCoordinator = undo {
undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
} else {
shoeGaze.removeBoard(board)
}
clampEditingIndex()
}
}
+23 -9
View File
@@ -63,6 +63,10 @@ public struct BoardFlowView: View {
private let shoeGaze: ShoeGaze
private let boardIndex: Int
/// Undo coordinator injected by ``ShoeGazeBuilderView``; `nil` in lightweight hosts (previews),
/// where edits run directly without recording history.
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
/// Identifier of the lane/card currently hovered as a drop target, for highlight.
@State private var dropTarget: String?
@@ -293,12 +297,12 @@ public struct BoardFlowView: View {
do {
if split {
guard !shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return }
_ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board)
try editing("Split L/R") { _ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board) }
} else {
// Only remove the next segment if it is in fact this pedal's unzip region —
// it may have been removed via the region's own trash button.
guard shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return }
_ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board)
try editing("Merge L/R") { _ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board) }
}
} catch {
print("[BoardFlowView] split toggle failed: \(error)")
@@ -507,7 +511,7 @@ public struct BoardFlowView: View {
sourceIndex = index
}
do {
_ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board)
try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board) }
return true
} catch {
print("[BoardFlowView] cross-lane move failed: \(error)")
@@ -522,15 +526,25 @@ public struct BoardFlowView: View {
return shoeGaze.boards[boardIndex]
}
/// Runs a structural edit through the undo coordinator (recording a checkpoint when it changes
/// the rig), or directly when no coordinator is present.
@discardableResult
private func editing<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
if let undo: UndoCoordinator = undo {
return try undo.perform(label, action)
}
return try action()
}
private func append(type: String, lane: PedalLane) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) }
do { try editing("Add \(type)") { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) } }
catch { print("[BoardFlowView] appendPedal failed: \(error)") }
}
private func insert(type: String, at index: Int, lane: PedalLane) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) }
do { try editing("Add \(type)") { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) } }
catch { print("[BoardFlowView] insertPedal failed: \(error)") }
}
@@ -539,20 +553,20 @@ public struct BoardFlowView: View {
// Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`:
// a forward move lands after the target (target + 1); a backward move lands before it.
let destination: Int = source < target ? target + 1 : target
do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) }
do { try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } }
catch { print("[BoardFlowView] movePedal(main) failed: \(error)") }
}
private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) {
guard source != target, let board: PedalBoard = board else { return }
let destination: Int = source < target ? target + 1 : target
do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) }
do { try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } }
catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") }
}
private func removePedal(at index: Int, lane: PedalLane) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) }
do { try editing("Remove Pedal") { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } }
catch { print("[BoardFlowView] removePedal failed: \(error)") }
}
@@ -563,7 +577,7 @@ public struct BoardFlowView: View {
private func removeSegment(at segmentIndex: Int) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) }
do { try editing("Remove Section") { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } }
catch { print("[BoardFlowView] removeSegment failed: \(error)") }
}
}
@@ -48,6 +48,9 @@ public struct BoardsSheetView: View {
private let onAddBoard: () -> Void
@Environment(\.dismiss) private var dismiss
/// Undo coordinator; re-injected onto this sheet by the builder so board moves/removals here
/// record history. `nil` outside the builder (edits run directly).
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
@State private var mode: PlayMode = .solo
// MARK: - Init
@@ -219,13 +222,24 @@ public struct BoardsSheetView: View {
// SwiftUI's destination is the insertion point in the pre-move list; moveBoard
// removes first, so shift down by one when moving forward.
let target: Int = destination > sourceIndex ? destination - 1 : destination
shoeGaze.moveBoard(board, to: target)
if let undo: UndoCoordinator = undo {
undo.perform("Move Board") { shoeGaze.moveBoard(board, to: target) }
} else {
shoeGaze.moveBoard(board, to: target)
}
clampEditingIndex()
}
private func deleteBoards(_ offsets: IndexSet) {
for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count {
shoeGaze.removeBoard(shoeGaze.boards[index])
let remove: () -> Void = {
for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count {
shoeGaze.removeBoard(shoeGaze.boards[index])
}
}
if let undo: UndoCoordinator = undo {
undo.perform("Remove Board", remove)
} else {
remove()
}
clampEditingIndex()
}
+8 -6
View File
@@ -54,13 +54,15 @@ public struct HelpView: View {
"⌘1–⌘9 switch to (and solo) boards 1–9 — the fastest way to change board live.",
"⌘⇧1–⌘⇧9 and ⌘⇧0 load set-list rigs 1–10 in the order shown in the Rigs list — "
+ "build a set list by reordering rigs, then step through them hands-free.",
"⌘Z mutes and unmutes the whole rig — a hard silence of all output (distinct "
+ "from Bypass Rig, which passes your dry signal through).",
"⌘Z undoes the last board edit and ⇧⌘Z redoes it — add / remove / move a pedal, "
+ "board, or routing split. ⌘M mutes and unmutes the whole rig (a hard "
+ "silence of all output, distinct from Bypass Rig, which passes your dry "
+ "signal through).",
"On macOS the menu bar adds: ⌘N New Rig, ⌘S Save Rig, ⌘E Export Archive, "
+ "⌘I Import Archive, ⌘B Add Board, ⇧⌘R Start / Stop Recording, ⌘? Help, and "
+ "Rigs ▸ Set List (the ⌘⇧ rig slots).",
"The board and set-list shortcuts and ⌘Z also work on iOS / iPadOS with a "
+ "hardware keyboard attached.",
+ "⌘I Import Archive, Edit ▸ Undo / Redo (⌘Z / ⇧⌘Z), ⌘B Add Board, "
+ "⇧⌘R Start / Stop Recording, ⌘? Help, and Rigs ▸ Set List (the ⌘⇧ rig slots).",
"The board and set-list shortcuts, plus ⌘Z / ⇧⌘Z (undo / redo) and ⌘M (mute), "
+ "also work on iOS / iPadOS with a hardware keyboard attached.",
]
)
topicSection(
@@ -89,6 +89,11 @@ public struct ShoeGazeBuilderView: View {
/// engine already exposes an input channel, where live input is selected directly.
private let onEnableLiveInput: (() -> Void)?
/// Multi-level undo / redo for structural edits (add / remove / move pedals, boards, routing).
/// Supplied by the host app so the same instance also backs the macOS Edit-menu items. `nil` in
/// lightweight hosts (previews): edits then run directly, without recording history.
private let undo: UndoCoordinator?
/// Index of the board currently being edited.
@State private var selectedBoardIndex: Int = 0
@@ -229,13 +234,15 @@ public struct ShoeGazeBuilderView: View {
library: RigLibraryStore,
hardwareSampleRate: @escaping () -> Double? = { nil },
onEnableLiveInput: (() -> Void)? = nil,
midi: MIDIController? = nil
midi: MIDIController? = nil,
undo: UndoCoordinator? = nil
) {
self.shoeGaze = shoeGaze
self.library = library
self.hardwareSampleRate = hardwareSampleRate
self.onEnableLiveInput = onEnableLiveInput
self.midi = midi
self.undo = undo
}
// MARK: - Body
@@ -716,6 +723,9 @@ public struct ShoeGazeBuilderView: View {
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// Make the undo coordinator reachable to every board / palette subview so their structural
// edits record history. Optional-object injection: `nil` resolves `@Environment(...)` to nil.
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip.
// Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
@@ -818,6 +828,8 @@ public struct ShoeGazeBuilderView: View {
private var compactRigControlsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
undoButton
redoButton
rigBypassButton
rigMuteButton
inputMuteButton
@@ -829,6 +841,35 @@ public struct ShoeGazeBuilderView: View {
}
}
/// Undo of the last structural edit. Shown on iOS (where there is no Edit menu); disabled when
/// the undo stack is empty. macOS drives undo from the Edit menu (⌘Z) instead.
private var undoButton: some View {
Button {
undo?.undo()
} label: {
Image(systemName: "arrow.uturn.backward")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
.disabled(!(undo?.canUndo ?? false))
.help("Undo the last edit")
}
/// Redo of the last undone structural edit. iOS counterpart to the Edit-menu ⇧⌘Z.
private var redoButton: some View {
Button {
undo?.redo()
} label: {
Image(systemName: "arrow.uturn.forward")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
.disabled(!(undo?.canRedo ?? false))
.help("Redo the last undone edit")
}
/// The composition-panel row: buttons that open the Rigs / Pedals / Settings sheets.
private var compactPanelRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
@@ -1057,6 +1098,8 @@ public struct ShoeGazeBuilderView: View {
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
// Sheet content gets a fresh environment, so re-inject the coordinator here.
.environment(undo)
.presentationDetents([.medium, .large])
}
}
@@ -1357,9 +1400,9 @@ public struct ShoeGazeBuilderView: View {
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do {
switch action {
case .stereoSplit: _ = try shoeGaze.appendStereoSplit(to: board)
case .parallelSplit: _ = try shoeGaze.appendParallelSplit(to: board)
case .mergeToMono: _ = try shoeGaze.appendMergeToMono(to: board)
case .stereoSplit: try editing("Add Stereo Split") { _ = try shoeGaze.appendStereoSplit(to: board) }
case .parallelSplit: try editing("Add Parallel Split") { _ = try shoeGaze.appendParallelSplit(to: board) }
case .mergeToMono: try editing("Add Merge to Mono") { _ = try shoeGaze.appendMergeToMono(to: board) }
case .chainRouter: break // multi-board routing; not handled in the single-board builder
}
} catch {
@@ -1401,11 +1444,22 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Actions
/// Runs a structural edit through the undo coordinator (recording a checkpoint when it changes
/// the rig), or directly when no coordinator is present. Keep the closure to the mutation itself
/// so the before/after snapshots bracket exactly the edit.
@discardableResult
private func editing<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
if let undo: UndoCoordinator = undo {
return try undo.perform(label, action)
}
return try action()
}
private func addPedal(type: String) {
guard !shoeGaze.boards.isEmpty else { return }
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do {
_ = try shoeGaze.appendPedal(PedalType(type), to: board)
try editing("Add \(type)") { try shoeGaze.appendPedal(PedalType(type), to: board) }
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
@@ -1416,9 +1470,11 @@ public struct ShoeGazeBuilderView: View {
private func addBoard() {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.finalizeBoard(board)
try editing("Add Board") {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.finalizeBoard(board)
}
selectedBoardIndex = shoeGaze.boards.count - 1
autosave()
} catch {
@@ -1444,21 +1500,25 @@ public struct ShoeGazeBuilderView: View {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
// re-resolve onto the fresh board's pedals.
shoeGaze.midiMap = nil
// Recorded as one undoable checkpoint: undo restores the whole pre-clear rig (boards +
// MIDI bindings). The snapshot is captured at the top of this block, before the mutations.
editing("Clear Board") {
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
// re-resolve onto the fresh board's pedals.
shoeGaze.midiMap = nil
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
}
}
selectedBoardIndex = 0
@@ -1525,8 +1585,8 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Board-switch shortcuts
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
/// edit target, plus ⌘M to toggle the rig mute. Kept at zero opacity so the shortcuts stay
/// active without showing chrome.
/// edit target, plus ⌘Z / ⇧⌘Z (undo / redo), ⌘M (rig mute), and ⌘⇧1…⌘⇧0 (set-list rigs) on
/// iOS/iPadOS. Kept at zero opacity so the shortcuts stay active without showing chrome.
private var boardSwitchShortcuts: some View {
ZStack {
ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in
@@ -1535,11 +1595,18 @@ public struct ShoeGazeBuilderView: View {
Button("Switch to Board \(index + 1)") { switchToBoard(index) }
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
}
// ⌘Z toggles rig mute on iOS/iPadOS hardware keyboards. On macOS the Board menu item
// owns the ⌘Z equivalent, so it is not also bound here (a double-bound event is ambiguous).
// ⌘Z / ⇧⌘Z are Undo / Redo on iOS/iPadOS hardware keyboards; rig mute moves to ⌘M so the
// standard undo chord is free. On macOS the Edit / Board menus own these equivalents, so
// they are not also bound here (a double-bound event is ambiguous).
#if !os(macOS)
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
Button("Undo") { undo?.undo() }
.keyboardShortcut("z", modifiers: .command)
.disabled(!(undo?.canUndo ?? false))
Button("Redo") { undo?.redo() }
.keyboardShortcut("z", modifiers: [.command, .shift])
.disabled(!(undo?.canRedo ?? false))
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
.keyboardShortcut("m", modifiers: .command)
// ⌘⇧1…⌘⇧9 + ⌘⇧0 load set-list rigs 1…10. macOS binds these via the Rigs ▸ Set List menu
// instead, so they are not also bound here.
ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in
@@ -1646,6 +1713,10 @@ public struct ShoeGazeBuilderView: View {
} catch {
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
}
// Switching to a different rig is not an undoable edit — discard the previous rig's history
// so an undo can't restore a different document's topology. Unconditional: `loadRig` tears
// the old rig down even when it throws, so the prior history is invalid either way.
undo?.clear()
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
}
@@ -1847,6 +1918,8 @@ public struct ShoeGazeBuilderView: View {
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
}
selectedBoardIndex = 0
// A brand-new rig is a fresh document — drop any prior undo history.
undo?.clear()
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
persist(shoeGaze.captureEntry(name: name))
+12 -5
View File
@@ -70,6 +70,9 @@ public struct ShoeGazeView: View {
private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double?
/// Multi-level undo / redo for board edits made from this view, injected into the board bar.
@State private var undo: UndoCoordinator
/// Bumped on each transport button press to force a re-read of the engine's
/// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning`
/// directly (the single source of truth) rather than a private mirror that could
@@ -102,6 +105,7 @@ public struct ShoeGazeView: View {
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
self._undo = State(initialValue: UndoCoordinator(shoeGaze: shoeGaze))
}
// MARK: - Body
@@ -118,6 +122,7 @@ public struct ShoeGazeView: View {
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
.environment(undo)
Divider()
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
boardList
@@ -249,7 +254,7 @@ public struct ShoeGazeView: View {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
let board: PedalBoard = pair.element
PedalBoardView(board: board) {
shoeGaze.removeBoard(board)
undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
}
}
}
@@ -293,10 +298,12 @@ public struct ShoeGazeView: View {
private func addBoard() {
var createdBoard: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
createdBoard = board
try board.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board)
try undo.perform("Add Board") {
let board: PedalBoard = try shoeGaze.addBoard()
createdBoard = board
try board.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board)
}
} catch {
if let board: PedalBoard = createdBoard {
shoeGaze.removeBoard(board)