forked from qodo-benchmark/firefox-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntroViewController.swift
More file actions
450 lines (395 loc) · 17.2 KB
/
IntroViewController.swift
File metadata and controls
450 lines (395 loc) · 17.2 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
// 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 Common
import Foundation
import Redux
import Shared
import UIKit
class IntroViewController: UIViewController,
OnboardingViewControllerProtocol,
Themeable,
Notifiable,
FeatureFlaggable,
StoreSubscriber {
struct UX {
static let closeButtonSize: CGFloat = 30
static let closeHorizontalMargin: CGFloat = 24
static let closeVerticalMargin: CGFloat = 20
static let pageControlHeight: CGFloat = 40
}
typealias SubscriberStateType = OnboardingViewControllerState
// MARK: - Properties
var viewModel: OnboardingViewModelProtocol
var windowUUID: WindowUUID
var didFinishFlow: (() -> Void)?
var notificationCenter: NotificationProtocol
var themeManager: ThemeManager
var themeListenerCancellable: Any?
var userDefaults: UserDefaultsInterface
var hasRegisteredForDefaultBrowserNotification = false
var currentWindowUUID: UUID? { windowUUID }
weak var qrCodeNavigationHandler: QRCodeNavigationHandler?
private var introViewControllerState: OnboardingViewControllerState?
// MARK: - UI elements
private lazy var closeButton: UIButton = .build { button in
button.setImage(UIImage(named: StandardImageIdentifiers.ExtraLarge.crossCircleFill), for: .normal)
button.addTarget(self, action: #selector(self.closeOnboarding), for: .touchUpInside)
button.accessibilityLabel = String.localizedStringWithFormat(
.Onboarding.Welcome.CloseButtonAccessibilityLabel,
AppName.shortName.rawValue
)
button.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.closeButton
}
lazy var pageController: UIPageViewController = {
let pageVC = UIPageViewController(transitionStyle: .scroll,
navigationOrientation: .horizontal)
pageVC.dataSource = self
pageVC.delegate = self
return pageVC
}()
lazy var pageControl: UIPageControl = .build { pageControl in
pageControl.currentPage = 0
pageControl.numberOfPages = self.viewModel.availableCards.count
pageControl.isUserInteractionEnabled = false
pageControl.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.pageControl
}
// MARK: Initializers
init(
viewModel: IntroViewModel,
windowUUID: WindowUUID,
themeManager: ThemeManager = AppContainer.shared.resolve(),
notificationCenter: NotificationProtocol = NotificationCenter.default,
userDefaults: UserDefaultsInterface = UserDefaults.standard
) {
self.viewModel = viewModel
self.windowUUID = windowUUID
self.themeManager = themeManager
self.windowUUID = windowUUID
self.notificationCenter = notificationCenter
self.userDefaults = userDefaults
super.init(nibName: nil, bundle: nil)
self.viewModel.setupViewControllerDelegates(with: self, for: windowUUID)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
populatePageController()
listenForThemeChanges(withNotificationCenter: notificationCenter)
applyTheme()
}
// MARK: View setup
private func populatePageController() {
if let firstViewController = viewModel.availableCards.first {
pageController.setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
private func setupLayout() {
setupPageController()
if viewModel.isDismissible { setupCloseButton() }
}
private func setupPageController() {
addChild(pageController)
view.addSubview(pageController.view)
pageController.didMove(toParent: self)
view.addSubview(pageControl)
NSLayoutConstraint.activate([
pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
private func setupCloseButton() {
guard viewModel.isDismissible else { return }
view.addSubview(closeButton)
view.bringSubviewToFront(closeButton)
view.accessibilityElements = [closeButton, pageController.view as Any, pageControl]
NSLayoutConstraint.activate([
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: UX.closeVerticalMargin),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor,
constant: -UX.closeHorizontalMargin),
closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize),
closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize),
])
}
// MARK: - Redux
func subscribeToRedux() {
let action = ScreenAction(windowUUID: windowUUID,
actionType: ScreenActionType.showScreen,
screen: .onboardingViewController)
store.dispatch(action)
let uuid = windowUUID
store.subscribe(self, transform: {
$0.select({ appState in
return OnboardingViewControllerState(appState: appState, uuid: uuid)
})
})
}
// Note: actual `store.unsubscribe()` is not strictly needed; Redux uses weak subscribers
func unsubscribeFromRedux() {
let action = ScreenAction(windowUUID: windowUUID,
actionType: ScreenActionType.closeScreen,
screen: .onboardingViewController)
store.dispatch(action)
}
func newState(state: OnboardingViewControllerState) {
ensureMainThread { [weak self] in
guard let self else { return }
introViewControllerState = state
applyTheme()
}
}
// MARK: - Button actions
@objc
func closeOnboarding() {
guard let viewModel = viewModel as? IntroViewModel else { return }
viewModel.saveHasSeenOnboarding()
viewModel.saveSearchBarPosition()
didFinishFlow?()
viewModel.telemetryUtility.sendDismissOnboardingTelemetry(
from: viewModel.availableCards[pageControl.currentPage].viewModel.name)
}
@objc
func dismissSignInViewController() {
dismiss(animated: true, completion: nil)
}
@objc
func dismissPrivacyPolicyViewController() {
dismiss(animated: true, completion: nil)
}
// MARK: - Notifiable
func handleNotifications(_ notification: Notification) {
switch notification.name {
case UIApplication.didEnterBackgroundNotification:
ensureMainThread {
self.appDidEnterBackgroundNotification()
}
default:
break
}
}
func registerForNotification() {
if !hasRegisteredForDefaultBrowserNotification {
startObservingNotifications(
withNotificationCenter: notificationCenter,
forObserver: self,
observing: [UIApplication.didEnterBackgroundNotification]
)
hasRegisteredForDefaultBrowserNotification = true
}
}
func appDidEnterBackgroundNotification() {
let currentViewModel = viewModel.availableCards[pageControl.currentPage].viewModel
guard currentViewModel.buttons.primary.action == .setDefaultBrowser
|| currentViewModel.buttons.secondary?.action == .setDefaultBrowser
else { return }
advance(
numberOfPages: 1,
from: currentViewModel.name,
completionIfLastCard: { self.showNextPageCompletionForLastCard() })
}
// MARK: - Themable
func applyTheme() {
let theme = themeManager.getCurrentTheme(for: windowUUID)
view.backgroundColor = theme.colors.layer2
pageControl.currentPageIndicatorTintColor = theme.colors.actionPrimary
pageControl.pageIndicatorTintColor = theme.colors.formSurfaceOff
// viewModel.availableCards.forEach { $0.applyTheme() }
}
}
// MARK: UIPageViewControllerDataSource & UIPageViewControllerDelegate
extension IntroViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController<OnboardingKitCardInfoModel>,
let index = getCardIndex(viewController: onboardingVC)
else { return nil }
pageControl.currentPage = index
return getNextOnboardingCard(
currentIndex: index,
numberOfCardsToMove: 1,
goForward: false
)
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController
) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController<OnboardingKitCardInfoModel>,
let index = getCardIndex(viewController: onboardingVC)
else { return nil }
pageControl.currentPage = index
return getNextOnboardingCard(
currentIndex: index,
numberOfCardsToMove: 1,
goForward: true
)
}
}
// MARK: - OnboardingCardDelegate
extension IntroViewController: OnboardingCardDelegate {
func handleBottomButtonActions(
for action: OnboardingActions,
from cardName: String,
isPrimaryButton: Bool
) {
viewModel.telemetryUtility.sendButtonActionTelemetry(
from: cardName,
with: action,
and: isPrimaryButton)
guard let introViewModel = viewModel as? IntroViewModel else { return }
switch action {
case .requestNotifications:
introViewModel.chosenOptions.insert(.askForNotificationPermission)
introViewModel.updateOnboardingUserActivationEvent()
askForNotificationPermission(from: cardName)
case .forwardOneCard:
advance(numberOfPages: 1, from: cardName) {
self.showNextPageCompletionForLastCard()
}
case .forwardTwoCard:
advance(numberOfPages: 2, from: cardName) {
self.showNextPageCompletionForLastCard()
}
case .forwardThreeCard:
advance(numberOfPages: 3, from: cardName) {
self.showNextPageCompletionForLastCard()
}
case .syncSignIn:
introViewModel.chosenOptions.insert(.syncSignIn)
introViewModel.updateOnboardingUserActivationEvent()
let fxaPrams = FxALaunchParams(entrypoint: .introOnboarding, query: [:])
presentSignToSync(
windowUUID: windowUUID,
with: fxaPrams,
selector: #selector(dismissSignInViewController),
completion: {
self.advance(numberOfPages: 1, from: cardName) {
self.showNextPageCompletionForLastCard()
}
},
qrCodeNavigationHandler: qrCodeNavigationHandler
)
case .setDefaultBrowser:
introViewModel.chosenOptions.insert(.setAsDefaultBrowser)
introViewModel.updateOnboardingUserActivationEvent()
registerForNotification()
viewModel.telemetryUtility.sendGoToSettingsButtonTappedTelemetry()
DefaultApplicationHelper().openSettings()
case .openInstructionsPopup:
/// Setting default browser card action opens an instruction pop up instead of
/// setting a default browser action. TBD if the above code even still fires.
introViewModel.chosenOptions.insert(.setAsDefaultBrowser)
introViewModel.updateOnboardingUserActivationEvent()
registerForNotification()
presentDefaultBrowserPopup(
windowUUID: windowUUID,
from: cardName,
completionIfLastCard: { self.showNextPageCompletionForLastCard() })
case .readPrivacyPolicy:
presentPrivacyPolicy(
windowUUID: windowUUID,
from: cardName,
selector: #selector(dismissPrivacyPolicyViewController))
case .openIosFxSettings:
viewModel.telemetryUtility.sendGoToSettingsButtonTappedTelemetry()
DefaultApplicationHelper().openSettings()
advance(numberOfPages: 1, from: cardName) {
self.showNextPageCompletionForLastCard()
}
case .endOnboarding:
closeOnboarding()
}
}
func handleMultipleChoiceButtonActions(
for action: OnboardingMultipleChoiceAction,
from cardName: String
) {
switch action {
case .themeDark:
turnSystemTheme(on: false)
let action = ThemeSettingsViewAction(manualThemeType: .dark,
windowUUID: windowUUID,
actionType: ThemeSettingsViewActionType.switchManualTheme)
store.dispatch(action)
case .themeLight:
turnSystemTheme(on: false)
let action = ThemeSettingsViewAction(manualThemeType: .light,
windowUUID: windowUUID,
actionType: ThemeSettingsViewActionType.switchManualTheme)
store.dispatch(action)
case .themeSystemDefault:
turnSystemTheme(on: true)
case .toolbarBottom:
featureFlags.set(feature: .searchBarPosition, to: SearchBarPosition.bottom)
let notificationObject = [PrefsKeys.FeatureFlags.SearchBarPosition: SearchBarPosition.bottom]
notificationCenter.post(name: .SearchBarPositionDidChange, withObject: notificationObject)
case .toolbarTop:
featureFlags.set(feature: .searchBarPosition, to: SearchBarPosition.top)
let notificationObject = [PrefsKeys.FeatureFlags.SearchBarPosition: SearchBarPosition.top]
notificationCenter.post(name: .SearchBarPositionDidChange, withObject: notificationObject)
}
viewModel.telemetryUtility.sendMultipleChoiceButtonActionTelemetry(
from: cardName,
with: action
)
}
private func turnSystemTheme(on state: Bool) {
let action = ThemeSettingsViewAction(useSystemAppearance: state,
windowUUID: windowUUID,
actionType: ThemeSettingsViewActionType.toggleUseSystemAppearance)
store.dispatch(action)
}
func sendCardViewTelemetry(from cardName: String) {
viewModel.telemetryUtility.sendCardViewTelemetry(from: cardName)
}
private func showNextPageCompletionForLastCard() {
guard let viewModel = viewModel as? IntroViewModel else { return }
viewModel.saveHasSeenOnboarding()
didFinishFlow?()
}
private func askForNotificationPermission(from cardName: String) {
let notificationManager = NotificationManager()
notificationManager.requestAuthorization { [weak self] granted, error in
guard error == nil, let self = self else { return }
DispatchQueue.main.async {
if granted {
if self.userDefaults.object(forKey: PrefsKeys.Notifications.SyncNotifications) == nil {
self.userDefaults.set(granted, forKey: PrefsKeys.Notifications.SyncNotifications)
}
if self.userDefaults.object(forKey: PrefsKeys.Notifications.TipsAndFeaturesNotifications) == nil {
self.userDefaults.set(granted, forKey: PrefsKeys.Notifications.TipsAndFeaturesNotifications)
}
NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil)
}
self.advance(numberOfPages: 1, from: cardName) {
self.showNextPageCompletionForLastCard()
}
}
}
}
}
// MARK: 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
}
}