46 lines
1.2 KiB
Swift
46 lines
1.2 KiB
Swift
import Foundation
|
|
import Observation
|
|
import SwiftData
|
|
|
|
@MainActor
|
|
@Observable
|
|
final class CategoryViewModel {
|
|
private(set) var categories: [Category] = []
|
|
private var context: ModelContext?
|
|
|
|
static let presetColors: [String] = [
|
|
"#2EB852", "#F5DC1F", "#4A90D9", "#F5A623",
|
|
"#9B59B6", "#E74C3C", "#1ABC9C", "#F39C12"
|
|
]
|
|
|
|
func setup(context: ModelContext) {
|
|
self.context = context
|
|
fetchCategories()
|
|
}
|
|
|
|
func fetchCategories() {
|
|
guard let context else { return }
|
|
let descriptor = FetchDescriptor<Category>(sortBy: [SortDescriptor(\.name)])
|
|
categories = (try? context.fetch(descriptor)) ?? []
|
|
}
|
|
|
|
func addCategory(name: String, colorHex: String) {
|
|
guard let context else { return }
|
|
let category = Category(name: name, colorHex: colorHex)
|
|
context.insert(category)
|
|
try? context.save()
|
|
fetchCategories()
|
|
}
|
|
|
|
func deleteCategory(_ category: Category) {
|
|
guard let context else { return }
|
|
context.delete(category)
|
|
try? context.save()
|
|
fetchCategories()
|
|
}
|
|
|
|
func taskCount(for category: Category) -> Int {
|
|
category.tasks.count
|
|
}
|
|
}
|