Repository Public
1// SP Music iOS2// File: Features/NowPlaying/NowPlayingView.swift3// Description: Full player: cover, transport, source badge, queue, lyrics.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import SPMusicCore9import SwiftUI1011/// The full player. The backdrop is the cover itself, blurred once — a still image, so it costs nothing while the12/// music plays.13struct NowPlayingView: View {14 @Environment(AppEnvironment.self) private var env15 @Environment(\.dismiss) private var dismiss16 @Environment(\.horizontalSizeClass) private var hSize17 @Environment(\.verticalSizeClass) private var vSize18 enum Panel { case none, queue, lyrics }19 @State private var panel = Panel.none20 @State private var backdrop: UIImage?21 @State private var playlistFor: Track?2223 var body: some View {24 let player = env.player25 ZStack {26 if let track = player.current {27 Group {28 if hSize == .regular && vSize == .regular || vSize == .compact { wide(track) } else { tall(track) }29 }30 .padding(.horizontal, 24).padding(.bottom, 12)31 } else {32 ContentUnavailableView("Rien en lecture", systemImage: "music.note", description: Text("Choisissez un titre dans la bibliothèque."))33 }34 }35 .frame(maxWidth: .infinity, maxHeight: .infinity)36 // As a background, the blurred cover takes the size of the screen instead of imposing its own.37 .background { background }38 .foregroundStyle(.white)39 .task(id: player.current?.artworkId) {40 guard let id = player.current?.artworkId else { backdrop = nil; return }41 let image = await env.artwork.image(id, size: 320)42 withAnimation(.easeInOut(duration: 0.6)) { backdrop = image }43 }44 .sheet(item: $playlistFor) { AddToPlaylistSheet(tracks: [$0]) }45 .presentationDragIndicator(.visible)46 }4748 private var background: some View {49 ZStack {50 Color.spBackground51 if let backdrop {52 GeometryReader { g in53 Image(uiImage: backdrop).resizable().aspectRatio(contentMode: .fill).frame(width: g.size.width, height: g.size.height).clipped()54 .blur(radius: 70, opaque: true).saturation(1.3).opacity(0.75)55 }56 }57 LinearGradient(colors: [.black.opacity(0.25), .black.opacity(0.75)], startPoint: .top, endPoint: .bottom)58 }59 .ignoresSafeArea()60 .accessibilityHidden(true)61 }6263 // iPhone portrait: everything stacked.64 private func tall(_ track: Track) -> some View {65 VStack(spacing: 0) {66 header67 Spacer(minLength: 8)68 switch panel {69 case .none: ArtworkView(id: track.artworkId, corner: 14).shadow(color: .black.opacity(0.5), radius: 24, y: 12)70 .scaleEffect(env.player.isPlaying ? 1 : 0.88).animation(.spring(response: 0.45, dampingFraction: 0.75), value: env.player.isPlaying)71 .padding(.horizontal, 4)72 case .queue: QueueView()73 case .lyrics: LyricsView(track: track)74 }75 Spacer(minLength: 16)76 controls(track)77 }78 }7980 // iPad and landscape: cover and controls on the left, queue or lyrics on the right.81 private func wide(_ track: Track) -> some View {82 VStack(spacing: 0) {83 header84 HStack(alignment: .center, spacing: 40) {85 VStack(spacing: 20) {86 ArtworkView(id: track.artworkId, corner: 14).shadow(color: .black.opacity(0.5), radius: 24, y: 12).frame(maxWidth: 420)87 controls(track).frame(maxWidth: 460)88 }89 .frame(maxWidth: .infinity)90 Group { if panel == .lyrics { LyricsView(track: track) } else { QueueView() } }91 .frame(maxWidth: .infinity, maxHeight: .infinity)92 }93 }94 }9596 private var header: some View {97 HStack {98 Button { dismiss() } label: { Image(systemName: "chevron.down").font(.title3.weight(.semibold)).frame(width: 44, height: 44) }99 .accessibilityLabel("Fermer le lecteur").accessibilityIdentifier("close-player")100 Spacer()101 SourceBadge()102 Spacer()103 Menu {104 if let t = env.player.current {105 Button { playlistFor = t } label: { Label("Ajouter à une liste de lecture…", systemImage: "text.badge.plus") }106 if env.downloadsModel.state(t.id) == nil {107 Button { Task { _ = await env.download(.track, t.id, confirmed: true) } } label: { Label("Télécharger", systemImage: "arrow.down.circle") }108 }109 }110 } label: { Image(systemName: "ellipsis").font(.title3.weight(.semibold)).frame(width: 44, height: 44) }111 .accessibilityLabel("Plus d'actions")112 }113 .padding(.top, 8)114 }115116 private func controls(_ track: Track) -> some View {117 let player = env.player118 return VStack(spacing: 18) {119 HStack(alignment: .center) {120 VStack(alignment: .leading, spacing: 3) {121 Text(track.title).font(.title2.bold()).lineLimit(1).accessibilityIdentifier("np-title")122 Text(track.artistName).font(.title3).foregroundStyle(.white.opacity(0.7)).lineLimit(1)123 }124 Spacer()125 Button { Task { await env.setFavorite(track: track, !track.favorite) } } label: {126 Image(systemName: track.favorite ? "heart.fill" : "heart").font(.title2).foregroundStyle(track.favorite ? Color.spEmber : .white).contentTransition(.symbolEffect(.replace))127 .frame(width: 44, height: 44)128 }129 .accessibilityLabel(track.favorite ? "Retirer des favoris" : "Ajouter aux favoris")130 }131 Scrubber()132 if let e = player.error {133 HStack {134 Label(e.message, systemImage: "exclamationmark.triangle.fill").font(.footnote).foregroundStyle(.yellow)135 Spacer()136 Button("Réessayer") { player.retry() }.font(.footnote.weight(.semibold))137 }138 }139 HStack {140 Button { player.setShuffle(!player.queue.shuffle) } label: { Image(systemName: "shuffle").font(.title3).foregroundStyle(player.queue.shuffle ? Color.spEmber : .white) }141 .accessibilityLabel("Lecture aléatoire").accessibilityValue(player.queue.shuffle ? "activée" : "désactivée").accessibilityIdentifier("shuffle")142 Spacer()143 Button { player.previous() } label: { Image(systemName: "backward.fill").font(.system(size: 30)) }.accessibilityLabel("Titre précédent").accessibilityIdentifier("previous")144 Spacer()145 Button { player.toggle() } label: {146 ZStack {147 Circle().fill(.white).frame(width: 72, height: 72)148 if player.isBuffering { ProgressView().tint(.black) }149 else { Image(systemName: player.isPlaying ? "pause.fill" : "play.fill").font(.system(size: 30)).foregroundStyle(.black).contentTransition(.symbolEffect(.replace)) }150 }151 }152 .accessibilityLabel(player.isPlaying ? "Pause" : "Lecture").accessibilityIdentifier("play-pause")153 Spacer()154 Button { player.next() } label: { Image(systemName: "forward.fill").font(.system(size: 30)) }.accessibilityLabel("Titre suivant").accessibilityIdentifier("next")155 Spacer()156 Button { player.cycleRepeat() } label: {157 Image(systemName: player.queue.repeatMode == .one ? "repeat.1" : "repeat").font(.title3).foregroundStyle(player.queue.repeatMode == .off ? .white : Color.spEmber)158 }159 .accessibilityLabel("Répétition")160 .accessibilityValue(player.queue.repeatMode == .off ? "désactivée" : player.queue.repeatMode == .all ? "toute la file" : "ce titre").accessibilityIdentifier("repeat")161 }162 .buttonStyle(.plain)163 HStack(spacing: 10) {164 Image(systemName: "speaker.fill").font(.caption).foregroundStyle(.white.opacity(0.6))165 SystemVolumeSlider().frame(height: 28).accessibilityLabel("Volume")166 Image(systemName: "speaker.wave.3.fill").font(.caption).foregroundStyle(.white.opacity(0.6))167 }168 HStack {169 Button { withAnimation(.snappy) { panel = panel == .lyrics ? .none : .lyrics } } label: {170 Image(systemName: "quote.bubble").foregroundStyle(panel == .lyrics ? Color.spEmber : .white).frame(width: 44, height: 36)171 }172 .accessibilityLabel("Paroles").accessibilityIdentifier("lyrics-button")173 Spacer()174 VStack(spacing: 2) {175 RoutePickerButton().frame(width: 30, height: 30)176 if !env.audioSession.route.name.isEmpty { Text(env.audioSession.route.name).font(.caption2).foregroundStyle(.white.opacity(0.6)).lineLimit(1) }177 }178 .accessibilityElement(children: .combine).accessibilityLabel("Sortie audio : \(env.audioSession.route.name)")179 Spacer()180 Button { withAnimation(.snappy) { panel = panel == .queue ? .none : .queue } } label: {181 Image(systemName: "list.bullet").foregroundStyle(panel == .queue ? Color.spEmber : .white).frame(width: 44, height: 36)182 }183 .accessibilityLabel("File d'attente").accessibilityIdentifier("queue-button")184 }185 .buttonStyle(.plain).font(.title3)186 }187 }188}189190/// Where the sound comes from and what the file is. It states facts only: the file's format, whether it is read191/// from the device or streamed, and the output's current rate — never a "bit-perfect" promise the app cannot check.192struct SourceBadge: View {193 @Environment(AppEnvironment.self) private var env194 @State private var showDetails = false195 var body: some View {196 let player = env.player197 if let track = player.current {198 Button { showDetails = true } label: {199 HStack(spacing: 6) {200 Image(systemName: player.source?.isLocal == true ? "arrow.down.circle.fill" : "dot.radiowaves.left.and.right")201 Text(label(track)).lineLimit(1).minimumScaleFactor(0.75)202 }203 .font(.caption.weight(.semibold)).padding(.horizontal, 10).padding(.vertical, 6).background(.white.opacity(0.14), in: .capsule)204 }205 .buttonStyle(.plain)206 .accessibilityIdentifier("source-badge")207 .accessibilityLabel(label(track))208 .popover(isPresented: $showDetails) { details(track).presentationCompactAdaptation(.popover) }209 }210 }211 private func label(_ t: Track) -> String {212 guard let s = env.player.source else { return "Préparation…" }213 let what = s.variant == .compat ? "AAC 256" : t.formatDescription.replacingOccurrences(of: " bits / ", with: "/").replacingOccurrences(of: " · ", with: " ")214 return "\(s.isLocal ? "Sur l'appareil" : "Diffusion") · \(what)"215 }216 private func details(_ t: Track) -> some View {217 let route = env.audioSession.route218 return VStack(alignment: .leading, spacing: 10) {219 row("Fichier", env.player.source?.variant == .compat ? "Rendu AAC 256 kbit/s (l'original est \(t.formatDescription))" : t.formatDescription)220 row("Source", env.player.source?.isLocal == true ? "Fichier téléchargé sur cet appareil" : "Diffusion depuis MacLustr")221 row("Sortie", route.name.isEmpty ? "—" : route.name + (route.sampleRate > 0 ? " · \(Int(route.sampleRate / 1000 * 10) / 10) kHz" : ""))222 Text(route.kind == .bluetooth ? "En Bluetooth, le son est toujours recompressé par le système avant d'atteindre les écouteurs."223 : "Le décodage est fait par iOS. La sortie peut rééchantillonner : l'app indique le format du fichier, pas une garantie « bit-perfect ».")224 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)225 }226 .padding(16).frame(width: 300)227 }228 private func row(_ k: String, _ v: String) -> some View {229 VStack(alignment: .leading, spacing: 1) { Text(k).font(.caption).foregroundStyle(.secondary); Text(v).font(.subheadline) }230 }231}232233struct QueueView: View {234 @Environment(AppEnvironment.self) private var env235 var body: some View {236 let player = env.player237 VStack(alignment: .leading, spacing: 8) {238 HStack {239 Text("File d'attente").font(.headline)240 Spacer()241 if !player.queue.upcoming.isEmpty { Button("Vider") { player.clearUpcoming() }.font(.subheadline) }242 }243 List {244 ForEach(Array(player.queue.tracks.enumerated()), id: \.offset) { i, t in245 Button { player.jump(to: i) } label: {246 HStack(spacing: 10) {247 ArtworkView(id: t.artworkId, side: 40, corner: 5)248 VStack(alignment: .leading, spacing: 1) {249 Text(t.title).lineLimit(1).foregroundStyle(i == player.queue.index ? Color.spEmber : .white)250 Text(t.artistName).font(.caption).foregroundStyle(.white.opacity(0.6)).lineLimit(1)251 }252 Spacer()253 if i == player.queue.index { PlayingBars(animating: player.isPlaying && !player.isBuffering) }254 }255 .opacity(i < player.queue.index ? 0.45 : 1)256 }257 .listRowBackground(Color.clear).listRowSeparatorTint(.white.opacity(0.12)).listRowInsets(EdgeInsets(top: 6, leading: 0, bottom: 6, trailing: 0))258 .accessibilityIdentifier("queue-row")259 }260 .onMove { from, to in if let f = from.first { player.move(from: f, to: to > f ? to - 1 : to) } }261 .onDelete { idx in for i in idx.sorted(by: >) { player.remove(at: i) } }262 }263 .listStyle(.plain).scrollContentBackground(.hidden).environment(\.editMode, .constant(.active))264 }265 }266}267268/// Lyrics with the current line lit. Kept on the device with downloaded tracks; fetched otherwise.269struct LyricsView: View {270 @Environment(AppEnvironment.self) private var env271 let track: Track272 @State private var lyrics: Lyrics?273 @State private var loaded = false274275 var body: some View {276 let ms = Int(env.player.position * 1000)277 Group {278 if let lyrics, lyrics.hasText {279 let current = lyrics.lines.lastIndex { $0.t <= ms + 150 }280 ScrollViewReader { proxy in281 ScrollView {282 LazyVStack(alignment: .leading, spacing: 14) {283 ForEach(Array(lyrics.lines.enumerated()), id: \.offset) { i, line in284 Text(line.text).font(.title2.weight(.bold)).foregroundStyle(i == current ? .white : .white.opacity(0.35)).id(i)285 .frame(maxWidth: .infinity, alignment: .leading).contentShape(.rect)286 .onTapGesture { env.player.seek(to: Double(line.t) / 1000) }287 }288 }289 .padding(.vertical, 40)290 }291 .scrollIndicators(.hidden)292 .onChange(of: current) { _, new in if let new { withAnimation(.easeInOut(duration: 0.4)) { proxy.scrollTo(new, anchor: .center) } } }293 }294 } else if loaded {295 ContentUnavailableView(lyrics?.state == "empty" ? "Titre instrumental" : "Pas de paroles", systemImage: "quote.bubble",296 description: Text(env.isOnline ? "Aucune parole n'est disponible pour ce titre." : "Les paroles de ce titre ne sont pas sur l'appareil."))297 } else { ProgressView().tint(.white) }298 }299 .task(id: track.id) {300 loaded = false; lyrics = await env.db.lyrics(trackId: track.id)301 if lyrics == nil, env.isOnline, track.lyricsState == "ready" || track.lyricsState == "empty" { lyrics = try? await env.api.lyrics(trackId: track.id) }302 loaded = true303 }304 }305}306