SPB Git

Repository Public License

SleepDial.swift 7.2 KB 150 lines swift

1// ORIX Alarm2// File: App/Features/Sleep/SleepDial.swift3// Description: Circular 24-hour dial with two draggable ends (bedtime, wake time) and the resulting time in bed at its centre.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// A 24-hour ring: midnight at the top, noon at the bottom. The arc runs clockwise from bedtime to wake time.11/// Both ends can be dragged (5-minute steps); VoiceOver users adjust each end in 15-minute steps.12struct SleepDial: View {13    /// Minutes since midnight.14    @Binding var bedtime: Int15    @Binding var wake: Int16    var use24h: Bool?17    /// Called when a drag or an accessibility adjustment ends, so the owner can persist once.18    var onCommit: () -> Void1920    private enum End { case bedtime, wake }21    private let trackWidth: CGFloat = 3822    private let space = "sleep.dial"2324    private var opportunity: Int { SleepPlanner.minutes(from: ClockTime(minutesSinceMidnight: bedtime), to: ClockTime(minutesSinceMidnight: wake)) }2526    var body: some View {27        GeometryReader { geo in28            let side = min(geo.size.width, geo.size.height)29            let radius = side / 2 - trackWidth / 2 - 430            let center = CGPoint(x: geo.size.width / 2, y: geo.size.height / 2)31            ZStack {32                Circle().stroke(Theme.surfaceRaised, lineWidth: trackWidth)33                    .frame(width: radius * 2, height: radius * 2)34                Circle().stroke(Theme.hairline, lineWidth: 1)35                    .frame(width: radius * 2 + trackWidth, height: radius * 2 + trackWidth)36                // Time in bed: clockwise from bedtime to wake time.37                Circle().trim(from: 0, to: max(CGFloat(opportunity) / 1440, 0.002))38                    .stroke(AngularGradient(colors: [Theme.violet, Theme.azure, Theme.sunrise, Theme.gold], center: .center,39                                            startAngle: .degrees(0), endAngle: .degrees(max(Double(opportunity) / 4, 1))),40                            style: StrokeStyle(lineWidth: trackWidth - 8, lineCap: .round))41                    .frame(width: radius * 2, height: radius * 2)42                    .rotationEffect(.degrees(Double(bedtime) / 4 - 90))43                ticks(radius: radius - trackWidth / 2 - 8, center: center)44                centerReadout45                handle(.bedtime, radius: radius, center: center)46                handle(.wake, radius: radius, center: center)47            }48            .frame(width: geo.size.width, height: geo.size.height)49            .coordinateSpace(.named(space))50        }51        .aspectRatio(1, contentMode: .fit)52        .accessibilityElement(children: .contain)53        .accessibilityLabel("Sleep plan dial")54    }5556    // MARK: Parts57    private var centerReadout: some View {58        VStack(spacing: 2) {59            Text(SleepFmt.span(opportunity))60                .font(.system(size: 30, weight: .semibold, design: .rounded).monospacedDigit())61                .contentTransition(.numericText())62                .minimumScaleFactor(0.6).lineLimit(1)63            Text("time in bed").font(.orixCaption).foregroundStyle(Theme.textSecondary)64        }65        .padding(.horizontal, 70)66        .accessibilityElement(children: .combine)67        .accessibilityLabel("Time in bed")68        .accessibilityValue(SleepFmt.span(opportunity))69        .accessibilityIdentifier("sleep.opportunity")70    }7172    private func ticks(radius: CGFloat, center: CGPoint) -> some View {73        ZStack {74            ForEach(0..<24, id: \.self) { hour in75                let major = hour % 6 == 076                let p = point(minute: hour * 60, radius: radius, center: center)77                if major {78                    Text(hourLabel(hour)).font(.system(size: 11, weight: .bold, design: .rounded).monospacedDigit())79                        .foregroundStyle(Theme.textSecondary).position(p)80                } else {81                    Circle().fill(hour % 2 == 0 ? Theme.textTertiary : Theme.hairline).frame(width: 3, height: 3).position(p)82                }83            }84        }85        .accessibilityHidden(true)86    }8788    private func hourLabel(_ hour: Int) -> String {89        let r = Fmt.time(ClockTime(hour: hour, minute: 0), use24h: use24h)90        if r.period.isEmpty { return String(format: "%02d", hour) }91        return "\(r.digits.split(separator: ":").first ?? "")\(r.period)"92    }9394    private func handle(_ end: End, radius: CGFloat, center: CGPoint) -> some View {95        let minute = end == .bedtime ? bedtime : wake96        return Image(systemName: end == .bedtime ? "bed.double.fill" : "alarm.fill")97            .font(.system(size: 15, weight: .bold))98            .foregroundStyle(Theme.midnight)99            .frame(width: trackWidth - 4, height: trackWidth - 4)100            .background(end == .bedtime ? AnyShapeStyle(Theme.nightGradient) : AnyShapeStyle(Theme.sunriseGradient), in: Circle())101            .overlay(Circle().strokeBorder(.white.opacity(0.85), lineWidth: 2))102            .shadow(color: .black.opacity(0.4), radius: 5, y: 2)103            .frame(width: 52, height: 52)          // 44 pt+ touch target around the visible knob104            .contentShape(Circle())105            .position(point(minute: minute, radius: radius, center: center))106            .gesture(107                DragGesture(minimumDistance: 0, coordinateSpace: .named(space))108                    .onChanged { value in set(end, to: SleepPlanner.snapped(minute: self.minute(at: value.location, center: center), step: 5)) }109                    .onEnded { _ in onCommit() }110            )111            .accessibilityElement()112            .accessibilityLabel(end == .bedtime ? "Bedtime" : "Wake time")113            .accessibilityValue(Fmt.timeString(ClockTime(minutesSinceMidnight: minute), use24h: use24h))114            .accessibilityHint("Swipe up or down to adjust by 15 minutes")115            .accessibilityAdjustableAction { direction in116                set(end, to: SleepPlanner.snapped(minute: minute + (direction == .increment ? 15 : -15), step: 15))117                onCommit()118            }119            .accessibilityIdentifier(end == .bedtime ? "sleep.dial.bedtime" : "sleep.dial.wake")120    }121122    // MARK: Geometry123    private func point(minute: Int, radius: CGFloat, center: CGPoint) -> CGPoint {124        let angle = Double(minute) / 1440 * 2 * .pi - .pi / 2125        return CGPoint(x: center.x + radius * CGFloat(cos(angle)), y: center.y + radius * CGFloat(sin(angle)))126    }127128    private func minute(at location: CGPoint, center: CGPoint) -> Int {129        var angle = atan2(Double(location.y - center.y), Double(location.x - center.x)) + .pi / 2130        if angle < 0 { angle += 2 * .pi }131        return Int((angle / (2 * .pi) * 1440).rounded())132    }133134    private func set(_ end: End, to value: Int) {135        let current = end == .bedtime ? bedtime : wake136        guard value != current else { return }137        if value % 15 == 0 { Haptics.play(.tick) }138        if end == .bedtime { bedtime = value } else { wake = value }139    }140}141142/// Durations of the sleep planner: "8 h", "7 h 30 min", "45 min".143enum SleepFmt {144    static func span(_ minutes: Int) -> String {145        let h = minutes / 60, m = minutes % 60146        if h == 0 { return String(localized: "\(m) min") }147        return m == 0 ? String(localized: "\(h) h") : String(localized: "\(h) h \(m) min")148    }149}150
Files main
Menu

Theme