import SwiftUI import UIKit /// The tab bar, a navigation stack per tab, the mini player and the Now Playing sheet. /// On an unfolded iPhone Duo each tab splits at the hinge: Now Playing docks on one side, the tab /// (or the stems, queue and lyrics deck) on the other, and the tabs stay in the system's own bar. struct RootView: View { @State private var ui = Ui(overlays: Overlays()) @State private var art: ArtHue? private var g: AppGraph { .shared } var body: some View { let s = g.settings let base = Palette.of(s.theme, s.accent) let p = s.albumTheme ? art.map { base.art($0, mode: s.theme) } ?? base : base bar .modifier(GlassMiniPlayerHost()) // Folded on the Duo the app stays upright (the window's trailing inset gives the Duo away). .onGeometryChange(for: CGFloat.self) { $0.safeAreaInsets.trailing } action: { ui.sawInsets(trailing: $0, upright: vSize == .regular) } .background(p.bg.ignoresSafeArea()) .onChange(of: ui.tabs) { _, _ in ui.ensureValidTab() } .onChange(of: phase) { _, ph in if ph == .active { ui.resumed() } } .fullScreenCover(isPresented: Binding(get: { ui.nowPlayingOpen }, set: { ui.nowPlayingOpen = $0 })) { NowPlayingScreen() .overlayHost(ui.overlays, level: 1) .environment(ui) .environment(\.palette, p) .preferredColorScheme(s.theme == .White ? .light : .dark) .tint(p.accent) } .overlayHost(ui.overlays, level: 0) .onChange(of: g.playback.message) { _, m in if let m { ui.overlays.hud(m.text, "info.circle") } } .environment(ui) .environment(\.palette, p) .preferredColorScheme(s.theme == .White ? .light : .dark) .tint(p.accent) .task(id: "\(g.playback.current?.track.thumb ?? "")|\(s.albumTheme)") { guard s.albumTheme, let thumb = g.playback.current?.track.thumb else { art = nil; return } let a = await artHue(thumb) withAnimation(.easeInOut(duration: 0.4)) { art = a } } } @Environment(\.verticalSizeClass) private var vSize @Environment(\.scenePhase) private var phase private enum BarItem: Hashable { case deck, tab(Tab) } private var selection: Binding { Binding(get: { ui.showsDeck ? BarItem.deck : .tab(ui.tab) }, set: { if case .tab(let t) = $0 { ui.selectTab(t) } else { ui.showDeck() } }) } /// The bar always holds the same slots. Unfolded with something playing, Now Playing takes /// the place of the last tab before Settings (iOS folds a sixth item into "More"), so folding /// and unfolding swaps one item in place and nothing else moves. private var slots: [BarItem] { let all = Tab.layout(g.settings.tabLayout) var items = all.map { BarItem.tab($0) } guard ui.hasDeckTab else { return items } if all.count >= Tab.maxVisible, let i = all.lastIndex(where: { $0 != .Settings }) { items[i] = .deck } else { items.insert(.deck, at: all.lastIndex(of: .Settings) ?? items.count) } return items } private var bar: some View { TabView(selection: selection) { ForEach(Array(slots.enumerated()), id: \.offset) { _, item in switch item { case .deck: DuoPane { NowPlayingDeck() } .tabItem { Label("Now Playing", systemImage: "waveform") } .tag(item) case .tab(let t): page(t).tabItem { Label(t.rawValue, systemImage: t.icon) }.tag(item) } } } .transaction { $0.animation = nil } } private func page(_ t: Tab) -> some View { DuoPane { NavigationStack(path: ui.path(t)) { root(t).miniPlayerRoom() .navigationDestination(for: Route.self) { destination($0).miniPlayerRoom() } } .modifier(FloatingMiniPlayer()) } } @ViewBuilder private func root(_ t: Tab) -> some View { switch t { case .Library: LibraryHome() case .Songs: SongsScreen() case .Albums: AlbumsScreen() case .Artists: ArtistsScreen() case .Genres: GenresScreen() case .Playlists: PlaylistsScreen() case .Search: SearchScreen() case .Downloads: DownloadsScreen() case .Settings: SettingsScreen() } } @ViewBuilder private func destination(_ r: Route) -> some View { switch r { case .Artists: ArtistsScreen() case .Albums: AlbumsScreen() case .Songs: SongsScreen() case .RecentlyAdded: SongsScreen(recent: true) case .Playlists: PlaylistsScreen() case .Genres: GenresScreen() case .Downloads: DownloadsScreen() case .DownloadQueue: DownloadQueueScreen() case .TabBar: TabBarScreen() case .WebRadio: WebRadioScreen() case .GenrePage(let g): GenreScreen(genre: g) case .Eq: EqScreen() case .EqFilters(let id): EqFiltersScreen(profileId: id) case .EqFilterPage(let id, let f): EqFilterPage(profileId: id, filterId: f) case .Servers: ServersScreen() case .ServerList: ServerListScreen() case .Server(let id): ServerScreen(id: id) case .StemServer: StemServerScreen() case .Quality: QualityScreen() case .Storage: StorageScreen() case .Appearance: AppearanceScreen() case .NowPlayingOptions: NowPlayingOptionsScreen() case .StemEditor: StemEditorScreen() case .LibraryLayout: LibraryLayoutScreen() case .About: AboutScreen() case .ArtistPage(let a): ArtistScreen(artist: a) case .AlbumPage(let a): AlbumScreen(album: a) case .PlaylistPage(let pl): PlaylistScreen(playlist: pl) case .StemPlaylistPage(let id): StemPlaylistScreen(id: id) } } } /// iOS 26.1 and up put the mini player in the tab bar's glass accessory; older ones float a card over each tab. private let glassAccessory: Bool = { if #available(iOS 26.1, *) { return true } else { return false } }() private struct GlassMiniPlayerHost: ViewModifier { @Environment(Ui.self) private var ui private var g: AppGraph { .shared } func body(content: Content) -> some View { if #available(iOS 26.1, *) { content .tabViewBottomAccessory(isEnabled: g.playback.current != nil && !ui.split) { MiniPlayer() } .tabBarMinimizeBehavior(.onScrollDown) } else { content } } } /// Floats over the screens; each screen leaves room for it so nothing ends up underneath. private struct FloatingMiniPlayer: ViewModifier { @Environment(Ui.self) private var ui private var g: AppGraph { .shared } func body(content: Content) -> some View { if glassAccessory || ui.split { content } else { content .overlay(alignment: .bottom) { if g.playback.current != nil { MiniPlayer().transition(.move(edge: .bottom).combined(with: .opacity)) } } .animation(.spring(duration: 0.35), value: g.playback.current != nil) } } } private struct MiniPlayerRoom: ViewModifier { @Environment(Ui.self) private var ui private var g: AppGraph { .shared } func body(content: Content) -> some View { content.safeAreaInset(edge: .bottom, spacing: 0) { if !glassAccessory && !ui.split && g.playback.current != nil { Color.clear.frame(height: 66) } } } } private extension View { func miniPlayerRoom() -> some View { modifier(MiniPlayerRoom()) } } /// One tab's content, split at the iPhone Duo's hinge (the system's division region): the tab /// (or, for the Now Playing item, the deck) on one side, docked Now Playing on the other, left /// and right trading places with the deck's swap button. It measures inside the tab's safe area, /// so the system's tab bar is never covered. Anywhere without a hinge it's just the tab, and the /// tab stays put in the view tree so its scroll state survives folding, unfolding and swapping. private struct DuoPane: View { @ViewBuilder var content: Content @Environment(Ui.self) private var ui @AppStorage("duoSwap") private var swap = false @Environment(\.palette) private var p private var g: AppGraph { .shared } var body: some View { GeometryReader { geo in let hinge = Self.cut(geo) // Unfolded upright (hinge across) never splits: the app turns to landscape instead. let cut = hinge?.vertical == true ? hinge : nil let flip = duoSwapEnabled && swap && cut?.vertical == true let layout = cut?.vertical == false ? AnyLayout(VStackLayout(spacing: cut?.gap ?? 0)) : AnyLayout(HStackLayout(spacing: cut?.gap ?? 0)) layout { content .environment(\.layoutDirection, .leftToRight) // The tab's navigation picks up the window's right-hand inset (the status column) // even though it ends at the hinge, so the bar and rows stopped short of it. The // hinge side never needs an inset. .ignoresSafeArea(.container, edges: cut?.vertical == true ? (flip ? .leading : .trailing) : []) .frame(width: cut.map { $0.vertical ? (flip ? $0.second : $0.first) : geo.size.width } ?? geo.size.width, height: cut.map { $0.vertical ? geo.size.height : $0.first } ?? geo.size.height) if let cut { NowPlayingScreen(docked: true) .environment(\.layoutDirection, .leftToRight) .frame(width: cut.vertical ? (flip ? cut.first : cut.second) : geo.size.width, height: cut.vertical ? geo.size.height : cut.second) } } // Right-to-left lays the same two children out mirrored, so swapping doesn't rebuild either. .environment(\.layoutDirection, flip ? .rightToLeft : .leftToRight) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) // The hinge gap shows whatever is behind; paint it so the two sides read as one. .background(p.bg.ignoresSafeArea()) .animation(.spring(duration: 0.4, bounce: 0.1), value: flip) .onChange(of: hinge != nil, initial: true) { _, on in ui.setUnfolded(on) } .onChange(of: cut != nil, initial: true) { _, on in ui.setSplit(on) } } } /// Where the hinge cuts the view: sizes of the two sides and the gap between them. private struct Cut { var vertical: Bool; var first: CGFloat; var gap: CGFloat; var second: CGFloat } private static func cut(_ geo: GeometryProxy) -> Cut? { let size = geo.size var c: Cut? // The hinge reports inactive while the phone lies flat, so ask for inactive regions too. if #available(iOS 27.1, *), let r = geo.reservedRegions(kind: .division, options: .includeInactive).first?.frame { let vertical = r.height >= r.width c = vertical ? Cut(vertical: true, first: r.minX, gap: r.width, second: size.width - r.maxX) : Cut(vertical: false, first: r.minY, gap: r.height, second: size.height - r.maxY) } else if UIDevice.current.userInterfaceIdiom == .phone, size.width >= 700, size.height >= 500 { // No region reported: only an unfolded Duo gives an iPhone this much room both ways. // The hinge sits at the middle of the screen, not of the safe area, so place it from there. let screenW = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.screen.bounds.width let half = ((screenW ?? size.width) / 2 - geo.frame(in: .global).minX).rounded() c = Cut(vertical: true, first: half - 12, gap: 24, second: size.width - half - 12) } else if UIDevice.current.userInterfaceIdiom == .phone, size.width >= 500, size.height >= 700 { // Unfolded but still upright: only marks the phone as unfolded so it turns to landscape. let half = (size.height / 2).rounded() c = Cut(vertical: false, first: half - 12, gap: 24, second: size.height - half - 12) } guard let c else { return nil } // A region that doesn't leave usable room on both sides isn't a hinge worth splitting at. return c.first > 200 && c.second > 200 ? c : nil } }