SPB Git

Repository Public

PlayerBar.swift 11.5 KB 199 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/PlayerBar.swift3// Description: Persistent player bar: seek bar, transport, volume, quality and source labels.4import SwiftUI5import SPMusicCore67/// Seek bar: shows the position and how much of a streamed file has arrived; while dragging, the thumb follows the8/// pointer and the player seeks once on release.9struct SeekBar: View {10    @Environment(AppModel.self) private var model11    var height: CGFloat = 412    @State private var dragValue: Double?13    @State private var hovering = false1415    var body: some View {16        let p = model.playback17        let duration = max(p.duration, 0.001)18        let value = dragValue ?? p.position19        GeometryReader { geo in20            let w = geo.size.width21            ZStack(alignment: .leading) {22                Capsule().fill(.primary.opacity(0.12))23                if p.sourceKind == .stream, p.bufferedFraction > 0, p.bufferedFraction < 0.999 { Capsule().fill(.primary.opacity(0.14)).frame(width: w * p.bufferedFraction) }24                Capsule().fill(hovering || dragValue != nil ? Color.accentColor : Color.primary.opacity(0.55)).frame(width: max(0, min(w, w * value / duration)))25                if hovering || dragValue != nil {26                    Circle().fill(.white).shadow(color: .black.opacity(0.3), radius: 1.5, y: 0.5).frame(width: 11, height: 11).offset(x: max(0, min(w, w * value / duration)) - 5.5)27                }28            }29            .frame(height: height).frame(maxHeight: .infinity)30            .contentShape(Rectangle())31            .gesture(DragGesture(minimumDistance: 0)32                .onChanged { g in dragValue = max(0, min(duration, Double(g.location.x / max(w, 1)) * duration)) }33                .onEnded { _ in if let v = dragValue { p.seek(to: v) }; dragValue = nil })34            .onHover { hovering = $0 }35        }36        .frame(height: 14)37        .disabled(p.currentTrack == nil)38        .accessibilityElement().accessibilityLabel("Position de lecture").accessibilityValue("\(Format.duration(seconds: value)) sur \(Format.duration(seconds: p.duration))")39        .accessibilityAdjustableAction { d in p.skip(by: d == .increment ? 10 : -10) }40    }41    var displayed: Double { dragValue ?? model.playback.position }42}4344struct TransportButtons: View {45    @Environment(AppModel.self) private var model46    var large = false47    var body: some View {48        let p = model.playback49        HStack(spacing: large ? 26 : 16) {50            Button { p.toggleShuffle() } label: { Image(systemName: "shuffle").font(.system(size: large ? 16 : 12, weight: .medium)).foregroundStyle(p.queue.shuffle ? Color.accentColor : .secondary) }51                .help("Lecture aléatoire").accessibilityLabel("Lecture aléatoire").accessibilityValue(p.queue.shuffle ? "activée" : "désactivée")52            Button { p.previous() } label: { Image(systemName: "backward.fill").font(.system(size: large ? 22 : 15)) }.help("Précédent").accessibilityLabel("Piste précédente")53            Button { p.togglePlay() } label: {54                ZStack {55                    if p.isBuffering && p.isPlaying { ProgressView().controlSize(large ? .regular : .small) }56                    else { Image(systemName: p.isPlaying ? "pause.fill" : "play.fill").font(.system(size: large ? 34 : 22)) }57                }58                .frame(width: large ? 48 : 30, height: large ? 48 : 30)59            }60            .help(p.isPlaying ? "Pause" : "Lecture").accessibilityLabel(p.isPlaying ? "Pause" : "Lecture")61            Button { p.next() } label: { Image(systemName: "forward.fill").font(.system(size: large ? 22 : 15)) }.help("Suivant").accessibilityLabel("Piste suivante")62            Button { p.cycleRepeat() } label: {63                Image(systemName: p.queue.repeatMode == .one ? "repeat.1" : "repeat").font(.system(size: large ? 16 : 12, weight: .medium)).foregroundStyle(p.queue.repeatMode == .off ? .secondary : Color.accentColor)64            }65            .help("Répétition").accessibilityLabel("Répétition").accessibilityValue(p.queue.repeatMode == .off ? "désactivée" : p.queue.repeatMode == .all ? "toute la file" : "ce titre")66        }67        .buttonStyle(.plain).disabled(p.currentTrack == nil)68    }69}7071struct VolumeSlider: View {72    @Environment(AppModel.self) private var model73    var width: CGFloat = 9074    var body: some View {75        @Bindable var settings = model.settings76        HStack(spacing: 5) {77            Image(systemName: settings.volume == 0 ? "speaker.slash.fill" : settings.volume < 0.4 ? "speaker.wave.1.fill" : "speaker.wave.2.fill").font(.system(size: 11)).foregroundStyle(.secondary).frame(width: 16)78                .onTapGesture { settings.volume = settings.volume == 0 ? 0.8 : 0; model.applyAudioSettings() }79            Slider(value: $settings.volume, in: 0...1) { _ in }.controlSize(.mini).frame(width: width)80                .onChange(of: settings.volume) { model.applyAudioSettings() }81                .accessibilityLabel("Volume")82        }83    }84}8586/// What is feeding the player right now, in three words.87struct SourceLabel: View {88    @Environment(AppModel.self) private var model89    var body: some View {90        let p = model.playback91        if let kind = p.sourceKind, p.currentTrack != nil {92            let (symbol, text): (String, String) = switch kind {93            case .local: ("internaldrive", "Fichier local")94            case .cache: ("internaldrive", "Cache local")95            case .stream: ("antenna.radiowaves.left.and.right", p.isRendition ? "Cluster · rendu AAC" : "Cluster MacLustr")96            case .file: ("doc", "Fichier ouvert")97            }98            Label(text, systemImage: symbol).font(.caption2).foregroundStyle(.secondary).labelStyle(.titleAndIcon)99        }100    }101}102103struct QualityLabel: View {104    @Environment(AppModel.self) private var model105    var body: some View {106        let p = model.playback107        if let t = p.currentTrack {108            // What is really being decoded when known, the catalogue's description otherwise.109            let text: String = {110                guard let i = p.info else { return Format.quality(of: t) }111                let name = Format.codecName(p.isRendition ? "aac" : (t.codec.isEmpty ? i.formatID : t.codec), container: t.container)112                if let b = i.bitDepth { return "\(name) · \(b) bits / \(Format.sampleRate(Int(i.sampleRate)))" }113                return t.bitrate.map { "\(name) · \(Int((Double($0) / 1000).rounded())) kb/s" } ?? "\(name) · \(Format.sampleRate(Int(i.sampleRate)))"114            }()115            Text(text).font(.caption2.monospacedDigit()).foregroundStyle(.secondary)116        }117    }118}119120struct PlayerBar: View {121    @Environment(AppModel.self) private var model122    @Environment(\.openWindow) private var openWindow123124    var body: some View {125        let p = model.playback126        HStack(spacing: 14) {127            // Now playing: cover, title, artist — click to open the immersive view.128            HStack(spacing: 10) {129                ArtworkView(artworkID: p.currentTrack?.artworkID, size: 46, cornerRadius: 5, externalKey: p.currentTrack?.externalFileURL != nil ? p.currentTrack?.id : nil)130                VStack(alignment: .leading, spacing: 2) {131                    Text(p.currentTrack?.title ?? "Aucun titre").font(.callout.weight(.medium)).lineLimit(1)132                    if let t = p.currentTrack {133                        Text([t.artistName, t.albumTitle].filter { !$0.isEmpty }.joined(separator: " — ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)134                    } else { Text("Choisissez un album pour commencer").font(.caption).foregroundStyle(.tertiary) }135                    if let m = p.message { Text(m).font(.caption2).foregroundStyle(.orange).lineLimit(1) }136                }137                if let t = p.currentTrack, t.externalFileURL == nil {138                    Button { model.toggleFavorite(t); refreshCurrent() } label: { Image(systemName: currentFavorite ? "heart.fill" : "heart").foregroundStyle(currentFavorite ? .pink : .secondary) }139                        .buttonStyle(.plain).help(currentFavorite ? "Retirer des favoris" : "Ajouter aux favoris").accessibilityLabel("Favori")140                }141            }142            .frame(minWidth: 180, idealWidth: 260, maxWidth: 300, alignment: .leading)143            .contentShape(Rectangle())144            .onTapGesture { if p.currentTrack != nil { withAnimation(.spring(duration: 0.35)) { model.showNowPlaying.toggle() } } }145            .contextMenu { if let t = p.currentTrack { TrackMenu(tracks: [t]) } }146147            VStack(spacing: 3) {148                TransportButtons()149                HStack(spacing: 8) {150                    Text(Format.duration(seconds: p.position)).font(.caption2.monospacedDigit()).foregroundStyle(.secondary).frame(width: 40, alignment: .trailing)151                    SeekBar()152                    Text(Format.duration(seconds: p.duration)).font(.caption2.monospacedDigit()).foregroundStyle(.secondary).frame(width: 40, alignment: .leading)153                }154            }155            .frame(maxWidth: 560)156157            HStack(spacing: 12) {158                VStack(alignment: .trailing, spacing: 2) { QualityLabel(); SourceLabel() }159                if let t = p.currentTrack, t.externalFileURL == nil { CurrentDownloadButton(trackID: t.id) }160                Button { model.showQueue.toggle() } label: { Image(systemName: "list.bullet").foregroundStyle(model.showQueue ? Color.accentColor : .secondary) }161                    .buttonStyle(.plain).help("File d’attente").accessibilityLabel("File d’attente")162                    .popover(isPresented: Binding(get: { model.showQueue && !model.showNowPlaying }, set: { model.showQueue = $0 }), arrowEdge: .top) { QueueView().frame(width: 360, height: 460) }163                Button { openWindow(id: "mini") } label: { Image(systemName: "pip").foregroundStyle(.secondary) }.buttonStyle(.plain).help("Mini-lecteur").accessibilityLabel("Mini-lecteur")164                VolumeSlider()165            }166            .frame(minWidth: 240, alignment: .trailing)167        }168        .padding(.horizontal, 16).padding(.vertical, 9)169        .frame(maxWidth: .infinity)170        .background(.bar)171        .overlay(alignment: .top) { Divider() }172        .task(id: "\(p.currentTrack?.id ?? "")-\(model.libraryRevision)") { refreshCurrent() }173    }174175    @State private var currentFavorite = false176    private func refreshCurrent() {177        guard let id = model.playback.currentTrack?.id, let s = model.store else { currentFavorite = false; return }178        Task { if let t = await s.track(id) { currentFavorite = t.favorite; model.playback.refreshTracks([t]) } }179    }180}181182/// Download state of the playing track, with the action that makes sense for it.183struct CurrentDownloadButton: View {184    @Environment(AppModel.self) private var model185    let trackID: String186    @State private var track: Track?187    var body: some View {188        Group {189            if let track {190                if let p = model.liveProgress[track.id] { ProgressRing(fraction: p.fraction).frame(width: 14, height: 14).help("Téléchargement : \(Int(p.fraction * 100)) %") }191                else if track.isDownloaded { Image(systemName: "arrow.down.circle.fill").foregroundStyle(.secondary).help("Téléchargé sur ce Mac") }192                else { Button { model.download([track]) } label: { Image(systemName: "arrow.down.circle").foregroundStyle(.secondary) }.buttonStyle(.plain).help("Télécharger ce titre").accessibilityLabel("Télécharger ce titre") }193            }194        }195        .frame(width: 18)196        .task(id: "\(trackID)-\(model.libraryRevision)") { track = await model.store?.track(trackID) }197    }198}199
Files main
Menu

Theme