From 1f5b70edc7ae9ebd1eeee2561d7f24a5a02c658e Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Wed, 25 Nov 2026 14:23:00 -0800 Subject: [PATCH] feat(undo): parameter undo for knobs, sliders, switches, selectors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier 2 of the rig-undo feature, on the same undo stack as the structural (tier 1) edits. Records one undo checkpoint when the user finishes changing a pedal control, so ⌘Z / the ↶ button step back through knob turns and switch flips as well as add/remove/move. - UndoEntry.parameter + PedalControlGroup (knob/advancedKnob/slider/switch/ selector); UndoCoordinator.recordParameterEdit + .parameter handling in undo()/redo(). applyParameter re-resolves the LIVE node by (pedalID, group, controlLabel) via ShoeGaze.pedal(id:), so an undo lands on the right control even after an intervening structural rebuild replaced the pedal's node (pedal ids persist through rebuild). old == new records nothing. - Knobs record via Lyrebird 2.3.0's ParameterKnob.onEditingEnded (one edit per drag): PedalView.recordingKnob (main / advanced / mix / level / looper) and TempoSyncKnobView. - Self-contained views (VerticalParameterSlider, PedalSwitchView, PedalSelectorKnobView) record via a new \.pedalParameterEditRecorder environment closure PedalView installs, capturing pedal.id + the coordinator. Slider/selector snapshot node.value at drag start; switch records old→new on the committing tap. - rebuildsOnChange switches/selectors are deliberately NOT recorded (they alter graph topology and would fight the structural restore's live-value merge) — documented as a known gap, along with tempo-sync division changes. - Bump the Lyrebird pin to 2.3.0 (the released tag with onEditingEnded), drop the dev-time local path override. Tests: 18 UndoCoordinator tests (knob/slider/switch/selector round-trips, post-rebuild re-resolution, + a catalogue test asserting unique control labels per group so the by-label resolution can't mis-target). Full suite 837 green; both demo schemes build against 2.3.0. External review + caveman sweep: no blocking findings. Co-Authored-By: Claude Opus 4.8 --- .../xcshareddata/swiftpm/Package.resolved | 4 +- Package.resolved | 6 +- Package.swift | 2 +- .../xcshareddata/swiftpm/Package.resolved | 6 +- Sources/LyrebirdShoeGaze/ShoeGaze.swift | 7 + .../Undo/PedalControlGroup.swift | 26 ++++ .../Undo/UndoCoordinator.swift | 91 ++++++++++-- Sources/LyrebirdShoeGaze/Undo/UndoEntry.swift | 32 ++++- .../PedalRebuildEnvironment.swift | 17 +++ .../PedalSelectorKnobView.swift | 17 ++- .../LyrebirdShoeGazeUI/PedalSwitchView.swift | 16 ++- Sources/LyrebirdShoeGazeUI/PedalView.swift | 57 +++++++- .../VerticalParameterSlider.swift | 15 ++ .../UndoCoordinatorTests.swift | 131 ++++++++++++++++++ 14 files changed, 396 insertions(+), 31 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Undo/PedalControlGroup.swift diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index bd48b48..8680d91 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7", - "version" : "2.2.0" + "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30", + "version" : "2.3.0" } }, { diff --git a/Package.resolved b/Package.resolved index 0afb3bf..e56565d 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "c8855e41a403b5b1fccd9ccb4b3ef4d75c4307590ae6a0b8e985e71c41011e09", + "originHash" : "6094cf70541e0593db7264ad9c75576ce239a5a5885ca4b783b5444793b6fee5", "pins" : [ { "identity" : "linenoise-swift", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7", - "version" : "2.2.0" + "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30", + "version" : "2.3.0" } }, { diff --git a/Package.swift b/Package.swift index c8caf30..0290ce1 100644 --- a/Package.swift +++ b/Package.swift @@ -24,7 +24,7 @@ let package = Package( .library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]), ], dependencies: [ - .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.0.0"), + .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.3.0"), ], targets: [ // Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`. diff --git a/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1c850d1..c79f3a7 100644 --- a/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "13b4323e9d41dfdff1c6aeac595cff272eb4eee9cc1a3146483bdaf8543bc103", + "originHash" : "9e278ce69e19f7dabaaaed1b75fb6112a02ece1e30e2aad82c12942c5ddeb192", "pins" : [ { "identity" : "linenoise-swift", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54", - "version" : "2.0.0" + "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30", + "version" : "2.3.0" } }, { diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 6ecd5f1..fe6b0d2 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -238,6 +238,13 @@ public final class ShoeGaze { engine.stop() } + /// The live pedal with the given `id`, searching every board (main chain + parallel / stereo + /// branches) and router branches, or `nil` if none matches. Used by undo to re-resolve a + /// control's live node after an edit has rebuilt the board it lives on. + func pedal(id: UUID) -> Pedal? { + allPedals().first { $0.id == id } + } + /// Every live `Pedal` across all main boards and chain-router branches. private func allPedals() -> [Pedal] { var result: [Pedal] = [] diff --git a/Sources/LyrebirdShoeGaze/Undo/PedalControlGroup.swift b/Sources/LyrebirdShoeGaze/Undo/PedalControlGroup.swift new file mode 100644 index 0000000..c33205b --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Undo/PedalControlGroup.swift @@ -0,0 +1,26 @@ +// PedalControlGroup.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Identifies which of a pedal's control collections holds a given parameter, so a parameter-undo +/// entry can re-resolve the live ``UIParamNode`` by `(pedal id, group, control label)` after an +/// edit has rebuilt the pedal. +public enum PedalControlGroup: Sendable { + + /// A face knob — ``Pedal/knobs`` (includes the trailing `Mix` / `Level`). + case knob + + /// A knob in the pedal's advanced popover — ``Pedal/advancedKnobs``. + case advancedKnob + + /// A continuous slider — ``Pedal/effectSliders``. + case slider + + /// A segmented switch — ``Pedal/effectSwitches``. + case `switch` + + /// A stepped selector knob — ``Pedal/effectSelectors``. + case selector +} diff --git a/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift b/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift index 271ff5f..0ab76c7 100644 --- a/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift +++ b/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift @@ -6,18 +6,25 @@ import Foundation import Observation +import LyrebirdSynth -/// Multi-level undo / redo for structural rig edits. +/// Multi-level undo / redo for rig edits — both structural topology changes and parameter changes, +/// interleaved on one stack. /// -/// `UndoCoordinator` wraps every structural edit (add / remove / move a pedal, board, split-merge -/// region, or router) in ``perform(_:_:)``. Before running the edit it snapshots the whole rig as a -/// ``ShoeGazeState``; if the edit actually changed the rig it records that pre-edit snapshot on the -/// undo stack. ``undo()`` restores the recorded snapshot via `ShoeGaze.loadRig(from:)` and moves the -/// pre-undo state onto the redo stack; ``redo()`` is the mirror. Any new edit clears the redo stack. +/// **Structural edits** (add / remove / move a pedal, board, split-merge region) are wrapped in +/// ``perform(_:_:)``, which snapshots the whole rig as a ``ShoeGazeState`` before the edit and +/// records that pre-edit snapshot if the rig actually changed. ``undo()`` restores it *surgically* +/// (see ``restore(_:on:)`` — board-by-board reconciliation, not a whole-rig reload) and moves the +/// pre-undo state onto the redo stack; ``redo()`` is the mirror. /// -/// This tier covers topology only. Continuous parameter changes (knob / switch values) are far too -/// frequent to snapshot the whole rig per change and are handled separately with coalesced per-node -/// deltas — see the project's undo notes. +/// **Parameter edits** (one knob / slider / switch / selector the user finished changing) are +/// recorded by ``recordParameterEdit(label:pedalID:group:controlLabel:oldValue:newValue:)`` as the +/// control's identity plus its before/after values — undo sets it back, redo re-applies, re-resolving +/// the live node by id each time so it survives an intervening rebuild. Topology-changing +/// (`rebuildsOnChange`) controls are deliberately NOT recorded this way (they belong to the +/// structural path). +/// +/// Any new edit of either kind clears the redo stack. /// /// The coordinator holds the ``ShoeGaze`` instance weakly: it is a companion object the UI owns /// alongside the rig, and the rig never refers back to it. All access is `@MainActor`, matching the @@ -105,6 +112,37 @@ public final class UndoCoordinator { return result } + /// Records a single parameter edit (a knob / slider the user finished turning). Does nothing when + /// the value is unchanged. Clears the redo stack, matching standard undo semantics. + /// + /// - Parameters: + /// - label: Short description (typically the control's label, e.g. `"Drive"`). + /// - pedalID: The id of the pedal the control belongs to. + /// - group: Which of the pedal's control collections holds it. + /// - controlLabel: The control's label, used to find it within the group. + /// - oldValue: The value when the edit began. + /// - newValue: The value when the edit ended. + public func recordParameterEdit( + label: String, + pedalID: UUID, + group: PedalControlGroup, + controlLabel: String, + oldValue: Double, + newValue: Double + ) { + guard oldValue != newValue else { return } + appendUndo(.parameter( + label: label, + pedalID: pedalID, + group: group, + controlLabel: controlLabel, + oldValue: oldValue, + newValue: newValue + )) + redoStack.removeAll() + refreshState() + } + /// Reverts the most recent recorded edit, restoring the rig to its state before that edit, and /// moves the edit onto the redo stack. No-op when there is nothing to undo. public func undo() { @@ -116,6 +154,10 @@ public final class UndoCoordinator { let afterState: ShoeGazeState = shoeGaze.captureState() appendRedo(.structural(label: label, state: afterState)) restore(beforeState, on: shoeGaze) + case .parameter(_, let pedalID, let group, let controlLabel, let oldValue, _): + applyParameter(pedalID: pedalID, group: group, controlLabel: controlLabel, + value: oldValue, on: shoeGaze) + appendRedo(entry) } refreshState() } @@ -131,6 +173,10 @@ public final class UndoCoordinator { let beforeState: ShoeGazeState = shoeGaze.captureState() appendUndo(.structural(label: label, state: beforeState)) restore(afterState, on: shoeGaze) + case .parameter(_, let pedalID, let group, let controlLabel, _, let newValue): + applyParameter(pedalID: pedalID, group: group, controlLabel: controlLabel, + value: newValue, on: shoeGaze) + appendUndo(entry) } refreshState() } @@ -209,6 +255,33 @@ public final class UndoCoordinator { // routers currently present are left exactly as they are. } + /// Sets a parameter back to `value` by re-resolving the control's live node from the current rig + /// (by pedal id, group, and label), so a parameter undo/redo lands on the right control even when + /// an earlier structural edit has since rebuilt the pedal. A missing pedal or control is a no-op. + private func applyParameter( + pedalID: UUID, + group: PedalControlGroup, + controlLabel: String, + value: Double, + on shoeGaze: ShoeGaze + ) { + guard let pedal: Pedal = shoeGaze.pedal(id: pedalID) else { return } + let node: UIParamNode? + switch group { + case .knob: + node = pedal.knobs.first { $0.label == controlLabel }?.node + case .advancedKnob: + node = pedal.advancedKnobs.first { $0.label == controlLabel }?.node + case .slider: + node = pedal.effectSliders.first { $0.label == controlLabel }?.node + case .switch: + node = pedal.effectSwitches.first { $0.label == controlLabel }?.node + case .selector: + node = pedal.effectSelectors.first { $0.label == controlLabel }?.node + } + node?.update(value) + } + /// Flattens every pedal in the current rig into an `id → PedalState` map, descending into /// parallel / stereo-split / stereo-unzip branches. private func currentPedalStatesByID(_ shoeGaze: ShoeGaze) -> [UUID: PedalState] { diff --git a/Sources/LyrebirdShoeGaze/Undo/UndoEntry.swift b/Sources/LyrebirdShoeGaze/Undo/UndoEntry.swift index c28edd5..4518e34 100644 --- a/Sources/LyrebirdShoeGaze/Undo/UndoEntry.swift +++ b/Sources/LyrebirdShoeGaze/Undo/UndoEntry.swift @@ -4,11 +4,19 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation + /// One entry on an ``UndoCoordinator`` undo or redo stack. /// -/// Structural edits (adding, removing, moving, or re-routing pedals and boards) are captured as a -/// whole-rig ``ShoeGazeState`` snapshot. Undo and redo are a symmetric swap: applying an entry -/// restores its snapshot and pushes the pre-restore state onto the opposite stack. +/// Two kinds of edit are recorded: +/// - **Structural** topology changes (adding, removing, moving, or re-routing pedals and boards) are +/// captured as a whole-rig ``ShoeGazeState`` snapshot, restored surgically on undo. +/// - **Parameter** changes (a single knob / slider turn) are captured as the control's identity plus +/// its before/after values, so undo sets it back without disturbing anything else. +/// +/// Both undo and redo are a symmetric swap: a structural entry restores its snapshot; a parameter +/// entry sets its control to the old value on undo and the new value on redo. Either way the applied +/// entry moves to the opposite stack. enum UndoEntry { /// A whole-rig topology change — adding, removing, or moving a pedal, board, split/merge region, @@ -17,12 +25,26 @@ enum UndoEntry { /// redo entry. case structural(label: String, state: ShoeGazeState) - /// A human-readable description of the action (e.g. `"Add Reverb"`), shown next to the Undo / - /// Redo menu items and toolbar buttons. + /// A single parameter change on one pedal control. The control is addressed by its pedal's id, + /// its group, and its label (re-resolved live so it survives an intervening rebuild); `oldValue` + /// is restored on undo and `newValue` on redo. + case parameter( + label: String, + pedalID: UUID, + group: PedalControlGroup, + controlLabel: String, + oldValue: Double, + newValue: Double + ) + + /// A human-readable description of the action (e.g. `"Add Reverb"`, `"Drive"`), shown next to the + /// Undo / Redo menu items and toolbar buttons. var label: String { switch self { case .structural(let label, _): return label + case .parameter(let label, _, _, _, _, _): + return label } } } diff --git a/Sources/LyrebirdShoeGazeUI/PedalRebuildEnvironment.swift b/Sources/LyrebirdShoeGazeUI/PedalRebuildEnvironment.swift index 1088ff0..a80cc11 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalRebuildEnvironment.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalRebuildEnvironment.swift @@ -23,3 +23,20 @@ extension EnvironmentValues { set { self[PedalRebuildActionKey.self] = newValue } } } + +/// Environment action a leaf pedal control calls when the user finishes changing it, so the host +/// can record one undo checkpoint per edit. Arguments: the control's group, its label, and the +/// values before and after the edit. ``PedalView`` installs it capturing the pedal's id and the +/// undo coordinator; it defaults to a no-op, so a control outside the builder records nothing. +private struct PedalParameterEditRecorderKey: EnvironmentKey { + static let defaultValue: @MainActor @Sendable (PedalControlGroup, String, Double, Double) -> Void = { _, _, _, _ in } +} + +extension EnvironmentValues { + /// Records a finished parameter edit (group, control label, old value, new value). No-op unless + /// the host installs it. + var pedalParameterEditRecorder: @MainActor @Sendable (PedalControlGroup, String, Double, Double) -> Void { + get { self[PedalParameterEditRecorderKey.self] } + set { self[PedalParameterEditRecorderKey.self] = newValue } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift index 33efadd..2e12d04 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift @@ -33,9 +33,15 @@ struct PedalSelectorKnobView: View { /// rebuild for `rebuildsOnChange` selectors. `nil` for plain live-value selectors. private let onCommit: (() -> Void)? + /// Records one undo checkpoint per drag that changes the stop. Installed by ``PedalView``. + @Environment(\.pedalParameterEditRecorder) private var recordEdit + // MARK: - Drag state @State private var dragStartIndex: Int = 0 + /// Node value captured when a drag begins — the undo checkpoint's "before" (read from the node, + /// not the stop table, so it can't index out of range if the stops change). + @State private var dragStartValue: Double = 0 @State private var dragInProgress: Bool = false // MARK: - Init @@ -94,6 +100,7 @@ struct PedalSelectorKnobView: View { if !dragInProgress { dragInProgress = true dragStartIndex = currentIndex + dragStartValue = selector.node.value } let delta: CGFloat = gesture.translation.height // down = positive // Up should advance (increase index), so subtract the downward delta. @@ -107,7 +114,15 @@ struct PedalSelectorKnobView: View { .onEnded { _ in let changed: Bool = currentIndex != dragStartIndex dragInProgress = false - if changed { onCommit?() } + if changed { + onCommit?() + // A rebuildsOnChange selector alters graph topology: it is NOT recorded as a + // parameter edit (and isn't undoable yet — recording it would fight the + // structural restore's live-value merge). Only plain live-value selectors record. + if !selector.rebuildsOnChange { + recordEdit(.selector, selector.label, dragStartValue, selector.node.value) + } + } } } diff --git a/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift b/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift index 12e44b5..e0486eb 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift @@ -56,6 +56,9 @@ public struct PedalSwitchView: View { @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool + /// Records one undo checkpoint per committed change. Installed by ``PedalView``; no-op elsewhere. + @Environment(\.pedalParameterEditRecorder) private var recordEdit + // MARK: - Init /// Creates a segmented switch view. @@ -105,9 +108,18 @@ public struct PedalSwitchView: View { private func segment(option: PedalSwitch.Option, isActive: Bool) -> some View { Button(action: { - let changed: Bool = option.value != pedalSwitch.node.value + let oldValue: Double = pedalSwitch.node.value + let changed: Bool = option.value != oldValue pedalSwitch.node.update(option.value) - if changed { onCommit?() } + if changed { + onCommit?() + // A rebuildsOnChange switch alters graph topology: it is NOT recorded as a parameter + // edit (and isn't undoable yet — recording it would fight the structural restore's + // live-value merge). Only plain live-value switches become parameter edits. + if !pedalSwitch.rebuildsOnChange { + recordEdit(.switch, pedalSwitch.label, oldValue, option.value) + } + } }) { Text(option.title) .font(.system(size: PedalSwitchView.fontSize, weight: .semibold)) diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 177e9bc..1ea1ac4 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -246,6 +246,9 @@ struct TempoSyncKnobView: View { let knob: PedalKnob let param: TempoSyncableParam + /// Undo coordinator injected by the host; `nil` outside the builder. + @Environment(UndoCoordinator.self) private var undo: UndoCoordinator? + /// Presentation flag for the division-picker popover. @State private var showDivisionPicker: Bool = false @@ -270,6 +273,18 @@ struct TempoSyncKnobView: View { VStack(spacing: TempoSyncKnobView.cellSpacing) { ParameterKnob(knob.label, node: knob.node, range: knob.range) + .onEditingEnded { previous, newValue in + // Only reachable when free (synced knobs are disabled), so a recorded edit is a + // genuine manual turn of this time/rate knob. + undo?.recordParameterEdit( + label: knob.label, + pedalID: pedal.id, + group: .knob, + controlLabel: knob.label, + oldValue: previous, + newValue: newValue + ) + } .foregroundStyle(Color.white) .disabled(isSynced) .opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0) @@ -513,6 +528,9 @@ public struct PedalView: View { /// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off. @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool + /// Undo coordinator injected by the host; `nil` outside the builder (edits aren't recorded). + @Environment(UndoCoordinator.self) private var undo: UndoCoordinator? + // MARK: - Init /// Creates a stompbox pedal view for the given pedal. @@ -597,6 +615,18 @@ public struct PedalView: View { PedalInfoView(pedal: pedal) .presentationDetents([.medium, .large]) } + // Let the self-contained control views (switch / selector / slider) record one undo + // checkpoint per edit. Captures this pedal's id + the coordinator; a no-op when `undo` is nil. + .environment(\.pedalParameterEditRecorder) { @MainActor [pedal, undo] (group: PedalControlGroup, label: String, oldValue: Double, newValue: Double) in + undo?.recordParameterEdit( + label: label, + pedalID: pedal.id, + group: group, + controlLabel: label, + oldValue: oldValue, + newValue: newValue + ) + } } // MARK: - Content layouts @@ -670,7 +700,7 @@ public struct PedalView: View { Spacer(minLength: 0) ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in let knob: PedalKnob = knobPair.element - ParameterKnob(knob.label, node: knob.node, range: knob.range) + recordingKnob(knob) .foregroundStyle(Color.white) } Spacer(minLength: 0) @@ -866,7 +896,7 @@ public struct PedalView: View { ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in HStack(alignment: .top, spacing: PedalView.advancedPopoverSpacing) { ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in - ParameterKnob(knobPair.element.label, node: knobPair.element.node, range: knobPair.element.range) + recordingKnob(knobPair.element, group: .advancedKnob) .foregroundStyle(Color.white) } } @@ -924,11 +954,28 @@ public struct PedalView: View { if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) { TempoSyncKnobView(pedal: pedal, knob: knob, param: param) } else { - ParameterKnob(knob.label, node: knob.node, range: knob.range) + recordingKnob(knob) .foregroundStyle(Color.white) } } + /// A ``ParameterKnob`` that records one undo checkpoint per drag (via the coordinator) when the + /// user finishes turning it. The control is addressed by the pedal's id, its group, and its + /// label so undo re-resolves the live node even after an intervening rebuild. + private func recordingKnob(_ knob: PedalKnob, group: PedalControlGroup = .knob) -> ParameterKnob { + ParameterKnob(knob.label, node: knob.node, range: knob.range) + .onEditingEnded { previous, newValue in + undo?.recordParameterEdit( + label: knob.label, + pedalID: pedal.id, + group: group, + controlLabel: knob.label, + oldValue: previous, + newValue: newValue + ) + } + } + /// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is /// not syncable. Matched by `UIParamNode` identity so it is robust to label changes. private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? { @@ -1141,7 +1188,7 @@ public struct PedalView: View { @ViewBuilder private var levelControl: some View { if let level: PedalKnob = pedal.knobs.last { - ParameterKnob(level.label, node: level.node, range: level.range) + recordingKnob(level) .foregroundStyle(Color.white) } } @@ -1152,7 +1199,7 @@ public struct PedalView: View { @ViewBuilder private var mixControl: some View { if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last { - ParameterKnob(mix.label, node: mix.node, range: mix.range) + recordingKnob(mix) .foregroundStyle(Color.white) } } diff --git a/Sources/LyrebirdShoeGazeUI/VerticalParameterSlider.swift b/Sources/LyrebirdShoeGazeUI/VerticalParameterSlider.swift index 386665a..ca60c47 100644 --- a/Sources/LyrebirdShoeGazeUI/VerticalParameterSlider.swift +++ b/Sources/LyrebirdShoeGazeUI/VerticalParameterSlider.swift @@ -49,6 +49,13 @@ struct VerticalParameterSlider: View { private let node: UIParamNode private let range: ClosedRange + /// Records one undo checkpoint per drag. Installed by ``PedalView``; no-op elsewhere. + @Environment(\.pedalParameterEditRecorder) private var recordEdit + + /// Node value captured when a drag begins, for the undo checkpoint's "before". + @State private var dragStartValue: Double = 0 + @State private var dragInProgress: Bool = false + // MARK: - Init /// Creates a vertical fader. @@ -141,8 +148,16 @@ struct VerticalParameterSlider: View { .gesture( DragGesture(minimumDistance: 0) .onChanged { drag in + if !dragInProgress { + dragInProgress = true + dragStartValue = node.value + } updateValue(forY: drag.location.y, height: height) } + .onEnded { _ in + dragInProgress = false + recordEdit(.slider, label, dragStartValue, node.value) + } ) } .frame(width: VerticalParameterSlider.controlWidth, height: VerticalParameterSlider.trackHeight) diff --git a/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift b/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift index 29976cb..208d1f1 100644 --- a/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift +++ b/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift @@ -273,6 +273,137 @@ struct UndoCoordinatorTests { #expect(sg.boards.last?.pedals.map { $0.displayName } == ["Reverb"], "second board restored too") } + // MARK: - Parameter (knob) undo / redo + + @Test func parameterUndoSetsTheKnobBackAndRedoReapplies() throws { + let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let pedal: Pedal = board.pedals[0] + let knob: PedalKnob = try #require(pedal.knobs.first) + let oldValue: Double = knob.node.value + let newValue: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.63 + try #require(abs(newValue - oldValue) > 1e-9) + + // The vendored knob would call node.update as the drag runs; simulate the settled value. + knob.node.update(newValue) + undo.recordParameterEdit( + label: knob.label, pedalID: pedal.id, group: .knob, + controlLabel: knob.label, oldValue: oldValue, newValue: newValue + ) + #expect(undo.canUndo == true) + #expect(undo.undoActionLabel == knob.label) + + undo.undo() + #expect(abs(knob.node.value - oldValue) < 1e-9, "undo restores the previous knob value") + + undo.redo() + #expect(abs(knob.node.value - newValue) < 1e-9, "redo re-applies the new value") + } + + @Test func parameterUndoResolvesTheLiveNodeAfterARebuild() throws { + let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let pedalID: UUID = board.pedals[0].id + let knob: PedalKnob = try #require(board.pedals[0].knobs.first) + let knobLabel: String = knob.label + let oldValue: Double = knob.node.value + let newValue: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.55 + knob.node.update(newValue) + undo.recordParameterEdit( + label: knobLabel, pedalID: pedalID, group: .knob, + controlLabel: knobLabel, oldValue: oldValue, newValue: newValue + ) + + // A later structural edit rebuilds the board, replacing the pedal's live node (same id). + try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) } + + // Undo the structural edit, then the parameter edit; the latter must re-resolve the fresh node. + undo.undo() // removes Reverb (rebuild) + undo.undo() // the knob edit — resolve the live Overdrive by id and set it back + let livePedal: Pedal = try #require(sg.pedal(id: pedalID)) + let liveKnob: PedalKnob = try #require(livePedal.knobs.first { $0.label == knobLabel }) + #expect(abs(liveKnob.node.value - oldValue) < 1e-9, "param undo resolves the live node after a rebuild") + } + + // MARK: - Parameter undo for sliders / switches / selectors + + @Test func parameterUndoForASlider() throws { + let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) = + try makeRig(pedals: ["Graphic EQ"]) + defer { try? FileManager.default.removeItem(at: url) } + let pedal: Pedal = board.pedals[0] + let slider: PedalSlider = try #require(pedal.effectSliders.first) + let oldValue: Double = slider.node.value + let newValue: Double = slider.range.lowerBound + (slider.range.upperBound - slider.range.lowerBound) * 0.3 + try #require(abs(newValue - oldValue) > 1e-9) + + slider.node.update(newValue) + undo.recordParameterEdit(label: slider.label, pedalID: pedal.id, group: .slider, + controlLabel: slider.label, oldValue: oldValue, newValue: newValue) + undo.undo() + #expect(abs(slider.node.value - oldValue) < 1e-9) + undo.redo() + #expect(abs(slider.node.value - newValue) < 1e-9) + } + + @Test func parameterUndoForASwitch() throws { + let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) = + try makeRig(pedals: ["Sixties Combo"]) + defer { try? FileManager.default.removeItem(at: url) } + let pedal: Pedal = board.pedals[0] + let sw: PedalSwitch = try #require(pedal.effectSwitches.first) + let oldValue: Double = sw.node.value + let newValue: Double = try #require(sw.options.first { abs($0.value - oldValue) > 1e-9 }?.value) + + sw.node.update(newValue) + undo.recordParameterEdit(label: sw.label, pedalID: pedal.id, group: .switch, + controlLabel: sw.label, oldValue: oldValue, newValue: newValue) + undo.undo() + #expect(abs(sw.node.value - oldValue) < 1e-9) + undo.redo() + #expect(abs(sw.node.value - newValue) < 1e-9) + } + + @Test func parameterUndoForASelector() throws { + let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) = + try makeRig(pedals: ["Karplus Resonator"]) + defer { try? FileManager.default.removeItem(at: url) } + let pedal: Pedal = board.pedals[0] + let selector: PedalSelectorKnob = try #require(pedal.effectSelectors.first) + let oldValue: Double = selector.node.value + let newValue: Double = try #require(selector.stops.first { abs($0.value - oldValue) > 1e-9 }?.value) + + selector.node.update(newValue) + undo.recordParameterEdit(label: selector.label, pedalID: pedal.id, group: .selector, + controlLabel: selector.label, oldValue: oldValue, newValue: newValue) + undo.undo() + #expect(abs(selector.node.value - oldValue) < 1e-9) + undo.redo() + #expect(abs(selector.node.value - newValue) < 1e-9) + } + + // MARK: - Parameter resolution relies on unique labels per group + + @Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws { + // `applyParameter` resolves a control by (pedal id, group, label), so labels must be unique + // within a group on every pedal — otherwise an undo could land on the wrong control. + func duplicates(_ labels: [String]) -> [String] { + Dictionary(grouping: labels, by: { $0 }).filter { $0.value.count > 1 }.map { $0.key } + } + for type: String in PedalRegistry.builtIn.keys.sorted() { + guard let pedal: Pedal = PedalRegistry.makePedal(type: type) else { continue } + #expect(duplicates(pedal.knobs.map { $0.label }).isEmpty, "\(type): duplicate knob labels") + #expect(duplicates(pedal.advancedKnobs.map { $0.label }).isEmpty, "\(type): duplicate advancedKnob labels") + #expect(duplicates(pedal.effectSliders.map { $0.label }).isEmpty, "\(type): duplicate slider labels") + #expect(duplicates(pedal.effectSwitches.map { $0.label }).isEmpty, "\(type): duplicate switch labels") + #expect(duplicates(pedal.effectSelectors.map { $0.label }).isEmpty, "\(type): duplicate selector labels") + } + } + // MARK: - A throwing action records nothing @Test func aThrowingActionRecordsNoCheckpoint() throws {