import Foundation import Observation import ParcelCore import ParcelEngine @MainActor @Observable final class SetupEditorModel: Identifiable { let id = UUID() let setupID: UUID? var name: String var emoji: String var shortcut: String var hideOtherApps: Bool private(set) var failure: String? private(set) var isSaving = false init(setup: SavedSetup? = nil) { setupID = setup?.id name = setup?.name ?? "" emoji = setup?.emoji ?? "" shortcut = setup?.shortcut ?? "" hideOtherApps = setup?.hideOtherApps ?? true } var canSubmit: Bool { !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isSaving } var title: String { setupID == nil ? SettingsText.string("Save Setup") : SettingsText.string("Edit Setup") } func validatedDraft() throws -> SavedSetup { let normalizedShortcut = shortcut.trimmingCharacters(in: .whitespacesAndNewlines) let chord = normalizedShortcut.isEmpty ? nil : try ShortcutRecorderParser.parse(normalizedShortcut) let normalizedEmoji = emoji.trimmingCharacters(in: .whitespacesAndNewlines) let draft = SavedSetup( name: name.trimmingCharacters(in: .whitespacesAndNewlines), emoji: normalizedEmoji.isEmpty ? nil : normalizedEmoji, shortcut: chord?.description, hideOtherApps: hideOtherApps, memory: .init()) do { try draft.validate() } catch let error as SavedSetupError { switch error { case .invalidName: throw SettingsFailure(SettingsText.string("Enter a setup name of up to 128 characters.")) case .invalidEmoji: throw SettingsFailure(SettingsText.string("Choose one emoji, or leave the emoji empty.")) default: throw error } } return draft } func submit(to coordinator: SetupCoordinator) async -> Bool { guard !isSaving, !coordinator.isBusy else { return false } isSaving = true failure = nil defer { isSaving = false } let draft: SavedSetup do { draft = try validatedDraft() } catch { failure = error.localizedDescription return false } do { if let setupID { try await coordinator.edit( setupID, name: draft.name, emoji: draft.emoji, shortcut: draft.shortcut, hideOtherApps: draft.hideOtherApps) } else { try await coordinator.save( name: draft.name, emoji: draft.emoji, hideOtherApps: draft.hideOtherApps, shortcut: draft.shortcut) } return true } catch SavedSetupError.duplicateName { failure = SettingsText.string("A setup with that name already exists.") return false } catch { failure = coordinator.failure ?? error.localizedDescription return false } } func recordFailure(_ error: SettingsFailure) { failure = error.message } }