Files
otunes/apps/mobile/native/TabletSidebar.swift
T

247 lines
9.5 KiB
Swift

import UIKit
internal import ExpoModulesCore
final class TabletSidebar: Module {
public func definition() -> ExpoModulesCore.ModuleDefinition {
Name("TabletSidebar")
View(TabletSidebarView.self) {
Events("onProfilePress")
Prop("accountName") { (view: TabletSidebarView, value: String) in
view.accountName = value
view.configure()
}
Prop("initials") { (view: TabletSidebarView, value: String) in
view.initials = value
view.configure()
}
Prop("imageURL") { (view: TabletSidebarView, value: String?) in
view.imageURL = value
view.configure()
}
Prop("active") { (view: TabletSidebarView, value: Bool) in
view.active = value
view.configure()
}
}
}
}
/// Adds UIKit sidebar features not yet exposed by Expo Router's native tabs.
final class TabletSidebarView: ExpoView {
let onProfilePress = EventDispatcher()
var accountName = ""
var initials = ""
var imageURL: String?
var active = false
private var tabsObserver: NSObjectProtocol?
override func didMoveToWindow() {
super.didMoveToWindow()
if let tabsObserver {
NotificationCenter.default.removeObserver(tabsObserver)
self.tabsObserver = nil
}
if window != nil {
tabsObserver = NotificationCenter.default.addObserver(
forName: Notification.Name("oTunesTabsDidUpdate"), object: nil, queue: .main
) { [weak self] notification in
guard let self, self.active, self.window != nil,
let controller = notification.object as? UITabBarController,
self.owningTabController() === controller else { return }
if #available(iOS 18.0, *) { self.configure(controller) }
}
}
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
configure()
}
func configure() {
guard active, window != nil, UIDevice.current.userInterfaceIdiom == .pad else { return }
DispatchQueue.main.async { [weak self] in
guard let self, self.active else { return }
if let tabs = self.owningTabController(), #available(iOS 18.0, *) {
self.configure(tabs)
}
}
}
private func owningTabController() -> UITabBarController? {
var responder: UIResponder? = self
while let current = responder {
if let controller = current as? UIViewController, let tabs = controller.tabBarController {
return tabs
}
responder = current.next
}
return nil
}
deinit {
if let tabsObserver { NotificationCenter.default.removeObserver(tabsObserver) }
}
@available(iOS 18.0, *)
private func configure(_ controller: UITabBarController) {
configureGroups(controller)
let footer: SidebarAccountButton
if let existing = controller.sidebar.bottomBarView as? SidebarAccountButton {
footer = existing
} else {
footer = SidebarAccountButton()
controller.sidebar.bottomBarView = footer
}
configureTabBar(controller, footer: footer)
footer.update(name: accountName, initials: initials, imageURL: imageURL)
footer.onPress = { [weak self] in self?.onProfilePress() }
}
@available(iOS 18.0, *)
private func configureTabBar(_ controller: UITabBarController, footer: SidebarAccountButton) {
let destinations = controller.tabs.compactMap { $0 as? UITabGroup }.flatMap { $0.children }
let selected = destinations.first { $0 === controller.selectedTab }
let contextualTab = selected ?? footer.contextualTab ?? destinations.first
footer.contextualTab = contextualTab
for tab in destinations {
let placement: UITab.Placement = tab === contextualTab ? .fixed : .sidebarOnly
if tab.preferredPlacement != placement {
tab.preferredPlacement = placement
}
}
}
@available(iOS 18.0, *)
private func configureGroups(_ controller: UITabBarController) {
// Reuse the router's UITab instances so selection and stack state stay native.
if !controller.tabs.contains(where: { $0.identifier == "otunes.library" }) {
let tabs = controller.tabs
guard tabs.count >= 9 else { return }
let selected = controller.selectedTab
func tab(_ route: String) -> UITab? {
tabs.first { $0.identifier == route }
}
let library = ["library", "(artists)", "(albums)", "(songs)", "(recent)"].compactMap(tab)
let playlists = ["(playlists)", "(favorites)"].compactMap(tab)
guard library.count == 5, playlists.count == 2,
let home = tab("home"), let search = tab("search") else { return }
let libraryGroup = UITabGroup(
title: "Library", image: nil, identifier: "otunes.library", children: library,
viewControllerProvider: { _ in UIViewController() })
let playlistGroup = UITabGroup(
title: "Playlists", image: nil, identifier: "otunes.playlists", children: playlists,
viewControllerProvider: { _ in UIViewController() })
// UIKit requires a managing controller to display the selected child of a group.
let libraryNavigation = UINavigationController()
libraryNavigation.isNavigationBarHidden = true
libraryGroup.managingNavigationController = libraryNavigation
let playlistNavigation = UINavigationController()
playlistNavigation.isNavigationBarHidden = true
playlistGroup.managingNavigationController = playlistNavigation
libraryGroup.sidebarAppearance = .rootSection
playlistGroup.sidebarAppearance = .rootSection
libraryGroup.preferredPlacement = .sidebarOnly
playlistGroup.preferredPlacement = .sidebarOnly
home.preferredPlacement = .fixed
search.preferredPlacement = .pinned
let contextualTab = (library + playlists).first { $0 === selected } ?? library.first
for tab in library + playlists {
tab.preferredPlacement = tab === contextualTab ? .fixed : .sidebarOnly
}
let delegate = controller.delegate
controller.delegate = nil
controller.setTabs([home, search, libraryGroup, playlistGroup], animated: false)
controller.selectedTab = selected
controller.delegate = delegate
}
}
}
@available(iOS 18.0, *)
private final class SidebarAccountButton: UIView {
var onPress: (() -> Void)?
var contextualTab: UITab?
private let button = UIButton(type: .system)
private let avatar = UILabel()
private let imageView = UIImageView()
private var currentURL: String?
private var imageTask: URLSessionDataTask?
override init(frame: CGRect) {
super.init(frame: frame)
let separator = UIView()
separator.backgroundColor = .separator
addSubview(separator)
addSubview(button)
button.addSubview(avatar)
avatar.addSubview(imageView)
avatar.backgroundColor = .secondarySystemFill
avatar.textColor = .white
avatar.font = .systemFont(ofSize: 13, weight: .semibold)
avatar.textAlignment = .center
avatar.layer.cornerRadius = 16
avatar.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
button.contentHorizontalAlignment = .leading
button.titleLabel?.font = .systemFont(ofSize: 17, weight: .medium)
button.setTitleColor(.white, for: .normal)
button.addAction(UIAction { [weak self] _ in self?.onPress?() }, for: .touchUpInside)
for view in [separator, button, avatar, imageView] {
view.translatesAutoresizingMaskIntoConstraints = false
}
NSLayoutConstraint.activate([
separator.topAnchor.constraint(equalTo: topAnchor),
separator.leadingAnchor.constraint(equalTo: leadingAnchor),
separator.trailingAnchor.constraint(equalTo: trailingAnchor),
separator.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale),
button.topAnchor.constraint(equalTo: topAnchor),
button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
button.bottomAnchor.constraint(equalTo: bottomAnchor),
avatar.leadingAnchor.constraint(equalTo: button.leadingAnchor),
avatar.centerYAnchor.constraint(equalTo: button.centerYAnchor),
avatar.widthAnchor.constraint(equalToConstant: 32),
avatar.heightAnchor.constraint(equalToConstant: 32),
imageView.topAnchor.constraint(equalTo: avatar.topAnchor),
imageView.bottomAnchor.constraint(equalTo: avatar.bottomAnchor),
imageView.leadingAnchor.constraint(equalTo: avatar.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: avatar.trailingAnchor),
])
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 44, bottom: 0, right: 0)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func systemLayoutSizeFitting(
_ targetSize: CGSize,
withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
verticalFittingPriority: UILayoutPriority
) -> CGSize {
CGSize(width: targetSize.width, height: 76)
}
func update(name: String, initials: String, imageURL: String?) {
button.setTitle(name, for: .normal)
button.accessibilityLabel = "Open profile, " + name
avatar.text = initials
guard imageURL != currentURL else { return }
currentURL = imageURL
imageTask?.cancel()
imageView.image = nil
guard let imageURL, let url = URL(string: imageURL) else { return }
imageTask = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
guard let data, let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
guard let self, self.currentURL == imageURL else { return }
self.imageView.image = image
}
}
imageTask?.resume()
}
deinit { imageTask?.cancel() }
}