-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTodayFeature.swift
More file actions
362 lines (334 loc) · 12.8 KB
/
Copy pathTodayFeature.swift
File metadata and controls
362 lines (334 loc) · 12.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
//
// TodayFeature.swift
// DevLogPresentation
//
// Created by opfic on 6/14/26.
//
import ComposableArchitecture
import DevLogCore
import DevLogDomain
import Foundation
@Reducer
struct TodayFeature {
enum SectionScope: Hashable, CaseIterable {
case all
case focused
case overdue
case dueSoon
}
enum SectionCategory: Hashable {
case later
case unscheduled
case focused
case overdue
case dueSoon
}
struct SectionContent: Identifiable, Equatable {
var id: SectionCategory { category }
let category: SectionCategory
let title: String
let items: [TodayTodoItem]
}
struct SectionCollection {
var focused: [TodayTodoItem] = []
var overdue: [TodayTodoItem] = []
var dueSoon: [TodayTodoItem] = []
var later: [TodayTodoItem] = []
var unscheduled: [TodayTodoItem] = []
}
@ObservableState
struct State: Equatable {
@Presents var alert: AlertState<Never>?
var todos: [TodayTodoItem] = []
var selectedSectionScope: SectionScope = .all
var displayOptions: TodayDisplayOptions
var loading = LoadingFeature.State()
init(displayOptions: TodayDisplayOptions = .default) {
self.displayOptions = displayOptions
}
var isLoading: Bool {
loading.isLoading
}
var sections: [SectionContent] {
let now = Date()
let items = TodayFeature.groupedSectionItems(
from: TodayFeature.displayedTodos(
todos: todos,
displayOptions: displayOptions
),
now: now
)
switch selectedSectionScope {
case .all:
return
TodayFeature.makeSection(
category: .focused,
title: String(localized: "today_section_focused"),
items: items.focused
)
+ TodayFeature.makeSection(
category: .overdue,
title: String(localized: "today_section_overdue"),
items: items.overdue
)
+ TodayFeature.makeSection(
category: .dueSoon,
title: String.localizedStringWithFormat(
String(localized: "today_section_due_soon_format"),
Int64(TodayFeature.upcomingWindowDays)
),
items: items.dueSoon
)
+ TodayFeature.makeSection(
category: .later,
title: String(localized: "today_section_later"),
items: items.later
)
+ TodayFeature.makeSection(
category: .unscheduled,
title: String(localized: "today_section_unscheduled"),
items: items.unscheduled
)
case .focused:
return TodayFeature.makeSection(
category: .focused,
title: String(localized: "today_section_focused"),
items: items.focused
)
case .overdue:
return TodayFeature.makeSection(
category: .overdue,
title: String(localized: "today_section_overdue"),
items: items.overdue
)
case .dueSoon:
return TodayFeature.makeSection(
category: .dueSoon,
title: String.localizedStringWithFormat(
String(localized: "today_section_due_soon_format"),
Int64(TodayFeature.upcomingWindowDays)
),
items: items.dueSoon
)
}
}
var summaryCounts: [SectionScope: Int] {
let now = Date()
return Dictionary(
uniqueKeysWithValues: SectionScope.allCases.map { scope in
(
scope,
TodayFeature.summaryValue(
for: scope,
todos: todos,
displayOptions: displayOptions,
now: now
)
)
}
)
}
}
enum Action: BindableAction, Equatable {
case alert(PresentationAction<Never>)
case binding(BindingAction<State>)
case refresh
case fetchData
case setSectionScope(SectionScope)
case resetDisplayOptions
case completeTodo(TodayTodoItem)
case togglePinned(TodayTodoItem)
case store(StoreAction)
case loading(LoadingFeature.Action)
enum StoreAction: Equatable {
case setAlert
case setTodos([TodayTodoItem])
case updateTodo(TodayTodoItem)
case removeTodo(String)
}
}
@Dependency(\.todayFetchTodosUseCase) var fetchTodosUseCase
@Dependency(\.fetchTodoByIdUseCase) var fetchTodoByIdUseCase
@Dependency(\.upsertTodoUseCase) var upsertTodoUseCase
@Dependency(\.updateTodayDisplayOptionsUseCase) var updateTodayDisplayOptionsUseCase
@Dependency(\.trackAnalyticsEventUseCase) var trackAnalyticsEventUseCase
static let pageSize = 20
static let upcomingWindowDays = 7
var body: some ReducerOf<Self> {
Scope(state: \.loading, action: \.loading) {
LoadingFeature()
}
BindingReducer()
Reduce { state, action in
switch action {
case .alert:
break
case .binding(\.displayOptions.dueDateVisibility),
.binding(\.displayOptions.focusVisibility),
.binding(\.displayOptions.isFocusedOnly):
return updateDisplayOptionsEffect(state.displayOptions)
case .binding:
break
case .refresh:
return fetchTodosEffect(showsIndicator: false)
case .fetchData:
return fetchTodosEffect()
case .setSectionScope(let scope):
if state.selectedSectionScope == scope, scope != .all {
state.selectedSectionScope = .all
} else {
state.selectedSectionScope = scope
}
case .resetDisplayOptions:
state.displayOptions = .default
return updateDisplayOptionsEffect(state.displayOptions)
case .completeTodo(let item):
return completeTodoEffect(item)
case .togglePinned(let item):
return togglePinnedEffect(item)
case .store(.setAlert):
state.alert = Self.alertState()
case .store(.setTodos(let todos)):
state.todos = todos
case .store(.updateTodo(let item)):
if let index = state.todos.firstIndex(where: { $0.id == item.id }) {
state.todos[index] = item
} else {
state.todos.append(item)
}
case .store(.removeTodo(let todoId)):
state.todos.removeAll { $0.id == todoId }
case .loading:
break
}
return .none
}
.ifLet(\.$alert, action: \.alert)
}
}
extension DependencyValues {
var todayFetchTodosUseCase: FetchTodosUseCase {
get { self[TodayFetchTodosUseCaseKey.self] }
set { self[TodayFetchTodosUseCaseKey.self] = newValue }
}
var updateTodayDisplayOptionsUseCase: UpdateTodayDisplayOptionsUseCase {
get { self[UpdateTodayDisplayOptionsUseCaseKey.self] }
set { self[UpdateTodayDisplayOptionsUseCaseKey.self] = newValue }
}
}
private enum TodayFetchTodosUseCaseKey: DependencyKey {
static var liveValue: FetchTodosUseCase {
preconditionFailure("FetchTodosUseCase must be provided.")
}
static var testValue: FetchTodosUseCase {
liveValue
}
}
private enum UpdateTodayDisplayOptionsUseCaseKey: DependencyKey {
static var liveValue: UpdateTodayDisplayOptionsUseCase {
preconditionFailure("UpdateTodayDisplayOptionsUseCase must be provided.")
}
static var testValue: UpdateTodayDisplayOptionsUseCase {
liveValue
}
}
private extension TodayFeature {
func fetchTodosEffect(showsIndicator: Bool = true) -> Effect<Action> {
.run { [fetchTodosUseCase] send in
if showsIndicator {
await send(.loading(.begin(target: .default, mode: .delayed)))
}
do {
async let todosWithDueDatePage = fetchTodosUseCase.execute(
TodoQuery(
completionFilter: .incomplete,
dueDateFilter: .withDueDate,
sortTarget: .dueDate,
sortOrder: .oldest,
pageSize: Self.pageSize,
fetchAllPages: true
),
cursor: nil
)
async let todosWithoutDueDatePage = fetchTodosUseCase.execute(
TodoQuery(
completionFilter: .incomplete,
dueDateFilter: .withoutDueDate,
sortTarget: .updatedAt,
sortOrder: .latest,
pageSize: Self.pageSize,
fetchAllPages: true
),
cursor: nil
)
let todosWithDueDate = try await todosWithDueDatePage.items.compactMap(TodayTodoItem.init(from:))
let todosWithoutDueDate = try await todosWithoutDueDatePage.items.compactMap(TodayTodoItem.init(from:))
await send(.store(.setTodos(todosWithDueDate + todosWithoutDueDate)))
if showsIndicator {
await send(.loading(.end(target: .default, mode: .delayed)))
}
} catch {
if showsIndicator {
await send(.loading(.end(target: .default, mode: .delayed)))
}
await send(.store(.setAlert))
}
}
}
func updateDisplayOptionsEffect(_ options: TodayDisplayOptions) -> Effect<Action> {
.run { [updateTodayDisplayOptionsUseCase] _ in
updateTodayDisplayOptionsUseCase.execute(options)
}
}
func completeTodoEffect(_ item: TodayTodoItem) -> Effect<Action> {
.run { [fetchTodoByIdUseCase, upsertTodoUseCase, trackAnalyticsEventUseCase] send in
await send(.loading(.begin(target: .default, mode: .delayed)))
do {
var todo = try await fetchTodoByIdUseCase.execute(item.id)
let now = Date()
todo.isCompleted = true
todo.completedAt = now
todo.updatedAt = now
try await upsertTodoUseCase.execute(todo)
trackAnalyticsEventUseCase.execute(.todoComplete)
await send(.store(.removeTodo(todo.id)))
await send(.loading(.end(target: .default, mode: .delayed)))
} catch {
await send(.loading(.end(target: .default, mode: .delayed)))
await send(.store(.setAlert))
}
}
}
func togglePinnedEffect(_ item: TodayTodoItem) -> Effect<Action> {
.run { [fetchTodoByIdUseCase, upsertTodoUseCase] send in
await send(.loading(.begin(target: .default, mode: .delayed)))
do {
var todo = try await fetchTodoByIdUseCase.execute(item.id)
todo.isPinned.toggle()
todo.updatedAt = Date()
try await upsertTodoUseCase.execute(todo)
guard let todayTodoItem = TodayTodoItem(from: todo) else {
await send(.loading(.end(target: .default, mode: .delayed)))
await send(.store(.setAlert))
return
}
await send(.store(.updateTodo(todayTodoItem)))
await send(.loading(.end(target: .default, mode: .delayed)))
} catch {
await send(.loading(.end(target: .default, mode: .delayed)))
await send(.store(.setAlert))
}
}
}
static func alertState() -> AlertState<Never> {
AlertState {
TextState(String(localized: "common_error_title"))
} actions: {
ButtonState(role: .cancel) {
TextState(String(localized: "common_close"))
}
} message: {
TextState(String(localized: "common_error_message"))
}
}
}