SPB Git

Repository Public License

EditorComponents.swift 11.9 KB 288 lines swift

1// ORIX Alarm2// File: App/Features/Editor/EditorComponents.swift3// Description: Small building blocks shared by the alarm editor and Alarm Studio: section cards, toggle rows, value steppers, notes, sound tiles, day tint.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Colours and symbols that follow the hour of the day: deep night, sunrise, daylight, dusk.11enum DayTint {12    private static let stops: [(hour: Double, color: Color)] = [13        (0, Theme.indigo), (4, Theme.violet), (5.5, Theme.ember), (7, Theme.sunrise), (9, Theme.gold), (13, Theme.peach),14        (17, Theme.gold), (18.5, Theme.sunrise), (20, Theme.ember), (21.5, Theme.violet), (24, Theme.indigo),15    ]1617    /// Ring colour for an hour in 0..<24 (fractional hours allowed).18    static func color(hour: Double) -> Color {19        let h = (hour.truncatingRemainder(dividingBy: 24) + 24).truncatingRemainder(dividingBy: 24)20        guard let upper = stops.firstIndex(where: { $0.hour >= h }), upper > 0 else { return stops[0].color }21        let a = stops[upper - 1], b = stops[upper]22        return a.color.mix(with: b.color, by: (h - a.hour) / (b.hour - a.hour))23    }2425    /// Gradient stops for a full 24-hour ring starting at midnight.26    static var ringStops: [Gradient.Stop] { stops.map { Gradient.Stop(color: $0.color, location: $0.hour / 24) } }2728    /// Background warmth (0 night ... about 0.6 morning) for `AuroraBackground`.29    static func warmth(hour: Double) -> Double {30        switch hour {31        case 5..<7: return 0.25 + 0.35 * (hour - 5) / 232        case 7..<10: return 0.6033        case 10..<17: return 0.4234        case 17..<20: return 0.42 - 0.30 * (hour - 17) / 335        default: return 0.0636        }37    }3839    static func symbol(hour: Int) -> String {40        switch hour {41        case 5..<8: "sunrise.fill"42        case 8..<17: "sun.max.fill"43        case 17..<20: "sunset.fill"44        default: "moon.stars.fill"45        }46    }4748    static func phaseName(hour: Int) -> String {49        switch hour {50        case 5..<8: String(localized: "Sunrise hours")51        case 8..<12: String(localized: "Morning")52        case 12..<17: String(localized: "Afternoon")53        case 17..<20: String(localized: "Evening")54        default: String(localized: "Night")55        }56    }57}5859/// Glass card with an icon and title header.60struct EditorCard<Content: View>: View {61    let title: LocalizedStringKey62    let symbol: String63    var tint: Color = Theme.sunrise64    @ViewBuilder var content: Content6566    var body: some View {67        VStack(alignment: .leading, spacing: 16) {68            HStack(spacing: 10) {69                Image(systemName: symbol).font(.system(size: 14, weight: .semibold)).foregroundStyle(tint)70                    .frame(width: 30, height: 30)71                    .background(tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 9, style: .continuous))72                    .accessibilityHidden(true)73                Text(title).font(.orixHeadline).accessibilityAddTraits(.isHeader)74                Spacer(minLength: 0)75            }76            content77        }78        .frame(maxWidth: .infinity, alignment: .leading)79        .glassCard()80    }81}8283struct ToggleRow: View {84    let title: LocalizedStringKey85    var detail: LocalizedStringKey? = nil86    @Binding var isOn: Bool8788    var body: some View {89        Toggle(isOn: $isOn) {90            VStack(alignment: .leading, spacing: 3) {91                Text(title).font(.orixBody)92                if let detail {93                    Text(detail).font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)94                }95            }96        }97        .tint(Theme.sunrise)98        .frame(minHeight: 44)99        .onChange(of: isOn) { Haptics.play(.selection) }100    }101}102103/// Minus / value / plus row, exposed to assistive technologies as one adjustable element.104struct ValueStepper: View {105    let title: LocalizedStringKey106    let value: String107    var canDecrement = true108    var canIncrement = true109    let onDecrement: () -> Void110    let onIncrement: () -> Void111112    var body: some View {113        HStack(spacing: 8) {114            Text(title).font(.orixBody)115            Spacer(minLength: 8)116            button("minus", enabled: canDecrement, action: onDecrement)117            Text(value).font(.system(.body, design: .rounded, weight: .semibold)).monospacedDigit()118                .frame(minWidth: 62).contentTransition(.numericText())119            button("plus", enabled: canIncrement, action: onIncrement)120        }121        .frame(minHeight: 44)122        .accessibilityElement(children: .ignore)123        .accessibilityLabel(title)124        .accessibilityValue(value)125        .accessibilityAdjustableAction { direction in126            switch direction {127            case .increment: if canIncrement { onIncrement() }128            case .decrement: if canDecrement { onDecrement() }129            @unknown default: break130            }131        }132    }133134    private func button(_ symbol: String, enabled: Bool, action: @escaping () -> Void) -> some View {135        Button {136            Haptics.play(.tick)137            withAnimation(.snappy(duration: 0.2)) { action() }138        } label: {139            Image(systemName: symbol).font(.system(size: 15, weight: .bold))140                .frame(width: 44, height: 44)141                .background(Theme.surfaceRaised, in: Circle())142                .overlay(Circle().strokeBorder(Theme.hairline))143        }144        .buttonStyle(.plain)145        .buttonRepeatBehavior(.enabled)146        .disabled(!enabled)147        .opacity(enabled ? 1 : 0.35)148    }149}150151/// Quiet explanatory note with a leading symbol.152struct InfoNote: View {153    var symbol = "info.circle.fill"154    var tint: Color = Theme.azure155    let text: LocalizedStringKey156157    var body: some View {158        HStack(alignment: .top, spacing: 10) {159            Image(systemName: symbol).font(.footnote).foregroundStyle(tint).padding(.top, 1).accessibilityHidden(true)160            Text(text).font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)161            Spacer(minLength: 0)162        }163        .padding(12)164        .background(tint.opacity(0.10), in: RoundedRectangle(cornerRadius: 14, style: .continuous))165        .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(tint.opacity(0.22)))166        .accessibilityElement(children: .combine)167    }168}169170extension SoundAsset.Category {171    var symbol: String {172        switch self {173        case .gentlePiano: "pianokeys"174        case .ambientSunrise: "sun.haze.fill"175        case .rain: "cloud.rain.fill"176        case .forest: "tree.fill"177        case .ocean: "water.waves"178        case .softElectronic: "waveform"179        case .classicAlarm: "bell.fill"180        case .energeticWake: "bolt.fill"181        case .minimalTones: "dot.radiowaves.left.and.right"182        }183    }184}185186/// Horizontal strip of selectable sound tiles with a preview button on each.187struct SoundStrip: View {188    let sounds: [SoundAsset]189    @Binding var selection: String190    let idPrefix: String191    private var player: SoundPlayer { SoundPlayer.shared }192193    var body: some View {194        ScrollView(.horizontal, showsIndicators: false) {195            HStack(spacing: 10) {196                ForEach(sounds) { sound in tile(sound) }197            }198            .padding(.horizontal, 18)199        }200        .padding(.horizontal, -18)201    }202203    private func tile(_ sound: SoundAsset) -> some View {204        let isSelected = selection == sound.id205        let isPlaying = player.previewingID == sound.id206        return VStack(alignment: .leading, spacing: 8) {207            HStack(alignment: .top) {208                Image(systemName: sound.category.symbol).font(.system(size: 18, weight: .medium))209                    .foregroundStyle(isSelected ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.textSecondary))210                    .frame(height: 28)211                    .accessibilityHidden(true)212                Spacer(minLength: 0)213                Button {214                    Haptics.play(.selection)215                    if sound.isSoundscape { player.togglePreview(soundscapeID: sound.id) } else { player.togglePreview(alarmSoundID: sound.id) }216                } label: {217                    Image(systemName: isPlaying ? "stop.fill" : "play.fill").font(.system(size: 12, weight: .bold))218                        .foregroundStyle(isPlaying ? Theme.midnight : Theme.textPrimary)219                        .frame(width: 32, height: 32)220                        .background(isPlaying ? AnyShapeStyle(Theme.gold) : AnyShapeStyle(Theme.surfaceRaised), in: Circle())221                        .frame(width: 44, height: 44)222                        .contentShape(Rectangle())223                }224                .buttonStyle(.plain)225                .padding(.top, -8).padding(.trailing, -8)226                .accessibilityLabel(isPlaying ? "Stop preview of \(sound.title)" : "Preview \(sound.title)")227                .accessibilityIdentifier("\(idPrefix).preview.\(sound.id)")228            }229            Spacer(minLength: 0)230            HStack(spacing: 5) {231                if isSelected { Image(systemName: "checkmark.circle.fill").font(.caption).foregroundStyle(Theme.gold).accessibilityHidden(true) }232                Text(sound.title).font(.orixCaption).lineLimit(2).multilineTextAlignment(.leading)233                    .minimumScaleFactor(0.85).fixedSize(horizontal: false, vertical: true)234                    .foregroundStyle(isSelected ? Theme.textPrimary : Theme.textSecondary)235            }236        }237        .padding(12)238        .frame(width: 124, height: 98, alignment: .topLeading)239        .background((isSelected ? Theme.sunrise.opacity(0.16) : Theme.surface), in: RoundedRectangle(cornerRadius: 18, style: .continuous))240        .overlay {241            RoundedRectangle(cornerRadius: 18, style: .continuous)242                .strokeBorder(isSelected ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.hairline), lineWidth: isSelected ? 1.5 : 1)243        }244        .contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous))245        .onTapGesture {246            guard selection != sound.id else { return }247            Haptics.play(.selection)248            withAnimation(.snappy(duration: 0.2)) { selection = sound.id }249        }250        .accessibilityElement(children: .contain)251        .accessibilityAction(named: Text("Select \(sound.title)")) { selection = sound.id }252        .accessibilityLabel(sound.title)253        .accessibilityValue(isSelected ? Text("Selected") : Text(""))254        .accessibilityIdentifier("\(idPrefix).sound.\(sound.id)")255    }256}257258/// Wrapping row of chips (simple flow layout).259struct FlowLayout: Layout {260    var spacing: CGFloat = 8261262    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {263        let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews)264        return CGSize(width: proposal.width ?? rows.width, height: rows.height)265    }266267    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {268        let result = arrange(width: bounds.width, subviews: subviews)269        for (index, origin) in result.origins.enumerated() {270            subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)271        }272    }273274    private func arrange(width: CGFloat, subviews: Subviews) -> (origins: [CGPoint], width: CGFloat, height: CGFloat) {275        var origins: [CGPoint] = []276        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxWidth: CGFloat = 0277        for subview in subviews {278            let size = subview.sizeThatFits(.unspecified)279            if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }280            origins.append(CGPoint(x: x, y: y))281            x += size.width + spacing282            rowHeight = max(rowHeight, size.height)283            maxWidth = max(maxWidth, x - spacing)284        }285        return (origins, maxWidth, y + rowHeight)286    }287}288
Files main
Menu

Theme