57 lines
1.6 KiB
Swift
57 lines
1.6 KiB
Swift
import CoreDomain
|
|
import CoreModel
|
|
import Observation
|
|
|
|
/// 提交计划页状态。
|
|
public enum PlanSubmitUiState: Equatable {
|
|
case loading
|
|
case success(PlanSubmitData)
|
|
case error(String)
|
|
}
|
|
|
|
@MainActor
|
|
@Observable
|
|
public final class PlanSubmitViewModel {
|
|
public private(set) var uiState: PlanSubmitUiState = .loading
|
|
public var saving = false
|
|
public var saved = false
|
|
|
|
private let planUseCase: PlanUseCase
|
|
private let type: PlanType
|
|
private let periodKey: String
|
|
private var loadTask: Task<Void, Never>?
|
|
|
|
public init(planUseCase: PlanUseCase, type: PlanType, periodKey: String) {
|
|
self.planUseCase = planUseCase
|
|
self.type = type
|
|
self.periodKey = periodKey
|
|
}
|
|
|
|
public func load() {
|
|
loadTask?.cancel()
|
|
loadTask = Task { [weak self] in
|
|
guard let self else { return }
|
|
self.uiState = .loading
|
|
do {
|
|
for try await data in self.planUseCase.observePlanSubmit(type: self.type, periodKey: self.periodKey) {
|
|
self.uiState = .success(data)
|
|
}
|
|
} catch is CancellationError {
|
|
} catch {
|
|
self.uiState = .error(error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
|
|
public func save(content: String) {
|
|
guard !saving else { return }
|
|
saving = true
|
|
Task { [weak self] in
|
|
guard let self else { return }
|
|
try? await self.planUseCase.savePlan(type: self.type, periodKey: self.periodKey, content: content, attachments: [])
|
|
self.saving = false
|
|
self.saved = true
|
|
}
|
|
}
|
|
}
|