Repository Public License
1// ORIX Alarm2// File: App/Features/Editor/TimeDial.swift3// Description: Circular time selector: 24-hour outer ring tinted like the sky, one-minute inner ring, draggable knobs, fine buttons and accessible adjustable elements.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Pure geometry of the dial, kept apart from the view so it stays easy to reason about.11enum TimeDialMath {12 /// Clockwise angle in degrees from 12 o'clock (0..<360) for a point relative to the centre.13 static func angle(dx: Double, dy: Double) -> Double {14 let degrees = atan2(dx, -dy) * 180 / .pi15 return degrees < 0 ? degrees + 360 : degrees16 }17 static func hour(forAngle angle: Double) -> Int { Int((angle / 15).rounded()) % 24 }18 static func minute(forAngle angle: Double) -> Int { Int((angle / 6).rounded()) % 60 }19 /// Position on a circle of `radius` for a clockwise angle from 12 o'clock.20 static func point(center: CGPoint, radius: Double, angle: Double) -> CGPoint {21 let r = angle * .pi / 18022 return CGPoint(x: center.x + radius * sin(r), y: center.y - radius * cos(r))23 }24}2526struct TimeDial: View {27 @Binding var time: ClockTime28 var use24h: Bool?2930 private enum Ring { case hour, minute }31 @State private var activeRing: Ring?32 @Environment(\.accessibilityReduceMotion) private var reduceMotion3334 private var tint: Color { DayTint.color(hour: Double(time.hour) + Double(time.minute) / 60) }35 private var is24: Bool { Fmt.time(ClockTime(hour: 13, minute: 0), use24h: use24h).period.isEmpty }3637 var body: some View {38 VStack(spacing: 18) {39 GeometryReader { geo in40 dial(side: min(geo.size.width, geo.size.height))41 .frame(width: geo.size.width, height: geo.size.height)42 }43 .aspectRatio(1, contentMode: .fit)44 .frame(maxWidth: 330)45 fineControls46 }47 }4849 // MARK: Dial50 private func dial(side: CGFloat) -> some View {51 let center = CGPoint(x: side / 2, y: side / 2)52 let hourWidth: CGFloat = 36, minuteWidth: CGFloat = 2853 let hourRadius = side / 2 - hourWidth / 2 - 254 let minuteRadius = hourRadius - hourWidth / 2 - minuteWidth / 2 - 855 let split = (hourRadius + minuteRadius) / 256 let hourAngle = Double(time.hour) * 1557 let minuteAngle = Double(time.minute) * 658 let touchArea = Path { p in59 p.addEllipse(in: CGRect(x: center.x - hourRadius - 26, y: center.y - hourRadius - 26, width: (hourRadius + 26) * 2, height: (hourRadius + 26) * 2))60 let inner = minuteRadius - minuteWidth / 2 - 1061 p.addEllipse(in: CGRect(x: center.x - inner, y: center.y - inner, width: inner * 2, height: inner * 2))62 }6364 return ZStack {65 // Soft glow following the hour.66 Circle().fill(RadialGradient(colors: [tint.opacity(0.30), tint.opacity(0)], center: .center, startRadius: 0, endRadius: minuteRadius))67 .frame(width: minuteRadius * 2, height: minuteRadius * 2)6869 // Hour ring: the whole day, midnight at the top.70 Circle().strokeBorder(AngularGradient(gradient: Gradient(stops: DayTint.ringStops), center: .center, startAngle: .degrees(-90), endAngle: .degrees(270)), lineWidth: hourWidth)71 .opacity(activeRing == .hour ? 0.62 : 0.44)72 .frame(width: (hourRadius + hourWidth / 2) * 2, height: (hourRadius + hourWidth / 2) * 2)73 Circle().strokeBorder(Theme.hairline, lineWidth: 1)74 .frame(width: (hourRadius + hourWidth / 2) * 2, height: (hourRadius + hourWidth / 2) * 2)7576 // Minute ring.77 Circle().stroke(Color.white.opacity(activeRing == .minute ? 0.12 : 0.07), lineWidth: minuteWidth)78 .frame(width: minuteRadius * 2, height: minuteRadius * 2)79 Circle().trim(from: 0, to: max(0.0001, Double(time.minute) / 60))80 .stroke(LinearGradient(colors: [tint.opacity(0.55), tint], startPoint: .top, endPoint: .bottom), style: StrokeStyle(lineWidth: minuteWidth, lineCap: .round))81 .rotationEffect(.degrees(-90))82 .frame(width: minuteRadius * 2, height: minuteRadius * 2)8384 Canvas { ctx, _ in85 // Hour marks and labels.86 for h in 0..<24 {87 let angle = Double(h) * 1588 if h % 3 == 0 {89 let label = Text(hourLabel(h)).font(.system(size: 11, weight: .bold, design: .rounded)).foregroundStyle(.white.opacity(0.92))90 ctx.draw(label, at: TimeDialMath.point(center: center, radius: hourRadius, angle: angle))91 } else {92 let p = TimeDialMath.point(center: center, radius: hourRadius, angle: angle)93 ctx.fill(Path(ellipseIn: CGRect(x: p.x - 1.5, y: p.y - 1.5, width: 3, height: 3)), with: .color(.white.opacity(0.55)))94 }95 }96 // Minute marks.97 for m in stride(from: 0, to: 60, by: 5) {98 let angle = Double(m) * 699 if m % 15 == 0 {100 let label = Text(String(format: "%02d", m)).font(.system(size: 10, weight: .semibold, design: .rounded)).foregroundStyle(.white.opacity(0.70))101 ctx.draw(label, at: TimeDialMath.point(center: center, radius: minuteRadius, angle: angle))102 } else {103 let p = TimeDialMath.point(center: center, radius: minuteRadius, angle: angle)104 ctx.fill(Path(ellipseIn: CGRect(x: p.x - 1.25, y: p.y - 1.25, width: 2.5, height: 2.5)), with: .color(.white.opacity(0.40)))105 }106 }107 }108 .allowsHitTesting(false)109110 // Knobs.111 knob(text: hourKnobLabel, diameter: hourWidth + 8, active: activeRing == .hour)112 .position(TimeDialMath.point(center: center, radius: hourRadius, angle: hourAngle))113 knob(text: String(format: "%02d", time.minute), diameter: minuteWidth + 8, active: activeRing == .minute)114 .position(TimeDialMath.point(center: center, radius: minuteRadius, angle: minuteAngle))115116 readout.frame(width: (minuteRadius - minuteWidth / 2 - 12) * 2)117 }118 .frame(width: side, height: side)119 .animation(reduceMotion ? nil : .snappy(duration: 0.18), value: time)120 .contentShape(touchArea, eoFill: true)121 .gesture(122 DragGesture(minimumDistance: 0, coordinateSpace: .local)123 .onChanged { value in124 let dx = value.location.x - center.x, dy = value.location.y - center.y125 if activeRing == nil {126 let start = hypot(value.startLocation.x - center.x, value.startLocation.y - center.y)127 activeRing = start >= split ? .hour : .minute128 }129 let angle = TimeDialMath.angle(dx: dx, dy: dy)130 switch activeRing {131 case .hour: set(hour: TimeDialMath.hour(forAngle: angle), minute: time.minute)132 case .minute: set(hour: time.hour, minute: TimeDialMath.minute(forAngle: angle))133 case nil: break134 }135 }136 .onEnded { _ in activeRing = nil }137 )138 .accessibilityElement(children: .ignore)139 .accessibilityLabel("Time dial")140 .accessibilityValue(Fmt.timeString(time, use24h: use24h))141 .accessibilityIdentifier("editor.dial")142 .accessibilityChildren {143 Rectangle()144 .accessibilityLabel("Hour")145 .accessibilityValue(hourSpoken)146 .accessibilityAdjustableAction { direction in147 switch direction {148 case .increment: stepHour(1)149 case .decrement: stepHour(-1)150 @unknown default: break151 }152 }153 .accessibilityIdentifier("editor.dial.hour")154 Rectangle()155 .accessibilityLabel("Minute")156 .accessibilityValue("\(time.minute)")157 .accessibilityAdjustableAction { direction in158 switch direction {159 case .increment: stepMinute(1)160 case .decrement: stepMinute(-1)161 @unknown default: break162 }163 }164 .accessibilityIdentifier("editor.dial.minute")165 }166 }167168 private func knob(text: String, diameter: CGFloat, active: Bool) -> some View {169 Circle().fill(.white)170 .overlay(Circle().strokeBorder(tint, lineWidth: 3))171 .overlay(Text(text).font(.system(size: diameter * 0.36, weight: .bold, design: .rounded)).monospacedDigit().foregroundStyle(Theme.midnight).minimumScaleFactor(0.6))172 .frame(width: diameter, height: diameter)173 .shadow(color: tint.opacity(0.7), radius: active ? 14 : 7)174 .scaleEffect(active ? 1.12 : 1)175 .allowsHitTesting(false)176 }177178 private var readout: some View {179 let parts = Fmt.time(time, use24h: use24h)180 return VStack(spacing: 2) {181 HStack(spacing: 5) {182 Image(systemName: DayTint.symbol(hour: time.hour)).font(.system(size: 12, weight: .semibold))183 Text(DayTint.phaseName(hour: time.hour)).font(.system(size: 11, weight: .semibold, design: .rounded))184 }185 .foregroundStyle(tint)186 Text(parts.digits).font(.clock(50, weight: .regular)).lineLimit(1).minimumScaleFactor(0.5)187 .contentTransition(.numericText())188 .accessibilityIdentifier("editor.timeReadout")189 if !parts.period.isEmpty {190 Text(parts.period).font(.system(size: 15, weight: .bold, design: .rounded)).kerning(1.5).foregroundStyle(Theme.textSecondary)191 }192 }193 .allowsHitTesting(false)194 }195196 // MARK: Fine controls (gesture-free alternative, one-minute precision)197 private var fineControls: some View {198 HStack(spacing: 12) {199 fineGroup(label: "Hour", value: hourKnobLabel + (is24 ? "" : (time.hour < 12 ? " AM" : " PM")), id: "editor.hour",200 minus: { stepHour(-1) }, plus: { stepHour(1) })201 fineGroup(label: "Minute", value: String(format: "%02d", time.minute), id: "editor.minute",202 minus: { stepMinute(-1) }, plus: { stepMinute(1) })203 }204 }205206 private func fineGroup(label: String, value: String, id: String, minus: @escaping () -> Void, plus: @escaping () -> Void) -> some View {207 HStack(spacing: 0) {208 fineButton("minus", label: "Decrease \(label.lowercased())", id: "\(id).minus", action: minus)209 VStack(spacing: 1) {210 Text(label.uppercased()).font(.system(size: 9, weight: .bold, design: .rounded)).kerning(1).foregroundStyle(Theme.textTertiary)211 Text(value).font(.system(size: 15, weight: .semibold, design: .rounded)).monospacedDigit().contentTransition(.numericText())212 }213 .frame(maxWidth: .infinity)214 .accessibilityHidden(true)215 fineButton("plus", label: "Increase \(label.lowercased())", id: "\(id).plus", action: plus)216 }217 .frame(maxWidth: .infinity)218 .background(Theme.surface, in: Capsule())219 .overlay(Capsule().strokeBorder(Theme.hairline))220 }221222 private func fineButton(_ symbol: String, label: String, id: String, action: @escaping () -> Void) -> some View {223 Button(action: action) {224 Image(systemName: symbol).font(.system(size: 14, weight: .bold)).frame(width: 46, height: 46).contentShape(Rectangle())225 }226 .buttonStyle(.plain)227 .buttonRepeatBehavior(.enabled)228 .accessibilityLabel(label)229 .accessibilityIdentifier(id)230 }231232 // MARK: Values233 private func hourLabel(_ h: Int) -> String {234 if is24 { return String(format: "%02d", h) }235 let twelve = h % 12 == 0 ? 12 : h % 12236 return "\(twelve)\(h < 12 ? "a" : "p")"237 }238 private var hourKnobLabel: String {239 is24 ? String(format: "%02d", time.hour) : "\(time.hour % 12 == 0 ? 12 : time.hour % 12)"240 }241 private var hourSpoken: String {242 is24 ? "\(time.hour)" : "\(time.hour % 12 == 0 ? 12 : time.hour % 12) \(time.hour < 12 ? "AM" : "PM")"243 }244245 private func set(hour: Int, minute: Int) {246 let next = ClockTime(hour: hour, minute: minute)247 guard next != time else { return }248 time = next249 Haptics.play(.tick)250 }251 private func stepHour(_ delta: Int) { set(hour: (time.hour + delta + 24) % 24, minute: time.minute) }252 /// Minute steps carry into the hour so that ± walks continuously through the day.253 private func stepMinute(_ delta: Int) {254 let next = time.adding(minutes: delta)255 set(hour: next.hour, minute: next.minute)256 }257}258259/// Standard wheel picker offered as the fallback way of entering the time.260struct TimeEntrySheet: View {261 @Binding var time: ClockTime262 var use24h: Bool?263 @Environment(\.dismiss) private var dismiss264265 private var date: Binding<Date> {266 Binding {267 Calendar.current.date(bySettingHour: time.hour, minute: time.minute, second: 0, of: Calendar.current.startOfDay(for: .now)) ?? .now268 } set: { newValue in269 let c = Calendar.current.dateComponents([.hour, .minute], from: newValue)270 time = ClockTime(hour: c.hour ?? time.hour, minute: c.minute ?? time.minute)271 }272 }273274 var body: some View {275 NavigationStack {276 DatePicker("Alarm time", selection: date, displayedComponents: .hourAndMinute)277 .datePickerStyle(.wheel).labelsHidden()278 // Same 12/24-hour decision as the dial readout (`Fmt.time`), so both always agree.279 .environment(\.locale, Locale(identifier: Fmt.time(ClockTime(hour: 13, minute: 0), use24h: use24h).period.isEmpty ? "en_GB" : "en_US"))280 .accessibilityIdentifier("editor.timePicker")281 .navigationTitle("Enter time").navigationBarTitleDisplayMode(.inline)282 .toolbar {283 ToolbarItem(placement: .confirmationAction) {284 Button("Done") { dismiss() }.accessibilityIdentifier("editor.timePicker.done")285 }286 }287 }288 .presentationDetents([.height(320)])289 .preferredColorScheme(.dark)290 }291}292