Repository Public License
1// ORIX Alarm2// File: App/Features/Settings/SettingsView.swift3// Description: Settings: clock style, time format, feedback, default sound and snooze, missions, alarm permission and verification, data, about.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct SettingsView: View {11 @Environment(AppModel.self) private var model12 @Environment(\.dismiss) private var dismiss13 @Environment(\.isPresented) private var isPresented14 @Environment(\.openURL) private var openURL15 @State private var isChecking = false16 @State private var checkResult: AlarmCheckResult?17 @State private var isRequesting = false1819 private var settings: AppSettings { model.settings }2021 var body: some View {22 NavigationStack {23 ScrollView {24 VStack(spacing: Theme.spacing) {25 clockCard26 feedbackCard27 soundCard28 snoozeCard29 missionsCard30 alarmsCard31 SettingsDataCard()32 aboutCard33 }34 .padding(.horizontal, 20).padding(.top, 8)35 }36 .contentMargins(.bottom, 96, for: .scrollContent)37 .navigationTitle("Settings")38 .toolbar {39 if isPresented {40 ToolbarItem(placement: .confirmationAction) {41 Button("Done") { dismiss() }.accessibilityIdentifier("settings.done")42 }43 }44 }45 .orixScreen()46 }47 .onAppear { SoundFX.isEnabled = settings.soundEffectsEnabled }48 .onDisappear { SoundPlayer.shared.stopPreview() }49 }5051 // MARK: Clock52 private var clockCard: some View {53 VStack(alignment: .leading, spacing: 14) {54 Overline("Clock")55 ScrollView(.horizontal, showsIndicators: false) {56 TimelineView(.periodic(from: .now, by: 1)) { context in57 HStack(spacing: 12) {58 ForEach(ClockStyle.allCases, id: \.self) { style in59 clockTile(style, date: context.date)60 }61 }62 .padding(.vertical, 2)63 }64 }65 .scrollClipDisabled()66 VStack(alignment: .leading, spacing: 8) {67 Text("Time format").font(.orixCaption).foregroundStyle(Theme.textSecondary)68 Picker("Time format", selection: Binding(get: { settings.use24HourClock }, set: { value in69 Haptics.play(.selection)70 model.updateSettings { $0.use24HourClock = value }71 })) {72 Text("System").tag(Bool?.none)73 Text("12-hour").tag(Bool?.some(false))74 Text("24-hour").tag(Bool?.some(true))75 }76 .pickerStyle(.segmented)77 .accessibilityIdentifier("settings.timeFormat")78 }79 }80 .glassCard()81 }8283 private func clockTile(_ style: ClockStyle, date: Date) -> some View {84 let selected = settings.clockStyle == style85 return Button {86 Haptics.play(.selection)87 model.updateSettings { $0.clockStyle = style }88 } label: {89 VStack(spacing: 8) {90 // The face is laid out at a comfortable size, then scaled down to a tile.91 ClockFaceView(style: style, date: date)92 .frame(width: 250, height: 250)93 .scaleEffect(0.42)94 .frame(width: 106, height: 106)95 .clipped()96 .allowsHitTesting(false)97 .accessibilityHidden(true)98 HStack(spacing: 5) {99 Image(systemName: selected ? "checkmark.circle.fill" : "circle").font(.caption)100 .foregroundStyle(selected ? Theme.sunrise : Theme.textTertiary)101 Text(style.settingsTitle).font(.orixCaption)102 }103 }104 .padding(10)105 .background(selected ? Theme.sunrise.opacity(0.14) : Theme.surface, in: RoundedRectangle(cornerRadius: 18, style: .continuous))106 .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(selected ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.hairline), lineWidth: selected ? 2 : 1))107 }108 .buttonStyle(.plain)109 .accessibilityLabel("\(style.settingsTitle) clock")110 .accessibilityAddTraits(selected ? .isSelected : [])111 .accessibilityIdentifier("settings.clock.\(style.rawValue)")112 }113114 // MARK: Feedback115 private var feedbackCard: some View {116 VStack(alignment: .leading, spacing: 4) {117 Overline("Feedback")118 Toggle(isOn: Binding(get: { settings.hapticsEnabled }, set: { on in119 model.updateSettings { $0.hapticsEnabled = on }120 Haptics.play(.selection)121 })) { SettingsLabel(symbol: "iphone.radiowaves.left.and.right", title: "Haptics", detail: "Taps and vibrations on meaningful actions.") }122 .tint(Theme.sunrise).frame(minHeight: 56)123 .accessibilityIdentifier("settings.haptics")124 Divider().overlay(Theme.hairline)125 Toggle(isOn: Binding(get: { settings.soundEffectsEnabled }, set: { on in126 model.updateSettings { $0.soundEffectsEnabled = on }127 SoundFX.isEnabled = on128 if on { SoundFX.play(.tap) }129 })) { SettingsLabel(symbol: "speaker.wave.2.fill", title: "Interface sounds", detail: "Short sounds in missions. Alarm sounds are not affected.") }130 .tint(Theme.sunrise).frame(minHeight: 56)131 .accessibilityIdentifier("settings.sounds")132 }133 .glassCard()134 }135136 // MARK: Default sound137 private var soundCard: some View {138 VStack(alignment: .leading, spacing: 10) {139 Overline("New alarms")140 NavigationLink { DefaultSoundPickerView() } label: {141 SettingsNavRow(symbol: "music.note", title: "Default alarm sound", value: SoundCatalog.alarmSound(settings.defaultSoundID).title)142 }143 .buttonStyle(.plain)144 .accessibilityIdentifier("settings.defaultSound")145 Text("Used when you create an alarm. Each alarm can have its own sound.")146 .font(.orixCaption).foregroundStyle(Theme.textSecondary)147 }148 .glassCard()149 }150151 // MARK: Default snooze152 private var snoozeCard: some View {153 let policy = settings.defaultSnooze154 return VStack(alignment: .leading, spacing: 12) {155 Overline("Default snooze")156 Toggle(isOn: snoozeBinding(\.isAllowed)) {157 SettingsLabel(symbol: "zzz", title: "Allow snooze", detail: "New alarms start with these rules. Existing alarms keep their own.")158 }159 .tint(Theme.sunrise).frame(minHeight: 56)160 .accessibilityIdentifier("settings.snooze.allowed")161 if policy.isAllowed {162 Divider().overlay(Theme.hairline)163 Picker("Snooze length", selection: snoozeBinding(\.mode)) {164 Text("Same every time").tag(SnoozePolicy.Mode.fixed)165 Text("Shorter each time").tag(SnoozePolicy.Mode.decreasing)166 }167 .pickerStyle(.segmented)168 .accessibilityIdentifier("settings.snooze.mode")169 Stepper(value: snoozeBinding(\.baseMinutes), in: 1...30) {170 stepperLabel(policy.mode == .fixed ? "Snooze length" : "First snooze", value: Fmt.duration(TimeInterval(policy.baseMinutes * 60)))171 }172 .accessibilityIdentifier("settings.snooze.minutes")173 Stepper(value: snoozeBinding(\.maxCount), in: 1...10) {174 stepperLabel("Snoozes allowed", value: "\(policy.maxCount)")175 }176 .accessibilityIdentifier("settings.snooze.count")177 Toggle(isOn: snoozeBinding(\.escalatesDifficulty)) {178 SettingsLabel(symbol: "arrow.up.forward.circle", title: "Harder missions after a snooze", detail: "Each snooze raises the mission level by one, up to Expert.")179 }180 .tint(Theme.sunrise).frame(minHeight: 56)181 .accessibilityIdentifier("settings.snooze.escalate")182 Text(snoozePreview(policy)).font(.orixCaption).foregroundStyle(Theme.textSecondary)183 .accessibilityIdentifier("settings.snooze.preview")184 }185 }186 .glassCard()187 }188189 private func snoozeBinding<T>(_ keyPath: WritableKeyPath<SnoozePolicy, T>) -> Binding<T> {190 Binding(get: { settings.defaultSnooze[keyPath: keyPath] }, set: { value in191 Haptics.play(.selection)192 model.updateSettings { $0.defaultSnooze[keyPath: keyPath] = value }193 })194 }195196 private func stepperLabel(_ title: LocalizedStringKey, value: String) -> some View {197 HStack {198 Text(title).font(.orixBody)199 Spacer()200 Text(value).font(.orixBody.monospacedDigit()).foregroundStyle(Theme.textSecondary)201 }202 .accessibilityElement(children: .combine)203 }204205 private func snoozePreview(_ policy: SnoozePolicy) -> String {206 let minutes = (1...policy.maxCount).compactMap { policy.duration(forSnooze: $0) }.map { String(Int($0 / 60)) }207 return String(localized: "Snoozes for a new alarm: \(minutes.joined(separator: ", ")) min, then the alarm can only be stopped.")208 }209210 // MARK: Missions211 private var missionsCard: some View {212 VStack(alignment: .leading, spacing: 12) {213 Overline("Missions")214 VStack(alignment: .leading, spacing: 8) {215 SettingsLabel(symbol: "textformat.abc", title: "Word Scramble language", detail: "Language of the words for new Word Scramble steps.")216 Picker("Word Scramble language", selection: Binding(get: { settings.wordLanguage }, set: { value in217 Haptics.play(.selection)218 model.updateSettings { $0.wordLanguage = value }219 })) {220 Text("English").tag(WordLanguage.english)221 Text("Français").tag(WordLanguage.french)222 }223 .pickerStyle(.segmented)224 .accessibilityIdentifier("settings.wordLanguage")225 }226 Divider().overlay(Theme.hairline)227 NavigationLink { QRTagManagerView() } label: {228 SettingsNavRow(symbol: "qrcode", title: "QR tags", value: model.qrTags.isEmpty ? String(localized: "None") : "\(model.qrTags.count)")229 }230 .buttonStyle(.plain)231 .accessibilityIdentifier("settings.qrTags")232 }233 .glassCard()234 }235236 // MARK: Alarm permission and verification237 private var alarmsCard: some View {238 VStack(alignment: .leading, spacing: 12) {239 Overline("System alarms")240 HStack(alignment: .top, spacing: 12) {241 Image(systemName: permissionSymbol).font(.title3).foregroundStyle(permissionTint).frame(width: 30).accessibilityHidden(true)242 VStack(alignment: .leading, spacing: 3) {243 Text("Alarm permission").font(.orixHeadline)244 Text(permissionText).font(.orixCaption).foregroundStyle(Theme.textSecondary)245 }246 Spacer(minLength: 0)247 }248 .accessibilityElement(children: .combine)249 .accessibilityIdentifier("settings.permission")250 switch model.authorization {251 case .authorized: EmptyView()252 case .notDetermined:253 Button(isRequesting ? "Requesting…" : "Allow alarms") {254 isRequesting = true255 Task { await model.requestAuthorization(); isRequesting = false; checkResult = nil }256 }257 .buttonStyle(PrimaryButtonStyle()).disabled(isRequesting)258 .accessibilityIdentifier("settings.permission.action")259 case .denied:260 Button("Open Settings") { if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) } }261 .buttonStyle(SecondaryButtonStyle())262 .accessibilityIdentifier("settings.permission.action")263 }264 Divider().overlay(Theme.hairline)265 Button {266 isChecking = true267 Task {268 await model.reconcile()269 checkResult = AlarmCheckResult(model: model)270 isChecking = false271 Haptics.play(checkResult?.notScheduled == 0 ? .success : .warning)272 }273 } label: {274 HStack(spacing: 8) {275 if isChecking { ProgressView().tint(Theme.textPrimary) } else { Image(systemName: "checkmark.shield.fill") }276 Text(isChecking ? "Checking…" : "Check alarms now")277 }278 }279 .buttonStyle(SecondaryButtonStyle()).disabled(isChecking)280 .accessibilityIdentifier("settings.checkAlarms")281 if let result = checkResult {282 VStack(alignment: .leading, spacing: 6) {283 Label(result.headline, systemImage: result.symbol).font(.orixHeadline).foregroundStyle(result.tint)284 Text(result.detail).font(.orixCaption).foregroundStyle(Theme.textSecondary)285 }286 .frame(maxWidth: .infinity, alignment: .leading)287 .padding(14)288 .background(result.tint.opacity(0.12), in: RoundedRectangle(cornerRadius: 16, style: .continuous))289 .accessibilityElement(children: .combine)290 .accessibilityIdentifier("settings.checkAlarms.result")291 } else {292 Text("Compares your alarms with what iOS actually holds and repairs any difference.")293 .font(.orixCaption).foregroundStyle(Theme.textSecondary)294 }295 }296 .glassCard()297 }298299 private var permissionSymbol: String {300 switch model.authorization { case .authorized: "checkmark.seal.fill"; case .denied: "xmark.octagon.fill"; case .notDetermined: "questionmark.circle.fill" }301 }302 private var permissionTint: Color {303 switch model.authorization { case .authorized: Theme.success; case .denied: Theme.danger; case .notDetermined: Theme.gold }304 }305 private var permissionText: String {306 switch model.authorization {307 case .authorized: String(localized: "Allowed. ORIX Alarm can schedule alarms with iOS.")308 case .denied: String(localized: "Not allowed. Your alarms are saved but cannot ring until you allow alarms for ORIX Alarm in Settings.")309 case .notDetermined: String(localized: "Not requested yet. Alarms cannot be scheduled until you allow them.")310 }311 }312313 // MARK: About314 private var aboutCard: some View {315 let info = Bundle.main.infoDictionary316 let version = info?["CFBundleShortVersionString"] as? String ?? "–"317 let build = info?["CFBundleVersion"] as? String ?? "–"318 return VStack(alignment: .leading, spacing: 4) {319 Overline("About")320 NavigationLink { HowItWorksView() } label: { SettingsNavRow(symbol: "gearshape.2.fill", title: "How ORIX Alarm works", value: "") }321 .buttonStyle(.plain).accessibilityIdentifier("settings.howItWorks")322 Divider().overlay(Theme.hairline)323 NavigationLink { PrivacySummaryView() } label: { SettingsNavRow(symbol: "lock.shield.fill", title: "Privacy", value: "") }324 .buttonStyle(.plain).accessibilityIdentifier("settings.privacy")325 Divider().overlay(Theme.hairline)326 HStack {327 SettingsLabel(symbol: "sun.horizon.fill", title: "ORIX Alarm", detail: "Wake smarter. Rise better.")328 Spacer()329 Text("Version \(version) (\(build))").font(.orixCaption.monospacedDigit()).foregroundStyle(Theme.textSecondary)330 .accessibilityIdentifier("settings.version")331 }332 .frame(minHeight: 56)333 }334 .glassCard()335 }336}337338/// Outcome of "Check alarms now": what iOS holds for the alarms that are switched on.339struct AlarmCheckResult: Equatable {340 var enabled = 0341 var confirmed = 0342 var notScheduled = 0343 var unverifiable = 0344345 init(model: AppModel) {346 for alarm in model.alarms where alarm.isEnabled {347 enabled += 1348 switch model.status(for: alarm.id) {349 case .confirmed: confirmed += 1350 case .missing, .mismatched: notScheduled += 1351 case .unverifiable, .off: unverifiable += 1352 }353 }354 }355356 var headline: String {357 if enabled == 0 { return String(localized: "No alarm is switched on") }358 if notScheduled == 0 && unverifiable == 0 { return enabled == 1 ? String(localized: "1 alarm confirmed") : String(localized: "All \(enabled) alarms confirmed") }359 return String(localized: "\(confirmed) confirmed, \(notScheduled) not scheduled")360 }361 var detail: String {362 if enabled == 0 { return String(localized: "There is nothing to verify. Alarms that are switched off are not registered with iOS.") }363 var text = String(localized: "\(enabled) switched on: \(confirmed) confirmed with iOS, \(notScheduled) not scheduled.")364 if unverifiable > 0 { text += " " + String(localized: "\(unverifiable) could not be verified.") }365 if notScheduled > 0 { text += " " + String(localized: "An alarm that is not scheduled will not ring: open it in the Alarms tab to see why, and check the alarm permission above.") }366 return text367 }368 var symbol: String { enabled == 0 ? "moon.zzz" : (notScheduled == 0 && unverifiable == 0 ? "checkmark.seal.fill" : "exclamationmark.triangle.fill") }369 var tint: Color { enabled == 0 ? Theme.textSecondary : (notScheduled > 0 ? Theme.danger : (unverifiable > 0 ? Theme.gold : Theme.success)) }370}371372extension ClockStyle {373 /// Name shown in the clock style picker.374 var settingsTitle: String {375 switch self {376 case .analog: String(localized: "Analog"); case .digital: String(localized: "Digital"); case .hybrid: String(localized: "Hybrid")377 case .minimal: String(localized: "Minimal"); case .chronograph: String(localized: "Chronograph")378 }379 }380}381382/// Icon, title and one line of explanation, used as the label of settings rows.383struct SettingsLabel: View {384 let symbol: String385 let title: LocalizedStringKey386 let detail: LocalizedStringKey387 var body: some View {388 HStack(spacing: 12) {389 Image(systemName: symbol).font(.callout.weight(.semibold)).foregroundStyle(Theme.gold)390 .frame(width: 34, height: 34).background(Theme.surfaceRaised, in: RoundedRectangle(cornerRadius: 10, style: .continuous))391 .accessibilityHidden(true)392 VStack(alignment: .leading, spacing: 2) {393 Text(title).font(.orixHeadline)394 Text(detail).font(.orixCaption).foregroundStyle(Theme.textSecondary)395 }396 }397 }398}399400/// Row that opens another page.401struct SettingsNavRow: View {402 let symbol: String403 let title: LocalizedStringKey404 let value: String405 var body: some View {406 HStack(spacing: 12) {407 Image(systemName: symbol).font(.callout.weight(.semibold)).foregroundStyle(Theme.gold)408 .frame(width: 34, height: 34).background(Theme.surfaceRaised, in: RoundedRectangle(cornerRadius: 10, style: .continuous))409 .accessibilityHidden(true)410 Text(title).font(.orixHeadline).lineLimit(2).minimumScaleFactor(0.85).layoutPriority(1)411 Spacer(minLength: 8)412 Text(value).font(.orixCaption).foregroundStyle(Theme.textSecondary).lineLimit(1)413 Image(systemName: "chevron.right").font(.caption.weight(.bold)).foregroundStyle(Theme.textTertiary).accessibilityHidden(true)414 }415 .frame(minHeight: 52)416 .contentShape(Rectangle())417 }418}419