// 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 /// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink. private static let flashDutyCycle: Double = 0.15 private static let minBpm: Double = 30.0 private static let maxBpm: Double = 300.0 private static let bpmStep: Double = 1.0 private static let ledDiameter: CGFloat = 16 private static let panelSpacing: CGFloat = 10 private static let rowSpacing: CGFloat = 14 private static let tapAreaSize: CGFloat = 64 // MARK: - Properties private let shoeGaze: ShoeGaze @State private var displayedBpm: Double @State private var ledOn: Bool = false // 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) } // MARK: - Body public var body: some View { VStack(spacing: TempoView.panelSpacing) { HStack(spacing: TempoView.rowSpacing) { led Text("\(Int(displayedBpm.rounded())) BPM") .font(.system(size: 18, weight: .semibold, design: .rounded)) .foregroundStyle(Color.white) Stepper( "", value: Binding( get: { displayedBpm }, set: { newValue in let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm) shoeGaze.clock.bpm = clamped displayedBpm = clamped } ), in: TempoView.minBpm ... TempoView.maxBpm, step: TempoView.bpmStep ) .labelsHidden() } tapArea } .task { while !Task.isCancelled { let beat: Double = shoeGaze.clock.currentBeat let phase: Double = beat - beat.rounded(.down) ledOn = phase < TempoView.flashDutyCycle displayedBpm = shoeGaze.clock.bpm try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds) } } } // MARK: - Subviews private var led: some View { Circle() .fill(ledOn ? Color.red : Color.red.opacity(0.15)) .frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter) } private var tapArea: some View { Button { shoeGaze.tapTempo() displayedBpm = shoeGaze.clock.bpm } label: { Text("TAP") .font(.system(size: 14, weight: .bold, design: .rounded)) .frame(width: TempoView.tapAreaSize, height: TempoView.tapAreaSize) .background(Color.white.opacity(0.08)) .clipShape(Circle()) } .buttonStyle(.plain) .foregroundStyle(Color.white) } }