-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathReaderSelectInterestsViewController.swift
More file actions
566 lines (471 loc) · 19.1 KB
/
Copy pathReaderSelectInterestsViewController.swift
File metadata and controls
566 lines (471 loc) · 19.1 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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import UIKit
import AutomatticTracks
import WordPressData
import WordPressUI
import WordPressKit
protocol ReaderDiscoverFlowDelegate: AnyObject {
func didCompleteReaderDiscoverFlow()
}
struct ReaderSelectInterestsConfiguration {
let title: String
let subtitle: String?
let buttonTitle: (enabled: String, disabled: String)?
let loading: String
let showsSkipButton: Bool
init(
title: String,
subtitle: String?,
buttonTitle: (enabled: String, disabled: String)?,
loading: String,
showsSkipButton: Bool = false
) {
self.title = title
self.subtitle = subtitle
self.buttonTitle = buttonTitle
self.loading = loading
self.showsSkipButton = showsSkipButton
}
}
class ReaderSelectInterestsViewController: UIViewController {
private struct Constants {
static let reuseIdentifier = ReaderInterestsCollectionViewCell.classNameWithoutNamespaces()
static let defaultCellIdentifier = "DefaultCell"
static let interestsLabelMargin: CGFloat = 12
static let cellCornerRadius: CGFloat = 5
static let cellSpacing: CGFloat = 6
static let cellHeight: CGFloat = 36
static let animationDuration: TimeInterval = 0.2
static let isCentered: Bool = true
}
private struct Strings {
static let noSearchResultsTitle = NSLocalizedString(
"reader.select.tags.no.results.follow.title",
value: "No new tags to follow",
comment: "Message shown when there are no new topics to follow."
)
static let tryAgainNoticeTitle = NSLocalizedString(
"Something went wrong. Please try again.",
comment: "Error message shown when the app fails to save user selected interests"
)
static let tryAgainButtonTitle = NSLocalizedString(
"Try Again",
comment: "Try to load the list of interests again."
)
static let skipButtonTitle = NSLocalizedString(
"reader.select.tags.skip",
value: "Skip",
comment: "Button title. Lets the user continue without selecting any tags."
)
}
// MARK: - IBOutlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var buttonContainerView: UIView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var contentContainerView: UIStackView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var loadingLabel: UILabel!
@IBOutlet weak var loadingView: UIStackView!
@IBOutlet weak var bottomSpaceHeightConstraint: NSLayoutConstraint!
// MARK: - Data
private lazy var dataSource: ReaderInterestsDataSource = {
ReaderInterestsDataSource(topics: topics)
}()
private let coordinator = ReaderSelectInterestsCoordinator()
private let noResultsViewController = NoResultsViewController.controller()
private let topics: [ReaderTagTopic]
private let configuration: ReaderSelectInterestsConfiguration
var didSaveInterests: (([RemoteReaderInterest]) -> Void)? = nil
weak var readerDiscoverFlowDelegate: ReaderDiscoverFlowDelegate?
// MARK: - Init
init(configuration: ReaderSelectInterestsConfiguration = .default, topics: [ReaderTagTopic] = []) {
self.configuration = configuration
self.topics = topics
super.init(nibName: "ReaderSelectInterestsViewController", bundle: .keystone)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
dataSource.delegate = self
configureNavigationBar()
configureI18N()
configureCollectionView()
configureNoResultsViewController()
configureSkipButton()
applyStyles()
updateNextButtonState()
refreshData()
// If the view is being presented overCurrentContext take into account tab bar height
if modalPresentationStyle == .overCurrentContext {
bottomSpaceHeightConstraint.constant =
presentingViewController?.tabBarController?.tabBar.bounds.size.height ?? 0
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetSelectedInterests()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
WPAnalytics.trackReader(.selectInterestsShown)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If this view was presented over current context and it's disappearing
// it means that the user switched tabs. Keeping it in the view hierarchy cause
// weird black screens, so we dismiss it to avoid that.
if modalPresentationStyle == .overCurrentContext {
dismiss(animated: false)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard let layout = collectionView.collectionViewLayout as? ReaderInterestsCollectionViewFlowLayout else {
return
}
layout.invalidateLayout()
}
// MARK: - IBAction's
@IBAction func nextButtonTapped(_ sender: Any) {
saveSelectedInterests()
}
// MARK: - Private: Configuration
private func configureCollectionView() {
collectionView.register(
ReaderInterestsCollectionViewCell.defaultNib,
forCellWithReuseIdentifier: Constants.reuseIdentifier
)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: Constants.defaultCellIdentifier)
guard let layout = collectionView.collectionViewLayout as? ReaderInterestsCollectionViewFlowLayout else {
return
}
layout.itemSpacing = Constants.cellSpacing
layout.cellHeight = Constants.cellHeight
layout.isCentered = Constants.isCentered
}
private func configureNoResultsViewController() {
noResultsViewController.delegate = self
}
/// Adds a "Skip" button below the primary button, letting the user continue
/// without selecting any tags. Only used by the Discover flow.
private func configureSkipButton() {
guard configuration.showsSkipButton else {
return
}
let button = UIButton(type: .system)
button.setTitle(Strings.skipButtonTitle, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(skipButtonTapped(_:)), for: .touchUpInside)
ReaderInterestsStyleGuide.applySkipButtonStyle(button: button)
if let index = contentContainerView.arrangedSubviews.firstIndex(of: buttonContainerView) {
contentContainerView.insertArrangedSubview(button, at: index + 1)
} else {
contentContainerView.addArrangedSubview(button)
}
}
@objc private func skipButtonTapped(_ sender: UIButton) {
// Disable on first tap so a fast double-tap can't complete the flow
// (re-triggering dismiss / stream refresh) twice, matching the primary
// button, which disables itself before dismissing.
sender.isEnabled = false
WPAnalytics.trackReader(.selectInterestsSkipped)
didSaveInterests?([])
// Keep skip symmetric with the save-success path so a flow that both
// shows the Skip button and sets `readerDiscoverFlowDelegate` still
// completes. The only current Skip flow (Discover) leaves this nil.
readerDiscoverFlowDelegate?.didCompleteReaderDiscoverFlow()
}
private func applyStyles() {
let styleGuide = ReaderInterestsStyleGuide.self
styleGuide.applyTitleLabelStyles(label: titleLabel)
styleGuide.applySubtitleLabelStyles(label: subTitleLabel)
styleGuide.applyNextButtonStyle(button: nextButton)
buttonContainerView.backgroundColor = ReaderInterestsStyleGuide.buttonContainerViewBackgroundColor
styleGuide.applyLoadingLabelStyles(label: loadingLabel)
styleGuide.applyActivityIndicatorStyles(indicator: activityIndicatorView)
}
private func configureNavigationBar() {
guard isModal() else {
return
}
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(saveSelectedInterests)
)
}
private func configureI18N() {
titleLabel.text = configuration.title
titleLabel.isHidden = false
if let subtitle = configuration.subtitle {
subTitleLabel.text = subtitle
subTitleLabel.isHidden = false
} else {
subTitleLabel.isHidden = true
}
if let buttonTitle = configuration.buttonTitle {
nextButton.setTitle(buttonTitle.enabled, for: .normal)
nextButton.setTitle(buttonTitle.disabled, for: .disabled)
buttonContainerView.isHidden = false
} else {
buttonContainerView.isHidden = true
}
loadingLabel.text = configuration.loading
}
// MARK: - Private: Data
private func refreshData() {
startLoading(hideLabel: true)
dataSource.reload()
}
private func resetSelectedInterests() {
dataSource.reset()
refreshData()
}
private func reloadData() {
collectionView.reloadData()
stopLoading()
}
@objc private func saveSelectedInterests() {
guard !dataSource.selectedInterests.isEmpty else {
self.didSaveInterests?([])
return
}
navigationItem.rightBarButtonItem?.isEnabled = false
startLoading()
announceLoadingTopics()
let selectedInterests = dataSource.selectedInterests.map { $0.interest }
coordinator.saveInterests(interests: selectedInterests) { [weak self] success in
guard success else {
self?.stopLoading()
self?.displayNotice(title: Strings.tryAgainNoticeTitle)
return
}
self?.trackEvents(with: selectedInterests)
self?.stopLoading()
self?.didSaveInterests?(selectedInterests)
self?.readerDiscoverFlowDelegate?.didCompleteReaderDiscoverFlow()
}
}
private func trackEvents(with selectedInterests: [RemoteReaderInterest]) {
selectedInterests.forEach {
WPAnalytics.track(.readerTagFollowed, withProperties: ["tag": $0.slug, "source": "discover"])
}
WPAnalytics.trackReader(.selectInterestsPicked, properties: ["quantity": selectedInterests.count])
}
// MARK: - Private: UI Helpers
private func updateNextButtonState() {
nextButton.isEnabled = !dataSource.selectedInterests.isEmpty
}
private func startLoading(hideLabel: Bool = false) {
loadingLabel.isHidden = hideLabel
loadingView.alpha = 0
loadingView.isHidden = false
activityIndicatorView.startAnimating()
contentContainerView.alpha = 0
loadingView.alpha = 1
}
private func stopLoading() {
activityIndicatorView.stopAnimating()
UIView.animate(
withDuration: Constants.animationDuration,
animations: {
self.contentContainerView.alpha = 1
self.loadingView.alpha = 0
}
) { _ in
self.loadingView.isHidden = true
}
}
private func announceLoadingTopics() {
UIAccessibility.post(notification: .screenChanged, argument: self.loadingLabel)
}
}
// MARK: - UICollectionViewDataSource
extension ReaderSelectInterestsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
dataSource.count
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
guard
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: Constants.reuseIdentifier,
for: indexPath
) as? ReaderInterestsCollectionViewCell
else {
fatalError("Expected a ReaderInterestsCollectionViewCell for identifier: \(Constants.reuseIdentifier)")
}
guard let interest = dataSource.interest(for: indexPath.row) else {
CrashLogging.main.logMessage(
"ReaderSelectInterestsViewController: Requested for data at invalid row",
properties: ["row": indexPath.row],
level: .warning
)
return collectionView.dequeueReusableCell(
withReuseIdentifier: Constants.defaultCellIdentifier,
for: indexPath
)
}
ReaderInterestsStyleGuide.applyCellLabelStyle(
label: cell.label,
isSelected: interest.isSelected
)
cell.layer.borderWidth = interest.isSelected ? 0 : 1
cell.layer.borderColor = UIColor.separator.cgColor
cell.layer.cornerRadius = Constants.cellCornerRadius
cell.label.text = interest.title
cell.label.accessibilityTraits = interest.isSelected ? [.selected, .button] : .button
return cell
}
}
// MARK: - UICollectionViewDelegate
extension ReaderSelectInterestsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let interest = dataSource.interest(for: indexPath.row) else {
return
}
interest.toggleSelected()
updateNextButtonState()
UIView.animate(withDuration: 0) {
collectionView.reloadItems(at: [indexPath])
}
}
}
// MARK: - UICollectionViewFlowLayout
extension ReaderSelectInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
guard let interest = dataSource.interest(for: indexPath.row) else {
return .zero
}
let attributes: [NSAttributedString.Key: Any] = [
.font: ReaderInterestsStyleGuide.cellLabelTitleFont
]
let title: NSString = interest.title as NSString
var size = title.size(withAttributes: attributes)
size.width += (Constants.interestsLabelMargin * 2)
return size
}
}
// MARK: - ReaderInterestsDataDelegate
extension ReaderSelectInterestsViewController: ReaderInterestsDataDelegate {
func readerInterestsDidUpdate(_ dataSource: ReaderInterestsDataSource) {
// swiftlint:disable:next empty_count
if dataSource.count != 0 {
hideLoadingView()
reloadData()
} else if !topics.isEmpty {
displayLoadingViewWithNoSearchResults(title: Strings.noSearchResultsTitle)
} else {
displayLoadingViewWithWebAction(title: "")
}
}
}
// MARK: - NoResultsViewController
extension ReaderSelectInterestsViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
refreshData()
}
}
extension ReaderSelectInterestsViewController {
func displayLoadingViewWithNoSearchResults(title: String) {
noResultsViewController.configureForNoSearchResults(title: title)
showLoadingView()
}
func displayLoadingViewWithWebAction(title: String, accessoryView: UIView? = nil) {
noResultsViewController.configure(
title: title,
buttonTitle: Strings.tryAgainButtonTitle,
accessoryView: accessoryView
)
showLoadingView()
}
func showLoadingView() {
hideLoadingView()
addChild(noResultsViewController)
view.addSubview(withFadeAnimation: noResultsViewController.view)
noResultsViewController.didMove(toParent: self)
}
func hideLoadingView() {
noResultsViewController.removeFromView()
}
}
extension ReaderSelectInterestsConfiguration {
static let `default` = ReaderSelectInterestsConfiguration(
title: NSLocalizedString(
"reader.select.interests.follow.title",
value: "Follow tags",
comment: "Screen title. Reader select interests title label text."
),
subtitle: nil,
buttonTitle: nil,
loading: NSLocalizedString(
"reader.select.interests.following",
value: "Following new tags...",
comment: "Label displayed to the user while loading their selected interests"
)
)
/// Configuration for the "Discover" screen.
static var discover: ReaderSelectInterestsConfiguration {
let title = NSLocalizedString(
"reader.select.tags.title",
value: "Discover and follow blogs you love",
comment: "Reader select interests title label text"
)
let subtitle = NSLocalizedString(
"reader.select.tags.subtitle",
value: "Choose your tags",
comment: "Reader select interests subtitle label text"
)
let buttonTitleEnabled = NSLocalizedString(
"reader.select.tags.done",
value: "Done",
comment: "Reader select interests next button enabled title text"
)
let buttonTitleDisabled = NSLocalizedString(
"reader.select.tags.continue",
value: "Select a few to continue",
comment: "Reader select interests next button disabled title text"
)
let loading = NSLocalizedString(
"reader.select.tags.loading",
value: "Finding blogs and stories you’ll love...",
comment: "Label displayed to the user while loading their selected interests"
)
return ReaderSelectInterestsConfiguration(
title: title,
subtitle: subtitle,
buttonTitle: (enabled: buttonTitleEnabled, disabled: buttonTitleDisabled),
loading: loading,
showsSkipButton: true
)
}
}
extension ReaderSelectInterestsViewController {
static func show(
from presentingViewController: UIViewController,
viewContext: NSManagedObjectContext = ContextManager.shared.mainContext
) {
let tags = viewContext.allObjects(
ofType: ReaderTagTopic.self,
matching: ReaderSidebarTagsSection.predicate,
sortedBy: [NSSortDescriptor(SortDescriptor<ReaderTagTopic>(\.title, order: .forward))]
)
let interestsVC = ReaderSelectInterestsViewController(topics: tags)
interestsVC.didSaveInterests = { [weak interestsVC] _ in
interestsVC?.presentingViewController?.dismiss(animated: true)
}
let navigationVC = UINavigationController(rootViewController: interestsVC)
navigationVC.modalPresentationStyle = .formSheet
presentingViewController.present(navigationVC, animated: true, completion: nil)
}
}