Branchwell

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

1import SwiftUI
2
3/// One thing: pick a to-do, then see only its next step with a gentle timer.
4struct OneThingView: View {
5 @Environment(JournalStore.self) private var store
6 @State private var tool: TodoTool?
7 @State private var showAll = false
8
9 var body: some View {
10 Page(title: "One thing", subtitle: "Just the next step, with a gentle timer. Everything else can wait.", width: 620) {
11 OneThingChoices { tool = .focus($0) }
12 if store.openPersonalTodos.count > 2 {
13 Panel(title: "Something else", plain: true) {
14 DisclosureGroup("All open to-dos (\(store.openPersonalTodos.count))", isExpanded: $showAll) {
15 VStack(spacing: 8) {
16 ForEach(store.openPersonalTodos) { todo in
17 ActionRow(title: todo.title, tint: GlimmerColor.sage) { tool = .focus(todo) }
18 }
19 }
20 .glassGroup(spacing: 8)
21 .padding(.top, 6)
22 }
23 }
24 }
25 }
26 .todoToolSheet($tool)
27 .hidesTabBar()
28 }
29}
30
31/// "What next?": two suggestions, chosen by due date, size and how focused the person feels.
32struct OneThingChoices: View {
33 @Environment(JournalStore.self) private var store
34 var excluding: UUID? = nil
35 let choose: (PersonalTodo) -> Void
36
37 private var choices: [PersonalTodo] {
38 OneThingPicker.choices(store.openPersonalTodos.filter { $0.id != excluding },
39 estimates: store.journal.todoEstimates ?? [],
40 focus: store.todaysFocus ?? .steady, today: PracticeDate.key(store.day),
41 hour: Calendar.current.component(.hour, from: .now))
42 }
43
44 var body: some View {
45 Panel(title: "What next?", plain: true) {
46 if choices.isEmpty {
47 Text("No open to-dos. Add one in Plan, or use Unload to empty your head.")
48 .font(.callout).foregroundStyle(.secondary)
49 } else {
50 VStack(spacing: 8) {
51 ForEach(choices) { todo in
52 ActionRow(title: todo.title, detail: reason(todo), icon: Glyph.symbol(name: todo.title, category: "todo"), tint: Glyph.tint(for: "todo")) { choose(todo) }
53 .accessibilityIdentifier("oneThing.choice")
54 }
55 }
56 .glassGroup(spacing: 8)
57 Text(choices.count == 2 ? "Two options. Pick whichever feels doable." : "Pick it when you’re ready.")
58 .font(.footnote).foregroundStyle(.secondary)
59 }
60 }
61 }
62
63 static func dueLabel(_ due: String, today: String) -> String {
64 if due < today { return "Overdue" }
65 if due == today { return "Due today" }
66 guard let date = PracticeDate.parse(due), let start = PracticeDate.parse(today),
67 let days = Calendar.current.dateComponents([.day], from: start, to: date).day else { return "Due later" }
68 if days == 1 { return "Due tomorrow" }
69 return days < 7 ? "Due \(date.formatted(.dateTime.weekday(.wide)))" : "Due \(date.formatted(.dateTime.month(.abbreviated).day()))"
70 }
71
72 private func reason(_ todo: PersonalTodo) -> String? {
73 var parts: [String] = []
74 let today = PracticeDate.key(store.day)
75 if let due = todo.dueDay { parts.append(Self.dueLabel(due, today: today)) }
76 if let minutes = store.journal.estimate(for: todo.id)?.minutes { parts.append(ToolkitFormat.chip(minutes)) }
77 if let step = store.journal.nextStep(for: todo.id) { parts.append("Next: \(step.title)") }
78 return parts.isEmpty ? nil : parts.joined(separator: " · ")
79 }
80}
81
82/// The focus card for one to-do.
83struct OneThingSheet: View {
84 @Environment(JournalStore.self) private var store
85 @Environment(\.dismiss) private var dismiss
86 @Environment(\.accessibilityReduceMotion) private var reduceMotion
87 @State private var todoID: UUID
88 @State private var skipped: Set<UUID> = []
89 @State private var deadline: Date?
90 @State private var timerMinutes = 10
91 @State private var finished = false
92 @State private var timeUp = false
93 @State private var breakdown: TodoTool?
94
95 init(start: PersonalTodo) {
96 _todoID = State(initialValue: start.id)
97 }
98
99 private var todo: PersonalTodo? { store.journal.personalTodos?.first { $0.id == todoID } }
100 private var allSteps: [TodoStep] { store.journal.flatSteps(for: todoID) }
101 private var current: TodoStep? { store.journal.nextStep(for: todoID, skipping: skipped) }
102
103 var body: some View {
104 NavigationStack {
105 ScrollView {
106 VStack(alignment: .leading, spacing: 22) {
107 if let todo {
108 if finished || todo.completed { done(todo) } else { focus(todo) }
109 } else {
110 ContentUnavailableView("This to-do was removed", systemImage: "checklist")
111 }
112 }
113 .frame(maxWidth: 560, alignment: .leading)
114 .padding(.horizontal, 24).padding(.top, 72).padding(.bottom, 28)
115 .frame(maxWidth: .infinity)
116 }
117 .background { PageBackdrop() }
118 .sheetCancel { dismiss() }
119 .actionBar(width: 560) { actions }
120 }
121 .sheet(item: $breakdown) { tool in
122 if case .breakDown(let todo, let parent) = tool { BreakItDownSheet(todo: todo, parent: parent) }
123 }
124 .onAppear {
125 if let minutes = store.journal.estimate(for: todoID)?.minutes {
126 let remaining = max(1, allSteps.filter { !$0.done }.count)
127 timerMinutes = min(25, max(5, minutes / remaining / 5 * 5))
128 }
129 }
130 #if os(macOS)
131 .frame(minWidth: 520, idealWidth: 600, minHeight: 520, idealHeight: 620)
132 #endif
133 }
134
135 // MARK: Focus
136
137 @ViewBuilder private func focus(_ todo: PersonalTodo) -> some View {
138 VStack(alignment: .leading, spacing: 8) {
139 Text(todo.title).font(.headline).foregroundStyle(.secondary)
140 if !allSteps.isEmpty {
141 let doneCount = allSteps.filter(\.done).count
142 StepDots(current: doneCount - 1, total: allSteps.count, tint: GlimmerColor.sage)
143 Text("\(doneCount) of \(allSteps.count) steps done").font(.footnote).foregroundStyle(.secondary)
144 }
145 }
146 VStack(alignment: .leading, spacing: 10) {
147 Text(current == nil ? "Now" : "Next step").font(.subheadline.weight(.semibold)).foregroundStyle(.secondary)
148 Text(current?.title ?? todo.title)
149 .font(GlimmerFont.reading(.largeTitle, weight: .medium))
150 .fixedSize(horizontal: false, vertical: true)
151 .contentTransition(.opacity)
152 .animation(reduceMotion ? nil : .easeOut(duration: 0.25), value: current?.id)
153 .accessibilityAddTraits(.isHeader)
154 .accessibilityIdentifier("oneThing.step")
155 if !skipped.isEmpty {
156 Button("Bring back skipped steps", systemImage: "arrow.uturn.backward") { skipped = [] }
157 .font(.callout).buttonStyle(.borderless)
158 }
159 }
160 timer
161 }
162
163 private var timer: some View {
164 VStack(alignment: .leading, spacing: 12) {
165 if let end = deadline {
166 FocusCountdown(end: end, totalMinutes: timerMinutes) {
167 timeUp = true
168 deadline = nil
169 }
170 Button("Stop timer", systemImage: "stop.fill") { deadline = nil }.glimmerButton()
171 } else {
172 if timeUp {
173 Text("Time’s up. Keep going if it’s flowing, or take a short break.").font(.callout)
174 }
175 HStack(spacing: 12) {
176 Button("Start timer", systemImage: "timer") {
177 timeUp = false
178 deadline = .now.addingTimeInterval(Double(timerMinutes) * 60)
179 }
180 .glimmerButton()
181 .accessibilityIdentifier("oneThing.timer")
182 Stepper(value: $timerMinutes, in: 5...60, step: 5) {
183 Text("\(timerMinutes) min").monospacedDigit().foregroundStyle(.secondary)
184 }
185 .fixedSize()
186 .accessibilityLabel("Timer length")
187 .accessibilityValue("\(timerMinutes) minutes")
188 }
189 }
190 }
191 .padding(.top, 8)
192 .sensoryFeedback(.success, trigger: timeUp) { _, new in new }
193 // Each finished step lands with a tap you can feel.
194 .sensoryFeedback(.success, trigger: allSteps.filter(\.done).count) { old, new in new > old }
195 }
196
197 @ViewBuilder private var actions: some View {
198 if let todo, !(finished || todo.completed) {
199 SheetCancel(title: "Close") { dismiss() }
200 Menu {
201 if let current {
202 Button("Skip this step", systemImage: "forward") { skipped.insert(current.id) }
203 if current.parentID == nil {
204 Button("Break this step down", systemImage: "list.bullet.indent") {
205 breakdown = .breakDown(todo, parent: current)
206 }
207 }
208 } else {
209 Button("Break it down", systemImage: "list.bullet.indent") { breakdown = .breakDown(todo, parent: nil) }
210 }
211 Button("Pick something else", systemImage: "arrow.triangle.swap") { finished = true }
212 } label: {
213 Label("More", systemImage: "ellipsis").labelStyle(.iconOnly).frame(width: 22, height: 30)
214 }
215 .menuStyle(.button).menuIndicator(.hidden)
216 .glimmerButton(.standard, circle: true).controlSize(.large)
217 .accessibilityLabel("More options")
218 .accessibilityIdentifier("oneThing.more")
219 PrimaryAction(title: current == nil ? "Done with this to-do" : "Done", systemImage: "checkmark", action: complete)
220 .keyboardShortcut(.defaultAction)
221 .accessibilityIdentifier("oneThing.done")
222 } else {
223 PrimaryAction(title: "Close") { dismiss() }
224 }
225 }
226
227 private func complete() {
228 deadline = nil
229 timeUp = false
230 if let current {
231 store.change { $0.setStepDone(current.id, done: true) }
232 if store.journal.nextStep(for: todoID, skipping: skipped) == nil,
233 store.journal.flatSteps(for: todoID).allSatisfy(\.done) {
234 store.setPersonalTodoDone(todoID, done: true)
235 finished = true
236 }
237 } else {
238 store.setPersonalTodoDone(todoID, done: true)
239 finished = true
240 }
241 }
242
243 // MARK: Done
244
245 @ViewBuilder private func done(_ todo: PersonalTodo) -> some View {
246 VStack(alignment: .leading, spacing: 8) {
247 if todo.completed {
248 Label("Done", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(GlimmerColor.sage)
249 }
250 Text(todo.completed ? todo.title : "Pick something else")
251 .font(GlimmerFont.reading(.largeTitle, weight: .medium))
252 .fixedSize(horizontal: false, vertical: true)
253 Text(todo.completed ? "That’s one thing finished. Rest, or pick the next." : "No problem. Here are two other options.")
254 .foregroundStyle(.secondary)
255 }
256 .completionLight(todo.completed, radius: 12)
257 OneThingChoices(excluding: todo.id) { next in
258 todoID = next.id
259 skipped = []
260 finished = false
261 }
262 }
263}
264
265/// A quiet countdown that calls `finished` once when it reaches zero.
266private struct FocusCountdown: View {
267 let end: Date
268 let totalMinutes: Int
269 let finished: () -> Void
270
271 var body: some View {
272 TimelineView(.periodic(from: .now, by: 1)) { tick in
273 let seconds = max(0, Int(ceil(end.timeIntervalSince(tick.date))))
274 VStack(alignment: .leading, spacing: 10) {
275 Text(String(format: "%d:%02d", seconds / 60, seconds % 60))
276 .font(.system(size: 48, weight: .bold, design: .rounded).monospacedDigit())
277 .contentTransition(.numericText(countsDown: true))
278 .accessibilityLabel("\(seconds / 60) minutes \(seconds % 60) seconds left")
279 Meter(value: 1 - Double(seconds) / Double(max(1, totalMinutes * 60)), tint: GlimmerColor.honey)
280 }
281 .onChange(of: seconds == 0) { _, done in if done { finished() } }
282 }
283 }
284}