SPB Git

Repository Public License

ClockFaceView.swift 9.2 KB 206 lines swift

1// ORIX Alarm2// File: App/Features/Clock/ClockFaceView.swift3// Description: Animated clock in five styles (analog, digital, hybrid, minimal, chronograph) with an optional next-alarm marker.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Animated clock in one of the five styles.11///12/// - `date`: the instant to display. Leave it `nil` for a live clock driven by its own `TimelineView`;13///   pass a date to render exactly that instant (the caller then owns the refresh).14/// - `nextAlarm`: optional fire date marked on the dial (12 h dials show it when it is less than 12 h away,15///   the hybrid 24 h ring when it is less than 24 h away).16///17/// The view is square and scales with the space it is given (designed for 120...320 pt).18struct ClockFaceView: View {19    let style: ClockStyle20    var date: Date? = nil21    var nextAlarm: Date? = nil2223    @Environment(AppModel.self) private var model24    @Environment(\.accessibilityReduceMotion) private var reduceMotion2526    var body: some View {27        Group {28            if let date {29                face(at: date)30            } else if style == .digital || reduceMotion {31                TimelineView(.periodic(from: Self.wholeSecond, by: 1)) { face(at: $0.date) }32            } else {33                TimelineView(.animation(minimumInterval: 1.0 / 30)) { face(at: $0.date) }34            }35        }36        .aspectRatio(1, contentMode: .fit)37    }3839    private static var wholeSecond: Date {40        Date(timeIntervalSinceReferenceDate: Date.now.timeIntervalSinceReferenceDate.rounded(.down))41    }4243    private func face(at date: Date) -> some View {44        let moment = ClockMoment(date: date, calendar: model.calendar, smooth: !reduceMotion)45        let use24h = model.settings.use24HourClock46        let time = Fmt.time(ClockTime(hour: moment.hour, minute: moment.minute), use24h: use24h)47        let alarm12 = alarmFraction(from: date, window: 12)48        let alarm24 = alarmFraction(from: date, window: 24)49        return GeometryReader { geo in50            let side = min(geo.size.width, geo.size.height)51            ZStack {52                Canvas { ctx, size in53                    let painter = ClockDialPainter(ctx: ctx, center: CGPoint(x: size.width / 2, y: size.height / 2), r: min(size.width, size.height) / 2)54                    switch style {55                    case .analog: painter.analog(moment, alarm: alarm12)56                    case .minimal: painter.minimal(moment, alarm: alarm12)57                    case .chronograph: painter.chronograph(moment, alarm: alarm12)58                    case .hybrid: painter.hybrid(moment, alarm: alarm24)59                    case .digital: break60                    }61                }62                if style == .hybrid { HybridCenter(time: time, date: date, side: side) }63                if style == .digital { DigitalFace(time: time, moment: moment, date: date, side: side, hasAlarm: alarm24 != nil, alarmText: alarmText(use24h: use24h)) }64            }65            .frame(width: side, height: side)66            .frame(maxWidth: .infinity, maxHeight: .infinity)67        }68        .accessibilityElement(children: .ignore)69        .accessibilityLabel(Text("Clock"))70        .accessibilityValue(Text(spokenValue(time: time, use24h: use24h)))71        .accessibilityAddTraits(.updatesFrequently)72    }7374    /// Position of the next alarm on a dial covering `window` hours, or `nil` when it is further away than one turn.75    private func alarmFraction(from date: Date, window: Double) -> Double? {76        guard let nextAlarm else { return nil }77        let delta = nextAlarm.timeIntervalSince(date)78        guard delta > 0, delta <= window * 3600 else { return nil }79        let m = ClockMoment(date: nextAlarm, calendar: model.calendar, smooth: false)80        return window == 12 ? m.hourFraction : m.dayFraction81    }8283    private func alarmText(use24h: Bool?) -> String? {84        guard let nextAlarm else { return nil }85        let m = ClockMoment(date: nextAlarm, calendar: model.calendar, smooth: false)86        return Fmt.timeString(ClockTime(hour: m.hour, minute: m.minute), use24h: use24h)87    }8889    private func spokenValue(time: (digits: String, period: String), use24h: Bool?) -> String {90        let now = time.period.isEmpty ? time.digits : "\(time.digits) \(time.period)"91        if let alarm = alarmText(use24h: use24h) { return String(localized: "\(now), next alarm at \(alarm)") }92        return now93    }94}9596extension ClockStyle {97    /// Display name of the clock face (style pickers, accessibility).98    var displayName: String {99        switch self {100        case .analog: String(localized: "Analog"); case .digital: String(localized: "Digital"); case .hybrid: String(localized: "Hybrid")101        case .minimal: String(localized: "Minimal"); case .chronograph: String(localized: "Chronograph")102        }103    }104}105106/// Wall-clock reading of an instant, as dial fractions (0...1, clockwise from the top).107struct ClockMoment {108    var hour: Int109    var minute: Int110    /// Seconds including the fraction; whole seconds when `smooth` is false (Reduce Motion: the hand ticks).111    var second: Double112    var day: Int113114    init(date: Date, calendar: Calendar, smooth: Bool) {115        let c = calendar.dateComponents([.day, .hour, .minute, .second, .nanosecond], from: date)116        hour = c.hour ?? 0; minute = c.minute ?? 0; day = c.day ?? 1117        let whole = Double(c.second ?? 0)118        second = smooth ? whole + Double(c.nanosecond ?? 0) / 1_000_000_000 : whole119    }120121    var secondFraction: Double { second / 60 }122    var minuteFraction: Double { (Double(minute) + second / 60) / 60 }123    var hourFraction: Double { (Double(hour % 12) + Double(minute) / 60 + second / 3600) / 12 }124    var dayFraction: Double { (Double(hour) + Double(minute) / 60 + second / 3600) / 24 }125    var isDaytime: Bool { hour >= 6 && hour < 18 }126}127128/// Digital time shown inside the hybrid ring.129private struct HybridCenter: View {130    let time: (digits: String, period: String)131    let date: Date132    let side: CGFloat133134    var body: some View {135        let u = side / 260136        VStack(spacing: 2 * u) {137            Text(time.digits)138                .font(.clock(58 * u, weight: .regular))139                .foregroundStyle(LinearGradient(colors: [.white, Theme.peach], startPoint: .top, endPoint: .bottom))140                .lineLimit(1).minimumScaleFactor(0.6)141            HStack(spacing: 6 * u) {142                if !time.period.isEmpty {143                    Text(time.period).foregroundStyle(Theme.gold)144                }145                if side >= 180 {146                    Text(date, format: .dateTime.weekday(.abbreviated).day().month(.abbreviated)).foregroundStyle(Theme.textSecondary)147                }148            }149            .font(.system(size: max(13 * u, 9), weight: .semibold, design: .rounded))150            .textCase(.uppercase)151        }152        .frame(width: side * 0.58)153    }154}155156/// Large digits, date, and a sixty-segment seconds bar.157private struct DigitalFace: View {158    let time: (digits: String, period: String)159    let moment: ClockMoment160    let date: Date161    let side: CGFloat162    let hasAlarm: Bool163    let alarmText: String?164165    var body: some View {166        let u = side / 260167        let compact = side < 180168        VStack(spacing: (compact ? 8 : 12) * u) {169            if !compact {170                Text(date, format: .dateTime.weekday(.wide).day().month(.abbreviated))171                    .font(.system(size: 14 * u, weight: .bold, design: .rounded)).kerning(1.4 * u)172                    .textCase(.uppercase).foregroundStyle(Theme.textSecondary)173            }174            HStack(alignment: .firstTextBaseline, spacing: 5 * u) {175                Text(time.digits)176                    .font(.clock((compact ? 82 : 78) * u, weight: .medium))177                    .foregroundStyle(LinearGradient(colors: [.white, Theme.peach], startPoint: .top, endPoint: .bottom))178                if !time.period.isEmpty {179                    Text(time.period).font(.system(size: (compact ? 22 : 20) * u, weight: .bold, design: .rounded)).foregroundStyle(Theme.gold)180                }181            }182            .lineLimit(1).minimumScaleFactor(0.5)183            Canvas { ctx, size in184                // Sixty segments; those already elapsed in the current minute are lit.185                let count = compact ? 30 : 60186                let gap = size.width / CGFloat(count)187                let lit = Int(moment.second) * count / 60188                for i in 0..<count {189                    let isMajor = i % (count / 4) == 0190                    let h = isMajor ? size.height : size.height * 0.6191                    let rect = CGRect(x: CGFloat(i) * gap + gap * 0.25, y: (size.height - h) / 2, width: gap * 0.5, height: h)192                    let colour = i <= lit ? Theme.sunrise.mix(with: Theme.gold, by: Double(i) / Double(count)) : Color.white.opacity(0.16)193                    ctx.fill(Path(roundedRect: rect, cornerRadius: gap * 0.25), with: .color(colour))194                }195            }196            .frame(width: side * 0.78, height: max(12 * u, 7))197            if !compact, hasAlarm, let alarmText {198                Label(alarmText, systemImage: "alarm.fill")199                    .font(.system(size: 13 * u, weight: .semibold, design: .rounded))200                    .foregroundStyle(Theme.gold)201            }202        }203        .frame(width: side * 0.94)204    }205}206
Files main
Menu

Theme