forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatFirstGoalsPage.swift
More file actions
441 lines (405 loc) · 15.8 KB
/
Copy pathChatFirstGoalsPage.swift
File metadata and controls
441 lines (405 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import Foundation
import OmiTheme
import SwiftUI
/// Universal canonical Goals destination. The page owns no copied goal or
/// task state: it renders the shared projection and delegates task mutation to
/// `TasksStore` after that store hydrates the canonical task ID.
@MainActor
struct ChatFirstGoalsPage: View {
@ObservedObject var navigation: ChatFirstShellNavigation
@ObservedObject var goalsStore: CanonicalGoalsStore
@ObservedObject var tasksStore: TasksStore
let chatProvider: ChatProvider
let automationRuntime: ChatFirstAutomationRuntime?
@State private var resolvingTaskIDs = Set<String>()
private var pendingGoalID: String? {
guard case .goal(let id) = navigation.pendingFocus else { return nil }
return id
}
private var displayedDetail: OmiAPI.GoalDetailProjection? {
guard let detail = goalsStore.selectedGoalDetail else { return nil }
if let pendingGoalID { return detail.goal.goalId == pendingGoalID ? detail : nil }
return detail.goal.goalId == goalsStore.primaryFocusedGoal?.goalId ? detail : nil
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
Group {
switch goalsStore.availability {
case .unavailable(let message):
unavailableState(message)
case .inactive, .loading:
if goalsStore.activeGoals.isEmpty {
ProgressView("Loading goals")
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
goalContent
}
default:
if !ChatFirstGoalPresentationPolicy.shouldShowGoalContent(
activeGoalCount: goalsStore.activeGoals.count,
displayedGoalID: displayedDetail?.goal.goalId
) {
emptyState
} else {
goalContent
}
}
}
}
.onAppear {
Task { await refreshProjectionAndDetail() }
registerAutomationActions()
}
.onDisappear { automationRuntime?.unregisterGoalsPage() }
.onChange(of: navigation.pendingFocus) { _, _ in
Task { await loadDetailForCurrentFocus() }
}
.accessibilityIdentifier("chat-first-goals-page")
}
private var header: some View {
HStack(alignment: .firstTextBaseline) {
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text("Goals")
.scaledFont(size: OmiType.title, weight: .bold)
.foregroundStyle(Ink.primary)
Text("Keep the work that matters in view.")
.scaledFont(size: OmiType.body)
.foregroundStyle(Ink.secondary)
}
Spacer()
Button {
Task { await refreshProjectionAndDetail() }
} label: {
Image(systemName: "arrow.clockwise")
.scaledFont(size: OmiType.body, weight: .medium)
}
.buttonStyle(.plain)
.disabled(goalsStore.isLoading)
.accessibilityLabel("Refresh goals")
.accessibilityIdentifier("chat-first-goals-refresh")
}
.padding(.horizontal, OmiSpacing.xxl)
.padding(.vertical, OmiSpacing.xl)
}
private var goalContent: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: OmiSpacing.xxl) {
if let detail = displayedDetail {
ChatFirstFocusedGoalSection(
detail: detail,
isResolvingTask: { resolvingTaskIDs.contains($0) },
onToggleTask: toggleTask,
onViewTasks: {
navigation.open(focus: .goal(id: detail.goal.goalId), destination: .tasks)
},
onContinueInChat: { navigation.discuss(.goal(id: detail.goal.goalId), using: chatProvider) },
onVisible: acknowledgeVisibleGoal
)
.id(detail.goal.goalId)
} else if goalsStore.primaryFocusedGoal != nil || pendingGoalID != nil {
ProgressView("Loading goal")
.frame(maxWidth: .infinity)
}
if !goalsStore.otherActiveGoals.isEmpty {
VStack(alignment: .leading, spacing: OmiSpacing.md) {
Text("Other active goals")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundStyle(Ink.primary)
ForEach(goalsStore.otherActiveGoals, id: \.goalId) { goal in
ChatFirstGoalRow(
goal: goal,
isSettingFocus: goalsStore.focusMutationGoalID == goal.goalId,
onDiscuss: { navigation.discuss(.goal(id: goal.goalId), using: chatProvider) },
onSetFocus: { setFocus(goalID: goal.goalId) }
)
}
}
}
if let error = goalsStore.error, displayedDetail != nil {
Text(error)
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.secondary)
.accessibilityIdentifier("chat-first-goals-inline-error")
}
}
.padding(.horizontal, OmiSpacing.xxl)
.padding(.bottom, OmiSpacing.xxl)
}
}
private var emptyState: some View {
ContentUnavailableView {
Label("No active goals", systemImage: "target")
} description: {
Text("Omi can help you turn what matters into a clear goal.")
} actions: {
Button("Talk to Omi about a goal") {
navigation.discuss(.goals, using: chatProvider)
}
.accessibilityIdentifier("chat-first-goals-empty-discuss")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func unavailableState(_ message: String) -> some View {
ContentUnavailableView {
Label("Goals are unavailable", systemImage: "exclamationmark.triangle")
} description: {
Text(message)
} actions: {
Button("Refresh") {
Task { await refreshProjectionAndDetail() }
}
.accessibilityIdentifier("chat-first-goals-unavailable-refresh")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func refreshProjectionAndDetail() async {
await goalsStore.load()
await loadDetailForCurrentFocus()
}
private func loadDetailForCurrentFocus() async {
let goalID = pendingGoalID ?? goalsStore.primaryFocusedGoal?.goalId
guard let goalID else { return }
_ = await goalsStore.loadDetail(goalID: goalID)
}
private func acknowledgeVisibleGoal(_ goalID: String) {
guard
let focus = ChatFirstGoalDetailPolicy.focusToAcknowledge(
pendingFocus: navigation.pendingFocus,
visibleGoalID: goalID
)
else { return }
_ = navigation.acknowledgeFocus(focus)
}
private func setFocus(goalID: String) {
Task { @MainActor in
guard await goalsStore.setAsFocus(goalID: goalID) else { return }
_ = await goalsStore.loadDetail(goalID: goalID)
}
}
private func toggleTask(_ taskID: String) {
guard !resolvingTaskIDs.contains(taskID) else { return }
resolvingTaskIDs.insert(taskID)
Task { @MainActor in
defer { resolvingTaskIDs.remove(taskID) }
guard let task = await tasksStore.resolveCanonicalTask(id: taskID) else { return }
await tasksStore.toggleTask(task)
if let goalID = displayedDetail?.goal.goalId {
_ = await goalsStore.loadDetail(goalID: goalID)
}
}
}
private func registerAutomationActions() {
automationRuntime?.registerGoalsPage(
setFocus: { [goalsStore] in
guard let goalID = goalsStore.otherActiveGoals.first?.goalId else { return false }
guard await goalsStore.setAsFocus(goalID: goalID) else { return false }
return await goalsStore.loadDetail(goalID: goalID) != nil
},
openRelatedTasks: { [navigation, goalsStore] in
guard let goalID = goalsStore.selectedGoalDetail?.goal.goalId else { return false }
navigation.open(focus: .goal(id: goalID), destination: .tasks)
return true
}
)
}
}
private struct ChatFirstFocusedGoalSection: View {
let detail: OmiAPI.GoalDetailProjection
let isResolvingTask: (String) -> Bool
let onToggleTask: (String) -> Void
let onViewTasks: () -> Void
let onContinueInChat: () -> Void
let onVisible: (String) -> Void
private var completedCount: Int { ChatFirstGoalDetailPolicy.completedTaskCount(in: detail) }
private var nextTasks: [OmiAPI.ActionItemResponse] {
detail.tasks.filter { !$0.completed }.prefix(3).map { $0 }
}
var body: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack(alignment: .top, spacing: OmiSpacing.md) {
Image(systemName: "target")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundStyle(Ink.secondary)
.frame(width: 28, height: 28)
.glassCard(cornerRadius: OmiChrome.chipRadius)
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text("Focused goal")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundStyle(Ink.secondary)
Text(detail.goal.title)
.scaledFont(size: OmiType.subheading, weight: .bold)
.foregroundStyle(Ink.primary)
Text(detail.goal.desiredOutcome)
.scaledFont(size: OmiType.body)
.foregroundStyle(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
if let whyItMatters = detail.goal.whyItMatters, !whyItMatters.isEmpty {
Text(whyItMatters)
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
HStack {
Text("Progress")
Spacer()
Text("\(completedCount) of \(detail.tasks.count) tasks")
}
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundStyle(Ink.secondary)
ProgressView(value: Double(completedCount), total: Double(max(1, detail.tasks.count)))
.tint(Ink.listeningGreen)
}
if !nextTasks.isEmpty {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
Text("Next up")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundStyle(Ink.secondary)
ForEach(nextTasks, id: \.id) { task in
ChatFirstGoalTaskRow(
task: task,
isResolving: isResolvingTask(task.id),
onToggle: { onToggleTask(task.id) }
)
}
}
}
HStack(spacing: OmiSpacing.lg) {
Button("View related tasks", action: onViewTasks)
.buttonStyle(.plain)
.foregroundStyle(Ink.secondary)
.accessibilityIdentifier("chat-first-goal-\(detail.goal.goalId)-tasks")
Button("Continue in Chat", action: onContinueInChat)
.buttonStyle(.plain)
.foregroundStyle(Ink.secondary)
.accessibilityIdentifier("chat-first-goal-\(detail.goal.goalId)-discuss")
}
.scaledFont(size: OmiType.caption, weight: .semibold)
}
.padding(OmiSpacing.xl)
.frame(maxWidth: .infinity, alignment: .leading)
// The focused goal is the emphasised card on the page; no drop shadow, because
// the panel already carries the one ambient shadow in this system.
.glassCard(emphasized: true)
.onAppear { onVisible(detail.goal.goalId) }
.accessibilityElement(children: .contain)
.accessibilityIdentifier("chat-first-goal-focused-\(detail.goal.goalId)")
}
}
private struct ChatFirstGoalTaskRow: View {
let task: OmiAPI.ActionItemResponse
let isResolving: Bool
let onToggle: () -> Void
var body: some View {
HStack(alignment: .top, spacing: OmiSpacing.sm) {
Button(action: onToggle) {
Image(systemName: task.completed ? "checkmark.circle.fill" : "circle")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundStyle(task.completed ? Ink.listeningGreen : Ink.secondary)
}
.buttonStyle(.plain)
.disabled(isResolving)
.accessibilityLabel(
task.completed ? "Mark \(task.description_) incomplete" : "Mark \(task.description_) complete"
)
.accessibilityIdentifier("chat-first-goal-task-\(task.id)-toggle")
Text(task.description_)
.scaledFont(size: OmiType.body)
.foregroundStyle(task.completed ? Ink.secondary : Ink.primary)
.strikethrough(task.completed, color: Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
if isResolving {
ProgressView()
.controlSize(.small)
}
}
.accessibilityIdentifier("chat-first-goal-task-\(task.id)")
}
}
private struct ChatFirstGoalRow: View {
let goal: OmiAPI.GoalResponse
let isSettingFocus: Bool
let onDiscuss: () -> Void
let onSetFocus: () -> Void
var body: some View {
HStack(alignment: .top, spacing: OmiSpacing.md) {
Image(systemName: goal.status == .focused ? "target" : "circle")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundStyle(Ink.secondary)
.frame(width: 22, height: 22)
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text(goal.title)
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundStyle(Ink.primary)
// Goals created without an outcome carry the title in `desiredOutcome`;
// echoing it under the title reads as a rendering bug.
if goal.desiredOutcome.trimmingCharacters(in: .whitespacesAndNewlines)
.compare(goal.title, options: .caseInsensitive) != .orderedSame
{
Text(goal.desiredOutcome)
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.secondary)
.lineLimit(2)
}
Text(ChatFirstGoalProgressPolicy.summary(for: goal))
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundStyle(Ink.secondary)
}
Spacer(minLength: OmiSpacing.md)
VStack(alignment: .trailing, spacing: OmiSpacing.sm) {
Button("Discuss", action: onDiscuss)
.buttonStyle(.plain)
.foregroundStyle(Ink.secondary)
.accessibilityIdentifier("chat-first-goal-\(goal.goalId)-discuss")
Button {
onSetFocus()
} label: {
HStack(spacing: OmiSpacing.xxs) {
if isSettingFocus { ProgressView().controlSize(.small) }
Text("Set as focus")
}
}
.buttonStyle(.plain)
.foregroundStyle(Ink.secondary)
.disabled(isSettingFocus)
.accessibilityIdentifier("chat-first-goal-\(goal.goalId)-set-focus")
}
.scaledFont(size: OmiType.caption, weight: .medium)
}
.padding(OmiSpacing.md)
.frame(maxWidth: .infinity, alignment: .leading)
.glassCard(cornerRadius: PageGlass.rowRadius)
.accessibilityElement(children: .contain)
.accessibilityIdentifier("chat-first-goal-row-\(goal.goalId)")
}
}
/// Canonical goals use a generic numeric projection. The list must therefore
/// show progress from that projection rather than inventing a task count or
/// consulting the legacy goal store.
enum ChatFirstGoalProgressPolicy {
static func summary(for goal: OmiAPI.GoalResponse) -> String {
let unit = goal.unit.map { " \($0)" } ?? ""
// A goal created without an explicit target keeps the creation default
// (1.0) while progress updates push `currentValue` past it — "20 of 1"
// reads as impossible because the target was never meaningfully set. When
// the current value has overshot that unconfigured default, the target
// carries no information; report the value alone.
if goal.unit == nil, goal.targetValue <= 1, goal.currentValue > goal.targetValue {
return "Progress: \(formatted(goal.currentValue))"
}
return "Progress: \(formatted(goal.currentValue)) of \(formatted(goal.targetValue))\(unit)"
}
private static func formatted(_ value: Double) -> String {
if value.rounded() == value { return String(Int(value)) }
return String(format: "%.1f", value)
}
}
enum ChatFirstGoalPresentationPolicy {
static func shouldShowGoalContent(activeGoalCount: Int, displayedGoalID: String?) -> Bool {
activeGoalCount > 0 || displayedGoalID != nil
}
}