-
-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathMainTabBarController.swift
More file actions
757 lines (645 loc) · 30.2 KB
/
MainTabBarController.swift
File metadata and controls
757 lines (645 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
//
// MainTabBarController.swift
// Mastodon
//
// Created by Cirno MainasuK on 2021-1-27.
//
import UIKit
import Combine
import CoreDataStack
import SafariServices
import MastodonAsset
import MastodonCore
import MastodonLocalization
import MastodonUI
import SDWebImage
class MainTabBarController: UITabBarController {
public var disposeBag = Set<AnyCancellable>()
var authenticationBox: MastodonAuthenticationBox?
private let largeContentViewerInteraction = UILargeContentViewerInteraction()
static let avatarButtonSize = CGSize(width: 25, height: 25)
let avatarButton = CircleAvatarButton()
let accountSwitcherChevron = UIImageView(
image: .chevronUpChevronDown?.withConfiguration(
UIImage.SymbolConfiguration(weight: .bold)
)
)
@Published var currentTab: Tab = .home
let homeTimelineViewController: UIViewController
let searchViewController: SearchViewController
let composeViewController: UIViewController // placeholder
let notificationViewController: UIViewController
var meProfileViewController: UIViewController // placeholder
private(set) var isReadyForWizardAvatarButton = false
// output
@Published var avatarURL: URL?
// haptic feedback
private let feedbackGenerator = FeedbackGenerator.shared
init(
authenticationBox: MastodonAuthenticationBox?
) {
self.authenticationBox = authenticationBox
homeTimelineViewController = TimelineListViewController(.home)
homeTimelineViewController.configureTabBarItem(with: .home)
searchViewController = SearchViewController()
searchViewController.configureTabBarItem(with: .search)
composeViewController = UIViewController()
composeViewController.configureTabBarItem(with: .compose)
notificationViewController = TimelineListViewController(.notifications(.everything))
notificationViewController.configureTabBarItem(with: .notifications)
meProfileViewController = UIViewController()
meProfileViewController.configureTabBarItem(with: .me)
if let authenticationBox {
searchViewController.viewModel = SearchViewModel(authenticationBox: authenticationBox)
}
super.init(nibName: nil, bundle: nil)
viewControllers = [homeTimelineViewController, searchViewController, composeViewController, notificationViewController, meProfileViewController].map {
if UserDefaults.standard.useBetaProfileView && $0 == meProfileViewController {
return $0
} else {
return AdaptiveStatusBarStyleNavigationController(rootViewController: $0)
}
}
tabBar.addInteraction(largeContentViewerInteraction)
for controller in viewControllers ?? [] {
(controller as? UINavigationController)?.delegate = self
}
layoutAvatarButton()
updateProfileTabA11y()
}
private func replace(_ oldVC: UIViewController, with newVC: UIViewController) {
if let containingNavigationController = viewControllers?.first(where: {
guard let navController = $0 as? UINavigationController else { return false }
return navController.viewControllers[0] == oldVC
}) {
(containingNavigationController as? UINavigationController)?.viewControllers = [newVC]
} else if let replacementIndex = viewControllers?.firstIndex(of: oldVC) {
var replaced = viewControllers ?? []
replaced[replacementIndex] = newVC
viewControllers = replaced
}
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
extension MainTabBarController {
open override var childForStatusBarStyle: UIViewController? {
return selectedViewController
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
view.backgroundColor = .systemBackground
// seealso: `ThemeService.apply(theme:)`
setViewControllers(viewControllers, animated: false)
selectedIndex = 0
// hacky workaround for FB11986255 (Setting accessibilityUserInputLabels on a UITabBarItem has no effect)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50)) {
if let searchItem = self.tabBar.subviews.first(where: { $0.accessibilityLabel == Tab.search.title }) {
searchItem.accessibilityUserInputLabels = Tab.search.inputLabels
}
}
APIService.shared.error
.receive(on: DispatchQueue.main)
.sink { [weak self] error in
guard let self, let coordinator = self.sceneCoordinator else { return }
switch error {
case .implicit:
break
case .explicit:
let alertController = UIAlertController(for: error, title: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
_ = coordinator.present(
scene: .alertController(alertController: alertController),
from: nil,
transition: .alertController(animated: true, completion: nil)
)
}
}
.store(in: &disposeBag)
// handle post failure
// handle push notification.
// toggle entry when finish fetch latest notification
Publishers.CombineLatest(
NotificationService.shared.unreadNotificationCountDidUpdate,
$currentTab
)
.receive(on: DispatchQueue.main)
.sink { [weak self] authentication, currentTab in
guard let self else { return }
let authentication = self.authenticationBox?.userAuthorization
let hasUnreadPushNotification: Bool = authentication.flatMap { authentication in
let count = UserDefaults.shared.getNotificationCountWithAccessToken(accessToken: authentication.accessToken)
return count > 0
} ?? false
let image: UIImage
if hasUnreadPushNotification {
let imageConfiguration = UIImage.SymbolConfiguration(paletteColors: [.red, SystemTheme.tabBarItemNormalIconColor])
image = UIImage(systemName: "bell.badge", withConfiguration: imageConfiguration)!
} else {
image = Tab.notifications.image
}
notificationViewController.tabBarItem.image = image.imageWithoutBaseline()
notificationViewController.navigationController?.tabBarItem.image = image.imageWithoutBaseline()
}
.store(in: &disposeBag)
$currentTab
.receive(on: DispatchQueue.main)
.sink { [weak self] currentTab in
guard let self else { return }
if currentTab == .me {
guard let authBox = authenticationBox, let myAccount = authBox.cachedAccount else { return }
guard !(meProfileViewController is ProfileViewController) && !(meProfileViewController is ProfileHostingViewController) else { return }
let oldMe = meProfileViewController
let updatedProfile: UIViewController = {
if UserDefaults.standard.useBetaProfileView {
let controller = ProfileHostingViewController(wrapInSwiftUINavigationStack: true)
controller.set(account: MastodonAccount.fromEntity(myAccount, authenticatedDomain: authBox.domain), relationship: .isMe)
return controller
} else {
return ProfileViewController(.me(myAccount), authenticationBox: authBox)
}
}()
meProfileViewController = updatedProfile
updatedProfile.configureTabBarItem(with: .me)
self.replace(oldMe, with: updatedProfile)
if let domain = myAccount.domain ?? myAccount.domainFromAcct {
self.avatarURL = myAccount.avatarImageURLWithFallback(domain: domain)
} else {
self.avatarURL = myAccount.avatarImageURL()
}
self.avatarButton.removeFromSuperview()
self.layoutAvatarButton()
}
}
.store(in: &disposeBag)
$avatarURL
.receive(on: DispatchQueue.main)
.sink { [weak self] avatarURL in
guard let self else { return }
if #available(iOS 26, *) {
self.layoutAvatarButton()
} else {
self.avatarButton.avatarImageView.setImage(
url: avatarURL,
scaleToSize: MainTabBarController.avatarButtonSize
)
}
}
.store(in: &disposeBag)
AuthenticationServiceProvider.shared.updateActiveUserAccountPublisher
.sink { [weak self] in
self?.updateUserAccount()
}
.store(in: &self.disposeBag)
AuthenticationServiceProvider.shared.currentActiveUser
.receive(on: DispatchQueue.main)
.sink { [weak self] activeUser in
if let domain = activeUser?.domain {
self?.avatarURL = activeUser?.cachedAccount?.avatarImageURLWithFallback(domain: domain)
} else {
self?.avatarURL = activeUser?.cachedAccount?.avatarImageURL()
}
}
.store(in: &disposeBag)
NotificationCenter.default.publisher(for: .userFetched)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self,
let authenticationBox,
let account = authenticationBox.cachedAccount else { return }
self.avatarURL = account.avatarImageURL()
// a11y
let _profileTabItem = self.tabBar.items?.first { item in item.tag == Tab.me.tag }
guard let profileTabItem = _profileTabItem else { return }
profileTabItem.accessibilityHint = L10n.Scene.AccountList.tabBarHint(account.displayNameWithFallback)
}
.store(in: &disposeBag)
let tabBarLongPressGestureRecognizer = UILongPressGestureRecognizer()
tabBarLongPressGestureRecognizer.addTarget(self, action: #selector(MainTabBarController.tabBarLongPressGestureRecognizerHandler(_:)))
tabBarLongPressGestureRecognizer.delegate = self
tabBar.addGestureRecognizer(tabBarLongPressGestureRecognizer)
self.isReadyForWizardAvatarButton = authenticationBox != nil
$currentTab
.receive(on: DispatchQueue.main)
.sink { [weak self] tab in
guard let self else { return }
self.updateAvatarButtonAppearance()
}
.store(in: &disposeBag)
updateTabBarDisplay()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateTabBarDisplay()
updateAvatarButtonAppearance()
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
.portraitOnPhone
}
}
extension MainTabBarController {
func updateProfileTabA11y() {
guard let authBox = authenticationBox, let account = authBox.cachedAccount else { return }
let _profileTabItem = self.tabBar.items?.first { item in item.tag == Tab.me.tag }
guard let profileTabItem = _profileTabItem else { return }
profileTabItem.accessibilityHint = L10n.Scene.AccountList.tabBarHint(account.displayNameWithFallback)
}
}
extension MainTabBarController {
@objc private func composeButtonDidPressed(_ sender: Any) {
feedbackGenerator.generate(.impact(.medium))
guard let authenticationBox else { return }
let composeViewModel = ComposeViewModel(
authenticationBox: authenticationBox,
composeContext: .composeStatus(quoting: nil),
destination: .topLevel
)
_ = self.sceneCoordinator?.present(scene: .compose(viewModel: composeViewModel), transition: .modal(animated: true, completion: nil))
}
private func touchedTab(by sender: UIGestureRecognizer) -> Tab? {
var _tab: Tab?
let location = sender.location(in: tabBar)
for item in tabBar.items ?? [] {
guard let tab = Tab(rawValue: item.tag) else { continue }
guard let view = item.value(forKey: "view") as? UIView else { continue }
guard view.frame.contains(location) else { continue}
_tab = tab
break
}
return _tab
}
@objc private func tabBarLongPressGestureRecognizerHandler(_ sender: UILongPressGestureRecognizer) {
guard sender.state == .began else { return }
guard let tab = touchedTab(by: sender) else { return }
switch tab {
case .me:
guard let authenticationBox else { return }
let accountListViewModel = AccountListViewModel(authenticationBox: authenticationBox)
_ = self.sceneCoordinator?.present(scene: .accountList(viewModel: accountListViewModel), from: self, transition: .formSheet(nil))
default:
break
}
}
}
extension MainTabBarController {
private func updateTabBarDisplay() {
switch traitCollection.horizontalSizeClass {
case .compact:
tabBar.isHidden = false
default:
tabBar.isHidden = true
if #available(iOS 18.0, *), UIDevice.current.userInterfaceIdiom == .pad {
self.isTabBarHidden = true
}
}
}
private func layoutAvatarButton() {
if #available(iOS 26, *) {
guard let avatarURL else { return }
Task { [weak self] in
guard let self else { return }
let avatarImage = try await AvatarButtonImageLoader.getImage(url: avatarURL)
guard self.avatarURL == avatarURL else { return }
let tabBarItem = UITabBarItem(title: nil, image: avatarImage?.withRenderingMode(.alwaysOriginal), tag: Tab.me.tag)
self.meProfileViewController.tabBarItem = tabBarItem
}
} else {
guard avatarButton.superview == nil else { return }
guard let profileTabItem = meProfileViewController.tabBarItem else { return }
guard let view = profileTabItem.value(forKey: "view") as? UIView else {
return
}
let _anchorImageView = view.subviews.first { subview in subview is UIImageView } as? UIImageView
guard let anchorImageView = _anchorImageView else {
assertionFailure()
return
}
anchorImageView.alpha = 0
accountSwitcherChevron.removeFromSuperview()
accountSwitcherChevron.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(accountSwitcherChevron)
self.avatarButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self.avatarButton)
NSLayoutConstraint.activate([
self.avatarButton.centerXAnchor.constraint(equalTo: anchorImageView.centerXAnchor),
self.avatarButton.centerYAnchor.constraint(equalTo: anchorImageView.centerYAnchor),
self.avatarButton.widthAnchor.constraint(equalToConstant: MainTabBarController.avatarButtonSize.width).priority(.required - 1),
self.avatarButton.heightAnchor.constraint(equalToConstant: MainTabBarController.avatarButtonSize.height).priority(.required - 1),
accountSwitcherChevron.widthAnchor.constraint(equalToConstant: 10),
accountSwitcherChevron.heightAnchor.constraint(equalToConstant: 18),
accountSwitcherChevron.leadingAnchor.constraint(equalTo: avatarButton.trailingAnchor, constant: 8),
accountSwitcherChevron.centerYAnchor.constraint(equalTo: avatarButton.centerYAnchor)
])
self.avatarButton.setContentHuggingPriority(.required - 1, for: .horizontal)
self.avatarButton.setContentHuggingPriority(.required - 1, for: .vertical)
self.avatarButton.isUserInteractionEnabled = false
}
}
private func updateAvatarButtonAppearance() {
if currentTab == .me {
accountSwitcherChevron.tintColor = Asset.Colors.Brand.blurple.color
avatarButton.borderColor = Asset.Colors.Brand.blurple.color
} else {
accountSwitcherChevron.tintColor = Asset.Theme.System.tabBarItemInactiveIconColor.color
avatarButton.borderColor = Asset.Theme.System.tabBarItemInactiveIconColor.color
}
avatarButton.setNeedsLayout()
}
private func updateUserAccount() {
guard let authenticationBox else { return }
Task { @MainActor in
let profileResponse = try await APIService.shared.accountInfo(authenticationBox)
}
}
}
// MARK: - UITabBarControllerDelegate
extension MainTabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if let tab = Tab(rawValue: viewController.tabBarItem.tag), tab == .compose {
let previousTab = selectedTab
composeButtonDidPressed(tabBarController)
if #available(iOS 26.0, *) {
// a bit of a hack to avoid interrupting the liquid glass animation when you tap the compose button in the tab bar
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.selectedTab = previousTab
}
return true
} else {
return false
}
}
// Different tab has been selected, send haptic feedback
if viewController.tabBarItem.tag != tabBarController.selectedIndex {
feedbackGenerator.generate(.impact(.medium))
}
// Assert index is as same as the tab rawValue. This check needs to be done `shouldSelect`
// because the nav controller has already popped in `didSelect`.
if currentTab.rawValue == viewController.tabBarItem.tag,
let navigationController = viewController as? UINavigationController,
navigationController.viewControllers.count == 1,
let scrollViewContainer = navigationController.topViewController as? ScrollViewContainer {
scrollViewContainer.scrollToTop(animated: true)
}
return true
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let previousTab = currentTab
if let tab = Tab(rawValue: viewController.tabBarItem.tag), tab != .compose {
currentTab = tab
switch (currentTab, previousTab) {
case (.home, .home):
// When home is tapped again, scroll to top
(homeTimelineViewController as? TimelineListViewController)?.scrollToTop()
break
case (.search, .search):
// When search is tapped again, expand and focus the search bar
searchViewController.searchBar.becomeFirstResponder()
break
default:
break
}
}
}
}
// HIG: keyboard UX
// https://developer.apple.com/design/human-interface-guidelines/macos/user-interaction/keyboard/
extension MainTabBarController {
var switchToTabKeyCommands: [UIKeyCommand] {
var commands: [UIKeyCommand] = []
let tabs: [Tab] = [
.home,
.search,
.notifications,
.me
]
for (i, tab) in tabs.enumerated() {
let title = L10n.Common.Controls.Keyboard.Common.switchToTab(tab.title)
let input = String(i + 1)
let command = UIKeyCommand(
title: title,
image: nil,
action: #selector(MainTabBarController.switchToTabKeyCommandHandler(_:)),
input: input,
modifierFlags: .command,
propertyList: tab.rawValue,
alternates: [],
discoverabilityTitle: nil,
attributes: [],
state: .off
)
commands.append(command)
}
return commands
}
var showFavoritesKeyCommand: UIKeyCommand {
UIKeyCommand(
title: L10n.Common.Controls.Keyboard.Common.showFavorites,
image: nil,
action: #selector(MainTabBarController.showFavoritesKeyCommandHandler(_:)),
input: "f",
modifierFlags: .command,
propertyList: nil,
alternates: [],
discoverabilityTitle: nil,
attributes: [],
state: .off
)
}
var openSettingsKeyCommand: UIKeyCommand {
UIKeyCommand(
title: L10n.Common.Controls.Keyboard.Common.openSettings,
image: nil,
action: #selector(MainTabBarController.openSettingsKeyCommandHandler(_:)),
input: ",",
modifierFlags: .command,
propertyList: nil,
alternates: [],
discoverabilityTitle: nil,
attributes: [],
state: .off
)
}
var composeNewPostKeyCommand: UIKeyCommand {
UIKeyCommand(
title: L10n.Common.Controls.Keyboard.Common.composeNewPost,
image: nil,
action: #selector(MainTabBarController.composeNewPostKeyCommandHandler(_:)),
input: "n",
modifierFlags: .command,
propertyList: nil,
alternates: [],
discoverabilityTitle: nil,
attributes: [],
state: .off
)
}
override var keyCommands: [UIKeyCommand]? {
guard let topMost = self.topMost else {
return []
}
var commands: [UIKeyCommand] = []
if topMost.isModal {
} else {
// switch tabs
commands.append(contentsOf: switchToTabKeyCommands)
// show compose
if !(self.topMost is ComposeViewController) {
commands.append(composeNewPostKeyCommand)
}
// show favorites
let includeShowFavoritesCommand = {
if let topTimeline = self.topMost as? TimelineListViewController {
switch topTimeline.type {
case .myFavorites:
false
default:
true
}
} else {
true
}
}()
if includeShowFavoritesCommand {
commands.append(showFavoritesKeyCommand)
}
// open settings
if SettingService.shared.currentSetting.value != nil {
commands.append(openSettingsKeyCommand)
}
}
return commands
}
@objc private func switchToTabKeyCommandHandler(_ sender: UIKeyCommand) {
guard let rawValue = sender.propertyList as? Int,
let tab = Tab(rawValue: rawValue) else { return }
guard let index = Tab.allCases.firstIndex(of: tab) else { return }
let previousTab = Tab(rawValue: selectedIndex)
selectedIndex = index
if let tab = Tab(rawValue: index) {
currentTab = tab
}
if let previousTab = previousTab {
switch (tab, previousTab) {
case (.home, .home):
guard let navigationController = topMost?.navigationController else { return }
if navigationController.viewControllers.count > 1 {
// pop to top when previous tab position already is home
navigationController.popToRootViewController(animated: true)
} else if let timelineViewController = topMost as? TimelineListViewController {
switch timelineViewController.type {
case .home:
// trigger scrollToTop if topMost is already the home timeline
timelineViewController.scrollToTop()
default:
break
}
}
default:
break
}
}
}
@objc private func showFavoritesKeyCommandHandler(_ sender: UIKeyCommand) {
guard let authenticationBox else { return }
_ = self.sceneCoordinator?.present(scene: .myFavorites, from: nil, transition: .show)
}
@objc private func openSettingsKeyCommandHandler(_ sender: UIKeyCommand) {
guard let setting = SettingService.shared.currentSetting.value else { return }
_ = self.sceneCoordinator?.present(scene: .settings(setting: setting), from: self, transition: .none)
}
@objc private func composeNewPostKeyCommandHandler(_ sender: UIKeyCommand) {
guard let authenticationBox else { return }
let composeViewModel = ComposeViewModel(
authenticationBox: authenticationBox,
composeContext: .composeStatus(quoting: nil),
destination: .topLevel
)
_ = self.sceneCoordinator?.present(scene: .compose(viewModel: composeViewModel), from: nil, transition: .modal(animated: true, completion: nil))
}
}
extension MainTabBarController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
true
}
}
extension MainTabBarController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
// disable animations when transitioning to/from the profile view controller, since it has a transparent background on the nav bar which makes the transition to standard nav bars look broken
if viewController is ProfileViewController || navigationController.topViewController is ProfileViewController {
if let coordinator = navigationController.topViewController?.transitionCoordinator {
let transparentAppearance = UINavigationBarAppearance()
transparentAppearance.configureWithTransparentBackground()
navigationController.navigationBar.standardAppearance = transparentAppearance
navigationController.navigationBar.compactAppearance = transparentAppearance
navigationController.navigationBar.scrollEdgeAppearance = transparentAppearance
coordinator.animate(alongsideTransition: nil) { _ in
navigationController.setNeedsStatusBarAppearanceUpdate()
}
}
} else {
let nonTransparentAppearance = UINavigationBarAppearance()
nonTransparentAppearance.configureWithDefaultBackground()
navigationController.navigationBar.standardAppearance = nonTransparentAppearance
navigationController.navigationBar.compactAppearance = nonTransparentAppearance
navigationController.navigationBar.scrollEdgeAppearance = nonTransparentAppearance
if let coordinator = navigationController.topViewController?.transitionCoordinator {
coordinator.animate(alongsideTransition: nil) { _ in
navigationController.setNeedsStatusBarAppearanceUpdate()
}
} else {
navigationController.setNeedsStatusBarAppearanceUpdate()
}
}
}
}
struct AvatarButtonImageLoader {
@MainActor
static var _cache = [URL : UIImage]()
@MainActor
static func getImage(url: URL) async throws -> UIImage? {
if let cached = _cache[url] {
return cached
} else {
let baseImage: UIImage? = try await withCheckedThrowingContinuation { continuation in
SDWebImageDownloader.shared.downloadImage(with: url) { image, data, error, finished in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: image)
}
}
}
guard let circular = baseImage?.circularMasked(diameter: 40) else { return nil }
_cache[url] = circular
return circular
}
}
}
var circularAvatarRenderer: UIGraphicsImageRenderer?
extension UIImage {
func circularMasked(diameter: CGFloat) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let scale = max(diameter/size.width, diameter/size.height)
let drawingRect = CGRect(
x: (size.width * scale - diameter) / 2,
y: (size.height * scale - diameter) / 2,
width: size.width * scale,
height: size.height * scale
)
let renderer = {
if let circularAvatarRenderer {
return circularAvatarRenderer
} else {
let _newRenderer = UIGraphicsImageRenderer(size: CGSize(width: diameter, height: diameter))
circularAvatarRenderer = _newRenderer
return _newRenderer
}
}()
return renderer.image { context in
let circleRect = CGRect(origin: .zero, size: CGSize(width: diameter, height: diameter))
UIBezierPath(ovalIn: circleRect).addClip()
UIImage(cgImage: cgImage).draw(in: drawingRect)
}
}
}