From a18c06076b6196271e9f2efb7a3d739f7961c21e Mon Sep 17 00:00:00 2001 From: Sarah Wolff Date: Thu, 9 Jul 2026 14:20:35 -0400 Subject: [PATCH 1/2] feat(profiles): scope reader preferences --- Piperly/App/PiperlyApp.swift | 6 +- Piperly/Models/ReaderProfile.swift | 132 ++++++++++++- Piperly/Services/BookStore.swift | 97 +++++++--- Piperly/Views/Reader/ReaderView.swift | 12 +- Piperly/Views/Reader/WordListSheet.swift | 6 +- .../Views/Settings/ReadingSettingsSheet.swift | 12 +- Piperly/Views/Settings/SettingsView.swift | 57 ++---- Piperly/Views/Settings/VoicePickerSheet.swift | 10 +- Piperly/Views/Settings/VoiceSetupSheet.swift | 17 +- Piperly/Views/Words/WordsView.swift | 6 +- PiperlyTests/PiperlyTests.swift | 177 +++++++++++++++++- 11 files changed, 427 insertions(+), 105 deletions(-) diff --git a/Piperly/App/PiperlyApp.swift b/Piperly/App/PiperlyApp.swift index f066af0..a8893a6 100644 --- a/Piperly/App/PiperlyApp.swift +++ b/Piperly/App/PiperlyApp.swift @@ -20,7 +20,6 @@ import SwiftUI struct PiperlyApp: App { @StateObject private var bookStore = BookStore() private let ttsEngine = TTSEngine() - @AppStorage("hasCompletedVoiceSetup") private var hasCompletedVoiceSetup = false @State private var showVoiceSetup = false @Environment(\.scenePhase) private var scenePhase @@ -31,13 +30,14 @@ struct PiperlyApp: App { .task { await bookStore.importSampleBooksIfNeeded() } - .onAppear { - if !hasCompletedVoiceSetup { + .onChange(of: bookStore.selectedProfileID, initial: true) { + if !bookStore.activeProfile.hasCompletedVoiceSetup { showVoiceSetup = true } } .sheet(isPresented: $showVoiceSetup) { VoiceSetupSheet(ttsEngine: ttsEngine) + .environmentObject(bookStore) } .onChange(of: scenePhase) { _, newPhase in if newPhase != .active { diff --git a/Piperly/Models/ReaderProfile.swift b/Piperly/Models/ReaderProfile.swift index 8e7f522..4d37255 100644 --- a/Piperly/Models/ReaderProfile.swift +++ b/Piperly/Models/ReaderProfile.swift @@ -20,24 +20,146 @@ struct ReaderProfile: Identifiable, Codable, Hashable, Sendable { static let defaultName = "Reader" static let defaultAvatarSymbol = "person.crop.circle.fill" static let defaultColorName = "accent" + static let defaultVoiceIdentifier = "" + static let defaultSpeechRate = 0.45 + static let defaultFontSize = 22.0 + static let defaultReaderTheme = "piperly" + + enum NicknameValidationError: Error, Equatable, LocalizedError { + case empty + case tooLong + case containsWhitespace + case containsDigits + case containsAccountIdentifier + + var errorDescription: String? { + switch self { + case .empty: + "Enter a nickname." + case .tooLong: + "Keep nicknames under 20 characters." + case .containsWhitespace: + "Use one nickname, not a full name." + case .containsDigits: + "Do not enter birthdays or ages." + case .containsAccountIdentifier: + "Do not enter email addresses or Apple IDs." + } + } + } let id: UUID - var name: String + private(set) var name: String var avatarSymbol: String var colorName: String let createdAt: Date + var voiceIdentifier: String + var speechRate: Double + var fontSize: Double + var readerTheme: String + var hasCompletedVoiceSetup: Bool init( id: UUID = UUID(), - name: String = Self.defaultName, + name: String, avatarSymbol: String = Self.defaultAvatarSymbol, colorName: String = Self.defaultColorName, - createdAt: Date = .now - ) { + createdAt: Date = .now, + voiceIdentifier: String = Self.defaultVoiceIdentifier, + speechRate: Double = Self.defaultSpeechRate, + fontSize: Double = Self.defaultFontSize, + readerTheme: String = Self.defaultReaderTheme, + hasCompletedVoiceSetup: Bool = false + ) throws { self.id = id - self.name = name + self.name = try Self.validatedNickname(name) self.avatarSymbol = avatarSymbol self.colorName = colorName self.createdAt = createdAt + self.voiceIdentifier = voiceIdentifier + self.speechRate = speechRate + self.fontSize = fontSize + self.readerTheme = readerTheme + self.hasCompletedVoiceSetup = hasCompletedVoiceSetup + } + + init() { + id = UUID() + name = Self.defaultName + avatarSymbol = Self.defaultAvatarSymbol + colorName = Self.defaultColorName + createdAt = .now + voiceIdentifier = Self.defaultVoiceIdentifier + speechRate = Self.defaultSpeechRate + fontSize = Self.defaultFontSize + readerTheme = Self.defaultReaderTheme + hasCompletedVoiceSetup = false + } + + mutating func updateNickname(_ name: String) throws { + self.name = try Self.validatedNickname(name) + } + + static func nicknameValidationError(for name: String) -> NicknameValidationError? { + do { + _ = try validatedNickname(name) + return nil + } catch let error as NicknameValidationError { + return error + } catch { + return .empty + } + } + + private static func validatedNickname(_ name: String) throws -> String { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw NicknameValidationError.empty + } + if trimmed.count > 20 { + throw NicknameValidationError.tooLong + } + if trimmed.rangeOfCharacter(from: .whitespacesAndNewlines) != nil { + throw NicknameValidationError.containsWhitespace + } + if trimmed.rangeOfCharacter(from: .decimalDigits) != nil { + throw NicknameValidationError.containsDigits + } + if trimmed.contains("@") || trimmed.contains(".") { + throw NicknameValidationError.containsAccountIdentifier + } + return trimmed + } + + private enum CodingKeys: String, CodingKey { + case id + case name + case avatarSymbol + case colorName + case createdAt + case voiceIdentifier + case speechRate + case fontSize + case readerTheme + case hasCompletedVoiceSetup + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(UUID.self, forKey: .id) + name = try Self.validatedNickname(container.decode(String.self, forKey: .name)) + avatarSymbol = try container.decode(String.self, forKey: .avatarSymbol) + colorName = try container.decode(String.self, forKey: .colorName) + createdAt = try container.decode(Date.self, forKey: .createdAt) + voiceIdentifier = try container.decodeIfPresent(String.self, forKey: .voiceIdentifier) + ?? Self.defaultVoiceIdentifier + speechRate = try container.decodeIfPresent(Double.self, forKey: .speechRate) + ?? Self.defaultSpeechRate + fontSize = try container.decodeIfPresent(Double.self, forKey: .fontSize) + ?? Self.defaultFontSize + readerTheme = try container.decodeIfPresent(String.self, forKey: .readerTheme) + ?? Self.defaultReaderTheme + hasCompletedVoiceSetup = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedVoiceSetup) + ?? false } } diff --git a/Piperly/Services/BookStore.swift b/Piperly/Services/BookStore.swift index 2219312..c47ff59 100644 --- a/Piperly/Services/BookStore.swift +++ b/Piperly/Services/BookStore.swift @@ -30,6 +30,7 @@ class BookStore: ObservableObject { private let documentsURL: URL private let coversURL: URL + private let userDefaults: UserDefaults private let booksKey = "piperly_books" private let profilesKey = "piperly_reader_profiles" private let selectedProfileKey = "piperly_selected_profile_id" @@ -40,10 +41,11 @@ class BookStore: ObservableObject { private var debouncedReadingStatesSave: Task? private var debouncedWordsSave: Task? - init() { + init(userDefaults: UserDefaults = .standard) { let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] self.documentsURL = docs.appendingPathComponent("Books", isDirectory: true) self.coversURL = docs.appendingPathComponent("Covers", isDirectory: true) + self.userDefaults = userDefaults try? FileManager.default.createDirectory(at: documentsURL, withIntermediateDirectories: true) try? FileManager.default.createDirectory(at: coversURL, withIntermediateDirectories: true) @@ -68,7 +70,7 @@ class BookStore: ObservableObject { } func loadBooks() { - guard let data = UserDefaults.standard.data(forKey: booksKey), + guard let data = userDefaults.data(forKey: booksKey), let saved = try? JSONDecoder().decode([Book].self, from: data) else { return } @@ -77,12 +79,12 @@ class BookStore: ObservableObject { func saveBooks() { if let data = try? JSONEncoder().encode(books) { - UserDefaults.standard.set(data, forKey: booksKey) + userDefaults.set(data, forKey: booksKey) } } func loadProfiles() { - guard let data = UserDefaults.standard.data(forKey: profilesKey), + guard let data = userDefaults.data(forKey: profilesKey), let saved = try? JSONDecoder().decode([ReaderProfile].self, from: data) else { return } @@ -91,12 +93,12 @@ class BookStore: ObservableObject { func saveProfiles() { if let data = try? JSONEncoder().encode(profiles) { - UserDefaults.standard.set(data, forKey: profilesKey) + userDefaults.set(data, forKey: profilesKey) } } func loadSelectedProfileID() { - guard let rawValue = UserDefaults.standard.string(forKey: selectedProfileKey), + guard let rawValue = userDefaults.string(forKey: selectedProfileKey), let id = UUID(uuidString: rawValue) else { return } @@ -105,7 +107,7 @@ class BookStore: ObservableObject { func saveSelectedProfileID() { guard let selectedProfileID else { return } - UserDefaults.standard.set(selectedProfileID.uuidString, forKey: selectedProfileKey) + userDefaults.set(selectedProfileID.uuidString, forKey: selectedProfileKey) } /// Guarantees there is always at least one profile and a valid selection. @@ -141,8 +143,8 @@ class BookStore: ObservableObject { } @discardableResult - func addProfile(name: String, avatarSymbol: String, colorName: String) -> ReaderProfile { - let profile = ReaderProfile( + func addProfile(name: String, avatarSymbol: String, colorName: String) throws -> ReaderProfile { + let profile = try ReaderProfile( name: Self.sanitizedProfileName(name), avatarSymbol: avatarSymbol, colorName: colorName @@ -154,9 +156,9 @@ class BookStore: ObservableObject { return profile } - func updateProfile(_ profileID: UUID, name: String, avatarSymbol: String, colorName: String) { + func updateProfile(_ profileID: UUID, name: String, avatarSymbol: String, colorName: String) throws { guard let index = profiles.firstIndex(where: { $0.id == profileID }) else { return } - profiles[index].name = Self.sanitizedProfileName(name) + try profiles[index].updateNickname(Self.sanitizedProfileName(name)) profiles[index].avatarSymbol = avatarSymbol profiles[index].colorName = colorName saveProfiles() @@ -182,12 +184,65 @@ class BookStore: ObservableObject { } private static func sanitizedProfileName(_ name: String) -> String { - let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? ReaderProfile.defaultName : trimmed + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func updateActiveProfile(_ update: (inout ReaderProfile) -> Void) { + guard let index = profiles.firstIndex(where: { $0.id == activeProfileID }) else { return } + update(&profiles[index]) + saveProfiles() + } + + var activeVoiceIdentifier: String { + activeProfile.voiceIdentifier + } + + var activeSpeechRate: Double { + activeProfile.speechRate + } + + var activeFontSize: Double { + activeProfile.fontSize + } + + var activeReaderTheme: ReaderTheme { + ReaderTheme(rawValue: activeProfile.readerTheme) ?? .piperly + } + + var activeVoiceIdentifierBinding: Binding { + Binding( + get: { self.activeVoiceIdentifier }, + set: { value in self.updateActiveProfile { $0.voiceIdentifier = value } } + ) + } + + var activeSpeechRateBinding: Binding { + Binding( + get: { self.activeSpeechRate }, + set: { value in self.updateActiveProfile { $0.speechRate = value } } + ) + } + + var activeFontSizeBinding: Binding { + Binding( + get: { self.activeFontSize }, + set: { value in self.updateActiveProfile { $0.fontSize = value } } + ) + } + + var activeReaderThemeBinding: Binding { + Binding( + get: { self.activeProfile.readerTheme }, + set: { value in self.updateActiveProfile { $0.readerTheme = value } } + ) + } + + func completeVoiceSetup() { + updateActiveProfile { $0.hasCompletedVoiceSetup = true } } func loadReadingStates() { - guard let data = UserDefaults.standard.data(forKey: readingStatesKey), + guard let data = userDefaults.data(forKey: readingStatesKey), let saved = try? JSONDecoder().decode([ReadingState].self, from: data) else { return } @@ -196,7 +251,7 @@ class BookStore: ObservableObject { func saveReadingStates() { if let data = try? JSONEncoder().encode(readingStates) { - UserDefaults.standard.set(data, forKey: readingStatesKey) + userDefaults.set(data, forKey: readingStatesKey) } } @@ -323,7 +378,7 @@ class BookStore: ObservableObject { // MARK: - Bookmarks func loadBookmarks() { - guard let data = UserDefaults.standard.data(forKey: bookmarksKey), + guard let data = userDefaults.data(forKey: bookmarksKey), let saved = try? JSONDecoder().decode([Bookmark].self, from: data) else { return } @@ -332,7 +387,7 @@ class BookStore: ObservableObject { func saveBookmarks() { if let data = try? JSONEncoder().encode(bookmarks) { - UserDefaults.standard.set(data, forKey: bookmarksKey) + userDefaults.set(data, forKey: bookmarksKey) } } @@ -377,7 +432,7 @@ class BookStore: ObservableObject { // MARK: - Saved Words func loadSavedWords() { - guard let data = UserDefaults.standard.data(forKey: savedWordsKey), + guard let data = userDefaults.data(forKey: savedWordsKey), let saved = try? JSONDecoder().decode([SavedWord].self, from: data) else { return } @@ -386,7 +441,7 @@ class BookStore: ObservableObject { func saveSavedWords() { if let data = try? JSONEncoder().encode(savedWords) { - UserDefaults.standard.set(data, forKey: savedWordsKey) + userDefaults.set(data, forKey: savedWordsKey) } } @@ -432,7 +487,7 @@ class BookStore: ObservableObject { // MARK: - Samples func importSampleBooksIfNeeded() async { - let hasImportedSamples = UserDefaults.standard.bool(forKey: "piperly_samples_imported") + let hasImportedSamples = userDefaults.bool(forKey: "piperly_samples_imported") guard !hasImportedSamples else { return } let sampleFiles = Bundle.main.urls(forResourcesWithExtension: "epub", subdirectory: nil) ?? [] @@ -440,7 +495,7 @@ class BookStore: ObservableObject { _ = try? await importBundledBook(from: url) } - UserDefaults.standard.set(true, forKey: "piperly_samples_imported") + userDefaults.set(true, forKey: "piperly_samples_imported") } private func importBundledBook(from bundleURL: URL) async throws -> Book { diff --git a/Piperly/Views/Reader/ReaderView.swift b/Piperly/Views/Reader/ReaderView.swift index 796da64..60d204e 100644 --- a/Piperly/Views/Reader/ReaderView.swift +++ b/Piperly/Views/Reader/ReaderView.swift @@ -37,10 +37,6 @@ struct ReaderView: View { @State private var showWordBubble = false @State private var isNewWord = false @State private var showingWordList = false - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" - @AppStorage("speechRate") private var speechRate: Double = 0.45 - @AppStorage("readerFontSize") private var fontSize: Double = 22 - @AppStorage("readerTheme") private var selectedTheme: String = ReaderTheme.piperly.rawValue @StateObject private var wordTapCoordinator = WordTapCoordinator() @State private var navigator: EPUBNavigatorViewController? @State private var currentLocator: Locator? @@ -263,11 +259,11 @@ struct ReaderView: View { } private var theme: ReaderTheme { - ReaderTheme(rawValue: selectedTheme) ?? .piperly + bookStore.activeReaderTheme } private var readerPreferences: EPUBPreferences { - theme.epubPreferences(fontSize: fontSize) + theme.epubPreferences(fontSize: bookStore.activeFontSize) } private var restoredLocator: Locator? { @@ -286,8 +282,8 @@ struct ReaderView: View { } ttsEngine.speak( word: word, - voiceIdentifier: selectedVoiceIdentifier, - rate: Float(speechRate) + voiceIdentifier: bookStore.activeVoiceIdentifier, + rate: Float(bookStore.activeSpeechRate) ) } diff --git a/Piperly/Views/Reader/WordListSheet.swift b/Piperly/Views/Reader/WordListSheet.swift index 4b398c8..b322043 100644 --- a/Piperly/Views/Reader/WordListSheet.swift +++ b/Piperly/Views/Reader/WordListSheet.swift @@ -21,8 +21,6 @@ struct WordListSheet: View { let bookID: UUID let ttsEngine: TTSEngine @Environment(\.dismiss) private var dismiss - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" - @AppStorage("speechRate") private var speechRate: Double = 0.45 private var words: [SavedWord] { bookStore.words(for: bookID) @@ -51,8 +49,8 @@ struct WordListSheet: View { Button { ttsEngine.speak( word: word.displayWord, - voiceIdentifier: selectedVoiceIdentifier, - rate: Float(speechRate) + voiceIdentifier: bookStore.activeVoiceIdentifier, + rate: Float(bookStore.activeSpeechRate) ) } label: { HStack { diff --git a/Piperly/Views/Settings/ReadingSettingsSheet.swift b/Piperly/Views/Settings/ReadingSettingsSheet.swift index acb1ace..6fb938a 100644 --- a/Piperly/Views/Settings/ReadingSettingsSheet.swift +++ b/Piperly/Views/Settings/ReadingSettingsSheet.swift @@ -18,12 +18,10 @@ import SwiftUI struct ReadingSettingsSheet: View { @Environment(\.dismiss) private var dismiss - @AppStorage("readerFontSize") private var fontSize: Double = 22 - @AppStorage("readerTheme") private var selectedTheme: String = ReaderTheme.piperly.rawValue - @AppStorage("speechRate") private var speechRate: Double = 0.45 + @EnvironmentObject private var bookStore: BookStore private var theme: ReaderTheme { - ReaderTheme(rawValue: selectedTheme) ?? .piperly + bookStore.activeReaderTheme } var body: some View { @@ -41,7 +39,7 @@ struct ReadingSettingsSheet: View { HStack(spacing: 16) { ForEach(ReaderTheme.allCases) { t in Button { - selectedTheme = t.rawValue + bookStore.activeReaderThemeBinding.wrappedValue = t.rawValue } label: { VStack(spacing: 8) { Circle() @@ -82,7 +80,7 @@ struct ReadingSettingsSheet: View { Text("A") .font(.system(size: 14)) .foregroundStyle(Piperly.Colors.textTertiary) - Slider(value: $fontSize, in: 18...30, step: 1) + Slider(value: bookStore.activeFontSizeBinding, in: 18...30, step: 1) .tint(Piperly.Colors.accent) Text("A") .font(.system(size: 24)) @@ -98,7 +96,7 @@ struct ReadingSettingsSheet: View { HStack { Image(systemName: "tortoise") .foregroundStyle(Piperly.Colors.textTertiary) - Slider(value: $speechRate, in: 0.30...0.60, step: 0.05) + Slider(value: bookStore.activeSpeechRateBinding, in: 0.30...0.60, step: 0.05) .tint(Piperly.Colors.accent) Image(systemName: "hare") .foregroundStyle(Piperly.Colors.textPrimary) diff --git a/Piperly/Views/Settings/SettingsView.swift b/Piperly/Views/Settings/SettingsView.swift index 8235be2..80718bf 100644 --- a/Piperly/Views/Settings/SettingsView.swift +++ b/Piperly/Views/Settings/SettingsView.swift @@ -21,21 +21,17 @@ struct SettingsView: View { @Environment(\.dismiss) private var dismiss @EnvironmentObject private var bookStore: BookStore - @AppStorage("readerFontSize") private var fontSize: Double = 22 - @AppStorage("readerTheme") private var selectedTheme: String = ReaderTheme.piperly.rawValue - @AppStorage("speechRate") private var speechRate: Double = 0.45 - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" @State private var isVoiceListExpanded = false @State private var voices: [Voice] = [] let ttsEngine: TTSEngine private var theme: ReaderTheme { - ReaderTheme(rawValue: selectedTheme) ?? .piperly + bookStore.activeReaderTheme } private var selectedVoiceName: String { - if let voice = voices.first(where: { $0.id == selectedVoiceIdentifier }) { + if let voice = voices.first(where: { $0.id == bookStore.activeVoiceIdentifier }) { return voice.name } return voices.first?.name ?? "Choose Voice" @@ -116,7 +112,7 @@ struct SettingsView: View { HStack { Image(systemName: "textformat.size.smaller") .foregroundStyle(Piperly.Colors.textTertiary) - Slider(value: $fontSize, in: 18...30, step: 1) { + Slider(value: bookStore.activeFontSizeBinding, in: 18...30, step: 1) { Text("Font Size") } minimumValueLabel: { Image(systemName: "textformat.size.smaller") @@ -140,7 +136,7 @@ struct SettingsView: View { ForEach(ReaderTheme.allCases) { readerTheme in Button { withAnimation(.snappy) { - selectedTheme = readerTheme.rawValue + bookStore.activeReaderThemeBinding.wrappedValue = readerTheme.rawValue } } label: { VStack(spacing: 6) { @@ -176,7 +172,7 @@ struct SettingsView: View { .padding(.vertical, 2) } - ReaderThemePreview(theme: theme, fontSize: fontSize) + ReaderThemePreview(theme: theme, fontSize: bookStore.activeFontSize) } .padding(.vertical, 4) } header: { @@ -230,13 +226,13 @@ struct SettingsView: View { ForEach(voices) { voice in SettingsVoiceRow( voice: voice, - isSelected: voice.id == selectedVoiceIdentifier, - onSelect: { selectedVoiceIdentifier = voice.id }, + isSelected: voice.id == bookStore.activeVoiceIdentifier, + onSelect: { bookStore.activeVoiceIdentifierBinding.wrappedValue = voice.id }, onPreview: { ttsEngine.speak( word: "Hi, I'm \(voice.name)!", voiceIdentifier: voice.id, - rate: Float(speechRate) + rate: Float(bookStore.activeSpeechRate) ) } ) @@ -254,7 +250,7 @@ struct SettingsView: View { HStack { Image(systemName: "tortoise") .foregroundStyle(Piperly.Colors.textTertiary) - Slider(value: $speechRate, in: 0.30...0.60, step: 0.05) { + Slider(value: bookStore.activeSpeechRateBinding, in: 0.30...0.60, step: 0.05) { Text("Voice Speed") } minimumValueLabel: { Image(systemName: "tortoise") @@ -294,9 +290,9 @@ struct SettingsView: View { private func refreshVoices() { voices = Voice.availableVoices() - if !voices.contains(where: { $0.id == selectedVoiceIdentifier }), + if !voices.contains(where: { $0.id == bookStore.activeVoiceIdentifier }), let first = voices.first { - selectedVoiceIdentifier = first.id + bookStore.activeVoiceIdentifierBinding.wrappedValue = first.id } } } @@ -430,7 +426,7 @@ private struct ReaderProfilesView: View { title: "Add Profile", profile: nil, onSave: { draft in - bookStore.addProfile( + try bookStore.addProfile( name: draft.name, avatarSymbol: draft.avatarSymbol, colorName: draft.colorName @@ -445,7 +441,7 @@ private struct ReaderProfilesView: View { title: "Edit Profile", profile: profile, onSave: { draft in - bookStore.updateProfile( + try bookStore.updateProfile( profile.id, name: draft.name, avatarSymbol: draft.avatarSymbol, @@ -542,9 +538,9 @@ private struct ProfileEditorView: View { @State private var draft: ProfileDraft let title: String - let onSave: (ProfileDraft) -> Void + let onSave: (ProfileDraft) throws -> Void - init(title: String, profile: ReaderProfile?, onSave: @escaping (ProfileDraft) -> Void) { + init(title: String, profile: ReaderProfile?, onSave: @escaping (ProfileDraft) throws -> Void) { self.title = title self.onSave = onSave _draft = State(initialValue: ProfileDraft(profile: profile)) @@ -593,8 +589,9 @@ private struct ProfileEditorView: View { } ToolbarItem(placement: .confirmationAction) { Button("Save") { - onSave(draft) - dismiss() + if (try? onSave(draft)) != nil { + dismiss() + } } .disabled(nameError != nil) .foregroundStyle(Piperly.Colors.accent) @@ -853,23 +850,7 @@ private struct ProfileDraft { } static func validationError(for name: String) -> String? { - let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { - return "Enter a nickname." - } - if trimmed.count > 20 { - return "Keep nicknames under 20 characters." - } - if trimmed.rangeOfCharacter(from: .whitespacesAndNewlines) != nil { - return "Use one nickname, not a full name." - } - if trimmed.rangeOfCharacter(from: .decimalDigits) != nil { - return "Do not enter birthdays or ages." - } - if trimmed.contains("@") || trimmed.contains(".") { - return "Do not enter email addresses or Apple IDs." - } - return nil + ReaderProfile.nicknameValidationError(for: name)?.localizedDescription } } diff --git a/Piperly/Views/Settings/VoicePickerSheet.swift b/Piperly/Views/Settings/VoicePickerSheet.swift index 370d190..77fddec 100644 --- a/Piperly/Views/Settings/VoicePickerSheet.swift +++ b/Piperly/Views/Settings/VoicePickerSheet.swift @@ -31,7 +31,7 @@ struct VoicePickerSheet: View { struct VoicePickerList: View { @Environment(\.dismiss) private var dismiss - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" + @EnvironmentObject private var bookStore: BookStore @State private var voices: [Voice] = [] let ttsEngine: TTSEngine @@ -61,8 +61,8 @@ struct VoicePickerList: View { ForEach(voices) { voice in VoiceCard( voice: voice, - isSelected: voice.id == selectedVoiceIdentifier, - onSelect: { selectedVoiceIdentifier = voice.id }, + isSelected: voice.id == bookStore.activeVoiceIdentifier, + onSelect: { bookStore.activeVoiceIdentifierBinding.wrappedValue = voice.id }, onPreview: { ttsEngine.speak( word: "Hi, I'm \(voice.name)!", @@ -103,9 +103,9 @@ struct VoicePickerList: View { private func refreshVoices() { voices = Voice.availableVoices() - if !voices.contains(where: { $0.id == selectedVoiceIdentifier }), + if !voices.contains(where: { $0.id == bookStore.activeVoiceIdentifier }), let first = voices.first { - selectedVoiceIdentifier = first.id + bookStore.activeVoiceIdentifierBinding.wrappedValue = first.id } } } diff --git a/Piperly/Views/Settings/VoiceSetupSheet.swift b/Piperly/Views/Settings/VoiceSetupSheet.swift index 5d03f7d..4d8062c 100644 --- a/Piperly/Views/Settings/VoiceSetupSheet.swift +++ b/Piperly/Views/Settings/VoiceSetupSheet.swift @@ -19,8 +19,7 @@ import AVFoundation struct VoiceSetupSheet: View { @Environment(\.dismiss) private var dismiss - @AppStorage("hasCompletedVoiceSetup") private var hasCompletedVoiceSetup = false - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" + @EnvironmentObject private var bookStore: BookStore @State private var voices: [Voice] = [] let ttsEngine: TTSEngine @@ -55,9 +54,9 @@ struct VoiceSetupSheet: View { ForEach(voices) { voice in VoiceRow( voice: voice, - isSelected: voice.id == selectedVoiceIdentifier, + isSelected: voice.id == bookStore.activeVoiceIdentifier, onTap: { - selectedVoiceIdentifier = voice.id + bookStore.activeVoiceIdentifierBinding.wrappedValue = voice.id ttsEngine.speak( word: previewPhrase, voiceIdentifier: voice.id, @@ -107,11 +106,11 @@ struct VoiceSetupSheet: View { } Button { - if let first = voices.first, selectedVoiceIdentifier.isEmpty { - selectedVoiceIdentifier = first.id + if let first = voices.first, bookStore.activeVoiceIdentifier.isEmpty { + bookStore.activeVoiceIdentifierBinding.wrappedValue = first.id } ttsEngine.stop() - hasCompletedVoiceSetup = true + bookStore.completeVoiceSetup() dismiss() } label: { Text("Continue") @@ -155,9 +154,9 @@ struct VoiceSetupSheet: View { private func refreshVoices() { voices = Voice.availableVoices() - if !voices.contains(where: { $0.id == selectedVoiceIdentifier }), + if !voices.contains(where: { $0.id == bookStore.activeVoiceIdentifier }), let first = voices.first { - selectedVoiceIdentifier = first.id + bookStore.activeVoiceIdentifierBinding.wrappedValue = first.id } } diff --git a/Piperly/Views/Words/WordsView.swift b/Piperly/Views/Words/WordsView.swift index dfd7956..130bb09 100644 --- a/Piperly/Views/Words/WordsView.swift +++ b/Piperly/Views/Words/WordsView.swift @@ -19,8 +19,6 @@ import SwiftUI struct WordsView: View { @EnvironmentObject var bookStore: BookStore let ttsEngine: TTSEngine - @AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = "" - @AppStorage("speechRate") private var speechRate: Double = 0.45 @State private var viewMode: ViewMode = .all enum ViewMode: String, CaseIterable { @@ -133,8 +131,8 @@ struct WordsView: View { private func speakWord(_ word: SavedWord) { ttsEngine.speak( word: word.displayWord, - voiceIdentifier: selectedVoiceIdentifier, - rate: Float(speechRate) + voiceIdentifier: bookStore.activeVoiceIdentifier, + rate: Float(bookStore.activeSpeechRate) ) } diff --git a/PiperlyTests/PiperlyTests.swift b/PiperlyTests/PiperlyTests.swift index 4bbf3ff..e009207 100644 --- a/PiperlyTests/PiperlyTests.swift +++ b/PiperlyTests/PiperlyTests.swift @@ -171,16 +171,191 @@ struct ReaderProfileTests { #expect(profile.name == "Reader") #expect(profile.avatarSymbol == "person.crop.circle.fill") #expect(profile.colorName == "accent") + #expect(profile.voiceIdentifier.isEmpty) + #expect(profile.speechRate == 0.45) + #expect(profile.fontSize == 22) + #expect(profile.readerTheme == "piperly") + #expect(!profile.hasCompletedVoiceSetup) } @Test func codableRoundTrip() throws { - let profile = ReaderProfile(name: "Ari", avatarSymbol: "star.fill", colorName: "yellow") + let profile = try ReaderProfile( + name: "Ari", + avatarSymbol: "star.fill", + colorName: "yellow", + voiceIdentifier: "voice.ari", + speechRate: 0.55, + fontSize: 27, + readerTheme: "ocean", + hasCompletedVoiceSetup: true + ) let data = try JSONEncoder().encode(profile) let decoded = try JSONDecoder().decode(ReaderProfile.self, from: data) #expect(decoded.id == profile.id) #expect(decoded.name == "Ari") #expect(decoded.avatarSymbol == "star.fill") #expect(decoded.colorName == "yellow") + #expect(decoded.voiceIdentifier == "voice.ari") + #expect(decoded.speechRate == 0.55) + #expect(decoded.fontSize == 27) + #expect(decoded.readerTheme == "ocean") + #expect(decoded.hasCompletedVoiceSetup) + } + + @Test func decodingOlderProfileUsesPreferenceDefaults() throws { + let id = UUID() + let createdAt = Date(timeIntervalSince1970: 1_700_000_000) + let legacyJSON = """ + { + "id": "\(id.uuidString)", + "name": "Ari", + "avatarSymbol": "star.fill", + "colorName": "yellow", + "createdAt": \(createdAt.timeIntervalSinceReferenceDate) + } + """ + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .deferredToDate + let decoded = try decoder.decode(ReaderProfile.self, from: Data(legacyJSON.utf8)) + #expect(decoded.voiceIdentifier.isEmpty) + #expect(decoded.speechRate == ReaderProfile.defaultSpeechRate) + #expect(decoded.fontSize == ReaderProfile.defaultFontSize) + #expect(decoded.readerTheme == ReaderProfile.defaultReaderTheme) + #expect(!decoded.hasCompletedVoiceSetup) + } + + @Test func rejectsInvalidNicknames() { + #expect(throws: ReaderProfile.NicknameValidationError.empty) { + _ = try ReaderProfile(name: " ") + } + #expect(throws: ReaderProfile.NicknameValidationError.containsWhitespace) { + _ = try ReaderProfile(name: "Ari Smith") + } + #expect(throws: ReaderProfile.NicknameValidationError.containsDigits) { + _ = try ReaderProfile(name: "Ari12") + } + #expect(throws: ReaderProfile.NicknameValidationError.containsAccountIdentifier) { + _ = try ReaderProfile(name: "ari@example.com") + } + } +} + +// MARK: - Reader Profile Preferences + +@Suite("ReaderProfilePreferences", .serialized) +struct ReaderProfilePreferenceTests { + @Test @MainActor func switchingProfilesChangesActivePreferences() throws { + let (store, defaults, suiteName) = makeStore() + defer { defaults.removePersistentDomain(forName: suiteName) } + let firstProfileID = store.activeProfile.id + store.updateActiveProfile { + $0.voiceIdentifier = "voice.first" + $0.fontSize = 24 + } + let secondProfile = try store.addProfile( + name: "Bee", + avatarSymbol: "star.fill", + colorName: "green" + ) + + #expect(store.activeProfile.id == secondProfile.id) + #expect(store.activeVoiceIdentifier.isEmpty) + #expect(store.activeFontSize == ReaderProfile.defaultFontSize) + + store.selectProfile(firstProfileID) + #expect(store.activeVoiceIdentifier == "voice.first") + #expect(store.activeFontSize == 24) + } + + @Test @MainActor func preferencesStayIsolatedBetweenProfiles() throws { + let (store, defaults, suiteName) = makeStore() + defer { defaults.removePersistentDomain(forName: suiteName) } + let firstProfileID = store.activeProfile.id + store.updateActiveProfile { + $0.voiceIdentifier = "voice.first" + $0.speechRate = 0.35 + $0.fontSize = 19 + $0.readerTheme = "forest" + $0.hasCompletedVoiceSetup = true + } + let secondProfile = try store.addProfile( + name: "Bee", + avatarSymbol: "moon.fill", + colorName: "info" + ) + store.updateActiveProfile { + $0.voiceIdentifier = "voice.second" + $0.speechRate = 0.60 + $0.fontSize = 30 + $0.readerTheme = "nightOwl" + } + + store.selectProfile(firstProfileID) + #expect(store.activeProfile.voiceIdentifier == "voice.first") + #expect(store.activeProfile.speechRate == 0.35) + #expect(store.activeProfile.fontSize == 19) + #expect(store.activeProfile.readerTheme == "forest") + #expect(store.activeProfile.hasCompletedVoiceSetup) + + store.selectProfile(secondProfile.id) + #expect(store.activeProfile.voiceIdentifier == "voice.second") + #expect(store.activeProfile.speechRate == 0.60) + #expect(store.activeProfile.fontSize == 30) + #expect(store.activeProfile.readerTheme == "nightOwl") + #expect(!store.activeProfile.hasCompletedVoiceSetup) + } + + @Test @MainActor func preferencesPersistAcrossStoreReload() throws { + let (store, defaults, suiteName) = makeStore() + defer { defaults.removePersistentDomain(forName: suiteName) } + store.updateActiveProfile { + $0.voiceIdentifier = "voice.persisted" + $0.speechRate = 0.50 + $0.fontSize = 26 + $0.readerTheme = "lavender" + $0.hasCompletedVoiceSetup = true + } + + let reloadedStore = BookStore(userDefaults: defaults) + #expect(reloadedStore.activeProfile.id == store.activeProfile.id) + #expect(reloadedStore.activeVoiceIdentifier == "voice.persisted") + #expect(reloadedStore.activeSpeechRate == 0.50) + #expect(reloadedStore.activeFontSize == 26) + #expect(reloadedStore.activeReaderTheme == .lavender) + #expect(reloadedStore.activeProfile.hasCompletedVoiceSetup) + } + + @Test @MainActor func serviceRejectsInvalidNicknameWithoutRemovingDefault() { + let (store, defaults, suiteName) = makeStore() + defer { defaults.removePersistentDomain(forName: suiteName) } + + #expect(throws: ReaderProfile.NicknameValidationError.containsWhitespace) { + _ = try store.addProfile( + name: "Ari Smith", + avatarSymbol: "star.fill", + colorName: "green" + ) + } + #expect(store.profiles.count == 1) + #expect(store.activeProfile.name == ReaderProfile.defaultName) + + #expect(throws: ReaderProfile.NicknameValidationError.containsDigits) { + try store.updateProfile( + store.activeProfile.id, + name: "Reader2", + avatarSymbol: "star.fill", + colorName: "green" + ) + } + #expect(store.activeProfile.name == ReaderProfile.defaultName) + } + + @MainActor + private func makeStore() -> (BookStore, UserDefaults, String) { + let suiteName = "PiperlyTests.ReaderProfilePreferences.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defaults.removePersistentDomain(forName: suiteName) + return (BookStore(userDefaults: defaults), defaults, suiteName) } } From d82ead175f8c10513003f7f5f5df441061e68858 Mon Sep 17 00:00:00 2001 From: Sarah Wolff Date: Thu, 9 Jul 2026 18:23:53 -0400 Subject: [PATCH 2/2] fix(profiles): sanitize legacy nickname on decode instead of throwing ReaderProfile.init(from:) validated the decoded name with validatedNickname, which throws for names that were valid under the old sanitizer (spaces, digits). Combined with try? decode([ReaderProfile].self), one such legacy name wiped the entire profiles array on upgrade. Decode now sanitizes the name to a valid form (or defaultName); validation still throws at the create/update boundary. --- Piperly/Models/ReaderProfile.swift | 14 +++++++++++++- PiperlyTests/PiperlyTests.swift | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Piperly/Models/ReaderProfile.swift b/Piperly/Models/ReaderProfile.swift index 4d37255..59d4bbf 100644 --- a/Piperly/Models/ReaderProfile.swift +++ b/Piperly/Models/ReaderProfile.swift @@ -111,6 +111,18 @@ struct ReaderProfile: Identifiable, Codable, Hashable, Sendable { } } + /// Non-throwing sanitizer for decode: coerces a legacy or invalid persisted + /// nickname into a valid one instead of throwing, so a name that was valid + /// under an older rule (e.g. contained a space or digit) can't wipe the + /// whole profiles array on upgrade. Validation still throws at create/update. + private static func sanitizedNickname(_ name: String) -> String { + if let valid = try? validatedNickname(name) { return valid } + var stripped = name.trimmingCharacters(in: .whitespacesAndNewlines) + stripped.removeAll { $0.isWhitespace || $0.isNumber || $0 == "@" || $0 == "." } + let trimmed = String(stripped.prefix(20)) + return (try? validatedNickname(trimmed)) ?? defaultName + } + private static func validatedNickname(_ name: String) throws -> String { let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { @@ -147,7 +159,7 @@ struct ReaderProfile: Identifiable, Codable, Hashable, Sendable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(UUID.self, forKey: .id) - name = try Self.validatedNickname(container.decode(String.self, forKey: .name)) + name = Self.sanitizedNickname(try container.decode(String.self, forKey: .name)) avatarSymbol = try container.decode(String.self, forKey: .avatarSymbol) colorName = try container.decode(String.self, forKey: .colorName) createdAt = try container.decode(Date.self, forKey: .createdAt) diff --git a/PiperlyTests/PiperlyTests.swift b/PiperlyTests/PiperlyTests.swift index e009207..88d9927 100644 --- a/PiperlyTests/PiperlyTests.swift +++ b/PiperlyTests/PiperlyTests.swift @@ -224,6 +224,24 @@ struct ReaderProfileTests { #expect(!decoded.hasCompletedVoiceSetup) } + // A name that was valid under the old sanitizer (spaces/digits allowed) must + // survive decode by being sanitized, not throw and wipe the profiles array. + @Test func decodingLegacyInvalidNicknameSanitizesInsteadOfThrowing() throws { + let id = UUID() + let legacyJSON = """ + { + "id": "\(id.uuidString)", + "name": "Ari Smith12", + "avatarSymbol": "star.fill", + "colorName": "yellow", + "createdAt": 0 + } + """ + let decoded = try JSONDecoder().decode(ReaderProfile.self, from: Data(legacyJSON.utf8)) + #expect(decoded.id == id) + #expect(decoded.name == "AriSmith") + } + @Test func rejectsInvalidNicknames() { #expect(throws: ReaderProfile.NicknameValidationError.empty) { _ = try ReaderProfile(name: " ")