Files
FeelAloud/Moment/AppIntent.swift
2026-07-22 22:54:03 +02:00

93 lines
2.7 KiB
Swift

import AppIntents
import Foundation
import WidgetKit
enum MomentRatingValue: String, AppEnum, Codable, Hashable, Sendable {
case veryGood = "Sehr gut"
case good = "Gut"
case middle = "Mittel"
case bad = "Schlecht"
case veryBad = "Sehr schlecht"
static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Stimmung")
static var caseDisplayRepresentations: [MomentRatingValue: DisplayRepresentation] = [
.veryGood: "Sehr gut",
.good: "Gut",
.middle: "Mittel",
.bad: "Schlecht",
.veryBad: "Sehr schlecht"
]
var emoji: String {
switch self {
case .veryGood: "😄"
case .good: "🙂"
case .middle: "😐"
case .bad: "🙁"
case .veryBad: "😞"
}
}
}
struct TrackMomentIntent: AppIntent {
static var title: LocalizedStringResource = "Momentaufnahme speichern"
static var description = IntentDescription("Speichert eine schnelle Stimmungsabfrage aus dem Homescreen-Widget.")
static var openAppWhenRun = true
@Parameter(title: "Stimmung")
var rating: MomentRatingValue
init() {
rating = .middle
}
init(rating: MomentRatingValue) {
self.rating = rating
}
func perform() async throws -> some IntentResult {
MomentWidgetStorage.enqueue(ratingRawValue: rating.rawValue)
WidgetCenter.shared.reloadTimelines(ofKind: Moment.kind)
return .result()
}
}
enum MomentWidgetStorage {
static let appGroupIdentifier = "group.de.feelaloud"
static let pendingSnapshotsKey = "pendingWidgetSnapshots"
static let lastRatingKey = "lastWidgetSnapshotRating"
static let lastRecordedAtKey = "lastWidgetSnapshotDate"
static var defaults: UserDefaults {
UserDefaults(suiteName: appGroupIdentifier) ?? .standard
}
static func enqueue(ratingRawValue: String) {
let defaults = defaults
var snapshots = pendingSnapshots(from: defaults)
snapshots.append(PendingWidgetSnapshot(ratingRawValue: ratingRawValue, createdAt: .now))
if let data = try? JSONEncoder().encode(snapshots) {
defaults.set(data, forKey: pendingSnapshotsKey)
}
defaults.set(ratingRawValue, forKey: lastRatingKey)
defaults.set(Date.now, forKey: lastRecordedAtKey)
}
private static func pendingSnapshots(from defaults: UserDefaults) -> [PendingWidgetSnapshot] {
guard let data = defaults.data(forKey: pendingSnapshotsKey),
let snapshots = try? JSONDecoder().decode([PendingWidgetSnapshot].self, from: data) else {
return []
}
return snapshots
}
}
struct PendingWidgetSnapshot: Codable {
var ratingRawValue: String
var createdAt: Date
}