// TempoView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import SwiftUI import LyrebirdSynth import LyrebirdShoeGaze /// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that /// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger). /// /// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter /// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT /// state, not push-notified UI state. public struct TempoView: View { // MARK: - Constants private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz private static let minBpm: Double = 30.0 private static let maxBpm: Double = 300.0 private static let bpmStep: Double = 1.0 /// Width of the editable BPM text field — fits three digits at the readout font. private static let bpmFieldWidth: CGFloat = 44 private static let bpmFontSize: CGFloat = 18 /// Maximum digits accepted in the BPM field (max 300 BPM is three digits). private static let bpmMaxDigits: Int = 3 private static let rowSpacing: CGFloat = 10 // Metronome track: a dot swings wall-to-wall once per beat, pausing at each wall (the beat) // so the eye can anticipate the hit. Pendulum easing comes for free from the cosine map. private static let trackWidth: CGFloat = 150 private static let trackHeight: CGFloat = 16 private static let trackCornerRadius: CGFloat = 4 private static let trackBrightness: Double = 0.14 private static let trackBorderOpacity: Double = 0.35 private static let trackBorderWidth: CGFloat = 1 /// Vertical playhead sweeping horizontally across the track (Looper-style), full track height. private static let lineWidth: CGFloat = 3 /// Playhead opacity floor at mid-swing; ramps to full at the walls so it fades as it travels /// toward center and re-brightens into each beat. private static let lineMinOpacity: Double = 0.25 /// Curve on the wall-proximity → brightness map; > 1 dims harder through the middle. private static let brightnessFadeCurve: Double = 1.6 /// Soft glow drawn behind the playhead; its opacity peaks at the turnaround (on the beat). private static let glowWidth: CGFloat = 16 private static let glowMaxOpacity: Double = 0.7 /// End-wall tick marks sit on the beat positions. private static let wallTickWidth: CGFloat = 2 private static let wallTickOpacity: Double = 0.4 /// Fixed row height = the enabled (BPM/TAP-visible) height, so toggling doesn't shift layout. static let enabledHeight: CGFloat = 34 // MARK: - Properties private let shoeGaze: ShoeGaze @State private var displayedBpm: Double /// Continuous beat position, polled from the clock; drives the metronome dot. @State private var beat: Double = 0.0 /// The editable BPM text. Kept in sync with `displayedBpm` while the field isn't focused; on /// commit it is validated (integer only), clamped to `[minBpm, maxBpm]`, and applied. @State private var bpmText: String @FocusState private var bpmFieldFocused: Bool // MARK: - Init /// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives. public init(shoeGaze: ShoeGaze) { self.shoeGaze = shoeGaze self._displayedBpm = State(initialValue: shoeGaze.clock.bpm) self._bpmText = State(initialValue: String(Int(shoeGaze.clock.bpm.rounded()))) } // MARK: - Body public var body: some View { HStack(spacing: TempoView.rowSpacing) { Button(shoeGaze.tempoEnabled ? "Tempo: On" : "Tempo: Off") { shoeGaze.setTempoEnabled(!shoeGaze.tempoEnabled) } .buttonStyle(.bordered) .tint(shoeGaze.tempoEnabled ? .green : .gray) .fixedSize() .help("Show the tempo indicator and enable tempo-synced controls") if shoeGaze.tempoEnabled { metronome bpmField Stepper( "", value: Binding( get: { displayedBpm }, set: { newValue in applyBpm(newValue) } ), in: TempoView.minBpm ... TempoView.maxBpm, step: TempoView.bpmStep ) .labelsHidden() tapArea } } // Pin to the enabled height (BPM / stepper / TAP visible) so toggling tempo on/off never // shifts the surrounding layout. .frame(height: TempoView.enabledHeight) .task(id: shoeGaze.tempoEnabled) { while shoeGaze.tempoEnabled && !Task.isCancelled { beat = shoeGaze.clock.currentBeat displayedBpm = shoeGaze.clock.bpm // Don't overwrite the field mid-edit — only reflect external tempo changes when the // field isn't focused (tap tempo, stepper, MIDI, rig load). if !bpmFieldFocused { bpmText = String(Int(displayedBpm.rounded())) } try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds) } } } // MARK: - BPM field /// Editable BPM readout. Accepts integer input, validated and clamped on commit (Return, or the /// keyboard's Done, or focus loss). Non-numeric or empty input reverts to the current tempo. private var bpmField: some View { HStack(spacing: TempoView.rowSpacing / 2) { TextField("", text: $bpmText) .textFieldStyle(.plain) .multilineTextAlignment(.trailing) .font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded)) .foregroundStyle(Color.white) .frame(width: TempoView.bpmFieldWidth) .fixedSize() .focused($bpmFieldFocused) .onSubmit { commitBpm() } #if os(iOS) .keyboardType(.numberPad) .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer() Button("Done") { bpmFieldFocused = false } } } #endif Text("BPM") .font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded)) .foregroundStyle(Color.white) } .onChange(of: bpmText) { _, newValue in // Reject non-numeric input as it is typed, and cap at three digits (max 300 BPM). let filtered: String = String(newValue.filter { $0.isNumber }.prefix(TempoView.bpmMaxDigits)) if filtered != newValue { bpmText = filtered } } .onChange(of: bpmFieldFocused) { _, focused in // Commit when focus leaves the field (tap away / Done), the counterpart to onSubmit. if !focused { commitBpm() } } } /// Validates and applies the typed BPM: integers only, clamped to `[minBpm, maxBpm]`. Non-numeric /// or empty input reverts the field to the current tempo without changing it. private func commitBpm() { let digits: String = bpmText.filter { $0.isNumber } if let value: Int = Int(digits) { applyBpm(Double(value)) } else { bpmText = String(Int(displayedBpm.rounded())) } } /// Clamps `bpm` to the allowed range, applies it to the session, and syncs the field text. private func applyBpm(_ bpm: Double) { let clamped: Double = min(max(bpm, TempoView.minBpm), TempoView.maxBpm) shoeGaze.setBpm(clamped) displayedBpm = clamped bpmText = String(Int(clamped.rounded())) } // MARK: - Subviews /// Horizontal pendulum: the dot maps `beat` through a cosine so it eases to a stop at each /// wall (an integer beat) and moves fastest at mid-swing — the wall pauses give the eye a /// runway to anticipate the beat. `x01 = (1 − cos(π·swing)) / 2`, `swing = beat mod 2`, puts /// the left wall on even beats and the right wall on odd beats (one wall hit per beat). private var metronome: some View { // Reduce beat mod 2 before the cosine so precision holds over a long session. let swing: Double = beat.truncatingRemainder(dividingBy: 2) let x01: Double = (1 - cos(.pi * swing)) / 2 // Proximity to a wall in [0, 1]: 1 at a wall (on the beat), 0 at mid-swing. The curve dims // harder through the middle so the playhead visibly fades as it travels toward center. let wallGlow: Double = pow(1 - 2 * min(x01, 1 - x01), TempoView.brightnessFadeCurve) return ZStack(alignment: .leading) { RoundedRectangle(cornerRadius: TempoView.trackCornerRadius) .fill(Color(white: TempoView.trackBrightness)) .overlay( RoundedRectangle(cornerRadius: TempoView.trackCornerRadius) .strokeBorder( Color.white.opacity(TempoView.trackBorderOpacity), lineWidth: TempoView.trackBorderWidth ) ) // Beat-position tick marks flush against each end wall. .overlay(alignment: .leading) { wallTick } .overlay(alignment: .trailing) { wallTick } playhead(x01: x01, wallGlow: wallGlow) } .frame(width: TempoView.trackWidth, height: TempoView.trackHeight) .clipShape(RoundedRectangle(cornerRadius: TempoView.trackCornerRadius)) } private var wallTick: some View { Rectangle() .fill(Color.white.opacity(TempoView.wallTickOpacity)) .frame(width: TempoView.wallTickWidth) } private func playhead(x01: Double, wallGlow: Double) -> some View { // Travel spans the track minus the line's own width so the playhead kisses each wall. let travel: CGFloat = TempoView.trackWidth - TempoView.lineWidth let x: CGFloat = CGFloat(x01) * travel let lineOpacity: Double = TempoView.lineMinOpacity + (1 - TempoView.lineMinOpacity) * wallGlow // Center glow + line share a leading-aligned box; offset positions the line's leading edge. return ZStack { Rectangle() .fill(Color.red.opacity(TempoView.glowMaxOpacity * wallGlow)) .frame(width: TempoView.glowWidth, height: TempoView.trackHeight) .blur(radius: TempoView.glowWidth / 3) Rectangle() .fill(Color.red.opacity(lineOpacity)) .frame(width: TempoView.lineWidth, height: TempoView.trackHeight) } .frame(width: TempoView.lineWidth, height: TempoView.trackHeight, alignment: .center) .offset(x: x) } private var tapArea: some View { // A standard-height bordered button (not a tall circle) so the tempo row matches the // height of the title and the engine-option buttons and top-aligns cleanly with them. Button { shoeGaze.tapTempo() displayedBpm = shoeGaze.clock.bpm } label: { Text("TAP") .font(.system(size: 13, weight: .bold, design: .rounded)) } .buttonStyle(.bordered) .tint(.gray) .foregroundStyle(Color.white) } }