Branchwell

Jotley / app · jotley.ai / iOS / Views / SettingsView.swift

Raw 16.5 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1import SwiftUI
2import FoundationModels
3import UIKit
4
5struct SettingsView: View {
6 @Environment(\.dismiss) private var dismiss
7 @Environment(\.colorScheme) private var colorScheme
8 @ObservedObject private var themeManager = ThemeManager.shared
9 @AppStorage("transcriptionLanguage") private var transcriptionLanguage = "en-US"
10 @AppStorage(CustomSpeechWords.defaultsKey) private var customWords = ""
11 @State private var modelStatus = "Checking installed Apple models…"
12 @State private var speechNeedsSetup = false
13 @State private var isSettingUpSpeech = false
14 @State private var speechSetupProgress = 0.0
15 @State private var speechSetupError: String?
16 @State private var speechSetupTask: Task<Void, Never>?
17 @State private var speechLanguages: [LocalSpeech.Language] = []
18 @State private var speechDetails = ""
19 @State private var speechIsReady = false
20 var onShowWelcome: () -> Void = {}
21 @EnvironmentObject private var persistenceController: SharedPersistenceController
22 @AppStorage(NoteSyncMode.preferenceKey) private var iCloudSyncEnabled = true
23 private let macDownloadURL = URL(string: "https://jotley.ai/download")!
24 private var versionLine: String {
25 let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "—"
26 let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—"
27 return "Version \(version) (\(build))"
28 }
29 var body: some View {
30 Form {
31 Section {
32 Menu {
33 Picker("Appearance Mode", selection: $themeManager.currentAppearanceMode) {
34 Text("Light").tag(AppearanceMode.light)
35 Text("Dark").tag(AppearanceMode.dark)
36 Text("System").tag(AppearanceMode.system)
37 }
38 } label: {
39 selectionLabel("Appearance Mode", value: String(localized: String.LocalizationValue(themeManager.currentAppearanceMode.rawValue)))
40 }
41 .accessibilityIdentifier("settingsAppearanceModePicker")
42 .onChange(of: themeManager.currentAppearanceMode) { _, newValue in
43 themeManager.setAppearanceMode(newValue)
44 }
45
46 Menu {
47 Picker("Theme Color", selection: $themeManager.currentThemeColor) {
48 ForEach(ThemeColor.allCases, id: \.self) { color in
49 Label {
50 Text(color.displayName)
51 } icon: {
52 themeSwatchImage(color)
53 }
54 .tag(color)
55 }
56 }
57 } label: {
58 selectionLabel("Theme Color", value: themeManager.currentThemeColor.displayName,
59 swatch: themeManager.currentThemeColor.color(in: swatchScheme))
60 }
61 .accessibilityIdentifier("settingsThemeColorPicker")
62 .onChange(of: themeManager.currentThemeColor) { _, newValue in
63 themeManager.setThemeColor(newValue)
64 }
65
66 } header: {
67 Text("Appearance")
68 }
69
70 Section {
71 SummaryDisplayStylePicker()
72 NavigationLink { SummaryTemplatesView() } label: {
73 Label("Summary Templates", systemImage: "doc.text")
74 }.accessibilityIdentifier("settingsTemplatesLink")
75 } header: {
76 Text("Summaries")
77 } footer: {
78 Text("Cards adds visual sections. Standard Text uses clean headings and bullets. Your choice applies to every note and can also be changed from a note’s More menu.")
79 }
80
81 Section {
82 JotleyNoteOrganizationSettings()
83 } header: {
84 Text("Note Organization")
85 } footer: {
86 Text("Auto Tags adds up to three topics when you generate a summary. Auto File Notes organizes completed recordings and unfiled summaries into a matching project or broad folder.")
87 }
88
89 Section {
90 HStack(alignment: .top, spacing: 14) {
91 Image(systemName: "desktopcomputer")
92 .font(.system(size: 28))
93 .foregroundStyle(Color.themePrimaryAccent)
94 .padding(12)
95 .background(Color.primary.opacity(0.08), in: RoundedRectangle(cornerRadius: 12))
96 .accessibilityHidden(true)
97 VStack(alignment: .leading, spacing: 6) {
98 Text("Your notes, connected on Mac.").font(.headline)
99 Text("Jotley for Mac now supports MCP. Connect Claude or Codex on your Mac to find, create and edit notes, manage folders and tags, and work with summary templates. You control whether agents can read or change your notes.")
100 .font(.subheadline).foregroundStyle(.secondary)
101 }
102 }
103 .padding(.vertical, 6)
104 .accessibilityElement(children: .combine)
105
106 Link(destination: macDownloadURL) {
107 MobileActionLabel("Mac Download & Installation Guide", systemImage: "arrow.down.circle")
108 }
109 .accessibilityIdentifier("settingsMacDownloadLink")
110 ShareLink(item: macDownloadURL) {
111 MobileActionLabel("Send Download Link to Your Mac", systemImage: "square.and.arrow.up")
112 }
113 .accessibilityIdentifier("settingsShareMacDownloadLink")
114 } header: {
115 Text("Jotley for Mac")
116 } footer: {
117 Text("MCP connections run in Jotley for Mac. Connected agents may send retrieved content to their AI provider. On your Mac, visit jotley.ai/download and drag Jotley into Applications. Requires Apple silicon, macOS 27 or later and Apple Intelligence enabled. Notes sync through iCloud when enabled on both devices. New sessions save transcripts without audio files.")
118 }
119
120 // Transcription Settings
121 Section {
122 Menu {
123 Picker("Transcription Language", selection: Binding(
124 get: { speechLanguages.contains(where: { $0.id == transcriptionLanguage }) ? transcriptionLanguage : "" },
125 set: { transcriptionLanguage = $0 }
126 )) {
127 if !speechLanguages.contains(where: { $0.id == transcriptionLanguage }) {
128 Text("Choose a supported language").tag("").disabled(true)
129 }
130 ForEach(speechLanguages) { language in Text(language.name).tag(language.id) }
131 }
132 } label: {
133 selectionLabel("Transcription Language", value: speechLanguages.first(where: { $0.id == transcriptionLanguage })?.name ?? "Choose a supported language")
134 }
135 .accessibilityIdentifier("settingsLanguagePicker")
136 .accessibilityLabel("Transcription Language")
137 .accessibilityValue(speechLanguages.first(where: { $0.id == transcriptionLanguage })?.name ?? "Choose a supported language")
138 .disabled(isSettingUpSpeech)
139 CustomSpeechWordsButton().disabled(isSettingUpSpeech)
140 } header: {
141 Text("Transcription")
142 } footer: {
143 Text("Choose an Apple Intelligence language supported by this device for transcription, summaries and Ask AI. This is the same preference used during welcome setup. Changing it does not translate existing notes or change the app’s interface language.")
144 }
145
146 Section("Built-in Models") {
147 Text(modelStatus).font(.footnote).accessibilityIdentifier("settingsModelStatus")
148 if isSettingUpSpeech {
149 ProgressView("Setting up Apple speech…", value: speechSetupProgress)
150 .accessibilityIdentifier("settingsSpeechSetupProgress")
151 Button("Cancel Setup") { speechSetupTask?.cancel() }
152 .jotleyDismissButtonStyle()
153 } else if speechNeedsSetup {
154 Button("Set Up On-Device Speech") { setUpSpeech() }
155 .accessibilityIdentifier("settingsSpeechSetupButton")
156 }
157 if let speechSetupError { Text(speechSetupError).font(.footnote).accessibilityIdentifier("settingsSpeechSetupError") }
158 if !speechIsReady && !isSettingUpSpeech {
159 Button("Refresh Speech Availability") { Task { await checkModels() } }
160 .accessibilityIdentifier("settingsSpeechRefreshButton")
161 }
162 DisclosureGroup("Speech Details") {
163 Text(speechDetails).font(.caption).textSelection(.enabled)
164 ShareLink(item: speechDetails) { Label("Share Speech Details", systemImage: "square.and.arrow.up") }
165 }
166 Text("Speech setup installs the selected language's model from Apple once and requires internet access. After setup, live transcription and summaries run on-device and work offline. New iPhone and iPad sessions do not save audio files. Audio and notes are never sent to an AI service.").font(.caption).foregroundColor(.secondary)
167 }
168 Section("iCloud Sync") {
169 if NoteSyncMode.configuredIdentifier(in: Bundle.main.infoDictionary ?? [:]) != nil {
170 Toggle("Sync notes with iCloud after restarting Jotley", isOn: $iCloudSyncEnabled)
171 .tint(Color.themePrimaryAccent)
172 .accessibilityIdentifier("settingsICloudSyncToggle")
173 }
174 Text("Sync is on by default in iCloud-enabled builds. You can turn it off here. It sends notes, transcripts, summaries, folders and tags to your private iCloud database. Audio and AI processing stay on this device. Changes take effect after closing and reopening Jotley; disabling does not delete data already in iCloud.")
175 .font(.caption).foregroundColor(.secondary)
176 Text(NoteSyncMode.configuredIdentifier(in: Bundle.main.infoDictionary ?? [:]) == nil
177 ? "iCloud sync requires a signed build configured with an iCloud container. This build saves notes only on this iPhone."
178 : (persistenceController.syncMode.isEnabled ? "iCloud sync is enabled for this session. Apple schedules synchronization when available." : "iCloud sync is off for this session."))
179 .font(.caption).foregroundColor(.secondary)
180 }
181 Section("Backup & Restore") { LibraryBackupControls() }
182 Section("Notifications") { JotleySummaryNotificationSettings() }
183 Section("About") {
184 JotleyAboutLogo()
185 Button { onShowWelcome() } label: {
186 MobileActionLabel("Welcome to Jotley", systemImage: "sparkles")
187 }.accessibilityIdentifier("settingsWelcomeJotley")
188 Text("Free note-taking · On-device AI")
189 Text("Every feature is free. No subscription.").font(.caption).foregroundStyle(.secondary)
190 Text(versionLine).lineLimit(1).accessibilityIdentifier("settingsAppVersion")
191 Text("Requires iOS or iPadOS 27 and Apple Intelligence-capable hardware: iPhone 15 Pro/Pro Max, iPhone 16 or newer, iPhone Air, iPad with M1 or later, or iPad mini with A17 Pro.").font(.caption)
192 }
193 }
194 .accessibilityIdentifier("settingsForm")
195 .scrollContentBackground(.hidden).background(Color.themeBackground)
196 .navigationTitle("Settings").navigationBarTitleDisplayMode(.inline)
197 .toolbar(.visible, for: .navigationBar)
198 .toggleStyle(.switch)
199 .tint(Color.themeActionText)
200 .toolbar { ToolbarItem(placement: .topBarTrailing) {
201 Button("Done") { dismiss() }
202 .jotleyDismissButtonStyle(inToolbar: true)
203 .accessibilityIdentifier("settingsDoneButton")
204 }.sharedBackgroundVisibility(.hidden) }
205 .task(id: [transcriptionLanguage, customWords]) { await checkModels() }
206 .onDisappear { speechSetupTask?.cancel() }
207 .preferredColorScheme(themeManager.effectiveColorScheme).observeThemeChanges()
208 }
209 /// Native menu selection stays intact; explicit label colors avoid a stale
210 /// selected-value tint when a presented Form changes appearance.
211 private var swatchScheme: ColorScheme { themeManager.effectiveColorScheme ?? colorScheme }
212
213 private func themeSwatchImage(_ color: ThemeColor) -> Image {
214 let size = CGSize(width: 18, height: 18)
215 let image = UIGraphicsImageRenderer(size: size).image { context in
216 context.cgContext.setFillColor(UIColor(color.color(in: swatchScheme)).cgColor)
217 context.cgContext.fillEllipse(in: CGRect(origin: .zero, size: size))
218 }
219 return Image(uiImage: image.withRenderingMode(.alwaysOriginal)).renderingMode(.original)
220 }
221
222 private func selectionLabel(_ title: LocalizedStringKey, value: String, swatch: Color? = nil) -> some View {
223 HStack {
224 Text(title).foregroundStyle(Color.themeTextPrimary)
225 Spacer()
226 if let swatch {
227 Circle().fill(swatch).frame(width: 12, height: 12).accessibilityHidden(true)
228 }
229 Text(value).foregroundStyle(Color.themeTextSecondary)
230 Image(systemName: "chevron.up.chevron.down")
231 .font(.caption2.weight(.semibold)).foregroundStyle(Color.themeTextSecondary)
232 }
233 .accessibilityElement(children: .combine)
234 }
235
236 private func checkModels() async {
237 let locale = Locale(identifier: transcriptionLanguage)
238 let speech = await LocalSpeech.readiness(locale: locale, checkingCustomWordsSetup: true)
239 let languages = await LocalSpeech.languages()
240 guard !Task.isCancelled else { return }
241 speechLanguages = languages
242 if let matched = LocalSpeech.selectedLanguage(locale: locale, in: languages)?.id,
243 matched != transcriptionLanguage {
244 transcriptionLanguage = matched
245 return
246 }
247 speechIsReady = speech.status == .installed && speechSetupError == nil
248 speechDetails = "\(versionLine)\nDevice: \(MobileDeviceEligibility.identifier)\niOS/iPadOS: \(UIDevice.current.systemVersion)\n\(speech.details)"
249 if let speechSetupError { speechDetails += "\nLast setup error: \(speechSetupError)" }
250 if let lastFailure = UserDefaults.standard.string(forKey: LocalSpeech.lastFailureDefaultsKey) {
251 speechDetails += "\nLast speech failure: \(lastFailure)"
252 }
253 speechNeedsSetup = speech.needsSetup || speechSetupError != nil
254 var statuses = [speech.status == .installed && speechSetupError != nil
255 ? "Speech assets are installed, but transcription setup failed. Choose Set Up On-Device Speech to try again."
256 : speech.customWordsStatus ?? speech.message]
257 // Model variant metadata is absent from some iOS 27 framework builds.
258 // Readiness uses the stable availability API without requiring that symbol.
259 statuses.append(LocalSummary.readiness(locale: locale) ?? "On-device summaries ready.")
260 modelStatus = statuses.joined(separator: " ")
261 }
262 private func setUpSpeech() {
263 guard !isSettingUpSpeech else { return }
264 let locale = Locale(identifier: transcriptionLanguage)
265 isSettingUpSpeech = true; speechSetupProgress = 0; speechSetupError = nil
266 speechSetupTask = Task { @MainActor in
267 defer { isSettingUpSpeech = false; speechSetupTask = nil }
268 do {
269 try await LocalSpeech.setUp(locale: locale) { value in
270 await MainActor.run { speechSetupProgress = value }
271 }
272 } catch is CancellationError {
273 speechSetupError = "Speech setup was canceled. Your notes are unchanged."
274 } catch {
275 let underlying = error as NSError
276 speechSetupError = Task.isCancelled ? "Speech setup was canceled." : "Speech setup failed: \(underlying.localizedDescription) (\(underlying.domain), \(underlying.code)). Connect to the internet and try again."
277 }
278 // Recheck in a fresh task even after cancellation so the retry stays available.
279 await Task { @MainActor in await checkModels() }.value
280 }
281 }
282}