-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushNotificationListViewModel.swift
More file actions
415 lines (381 loc) · 14.7 KB
/
PushNotificationListViewModel.swift
File metadata and controls
415 lines (381 loc) · 14.7 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
//
// PushNotificationListViewModel.swift
// DevLog
//
// Created by 최윤진 on 11/22/25.
//
import Foundation
import Combine
@Observable
final class PushNotificationListViewModel: Store {
struct State: Equatable {
var notifications: [PushNotificationItem] = []
var showAlert: Bool = false
var showToast: Bool = false
var alertTitle: String = ""
var alertMessage: String = ""
var toastMessage: String = ""
var isLoading: Bool = false
var hasMore: Bool = false
var nextCursor: PushNotificationCursor?
var query: PushNotificationQuery
var selectedTodoId: TodoIdItem?
}
enum Action {
case fetchNotifications
case loadNextPage
case deleteNotification(PushNotificationItem)
case toggleRead(PushNotificationItem)
case undoDelete
case setAlert(isPresented: Bool)
case setToast(isPresented: Bool)
case setLoading(Bool)
case appendNotifications([PushNotificationItem], nextCursor: PushNotificationCursor?)
case resetPagination
case setHasMore(Bool)
case syncNotifications([PushNotificationItem], nextCursor: PushNotificationCursor?, hasMore: Bool)
case restoreNotification(PushNotificationItem, Int)
case toggleSortOption
case setTimeFilter(PushNotificationQuery.TimeFilter)
case toggleUnreadOnly
case resetFilters
case tapNotification(PushNotificationItem)
case setSelectedTodoId(TodoIdItem?)
}
enum SideEffect {
case fetchNotifications(PushNotificationQuery, cursor: PushNotificationCursor?)
case delete(PushNotificationItem, Int)
case undoDelete(String)
case toggleRead(String)
}
private(set) var state: State
private let fetchUseCase: FetchPushNotificationsUseCase
private let deleteUseCase: DeletePushNotificationUseCase
private let undoDeleteUseCase: UndoDeletePushNotificationUseCase
private let toggleReadUseCase: TogglePushNotificationReadUseCase
private let fetchQueryUseCase: FetchPushNotificationQueryUseCase
private let updateQueryUseCase: UpdatePushNotificationQueryUseCase
private let loadingState = LoadingState()
private var undoDeleteNotificationId: String?
private var cancellable: AnyCancellable?
init(
fetchUseCase: FetchPushNotificationsUseCase,
deleteUseCase: DeletePushNotificationUseCase,
undoDeleteUseCase: UndoDeletePushNotificationUseCase,
toggleReadUseCase: TogglePushNotificationReadUseCase,
fetchQueryUseCase: FetchPushNotificationQueryUseCase,
updateQueryUseCase: UpdatePushNotificationQueryUseCase
) {
self.fetchUseCase = fetchUseCase
self.deleteUseCase = deleteUseCase
self.undoDeleteUseCase = undoDeleteUseCase
self.toggleReadUseCase = toggleReadUseCase
self.fetchQueryUseCase = fetchQueryUseCase
self.updateQueryUseCase = updateQueryUseCase
self.state = State(
query: fetchQueryUseCase.execute()
)
}
var appliedFilterCount: Int {
var count = 0
if state.query.sortOrder != .latest { count += 1 }
if state.query.timeFilter != .none { count += 1 }
if state.query.unreadOnly { count += 1 }
return count
}
func reduce(with action: Action) -> [SideEffect] {
var state = self.state
var effects: [SideEffect] = []
switch action {
case .deleteNotification, .toggleRead, .undoDelete, .setAlert, .toggleSortOption,
.setTimeFilter, .toggleUnreadOnly, .resetFilters, .tapNotification:
effects = reduceByUser(action, state: &state)
case .fetchNotifications, .setToast, .setSelectedTodoId, .loadNextPage:
effects = reduceByView(action, state: &state)
case .setLoading, .appendNotifications, .resetPagination, .setHasMore,
.syncNotifications, .restoreNotification:
effects = reduceByRun(action, state: &state)
}
if self.state != state { self.state = state }
return effects
}
func run(_ effect: SideEffect) {
switch effect {
case .fetchNotifications(let query, let cursor):
if cursor == nil {
stopObservingNotifications()
}
beginLoading(.delayed)
Task {
do {
defer { endLoading(.delayed) }
let existingCount = cursor == nil ? 0 : self.state.notifications.count
let page = try await fetchUseCase.execute(query, cursor: cursor)
if cursor == nil { send(.resetPagination) }
send(
.appendNotifications(
page.items.map { PushNotificationItem(from: $0) },
nextCursor: page.nextCursor
)
)
let hasMore = page.items.count == query.pageSize && page.nextCursor != nil
send(.setHasMore(hasMore))
startObservingNotifications(
query: query,
limit: max(query.pageSize, existingCount + page.items.count)
)
} catch {
send(.setAlert(isPresented: true))
}
}
case .delete(let item, let index):
beginLoading(.delayed)
Task {
do {
defer { endLoading(.delayed) }
try await deleteUseCase.execute(item.id)
} catch {
send(.restoreNotification(item, index))
send(.setAlert(isPresented: true))
}
}
case .undoDelete(let notificationId):
beginLoading(.delayed)
Task {
// endLoading(.delayed)를 defer로 두지 않는 이유
// send(.fetchNotifications)가 같은 턴에서 beginLoading(.delayed)를 먼저 올린 뒤
// delayed 로딩을 내려야 같은 isLoading이 끊기지 않기 때문
do {
try await undoDeleteUseCase.execute(notificationId)
} catch {
send(.setAlert(isPresented: true))
}
send(.fetchNotifications)
endLoading(.delayed)
}
case .toggleRead(let todoId):
beginLoading(.delayed)
Task {
do {
defer { endLoading(.delayed) }
try await toggleReadUseCase.execute(todoId)
} catch {
send(.setAlert(isPresented: true))
}
}
}
}
}
// MARK: - Reduce Methods
private extension PushNotificationListViewModel {
func reduceByUser(_ action: Action, state: inout State) -> [SideEffect] {
switch action {
case .deleteNotification(let item):
if let index = state.notifications.firstIndex(where: { $0.id == item.id }) {
undoDeleteNotificationId = item.id
state.notifications.remove(at: index)
setToast(&state, isPresented: true)
return [.delete(item, index)]
}
return []
case .toggleRead(let item):
if let index = state.notifications.firstIndex(where: { $0.id == item.id }) {
state.notifications[index].isRead.toggle()
return [.toggleRead(item.todoId)]
}
case .undoDelete:
guard let undoDeleteNotificationId else { return [] }
self.undoDeleteNotificationId = nil
return [.undoDelete(undoDeleteNotificationId)]
case .setAlert(let isPresented):
setAlert(&state, isPresented: isPresented)
case .toggleSortOption:
state.query.sortOrder = state.query.sortOrder == .latest ? .oldest : .latest
updateQueryUseCase.execute(state.query)
state.nextCursor = nil
return [.fetchNotifications(state.query, cursor: nil)]
case .setTimeFilter(let filter):
state.query.timeFilter = filter
updateQueryUseCase.execute(state.query)
state.nextCursor = nil
return [.fetchNotifications(state.query, cursor: nil)]
case .toggleUnreadOnly:
state.query.unreadOnly.toggle()
updateQueryUseCase.execute(state.query)
state.nextCursor = nil
return [.fetchNotifications(state.query, cursor: nil)]
case .resetFilters:
state.query = .default
updateQueryUseCase.execute(state.query)
state.nextCursor = nil
return [.fetchNotifications(state.query, cursor: nil)]
case .tapNotification(let item):
state.selectedTodoId = TodoIdItem(id: item.todoId)
if let index = state.notifications.firstIndex(where: { $0.id == item.id }), !item.isRead {
state.notifications[index].isRead.toggle()
return [.toggleRead(item.todoId)]
}
default:
break
}
return []
}
func reduceByView(_ action: Action, state: inout State) -> [SideEffect] {
switch action {
case .fetchNotifications:
state.nextCursor = nil
return [.fetchNotifications(state.query, cursor: nil)]
case .loadNextPage:
guard state.hasMore, !state.isLoading else { return [] }
return [.fetchNotifications(state.query, cursor: state.nextCursor)]
case .setToast(let isPresented):
setToast(&state, isPresented: isPresented)
if !isPresented {
undoDeleteNotificationId = nil
}
case .setSelectedTodoId(let todoId):
state.selectedTodoId = todoId
default:
break
}
return []
}
func reduceByRun(_ action: Action, state: inout State) -> [SideEffect] {
switch action {
case .setLoading(let value):
state.isLoading = value
case .setHasMore(let value):
state.hasMore = value
case .resetPagination:
state.notifications = []
state.nextCursor = nil
case .appendNotifications(let notifications, let nextCursor):
state.notifications.append(contentsOf: notifications)
state.nextCursor = nextCursor
case .syncNotifications(let notifications, let nextCursor, let hasMore):
state.notifications = notifications
state.nextCursor = nextCursor
state.hasMore = hasMore
case .restoreNotification(let notification, let index):
if state.notifications.contains(where: { $0.id == notification.id }) { break }
if index <= state.notifications.count {
state.notifications.insert(notification, at: index)
} else {
state.notifications.append(notification)
}
if undoDeleteNotificationId == notification.id {
undoDeleteNotificationId = nil
}
default:
break
}
return []
}
}
private extension PushNotificationListViewModel {
func setAlert(
_ state: inout State,
isPresented: Bool
) {
state.alertTitle = String(localized: "common_error_title")
state.alertMessage = String(localized: "common_error_message")
state.showAlert = isPresented
}
func setToast(
_ state: inout State,
isPresented: Bool
) {
state.toastMessage = String(localized: "common_undo")
state.showToast = isPresented
}
func startObservingNotifications(
query: PushNotificationQuery,
limit: Int
) {
cancellable = try? fetchUseCase.observe(query, limit: limit)
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
guard let self else { return }
if case .failure = completion {
self.send(.setAlert(isPresented: true))
}
},
receiveValue: { [weak self] page in
guard let self else { return }
let items = page.items.map { PushNotificationItem(from: $0) }
let hasMore = items.count == max(query.pageSize, limit) && page.nextCursor != nil
self.send(.syncNotifications(items, nextCursor: page.nextCursor, hasMore: hasMore))
}
)
}
func stopObservingNotifications() {
cancellable?.cancel()
cancellable = nil
}
private func beginLoading(_ mode: LoadingState.Mode) {
loadingState.begin(mode: mode) { [weak self] isLoading in
self?.send(.setLoading(isLoading))
}
}
private func endLoading(_ mode: LoadingState.Mode) {
loadingState.end(mode: mode) { [weak self] isLoading in
self?.send(.setLoading(isLoading))
}
}
}
extension PushNotificationQuery.SortOrder {
var title: String {
switch self {
case .latest: return String(localized: "push_sort_latest")
case .oldest: return String(localized: "push_sort_oldest")
}
}
}
extension PushNotificationQuery.TimeFilter {
var id: String {
switch self {
case .none: return "none"
case .hours(let value): return "hours-\(value)"
case .days(let value): return "days-\(value)"
}
}
var title: String {
switch self {
case .none:
return String(localized: "push_timefilter_all")
case .hours(let value):
return String.localizedStringWithFormat(
String(localized: "push_timefilter_hours_format"),
Int64(value)
)
case .days(let value):
return String.localizedStringWithFormat(
String(localized: "push_timefilter_days_format"),
Int64(value)
)
}
}
static var availableOptions: [PushNotificationQuery.TimeFilter] {[
.none,
.hours(1),
.hours(6),
.hours(24),
.days(3),
.days(7)
]
}
init(id: String) {
if id == "none" {
self = .none
} else if id.hasPrefix("hours-") {
let value = Int(id.replacingOccurrences(of: "hours-", with: "")) ?? 0
self = value > 0 ? .hours(value) : .none
} else if id.hasPrefix("days-") {
let value = Int(id.replacingOccurrences(of: "days-", with: "")) ?? 0
self = value > 0 ? .days(value) : .none
} else {
self = .none
}
}
}