Repository Public
1// ORIX Sonata2// File: Packages/SonataUI/Sources/SonataDesign/Controls.swift3// Description: Reusable controls: panel chrome, level meter, dB fader, pan control, toggle chips,4// status badge. All are keyboard-operable and expose value and label to VoiceOver.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI910// MARK: Panel chrome1112/// A titled panel: header strip with optional trailing accessory, content below.13public struct Panel<Accessory: View, Content: View>: View {14 let title: LocalizedStringKey15 let systemImage: String?16 @ViewBuilder var accessory: () -> Accessory17 @ViewBuilder var content: () -> Content1819 public init(_ title: LocalizedStringKey, systemImage: String? = nil, @ViewBuilder accessory: @escaping () -> Accessory = { EmptyView() }, @ViewBuilder content: @escaping () -> Content) {20 self.title = title21 self.systemImage = systemImage22 self.accessory = accessory23 self.content = content24 }2526 public var body: some View {27 VStack(spacing: 0) {28 HStack(spacing: 6) {29 if let systemImage { Image(systemName: systemImage).foregroundStyle(Sonata.textSecondary).imageScale(.small).accessibilityHidden(true) }30 Text(title).font(Sonata.label).foregroundStyle(Sonata.textSecondary).textCase(.uppercase).kerning(0.4)31 Spacer(minLength: 8)32 accessory()33 }34 .padding(.horizontal, 10)35 .frame(height: 28)36 .background(Sonata.well)37 Divider().overlay(Sonata.hairline)38 content().frame(maxWidth: .infinity, maxHeight: .infinity)39 }40 .background(Sonata.panel)41 .clipShape(RoundedRectangle(cornerRadius: Sonata.corner, style: .continuous))42 .overlay(RoundedRectangle(cornerRadius: Sonata.corner, style: .continuous).strokeBorder(Sonata.hairline))43 .accessibilityElement(children: .contain)44 }45}4647// MARK: Level meter4849/// Maps dBFS to 0...1 on a scale that gives the top 24 dB two thirds of the height.50public enum MeterScale {51 public static let floor: Double = -6052 public static func position(db: Double) -> Double {53 if !db.isFinite || db <= floor { return 0 }54 if db >= 6 { return 1 }55 // Piecewise linear: -60...-24 -> 0...1/3, -24...+6 -> 1/3...156 return db < -24 ? (db - floor) / (36 * 3) : 1.0 / 3 + (db + 24) / 30 * (2.0 / 3)57 }58 public static func db(position p: Double) -> Double {59 let p = min(max(p, 0), 1)60 return p < 1.0 / 3 ? floor + p * 108 : -24 + (p - 1.0 / 3) * 4561 }62}6364/// A stereo peak/RMS meter. Values are linear amplitudes measured by the engine; the view only draws.65public struct LevelMeter: View {66 public var peakLeft: Double67 public var peakRight: Double68 public var rmsLeft: Double69 public var rmsRight: Double70 public var holdLeft: Double71 public var holdRight: Double72 public var vertical: Bool7374 public init(peakLeft: Double, peakRight: Double, rmsLeft: Double = 0, rmsRight: Double = 0, holdLeft: Double = 0, holdRight: Double = 0, vertical: Bool = true) {75 self.peakLeft = peakLeft76 self.peakRight = peakRight77 self.rmsLeft = rmsLeft78 self.rmsRight = rmsRight79 self.holdLeft = holdLeft80 self.holdRight = holdRight81 self.vertical = vertical82 }8384 public var body: some View {85 Canvas { ctx, size in86 let channels = [(peakLeft, rmsLeft, holdLeft), (peakRight, rmsRight, holdRight)]87 let gap: CGFloat = 288 let across = vertical ? size.width : size.height89 let along = vertical ? size.height : size.width90 let bar = (across - gap) / 291 for (i, c) in channels.enumerated() {92 let origin = CGFloat(i) * (bar + gap)93 func rect(_ from: Double, _ to: Double) -> CGRect {94 let a = CGFloat(from) * along, b = CGFloat(to) * along95 return vertical ? CGRect(x: origin, y: along - b, width: bar, height: b - a) : CGRect(x: a, y: origin, width: b - a, height: bar)96 }97 ctx.fill(Path(roundedRect: rect(0, 1), cornerRadius: 1.5), with: .color(Sonata.well))98 let p = MeterScale.position(db: Format.linearToDb(c.0))99 // Three zones: below -12, -12...-3, above -3 dBFS.100 let z1 = MeterScale.position(db: -12), z2 = MeterScale.position(db: -3)101 if p > 0 { ctx.fill(Path(rect(0, min(p, z1))), with: .color(Sonata.meterLow.opacity(0.55))) }102 if p > z1 { ctx.fill(Path(rect(z1, min(p, z2))), with: .color(Sonata.meterMid.opacity(0.65))) }103 if p > z2 { ctx.fill(Path(rect(z2, p)), with: .color(Sonata.meterHigh.opacity(0.75))) }104 let r = MeterScale.position(db: Format.linearToDb(c.1))105 if r > 0 {106 if r > 0 { ctx.fill(Path(rect(0, min(r, z1))), with: .color(Sonata.meterLow)) }107 if r > z1 { ctx.fill(Path(rect(z1, min(r, z2))), with: .color(Sonata.meterMid)) }108 if r > z2 { ctx.fill(Path(rect(z2, r)), with: .color(Sonata.meterHigh)) }109 }110 let h = MeterScale.position(db: Format.linearToDb(c.2))111 if h > 0.01 {112 let color = h > z2 ? Sonata.meterHigh : (h > z1 ? Sonata.meterMid : Sonata.meterLow)113 ctx.fill(Path(rect(max(0, h - 1.5 / Double(along)), h)), with: .color(color))114 }115 }116 }117 .accessibilityElement()118 .accessibilityLabel(Text("Level"))119 .accessibilityValue(Text("\(Format.db(Format.linearToDb(max(peakLeft, peakRight))))"))120 }121}122123// MARK: Fader124125/// A vertical dB fader. Drag, scroll-free; double-click resets to 0 dB; arrow keys step 0.5 dB126/// (with Shift 0.1 dB). The value is the fader gain in dB; the minimum position is -∞.127public struct Fader: View {128 @Binding var db: Double129 public var range: ClosedRange<Double>130 public var label: String131 public var onEditingChanged: (Bool) -> Void132133 @FocusState private var focused: Bool134 @State private var dragStart: Double?135136 public init(db: Binding<Double>, range: ClosedRange<Double> = -60...12, label: String, onEditingChanged: @escaping (Bool) -> Void = { _ in }) {137 _db = db138 self.range = range139 self.label = label140 self.onEditingChanged = onEditingChanged141 }142143 /// 0...1, with 0 dB at 75 % of the travel and an audio taper below.144 static func position(db: Double, range: ClosedRange<Double>) -> Double {145 if db <= range.lowerBound { return 0 }146 if db >= 0 { return 0.75 + 0.25 * min(1, db / max(range.upperBound, 0.001)) }147 return 0.75 * pow(1 - db / range.lowerBound, 2.2)148 }149150 static func db(position p: Double, range: ClosedRange<Double>) -> Double {151 let p = min(max(p, 0), 1)152 if p >= 0.75 { return (p - 0.75) / 0.25 * range.upperBound }153 if p <= 0.0005 { return range.lowerBound }154 return range.lowerBound * (1 - pow(p / 0.75, 1 / 2.2))155 }156157 public var body: some View {158 GeometryReader { geo in159 let h = geo.size.height160 let knobH: CGFloat = 22161 let travel = max(1, h - knobH)162 let p = Self.position(db: db, range: range)163 ZStack(alignment: .top) {164 RoundedRectangle(cornerRadius: 2).fill(Sonata.well).frame(width: 4).frame(maxHeight: .infinity).padding(.vertical, knobH / 2)165 // 0 dB tick166 Rectangle().fill(Sonata.gridMajor).frame(width: 14, height: 1).offset(y: knobH / 2 + travel * 0.25)167 RoundedRectangle(cornerRadius: 3, style: .continuous)168 .fill(Sonata.panel)169 .overlay(RoundedRectangle(cornerRadius: 3, style: .continuous).strokeBorder(focused ? Sonata.accent : Sonata.hairline, lineWidth: focused ? 1.5 : 1))170 .overlay(Rectangle().fill(Sonata.accent).frame(height: 2))171 .shadow(color: .black.opacity(0.18), radius: 1.5, y: 1)172 .frame(width: 26, height: knobH)173 .offset(y: travel * (1 - p))174 }175 .frame(maxWidth: .infinity)176 .contentShape(Rectangle())177 .gesture(178 DragGesture(minimumDistance: 0)179 .onChanged { g in180 if dragStart == nil {181 dragStart = Self.position(db: db, range: range)182 onEditingChanged(true)183 }184 let fine: Double = NSEvent.modifierFlags.contains(.shift) ? 0.2 : 1185 let np = (dragStart ?? 0) - Double(g.translation.height / travel) * fine186 db = (Self.db(position: np, range: range) * 10).rounded() / 10187 }188 .onEnded { _ in189 dragStart = nil190 onEditingChanged(false)191 }192 )193 .simultaneousGesture(TapGesture(count: 2).onEnded {194 onEditingChanged(true)195 db = 0196 onEditingChanged(false)197 })198 }199 .frame(minWidth: 28)200 .focusable()201 .focused($focused)202 .onKeyPress(keys: [.upArrow, .downArrow]) { press in203 let step = press.modifiers.contains(.shift) ? 0.1 : 0.5204 onEditingChanged(true)205 db = min(range.upperBound, max(range.lowerBound, db + (press.key == .upArrow ? step : -step)))206 onEditingChanged(false)207 return .handled208 }209 .accessibilityElement()210 .accessibilityLabel(Text(label))211 .accessibilityValue(Text(Format.db(db, floor: range.lowerBound)))212 .accessibilityAdjustableAction { direction in213 onEditingChanged(true)214 db = min(range.upperBound, max(range.lowerBound, db + (direction == .increment ? 1 : -1)))215 onEditingChanged(false)216 }217 }218}219220// MARK: Pan221222/// A horizontal pan control, -1 (left) ... +1 (right), double-click to centre.223public struct PanControl: View {224 @Binding var pan: Double225 public var label: String226 public var onEditingChanged: (Bool) -> Void227 @FocusState private var focused: Bool228 @State private var dragging = false229230 public init(pan: Binding<Double>, label: String, onEditingChanged: @escaping (Bool) -> Void = { _ in }) {231 _pan = pan232 self.label = label233 self.onEditingChanged = onEditingChanged234 }235236 public static func text(_ pan: Double) -> String {237 abs(pan) < 0.005 ? "C" : (pan < 0 ? "L\(Int((-pan * 100).rounded()))" : "R\(Int((pan * 100).rounded()))")238 }239240 public var body: some View {241 GeometryReader { geo in242 let w = geo.size.width243 ZStack(alignment: .leading) {244 Capsule().fill(Sonata.well)245 let mid = w / 2246 let x = mid + CGFloat(pan) * (mid - 3)247 Rectangle().fill(Sonata.accent.opacity(0.55)).frame(width: abs(x - mid), height: geo.size.height).offset(x: min(x, mid))248 Rectangle().fill(Sonata.gridMajor).frame(width: 1).offset(x: mid)249 Capsule().fill(Sonata.accent).frame(width: 3).offset(x: x - 1.5)250 }251 .clipShape(Capsule())252 .overlay(Capsule().strokeBorder(focused ? Sonata.accent : Sonata.hairline))253 .contentShape(Rectangle())254 .gesture(DragGesture(minimumDistance: 0).onChanged { g in255 if !dragging {256 dragging = true257 onEditingChanged(true)258 }259 let v = Double((g.location.x - w / 2) / (w / 2 - 3))260 pan = abs(v) < 0.04 ? 0 : min(1, max(-1, (v * 100).rounded() / 100))261 }.onEnded { _ in262 dragging = false263 onEditingChanged(false)264 })265 .simultaneousGesture(TapGesture(count: 2).onEnded {266 onEditingChanged(true)267 pan = 0268 onEditingChanged(false)269 })270 }271 .frame(height: 12)272 .focusable()273 .focused($focused)274 .onKeyPress(keys: [.leftArrow, .rightArrow]) { press in275 onEditingChanged(true)276 pan = min(1, max(-1, pan + (press.key == .rightArrow ? 0.05 : -0.05)))277 onEditingChanged(false)278 return .handled279 }280 .accessibilityElement()281 .accessibilityLabel(Text(label))282 .accessibilityValue(Text(Self.text(pan)))283 .accessibilityAdjustableAction { direction in284 onEditingChanged(true)285 pan = min(1, max(-1, pan + (direction == .increment ? 0.1 : -0.1)))286 onEditingChanged(false)287 }288 }289}290291// MARK: Chips and badges292293/// A small latching button (M, S, bypass...).294public struct ToggleChip: View {295 @Binding var isOn: Bool296 let text: String297 let tint: Color298 let help: LocalizedStringKey299300 public init(_ text: String, isOn: Binding<Bool>, tint: Color, help: LocalizedStringKey) {301 self.text = text302 _isOn = isOn303 self.tint = tint304 self.help = help305 }306307 public var body: some View {308 Button {309 isOn.toggle()310 } label: {311 Text(text)312 .font(.system(size: 10, weight: .bold))313 .frame(width: 20, height: 18)314 .foregroundStyle(isOn ? Color.black.opacity(0.85) : Sonata.textSecondary)315 .background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(isOn ? tint : Sonata.well))316 .overlay(RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(Sonata.hairline))317 }318 .buttonStyle(.plain)319 .help(help)320 .accessibilityLabel(Text(help))321 .accessibilityAddTraits(isOn ? [.isSelected] : [])322 }323}324325/// A dot and a word describing a state (idle, compiling, ready, playing, rendering, failed).326public struct StatusBadge: View {327 let text: LocalizedStringKey328 let color: Color329 let busy: Bool330331 public init(_ text: LocalizedStringKey, color: Color, busy: Bool = false) {332 self.text = text333 self.color = color334 self.busy = busy335 }336337 public var body: some View {338 HStack(spacing: 5) {339 if busy {340 ProgressView().controlSize(.mini)341 } else {342 Circle().fill(color).frame(width: 7, height: 7)343 }344 Text(text).font(Sonata.label).foregroundStyle(Sonata.textSecondary)345 }346 .padding(.horizontal, 8)347 .frame(height: 22)348 .background(Capsule().fill(Sonata.well))349 .accessibilityElement(children: .combine)350 }351}352353/// A labelled read-out: caption above, monospaced value below.354public struct Readout: View {355 let caption: LocalizedStringKey356 let value: String357358 public init(_ caption: LocalizedStringKey, _ value: String) {359 self.caption = caption360 self.value = value361 }362363 public var body: some View {364 VStack(alignment: .leading, spacing: 1) {365 Text(caption).font(Sonata.caption).foregroundStyle(Sonata.textTertiary)366 Text(value).font(Sonata.value).foregroundStyle(Sonata.text).lineLimit(1)367 }368 .accessibilityElement(children: .combine)369 }370}371372/// Placeholder shown where content is honestly unavailable (no program compiled, nothing playing).373public struct EmptyState: View {374 let title: LocalizedStringKey375 let message: LocalizedStringKey376 let systemImage: String377378 public init(_ title: LocalizedStringKey, message: LocalizedStringKey, systemImage: String) {379 self.title = title380 self.message = message381 self.systemImage = systemImage382 }383384 public var body: some View {385 VStack(spacing: 8) {386 Image(systemName: systemImage).font(.system(size: 28, weight: .light)).foregroundStyle(Sonata.textTertiary).accessibilityHidden(true)387 Text(title).font(Sonata.title).foregroundStyle(Sonata.text)388 Text(message).font(.system(size: 12)).foregroundStyle(Sonata.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 360)389 }390 .padding(24)391 .frame(maxWidth: .infinity, maxHeight: .infinity)392 .accessibilityElement(children: .combine)393 }394}395