-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathIntroViewController.swift
465 lines (404 loc) · 18.6 KB
/
IntroViewController.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Shared
struct IntroUX {
static let Width = 375
static let Height = 667
static let MinimumFontScale: CGFloat = 0.5
static let PagerCenterOffsetFromScrollViewBottom = UIScreen.main.bounds.width <= 320 ? 20 : 30
static let StartBrowsingButtonColor = UIColor.Photon.Blue40
static let StartBrowsingButtonHeight = 56
static let SignInButtonColor = UIColor.Photon.Blue40
static let SignInButtonHeight = 60
static let PageControlHeight = 40
static let SignInButtonWidth = 290
static let CardTextWidth = UIScreen.main.bounds.width <= 320 ? 240 : 280
static let FadeDuration = 0.25
}
protocol IntroViewControllerDelegate: class {
func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool)
}
class IntroViewController: UIViewController {
weak var delegate: IntroViewControllerDelegate?
// We need to hang on to views so we can animate and change constraints as we scroll
var cardViews = [CardView]()
var cards = IntroCard.defaultCards()
lazy fileprivate var startBrowsingButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.clear
button.setTitle(Strings.StartBrowsingButtonTitle, for: UIControlState())
button.setTitleColor(IntroUX.StartBrowsingButtonColor, for: UIControlState())
button.addTarget(self, action: #selector(IntroViewController.startBrowsing), for: UIControlEvents.touchUpInside)
button.accessibilityIdentifier = "IntroViewController.startBrowsingButton"
button.isHidden = true
return button
}()
lazy var pageControl: UIPageControl = {
let pc = UIPageControl()
pc.pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.3)
pc.currentPageIndicatorTintColor = UIColor.black
pc.accessibilityIdentifier = "IntroViewController.pageControl"
pc.addTarget(self, action: #selector(IntroViewController.changePage), for: UIControlEvents.valueChanged)
return pc
}()
lazy fileprivate var scrollView: UIScrollView = {
let sc = UIScrollView()
sc.backgroundColor = UIColor.clear
sc.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel")
sc.delegate = self
sc.bounces = false
sc.isPagingEnabled = true
sc.showsHorizontalScrollIndicator = false
sc.accessibilityIdentifier = "IntroViewController.scrollView"
return sc
}()
var horizontalPadding: Int {
return self.view.frame.width <= 320 ? 20 : 50
}
var verticalPadding: CGFloat {
return self.view.frame.width <= 320 ? 10 : 38
}
lazy fileprivate var imageViewContainer: UIStackView = {
let sv = UIStackView()
sv.axis = .horizontal
sv.distribution = .fillEqually
return sv
}()
// Because a stackview cannot have a background color
fileprivate var imagesBackgroundView = UIView()
override func viewDidLoad() {
if AppConstants.MOZ_LP_INTRO {
syncViaLP()
}
assert(cards.count > 1, "Intro is empty. At least 2 cards are required")
view.backgroundColor = UIColor.white
// Add Views
view.addSubview(pageControl)
view.addSubview(scrollView)
view.addSubview(startBrowsingButton)
scrollView.addSubview(imagesBackgroundView)
scrollView.addSubview(imageViewContainer)
// Setup constraints
imagesBackgroundView.snp.makeConstraints { make in
make.edges.equalTo(imageViewContainer)
}
imageViewContainer.snp.makeConstraints { make in
make.top.equalTo(self.view)
make.height.equalTo(self.view.snp.width)
}
startBrowsingButton.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view.safeArea.bottom)
make.height.equalTo(IntroUX.StartBrowsingButtonHeight)
}
scrollView.snp.makeConstraints { make in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(startBrowsingButton.snp.top)
}
pageControl.snp.makeConstraints { make in
make.centerX.equalTo(self.scrollView)
make.centerY.equalTo(self.startBrowsingButton.snp.top).offset(-IntroUX.PagerCenterOffsetFromScrollViewBottom)
}
createSlides()
pageControl.addTarget(self, action: #selector(changePage), for: .valueChanged)
}
func syncViaLP() {
let startTime = Date.now()
LeanPlumClient.shared.introScreenVars?.onValueChanged({ [weak self] in
guard let newIntro = LeanPlumClient.shared.introScreenVars?.object(forKey: nil) as? [[String: Any]] else {
return
}
let decoder = JSONDecoder()
let newCards = newIntro.compactMap { (obj) -> IntroCard? in
guard let object = try? JSONSerialization.data(withJSONObject: obj, options: []) else {
return nil
}
let card = try? decoder.decode(IntroCard.self, from: object)
// Make sure the selector actually goes somewhere. Otherwise dont show that slide
if let selectorString = card?.buttonSelector, let wself = self {
return wself.responds(to: NSSelectorFromString(selectorString)) ? card : nil
} else {
return card
}
}
guard newCards != IntroCard.defaultCards(), newCards.count > 1 else {
return
}
// We need to still be on the first page otherwise the content will change underneath the user's finger
// We also need to let LP know this happened so we can track when a A/B test was not run
guard self?.pageControl.currentPage == 0 else {
let totalTime = Date.now() - startTime
LeanPlumClient.shared.track(event: .onboardingTestLoadedTooSlow, withParameters: ["Total time": "\(totalTime) ms" as AnyObject])
return
}
self?.cards = newCards
self?.createSlides()
self?.viewDidLayoutSubviews()
})
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = imageViewContainer.frame.size
}
func createSlides() {
// Make sure the scrollView has been setup before setting up the slides
guard scrollView.superview != nil else {
return
}
// Wipe any existing slides
imageViewContainer.subviews.forEach { $0.removeFromSuperview() }
cardViews.forEach { $0.removeFromSuperview() }
cardViews = cards.compactMap { addIntro(card: $0) }
pageControl.numberOfPages = cardViews.count
setupDynamicFonts()
if let firstCard = cardViews.first {
setActive(firstCard, forPage: 0)
}
imageViewContainer.layoutSubviews()
scrollView.contentSize = imageViewContainer.frame.size
// This should never happen but just in case make sure there is a way out
if cardViews.count == 1 {
startBrowsingButton.isHidden = false
}
}
func addIntro(card: IntroCard) -> CardView? {
guard let image = UIImage(named: card.imageName) else {
return nil
}
let imageView = UIImageView(image: image)
imageViewContainer.addArrangedSubview(imageView)
imageView.snp.makeConstraints { make in
make.height.equalTo(imageViewContainer.snp.height)
make.width.equalTo(imageViewContainer.snp.height)
}
let cardView = CardView(verticleSpacing: verticalPadding)
cardView.configureWith(card: card)
if let selectorString = card.buttonSelector, self.responds(to: NSSelectorFromString(selectorString)) {
cardView.button.addTarget(self, action: NSSelectorFromString(selectorString), for: .touchUpInside)
cardView.button.snp.makeConstraints { make in
make.width.equalTo(IntroUX.CardTextWidth)
make.height.equalTo(IntroUX.SignInButtonHeight)
}
}
self.view.addSubview(cardView)
cardView.snp.makeConstraints { make in
make.top.equalTo(self.imageViewContainer.snp.bottom).offset(verticalPadding)
make.bottom.equalTo(self.startBrowsingButton.snp.top)
make.left.right.equalTo(self.view).inset(horizontalPadding)
}
return cardView
}
@objc func startBrowsing() {
delegate?.introViewControllerDidFinish(self, requestToLogin: false)
LeanPlumClient.shared.track(event: .dismissedOnboarding, withParameters: ["dismissedOnSlide": pageControl.currentPage as AnyObject])
}
@objc func login() {
delegate?.introViewControllerDidFinish(self, requestToLogin: true)
LeanPlumClient.shared.track(event: .dismissedOnboardingShowLogin, withParameters: ["dismissedOnSlide": pageControl.currentPage as AnyObject])
}
@objc func changePage() {
let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true)
}
fileprivate func setActive(_ introView: UIView, forPage page: Int) {
guard introView.alpha != 1 else {
return
}
UIView.animate(withDuration: IntroUX.FadeDuration, animations: {
self.cardViews.forEach { $0.alpha = 0.0 }
introView.alpha = 1.0
self.pageControl.currentPage = page
}, completion: nil)
}
}
// UIViewController setup
extension IntroViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return .portrait
}
}
// Dynamic Font Helper
extension IntroViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil)
}
@objc func dynamicFontChanged(_ notification: Notification) {
guard notification.name == .DynamicFontChanged else { return }
setupDynamicFonts()
}
fileprivate func setupDynamicFonts() {
startBrowsingButton.titleLabel?.font = UIFont(name: "FiraSans-Regular", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
cardViews.forEach { cardView in
cardView.titleLabel.font = UIFont(name: "FiraSans-Medium", size: DynamicFontHelper.defaultHelper.IntroBigFontSize)
cardView.textLabel.font = UIFont(name: "FiraSans-UltraLight", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
}
}
}
extension IntroViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on.
// This especially affects sliding to the last or first cards.
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// Need to add this method so that tapping the pageControl will also change the card texts.
// scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on.
scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
if let cardView = cardViews[safe: page] {
setActive(cardView, forPage: page)
}
if page != 0 {
startBrowsingButton.isHidden = false
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let maximumHorizontalOffset = scrollView.frame.width
let currentHorizontalOffset = scrollView.contentOffset.x
var percentageOfScroll = currentHorizontalOffset / maximumHorizontalOffset
percentageOfScroll = percentageOfScroll > 1.0 ? 1.0 : percentageOfScroll
let whiteComponent = UIColor.white.components
let grayComponent = UIColor(rgb: 0xF2F2F2).components
let newRed = (1.0 - percentageOfScroll) * whiteComponent.red + percentageOfScroll * grayComponent.red
let newGreen = (1.0 - percentageOfScroll) * whiteComponent.green + percentageOfScroll * grayComponent.green
let newBlue = (1.0 - percentageOfScroll) * whiteComponent.blue + percentageOfScroll * grayComponent.blue
imagesBackgroundView.backgroundColor = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
// A cardView repersents the text for each page of the intro. It does not include the image.
class CardView: UIView {
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
return stackView
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.numberOfLines = 2
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = IntroUX.MinimumFontScale
titleLabel.textAlignment = .center
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
return titleLabel
}()
lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 5
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = IntroUX.MinimumFontScale
textLabel.textAlignment = .center
textLabel.lineBreakMode = .byTruncatingTail
textLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
return textLabel
}()
lazy var button: UIButton = {
let button = UIButton()
button.backgroundColor = IntroUX.SignInButtonColor
button.setTitle(Strings.SignInButtonTitle, for: [])
button.setTitleColor(.white, for: [])
button.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
button.clipsToBounds = true
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
init(verticleSpacing: CGFloat) {
super.init(frame: .zero)
stackView.spacing = verticleSpacing
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(textLabel)
addSubview(stackView)
stackView.snp.makeConstraints { make in
make.leading.trailing.top.equalTo(self)
make.bottom.lessThanOrEqualTo(self).offset(-IntroUX.PageControlHeight)
}
alpha = 0
}
func configureWith(card: IntroCard) {
titleLabel.text = card.title
textLabel.text = card.text
if let buttonText = card.buttonText, card.buttonSelector != nil {
button.setTitle(buttonText, for: .normal)
addSubview(button)
button.snp.makeConstraints { make in
make.bottom.centerX.equalTo(self)
}
// When there is a button reduce the spacing to make more room for text
stackView.spacing = stackView.spacing / 2
}
}
// Allows the scrollView to scroll while the CardView is in front
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let buttonSV = button.superview {
return convert(button.frame, from: buttonSV).contains(point)
}
return false
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct IntroCard: Codable {
let title: String
let text: String
let buttonText: String?
let buttonSelector: String? // Selector is a string that is synthisized into a Selector via NSSelectorFromString (for LeanPlum's sake)
let imageName: String
init(title: String, text: String, imageName: String, buttonText: String? = nil, buttonSelector: String? = nil) {
self.title = title
self.text = text
self.imageName = imageName
self.buttonText = buttonText
self.buttonSelector = buttonSelector
}
static func defaultCards() -> [IntroCard] {
let welcome = IntroCard(title: Strings.CardTitleWelcome, text: Strings.CardTextWelcome, imageName: "tour-Welcome")
let search = IntroCard(title: Strings.CardTitleSearch, text: Strings.CardTextSearch, imageName: "tour-Search")
let privateBrowsing = IntroCard(title: Strings.CardTitlePrivate, text: Strings.CardTextPrivate, imageName: "tour-Private")
let mailTo = IntroCard(title: Strings.CardTitleMail, text: Strings.CardTextMail, imageName: "tour-Mail")
let sync = IntroCard(title: Strings.CardTitleSync, text: Strings.CardTextSync, imageName: "tour-Sync", buttonText: Strings.SignInButtonTitle, buttonSelector: #selector(IntroViewController.login).description)
return [welcome, search, privateBrowsing, mailTo, sync]
}
/* Codable doesnt allow quick conversion to a dictonary */
func asDictonary() -> [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
extension IntroCard: Equatable {}
func == (lhs: IntroCard, rhs: IntroCard) -> Bool {
return lhs.buttonText == rhs.buttonText && lhs.buttonSelector == rhs.buttonSelector
&& lhs.imageName == rhs.imageName && lhs.text == rhs.text && lhs.title == rhs.title
}
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
}