Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/BoardsSheetView.swift
T
josh a8bd0242a3 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>
2026-11-25 10:22:51 -08:00

259 lines
9.1 KiB
Swift

// BoardsSheetView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdSynth
/// A full board manager presented as a sheet — the richer companion to the inline
/// ``BoardBarView``.
///
/// Each board is a `List` row with an audible toggle, a Solo button, a master-gain fader, an
/// inline rename field, and an "Edit" action that selects it as the builder's edit target and
/// dismisses. Rows reorder by drag (`.onMove`) and delete by swipe (`.onDelete`). A header
/// pairs the **Solo / Blend** mode switch with the crossfade slider, mirroring the board bar.
///
/// Primarily used on iOS/iPadOS (presented with `.presentationDetents`) where the inline bar
/// has no room for rename / reorder, but the view is platform-neutral.
public struct BoardsSheetView: View {
// MARK: - Play mode
private enum PlayMode: Hashable {
case solo
case blend
}
// MARK: - Layout constants
private static let rowSpacing: CGFloat = 12
private static let faderWidth: CGFloat = 120
private static let soloButtonSize: CGFloat = 28
private static let ledDiameter: CGFloat = 14
private static let ledDimBrightness: Double = 0.16
private static let ledRimOpacity: Double = 0.30
private static let maxCrossfadeSeconds: Double = 10.0
private static let crossfadeStep: Double = 0.1
private static let headerSpacing: CGFloat = 10
// MARK: - Properties
private let shoeGaze: ShoeGaze
@Binding private var editingBoardIndex: Int
@Binding private var crossfadeSeconds: Double
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
/// Creates a board-manager sheet.
///
/// - Parameters:
/// - shoeGaze: The manager whose `boards` are edited.
/// - editingBoardIndex: The builder's edit target; a row's "Edit" action sets this.
/// - crossfadeSeconds: Crossfade duration applied to switches / toggles.
/// - onAddBoard: Called when the **Add Board** button is tapped.
public init(
shoeGaze: ShoeGaze,
editingBoardIndex: Binding<Int>,
crossfadeSeconds: Binding<Double>,
onAddBoard: @escaping () -> Void
) {
self.shoeGaze = shoeGaze
self._editingBoardIndex = editingBoardIndex
self._crossfadeSeconds = crossfadeSeconds
self.onAddBoard = onAddBoard
}
// MARK: - Body
public var body: some View {
NavigationStack {
VStack(spacing: BoardsSheetView.headerSpacing) {
header
List {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
boardRow(index: pair.offset, board: pair.element)
}
.onMove(perform: moveBoards)
.onDelete(perform: deleteBoards)
}
}
.padding(.top, BoardsSheetView.headerSpacing)
.navigationTitle("Boards")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
ToolbarItem(placement: .primaryAction) {
Button {
onAddBoard()
} label: {
Label("Add Board", systemImage: "plus")
}
}
}
}
}
// MARK: - Header
private var header: some View {
HStack(spacing: BoardsSheetView.headerSpacing) {
Picker("Mode", selection: $mode) {
Text("Solo").tag(PlayMode.solo)
Text("Blend").tag(PlayMode.blend)
}
.pickerStyle(.segmented)
.frame(maxWidth: 180)
Button("All") {
shoeGaze.selectAllBoards(crossfadeSeconds: clampedCrossfade)
}
.buttonStyle(.bordered)
Spacer()
Text("XFade")
Slider(
value: $crossfadeSeconds,
in: 0 ... BoardsSheetView.maxCrossfadeSeconds,
step: BoardsSheetView.crossfadeStep
)
.frame(width: BoardsSheetView.faderWidth)
Text(String(format: "%.1fs", clampedCrossfade))
.monospacedDigit()
}
.padding(.horizontal)
}
// MARK: - Board row
@ViewBuilder
private func boardRow(index: Int, board: PedalBoard) -> some View {
let isAudible: Bool = shoeGaze.isBoardAudible(board)
let isSoloed: Bool = shoeGaze.activeBoardIndex == index
HStack(spacing: BoardsSheetView.rowSpacing) {
ledButton(board: board, isAudible: isAudible)
soloButton(board: board, isSoloed: isSoloed)
TextField(
"Board \(index + 1)",
text: Binding(
get: { board.label },
set: { board.label = $0 }
)
)
.textFieldStyle(.roundedBorder)
if let gainNode: UIParamNode = board.masterGainNode {
Slider(
value: Binding(
get: { gainNode.value },
set: { gainNode.update($0) }
),
in: 0.0 ... 1.0
)
.frame(width: BoardsSheetView.faderWidth)
}
Button("Edit") {
editingBoardIndex = index
dismiss()
}
.buttonStyle(.borderless)
}
.padding(.vertical, 4)
}
private func ledButton(board: PedalBoard, isAudible: Bool) -> some View {
Button {
switch mode {
case .solo:
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
case .blend:
shoeGaze.setBoard(board, audible: !isAudible, crossfadeSeconds: clampedCrossfade)
}
} label: {
Circle()
.fill(isAudible ? Color.green : Color(white: BoardsSheetView.ledDimBrightness))
.frame(width: BoardsSheetView.ledDiameter, height: BoardsSheetView.ledDiameter)
.overlay(
Circle().stroke(Color.white.opacity(BoardsSheetView.ledRimOpacity), lineWidth: 0.5)
)
}
.buttonStyle(.plain)
}
private func soloButton(board: PedalBoard, isSoloed: Bool) -> some View {
Button {
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
} label: {
Text("S")
.font(.system(size: 13, weight: .bold))
.foregroundStyle(isSoloed ? Color.black : Color.primary)
.frame(width: BoardsSheetView.soloButtonSize, height: BoardsSheetView.soloButtonSize)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(isSoloed ? Color.yellow : Color.secondary.opacity(0.2))
)
}
.buttonStyle(.plain)
}
// MARK: - Mutations
/// Reorders boards, translating SwiftUI's `onMove` offsets to `ShoeGaze.moveBoard`.
private func moveBoards(from source: IndexSet, to destination: Int) {
// List drag delivers a single source row; ignore any multi-selection move so a
// dropped row can never desync `shoeGaze.boards` from the displayed order.
guard source.count == 1, let sourceIndex: Int = source.first else { return }
let board: PedalBoard = shoeGaze.boards[sourceIndex]
// 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
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) {
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()
}
// MARK: - Helpers
private var clampedCrossfade: Double {
min(max(crossfadeSeconds, 0.0), BoardsSheetView.maxCrossfadeSeconds)
}
private func clampEditingIndex() {
let count: Int = shoeGaze.boards.count
guard count > 0 else { editingBoardIndex = 0; return }
editingBoardIndex = min(editingBoardIndex, count - 1)
}
}