TheNoiseClock/TheNoiseClockWidget/AlarmIntents.swift
Matt Bruce d2c6a09e47 more refactoring by codex
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2026-02-08 10:48:39 -06:00

120 lines
3.0 KiB
Swift

//
// AlarmIntents.swift
// TheNoiseClockWidget
//
// Created by Matt Bruce on 2/2/26.
//
// App Intents for alarm actions from Live Activity and widget buttons.
// These intents are duplicated in the widget target for compilation.
// Note: Must be kept in sync with TheNoiseClock/Features/Alarms/Intents/AlarmIntents.swift
//
import AlarmKit
import AppIntents
import Foundation
// MARK: - Stop Alarm Intent
/// Intent to stop an active alarm from the Live Activity or notification.
struct StopAlarmIntent: LiveActivityIntent {
static let title: LocalizedStringResource = "Stop Alarm"
static let description = IntentDescription("Stops the currently ringing alarm")
@Parameter(title: "Alarm ID")
var alarmId: String
static var supportedModes: IntentModes { .background }
init() {
self.alarmId = ""
}
init(alarmId: String) {
self.alarmId = alarmId
}
func perform() throws -> some IntentResult {
guard let uuid = UUID(uuidString: alarmId) else {
throw AlarmIntentError.invalidAlarmID
}
try AlarmManager.shared.stop(id: uuid)
return .result()
}
}
// MARK: - Snooze Alarm Intent
/// Intent to snooze an active alarm from the Live Activity or notification.
struct SnoozeAlarmIntent: LiveActivityIntent {
static let title: LocalizedStringResource = "Snooze Alarm"
static let description = IntentDescription("Snoozes the currently ringing alarm")
@Parameter(title: "Alarm ID")
var alarmId: String
static var supportedModes: IntentModes { .background }
init() {
self.alarmId = ""
}
init(alarmId: String) {
self.alarmId = alarmId
}
func perform() throws -> some IntentResult {
guard let uuid = UUID(uuidString: alarmId) else {
throw AlarmIntentError.invalidAlarmID
}
// Use countdown to postpone the alarm by its configured snooze duration
try AlarmManager.shared.countdown(id: uuid)
return .result()
}
}
// MARK: - Open App Intent
/// Intent to open the app when the user taps the Live Activity.
struct OpenAlarmAppIntent: LiveActivityIntent {
static let title: LocalizedStringResource = "Open TheNoiseClock"
static let description = IntentDescription("Opens the app to the alarm screen")
static let openAppWhenRun = true
@Parameter(title: "Alarm ID")
var alarmId: String
init() {
self.alarmId = ""
}
init(alarmId: String) {
self.alarmId = alarmId
}
func perform() throws -> some IntentResult {
// The app will be opened due to openAppWhenRun = true
return .result()
}
}
// MARK: - Errors
enum AlarmIntentError: Error, LocalizedError {
case invalidAlarmID
case alarmNotFound
var errorDescription: String? {
switch self {
case .invalidAlarmID:
return "Invalid alarm ID"
case .alarmNotFound:
return "Alarm not found"
}
}
}