Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / Settings.swift

1import Observation
2import SwiftUI
3import UniformTypeIdentifiers
4
5struct SettingsPage: View {
6 var onReplay: () -> Void = {}
7
8 @AppStorage(ReadingTheme.preference) private var appearance: ReadingTheme = .paper
9 @Environment(\.readingTheme) private var theme
10 @Environment(JournalStore.self) private var store
11 @State private var name = ""
12 @State private var exporting = false
13 @State private var importing = false
14 @State private var showRestore = false
15 @State private var backup: JournalBackup?
16 @State private var incoming: Journal?
17 @State private var message: String?
18 @State private var messageIsError = false
19 #if os(macOS)
20 @State private var agentTutorial = false
21 #endif
22
23 var body: some View {
24 Page(title: "Settings", width: 680) {
25 Panel(title: "Appearance") {
26 FlowLayout(spacing: 8) {
27 ForEach(ReadingTheme.allCases) { item in
28 Button { appearance = item } label: {
29 HStack(spacing: 6) {
30 Circle().fill(item.canvas).overlay { Circle().stroke(.secondary, lineWidth: 1) }.frame(width: 14, height: 14)
31 Text(item.rawValue)
32 if appearance == item { Image(systemName: "checkmark").accessibilityHidden(true) }
33 }
34 }
35 .glimmerButton()
36 .accessibilityAddTraits(appearance == item ? .isSelected : [])
37 }
38 }
39 .accessibilityIdentifier("settings.theme")
40 }
41 if store.journal.onboardingComplete {
42 Panel(title: "Onboarding") {
43 Button("Welcome to Glimmer", systemImage: "sparkles") {
44 store.showingOnboardingReplay = true
45 onReplay()
46 }
47 .glimmerButton()
48 .accessibilityIdentifier("settingsWelcomeGlimmer")
49 Text("See the onboarding again, from the beginning.")
50 .font(.callout).foregroundStyle(.secondary)
51 }
52 Panel(title: "Your plan") {
53 HStack(spacing: 8) {
54 TextField("First name", text: $name).glimmerField().onSubmit(saveName)
55 Button("Save name", action: saveName).glimmerButton(.standard).besideField()
56 }
57 LabeledContent("Plan tracker") {
58 GlassSegments(label: "Plan tracker", options: Tracker.allCases.map { GlassSegment(value: $0, title: $0.rawValue) },
59 selection: Binding(get: { store.journal.tracker }, set: { value in store.change { $0.tracker = value } }))
60 .frame(maxWidth: 260)
61 }
62 }
63 }
64
65 #if os(iOS)
66 if store.journal.onboardingComplete {
67 Panel(title: "Coach", accent: GlimmerColor.ember) {
68 SettingsValueRow(label: "Replies with", value: CoachDeviceRoute.title).font(.callout)
69 Text(CoachDeviceRoute.summary + " To use Claude Code, Codex or Gemini CLI, choose one in Glimmer on your Mac.")
70 .font(.callout).foregroundStyle(.secondary)
71 .fixedSize(horizontal: false, vertical: true)
72 }
73 }
74 #endif
75 CloudSyncPanel()
76 DiagnosticsPanel()
77 if store.journal.onboardingComplete { CoachDiagnosticsPanel() }
78 backupPanel
79
80 #if os(macOS)
81 if store.journal.onboardingComplete {
82 Panel(title: "Coach", accent: GlimmerColor.ember) {
83 CoachAgentSettings()
84 }
85 Panel(title: "Agent access") {
86 Button("Walk me through agent setup") { agentTutorial = true }
87 AgentSetupContent(section: .access)
88 if store.agentLevel != .off {
89 Divider()
90 AgentSetupContent(section: .connect)
91 }
92 Divider()
93 AgentSkillSection()
94 if store.agentLevel != .off {
95 Divider()
96 AgentSetupContent(section: .verify)
97 }
98 }
99 }
100 #endif
101
102 AboutPanel()
103 }
104 .onAppear { name = store.journal.name }
105 .onChange(of: store.journal.name) { old, new in
106 if name == old { name = new }
107 }
108 #if os(macOS)
109 .onAppear { store.refreshAgentState() }
110 .sheet(isPresented: $agentTutorial) { AgentTutorial() }
111 #endif
112 .fileExporter(isPresented: $exporting, document: backup, contentType: .json, defaultFilename: "Glimmer Journal") { result in
113 switch result {
114 case .success: report("Journal backup exported.")
115 case .failure: report("The backup could not be exported.", error: true)
116 }
117 }
118 .fileImporter(isPresented: $importing, allowedContentTypes: [.json]) { result in
119 do {
120 incoming = try store.readBackup(result.get())
121 showRestore = true
122 } catch { report("This file could not be opened as a Glimmer journal backup.", error: true) }
123 }
124 .alert("Replace this device’s journal?", isPresented: $showRestore) {
125 Button("Cancel", role: .cancel) { incoming = nil }
126 Button("Restore backup", role: .destructive) { restore() }
127 } message: {
128 if let incoming {
129 let effects = store.cloudEnabled
130 ? "The replacement will sync to your other devices."
131 : "It will replace your current journal on this device."
132 Text("This backup has \(incoming.moments.count) logged moments and \(incoming.tasks.count) tasks. \(effects) Export the current journal first if you want to keep it.")
133 }
134 }
135 }
136
137 private var backupPanel: some View {
138 Panel(title: "Privacy & backups", accent: GlimmerColor.sage) {
139 Label("Glimmer has no account or analytics. You choose where to save each backup.",
140 systemImage: "lock.shield")
141 .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
142 VStack(spacing: 8) {
143 ActionRow(title: "Export journal backup", detail: "Save a JSON file you can restore later",
144 icon: "square.and.arrow.up", tint: GlimmerColor.sage, trailing: "chevron.right") {
145 do {
146 backup = JournalBackup(data: try store.export())
147 exporting = true
148 } catch { report("Glimmer couldn’t create a backup.", error: true) }
149 }
150 .disabled(store.loadError != nil)
151 ActionRow(title: "Restore journal backup", detail: "Preview it before anything is replaced",
152 icon: "arrow.counterclockwise", tint: GlimmerColor.sage, trailing: "chevron.right") { importing = true }
153 }
154 .glassGroup(spacing: 8)
155 if let message {
156 Label(message, systemImage: messageIsError ? "exclamationmark.triangle" : "checkmark.circle")
157 .font(.callout.weight(.medium))
158 .foregroundStyle(messageIsError ? GlimmerColor.ember : GlimmerColor.sage)
159 }
160 }
161 }
162
163
164 private func report(_ text: String, error: Bool = false) {
165 message = text
166 messageIsError = error
167 }
168
169 private func saveName() {
170 if store.change({ $0.name = name.trimmingCharacters(in: .whitespacesAndNewlines) }) {
171 report("Name saved.")
172 }
173 }
174
175 private func restore() {
176 guard var restored = incoming else { return }
177 restored.engagement = store.journal.engagement
178 if store.change({ $0 = restored }) {
179 name = restored.name
180 report("Journal restored.")
181 } else { report("Glimmer couldn’t restore this journal.", error: true) }
182 incoming = nil
183 }
184}
185
186struct CloudSyncPanel: View {
187 @Environment(JournalStore.self) private var store
188
189 var body: some View {
190 Panel(title: "iCloud Sync", accent: GlimmerColor.sage) {
191 Toggle("Sync with iCloud", isOn: Binding(get: { store.cloudEnabled }, set: store.setCloudEnabled))
192 .toggleStyle(.switch)
193 .disabled(!store.canUseCloud)
194 Text("Keep your journal and progress in sync on devices that use the same Apple Account.")
195 .font(.callout).foregroundStyle(.secondary)
196 .fixedSize(horizontal: false, vertical: true)
197 VStack(spacing: 6) {
198 SettingsValueRow(label: "Apple Account", value: store.accountStatus)
199 .accessibilityIdentifier("settings.libraryStatus")
200 SettingsValueRow(label: "Last check", value: SyncTimestamp.text(store.lastCheck))
201 SettingsValueRow(label: "Last iCloud response", value: SyncTimestamp.text(store.lastCloudContact))
202 }
203 .font(.callout)
204 if store.cloudEnabled || store.cloudStatus != "Journal stays on this device." {
205 Text(store.cloudStatus)
206 .font(.callout).foregroundStyle(.secondary)
207 .accessibilityIdentifier("glimmerCloudStatus")
208 }
209 Button { Task { await store.syncNow() } } label: {
210 RowLabel(title: store.cloudSyncing ? "Checking iCloud…" : "Check Now", icon: "arrow.clockwise", trailing: nil)
211 }
212 .glassRow()
213 .disabled(!store.cloudEnabled || store.cloudSyncing)
214 }
215 }
216}
217
218struct DiagnosticsPanel: View {
219 @Environment(JournalStore.self) private var store
220 private var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0" }
221 private var appBuild: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—" }
222
223 var body: some View {
224 Panel(title: "Diagnostics") {
225 if let code = store.syncErrorCode {
226 SettingsValueRow(label: "Error code", value: code).font(.callout)
227 }
228 ShareLink(item: syncDiagnostics) {
229 RowLabel(title: "Share Sync Diagnostics", icon: "square.and.arrow.up", trailing: nil)
230 }
231 .glassRow()
232 .accessibilityIdentifier("settings.shareSyncDiagnostics")
233 Text("Includes sync status and timestamps. Your journal entries, tasks, and account details are not included.")
234 .font(.callout).foregroundStyle(.secondary)
235 .fixedSize(horizontal: false, vertical: true)
236 }
237 }
238
239 private var syncDiagnostics: String {
240 var lines = [
241 "Glimmer \(appVersion) (\(appBuild))",
242 "Apple Account: \(store.accountStatus)",
243 "Last check: \(SyncTimestamp.text(store.lastCheck))",
244 "Last iCloud response: \(SyncTimestamp.text(store.lastCloudContact))"
245 ]
246 if let code = store.syncErrorCode { lines.append("Error code: \(code)") }
247 return lines.joined(separator: "\n")
248 }
249}
250
251enum SyncTimestamp {
252 static func text(_ date: Date?) -> String {
253 date?.formatted(date: .abbreviated, time: .standard) ?? "—"
254 }
255}
256
257/// A label and value on one line, like LabeledContent in a Form.
258struct SettingsValueRow: View {
259 let label: String
260 let value: String
261
262 var body: some View {
263 ViewThatFits(in: .horizontal) {
264 HStack(alignment: .firstTextBaseline, spacing: 12) {
265 Text(label)
266 Spacer(minLength: 8)
267 Text(value).foregroundStyle(.secondary).lineLimit(1).textSelection(.enabled)
268 }
269 VStack(alignment: .leading, spacing: 2) {
270 Text(label)
271 Text(value).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
272 }
273 .frame(maxWidth: .infinity, alignment: .leading)
274 }
275 .accessibilityElement(children: .combine)
276 }
277}
278
279struct AboutPanel: View {
280 @Environment(JournalStore.self) private var store
281 @Environment(\.openURL) private var openURL
282 @State private var showSupportCard = false
283 private var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0" }
284 private var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "1" }
285
286 var body: some View {
287 VStack(spacing: 18) {
288 Panel(title: "About", padding: 20) {
289 HStack(spacing: 14) {
290 GlimmerLogo(size: 58)
291 VStack(alignment: .leading, spacing: 2) {
292 Text("Glimmer").font(GlimmerFont.display(.title, weight: .bold))
293 Text("Version \(version) (\(build)) · Project ATOM")
294 .font(.subheadline).foregroundStyle(.secondary)
295 }
296 }
297 Text("Glimmer is a gentle spiritual life coach for deep thinkers, neurodivergent minds, and anyone too busy thinking to stay organized. Reflect on what matters, then try one small step in your day.")
298 .fixedSize(horizontal: false, vertical: true)
299 Text("Log short moments on your own device, try one concrete change at a time, and review your week to see what genuinely helped. Glimmer respects rest and keeps every decision in your hands.")
300 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
301 VStack(spacing: 8) {
302 Link(destination: StoreLinks.website) {
303 RowLabel(title: "Glimmer website", detail: "glimmertoday.ai", icon: "globe", trailing: "arrow.up.right")
304 }.glassRow()
305 }
306 .glassGroup(spacing: 8)
307 }
308 Panel(title: "Ratings & support", accent: GlimmerColor.honey) {
309 Text("Your App Store rating helps more people discover Glimmer. Every feature is free.")
310 .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
311 VStack(spacing: 8) {
312 ActionRow(title: "Rate on the App Store",
313 detail: StoreLinks.review == nil ? "Available once Glimmer is on the App Store" : "On the App Store",
314 icon: "star.fill", tint: GlimmerColor.honey) {
315 if let url = StoreLinks.review {
316 openURL(url) { accepted in
317 if accepted { store.change { $0.engagement.actions.insert("review") } }
318 }
319 }
320 }
321 .disabled(StoreLinks.review == nil)
322 .accessibilityIdentifier("reviewGlimmer")
323 SupportTicketRow()
324 ShareLink(item: StoreLinks.website) {
325 RowLabel(title: "Share Glimmer", icon: "square.and.arrow.up.fill", tint: GlimmerColor.accent, trailing: nil)
326 }.glassRow()
327 Link(destination: StoreLinks.feedback) {
328 RowLabel(title: "Send Feedback", icon: "bubble.left.and.bubble.right.fill", tint: GlimmerColor.sage,
329 trailing: "arrow.up.right")
330 }.glassRow()
331 Link(destination: StoreLinks.protomotaApps) {
332 RowLabel(title: "More Free Apps from Project ATOM", icon: "square.grid.2x2.fill", tint: GlimmerColor.honey,
333 trailing: "arrow.up.right")
334 }.glassRow()
335 #if os(macOS)
336 ActionRow(title: "Share or send feedback", detail: "See which ones you’ve opened",
337 icon: "checklist", tint: GlimmerColor.dusk) { showSupportCard = true }
338 .accessibilityIdentifier("glimmerSupportCard")
339 #endif
340 }
341 .glassGroup(spacing: 8)
342 }
343 }
344 #if os(macOS)
345 .sheet(isPresented: $showSupportCard) { GlimmerSupportSheet(isReminder: false) }
346 #endif
347 }
348}
349
350struct JournalBackup: FileDocument {
351 static var readableContentTypes: [UTType] { [.json] }
352 let data: Data
353
354 init(data: Data) { self.data = data }
355 init(configuration: ReadConfiguration) throws {
356 guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) }
357 self.data = data
358 }
359 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }
360}
361
362/// Free personal technical support, the same on every device.
363struct SupportTicketRow: View {
364 @Environment(\.openURL) private var openURL
365
366 var body: some View {
367 ActionRow(title: "Technical Support", detail: "Free help from a real person for Mac, iPhone, and iPad",
368 icon: "headphones", tint: GlimmerColor.dusk, trailing: "arrow.up.right") {
369 #if os(macOS)
370 GlimmerSupportReminder.record(.support)
371 #endif
372 openURL(StoreLinks.support)
373 }
374 .accessibilityIdentifier("glimmerSupportTickets")
375 }
376}