/
ActivityStreamPanel.swift
733 lines (622 loc) · 30.2 KB
/
ActivityStreamPanel.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
/* 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 Shared
import UIKit
import Deferred
import Storage
import WebImage
import XCGLogger
private let log = Logger.browserLogger
private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites"
// MARK: - Lifecycle
struct ASPanelUX {
static let backgroundColor = UIColor(white: 1.0, alpha: 0.5)
static let topSitesCacheSize = 16
static let historySize = 10
static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20
static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 195
static let PageControlOffsetSize: CGFloat = 40
static let SectionInsetsForIpad: CGFloat = 101
static let SectionInsetsForIphone: CGFloat = 14
static let CompactWidth: CGFloat = 320
}
class ActivityStreamPanel: UICollectionViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
fileprivate let profile: Profile
fileprivate let telemetry: ActivityStreamTracker
fileprivate let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
fileprivate let topSitesManager = ASHorizontalScrollCellManager()
fileprivate var isInitialLoad = true //Prevents intro views from flickering while content is loading
fileprivate let events = [NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
fileprivate var sessionStart: Timestamp?
lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:)))
}()
// Not used for displaying. Only used for calculating layout.
lazy var topSiteCell: ASHorizontalScrollCell = {
let customCell = ASHorizontalScrollCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 0))
customCell.delegate = self.topSitesManager
return customCell
}()
var highlights: [Site] = []
init(profile: Profile, telemetry: ActivityStreamTracker? = nil) {
self.profile = profile
self.telemetry = telemetry ?? ActivityStreamTracker(eventsTracker: PingCentre.clientForTopic(.ActivityStreamEvents, clientID: profile.clientID), sessionsTracker: PingCentre.clientForTopic(.ActivityStreamSessions, clientID: profile.clientID))
super.init(collectionViewLayout: flowLayout)
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
collectionView?.addGestureRecognizer(longPressRecognizer)
self.profile.history.setTopSitesCacheSize(Int32(ASPanelUX.topSitesCacheSize))
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: $0, object: nil) }
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) }
self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")
collectionView?.backgroundColor = ASPanelUX.backgroundColor
collectionView?.keyboardDismissMode = .onDrag
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sessionStart = Date.now()
all([invalidateTopSites(), invalidateHighlights()]).uponQueue(DispatchQueue.main) { _ in
self.isInitialLoad = false
self.collectionView?.reloadData()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
telemetry.reportSessionStop(Date.now() - (sessionStart ?? 0))
sessionStart = nil
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: {context in
self.collectionViewLayout.invalidateLayout()
self.collectionView?.reloadData()
}, completion: nil)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.topSitesManager.currentTraits = self.traitCollection
}
}
// MARK: - Section management
extension ActivityStreamPanel {
enum Section: Int {
case topSites
case highlights
case highlightIntro
static let count = 3
static let allValues = [topSites, highlights, highlightIntro]
var title: String? {
switch self {
case .highlights: return Strings.ASHighlightsTitle
case .topSites: return nil
case .highlightIntro: return nil
}
}
var headerHeight: CGSize {
switch self {
case .highlights: return CGSize(width: 50, height: 40)
case .topSites: return CGSize(width: 0, height: 0)
case .highlightIntro: return CGSize(width: 50, height: 2)
}
}
func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat {
switch self {
case .highlights: return ASPanelUX.highlightCellHeight
case .topSites: return 0 //calculated dynamically
case .highlightIntro: return 200
}
}
func sectionInsets() -> CGFloat {
switch self {
case .highlights:
return UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad + ASHorizontalScrollCellUX.MinimumInsets : ASPanelUX.SectionInsetsForIphone
case .topSites:
return UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad : 0
case .highlightIntro:
return UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad : 0
}
}
func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize {
let height = cellHeight(traits, width: frameWidth)
let inset = sectionInsets() * 2
switch self {
case .highlights:
var numItems: CGFloat = 0
if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight {
numItems = 4
} else if UIDevice.current.userInterfaceIdiom == .pad {
numItems = 3
} else {
numItems = 2
}
return CGSize(width: floor(((frameWidth - inset) - (ASHorizontalScrollCellUX.MinimumInsets * (numItems - 1))) / numItems), height: height)
case .topSites:
return CGSize(width: frameWidth - inset, height: height)
case .highlightIntro:
return CGSize(width: frameWidth - inset - (ASHorizontalScrollCellUX.MinimumInsets * 2), height: height)
}
}
var headerView: UIView? {
switch self {
case .highlights:
let view = ASHeaderView()
view.title = title
return view
case .topSites:
return nil
case .highlightIntro:
let view = ASHeaderView()
view.title = title
return view
}
}
var cellIdentifier: String {
switch self {
case .topSites: return "TopSiteCell"
case .highlights: return "HistoryCell"
case .highlightIntro: return "HighlightIntroCell"
}
}
var cellType: UICollectionViewCell.Type {
switch self {
case .topSites: return ASHorizontalScrollCell.self
case .highlights: return ActivityStreamHighlightCell.self
case .highlightIntro: return HighlightIntroCell.self
}
}
init(at indexPath: IndexPath) {
self.init(rawValue: indexPath.section)!
}
init(_ section: Int) {
self.init(rawValue: section)!
}
}
}
// MARK: - Tableview Delegate
extension ActivityStreamPanel: UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView
let title = Section(indexPath.section).title
switch Section(indexPath.section) {
case .highlights:
view.title = title
return view
case .topSites:
return UICollectionReusableView()
case .highlightIntro:
view.title = title
return view
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.longPressRecognizer.isEnabled = false
selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width)
switch Section(indexPath.section) {
case .highlights:
if highlights.isEmpty {
return CGSize.zero
}
return cellSize
case .topSites:
// Create a temporary cell so we can calculate the height.
let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout
let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0))
return CGSize(width: cellSize.width, height: estimatedLayout.size.height)
case .highlightIntro:
return cellSize
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
switch Section(section) {
case .highlights:
return highlights.isEmpty ? CGSize.zero : Section(section).headerHeight
case .highlightIntro:
return !highlights.isEmpty ? CGSize.zero : Section(section).headerHeight
case .topSites:
return Section(section).headerHeight
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return ASPanelUX.rowSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let insets = Section(section).sectionInsets()
return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets)
}
fileprivate func showSiteWithURLHandler(_ url: URL) {
let visitType = VisitType.bookmark
homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType)
}
}
// MARK: - Tableview Data Source
extension ActivityStreamPanel {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch Section(section) {
case .topSites:
return topSitesManager.content.isEmpty ? 0 : 1
case .highlights:
return self.highlights.count
case .highlightIntro:
return self.highlights.isEmpty && !self.isInitialLoad ? 1 : 0
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = Section(indexPath.section).cellIdentifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
switch Section(indexPath.section) {
case .topSites:
return configureTopSitesCell(cell, forIndexPath: indexPath)
case .highlights:
return configureHistoryItemCell(cell, forIndexPath: indexPath)
case .highlightIntro:
return configureHighlightIntroCell(cell, forIndexPath: indexPath)
}
}
//should all be collectionview
func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let topSiteCell = cell as! ASHorizontalScrollCell
topSiteCell.delegate = self.topSitesManager
return cell
}
func configureHistoryItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let site = highlights[indexPath.row]
let simpleHighlightCell = cell as! ActivityStreamHighlightCell
simpleHighlightCell.configureWithSite(site)
return simpleHighlightCell
}
func configureHighlightIntroCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let introCell = cell as! HighlightIntroCell
//The cell is configured on creation. No need to configure. But leave this here in case we need it.
return introCell
}
}
// MARK: - Data Management
extension ActivityStreamPanel {
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationProfileDidFinishSyncing, NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged:
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
default:
log.warning("Received unexpected notification \(notification.name)")
}
}
fileprivate func reportMissingData(sites: [Site], source: ASPingSource) {
sites.forEach { site in
if site.metadata?.mediaURL == nil {
self.telemetry.reportBadState(badState: .MissingMetadataImage, source: source)
}
if site.icon == nil {
self.telemetry.reportBadState(badState: .MissingFavicon, source: source)
}
}
}
func invalidateHighlights() -> Success {
return self.profile.recommendations.getHighlights().bindQueue(DispatchQueue.main) { result in
if let newHighlights = result.successValue?.asArray() {
// Scan through the fetched highlights and report on anything that might be missing.
self.reportMissingData(sites: newHighlights, source: .Highlights)
self.highlights = newHighlights
}
return succeed()
}
}
func invalidateTopSites() -> Success {
let frecencyLimit = ASPanelUX.topSitesCacheSize
// Update our top sites cache if it's been invalidated
return self.profile.history.updateTopSitesCacheIfInvalidated() >>== { _ in
return self.profile.history.getTopSitesWithLimit(frecencyLimit) >>== { topSites in
let mySites = topSites.asArray()
let defaultSites = self.defaultTopSites()
// Merge default topsites with a user's topsites.
let mergedSites = mySites.union(defaultSites, f: { (site) -> String in
return URL(string: site.url)?.hostSLD ?? ""
})
// Favour topsites from defaultSites as they have better favicons.
let newSites = mergedSites.map { site -> Site in
let domain = URL(string: site.url)?.hostSLD
return defaultSites.find { $0.title.lowercased() == domain } ?? site
}
// Don't report bad states for default sites we provide
self.reportMissingData(sites: mySites, source: .TopSites)
self.topSitesManager.currentTraits = self.view.traitCollection
self.topSitesManager.content = newSites.count > ASPanelUX.topSitesCacheSize ? Array(newSites[0..<ASPanelUX.topSitesCacheSize]) : newSites
self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in
self.longPressRecognizer.isEnabled = false
self.telemetry.reportEvent(.Click, source: .TopSites, position: indexPath.item)
self.showSiteWithURLHandler(url as URL)
}
return succeed()
}
}
}
func hideURLFromTopSites(_ siteURL: URL) {
guard let host = siteURL.normalizedHost else {
return
}
let url = siteURL.absoluteString
// if the default top sites contains the siteurl. also wipe it from default suggested sites.
if defaultTopSites().filter({$0.url == url}).isEmpty == false {
deleteTileForSuggestedSite(url)
}
profile.history.removeHostFromTopSites(host).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
}
}
func hideFromHighlights(_ site: Site) {
profile.recommendations.removeHighlightForURL(site.url).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateHighlights().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
}
}
fileprivate func deleteTileForSuggestedSite(_ siteURL: String) {
var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
deletedSuggestedSites.append(siteURL)
profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey)
}
func defaultTopSites() -> [Site] {
let suggested = SuggestedSites.asArray()
let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
return suggested.filter({deleted.index(of: $0.url) == .none})
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let point = longPressGestureRecognizer.location(in: self.collectionView)
guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return }
switch Section(indexPath.section) {
case .highlights:
presentContextMenuForHighlightCellWithIndexPath(indexPath)
case .topSites:
let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell
let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView)
guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return }
presentContextMenuForTopSiteCellWithIndexPath(topSiteIndexPath)
case .highlightIntro:
break
}
}
func presentContextMenu(_ contextMenu: ActionOverlayTableViewController) {
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
self.present(contextMenu, animated: true, completion: nil)
}
func presentContextMenuForTopSiteCellWithIndexPath(_ indexPath: IndexPath) {
let site = self.topSitesManager.content[indexPath.item]
presentContextMenuForSite(site, atIndex: indexPath.item, forSection: .topSites)
}
func presentContextMenuForHighlightCellWithIndexPath(_ indexPath: IndexPath) {
let site = highlights[indexPath.row]
presentContextMenuForSite(site, atIndex: indexPath.row, forSection: .highlights)
}
fileprivate func fetchBookmarkStatusThenPresentContextMenu(_ site: Site, atIndex index: Int, forSection section: Section) {
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(site.url).uponQueue(DispatchQueue.main) { result in
guard let isBookmarked = result.successValue else {
log.error("Error getting bookmark status: \(result.failureValue).")
return
}
site.setBookmarked(isBookmarked)
self.presentContextMenuForSite(site, atIndex: index, forSection: section)
}
}
}
func presentContextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section) {
guard let _ = site.bookmarked else {
fetchBookmarkStatusThenPresentContextMenu(site, atIndex: index, forSection: section)
return
}
guard let contextMenu = contextMenuForSite(site, atIndex: index, forSection: section) else {
return
}
self.presentContextMenu(contextMenu)
}
func contextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section) -> ActionOverlayTableViewController? {
guard let siteURL = URL(string: site.url) else {
return nil
}
let pingSource: ASPingSource
switch section {
case .topSites:
pingSource = .TopSites
case .highlights:
pingSource = .Highlights
case .highlightIntro:
pingSource = .HighlightsIntro
}
let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "action_new_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "action_new_private_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
let bookmarkAction: ActionOverlayTableViewAction
if site.bookmarked ?? false {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in
self.profile.bookmarks.modelFactory >>== {
$0.removeByURL(siteURL.absoluteString)
site.setBookmarked(false)
}
})
} else {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in
let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon)
self.profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
site.setBookmarked(true)
})
}
let deleteFromHistoryAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.telemetry.reportEvent(.Delete, source: pingSource, position: index)
self.profile.history.removeHistoryForURL(site.url)
})
let shareAction = ActionOverlayTableViewAction(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in
let helper = ShareExtensionHelper(url: siteURL, tab: nil, activities: [])
let controller = helper.createActivityViewController { completed, activityType in
self.telemetry.reportEvent(.Share, source: pingSource, position: index, shareProvider: activityType)
}
self.present(controller, animated: true, completion: nil)
})
let removeTopSiteAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideURLFromTopSites(site.tileURL)
})
let dismissHighlightAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideFromHighlights(site)
})
var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction]
switch section {
case .highlights: actions.append(contentsOf: [dismissHighlightAction, deleteFromHistoryAction])
case .topSites: actions.append(removeTopSiteAction)
case .highlightIntro: break
}
return ActionOverlayTableViewController(site: site, actions: actions)
}
func selectItemAtIndex(_ index: Int, inSection section: Section) {
switch section {
case .highlights:
telemetry.reportEvent(.Click, source: .Highlights, position: index)
let site = self.highlights[index]
showSiteWithURLHandler(URL(string:site.url)!)
case .topSites, .highlightIntro:
return
}
}
}
// MARK: Telemetry
enum ASPingEvent: String {
case Click = "CLICK"
case Delete = "DELETE"
case Dismiss = "DISMISS"
case Share = "SHARE"
}
enum ASPingBadStateEvent: String {
case MissingMetadataImage = "MISSING_METADATA_IMAGE"
case MissingFavicon = "MISSING_FAVICON"
}
enum ASPingSource: String {
case Highlights = "HIGHLIGHTS"
case TopSites = "TOP_SITES"
case HighlightsIntro = "HIGHLIGHTS_INTRO"
}
struct ActivityStreamTracker {
let eventsTracker: PingCentreClient
let sessionsTracker: PingCentreClient
private var baseASPing: [String: Any] {
return [
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
]
}
func reportBadState(badState: ASPingBadStateEvent, source: ASPingSource) {
var eventPing: [String: Any] = [
"event": badState.rawValue,
"page": "NEW_TAB",
"source": source.rawValue,
]
eventPing.merge(with: baseASPing)
eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true)
}
func reportEvent(_ event: ASPingEvent, source: ASPingSource, position: Int, shareProvider: String? = nil) {
var eventPing: [String: Any] = [
"event": event.rawValue,
"page": "NEW_TAB",
"source": source.rawValue,
"action_position": position,
]
if let provider = shareProvider {
eventPing["share_provider"] = provider
}
eventPing.merge(with: baseASPing)
eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true)
}
func reportSessionStop(_ duration: UInt64) {
sessionsTracker.sendPing([
"session_duration": NSNumber(value: duration),
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
] as [String: Any], validate: true)
}
}
// MARK: - Section Header View
struct ASHeaderViewUX {
static let SeperatorColor = UIColor(rgb: 0xedecea)
static let TextFont = DynamicFontHelper.defaultHelper.DefaultMediumBoldFont
static let SeperatorHeight = 1
static let Insets: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad : ASPanelUX.SectionInsetsForIphone
static let TitleTopInset: CGFloat = 5
}
class ASHeaderView: UICollectionReusableView {
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = self.title
titleLabel.textColor = UIColor.gray
titleLabel.font = ASHeaderViewUX.TextFont
return titleLabel
}()
var title: String? {
willSet(newTitle) {
titleLabel.text = newTitle
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
let leftInset = UIDevice.current.userInterfaceIdiom == .pad ? ASHorizontalScrollCellUX.MinimumInsets : 0
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(self).inset(ASHeaderViewUX.Insets + leftInset)
make.trailing.equalTo(self).inset(-ASHeaderViewUX.Insets)
make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset)
make.bottom.equalTo(self)
}
let seperatorLine = UIView()
seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor
self.backgroundColor = UIColor.clear
addSubview(seperatorLine)
seperatorLine.snp.makeConstraints { make in
make.height.equalTo(ASHeaderViewUX.SeperatorHeight)
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.top.equalTo(self.snp.top)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}