This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 448
/
Copy pathBookmarksViewController.swift
912 lines (735 loc) · 31.6 KB
/
BookmarksViewController.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
/* 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 CoreData
import Shared
import Data
import BraveShared
import CoreServices
import os.log
class BookmarksViewController: SiteTableViewController, ToolbarUrlActionsProtocol {
private var bookmarksFRC: BookmarksV2FetchResultsController?
private let bookmarkManager: BookmarkManager
/// Called when the bookmarks are updated via some user input (i.e. Delete, edit, etc.)
private var bookmarksDidChange: (() -> Void)?
weak var toolbarUrlActionsDelegate: ToolbarUrlActionsDelegate?
private lazy var editBookmarksButton: UIBarButtonItem? = UIBarButtonItem().then {
$0.image = UIImage(named: "edit", in: .module, compatibleWith: nil)!.template
$0.style = .plain
$0.target = self
$0.action = #selector(onEditBookmarksButton)
}
private lazy var addFolderButton: UIBarButtonItem? = UIBarButtonItem().then {
$0.image = UIImage(named: "bookmarks_newfolder_icon", in: .module, compatibleWith: nil)!.template
$0.style = .plain
$0.target = self
$0.action = #selector(onAddBookmarksFolderButton)
}
private lazy var importExportButton: UIBarButtonItem? = UIBarButtonItem().then {
$0.image = UIImage(named: "nav-share", in: .module, compatibleWith: nil)!.template
$0.style = .plain
$0.target = self
$0.action = #selector(importExportAction(_:))
}
private var leftToolbarItems: [UIBarButtonItem?] {
var items: [UIBarButtonItem?] = [.fixedSpace(5)]
if currentFolder == nil {
items.append(importExportButton)
// Unlike Chromium, old CoreData implementation did not have permanent folders
if !Preferences.Chromium.syncV2BookmarksMigrationCompleted.value {
items.append(.fixedSpace(16))
items.append(addFolderButton)
}
} else {
items.append(addFolderButton)
}
return items
}
private weak var addBookmarksFolderOkAction: UIAlertAction?
private var isEditingIndividualBookmark = false
private var currentFolder: Bookmarkv2?
/// Certain bookmark actions are different in private browsing mode.
private let isPrivateBrowsing: Bool
private var isAtBookmarkRootLevel: Bool {
return self.currentFolder == nil
}
private let importExportUtility = BraveCoreImportExportUtility()
private var documentInteractionController: UIDocumentInteractionController?
private var searchBookmarksTimer: Timer?
private var isBookmarksBeingSearched = false
private let bookmarksSearchController = UISearchController(searchResultsController: nil)
private var bookmarksSearchQuery = ""
private lazy var noSearchResultOverlayView = EmptyStateOverlayView(
overlayDetails: EmptyOverlayStateDetails(title: Strings.noSearchResultsfound))
// MARK: Lifecycle
init(folder: Bookmarkv2?, bookmarkManager: BookmarkManager, isPrivateBrowsing: Bool) {
self.isPrivateBrowsing = isPrivateBrowsing
self.bookmarkManager = bookmarkManager
super.init(nibName: nil, bundle: nil)
self.currentFolder = folder
self.title = folder?.title ?? Strings.bookmarks
self.bookmarksFRC = bookmarkManager.frc(parent: folder)
self.bookmarksFRC?.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
applyTheme()
setUpToolbar()
updateEditBookmarksButtonStatus()
updatedFolderHierarchy()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.addSubview(spinner)
spinner.snp.makeConstraints {
$0.center.equalTo(self.view.snp.center)
}
spinner.startAnimating()
spinner.isHidden = false
updateLastVisitedFolder(currentFolder)
bookmarkManager.waitForBookmarkModelLoaded({ [weak self] in
guard let self = self else { return }
self.navigationController?.setToolbarHidden(false, animated: true)
self.reloadData()
self.switchTableEditingMode(true)
self.spinner.stopAnimating()
self.spinner.removeFromSuperview()
self.updateLastVisitedFolder(self.currentFolder)
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Make sure to remove fetch results controller when view disappears.
// Otherwise, it may result in crash if a user is in a nested folder and
// sync changes happen.
bookmarksFRC = nil
}
// MARK: Layout - Theme
private func applyTheme() {
bookmarksSearchController.do {
$0.searchBar.autocapitalizationType = .none
$0.searchResultsUpdater = self
$0.obscuresBackgroundDuringPresentation = false
$0.searchBar.placeholder = Strings.searchBookmarksTitle
$0.delegate = self
$0.hidesNavigationBarDuringPresentation = true
}
navigationItem.do {
$0.searchController = bookmarksSearchController
$0.hidesSearchBarWhenScrolling = false
$0.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tappedDone))
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tappedDone))
tableView.do {
$0.allowsSelectionDuringEditing = true
$0.register(
BookmarkTableViewCell.self,
forCellReuseIdentifier: String(describing: BookmarkTableViewCell.self))
}
definesPresentationContext = true
}
override func accessibilityPerformEscape() -> Bool {
dismiss(animated: true)
return true
}
private func setUpToolbar() {
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
let rightItem = { () -> UIBarButtonItem? in
return currentFolder == nil ? nil : editBookmarksButton
}()
let items = (leftToolbarItems + [flexibleSpace, rightItem, .fixedSpace(5)]).compactMap { $0 }
setToolbarItems(items, animated: true)
}
private func updateEditBookmarksButtonStatus() {
guard let objectsCount = bookmarksFRC?.fetchedObjectsCount else { return }
editBookmarksButton?.isEnabled = objectsCount != 0
if tableView.isEditing && objectsCount == 0 {
disableTableEditingMode()
}
}
private func updatedFolderHierarchy() {
DispatchQueue.main.async {
guard let navigationController = self.navigationController else { return }
let index = navigationController.viewControllers.firstIndex(of: self) ?? 0
if index <= 0 && self.currentFolder != nil {
let nextController = BookmarksViewController(folder: self.currentFolder?.parent, bookmarkManager: self.bookmarkManager, isPrivateBrowsing: self.isPrivateBrowsing)
nextController.profile = self.profile
nextController.bookmarksDidChange = self.bookmarksDidChange
nextController.toolbarUrlActionsDelegate = self.toolbarUrlActionsDelegate
navigationController.viewControllers.insert(nextController, at: index)
nextController.loadViewIfNeeded()
}
}
}
private func updateLastVisitedFolder(_ folder: Bookmarkv2?) {
Preferences.Chromium.lastBookmarksFolderNodeId.value = folder?.objectID ?? -1
}
private func updateEmptyPanelState() {
if isBookmarksBeingSearched, bookmarkManager.fetchedSearchObjectsCount == 0 {
showEmptyPanelState()
} else {
noSearchResultOverlayView.removeFromSuperview()
}
}
private func showEmptyPanelState() {
if noSearchResultOverlayView.superview == nil {
view.addSubview(noSearchResultOverlayView)
view.bringSubviewToFront(noSearchResultOverlayView)
noSearchResultOverlayView.snp.makeConstraints { make -> Void in
make.edges.equalTo(tableView)
}
}
}
// MARK: Actions
@objc private func tappedDone() {
dismiss(animated: true)
}
@objc private func onAddBookmarksFolderButton() {
let alert = UIAlertController.userTextInputAlert(title: Strings.newFolder, message: Strings.enterFolderName) {
input, _ in
if let input = input, !input.isEmpty {
self.addFolder(titled: input)
}
}
self.present(alert, animated: true) {}
}
@objc private func importExportAction(_ sender: UIBarButtonItem) {
let alert = AlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.popoverPresentationController?.barButtonItem = sender
let importAction = UIAlertAction(title: Strings.bookmarksImportAction, style: .default) { [weak self] _ in
let vc = UIDocumentPickerViewController(forOpeningContentTypes: [.html])
vc.delegate = self
self?.present(vc, animated: true)
}
let exportAction = UIAlertAction(title: Strings.bookmarksExportAction, style: .default) { [weak self] _ in
let fileUrl = FileManager.default.temporaryDirectory.appendingPathComponent("Bookmarks").appendingPathExtension("html")
self?.exportBookmarks(to: fileUrl)
}
let cancelAction = UIAlertAction(title: Strings.cancelButtonTitle, style: .cancel)
alert.addAction(importAction)
alert.addAction(exportAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
@objc private func onEditBookmarksButton() {
switchTableEditingMode()
}
// MARK: Data Fetch
override func reloadData() {
performBookmarkFetch()
super.reloadData()
}
private func performBookmarkFetch() {
if isBookmarksBeingSearched {
return
}
do {
// Recreate the frc if it was previously removed
// (when user navigated into a nested folder for example)
if bookmarksFRC == nil {
bookmarksFRC = bookmarkManager.frc(parent: currentFolder)
bookmarksFRC?.delegate = self
}
try self.bookmarksFRC?.performFetch()
} catch let error as NSError {
Logger.module.error("\(error.description)")
}
}
private func refreshBookmarkSearchResult(with query: String = "") {
guard isBookmarksBeingSearched else {
return
}
isLoading = true
fetchBookmarks(with: query) { [weak self] in
self?.isLoading = false
}
}
private func fetchBookmarks(with query: String, _ completion: @escaping () -> Void) {
bookmarkManager.fetchBookmarks(with: query) { [weak self] in
guard let self = self else { return }
self.tableView.reloadData()
self.updateEmptyPanelState()
completion()
}
}
private func fetchBookmarkItem(at indexPath: IndexPath) -> Bookmarkv2? {
if isBookmarksBeingSearched {
return bookmarkManager.searchObject(at: indexPath)
} else {
return bookmarksFRC?.object(at: indexPath)
}
}
// MARK: Internal
private func disableTableEditingMode() {
switchTableEditingMode(true)
}
private func switchTableEditingMode(_ forceOff: Bool = false) {
let editMode: Bool = forceOff ? false : !tableView.isEditing
tableView.setEditing(editMode, animated: forceOff ? false : true)
updateEditBookmarksButton(editMode)
editBookmarksButton?.isEnabled = bookmarksFRC?.fetchedObjectsCount != 0
addFolderButton?.isEnabled = !editMode
}
private func updateEditBookmarksButton(_ tableIsEditing: Bool) {
self.editBookmarksButton?.title = tableIsEditing ? Strings.done : Strings.edit
self.editBookmarksButton?.style = tableIsEditing ? .done : .plain
}
private func addFolder(titled title: String) {
bookmarkManager.addFolder(title: title, parentFolder: currentFolder)
tableView.setContentOffset(CGPoint.zero, animated: true)
}
fileprivate func configureCell(_ cell: BookmarkTableViewCell, atIndexPath indexPath: IndexPath) {
var fetchedBookmarkItem: Bookmarkv2?
if isBookmarksBeingSearched {
fetchedBookmarkItem = bookmarkManager.searchObject(at: indexPath)
} else {
// Make sure Bookmark at index path exists,
// `frc.object(at:)` crashes otherwise, doesn't fail safely with nil
if let objectsCount = bookmarksFRC?.fetchedObjectsCount, indexPath.row >= objectsCount {
assertionFailure("Bookmarks FRC index out of bounds")
return
}
fetchedBookmarkItem = bookmarksFRC?.object(at: indexPath)
}
guard let item = fetchedBookmarkItem else { return }
cell.tag = item.objectID
// See if the cell holds the same bookmark. If yes, we do not have to recreate its image view
// This makes scrolling through bookmarks better if there's many bookmarks with the same url
let domainOrFolderName = item.isFolder ? item.title : (item.domain?.url ?? item.url)
let shouldReuse = domainOrFolderName != cell.domainOrFolderName
cell.domainOrFolderName = domainOrFolderName
func configCell(image: UIImage? = nil, icon: FaviconMO? = nil) {
if !tableView.isEditing {
cell.gestureRecognizers?.forEach { cell.removeGestureRecognizer($0) }
}
if !shouldReuse {
return
}
cell.imageView?.cancelFaviconLoad()
cell.backgroundColor = .clear
cell.imageView?.contentMode = .scaleAspectFit
cell.imageView?.image = FaviconFetcher.defaultFaviconImage
cell.imageView?.layer.cornerRadius = 6
cell.imageView?.layer.cornerCurve = .continuous
cell.imageView?.layer.masksToBounds = true
if let image = image {
// folder or preset icon
cell.imageView?.image = image
cell.imageView?.contentMode = .center
cell.imageView?.layer.borderWidth = 0.0
cell.imageView?.clearMonogramFavicon()
} else {
cell.imageView?.layer.borderColor = BraveUX.faviconBorderColor.cgColor
cell.imageView?.layer.borderWidth = BraveUX.faviconBorderWidth
// Sets the favIcon of a cell's imageView from Brave-Core
// If the icon does not exist, fallback to our FavIconFetcher
let setFavIcon = { (cell: UITableViewCell, item: Bookmarkv2) in
cell.imageView?.clearMonogramFavicon()
if let icon = item.bookmarkNode.icon {
cell.imageView?.image = icon
} else if let domain = item.domain, let url = domain.url?.asURL {
// favicon object associated through domain relationship - set from cache only
cell.imageView?.loadFavicon(for: url, domain: domain, fallbackMonogramCharacter: item.title?.first, cachedOnly: true)
} else {
cell.imageView?.clearMonogramFavicon()
cell.imageView?.image = FaviconFetcher.defaultFaviconImage
}
}
// Brave-Core favIcons are async and notify an observer when changed..
bookmarkManager.addFavIconObserver(item) { [weak item] in
guard let item = item else { return }
setFavIcon(cell, item)
}
// `item.icon` triggers a favIcon load on Brave-Core, then it will notify observers
// and update `item.isFavIconLoading` and `item.isFavIconLoaded` properties..
// Order of this if-statement matters because of that logic!
if (item.bookmarkNode.icon == nil && (item.bookmarkNode.isFavIconLoading || item.bookmarkNode.isFavIconLoaded))
|| item.bookmarkNode.icon != nil {
setFavIcon(cell, item)
} else if let domain = item.domain, let url = domain.url?.asURL {
// favicon object associated through domain relationship - set from cache or download
cell.imageView?.loadFavicon(for: url, domain: domain, fallbackMonogramCharacter: item.title?.first)
} else {
cell.imageView?.clearMonogramFavicon()
cell.imageView?.image = FaviconFetcher.defaultFaviconImage
}
}
}
let fontSize: CGFloat = 14.0
cell.textLabel?.text = item.title ?? item.url
cell.textLabel?.lineBreakMode = .byTruncatingTail
if !item.isFolder {
configCell(icon: item.domain?.favicon)
cell.textLabel?.font = UIFont.systemFont(ofSize: fontSize)
cell.accessoryType = .none
} else {
configCell(image: UIImage(named: "bookmarks_folder_hollow", in: .module, compatibleWith: nil)!.withTintColor(.braveLabel))
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: fontSize)
cell.accessoryType = .disclosureIndicator
cell.setRightBadge(nil)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
nil
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
guard let bookmark = fetchBookmarkItem(at: indexPath) else { return }
if !bookmark.isFolder {
if tableView.isEditing {
// show editing view for bookmark item
self.showEditBookmarkController(bookmark: bookmark)
} else {
if let url = URL(string: bookmark.url ?? "") {
let bookmarkClickEvent: (() -> Void)? = {
/// Donate Custom Intent Open Bookmark List
if !self.isPrivateBrowsing {
ActivityShortcutManager.shared.donateCustomIntent(for: .openBookmarks, with: url.absoluteString)
}
self.toolbarUrlActionsDelegate?.select(url: url, visitType: .bookmark)
}
if presentingViewController is MenuViewController {
presentingViewController?.dismiss(animated: true, completion: bookmarkClickEvent)
} else {
dismiss(animated: true, completion: bookmarkClickEvent)
}
}
}
} else {
if tableView.isEditing {
// show editing view for bookmark item
self.showEditBookmarkController(bookmark: bookmark)
} else {
self.updateLastVisitedFolder(bookmark)
let nextController = BookmarksViewController(folder: bookmark, bookmarkManager: bookmarkManager, isPrivateBrowsing: isPrivateBrowsing)
nextController.profile = profile
nextController.bookmarksDidChange = bookmarksDidChange
nextController.toolbarUrlActionsDelegate = toolbarUrlActionsDelegate
self.navigationController?.pushViewController(nextController, animated: true)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
isBookmarksBeingSearched ? bookmarkManager.fetchedSearchObjectsCount : bookmarksFRC?.fetchedObjectsCount ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard
let cell =
tableView
.dequeueReusableCell(withIdentifier: String(describing: BookmarkTableViewCell.self), for: indexPath) as? BookmarkTableViewCell
else {
assertionFailure()
return UITableViewCell()
}
configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
var fetchedBookmarkItem: Bookmarkv2?
if isBookmarksBeingSearched {
return true
} else {
fetchedBookmarkItem = bookmarksFRC?.object(at: indexPath)
return fetchedBookmarkItem?.canBeDeleted ?? false
}
}
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard let bookmarkItem = fetchBookmarkItem(at: indexPath) else {
return nil
}
var actionItemsMenu: UIMenu
if bookmarkItem.isFolder {
var actionChildren: [UIAction] = []
let children = bookmarkManager.getChildren(forFolder: bookmarkItem, includeFolders: false) ?? []
let urls: [URL] = children.compactMap { bookmark in
guard let url = bookmark.url else { return nil }
return URL(string: url)
}
let openBatchURLAction = UIAction(
title: String(format: Strings.openAllBookmarks, children.count),
image: UIImage(systemName: "arrow.up.forward.app"),
handler: UIAction.deferredActionHandler { _ in
self.toolbarUrlActionsDelegate?.batchOpen(urls)
})
if children.count > 0 {
actionChildren.append(openBatchURLAction)
}
actionItemsMenu = UIMenu(title: "", identifier: nil, children: actionChildren)
} else {
guard let bookmarkItemURL = URL(string: bookmarkItem.url ?? "") else { return nil }
let openInNewTabAction = UIAction(
title: Strings.openNewTabButtonTitle,
image: UIImage(systemName: "plus.square.on.square"),
handler: UIAction.deferredActionHandler { [unowned self] _ in
self.toolbarUrlActionsDelegate?.openInNewTab(bookmarkItemURL, isPrivate: isPrivateBrowsing)
parent?.presentingViewController?.dismiss(animated: true)
})
let newPrivateTabAction = UIAction(
title: Strings.openNewPrivateTabButtonTitle,
image: UIImage(systemName: "plus.square.fill.on.square.fill"),
handler: UIAction.deferredActionHandler { [unowned self] _ in
self.toolbarUrlActionsDelegate?.openInNewTab(bookmarkItemURL, isPrivate: true)
parent?.presentingViewController?.dismiss(animated: true)
})
let copyAction = UIAction(
title: Strings.copyLinkActionTitle,
image: UIImage(systemName: "doc.on.doc"),
handler: UIAction.deferredActionHandler { [unowned self] _ in
self.toolbarUrlActionsDelegate?.copy(bookmarkItemURL)
})
let shareAction = UIAction(
title: Strings.shareLinkActionTitle,
image: UIImage(systemName: "square.and.arrow.up"),
handler: UIAction.deferredActionHandler { [unowned self] _ in
self.toolbarUrlActionsDelegate?.share(bookmarkItemURL)
})
var newTabActionMenu: [UIAction] = [openInNewTabAction]
if !PrivateBrowsingManager.shared.isPrivateBrowsing {
newTabActionMenu.append(newPrivateTabAction)
}
let urlMenu = UIMenu(title: "", options: .displayInline, children: newTabActionMenu)
let linkMenu = UIMenu(title: "", options: .displayInline, children: [copyAction, shareAction])
actionItemsMenu = UIMenu(title: bookmarkItemURL.absoluteString, identifier: nil, children: [urlMenu, linkMenu])
}
return UIContextMenuConfiguration(identifier: indexPath as NSCopying, previewProvider: nil) { _ in
return actionItemsMenu
}
}
}
// MARK: UITableViewDelegate - Editing
extension BookmarksViewController {
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
.delete
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
guard let item = fetchBookmarkItem(at: indexPath), item.canBeDeleted else { return nil }
let deleteAction = UIContextualAction(style: .destructive, title: Strings.delete) { [weak self] _, _, completion in
guard let self = self else {
completion(false)
return
}
if let children = item.children, !children.isEmpty {
let alert = UIAlertController(title: Strings.deleteBookmarksFolderAlertTitle, message: Strings.deleteBookmarksFolderAlertMessage, preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: Strings.cancelButtonTitle, style: .cancel) { _ in
completion(false)
})
alert.addAction(
UIAlertAction(title: Strings.yesDeleteButtonTitle, style: .destructive) { _ in
self.bookmarkManager.delete(item)
completion(true)
})
self.present(alert, animated: true, completion: nil)
} else {
self.bookmarkManager.delete(item)
completion(true)
}
}
let editAction = UIContextualAction(style: .normal, title: Strings.edit) { [weak self] _, _, completion in
self?.showEditBookmarkController(bookmark: item)
completion(true)
}
return UISwipeActionsConfiguration(actions: [deleteAction, editAction])
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let bookmarksFRC = bookmarksFRC else {
return
}
bookmarkManager.reorderBookmarks(frc: bookmarksFRC, sourceIndexPath: sourceIndexPath, destinationIndexPath: destinationIndexPath)
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
!isBookmarksBeingSearched
}
private func showEditBookmarkController(bookmark: Bookmarkv2) {
self.isEditingIndividualBookmark = true
var mode: BookmarkEditMode?
if bookmark.isFolder {
mode = .editFolder(bookmark)
} else {
mode = .editBookmark(bookmark)
}
if let mode = mode {
let vc = AddEditBookmarkTableViewController(bookmarkManager: bookmarkManager, mode: mode)
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
// MARK: BookmarksV2FetchResultsDelegate
extension BookmarksViewController: BookmarksV2FetchResultsDelegate {
func controllerWillChangeContent(_ controller: BookmarksV2FetchResultsController) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: BookmarksV2FetchResultsController) {
tableView.endUpdates()
bookmarksDidChange?()
updateEditBookmarksButtonStatus()
}
func controller(_ controller: BookmarksV2FetchResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .update:
let update = { (path: IndexPath?) in
// When Bookmark is moved to another folder, it can be interpreted as update action
// (since the object is not deleted but updated to have a different parent Bookmark)
// Make sure we are not out of bounds here.
if let path = path,
let cell = self.tableView
.dequeueReusableCell(
withIdentifier: String(describing: BookmarkTableViewCell.self),
for: path) as? BookmarkTableViewCell,
let fetchedObjectsCount = self.bookmarksFRC?.fetchedObjectsCount, path.row < fetchedObjectsCount {
self.configureCell(cell, atIndexPath: path)
}
}
[indexPath, newIndexPath].forEach(update)
case .insert:
guard let path = newIndexPath else {
return
}
tableView.insertRows(at: [path], with: .automatic)
case .delete:
guard let indexPath = indexPath else {
return
}
tableView.deleteRows(at: [indexPath], with: .automatic)
case .move:
break
@unknown default:
assertionFailure()
break
}
}
func controllerDidReloadContents(_ controller: BookmarksV2FetchResultsController) {
if isBookmarksBeingSearched {
refreshBookmarkSearchResult(with: bookmarksSearchQuery)
return
}
// We're in some sort of invalid state in sync..
// Somehow this folder was deleted but the user is currently viewing it..
// Might be a good idea to let the user know in the future that the folder they are currently viewing
// has been deleted from the sync chain on another device..
// This is only possible if the user tries to purposely break sync..
// See brave-ios/issues/3011 && brave-browser/issues/12530
// - Brandon T.
if let currentFolder = currentFolder, !currentFolder.existsInPersistentStore() {
self.navigationController?.popToRootViewController(animated: true)
return
}
// Everything is normal, we can reload the current view..
reloadData()
}
}
// MARK: UIDocumentPickerDelegate - UIDocumentInteractionControllerDelegate
extension BookmarksViewController: UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first, urls.count == 1 else {
return
}
DispatchQueue.main.async {
self.importBookmarks(from: url)
self.documentInteractionController = nil
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
self.documentInteractionController = nil
}
func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
if let url = controller.url {
try? FileManager.default.removeItem(at: url)
}
self.documentInteractionController = nil
}
func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) {
if let url = controller.url {
try? FileManager.default.removeItem(at: url)
}
self.documentInteractionController = nil
}
func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
if let url = controller.url {
try? FileManager.default.removeItem(at: url)
}
self.documentInteractionController = nil
}
}
// MARK: Export-Import Bookmarks
extension BookmarksViewController {
func importBookmarks(from url: URL) {
isLoading = true
self.importExportUtility.importBookmarks(from: url) { [weak self] success in
guard let self = self else { return }
self.isLoading = false
let alert = UIAlertController(
title: Strings.Sync.bookmarksImportPopupErrorTitle,
message: success ? Strings.Sync.bookmarksImportPopupSuccessMessage : Strings.Sync.bookmarksImportPopupFailureMessage,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.OKString, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func exportBookmarks(to url: URL) {
isLoading = true
self.importExportUtility.exportBookmarks(to: url) { [weak self] success in
guard let self = self else { return }
self.isLoading = false
// Controller must be retained otherwise `AirDrop` and other sharing options will fail!
self.documentInteractionController = UIDocumentInteractionController(url: url)
guard let vc = self.documentInteractionController else { return }
vc.uti = String(kUTTypeHTML)
vc.name = "Bookmarks.html"
vc.delegate = self
guard let importExportButton = self.importExportButton else { return }
vc.presentOptionsMenu(from: importExportButton, animated: true)
}
}
}
// MARK: UISearchResultUpdating
extension BookmarksViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let query = searchController.searchBar.text else { return }
if searchBookmarksTimer != nil {
searchBookmarksTimer?.invalidate()
searchBookmarksTimer = nil
}
searchBookmarksTimer =
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(fetchSearchResults(timer:)), userInfo: query, repeats: false)
}
@objc private func fetchSearchResults(timer: Timer) {
guard let query = timer.userInfo as? String else {
bookmarksSearchQuery = ""
return
}
bookmarksSearchQuery = query
refreshBookmarkSearchResult(with: bookmarksSearchQuery)
}
}
// MARK: UISearchControllerDelegate
extension BookmarksViewController: UISearchControllerDelegate {
func willPresentSearchController(_ searchController: UISearchController) {
isBookmarksBeingSearched = true
bookmarksSearchQuery = ""
tableView.setEditing(false, animated: true)
tableView.reloadData()
// Bottom toolbar needs to be hidden when searching for bookmarks
navigationController?.setToolbarHidden(true, animated: true)
}
func willDismissSearchController(_ searchController: UISearchController) {
isBookmarksBeingSearched = false
updateEmptyPanelState()
reloadData()
// Re-enable bottom var options when search is done
navigationController?.setToolbarHidden(false, animated: true)
}
}