SPB Git

Repository Public

Components.swift 16.4 KB 348 lines swift

1// ORIX DJ2// File: App/Sources/DesignSystem/Components.swift3// Description: Reusable controls of the ORIX DJ interface: knob, faders, level meter, pads and panels. Every control4//              is keyboard and VoiceOver adjustable and reports its value in words.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011/// A card surface.12struct Panel<Content: View>: View {13    var padding: CGFloat = ORIX.Space.sm14    @ViewBuilder var content: Content1516    var body: some View {17        content18            .frame(maxWidth: .infinity, alignment: .leading)19            .padding(padding)20            .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous))21            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))22    }23}2425struct SectionLabel: View {26    var text: LocalizedStringKey27    init(_ text: LocalizedStringKey) { self.text = text }28    var body: some View { Text(text).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).textCase(.uppercase) }29}3031/// Rotary control. Drag vertically, scroll, or use the arrow keys; double-click resets.32struct Knob: View {33    var label: LocalizedStringKey34    var value: Double35    var display: String36    var tint: Color = ORIX.Palette.accent37    /// Draws the arc from the centre (EQ, filter, pan) instead of from the minimum.38    var bipolar = false39    var size: CGFloat = 4040    /// Shows the value under the label. Dense layouts hide it; it stays in the tooltip and for VoiceOver.41    var showsValue = true42    var onChange: (Double) -> Void43    var onReset: () -> Void = {}4445    @State private var dragStart: Double?46    @FocusState private var focused: Bool4748    var body: some View {49        VStack(spacing: showsValue ? 3 : 1) {50            ZStack {51                Circle().fill(ORIX.Palette.surfaceRaised)52                Circle().trim(from: 0, to: 0.75).stroke(ORIX.Palette.hairline, style: StrokeStyle(lineWidth: 3, lineCap: .round)).rotationEffect(.degrees(135))53                arc.stroke(tint, style: StrokeStyle(lineWidth: 3, lineCap: .round)).rotationEffect(.degrees(135))54                Capsule().fill(ORIX.Palette.textPrimary).frame(width: 2.5, height: size * 0.28).offset(y: -size * 0.2).rotationEffect(.degrees(-135 + 270 * value))55            }56            .frame(width: size, height: size)57            .overlay(Circle().strokeBorder(focused ? tint : .clear, lineWidth: 1.5).padding(-3))58            .contentShape(Circle())59            .gesture(DragGesture(minimumDistance: 1).onChanged { g in60                if dragStart == nil { dragStart = value }61                let fine = NSEvent.modifierFlags.contains(.shift) ? 0.25 : 162                onChange(min(1, max(0, (dragStart ?? value) - Double(g.translation.height) / 160 * fine)))63            }.onEnded { _ in dragStart = nil })64            .onTapGesture(count: 2) { onReset() }65            .focusable()66            .focused($focused)67            .onKeyPress(.upArrow) { onChange(min(1, value + 0.02)); return .handled }68            .onKeyPress(.downArrow) { onChange(max(0, value - 0.02)); return .handled }69            .onKeyPress(.rightArrow) { onChange(min(1, value + 0.02)); return .handled }70            .onKeyPress(.leftArrow) { onChange(max(0, value - 0.02)); return .handled }71            .onKeyPress(.delete) { onReset(); return .handled }72            .background(ScrollWheel { delta in onChange(min(1, max(0, value + delta / 300))) })73            Text(label).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).minimumScaleFactor(0.7)74            if showsValue { Text(display).font(.system(size: 10).monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).minimumScaleFactor(0.7) }75        }76        .frame(minWidth: size + 8)77        .help(Text(verbatim: display))78        .accessibilityElement(children: .ignore)79        .accessibilityLabel(label)80        .accessibilityValue(display)81        .accessibilityAdjustableAction { direction in82            switch direction {83            case .increment: onChange(min(1, value + 0.05))84            case .decrement: onChange(max(0, value - 0.05))85            @unknown default: break86            }87        }88    }8990    private var arc: some Shape {91        let from = bipolar ? min(0.5, value) : 092        let to = bipolar ? max(0.5, value) : value93        return Circle().trim(from: from * 0.75, to: max(from * 0.75 + 0.001, to * 0.75))94    }95}9697/// Reports scroll-wheel movement over a control.98private struct ScrollWheel: NSViewRepresentable {99    var onScroll: (Double) -> Void100101    func makeNSView(context: Context) -> ScrollView { let v = ScrollView(); v.onScroll = onScroll; return v }102    func updateNSView(_ view: ScrollView, context: Context) { view.onScroll = onScroll }103104    final class ScrollView: NSView {105        var onScroll: ((Double) -> Void)?106        override func scrollWheel(with event: NSEvent) {107            if abs(event.scrollingDeltaY) > abs(event.scrollingDeltaX) { onScroll?(Double(event.scrollingDeltaY) * (event.hasPreciseScrollingDeltas ? 1 : 8)) } else { super.scrollWheel(with: event) }108        }109    }110}111112/// Vertical or horizontal fader.113struct Fader: View {114    var label: LocalizedStringKey115    var value: Double116    var display: String117    var tint: Color = ORIX.Palette.accent118    var horizontal = false119    /// Marks the centre (crossfader, tempo).120    var centreDetent = false121    var onChange: (Double) -> Void122    var onReset: () -> Void = {}123124    @State private var dragStart: Double?125    @FocusState private var focused: Bool126127    var body: some View {128        GeometryReader { geo in129            let length = horizontal ? geo.size.width : geo.size.height130            let cap: CGFloat = horizontal ? 26 : 22131            let travel = max(1, length - cap)132            ZStack(alignment: horizontal ? .leading : .bottom) {133                RoundedRectangle(cornerRadius: 3).fill(ORIX.Palette.well)134                    .frame(width: horizontal ? nil : 6, height: horizontal ? 6 : nil)135                    .frame(maxWidth: .infinity, maxHeight: .infinity)136                if centreDetent {137                    Rectangle().fill(ORIX.Palette.textTertiary).frame(width: horizontal ? 1 : 14, height: horizontal ? 14 : 1).frame(maxWidth: .infinity, maxHeight: .infinity)138                }139                RoundedRectangle(cornerRadius: 4, style: .continuous)140                    .fill(ORIX.Palette.surfaceRaised)141                    .overlay(RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(focused ? tint : ORIX.Palette.hairline, lineWidth: 1))142                    .overlay(Rectangle().fill(tint).frame(width: horizontal ? 2 : nil, height: horizontal ? nil : 2).padding(horizontal ? .vertical : .horizontal, 4))143                    .frame(width: horizontal ? cap : min(geo.size.width, 34), height: horizontal ? min(geo.size.height, 30) : cap)144                    .offset(x: horizontal ? travel * value : 0, y: horizontal ? 0 : -travel * value)145                    .frame(maxWidth: horizontal ? nil : .infinity, maxHeight: horizontal ? .infinity : nil)146            }147            .contentShape(Rectangle())148            .gesture(DragGesture(minimumDistance: 0).onChanged { g in149                if dragStart == nil {150                    // A click on the cap drags it; a click elsewhere on the track jumps there.151                    let click = horizontal ? Double((g.startLocation.x - cap / 2) / travel) : 1 - Double((g.startLocation.y - cap / 2) / travel)152                    dragStart = abs(click - value) < Double(cap / travel) ? value : min(1, max(0, click))153                }154                let delta = horizontal ? Double(g.translation.width / travel) : -Double(g.translation.height / travel)155                onChange(min(1, max(0, (dragStart ?? value) + delta * (NSEvent.modifierFlags.contains(.shift) ? 0.25 : 1))))156            }.onEnded { _ in dragStart = nil })157            .onTapGesture(count: 2) { onReset() }158        }159        .focusable()160        .focused($focused)161        .onKeyPress(horizontal ? .rightArrow : .upArrow) { onChange(min(1, value + 0.02)); return .handled }162        .onKeyPress(horizontal ? .leftArrow : .downArrow) { onChange(max(0, value - 0.02)); return .handled }163        .background(ScrollWheel { delta in onChange(min(1, max(0, value + delta / 300))) })164        .accessibilityElement(children: .ignore)165        .accessibilityLabel(label)166        .accessibilityValue(display)167        .accessibilityAdjustableAction { direction in168            switch direction {169            case .increment: onChange(min(1, value + 0.05))170            case .decrement: onChange(max(0, value - 0.05))171            @unknown default: break172            }173        }174    }175}176177/// Peak meter with a dB scale. Colour changes are doubled by position, and clipping is announced in words.178struct LevelMeter: View {179    var label: LocalizedStringKey180    /// Linear peak.181    var level: Float182    var clipped = false183    var horizontal = false184185    private var fraction: Double {186        // -48 dB ... +6 dB mapped to 0 ... 1.187        let db = Double(linearToDB(level))188        return min(1, max(0, (db + 48) / 54))189    }190191    var body: some View {192        Canvas { context, size in193            let rect = CGRect(origin: .zero, size: size)194            context.fill(Path(roundedRect: rect, cornerRadius: 2), with: .color(ORIX.Palette.well))195            let zero = 48.0 / 54.0, yellow = 42.0 / 54.0196            func segment(_ from: Double, _ to: Double, _ color: Color) {197                let a = min(fraction, to), b = from198                guard a > b else { return }199                let r = horizontal ? CGRect(x: size.width * b, y: 0, width: size.width * (a - b), height: size.height)200                    : CGRect(x: 0, y: size.height * (1 - a), width: size.width, height: size.height * (a - b))201                context.fill(Path(r), with: .color(color))202            }203            segment(0, yellow, ORIX.Palette.success)204            segment(yellow, zero, ORIX.Palette.warning)205            segment(zero, 1, ORIX.Palette.danger)206            // 0 dBFS mark.207            let mark = horizontal ? CGRect(x: size.width * zero, y: 0, width: 1, height: size.height) : CGRect(x: 0, y: size.height * (1 - zero), width: size.width, height: 1)208            context.fill(Path(mark), with: .color(ORIX.Palette.textTertiary))209        }210        .accessibilityElement(children: .ignore)211        .accessibilityLabel(label)212        .accessibilityValue(clipped ? Text("clipping") : Text("\(Int(linearToDB(level).rounded())) decibels"))213    }214}215216/// A latching button (sync, key lock, cue…). State is shown by fill and by an accessibility trait, not by colour alone.217struct ToggleChip: View {218    var title: LocalizedStringKey219    var symbol: String?220    var isOn: Bool221    var tint: Color = ORIX.Palette.accent222    var action: () -> Void223224    var body: some View {225        Button(action: action) {226            HStack(spacing: 4) {227                if let symbol { Image(systemName: symbol).font(.system(size: 10, weight: .bold)).accessibilityHidden(true) }228                Text(title).font(.system(size: 11, weight: .semibold)).lineLimit(1)229            }230            .padding(.horizontal, 8).frame(minHeight: 24)231            .foregroundStyle(isOn ? ORIX.Palette.onTint : ORIX.Palette.textPrimary)232            .background(isOn ? AnyShapeStyle(tint) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))233            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous).strokeBorder(isOn ? tint : ORIX.Palette.hairline, lineWidth: 1))234        }235        .buttonStyle(.plain)236        .accessibilityAddTraits(isOn ? [.isSelected] : [])237        .accessibilityValue(isOn ? Text("on") : Text("off"))238    }239}240241/// A momentary button.242struct PadButton: View {243    var title: String244    var symbol: String?245    var tint: Color = ORIX.Palette.textPrimary246    var filled = false247    var minWidth: CGFloat = 30248    var height: CGFloat = 26249    var action: () -> Void250251    var body: some View {252        Button(action: action) {253            HStack(spacing: 4) {254                if let symbol { Image(systemName: symbol).font(.system(size: 11, weight: .bold)).accessibilityHidden(true) }255                if !title.isEmpty { Text(verbatim: title).font(.system(size: 11, weight: .semibold).monospacedDigit()).lineLimit(1).minimumScaleFactor(0.7) }256            }257            .padding(.horizontal, 6).frame(minWidth: minWidth, minHeight: height)258            .foregroundStyle(filled ? ORIX.Palette.onTint : tint)259            .background(filled ? AnyShapeStyle(tint) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))260            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous).strokeBorder(filled ? tint : ORIX.Palette.hairline, lineWidth: 1))261        }262        .buttonStyle(.plain)263    }264}265266/// Small coloured square with the deck letter, so a deck is never identified by colour alone.267struct DeckBadge: View {268    var index: Int269    var size: CGFloat = 20270    var body: some View {271        Text(verbatim: deckLetters[index])272            .font(.system(size: size * 0.6, weight: .heavy, design: .rounded))273            .foregroundStyle(ORIX.Palette.onTint)274            .frame(width: size, height: size)275            .background(ORIX.deck(index), in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous))276            .accessibilityLabel(Text("Deck \(deckLetters[index])"))277    }278}279280/// Empty-state message with an optional action.281struct EmptyState: View {282    var symbol: String283    var title: LocalizedStringKey284    var message: LocalizedStringKey285    var actionTitle: LocalizedStringKey?286    var action: (() -> Void)?287288    var body: some View {289        VStack(spacing: ORIX.Space.xs) {290            Image(systemName: symbol).font(.system(size: 30, weight: .light)).foregroundStyle(ORIX.Palette.textTertiary)291            Text(title).font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary)292            Text(message).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 420)293            if let actionTitle, let action { Button(actionTitle, action: action).controlSize(.regular).padding(.top, 4) }294        }295        .padding(ORIX.Space.lg)296        .frame(maxWidth: .infinity, maxHeight: .infinity)297    }298}299300/// A knob bound to an engine parameter.301struct ParamKnob: View {302    @Environment(AppModel.self) private var model303    var label: LocalizedStringKey304    var address: ParamAddress305    var tint: Color = ORIX.Palette.accent306    var bipolar = false307    var size: CGFloat = 40308    var showsValue = true309310    var body: some View {311        Knob(label: label, value: model.position(address), display: model.display(address), tint: tint, bipolar: bipolar, size: size, showsValue: showsValue,312             onChange: { model.setPosition(address, $0) }, onReset: { model.reset(address) })313    }314}315316/// Lays children out left to right and wraps to a new line when the row is full.317struct FlowLayout: Layout {318    var spacing: CGFloat = 4319    var lineSpacing: CGFloat = 4320321    private func arrange(_ subviews: Subviews, width: CGFloat) -> (size: CGSize, origins: [CGPoint]) {322        var origins: [CGPoint] = []323        var x: CGFloat = 0, y: CGFloat = 0, lineHeight: CGFloat = 0, widest: CGFloat = 0324        for view in subviews {325            let size = view.sizeThatFits(.unspecified)326            if x > 0, x + size.width > width { x = 0; y += lineHeight + lineSpacing; lineHeight = 0 }327            origins.append(CGPoint(x: x, y: y))328            x += size.width + spacing329            lineHeight = max(lineHeight, size.height)330            widest = max(widest, x - spacing)331        }332        return (CGSize(width: widest, height: y + lineHeight), origins)333    }334335    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {336        let result = arrange(subviews, width: proposal.width ?? .infinity)337        return CGSize(width: proposal.width.map { min($0, max(result.size.width, 0)) } ?? result.size.width, height: result.size.height)338    }339340    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {341        let result = arrange(subviews, width: bounds.width)342        for (view, origin) in zip(subviews, result.origins) {343            // Centre each child on its line's first-row height.344            view.place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)345        }346    }347}348
Files main
Menu

Theme