Branchwell

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

1import SwiftUI
2
3/// What a to-do sheet is open for.
4enum TodoTool: Identifiable {
5 case breakDown(PersonalTodo, parent: TodoStep?)
6 case timeCheck(PersonalTodo)
7 case focus(PersonalTodo)
8
9 var id: String {
10 switch self {
11 case .breakDown(let todo, let parent): "break-\(todo.id)-\(parent?.id.uuidString ?? "")"
12 case .timeCheck(let todo): "time-\(todo.id)"
13 case .focus(let todo): "focus-\(todo.id)"
14 }
15 }
16}
17
18extension View {
19 /// Presents the Toolkit sheet for a to-do.
20 /// One thing covers the whole screen on iPhone and iPad so nothing else competes for attention.
21 func todoToolSheet(_ tool: Binding<TodoTool?>) -> some View {
22 let sheetTool = Binding<TodoTool?>(
23 get: { if case .focus = tool.wrappedValue { nil } else { tool.wrappedValue } },
24 set: { tool.wrappedValue = $0 })
25 let focusTodo = Binding<PersonalTodo?>(
26 get: { if case .focus(let todo) = tool.wrappedValue { todo } else { nil } },
27 set: { if $0 == nil { tool.wrappedValue = nil } })
28 return sheet(item: sheetTool) { tool in
29 switch tool {
30 case .breakDown(let todo, let parent): BreakItDownSheet(todo: todo, parent: parent)
31 case .timeCheck(let todo): TimeCheckSheet(todo: todo)
32 case .focus(let todo): OneThingSheet(start: todo)
33 }
34 }
35 #if os(iOS)
36 .fullScreenCover(item: focusTodo) { OneThingSheet(start: $0) }
37 #else
38 .sheet(item: focusTodo) { OneThingSheet(start: $0) }
39 #endif
40 }
41}
42
43// MARK: - Break it down
44
45struct BreakItDownPicker: View {
46 @Environment(JournalStore.self) private var store
47 @State private var tool: TodoTool?
48
49 var body: some View {
50 Page(title: "Break it down", subtitle: "Pick a to-do, and Glimmer suggests small steps you can edit before saving.", width: 620) {
51 TodoChooser(prompt: "What feels heavy?", detail: detail) { tool = .breakDown($0, parent: nil) }
52 }
53 .todoToolSheet($tool)
54 }
55
56 private func detail(_ todo: PersonalTodo) -> String? {
57 let steps = store.journal.steps(for: todo.id)
58 guard !steps.isEmpty else { return nil }
59 return "\(steps.filter(\.done).count) of \(steps.count) steps done"
60 }
61}
62
63/// Suggests steps for a to-do, or smaller steps for one step. Nothing is saved until Save.
64struct BreakItDownSheet: View {
65 @Environment(JournalStore.self) private var store
66 @Environment(\.dismiss) private var dismiss
67 @AppStorage(StepSize.preference) private var stepSize = StepSize.balanced.rawValue
68 let todo: PersonalTodo
69 let parent: TodoStep?
70
71 @State private var draft: [DraftStep] = []
72 @State private var previous: [DraftStep]?
73 @State private var result: (source: ToolkitSource, note: String?)?
74 @State private var working: Task<Void, Never>?
75 @State private var loaded = false
76
77 private struct DraftStep: Identifiable, Equatable {
78 let id = UUID()
79 var title: String
80 }
81
82 private var cleanTitles: [String] {
83 draft.map { $0.title.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
84 }
85 private var changed: Bool { cleanTitles != store.journal.steps(for: todo.id, parent: parent?.id).map(\.title) }
86
87 var body: some View {
88 NavigationStack {
89 Page(title: parent?.title ?? todo.title,
90 subtitle: parent == nil ? "Steps you could start right now. Edit anything before you save."
91 : "Smaller steps for this one step.", width: 560) {
92 Panel(title: "Step size") { StepSizeControl(value: $stepSize) }
93 if working != nil {
94 Panel { ToolkitThinking(text: thinkingText) }
95 } else if !draft.isEmpty {
96 steps
97 }
98 }
99 .actionBar(width: 560) {
100 SheetCancel { dismiss() }
101 if draft.isEmpty {
102 PrimaryAction(title: "Break it down", systemImage: "list.bullet.indent", action: generate)
103 .disabled(working != nil)
104 .accessibilityIdentifier("breakItDown.generate")
105 } else {
106 Button("Try again", systemImage: "arrow.clockwise", action: generate)
107 .glimmerButton().controlSize(.large)
108 .disabled(working != nil)
109 .accessibilityIdentifier("breakItDown.again")
110 PrimaryAction(title: "Save steps", action: save)
111 .disabled(working != nil || cleanTitles.isEmpty || !changed)
112 .keyboardShortcut(.defaultAction)
113 .accessibilityIdentifier("breakItDown.save")
114 }
115 }
116 .sheetCancel { dismiss() }
117 }
118 .onAppear {
119 guard !loaded else { return }
120 loaded = true
121 draft = store.journal.steps(for: todo.id, parent: parent?.id).map { DraftStep(title: $0.title) }
122 #if DEBUG
123 if ProcessInfo.processInfo.environment["GLIMMER_TOOLKIT_AUTORUN"] == "1" { generate() }
124 #endif
125 }
126 .onDisappear { working?.cancel() }
127 #if os(macOS)
128 .frame(minWidth: 520, idealWidth: 560, minHeight: 560, idealHeight: 640)
129 #endif
130 }
131
132 private var thinkingText: String {
133 if let agent = ToolkitAI.agentChoice { return "Asking \(agent.agent.title)…" }
134 return ToolkitAI.hasDeviceModel ? "Thinking on this device…" : "Finding steps…"
135 }
136
137 private var steps: some View {
138 Panel(title: "Steps") {
139 VStack(spacing: 6) {
140 ForEach($draft) { $step in
141 let index = draft.firstIndex(of: step) ?? 0
142 HStack(spacing: 8) {
143 Text("\(index + 1)").font(.callout.monospacedDigit().weight(.semibold)).foregroundStyle(.secondary)
144 .frame(minWidth: 22)
145 .accessibilityHidden(true)
146 TextField("Step", text: $step.title, axis: .vertical)
147 .textFieldStyle(.plain)
148 .frame(maxWidth: .infinity, minHeight: 36, alignment: .leading)
149 .accessibilityLabel("Step \(index + 1)")
150 Menu {
151 Button("Move up", systemImage: "arrow.up") { move(index, by: -1) }.disabled(index == 0)
152 Button("Move down", systemImage: "arrow.down") { move(index, by: 1) }.disabled(index == draft.count - 1)
153 Button("Remove step", systemImage: "trash", role: .destructive) { draft.remove(at: index) }
154 } label: {
155 Image(systemName: "ellipsis").frame(width: 32, height: 32).contentShape(.rect)
156 }
157 .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)
158 .foregroundStyle(.secondary)
159 .accessibilityLabel("Options for step \(index + 1)")
160 }
161 if step.id != draft.last?.id { Divider().padding(.leading, 30) }
162 }
163 }
164 HStack {
165 Button("Add a step", systemImage: "plus") { draft.append(DraftStep(title: "")) }
166 .glimmerButton()
167 .accessibilityIdentifier("breakItDown.addStep")
168 if let previous {
169 Button("Undo", systemImage: "arrow.uturn.backward") {
170 draft = previous
171 self.previous = nil
172 result = nil
173 }
174 .glimmerButton()
175 }
176 }
177 if let result { ToolkitSourceLabel(source: result.source, note: result.note) }
178 }
179 }
180
181 private func move(_ index: Int, by offset: Int) {
182 let target = index + offset
183 guard draft.indices.contains(target) else { return }
184 draft.swapAt(index, target)
185 }
186
187 private func generate() {
188 let size = StepSize(rawValue: stepSize) ?? .balanced
189 working = Task {
190 let answer = await ToolkitAI.breakDown(todo.title, parent: parent?.title, size: size)
191 guard !Task.isCancelled else { return }
192 if !draft.isEmpty { previous = draft }
193 draft = answer.value.map { DraftStep(title: $0) }
194 result = (answer.source, answer.note)
195 working = nil
196 AccessibilityNotification.Announcement("\(draft.count) steps suggested").post()
197 }
198 }
199
200 private func save() {
201 guard store.journal.personalTodos?.contains(where: { $0.id == todo.id }) == true else {
202 store.notice = "This to-do was removed."
203 dismiss()
204 return
205 }
206 if store.change({ $0.replaceSteps(for: todo.id, parent: parent?.id, with: cleanTitles) }) {
207 store.notice = "Steps saved."
208 dismiss()
209 }
210 }
211}
212
213/// A to-do's steps as a checklist, inside the to-do editor.
214struct TodoStepsPanel: View {
215 @Environment(JournalStore.self) private var store
216 let todo: PersonalTodo
217 @Binding var tool: TodoTool?
218 @State private var offerComplete = false
219
220 private var steps: [TodoStep] { store.journal.steps(for: todo.id) }
221 private var estimate: TodoEstimate? { store.journal.estimate(for: todo.id) }
222
223 var body: some View {
224 Panel(title: "Steps") {
225 if steps.isEmpty {
226 Text("Big or vague? Break it into steps you could start right now.")
227 .font(.callout).foregroundStyle(.secondary)
228 } else {
229 VStack(alignment: .leading, spacing: 0) {
230 ForEach(steps) { step in
231 row(step, level: 0)
232 ForEach(store.journal.steps(for: todo.id, parent: step.id)) { row($0, level: 1) }
233 }
234 }
235 .padding(.leading, -8)
236 }
237 FlowLayout(spacing: 8) {
238 Button(steps.isEmpty ? "Break it down" : "Redo steps", systemImage: "list.bullet.indent") {
239 tool = .breakDown(todo, parent: nil)
240 }
241 .accessibilityIdentifier("todoSteps.breakDown")
242 Button(estimate.map { "Time check · \(ToolkitFormat.chip($0.minutes))" } ?? "Time check", systemImage: "clock") {
243 tool = .timeCheck(todo)
244 }
245 .accessibilityIdentifier("todoSteps.timeCheck")
246 if !todo.completed {
247 Button("One thing", systemImage: "scope") { tool = .focus(todo) }
248 .accessibilityIdentifier("todoSteps.focus")
249 }
250 }
251 .glimmerButton()
252 }
253 .alert("All steps done", isPresented: $offerComplete) {
254 Button("Complete to-do") { store.setPersonalTodoDone(todo.id, done: true) }
255 Button("Not yet", role: .cancel) {}
256 } message: {
257 Text("Mark “\(todo.title)” complete?")
258 }
259 }
260
261 private func row(_ step: TodoStep, level: Int) -> some View {
262 HStack(spacing: 4) {
263 TickButton(done: step.done, label: step.title, size: level == 0 ? 24 : 20) { toggle(step) }
264 .accessibilityValue(step.done ? "Done" : "Not done")
265 .accessibilityAddTraits(.isToggle)
266 Text(step.title).font(level == 0 ? .body : .callout)
267 .foregroundStyle(step.done ? .secondary : .primary)
268 .frame(maxWidth: .infinity, alignment: .leading)
269 .accessibilityHidden(true)
270 if level < TodoStep.maxLevels - 1 && !step.done {
271 Button {
272 tool = .breakDown(todo, parent: step)
273 } label: {
274 Image(systemName: "arrow.turn.down.right").font(.footnote.weight(.semibold))
275 .frame(width: 36, height: 36).contentShape(.rect)
276 }
277 .buttonStyle(.plain).foregroundStyle(.secondary)
278 .help("Break this step down")
279 .accessibilityLabel("Break “\(step.title)” down")
280 }
281 }
282 .padding(.leading, CGFloat(level) * 28)
283 .animation(.easeOut(duration: 0.2), value: step.done)
284 }
285
286 private func toggle(_ step: TodoStep) {
287 guard store.change({ $0.setStepDone(step.id, done: !step.done) }) else { return }
288 let all = store.journal.flatSteps(for: todo.id)
289 if !step.done, !all.isEmpty, all.allSatisfy(\.done), !todo.completed { offerComplete = true }
290 }
291}
292
293// MARK: - Time check
294
295struct TimeCheckView: View {
296 @Environment(JournalStore.self) private var store
297 @State private var tool: TodoTool?
298
299 private var dueTotal: Int {
300 store.duePersonalTodos.compactMap { store.journal.estimate(for: $0.id)?.minutes }.reduce(0, +)
301 }
302
303 var body: some View {
304 Page(title: "Time check", subtitle: "Realistic guesses, adjusted for how focused you feel today. Adjust any of them.", width: 620) {
305 if dueTotal > 0 {
306 Panel {
307 Text("About \(ToolkitFormat.minutes(dueTotal)) of to-dos due today")
308 .font(GlimmerFont.display(.title3, weight: .semibold))
309 Text("Leave room for breaks and the unexpected.").font(.callout).foregroundStyle(.secondary)
310 }
311 .accessibilityElement(children: .combine)
312 }
313 TodoChooser(prompt: "Add a to-do", detail: detail) { tool = .timeCheck($0) }
314 }
315 .todoToolSheet($tool)
316 }
317
318 private func detail(_ todo: PersonalTodo) -> String? {
319 store.journal.estimate(for: todo.id).map { ToolkitFormat.chip($0.minutes) }
320 }
321}
322
323struct TimeCheckSheet: View {
324 @Environment(JournalStore.self) private var store
325 @Environment(\.dismiss) private var dismiss
326 let todo: PersonalTodo
327 @State private var chosenFocus: FocusLevel = .steady
328 @State private var minutes: Int?
329 @State private var source: ToolkitSource = .guide
330 @State private var note: String?
331 @State private var working: Task<Void, Never>?
332
333 private var loggedFocus: FocusLevel? { store.todaysFocus }
334 private var focus: FocusLevel { loggedFocus ?? chosenFocus }
335 private var saved: TodoEstimate? { store.journal.estimate(for: todo.id) }
336
337 var body: some View {
338 NavigationStack {
339 Page(title: todo.title, subtitle: "How long might this take you today?", width: 520) {
340 Panel(title: "Focus") {
341 if let loggedFocus {
342 Label("From today’s energy check-in: \(loggedFocus.rawValue.lowercased())", systemImage: "bolt.heart")
343 .font(.callout)
344 } else {
345 Text("How focused do you feel?").font(.callout)
346 GlassSegments(label: "How focused do you feel?",
347 options: FocusLevel.allCases.map { GlassSegment(value: $0, title: $0.rawValue) },
348 selection: $chosenFocus)
349 .accessibilityIdentifier("timeCheck.focus")
350 Text(chosenFocus.detail).font(.footnote).foregroundStyle(.secondary)
351 }
352 }
353 if working != nil {
354 Panel { ToolkitThinking(text: "Estimating…") }
355 } else if let minutes {
356 Panel(title: "Estimate") {
357 Text(ToolkitFormat.chip(minutes))
358 .font(.system(size: 44, weight: .bold, design: .rounded).monospacedDigit())
359 .contentTransition(.numericText(value: Double(minutes)))
360 .accessibilityIdentifier("timeCheck.result")
361 Stepper("Adjust", value: Binding(get: { minutes }, set: { self.minutes = $0; source = .person; note = nil }),
362 in: 5...600, step: 5)
363 .accessibilityValue(ToolkitFormat.minutes(minutes))
364 ToolkitSourceLabel(source: source, note: note)
365 }
366 }
367 }
368 .actionBar(width: 520) {
369 SheetCancel { dismiss() }
370 if saved != nil {
371 Button("Clear estimate", systemImage: "xmark") {
372 if store.change({ $0.setEstimate(nil, source: "", for: todo.id) }) { dismiss() }
373 }
374 .labelStyle(.iconOnly).glimmerButton().controlSize(.large)
375 }
376 if minutes == nil {
377 PrimaryAction(title: "Check time", systemImage: "clock", action: estimate)
378 .disabled(working != nil)
379 .accessibilityIdentifier("timeCheck.estimate")
380 } else {
381 Button("Again", systemImage: "arrow.clockwise", action: estimate)
382 .glimmerButton().controlSize(.large).disabled(working != nil)
383 PrimaryAction(title: "Save", action: save)
384 .disabled(working != nil)
385 .keyboardShortcut(.defaultAction)
386 .accessibilityIdentifier("timeCheck.save")
387 }
388 }
389 .sheetCancel { dismiss() }
390 }
391 .onAppear {
392 if let saved {
393 minutes = saved.minutes
394 source = ToolkitSource(rawValue: saved.source) ?? .guide
395 }
396 #if DEBUG
397 if ProcessInfo.processInfo.environment["GLIMMER_TOOLKIT_AUTORUN"] == "1" { estimate() }
398 #endif
399 }
400 .onDisappear { working?.cancel() }
401 #if os(macOS)
402 .frame(minWidth: 480, idealWidth: 520, minHeight: 460)
403 #endif
404 }
405
406 private func estimate() {
407 let steps = store.journal.flatSteps(for: todo.id).filter { !$0.done }.map(\.title)
408 let level = focus
409 working = Task {
410 let answer = await ToolkitAI.estimate(todo.title, steps: steps, focus: level)
411 guard !Task.isCancelled else { return }
412 minutes = answer.value
413 source = answer.source
414 note = answer.note
415 working = nil
416 AccessibilityNotification.Announcement("About \(ToolkitFormat.minutes(answer.value))").post()
417 }
418 }
419
420 private func save() {
421 guard let minutes else { return }
422 if store.change({ $0.setEstimate(minutes, source: source.rawValue, for: todo.id) }) {
423 store.notice = "Estimate saved."
424 dismiss()
425 }
426 }
427}