104 lines
2.9 KiB
Swift
104 lines
2.9 KiB
Swift
// ParameterButton.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import SwiftUI
|
|
import LyrebirdSynth
|
|
|
|
/// A button control for triggering actions or toggling a `UIParamNode` between two values.
|
|
///
|
|
/// Two styles:
|
|
/// - `.momentary` (default) — executes a closure on press; no node binding required.
|
|
/// - `.toggle` — flips the bound node between `offValue` and `onValue` on each press.
|
|
///
|
|
/// ```swift
|
|
/// // Momentary action button
|
|
/// ParameterButton("Trigger") { synth.trigger() }
|
|
///
|
|
/// // Toggle bound to a UIParamNode
|
|
/// ParameterButton("Mute", node: synth.$muted, style: .toggle)
|
|
/// ```
|
|
public struct ParameterButton: View {
|
|
|
|
// MARK: - Style
|
|
|
|
public enum Style {
|
|
/// Executes the action closure on each press.
|
|
case momentary
|
|
/// Flips the node between `offValue` (0) and `onValue` (1) on each press.
|
|
case toggle
|
|
}
|
|
|
|
// MARK: - Properties
|
|
|
|
private let label: String
|
|
private let node: UIParamNode?
|
|
private let style: Style
|
|
private let action: (() -> Void)?
|
|
|
|
/// Value representing the "off" state for `.toggle` style (default 0).
|
|
public var offValue: Double = 0.0
|
|
/// Value representing the "on" state for `.toggle` style (default 1).
|
|
public var onValue: Double = 1.0
|
|
|
|
// MARK: - Inits
|
|
|
|
/// Creates a momentary button that runs `action` on press.
|
|
///
|
|
/// - Parameters:
|
|
/// - label: Button text.
|
|
/// - action: Closure called each time the button is pressed.
|
|
public init(
|
|
_ label: String,
|
|
action: @escaping (
|
|
) -> Void) {
|
|
self.label = label
|
|
self.node = nil
|
|
self.style = .momentary
|
|
self.action = action
|
|
}
|
|
|
|
/// Creates a toggle button bound to a `UIParamNode`.
|
|
///
|
|
/// The node's value is interpreted as a boolean: any value ≥ 0.5 is "on".
|
|
///
|
|
/// - Parameters:
|
|
/// - label: Button text.
|
|
/// - node: The `UIParamNode` to toggle (pass `synth.$paramName`).
|
|
/// - style: Must be `.toggle`; `.momentary` is handled by the other initializer.
|
|
public init(
|
|
_ label: String,
|
|
node: UIParamNode,
|
|
style: Style = .toggle
|
|
) {
|
|
self.label = label
|
|
self.node = node
|
|
self.style = style
|
|
self.action = nil
|
|
}
|
|
|
|
// MARK: - Body
|
|
|
|
public var body: some View {
|
|
switch style {
|
|
case .momentary:
|
|
Button(label) { action?() }
|
|
.buttonStyle(.bordered)
|
|
|
|
case .toggle:
|
|
let isOn: Bool = (node?.value ?? 0) >= 0.5
|
|
Button(action: {
|
|
node?.update(isOn ? offValue : onValue)
|
|
}) {
|
|
Text(label)
|
|
.frame(minWidth: 60)
|
|
}
|
|
.buttonStyle(.bordered)
|
|
.background(isOn ? Color.accentColor.opacity(0.3) : Color.clear)
|
|
.cornerRadius(6)
|
|
}
|
|
}
|
|
}
|