SPB Git

Repository Public

AlbumsView.swift 11.1 KB 213 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music pour macOS9// File             : Features/Albums/AlbumsView.swift10// Description      : Albums grid and album detail (track list, download of the11//                    whole album).12// Module           : Features13// Repository       : https://git.spboucher.ai/sp-music-macos14// Created          : 2026-11-1815// Last Modified    : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import SwiftUI90import SPMusicCore9192struct AlbumsView: View {93    @Environment(AppModel.self) private var model94    @AppStorage("albumSort") private var sortRaw = AlbumSort.artist.rawValue95    @State private var albums: [Album] = []96    @State private var loaded = false9798    var body: some View {99        Group {100            if loaded && albums.isEmpty {101                EmptyState(symbol: "square.stack", title: model.downloadedOnly ? "Aucun album téléchargé" : "Aucun album",102                           message: model.downloadedOnly ? "Téléchargez un album pour l’écouter sans connexion : ouvrez-le et choisissez « Télécharger l’album »." : "")103            } else {104                ScrollView { AlbumGrid(albums: albums).padding(24) }105            }106        }107        .navigationTitle("Albums").navigationSubtitle(loaded ? "\(albums.count) albums" : "")108        .toolbar {109            ToolbarItem {110                Picker("Trier", selection: $sortRaw) {111                    Text("Par artiste").tag(AlbumSort.artist.rawValue); Text("Par titre").tag(AlbumSort.title.rawValue)112                    Text("Par année").tag(AlbumSort.year.rawValue); Text("Ajouts récents").tag(AlbumSort.recent.rawValue)113                }114                .pickerStyle(.menu).help("Ordre des albums")115            }116        }117        .libraryTask(model, extra: sortRaw) {118            albums = await model.store?.albums(sort: AlbumSort(rawValue: sortRaw) ?? .artist, downloadedOnly: model.downloadedOnly) ?? []119            loaded = true120        }121    }122}123124struct AlbumDetailView: View {125    @Environment(AppModel.self) private var model126    let albumID: String127    @State private var album: Album?128    @State private var tracks: [Track] = []129    @State private var loaded = false130    @State private var confirmRemove = false131132    var body: some View {133        ZStack {134            Color.clear135            if let album {136                ScrollView {137                    VStack(alignment: .leading, spacing: 22) {138                        header(album)139                        VStack(spacing: 0) {140                            let multiDisc = Set(tracks.map(\.discNo)).count > 1141                            ForEach(Array(tracks.enumerated()), id: \.element.id) { i, t in142                                if multiDisc, i == 0 || tracks[i - 1].discNo != t.discNo {143                                    Text("Disque \(t.discNo)").font(.caption.weight(.semibold)).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.top, i == 0 ? 0 : 14).padding(.bottom, 4).padding(.leading, 8)144                                }145                                TrackRow(track: t, number: t.trackNo ?? i + 1, showArtwork: false, showAlbum: false, showArtist: t.artistName != album.artistName) { model.play(tracks, at: i) }146                                if i < tracks.count - 1 { Divider().padding(.leading, 42).opacity(0.5) }147                            }148                        }149                        Text(footer(album)).font(.caption).foregroundStyle(.tertiary)150                    }151                    .padding(24).frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)152                }153            } else if loaded {154                EmptyState(symbol: "square.stack", title: "Album introuvable", message: "Il a peut-être été retiré du cluster.")155            }156        }157        .navigationTitle(album?.title ?? "")158        .libraryTask(model, extra: albumID) {159            guard let s = model.store else { return }160            album = await s.album(albumID); tracks = await s.albumTracks(albumID); loaded = true161        }162        .confirmationDialog("Supprimer les fichiers de cet album sur ce Mac ?", isPresented: $confirmRemove) {163            Button("Supprimer le téléchargement", role: .destructive) { if let album { model.removeAlbumDownload(album) } }164        } message: { Text("L’album reste dans votre bibliothèque sur le cluster et pourra être téléchargé de nouveau.") }165    }166167    private func header(_ album: Album) -> some View {168        HStack(alignment: .bottom, spacing: 22) {169            ArtworkView(artworkID: album.artworkID, size: 220, cornerRadius: 10, symbol: "square.stack").shadow(color: .black.opacity(0.25), radius: 16, y: 8)170            VStack(alignment: .leading, spacing: 8) {171                Text(album.title).font(.system(size: 30, weight: .bold)).lineLimit(3)172                Button(album.artistName) { model.show(.artist(album.artistID)) }.buttonStyle(.plain).font(.title2).foregroundStyle(Color.accentColor)173                Text(([album.genre, album.year.map(String.init)].compactMap { $0 } + ["\(tracks.count) titres", Format.longDuration(ms: album.durationMs)]).joined(separator: " · ")).font(.callout).foregroundStyle(.secondary)174                if let t = tracks.first { HStack(spacing: 6) { QualityBadge(track: t); Text(Format.quality(of: t)).font(.caption).foregroundStyle(.secondary) } }175                HStack(spacing: 10) {176                    Button { model.play(tracks) } label: { Label("Lire", systemImage: "play.fill").frame(minWidth: 70) }.buttonStyle(.borderedProminent).controlSize(.large)177                    Button { model.play(tracks, shuffle: true) } label: { Label("Aléatoire", systemImage: "shuffle") }.controlSize(.large)178                    downloadButton(album)179                    Button { model.toggleFavorite(album) } label: { Image(systemName: album.favorite ? "heart.fill" : "heart").foregroundStyle(album.favorite ? .pink : .primary) }.controlSize(.large).help(album.favorite ? "Retirer des favoris" : "Ajouter aux favoris").accessibilityLabel("Favori")180                    Menu { AlbumMenu(album: album) } label: { Image(systemName: "ellipsis") }.menuStyle(.borderlessButton).frame(width: 30)181                }182                .padding(.top, 6)183            }184        }185    }186187    @ViewBuilder private func downloadButton(_ album: Album) -> some View {188        let active = tracks.filter { model.liveProgress[$0.id] != nil || $0.downloadState == .queued || $0.downloadState == .downloading }189        if album.isFullyDownloaded {190            Button { confirmRemove = true } label: { Label("Téléchargé", systemImage: "checkmark.circle.fill") }.controlSize(.large).help("Cet album est sur ce Mac. Cliquez pour le supprimer.")191        } else if !active.isEmpty {192            // Whole-album progress, by bytes.193            let total = tracks.reduce(Int64(0)) { $0 + $1.sizeBytes }194            let done = tracks.reduce(Int64(0)) { $0 + ($1.isDownloaded ? $1.sizeBytes : (model.liveProgress[$1.id]?.received ?? 0)) }195            Button { model.removeDownloads(active) } label: {196                HStack(spacing: 8) {197                    ProgressRing(fraction: total > 0 ? Double(done) / Double(total) : 0).frame(width: 14, height: 14)198                    Text("\(album.downloadedCount)/\(tracks.count)").monospacedDigit()199                }200            }201            .controlSize(.large).help("Téléchargement en cours. Cliquez pour annuler ce qui reste.")202        } else {203            Button { model.downloadAlbum(album) } label: { Label("Télécharger l’album", systemImage: "arrow.down.circle") }.controlSize(.large)204                .disabled(!model.isOnline).help(model.isOnline ? "Copier cet album sur ce Mac pour l’écouter sans connexion" : "Indisponible hors ligne")205        }206    }207208    private func footer(_ album: Album) -> String {209        let size = tracks.reduce(Int64(0)) { $0 + $1.sizeBytes }210        return "Taille des fichiers originaux : \(Format.bytes(size))" + (album.downloadedCount > 0 ? " · \(album.downloadedCount) sur \(tracks.count) sur ce Mac" : "")211    }212}213
Files main
Menu

Theme