-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
DiscoveryPageViewController.swift
512 lines (418 loc) · 16.7 KB
/
DiscoveryPageViewController.swift
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import KsApi
import Library
import Prelude
import UIKit
protocol DiscoveryPageViewControllerDelegate: AnyObject {
func discoverPageViewController(
_ viewController: DiscoveryPageViewController,
contentOffsetDidChangeTo offset: CGPoint
)
}
internal final class DiscoveryPageViewController: UITableViewController {
fileprivate let viewModel: DiscoveryPageViewModelType = DiscoveryPageViewModel()
fileprivate let shareViewModel: ShareViewModelType = ShareViewModel()
// MARK: - Properties
private var configUpdatedObserver: Any?
private var currentEnvironmentChangedObserver: Any?
fileprivate let dataSource = DiscoveryProjectsDataSource()
public weak var delegate: DiscoveryPageViewControllerDelegate?
fileprivate var emptyStatesController: EmptyStatesViewController?
private lazy var headerLabel = { UILabel(frame: .zero) }()
private var onboardingCompletedObserver: Any?
private var sessionEndedObserver: Any?
private var sessionStartedObserver: Any?
internal static func configuredWith(sort: DiscoveryParams.Sort) -> DiscoveryPageViewController {
let vc = Storyboard.DiscoveryPage.instantiate(DiscoveryPageViewController.self)
vc.viewModel.inputs.configureWith(sort: sort)
return vc
}
internal override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(nib: Nib.DiscoveryPostcardCell)
self.tableView.registerCellClass(PersonalizationCell.self)
self.tableView.registerCellClass(DiscoveryProjectCardCell.self)
self.tableView.dataSource = self.dataSource
let refreshControl = UIRefreshControl()
refreshControl.addTarget(
self,
action: #selector(self.pulledToRefresh),
for: .valueChanged
)
self.refreshControl = refreshControl
self.onboardingCompletedObserver = NotificationCenter.default
.addObserver(forName: .ksr_onboardingCompleted, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.onboardingCompleted()
}
self.sessionStartedObserver = NotificationCenter.default
.addObserver(forName: .ksr_sessionStarted, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.userSessionStarted()
}
self.sessionEndedObserver = NotificationCenter.default
.addObserver(forName: .ksr_sessionEnded, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.userSessionEnded()
}
self.currentEnvironmentChangedObserver = NotificationCenter.default
.addObserver(forName: .ksr_environmentChanged, object: nil, queue: nil, using: { [weak self] _ in
self?.viewModel.inputs.currentEnvironmentChanged(
environment:
AppEnvironment.current.apiService.serverConfig.environment
)
})
self.configUpdatedObserver = NotificationCenter.default
.addObserver(forName: .ksr_configUpdated, object: nil, queue: nil, using: { [weak self] _ in
self?.viewModel.inputs.configUpdated(config: AppEnvironment.current.config)
})
let emptyVC = EmptyStatesViewController.configuredWith(emptyState: nil)
self.emptyStatesController = emptyVC
emptyVC.delegate = self
self.addChild(emptyVC)
self.view.addSubview(emptyVC.view)
NSLayoutConstraint.activate([
emptyVC.view.topAnchor.constraint(equalTo: self.view.topAnchor),
emptyVC.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
emptyVC.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
emptyVC.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
])
emptyVC.didMove(toParent: self)
}
deinit {
[
self.sessionEndedObserver,
self.sessionStartedObserver,
self.currentEnvironmentChangedObserver,
self.configUpdatedObserver,
self.onboardingCompletedObserver
].forEach { $0.doIfSome(NotificationCenter.default.removeObserver) }
}
internal override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.viewWillAppear()
}
internal override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewModel.inputs.viewDidAppear()
}
internal override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.viewModel.inputs.viewDidDisappear(animated: animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.ksr_sizeHeaderFooterViewsToFit()
}
internal override func bindStyles() {
super.bindStyles()
_ = self.tableView
|> \.rowHeight .~ UITableView.automaticDimension
|> \.estimatedRowHeight .~ 200.0
_ = self.view
|> \.backgroundColor .~ discoveryPageBackgroundColor()
_ = self.headerLabel
|> headerLabelStyle
}
internal override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.projectsAreLoadingAnimated
.observeForUI()
.observeValues { [weak self] isLoading, animated in
DispatchQueue.main.async {
if isLoading {
UIView.perform(animated: true) {
self?.refreshControl?.beginRefreshing()
}
} else {
UIView.perform(animated: animated) {
self?.refreshControl?.endRefreshing()
}
}
}
}
self.viewModel.outputs.activitiesForSample
.observeForUI()
.observeValues { [weak self] activities in
self?.dataSource.load(activities: activities)
self?.tableView.reloadData()
}
self.viewModel.outputs.asyncReloadData
.observeForUI()
.observeValues { [weak self] in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
self.viewModel.outputs.goToActivityProject
.observeForControllerAction()
.observeValues { [weak self] in self?.goTo(project: $0, refTag: $1) }
self.viewModel.outputs.goToProjectPlaylist
.observeForControllerAction()
.observeValues { [weak self] in
self?.goTo(project: $0, initialPlaylist: $1, refTag: $2)
}
self.viewModel.outputs.goToProjectUpdate
.observeForControllerAction()
.observeValues { [weak self] project, update in self?.goTo(project: project, update: update) }
self.viewModel.outputs.projectsLoaded
.observeForUI()
.observeValues { [weak self] projects, params, variant in
self?.dataSource.load(projects: projects, params: params, projectCardVariant: variant)
self?.tableView.reloadData()
}
self.viewModel.outputs.showOnboarding
.observeForUI()
.observeValues { [weak self] in
self?.dataSource.show(onboarding: $0)
self?.tableView.reloadData()
}
self.viewModel.outputs.showPersonalization
.observeForUI()
.observeValues { [weak self] shouldShow in
self?.dataSource.showPersonalization(shouldShow)
self?.tableView.reloadData()
}
self.viewModel.outputs.dismissPersonalizationCell
.observeForUI()
.observeValues { [weak self] _ in
self?.dataSource.showPersonalization(false)
let section = DiscoveryProjectsDataSource.Section.personalization.rawValue
self?.tableView.beginUpdates()
self?.tableView.deleteRows(at: [IndexPath(row: 0, section: section)], with: .automatic)
self?.tableView.endUpdates()
}
self.viewModel.outputs.goToCuratedProjects
.observeForUI()
.observeValues { [weak self] categories in
let curatedProjectsVC = CuratedProjectsViewController.instantiate()
curatedProjectsVC.configure(with: categories, context: .discovery)
let isIpad = AppEnvironment.current.device.userInterfaceIdiom == .pad
let navController = NavigationController(rootViewController: curatedProjectsVC)
|> \.modalPresentationStyle .~ (isIpad ? .formSheet : .fullScreen)
self?.present(navController, animated: true)
}
self.viewModel.outputs.setScrollsToTop
.observeForUI()
.observeValues { [weak self] in
_ = self?.tableView ?|> UIScrollView.lens.scrollsToTop .~ $0
}
self.shareViewModel.outputs.showShareSheet
.observeForControllerAction()
.observeValues { [weak self] in self?.showShareSheet($0, shareContextView: $1) }
self.viewModel.outputs.showEmptyState
.observeForUI()
.observeValues { [weak self] emptyState in
self?.showEmptyState(emptyState)
}
self.viewModel.outputs.hideEmptyState
.observeForUI()
.observeValues { [weak self] in
self?.emptyStatesController?.view.alpha = 0
self?.emptyStatesController?.view.isHidden = true
if let discovery = self?.parent?.parent as? DiscoveryViewController {
discovery.setSortsEnabled(true)
}
}
self.viewModel.outputs.notifyDelegateContentOffsetChanged
.observeForUI()
.observeValues { [weak self] offset in
guard let self = self else { return }
self.delegate?.discoverPageViewController(self, contentOffsetDidChangeTo: offset)
}
self.viewModel.outputs.goToLoginSignup
.observeForControllerAction()
.observeValues { [weak self] intent in
let loginTout = LoginToutViewController.configuredWith(loginIntent: intent)
let isIpad = AppEnvironment.current.device.userInterfaceIdiom == .pad
let nav = UINavigationController(rootViewController: loginTout)
|> \.modalPresentationStyle .~ (isIpad ? .formSheet : .fullScreen)
self?.present(nav, animated: true, completion: nil)
}
self.viewModel.outputs.contentInset
.observeForUI()
.observeValues { [weak self] inset in
guard let self = self else { return }
_ = self.tableView
|> \.contentInset .~ inset
}
}
internal override func tableView(
_: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath
) {
if let cell = cell as? DiscoveryPostcardCell {
cell.delegate = self
} else if let cell = cell as? ActivitySampleBackingCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? ActivitySampleFollowCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? ActivitySampleProjectCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? DiscoveryOnboardingCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? PersonalizationCell {
cell.delegate = self
} else if let cell = cell as? DiscoveryProjectCardCell {
cell.delegate = self
cell.layoutIfNeeded()
}
self.viewModel.inputs.willDisplayRow(
self.dataSource.itemIndexAt(indexPath),
outOf: self.dataSource.numberOfItems()
)
}
internal override func tableView(
_: UITableView,
didSelectRowAt indexPath: IndexPath
) {
if let project = self.dataSource.projectAtIndexPath(indexPath) {
self.viewModel.inputs.tapped(project: project)
} else if let activity = self.dataSource.activityAtIndexPath(indexPath) {
self.viewModel.inputs.tapped(activity: activity)
}
}
// MARK: - Functions
fileprivate func showShareSheet(_ controller: UIActivityViewController, shareContextView: UIView?) {
if UIDevice.current.userInterfaceIdiom == .pad {
controller.modalPresentationStyle = .popover
let popover = controller.popoverPresentationController
popover?.sourceView = shareContextView
}
self.present(controller, animated: true, completion: nil)
}
fileprivate func goTo(project: Project, refTag: RefTag) {
let projectParam = Either<Project, Param>(left: project)
let vc = ProjectPageViewController.configuredWith(
projectOrParam: projectParam,
refTag: refTag
)
let nav = NavigationController(rootViewController: vc)
nav.modalPresentationStyle = self.traitCollection.userInterfaceIdiom == .pad ? .fullScreen : .formSheet
self.present(nav, animated: true, completion: nil)
}
fileprivate func goTo(project: Project, initialPlaylist _: [Project], refTag: RefTag) {
let projectParam = Either<Project, Param>(left: project)
let vc = ProjectPageViewController.configuredWith(
projectOrParam: projectParam,
refTag: refTag
)
let nav = NavigationController(rootViewController: vc)
nav.modalPresentationStyle = self.traitCollection.userInterfaceIdiom == .pad ? .fullScreen : .formSheet
self.present(nav, animated: true, completion: nil)
}
fileprivate func goTo(project: Project, update: Update) {
let vc = UpdateViewController.configuredWith(project: project, update: update, context: .activitySample)
self.navigationController?.pushViewController(vc, animated: true)
}
fileprivate func showEmptyState(_ emptyState: EmptyState) {
guard let emptyVC = self.emptyStatesController else { return }
emptyVC.setEmptyState(emptyState)
emptyVC.view.isHidden = false
self.view.bringSubviewToFront(emptyVC.view)
UIView.animate(
withDuration: 0.3,
animations: {
self.emptyStatesController?.view.alpha = 1.0
}, completion: nil
)
if let discovery = self.parent?.parent as? DiscoveryViewController {
discovery.setSortsEnabled(false)
}
}
// MARK: - Accessors
internal func change(filter: DiscoveryParams) {
self.viewModel.inputs.selectedFilter(filter)
}
// MARK: - Actions
@objc private func pulledToRefresh() {
self.viewModel.inputs.pulledToRefresh()
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.viewModel.inputs.scrollViewDidScroll(toContentOffset: scrollView.contentOffset)
}
}
extension DiscoveryPageViewController: ActivitySampleBackingCellDelegate, ActivitySampleFollowCellDelegate,
ActivitySampleProjectCellDelegate {
internal func goToActivity() {
guard let root = self.tabBarController as? RootTabBarViewController else { return }
root.switchToActivities()
}
}
// MARK: - DiscoveryOnboardingCellDelegate
extension DiscoveryPageViewController: DiscoveryOnboardingCellDelegate {
internal func discoveryOnboardingTappedSignUpLoginButton() {
self.viewModel.inputs.signupLoginButtonTapped()
}
}
// MARK: - PersonalizationCellDelegate
extension DiscoveryPageViewController: PersonalizationCellDelegate {
func personalizationCellTapped(_: PersonalizationCell) {
self.viewModel.inputs.personalizationCellTapped()
}
func personalizationCellDidTapDismiss(_: PersonalizationCell) {
self.viewModel.inputs.personalizationCellDismissTapped()
}
}
// MARK: - EmptyStatesViewControllerDelegate
extension DiscoveryPageViewController: EmptyStatesViewControllerDelegate {
func emptyStatesViewController(
_: EmptyStatesViewController,
goToDiscoveryWithParams params: DiscoveryParams?
) {
self.view.window?.rootViewController
.flatMap { $0 as? RootTabBarViewController }
.doIfSome { $0.switchToDiscovery(params: params) }
}
func emptyStatesViewControllerGoToFriends() {
let vc = FindFriendsViewController.configuredWith(source: .discovery)
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension DiscoveryPageViewController: DiscoveryPostcardCellDelegate {
internal func discoveryPostcard(
cell _: DiscoveryPostcardCell, tappedShare context: ShareContext,
fromSourceView: UIView
) {
self.shareViewModel.inputs.configureWith(shareContext: context, shareContextView: fromSourceView)
self.shareViewModel.inputs.shareButtonTapped()
}
internal func discoveryPostcardCellProjectSaveAlert() {
let alertController = UIAlertController(
title: Strings.Project_saved(),
message: Strings.Well_remind_you_forty_eight_hours_before_this_project_ends(),
preferredStyle: .alert
)
alertController.addAction(
UIAlertAction(
title: Strings.Got_it(),
style: .cancel,
handler: nil
)
)
self.present(alertController, animated: true, completion: nil)
}
internal func discoveryPostcardCellGoToLoginTout() {
let vc = LoginToutViewController.configuredWith(loginIntent: .starProject)
let isIpad = AppEnvironment.current.device.userInterfaceIdiom == .pad
let nav = UINavigationController(rootViewController: vc)
|> \.modalPresentationStyle .~ (isIpad ? .formSheet : .fullScreen)
self.present(nav, animated: true, completion: nil)
}
}
private extension UIView {
static func perform(animated: Bool, _ closure: () -> Void) {
if animated {
closure()
} else {
UIView.performWithoutAnimation { closure() }
}
}
}
// MARK: - Styles
private let headerLabelStyle: LabelStyle = { label in
label
|> \.textColor .~ UIColor.ksr_trust_700
|> \.font .~ UIFont.ksr_subhead().bolded
|> \.lineBreakMode .~ .byWordWrapping
|> \.numberOfLines .~ 0
|> \.textAlignment .~ .center
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}