Branchwell

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

1import StoreKit
2import SwiftUI
3
4@main
5struct GlimmerEntry {
6 @MainActor static func main() {
7 #if os(macOS)
8 if CommandLine.arguments.dropFirst() == ["--mcp"] {
9 AgentAccess.run()
10 return
11 }
12 // Settings → Coach → Test Coach from Terminal: --test-coach claude|codex|gemini [model] [effort]
13 if CommandLine.arguments.dropFirst().first == "--test-coach" {
14 CoachAgentRoute.runTestCommand(Array(CommandLine.arguments.dropFirst(2)))
15 return
16 }
17 #endif
18 GlimmerApp.main()
19 }
20}
21
22struct GlimmerApp: App {
23 @State private var store = JournalStore()
24 #if os(macOS)
25 @Environment(\.openWindow) private var openWindow
26 @StateObject private var updates = AppUpdates()
27 #endif
28
29 var body: some Scene {
30 #if os(macOS)
31 mainWindow
32 .defaultSize(width: 1000, height: 760)
33 .commands {
34 CommandGroup(replacing: .appInfo) {
35 Button("About Glimmer") { openWindow(id: "about-glimmer") }
36 if updates.isAvailable { CheckForUpdatesButton(updates: updates) }
37 }
38 }
39
40 Settings {
41 SettingsPage(onReplay: { NSApp.keyWindow?.close() }).environment(store).modifier(ReadingAppearance())
42 .frame(minWidth: 510, minHeight: 570)
43 }
44 Window("About Glimmer", id: "about-glimmer") {
45 Page(title: "About Glimmer", width: 520) { AboutPanel() }
46 .environment(store)
47 .modifier(ReadingAppearance()).frame(minWidth: 430, minHeight: 450)
48 }.defaultSize(width: 490, height: 570)
49 #else
50 mainWindow
51 #endif
52 }
53
54 private var mainWindow: some Scene {
55 WindowGroup {
56 RootView().environment(store).modifier(ReadingAppearance())
57 .disclosureGroupStyle(GlimmerDisclosureStyle())
58 #if DEBUG
59 .task {
60 let env = ProcessInfo.processInfo.environment
61 if env["GLIMMER_TEST_JOURNAL"] != nil, env["GLIMMER_TEST_START_PLAN"] == "1" {
62 store.start(name: "")
63 }
64 }
65 #endif
66 #if DEBUG && os(macOS)
67 .task {
68 // Design review captures need a key window so glass renders in its active state.
69 guard ProcessInfo.processInfo.environment["GLIMMER_TEST_JOURNAL"] != nil else { return }
70 for _ in 0..<4 {
71 NSApplication.shared.activate(ignoringOtherApps: true)
72 try? await Task.sleep(for: .seconds(0.6))
73 }
74 }
75 #endif
76 }
77 }
78}
79
80enum Destination: String, Hashable, CaseIterable, Identifiable {
81 case today = "Today", insights = "Insights", weekly = "Weekly", coach = "Coach"
82 case plan = "Plan", toolkit = "Toolkit", habits = "Habits", challenges = "Challenges", lessons = "Lessons"
83 case cleaning = "Cleaning", seasonal = "Seasonal", settings = "Settings"
84
85 var id: Self { self }
86 var title: String { self == .cleaning ? "Cleaning & maintenance" : rawValue }
87 var icon: String {
88 switch self {
89 case .today: "sun.horizon.fill"
90 case .insights: "chart.bar.fill"
91 case .weekly: "calendar"
92 case .coach: "text.bubble.fill"
93 case .plan: "list.bullet.clipboard.fill"
94 case .toolkit: "wrench.and.screwdriver.fill"
95 case .habits: "leaf.fill"
96 case .challenges: "trophy.fill"
97 case .lessons: "book.fill"
98 case .cleaning: "bubbles.and.sparkles.fill"
99 case .seasonal: "tree.fill"
100 case .settings: "gearshape.fill"
101 }
102 }
103
104 var tint: Color {
105 switch self {
106 case .today, .plan, .cleaning: GlimmerColor.accent
107 case .insights, .habits: GlimmerColor.sage
108 case .weekly, .challenges: GlimmerColor.honey
109 case .coach, .seasonal: GlimmerColor.ember
110 case .toolkit, .lessons, .settings: GlimmerColor.dusk
111 }
112 }
113
114 var detail: String {
115 switch self {
116 case .plan: "Checklist and recurring tasks"
117 case .toolkit: "Break things down, size them, focus"
118 case .habits: "Daily habits and mood"
119 case .challenges: "Short guided challenges"
120 case .lessons: "Your 90-day reading plan"
121 case .cleaning: "Tidy up and keep things working"
122 case .seasonal: "Timely tips and checklists"
123 case .settings: "Backups, privacy and support"
124 default: ""
125 }
126 }
127}
128
129enum QuickFlow: String, Identifiable {
130 case log, energy
131 #if os(macOS)
132 case agentTutorial
133 #endif
134 var id: Self { self }
135}
136
137struct RootView: View {
138 @Environment(\.readingTheme) private var theme
139 @Environment(JournalStore.self) private var store
140 @Environment(\.scenePhase) private var phase
141 @Environment(\.requestReview) private var requestReview
142 #if os(iOS)
143 @Environment(\.horizontalSizeClass) private var sizeClass
144 #endif
145 @State private var destination: Destination? = .today
146 @FocusState private var focusedSidebarItem: Destination?
147 @State private var mobileTab: Destination = .today
148 @State private var mobilePath: [Destination] = []
149 @State private var flow: QuickFlow?
150 @State private var visibleCoins: EarnedCoins?
151 @State private var coinBurst: (award: EarnedCoins, startedAt: Date)?
152 @State private var presentedAwardID: UUID?
153 #if os(macOS)
154 @State private var showsSupportReminder = false
155 #endif
156 @Environment(\.accessibilityReduceMotion) private var reduceMotion
157
158 private var compact: Bool {
159 #if os(macOS)
160 false
161 #else
162 sizeClass == .compact
163 #endif
164 }
165
166 var body: some View {
167 Group {
168 if let loadError = store.loadError {
169 ContentUnavailableView {
170 Label("Journal unavailable", systemImage: "lock.doc")
171 } description: {
172 Text(loadError)
173 } actions: {
174 Button("Try again") { store.reload() }.glimmerButton(.prominent)
175 }
176 .background { PageBackdrop() }
177 } else if let catalog = store.catalog {
178 if store.showingOnboardingReplay {
179 OnboardingView(catalog: catalog, onFinishReplay: { store.showingOnboardingReplay = false })
180 .id("onboarding-replay")
181 } else if store.journal.onboardingComplete {
182 if compact {
183 tabs(catalog)
184 } else {
185 split(catalog)
186 }
187 } else {
188 OnboardingView(catalog: catalog)
189 }
190 } else {
191 ContentUnavailableView("Glimmer’s library is missing", systemImage: "book.closed")
192 .background { PageBackdrop() }
193 }
194 }
195 .tint(GlimmerColor.accent)
196 .sheet(item: $flow) { flow in
197 if let catalog = store.catalog {
198 switch flow {
199 case .log: MomentFlow(catalog: catalog).tallSheet()
200 case .energy: EnergyFlow(catalog: catalog).tallSheet()
201 #if os(macOS)
202 case .agentTutorial: AgentTutorial()
203 #endif
204 }
205 }
206 }
207 .overlay {
208 if let coinBurst, !reduceMotion {
209 CoinBurst(startedAt: coinBurst.startedAt, amount: coinBurst.award.amount)
210 .id(coinBurst.award.id)
211 .task(id: coinBurst.award.id) {
212 try? await Task.sleep(for: .seconds(CoinBurst.duration))
213 if !Task.isCancelled, self.coinBurst?.award.id == coinBurst.award.id {
214 self.coinBurst = nil
215 }
216 }
217 }
218 }
219 .overlay(alignment: .bottom) {
220 if let award = visibleCoins {
221 EarnedCoinsToast(award: award)
222 .padding(.bottom, compact ? 118 : 24)
223 .padding(.horizontal, 16)
224 .id(award.id)
225 .transition(.opacity)
226 } else if store.earnedCoins?.id == presentedAwardID, let notice = store.notice {
227 NoticeToast(text: notice)
228 .padding(.bottom, compact ? 118 : 24).padding(.horizontal, 16)
229 .id(notice)
230 .transition(reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 6)))
231 .task(id: notice) {
232 try? await Task.sleep(for: .seconds(2.6))
233 if !Task.isCancelled, store.notice == notice { store.notice = nil }
234 }
235 }
236 }
237 .animation(.smooth, value: store.notice)
238 .sensoryFeedback(.impact(weight: .light), trigger: visibleCoins?.id) { _, next in next != nil }
239 .task(id: store.earnedCoins) {
240 guard let award = store.earnedCoins, award.id != presentedAwardID else { return }
241 // A save can dismiss a sheet or reader. Give that transition room to finish.
242 try? await Task.sleep(for: .milliseconds(420))
243 guard !Task.isCancelled else { return }
244 presentedAwardID = award.id
245 await showCoins(award)
246 }
247 .onChange(of: phase, initial: true) { _, state in
248 if state == .active {
249 store.day = .now
250 refreshPersonalReminders()
251 }
252 }
253 .onChange(of: store.journal.personalTodos) { _, _ in refreshPersonalReminders() }
254 .task(id: phase) {
255 guard phase == .active else { return }
256 while !Task.isCancelled {
257 if let editor = store.editorialLibrary {
258 await editor.refreshIfNeeded()
259 }
260 if store.editorialLibrary?.edition == nil {
261 await GalleryLibrary.shared.refreshIfNeeded()
262 }
263 do { try await Task.sleep(for: .seconds(EditorialLibrary.refreshInterval)) } catch { return }
264 }
265 }
266 .task(id: phase == .active && store.cloudEnabled) {
267 if phase == .active { await store.syncWhileActive() }
268 }
269 .onReceive(NotificationCenter.default.publisher(for: .NSUbiquityIdentityDidChange)) { _ in store.cloudAccountChanged() }
270 .onReceive(NotificationCenter.default.publisher(for: .NSCalendarDayChanged)) { _ in store.day = .now }
271 #if DEBUG
272 .task { openReviewScreen() }
273 #endif
274 .task(id: canRequestReview) {
275 guard canRequestReview else { return }
276 try? await Task.sleep(for: .seconds(2))
277 #if !DEBUG
278 // The native sheet rates an App Store install. TestFlight and the direct Mac download
279 // shouldn't use up the one prompt before someone has the App Store build.
280 guard case .verified(let transaction) = try? await AppTransaction.shared,
281 transaction.environment == .production else { return }
282 #endif
283 guard !Task.isCancelled, canRequestReview else { return }
284 if store.change({ $0.engagement.requestedReview = true }) { requestReview() }
285 }
286 #if os(macOS)
287 .task(id: canShowSupportReminder) {
288 guard canShowSupportReminder else { return }
289 // Let the App Store prompt and any open sheet go first.
290 do { try await Task.sleep(for: .seconds(8)) } catch { return }
291 guard canShowSupportReminder, NSApp.isActive, let window = NSApp.keyWindow, !window.isSheet,
292 window.attachedSheet == nil,
293 GlimmerSupportReminder.claim(activity: store.journal.engagement.count) else { return }
294 showsSupportReminder = true
295 }
296 .sheet(isPresented: $showsSupportReminder) { GlimmerSupportSheet(isReminder: true) }
297 #endif
298 }
299
300 #if os(macOS)
301 private var canShowSupportReminder: Bool {
302 phase == .active && flow == nil && store.notice == nil && store.journal.onboardingComplete
303 && store.journal.engagement.count >= GlimmerSupportReminder.milestone
304 }
305 #endif
306
307 private var canRequestReview: Bool {
308 phase == .active && flow == nil && store.notice == nil
309 && (compact ? mobileTab == .today && mobilePath.isEmpty : destination == .today)
310 && store.journal.engagement.shouldRequestReview && StoreLinks.review != nil
311 }
312
313 private func open(_ page: Destination) {
314 if compact {
315 mobileTab = .today
316 mobilePath.append(page)
317 } else {
318 destination = page
319 }
320 }
321
322 private func showCoins(_ award: EarnedCoins) async {
323 if !reduceMotion { coinBurst = (award, .now) }
324 withAnimation(.easeOut(duration: reduceMotion ? 0.10 : 0.16)) { visibleCoins = award }
325 AccessibilityNotification.Announcement("\(award.amount) coins earned").post()
326 try? await Task.sleep(for: .seconds(2.1))
327 if visibleCoins == award {
328 withAnimation(.easeInOut(duration: 0.16)) { visibleCoins = nil }
329 }
330 }
331
332 private func launch(_ quickFlow: QuickFlow) { flow = quickFlow }
333
334 private func refreshPersonalReminders() {
335 guard store.loadError == nil, store.usesDeviceReminders else { return }
336 PersonalReminders.shared.refresh(store.journal.personalTodos ?? [])
337 }
338
339 #if DEBUG
340 /// Opens a screen named in the launch environment, for design review captures with test journals.
341 private func openReviewScreen() {
342 let environment = ProcessInfo.processInfo.environment
343 guard environment["GLIMMER_TEST_JOURNAL"] != nil else { return }
344 if environment["GLIMMER_COIN_DEMO"] != nil {
345 // Shows the coin celebration twice for design review recordings.
346 Task {
347 try? await Task.sleep(for: .seconds(4.5))
348 await showCoins(EarnedCoins(amount: 10))
349 try? await Task.sleep(for: .seconds(2.9))
350 await showCoins(EarnedCoins(amount: 60))
351 for message in ["Task added to your plan.", "Nice. Let’s use that momentum.", "Glimmer couldn’t save this change. Please try again."] {
352 try? await Task.sleep(for: .seconds(4))
353 store.notice = message
354 }
355 }
356 }
357 if let name = environment["GLIMMER_SCREEN"],
358 let page = Destination.allCases.first(where: {
359 $0.rawValue.caseInsensitiveCompare(name) == .orderedSame ||
360 $0.title.caseInsensitiveCompare(name) == .orderedSame
361 }) {
362 if compact && [.insights, .weekly, .coach].contains(page) { mobileTab = page } else if page != .today { open(page) }
363 }
364 if let name = environment["GLIMMER_FLOW"] { flow = QuickFlow(rawValue: name) }
365 }
366 #endif
367
368 private func sidebarHeading(_ title: String) -> some View {
369 Text(title)
370 .font(.caption.weight(.semibold))
371 .foregroundStyle(.secondary)
372 .textCase(nil)
373 }
374
375 private func split(_ catalog: Catalog) -> some View {
376 NavigationSplitView {
377 List {
378 Section {
379 ForEach([Destination.today, .coach, .lessons, .plan, .toolkit]) { sidebarRow($0) }
380 } header: { sidebarHeading("Glimmer") }
381 Section {
382 ForEach([Destination.insights, .weekly, .habits, .challenges, .cleaning, .seasonal, .settings]) { sidebarRow($0) }
383 } header: { sidebarHeading("Your space") }
384 }
385 .listStyle(.plain)
386 .scrollContentBackground(.hidden)
387 .navigationSplitViewColumnWidth(min: 190, ideal: 220)
388 } detail: {
389 NavigationStack {
390 detail(catalog)
391 .toolbar { quickToolbar(catalog) }
392 }.id(destination)
393 }
394 .toolbar(removing: .title)
395 }
396
397 #if os(macOS)
398 private static let sidebarGlyph: CGFloat = 15
399 #else
400 private static let sidebarGlyph: CGFloat = 20
401 #endif
402
403 private func sidebarRow(_ item: Destination) -> some View {
404 let selected = (destination ?? .today) == item
405 #if os(macOS)
406 let rowHeight: CGFloat = 32
407 #else
408 let rowHeight: CGFloat = 44
409 #endif
410
411 return Button { destination = item } label: {
412 Label {
413 Text(item.title)
414 .fontWeight(selected ? .semibold : .regular)
415 .underline(focusedSidebarItem == item)
416 .foregroundStyle(.primary)
417 } icon: {
418 Image(systemName: item.icon)
419 .font(.system(size: Self.sidebarGlyph, weight: .medium))
420 .symbolRenderingMode(.monochrome)
421 .foregroundStyle(item.tint)
422 .frame(width: Self.sidebarGlyph + 9)
423 .accessibilityHidden(true)
424 }
425 .padding(.horizontal, 16)
426 .padding(.vertical, 4)
427 .frame(maxWidth: .infinity, minHeight: rowHeight, alignment: .leading)
428 .contentShape(.rect)
429 }
430 .buttonStyle(.plain)
431 .focusEffectDisabled()
432 .focused($focusedSidebarItem, equals: item)
433 .accessibilityAddTraits(selected ? .isSelected : [])
434 .listRowInsets(EdgeInsets())
435 .listRowSeparator(.hidden)
436 .listRowBackground(Color.primary.opacity(selected ? (theme == .glimmer ? 0.12 : 0.075) : 0))
437 }
438
439 @ToolbarContentBuilder
440 private func quickToolbar(_ catalog: Catalog) -> some ToolbarContent {
441 ToolbarItemGroup(placement: .primaryAction) {
442 Button { launch(.energy) } label: { Label("Check in", systemImage: "bolt.heart") }.tint(Color.primary)
443 .help("Check in your energy")
444 .keyboardShortcut("e", modifiers: [.command, .shift])
445 Menu {
446 Button("Open your plan", systemImage: "checklist") { open(.plan) }
447 Button("Try a tiny win", systemImage: "sparkles") { open(.challenges) }
448 Button("Read today’s lesson", systemImage: "book") { open(.lessons) }
449 } label: {
450 Label("Quick actions", systemImage: "ellipsis")
451 }
452 .tint(Color.primary)
453 .help("More quick actions")
454 Button { launch(.log) } label: { Label("Log a moment", systemImage: "plus") }.glimmerButton(.prominent).tint(Color.primary)
455 .help("Log a moment")
456 .keyboardShortcut("l", modifiers: [.command, .shift])
457 }
458 }
459
460 @ViewBuilder
461 private func tabs(_ catalog: Catalog) -> some View {
462 let view = TabView(selection: $mobileTab) {
463 Tab("Today", systemImage: Destination.today.icon, value: Destination.today) {
464 NavigationStack(path: $mobilePath) {
465 compactToday(catalog)
466 .navigationDestination(for: Destination.self) { page in
467 if page == .plan || page == .toolkit {
468 screen(page, catalog: catalog).hidesTabBar()
469 } else {
470 screen(page, catalog: catalog)
471 }
472 }
473 .toolbar { compactToolbar }
474 }
475 }
476 ForEach([Destination.insights, .weekly, .coach]) { tab in
477 Tab(tab.rawValue, systemImage: tab.icon, value: tab) {
478 NavigationStack { screen(tab, catalog: catalog).toolbar { compactToolbar } }
479 }
480 }
481 }
482 #if os(iOS)
483 if #available(iOS 26, *) {
484 view.tabBarMinimizeBehavior(mobileTab == .coach ? .never : .onScrollDown)
485 } else {
486 view
487 }
488 #else
489 view
490 #endif
491 }
492
493 @ViewBuilder private func compactToday(_ catalog: Catalog) -> some View {
494 #if DEBUG
495 if let name = ReviewLaunch.detail {
496 ReviewDetail(name: name, catalog: catalog)
497 } else {
498 screen(.today, catalog: catalog)
499 }
500 #else
501 screen(.today, catalog: catalog)
502 #endif
503 }
504
505 @ToolbarContentBuilder
506 private var compactToolbar: some ToolbarContent {
507 ToolbarItemGroup(placement: .primaryAction) {
508 Button { launch(.energy) } label: { Label("Check in", systemImage: "bolt.heart") }.tint(Color.primary)
509 Button { launch(.log) } label: { Label("Log a moment", systemImage: "plus") }.glimmerButton(.prominent).tint(Color.primary)
510 }
511 }
512
513 @ViewBuilder private func detail(_ catalog: Catalog) -> some View {
514 #if DEBUG
515 if let name = ReviewLaunch.detail {
516 ReviewDetail(name: name, catalog: catalog)
517 } else {
518 screen(destination ?? .today, catalog: catalog)
519 }
520 #else
521 screen(destination ?? .today, catalog: catalog)
522 #endif
523 }
524
525 @ViewBuilder private func screen(_ page: Destination, catalog: Catalog) -> some View {
526 switch page {
527 case .today: TodayView(catalog: catalog, open: open, launch: launch)
528 case .insights: InsightsView(catalog: catalog)
529 case .weekly: WeeklyView(catalog: catalog)
530 case .coach: CoachView(catalog: catalog)
531 case .plan: PlanView(catalog: catalog)
532 case .toolkit: ToolkitView()
533 case .habits: HabitsView(catalog: catalog)
534 case .challenges: ChallengesView(catalog: catalog)
535 case .lessons: LessonsView(catalog: catalog)
536 case .cleaning: CleaningView(catalog: catalog)
537 case .seasonal: SeasonalView()
538 case .settings: SettingsPage()
539 }
540 }
541}
542
543#if DEBUG
544/// Opens nested screens directly for design-review captures using an isolated test journal.
545struct ReviewDetail: View {
546 @Environment(JournalStore.self) private var store
547 let name: String
548 let catalog: Catalog
549 @State private var sheet = false
550 @State private var pushed = false
551 @State private var cover = false
552
553 var body: some View {
554 content
555 #if os(iOS)
556 .fullScreenCover(isPresented: $cover) {
557 if let todo = store.openPersonalTodos.first(where: { !store.journal.steps(for: $0.id).isEmpty }) { OneThingSheet(start: todo) }
558 }
559 #endif
560 .sheet(isPresented: $sheet) {
561 let todo = store.openPersonalTodos.first { !store.journal.steps(for: $0.id).isEmpty } ?? store.openPersonalTodos.first
562 switch name {
563 case "taskeditor": TaskEditor(task: store.journal.tasks.first ?? PlanTask())
564 case "breaksheet": if let todo = store.openPersonalTodos.last { BreakItDownSheet(todo: todo, parent: nil) }
565 case "timesheet": if let todo { TimeCheckSheet(todo: todo) }
566 case "todoeditor": if let todo { PersonalTodoEditor(task: todo, today: store.day) }
567 case "focussheet": if let todo { OneThingSheet(start: todo) }
568 #if os(macOS)
569 case "support": GlimmerSupportSheet(isReminder: true)
570 #endif
571 default: EmptyView()
572 }
573 }
574 .task {
575 #if os(iOS)
576 cover = name == "focussheet"
577 sheet = ["taskeditor", "breaksheet", "timesheet", "todoeditor"].contains(name)
578 #else
579 sheet = ["taskeditor", "support", "breaksheet", "timesheet", "todoeditor", "focussheet"].contains(name)
580 #endif
581 pushed = toolkitPages.contains(name)
582 }
583 }
584
585 // Toolkit pages open pushed from the Toolkit, the way people reach them.
586 private let toolkitPages = ["onething", "breakitdown", "timecheck", "unload", "readtheroom", "reword", "weighit"]
587
588 @ViewBuilder private var toolkitPage: some View {
589 switch name {
590 case "onething": OneThingView()
591 case "breakitdown": BreakItDownPicker()
592 case "timecheck": TimeCheckView()
593 case "unload": UnloadView()
594 case "readtheroom": ReadTheRoomView()
595 case "reword": RewordView()
596 default: WeighItView()
597 }
598 }
599
600 @ViewBuilder private var content: some View {
601 switch name {
602 case "lesson": LessonReader(lesson: catalog.lessons[0])
603 case "challenge": ChallengeView(challenge: catalog.challenges[0])
604 case "library": TaskLibraryView(catalog: catalog)
605 case "suggestions": PreloadView(catalog: catalog)
606 case "cleaninglist": CleaningSession(list: catalog.cleaning.daily)
607 case "practices": PracticeView(topics: catalog.practiceTopics, title: "Practice exercises")
608 case "screentime": ScreenTimeCheck()
609 case "about": Page(title: "About Glimmer") { AboutPanel() }
610 #if os(macOS)
611 case "coachagent": Page(title: "Coach", width: 680) {
612 Panel(title: "Coach", accent: GlimmerColor.ember) { CoachAgentSettings() }
613 CoachDiagnosticsPanel()
614 }
615 #else
616 case "coachagent": SettingsPage()
617 #endif
618 case "toolkit", "breaksheet", "timesheet", "todoeditor": ToolkitView()
619 case "focussheet": OneThingView()
620 case _ where toolkitPages.contains(name):
621 ToolkitView().navigationDestination(isPresented: $pushed) { toolkitPage.hidesTabBar() }
622 case "review": if let experiment = store.journal.experiment { ExperimentReview(experiment: experiment) }
623 default: PlanView(catalog: catalog)
624 }
625 }
626}
627
628enum ReviewLaunch {
629 static var detail: String? {
630 let environment = ProcessInfo.processInfo.environment
631 return environment["GLIMMER_TEST_JOURNAL"] == nil ? nil : environment["GLIMMER_DETAIL"]
632 }
633
634 static var colorScheme: ColorScheme? {
635 let environment = ProcessInfo.processInfo.environment
636 guard environment["GLIMMER_TEST_JOURNAL"] != nil else { return nil }
637 return switch environment["GLIMMER_APPEARANCE"] {
638 case "light": .light
639 case "dark": .dark
640 default: nil
641 }
642 }
643}
644#endif
645
646/// A short message that confirms a routine app action.
647struct NoticeToast: View {
648 let text: String
649
650 private var appearance: (symbol: String, color: Color) {
651 if text.contains("couldn’t") { return ("exclamationmark", GlimmerColor.ember) }
652 let confirmations = ["added", "copied", "complete", "started", "saved", "logged", "set", "whole day"]
653 if confirmations.contains(where: text.localizedCaseInsensitiveContains) { return ("checkmark", GlimmerColor.sage) }
654 return ("sparkles", GlimmerColor.dusk)
655 }
656
657 var body: some View {
658 HStack(spacing: 12) {
659 Image(systemName: appearance.symbol)
660 .font(.subheadline.weight(.semibold))
661 .foregroundStyle(appearance.color)
662 .frame(width: 26, height: 26)
663 .background(appearance.color.opacity(0.14), in: .circle)
664 Text(text).font(.callout.weight(.semibold)).fixedSize(horizontal: false, vertical: true)
665 }
666 .padding(.leading, 10).padding(.trailing, 20).padding(.vertical, 10)
667 .glimmerGlass(.capsule, tint: appearance.color.opacity(0.16))
668 .shadow(color: .black.opacity(0.12), radius: 12, y: 4)
669 .allowsHitTesting(false)
670 .accessibilityElement(children: .ignore)
671 .accessibilityLabel(text)
672 .accessibilityAddTraits(.updatesFrequently)
673 }
674}
675
676struct TodayView: View {
677 @Environment(JournalStore.self) private var store
678 @Environment(\.dynamicTypeSize) private var typeSize
679 @Environment(\.horizontalSizeClass) private var sizeClass
680 let catalog: Catalog
681 let open: (Destination) -> Void
682 let launch: (QuickFlow) -> Void
683
684 #if os(macOS)
685 @AppStorage("glimmer.didSeeAgentInvite") private var didSeeAgentInvite = false
686 #endif
687
688 private var greeting: String {
689 let hour = Calendar.current.component(.hour, from: .now)
690 let part = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening"
691 return store.journal.name.isEmpty ? part : "\(part), \(store.journal.name)"
692 }
693
694 private var energy: EnergyCheck? { store.journal.energy[store.todayKey] }
695 private var completed: Int { store.todaysTasks.filter { store.todayCompletion.contains($0.id) }.count }
696 private var featuredSeason: SeasonalEdition? {
697 store.seasonalEditions.first { $0.recommendation(on: store.day) != nil }
698 }
699
700 var body: some View {
701 GeometryReader { viewport in
702 if viewport.size.width >= 700 && viewport.size.height >= 745 && !typeSize.isAccessibilitySize {
703 ScrollView {
704 VStack(alignment: .leading, spacing: 18) {
705 header
706 HStack(alignment: .top, spacing: 30) {
707 VStack(alignment: .leading, spacing: 16) {
708 lesson
709 seasonalLink
710 reflection
711 assistantInvite
712 }
713 .frame(maxWidth: .infinity, alignment: .leading)
714 VStack(alignment: .leading, spacing: 16) {
715 plan
716 PersonalTodoList(openPlan: { open(.plan) })
717 }
718 .frame(width: min(325, viewport.size.width * 0.34))
719 }
720 }
721 .padding(24)
722 .frame(maxWidth: 1000, alignment: .topLeading)
723 .frame(maxWidth: .infinity)
724 }
725 .background { PageBackdrop() }
726 } else {
727 ScrollView {
728 VStack(alignment: .leading, spacing: 20) {
729 header
730 lesson
731 seasonalLink
732 plan
733 PersonalTodoList(openPlan: { open(.plan) })
734 reflection
735 assistantInvite
736 if sizeClass == .compact { space }
737 }
738 .frame(maxWidth: 650, alignment: .leading)
739 .padding(20)
740 .frame(maxWidth: .infinity)
741 }
742 .background { PageBackdrop() }
743 }
744 }
745 }
746
747 @ViewBuilder private var seasonalLink: some View {
748 if let edition = featuredSeason, let recommendation = edition.recommendation(on: store.day) {
749 SeasonalRecommendation(edition: edition, list: recommendation.list, item: recommendation.item) {
750 open(.seasonal)
751 }
752 }
753 }
754
755 private var header: some View {
756 VStack(alignment: .leading, spacing: 8) {
757 Eyebrow(store.day.formatted(.dateTime.weekday(.wide).month(.wide).day()))
758 ReaderRankBar(progress: ReaderProgress(journal: store.journal, catalog: catalog), coins: store.journal.coins)
759 Text(greeting).font(GlimmerFont.reading(.largeTitle, weight: .medium))
760 .accessibilityAddTraits(.isHeader)
761 FlowLayout(spacing: 12, centerItemsVertically: true) {
762 Button { launch(.energy) } label: { Label("How’s your energy?", systemImage: "bolt.heart") }.accessibilityIdentifier("today.energy")
763 Button { launch(.log) } label: { Label("Log a moment", systemImage: "plus") }.glimmerButton(.prominent).accessibilityIdentifier("today.log")
764 if !store.todayLogs.isEmpty { Text("\(store.todayLogs.count) logged today").font(.callout).foregroundStyle(.secondary) }
765 }
766 .glimmerButton()
767 .controlSize(.regular)
768 if let quote = store.dailyQuote {
769 VStack(alignment: .leading, spacing: 3) {
770 VStack(alignment: .leading, spacing: 3) {
771 Text("“\(quote.text)”")
772 .font(GlimmerFont.reading(.title3).italic())
773 .fixedSize(horizontal: false, vertical: true)
774 Text(quote.author).font(.callout).foregroundStyle(.secondary)
775 }
776 .accessibilityElement(children: .combine)
777 .accessibilityIdentifier("today.quote")
778 SendToInkspringButton(quote: quote)
779 }
780 .padding(.top, 4)
781 .frame(maxWidth: 580, alignment: .leading)
782 }
783 }
784 }
785
786 @ViewBuilder private var assistantInvite: some View {
787 #if os(macOS)
788 if !didSeeAgentInvite && store.agentLevel == .off {
789 HStack {
790 Button("Connect your assistant to Glimmer") { didSeeAgentInvite = true; launch(.agentTutorial) }.glimmerButton()
791 Button("Later") { didSeeAgentInvite = true }.buttonStyle(.borderless)
792 }.font(.callout)
793 }
794 #endif
795 }
796
797 @ViewBuilder private var lesson: some View {
798 if let lesson = catalog.dailyLesson(for: store.journal, on: store.day) {
799 VStack(alignment: .leading, spacing: 8) {
800 Artwork(slot: 0, featured: true, height: 145)
801 .readingArrival()
802 Eyebrow("Today’s lesson · \(lesson.minutes) min")
803 Text(lesson.title).font(GlimmerFont.reading(.title, weight: .medium))
804 Text(lesson.tagline).foregroundStyle(.secondary)
805 NavigationLink { LessonReader(lesson: lesson) } label: {
806 Text(store.journal.lessons[lesson.id]?.completed == true ? "Read again" : "Read today’s lesson")
807 }
808 .glimmerButton(.prominent)
809 .padding(.top, 8)
810 }
811 }
812 }
813
814 @ViewBuilder private var reflection: some View {
815 if let practice = catalog.dailyReflection(on: store.day, level: store.journal.guidanceLevel(asOf: store.day)) {
816 Divider()
817 VStack(alignment: .leading, spacing: 12) {
818 VStack(alignment: .leading, spacing: 5) {
819 Eyebrow("A moment to reflect")
820 Text(practice.title).font(.headline)
821 Text(reflectionBody(practice.sub)).font(.callout)
822 }
823 Button("Open Coach") { open(.coach) }
824 .glimmerButton(.prominent)
825 .controlSize(.large)
826 }
827 }
828 }
829
830 private func reflectionBody(_ text: String) -> String {
831 // Keep the last two words together as the reflection changes each day.
832 guard let lastSpace = text.lastIndex(of: " ") else { return text }
833 var body = text
834 body.replaceSubrange(lastSpace...lastSpace, with: "\u{00A0}")
835 return body
836 }
837
838 private var plan: some View {
839 Panel(title: "Today’s plan") {
840 HStack {
841 Text("\(completed) of \(store.todaysTasks.count) complete").font(.headline)
842 Spacer()
843 CoinCount(count: store.journal.coins)
844 }
845 if !store.todaysTasks.isEmpty {
846 Meter(value: Double(completed) / Double(store.todaysTasks.count), tint: GlimmerColor.sage)
847 if store.todaysTasks.count > 5 && !typeSize.isAccessibilitySize {
848 ScrollView { taskList }.frame(height: 200)
849 } else { taskList }
850 }
851 Button("Plan my day") { open(.plan) }
852 .glimmerButton()
853 .controlSize(.large)
854 }
855 .completionLight(completed > 0 && completed == store.todaysTasks.count, radius: 16)
856 .readingArrival(delay: 0.14)
857 }
858
859 private var taskList: some View {
860 VStack(alignment: .leading, spacing: 0) {
861 ForEach(store.todaysTasks) { task in
862 let done = store.todayCompletion.contains(task.id)
863 Button {
864 _ = store.change { $0.toggleTask(task, on: store.day) }
865 } label: {
866 HStack(spacing: 2) {
867 Tick(done: done, size: 24).frame(width: 40, height: 44)
868 Text(task.name).multilineTextAlignment(.leading)
869 .foregroundStyle(done ? Color.secondary : Color.primary)
870 Spacer(minLength: 0)
871 }
872 .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading).contentShape(.rect)
873 }
874 .buttonStyle(RowPressStyle())
875 .tickFeedback(done)
876 .accessibilityValue(done ? "Complete" : "Incomplete")
877 }
878 }
879 // The tick sits in a wider target; pull it out so the mark lines up with the heading.
880 .padding(.leading, -8)
881 }
882
883 private var space: some View {
884 Panel(title: "Make a little space", plain: true) {
885 LazyVGrid(columns: [GridItem(.adaptive(minimum: typeSize.isAccessibilitySize ? 300 : 260), spacing: 10)],
886 alignment: .leading, spacing: 10) {
887 ForEach([Destination.toolkit, .challenges, .habits, .lessons, .cleaning, .seasonal, .settings]
888 .filter { $0 != .seasonal || featuredSeason == nil }) { item in
889 ActionRow(title: item.title, detail: item.detail, icon: item.icon, tint: item.tint) { open(item) }
890 }
891 }
892 .glassGroup(spacing: 10)
893 }
894 }
895}