import SwiftUI /// App-wide UI state: tabs, the now-playing sheet, menus and toasts. @MainActor final class UIState: ObservableObject { static let shared = UIState() @Published var tab = 0 @Published var nowPlaying = false @Published var menu: MenuSheet? @Published var toast: String? @Published var libraryPath: [LibraryRoute] = [] @Published var addToPlaylist: [Song]? @Published var editTags: [Song]? @Published var details: Song? private var toastTask: Task? func show(_ text: String) { toastTask?.cancel() withAnimation(.spring(response: 0.3)) { toast = text } toastTask = Task { try? await Task.sleep(nanoseconds: 2_400_000_000) if !Task.isCancelled { withAnimation(.easeOut) { toast = nil } } } } /// Standard per-song menu (Android MainActivity song sheet). func songMenu(_ s: Song, in list: [Song]? = nil, playlist: Playlists.PL? = nil, index: Int? = nil) { let player = Player.shared, stats = PlayStats.shared var items: [MenuSheet.Item] = [ .init("Play next", "text.insert") { player.playNext([s]); self.show("Plays next") }, .init("Add to queue", "text.append") { player.enqueue([s]); self.show("Added to queue") }, .init("Add to playlist…", "music.note.list") { self.addToPlaylist = [s] }, .init(stats.fav(s) ? "Remove from favourites" : "Add to favourites", stats.fav(s) ? "heart.slash" : "heart") { stats.setFav(s, !stats.fav(s)) }, ] if !s.album.isEmpty { items.append(.init("Go to album", "square.stack") { if let g = Library.shared.albums.first(where: { $0.id == "album:" + s.albumKey }) { self.go(.group(g)) } }) } items.append(.init("Go to artist", "person") { if let g = Library.shared.artists.first(where: { $0.title == s.groupArtist }) { self.go(.group(g)) } }) if !s.isStream { items.append(.init("Edit tags…", "pencil") { self.editTags = [s] }) items.append(.init("Details", "info.circle") { self.details = s }) items.append(.init("Share", "square.and.arrow.up") { share([s.url]) }) } if let pl = playlist, let index { items.append(.init("Remove from playlist", "minus.circle") { Playlists.shared.removeAt(pl, IndexSet(integer: index)) }) } if !s.isStream { items.append(.init("Delete file", "trash", destructive: true) { self.menu = MenuSheet(title: "Delete \(s.displayTitle)?", subtitle: "The file is removed from your iPhone.", items: [.init("Delete", "trash", destructive: true) { Library.shared.delete(s) }]) }) } menu = MenuSheet(title: s.displayTitle, subtitle: s.subtitle, song: s, items: items) } func groupMenu(_ g: Library.Group) { let player = Player.shared menu = MenuSheet(title: g.title, subtitle: g.subtitle, song: g.cover, items: [ .init("Play", "play.fill") { player.playList(g.songs) }, .init("Shuffle", "shuffle") { player.playShuffled(g.songs) }, .init("Play next", "text.insert") { player.playNext(g.songs); self.show("Plays next") }, .init("Add to queue", "text.append") { player.enqueue(g.songs); self.show("Added to queue") }, .init("Add to playlist…", "music.note.list") { self.addToPlaylist = g.songs }, .init("Edit tags of all songs…", "pencil") { self.editTags = g.songs }, ]) } func go(_ r: LibraryRoute) { nowPlaying = false tab = 0 libraryPath.append(r) } } struct MenuSheet: Identifiable { struct Item: Identifiable { let id = UUID() let title: String let icon: String var destructive = false let action: () -> Void init(_ t: String, _ i: String, destructive: Bool = false, _ a: @escaping () -> Void) { title = t; icon = i; self.destructive = destructive; action = a } } let id = UUID() var title: String var subtitle = "" var song: Song? var items: [Item] } enum LibraryRoute: Hashable { case group(Library.Group) case smart(String) case playlist(UUID) } func share(_ urls: [URL]) { let vc = UIActivityViewController(activityItems: urls, applicationActivities: nil) guard let root = UIApplication.shared.connectedScenes.compactMap({ ($0 as? UIWindowScene)?.keyWindow }).first?.rootViewController else { return } var top = root while let p = top.presentedViewController { top = p } vc.popoverPresentationController?.sourceView = top.view top.present(vc, animated: true) } struct RootView: View { @EnvironmentObject var theme: Theme @EnvironmentObject var ui: UIState @EnvironmentObject var player: Player @EnvironmentObject var prefs: Prefs @EnvironmentObject var scrobbler: Scrobbler @Environment(\.colorScheme) var scheme var body: some View { let p = theme.palette ZStack(alignment: .bottom) { Group { switch ui.tab { case 1: PlaylistsView() case 2: SettingsView() default: LibraryView() } } .frame(maxWidth: .infinity, maxHeight: .infinity) .safeAreaInset(edge: .bottom) { Color.clear.frame(height: player.current == nil ? 80 : 168) } VStack(spacing: 0) { if player.current != nil { MiniPlayer() .padding(.horizontal, 12) .padding(.bottom, 8) .transition(.move(edge: .bottom).combined(with: .opacity)) } NavBar() } if prefs.bassShape && !prefs.lowPower && player.current != nil && !ui.nowPlaying { BassShapeView(playing: player.isPlaying) .frame(width: 56, height: 56) .allowsHitTesting(false) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) .padding(.leading, 6) .padding(.bottom, 170) } if let t = ui.toast ?? scrobbler.toast { Toast(text: t) .padding(.bottom, player.current == nil ? 96 : 184) .transition(.move(edge: .bottom).combined(with: .opacity)) .onAppear { if scrobbler.toast != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 2.4) { scrobbler.toast = nil } } } } } .surface(p) .preferredColorScheme(prefs.themeMode == "system" ? nil : (prefs.themeMode == "dark" ? .dark : .light)) .tint(p.cPrimary) .fullScreenCover(isPresented: $ui.nowPlaying) { NowPlayingView().environmentObjects() } .sheet(item: $ui.menu) { m in MenuSheetView(menu: m).environmentObjects() } .sheet(isPresented: Binding(get: { ui.addToPlaylist != nil }, set: { if !$0 { ui.addToPlaylist = nil } })) { AddToPlaylistSheet(songs: ui.addToPlaylist ?? []).environmentObjects() } .sheet(isPresented: Binding(get: { ui.editTags != nil }, set: { if !$0 { ui.editTags = nil } })) { TagEditorView(songs: ui.editTags ?? []).environmentObjects() } .sheet(item: $ui.details) { s in DetailsSheet(song: s).environmentObjects() } .onAppear { theme.systemDark = scheme == .dark } .onChange(of: scheme) { theme.systemDark = $0 == .dark } .onChange(of: prefs.themeMode) { _ in theme.update() } .onChange(of: prefs.colorSource) { _ in theme.update() } .onChange(of: prefs.customColor) { _ in theme.update() } } } extension View { /// Sheets and covers don't inherit environment objects reliably across presentations. func environmentObjects() -> some View { environmentObject(Theme.shared) .environmentObject(UIState.shared) .environmentObject(Player.shared) .environmentObject(Prefs.shared) .environmentObject(Library.shared) .environmentObject(Playlists.shared) .environmentObject(PlayStats.shared) .environmentObject(Scrobbler.shared) } } /// Material 3 navigation bar with a pill indicator. struct NavBar: View { @EnvironmentObject var theme: Theme @EnvironmentObject var ui: UIState var body: some View { let p = theme.palette HStack { item(0, "Library", "music.note.house") item(1, "Playlists", "music.note.list") item(2, "Settings", "gearshape") } .padding(.top, 10) .padding(.bottom, 4) .background(p.cSurfaceC.ignoresSafeArea(edges: .bottom)) } private func item(_ i: Int, _ title: String, _ icon: String) -> some View { let p = theme.palette let sel = ui.tab == i return Button { if ui.tab == i && i == 0 { ui.libraryPath = [] } withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) { ui.tab = i } } label: { VStack(spacing: 4) { Image(systemName: icon) .font(.system(size: 20, weight: sel ? .semibold : .regular)) .foregroundColor(sel ? p.cOnSecondaryC : p.cOnSurfaceVar) .frame(width: 64, height: 32) .background(Capsule().fill(sel ? p.cSecondaryC : .clear)) Text(title) .font(.system(size: 12, weight: sel ? .semibold : .medium)) .foregroundColor(sel ? p.cOnSurface : p.cOnSurfaceVar) } .frame(maxWidth: .infinity) .contentShape(Rectangle()) } .buttonStyle(.plain) } } /// Floating mini player card above the nav bar (cover cookie, title, play, next, wavy progress). struct MiniPlayer: View { @EnvironmentObject var theme: Theme @EnvironmentObject var player: Player @EnvironmentObject var ui: UIState var body: some View { let p = theme.palette TimelineView(.periodic(from: .now, by: 0.5)) { _ in VStack(spacing: 2) { HStack(spacing: 12) { CookieView(image: player.art, playing: player.isPlaying, small: true) .frame(width: 64, height: 64) VStack(alignment: .leading, spacing: 2) { Text(player.current?.displayTitle ?? "") .font(.system(size: 17, weight: .bold)) .foregroundColor(p.cOnPrimaryC) .lineLimit(1) Text(player.current?.displayArtist ?? "") .font(.system(size: 15)) .foregroundColor(p.cPrimary) .lineLimit(1) } Spacer(minLength: 4) PlayButton(playing: player.isPlaying) { player.toggle() } .frame(width: 64, height: 48) IconButton(icon: "forward.end.fill", size: 40, tint: p.cOnPrimaryC) { player.next() } } WavySeekBar(position: player.position, duration: player.duration, playing: player.isPlaying, height: 22) { player.seek($0) } } .padding(.leading, 10) .padding(.trailing, 8) .padding(.top, 8) .padding(.bottom, 4) .background( RoundedRectangle(cornerRadius: 28, style: .continuous) .fill(LinearGradient(colors: [Color(rgb: Palette.mix(p.primaryContainer, p.surfaceHigh, 0.35)), Color(rgb: Palette.mix(p.primaryContainer, p.surfaceHigh, 0.6))], startPoint: .topLeading, endPoint: .bottomTrailing)) ) .contentShape(Rectangle()) .onTapGesture { ui.nowPlaying = true } .gesture(DragGesture(minimumDistance: 20).onEnded { g in if g.translation.height < -40 { ui.nowPlaying = true } else if g.translation.width < -60 { player.next() } else if g.translation.width > 60 { player.prev() } }) } } } /// Bottom sheet with a header and a list of actions. struct MenuSheetView: View { let menu: MenuSheet @EnvironmentObject var theme: Theme @Environment(\.dismiss) var dismiss var body: some View { let p = theme.palette VStack(alignment: .leading, spacing: 0) { HStack(spacing: 14) { if let s = menu.song { CoverThumb(song: s, size: 52, radius: 12) } VStack(alignment: .leading, spacing: 2) { Text(menu.title).font(.system(size: 18, weight: .semibold)).foregroundColor(p.cOnSurface).lineLimit(2) if !menu.subtitle.isEmpty { Text(menu.subtitle).font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar).lineLimit(2) } } } .padding(.horizontal, 24) .padding(.top, 24) .padding(.bottom, 12) ScrollView { VStack(spacing: 0) { ForEach(menu.items) { it in Button { dismiss() DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { it.action() } } label: { HStack(spacing: 18) { Image(systemName: it.icon).frame(width: 24) Text(it.title).font(.system(size: 16)) Spacer() } .foregroundColor(it.destructive ? Color(rgb: p.error) : p.cOnSurface) .padding(.horizontal, 24) .padding(.vertical, 14) .contentShape(Rectangle()) } .buttonStyle(.plain) } } } } .presentationDetents([.medium, .large]) .presentationDragIndicator(.visible) .presentationBackground(p.cSurfaceLow) .presentationCornerRadius(28) } }