-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathTabTrayController.swift
1171 lines (983 loc) · 46.5 KB
/
TabTrayController.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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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 Storage
import Shared
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(6.0)
static let TextBoxHeight = CGFloat(32.0)
static let SearchBarHeight = CGFloat(64)
static let FaviconSize = CGFloat(20)
static let Margin = CGFloat(15)
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonSize = CGFloat(32)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(7)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
static let MenuFixedWidth: CGFloat = 320
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
protocol TabTrayDelegate: AnyObject {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddTab(_ tabTray: TabTrayController, tab: Tab)
func tabTrayDidAddBookmark(_ tab: Tab)
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
var tabDisplayManager: TabDisplayManager!
var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TabCell.Identifier
var otherBrowsingModeOffset = CGPoint.zero
var collectionView: UICollectionView!
let statusBarBG = UIView()
lazy var toolbar: TrayToolbar = {
let toolbar = TrayToolbar()
toolbar.addTabButton.addTarget(self, action: #selector(openTab), for: .touchUpInside)
toolbar.maskButton.addTarget(self, action: #selector(didTogglePrivateMode), for: .touchUpInside)
toolbar.deleteButton.addTarget(self, action: #selector(didTapDelete), for: .touchUpInside)
return toolbar
}()
lazy var searchBar: UITextField = {
let searchBar = SearchBarTextField()
searchBar.backgroundColor = UIColor.theme.tabTray.searchBackground
searchBar.leftView = UIImageView(image: UIImage(named: "quickSearch"))
searchBar.leftViewMode = .unlessEditing
searchBar.textColor = UIColor.theme.tabTray.tabTitleText
searchBar.attributedPlaceholder = NSAttributedString(string: Strings.TabSearchPlaceholderText, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tabTray.tabTitleText.withAlphaComponent(0.7)])
searchBar.clearButtonMode = .never
searchBar.delegate = self
searchBar.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
return searchBar
}()
var searchBarHolder = UIView()
var roundedSearchBarHolder: UIView = {
let roundedView = UIView()
roundedView.backgroundColor = UIColor.theme.tabTray.searchBackground
roundedView.layer.cornerRadius = 4
roundedView.layer.masksToBounds = true
return roundedView
}()
lazy var cancelButton: UIButton = {
let cancelButton = UIButton()
cancelButton.setImage(UIImage.templateImageNamed("close-medium"), for: .normal)
cancelButton.addTarget(self, action: #selector(didPressCancel), for: .touchUpInside)
cancelButton.tintColor = UIColor.theme.tabTray.tabTitleText
cancelButton.isHidden = true
return cancelButton
}()
fileprivate(set) internal var privateMode: Bool = false {
didSet {
toolbar.applyUIMode(isPrivate: privateMode)
}
}
fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
let emptyView = EmptyPrivateTabsView()
emptyView.learnMoreButton.addTarget(self, action: #selector(didTapLearnMore), for: .touchUpInside)
return emptyView
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection, scrollView: self.collectionView)
delegate.tabSelectionDelegate = self
return delegate
}()
var numberOfColumns: Int {
return tabLayoutDelegate.numberOfColumns
}
init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate? = nil) {
self.tabManager = tabManager
self.profile = profile
self.delegate = tabTrayDelegate
super.init(nibName: nil, bundle: nil)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self, reuseID: TabCell.Identifier)
collectionView.dataSource = tabDisplayManager
collectionView.delegate = tabLayoutDelegate
collectionView.contentInset = UIEdgeInsets(top: TabTrayControllerUX.SearchBarHeight, left: 0, bottom: 0, right: 0)
// these will be animated during view show/hide transition
statusBarBG.alpha = 0
searchBarHolder.alpha = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
}
deinit {
tabManager.removeDelegate(self.tabDisplayManager)
tabManager.removeDelegate(self)
tabDisplayManager.removeObservers()
tabDisplayManager = nil
}
func focusTab() {
guard let currentTab = tabManager.selectedTab, let index = self.tabDisplayManager.tabStore.index(of: currentTab), let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame else {
return
}
self.collectionView.scrollRectToVisible(rect, animated: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func dynamicFontChanged(_ notification: Notification) {
guard notification.name == .DynamicFontChanged else { return }
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
tabManager.addDelegate(self)
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
collectionView.alwaysBounceVertical = true
collectionView.backgroundColor = UIColor.theme.tabTray.background
collectionView.keyboardDismissMode = .onDrag
// XXX: Bug 1485064 - Temporarily disable drag-and-drop in tabs tray
if #available(iOS 11.0, *), LeanPlumClient.shared.enableDragDrop.boolValue() {
collectionView.dragInteractionEnabled = true
collectionView.dragDelegate = tabDisplayManager
collectionView.dropDelegate = tabDisplayManager
}
searchBarHolder.addSubview(roundedSearchBarHolder)
searchBarHolder.addSubview(searchBar)
searchBarHolder.backgroundColor = UIColor.theme.tabTray.toolbar
[collectionView, toolbar, searchBarHolder, cancelButton].forEach { view.addSubview($0) }
makeConstraints()
// The statusBar needs a background color
statusBarBG.backgroundColor = UIColor.theme.tabTray.toolbar
view.addSubview(statusBarBG)
statusBarBG.snp.makeConstraints { make in
make.leading.trailing.top.equalTo(self.view)
make.bottom.equalTo(self.topLayoutGuide.snp.bottom)
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.snp.makeConstraints { make in
make.top.left.right.equalTo(self.collectionView)
make.bottom.equalTo(self.toolbar.snp.top)
}
if let tab = tabManager.selectedTab, tab.isPrivate {
privateMode = true
}
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
}
override var preferredStatusBarStyle: UIStatusBarStyle {
//special case for iPad
if UIDevice.current.userInterfaceIdiom == .pad && ThemeManager.instance.currentName == .normal {
return .default
}
return ThemeManager.instance.statusBarStyle
}
fileprivate func makeConstraints() {
collectionView.snp.makeConstraints { make in
make.left.equalTo(view.safeArea.left)
make.right.equalTo(view.safeArea.right)
make.bottom.equalTo(toolbar.snp.top)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
toolbar.snp.makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.height.equalTo(UIConstants.BottomToolbarHeight)
}
cancelButton.snp.makeConstraints { make in
make.centerY.equalTo(self.roundedSearchBarHolder.snp.centerY)
make.trailing.equalTo(self.roundedSearchBarHolder.snp.trailing).offset(-8)
}
searchBarHolder.snp.makeConstraints { make in
make.leading.equalTo(view.safeArea.leading)
make.trailing.equalTo(view.safeArea.trailing)
make.height.equalTo(TabTrayControllerUX.SearchBarHeight)
self.tabLayoutDelegate.searchHeightConstraint = make.bottom.equalTo(self.topLayoutGuide.snp.bottom).constraint
}
searchBar.snp.makeConstraints { make in
make.edges.equalTo(searchBarHolder).inset(UIEdgeInsetsMake(15, 20, 10, 40))
}
roundedSearchBarHolder.snp.makeConstraints { make in
make.edges.equalTo(searchBarHolder).inset(UIEdgeInsetsMake(15, 10, 10, 10))
}
}
@objc func didTogglePrivateMode() {
if tabDisplayManager.isDragging {
return
}
toolbar.isUserInteractionEnabled = false
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
let newOffset = CGPoint(x: 0.0, y: collectionView.contentOffset.y)
if self.otherBrowsingModeOffset.y > 0 {
collectionView.setContentOffset(self.otherBrowsingModeOffset, animated: false)
}
self.otherBrowsingModeOffset = newOffset
let fromView: UIView
if !privateTabsAreEmpty(), let snapshot = collectionView.snapshotView(afterScreenUpdates: false) {
snapshot.frame = collectionView.frame
view.insertSubview(snapshot, aboveSubview: collectionView)
fromView = snapshot
} else {
fromView = emptyPrivateTabsView
}
tabDisplayManager.isPrivate = !tabDisplayManager.isPrivate
tabManager.willSwitchTabMode(leavingPBM: privateMode)
privateMode = !privateMode
if tabDisplayManager.searchActive {
self.didPressCancel()
} else {
self.tabDisplayManager.reloadData()
}
tabDisplayManager.isPrivate = privateMode
// If we are exiting private mode and we have the close private tabs option selected, make sure
// we clear out all of the private tabs
let exitingPrivateMode = !privateMode && tabManager.shouldClearPrivateTabs()
toolbar.maskButton.setSelected(privateMode, animated: true)
collectionView.layoutSubviews()
let toView: UIView
if !privateTabsAreEmpty(), let newSnapshot = collectionView.snapshotView(afterScreenUpdates: !exitingPrivateMode) {
emptyPrivateTabsView.isHidden = true
//when exiting private mode don't screenshot the collectionview (causes the UI to hang)
newSnapshot.frame = collectionView.frame
view.insertSubview(newSnapshot, aboveSubview: fromView)
collectionView.alpha = 0
toView = newSnapshot
} else {
emptyPrivateTabsView.isHidden = false
toView = emptyPrivateTabsView
}
toView.alpha = 0
toView.transform = scaleDownTransform
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { () -> Void in
fromView.transform = scaleDownTransform
fromView.alpha = 0
toView.transform = .identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if toView != self.emptyPrivateTabsView {
toView.removeFromSuperview()
}
self.collectionView.alpha = 1
self.toolbar.isUserInteractionEnabled = true
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.privateTabs.count == 0
}
@objc func openTab() {
openNewTab()
}
func openNewTab(_ request: URLRequest? = nil) {
if tabDisplayManager.isDragging {
return
}
// We dismiss the tab tray once we are done. So no need to re-enable the toolbar
toolbar.isUserInteractionEnabled = false
tabManager.selectTab(tabManager.addTab(request, isPrivate: tabDisplayManager.isPrivate))
self.tabDisplayManager.performTabUpdates {
self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
self.dismissTabTray()
}
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Tab Tray"])
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard let toast = toast, privateMode else {
return
}
view.addSubview(toast)
toast.showToast(delay: SimpleToastUX.ToastPrivateModeDelayBefore, makeConstraints: { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.toolbar.snp.top)
})
}
}
extension TabTrayController: UITextFieldDelegate {
@objc func didPressCancel() {
clearSearch()
UIView.animate(withDuration: 0.1) {
self.cancelButton.isHidden = true
}
self.searchBar.resignFirstResponder()
}
@objc func textDidChange(textField: UITextField) {
guard let text = textField.text, !text.isEmpty else {
clearSearch()
return
}
ensureMainThread {
self.searchTabs(for: text)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.1) {
self.cancelButton.isHidden = false
}
}
func searchTabs(for searchString: String) {
let currentTabs = self.tabDisplayManager.isPrivate ? self.tabManager.privateTabs : self.tabManager.normalTabs
let filteredTabs = currentTabs.filter { tab in
if let url = tab.url, url.isLocal {
return false
}
let title = tab.title ?? tab.lastTitle
if title?.lowercased().range(of: searchString.lowercased()) != nil {
return true
}
if tab.url?.absoluteString.lowercased().range(of: searchString.lowercased()) != nil {
return true
}
return false
}
self.tabDisplayManager.searchActive = true
self.tabDisplayManager.searchedTabs = filteredTabs
self.tabDisplayManager.performTabUpdates()
}
func clearSearch() {
tabDisplayManager.searchActive = false
tabDisplayManager.searchedTabs = []
searchBar.text = ""
ensureMainThread {
self.tabDisplayManager.performTabUpdates()
}
}
}
extension TabTrayController: TabDisplayer {
func focusSelectedTab() {
self.focusTab()
}
func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell {
guard let tabCell = cell as? TabCell else { return cell }
tabCell.animator.delegate = self
tabCell.delegate = self
let selected = tab == tabManager.selectedTab
tabCell.configureWith(tab: tab, is: selected)
return tabCell
}
}
extension TabTrayController {
@objc func didTapLearnMore() {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
if let langID = Locale.preferredLanguages.first {
let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion ?? "0.0")/iOS/\(langID)/private-browsing-ios".asURL!)
openNewTab(learnMoreRequest)
}
}
func closeTabsForCurrentTray() {
tabManager.removeTabsWithUndoToast(tabDisplayManager.tabStore)
if !tabDisplayManager.isPrivate {
// when closing all tabs in normal mode we automatically open a new tab and focus it
self.tabDisplayManager.performTabUpdates {
self.dismissTabTray()
}
} else {
emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
if !emptyPrivateTabsView.isHidden {
// Fade in the empty private tabs message. This slow fade allows time for the closing tab animations to complete.
emptyPrivateTabsView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.2, options: .curveEaseIn, animations: {
self.emptyPrivateTabsView.alpha = 1
}, completion: nil)
}
}
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != tabDisplayManager.isPrivate {
didTogglePrivateMode()
}
}
func dismissTabTray() {
_ = self.navigationController?.popViewController(animated: true)
}
}
// MARK: - App Notifications
extension TabTrayController {
@objc func appWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
searchBarHolder.alpha = 0
}
}
@objc func appDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
self.collectionView.alpha = 1
self.searchBarHolder.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
if let tab = tabDisplayManager.tabStore[safe: index] {
tabManager.selectTab(tab)
dismissTabTray()
}
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
guard var visibleCells = collectionView.visibleCells as? [TabCell] else { return nil }
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
guard !indexPaths.isEmpty else {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if firstTab == lastTab {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
guard let tabCell = animator.animatingView as? TabCell, let indexPath = collectionView.indexPath(for: tabCell) else { return }
if let tab = tabDisplayManager.tabStore[safe: indexPath.item] {
self.removeTab(tab: tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "Accessibility label (used by assistive technology) notifying the user that the tab is being closed."))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
if let indexPath = collectionView.indexPath(for: cell), let tab = tabDisplayManager.tabStore[safe: indexPath.item] {
self.removeTab(tab: tab)
}
}
}
extension TabTrayController: TabPeekDelegate {
func tabPeekDidAddBookmark(_ tab: Tab) {
delegate?.tabTrayDidAddBookmark(tab)
}
func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem? {
return delegate?.tabTrayDidAddToReadingList(tab)
}
func tabPeekDidCloseTab(_ tab: Tab) {
if let index = tabDisplayManager.tabStore.index(of: tab),
let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? TabCell {
cell.close()
}
}
func tabPeekRequestsPresentationOf(_ viewController: UIViewController) {
delegate?.tabTrayRequestsPresentationOf(viewController)
}
}
extension TabTrayController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let collectionView = collectionView else { return nil }
let convertedLocation = self.view.convert(location, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: convertedLocation),
let cell = collectionView.cellForItem(at: indexPath) else { return nil }
guard let tab = tabDisplayManager.tabStore[safe: indexPath.row] else {
return nil
}
let tabVC = TabPeekViewController(tab: tab, delegate: self)
if let browserProfile = profile as? BrowserProfile {
tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self)
}
previewingContext.sourceRect = self.view.convert(cell.frame, from: collectionView)
return tabVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return }
tabManager.selectTab(tpvc.tab)
navigationController?.popViewController(animated: true)
delegate?.tabTrayDidDismiss(self)
}
}
extension TabTrayController {
func removeTab(tab: Tab) {
// when removing the last tab (only in normal mode) we will automatically open a new tab.
// When that happens focus it by dismissing the tab tray
let isLastTab = tabDisplayManager.tabStore.count == 1
tabManager.removeTabAndUpdateSelectedIndex(tab)
guard !tabDisplayManager.searchActive else { return }
self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
self.tabDisplayManager.performTabUpdates {
if isLastTab, !self.tabDisplayManager.isPrivate {
self.dismissTabTray()
}
}
}
}
extension TabTrayController {
@objc func didTapDelete(_ sender: UIButton) {
let controller = AlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: Strings.AppMenuCloseAllTabsTitleString, style: .default, handler: { _ in self.closeTabsForCurrentTray() }), accessibilityIdentifier: "TabTrayController.deleteButton.closeAll")
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil), accessibilityIdentifier: "TabTrayController.deleteButton.cancel")
controller.popoverPresentationController?.sourceView = sender
controller.popoverPresentationController?.sourceRect = sender.bounds
present(controller, animated: true, completion: nil)
}
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
weak var tabSelectionDelegate: TabSelectionDelegate?
var searchHeightConstraint: Constraint?
let scrollView: UIScrollView
var lastYOffset: CGFloat = 0
enum ScrollDirection {
case up
case down
}
fileprivate var scrollDirection: ScrollDirection = .down
fileprivate var traitCollection: UITraitCollection
fileprivate var numberOfColumns: Int {
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return TabTrayControllerUX.CompactNumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection, scrollView: UIScrollView) {
self.scrollView = scrollView
self.traitCollection = traitCollection
super.init()
}
func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
if scrollDirection == .up {
hideSearch()
}
}
}
func checkRubberbandingForDelta(_ delta: CGFloat, for scrollView: UIScrollView) -> Bool {
if scrollView.contentOffset.y < 0 {
return true
} else {
return false
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let float = scrollView.contentOffset.y
defer {
self.lastYOffset = float
}
let delta = lastYOffset - float
if delta > 0 {
scrollDirection = .down
} else if delta < 0 {
scrollDirection = .up
}
if checkRubberbandingForDelta(delta, for: scrollView) {
let offset = clamp(abs(scrollView.contentOffset.y), min: 0, max: TabTrayControllerUX.SearchBarHeight)
searchHeightConstraint?.update(offset: offset)
scrollView.contentInset = UIEdgeInsets(top: offset, left: 0, bottom: 0, right: 0)
} else {
self.hideSearch()
}
}
func showSearch() {
searchHeightConstraint?.update(offset: TabTrayControllerUX.SearchBarHeight)
scrollView.contentInset = UIEdgeInsets(top: TabTrayControllerUX.SearchBarHeight, left: 0, bottom: 0, right: 0)
}
func hideSearch() {
searchHeightConstraint?.update(offset: 0)
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let shortHeight = TabTrayControllerUX.TextBoxHeight * 6
if self.traitCollection.verticalSizeClass == .compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == .compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(equalInset: TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
private struct EmptyPrivateTabsViewUX {
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.medium)
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
static let MinBottomMargin: CGFloat = 10
}
// View we display when there are no private tabs created
fileprivate class EmptyPrivateTabsView: UIView {
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.Photon.White100
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = .center
return label
}()
fileprivate var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.Photon.White100
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = .center
label.numberOfLines = 0
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
fileprivate var learnMoreButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(
NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"),
for: [])
button.setTitleColor(UIColor.theme.tabTray.privateModeLearnMore, for: [])
button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont
return button
}()
fileprivate var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won’t remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
addSubview(learnMoreButton)
titleLabel.snp.makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp.makeConstraints { make in
make.bottom.equalTo(titleLabel.snp.top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
learnMoreButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(descriptionLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin).priority(10)
make.bottom.lessThanOrEqualTo(self).offset(-EmptyPrivateTabsViewUX.MinBottomMargin).priority(1000)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TabTrayController: ClientPickerViewControllerDelegate {
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
if let item = clientPickerViewController.shareItem {
_ = self.profile.sendItem(item, toClients: clients)
}
clientPickerViewController.dismiss(animated: true, completion: nil)
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
clientPickerViewController.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
// MARK: - Toolbar
class TrayToolbar: UIView, Themeable, PrivateModeUI {
fileprivate let toolbarButtonSize = CGSize(width: 44, height: 44)
lazy var addTabButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("nav-add"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.addTabButton"
return button
}()
lazy var deleteButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("action_delete"), for: .normal)
button.accessibilityLabel = Strings.TabTrayDeleteMenuButtonAccessibilityLabel
button.accessibilityIdentifier = "TabTrayController.removeTabsButton"
return button
}()
lazy var maskButton: PrivateModeButton = PrivateModeButton()
fileprivate let sideOffset: CGFloat = 32
fileprivate override init(frame: CGRect) {
super.init(frame: frame)
addSubview(addTabButton)
var buttonToCenter: UIButton?
addSubview(deleteButton)
buttonToCenter = deleteButton
maskButton.accessibilityIdentifier = "TabTrayController.maskButton"
buttonToCenter?.snp.makeConstraints { make in
make.centerX.equalTo(self)
make.top.equalTo(self)
make.size.equalTo(toolbarButtonSize)
}
addTabButton.snp.makeConstraints { make in
make.top.equalTo(self)
make.trailing.equalTo(self).offset(-sideOffset)
make.size.equalTo(toolbarButtonSize)
}
addSubview(maskButton)
maskButton.snp.makeConstraints { make in
make.top.equalTo(self)
make.leading.equalTo(self).offset(sideOffset)
make.size.equalTo(toolbarButtonSize)
}
applyTheme()
applyUIMode(isPrivate: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyUIMode(isPrivate: Bool) {
maskButton.applyUIMode(isPrivate: isPrivate)
}
func applyTheme() {
[addTabButton, deleteButton].forEach {
$0.tintColor = UIColor.theme.tabTray.toolbarButtonTint
}
backgroundColor = UIColor.theme.tabTray.toolbar
maskButton.offTint = UIColor.theme.tabTray.privateModeButtonOffTint
maskButton.onTint = UIColor.theme.tabTray.privateModeButtonOnTint
}
}
protocol TabCellDelegate: AnyObject {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case light
case dark
}
static let Identifier = "TabCellIdentifier"
static let BorderWidth: CGFloat = 3
let backgroundHolder: UIView = {
let view = UIView()
view.layer.cornerRadius = TabTrayControllerUX.CornerRadius
view.clipsToBounds = true
view.backgroundColor = UIColor.theme.tabTray.cellBackground
return view
}()
let screenshotView: UIImageViewAligned = {
let view = UIImageViewAligned()
view.contentMode = .scaleAspectFill
view.clipsToBounds = true
view.isUserInteractionEnabled = false
view.alignLeft = true
view.alignTop = true
view.backgroundColor = UIColor.theme.browser.background
return view
}()
let titleText: UILabel = {
let label = UILabel()
label.isUserInteractionEnabled = false
label.numberOfLines = 1