Files
music-app/Music/View/Library/LibraryView.swift
T

202 lines
6.8 KiB
Swift

import Combine
import SwiftUI
@MainActor
private final class LibraryViewModel: ObservableObject {
@Published private(set) var recentlyPlayedAlbums: [RecentAlbum] = []
@Published private(set) var isLoading = false
@Published private(set) var errorMessage: String?
private let api = MusicAPI()
private let recentTracksKey = "music-v2-recently-played-track-ids"
func loadRecentlyPlayed(forceRefresh: Bool = false) async {
guard !isLoading else { return }
let ids = UserDefaults.standard.stringArray(forKey: recentTracksKey) ?? []
guard !ids.isEmpty else {
recentlyPlayedAlbums = []
errorMessage = nil
return
}
if !forceRefresh, !recentlyPlayedAlbums.isEmpty { return }
isLoading = true
errorMessage = nil
defer { isLoading = false }
do {
let tracks = try await api.tracks(ids: ids)
let tracksByID = Dictionary(uniqueKeysWithValues: tracks.map { ($0.id, $0) })
let orderedTracks = ids.compactMap { tracksByID[$0] }
var seenAlbumIDs = Set<String>()
recentlyPlayedAlbums = orderedTracks.compactMap { track in
guard case .value(let album) = track.album,
seenAlbumIDs.insert(album.id).inserted else { return nil }
return RecentAlbum(id: album.id, name: album.name, file: album.file, track: track)
}
} catch {
errorMessage = error.localizedDescription
}
}
func artworkURL(for album: RecentAlbum) -> URL? {
api.client.configuration.mediaURL(for: album.file)
}
}
private struct RecentAlbum: Identifiable {
let id: String
let name: String
let file: String
let track: Track
}
struct LibraryView: View {
@StateObject private var model = LibraryViewModel()
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Text("Library")
.font(.system(size: 34, weight: .bold))
.padding(.top, 4)
.padding(.bottom, 16)
categoryList
Text("Recently Played")
.font(.title2.weight(.bold))
.padding(.top, 26)
.padding(.bottom, 12)
recentlyPlayedSection
}
.padding(.horizontal, 20)
.padding(.bottom, 24)
}
.scrollIndicators(.hidden)
.background(Color.black.ignoresSafeArea())
.foregroundStyle(.white)
.toolbar(.hidden, for: .navigationBar)
.refreshable { await model.loadRecentlyPlayed(forceRefresh: true) }
}
.task { await model.loadRecentlyPlayed() }
}
private var categoryList: some View {
VStack(spacing: 0) {
categoryRow("Artists", symbol: "mic")
NavigationLink {
LibraryAlbumsView()
} label: {
categoryRow("Albums", symbol: "square.stack")
}
.buttonStyle(.plain)
NavigationLink {
LibrarySongsView()
} label: {
categoryRow("Songs", symbol: "music.note")
}
.buttonStyle(.plain)
}
}
private func categoryRow(_ title: String, symbol: String) -> some View {
HStack(spacing: 20) {
Image(systemName: symbol)
.font(.system(size: 27, weight: .medium))
.foregroundStyle(.red)
.frame(width: 40)
Text(title)
.font(.system(size: 20))
.foregroundStyle(.primary)
Spacer()
Image(systemName: "chevron.right")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(.tertiary)
}
.frame(minHeight: 70)
.overlay(alignment: .bottom) {
Rectangle()
.fill(.white.opacity(0.16))
.frame(height: 1)
.padding(.leading, 60)
}
.accessibilityElement(children: .combine)
}
@ViewBuilder
private var recentlyPlayedSection: some View {
if model.isLoading && model.recentlyPlayedAlbums.isEmpty {
ProgressView()
.tint(.red)
.frame(maxWidth: .infinity)
.padding(.vertical, 28)
} else if let errorMessage = model.errorMessage {
ContentUnavailableView {
Label("Couldn't Load Recently Played", systemImage: "wifi.exclamationmark")
} description: {
Text(errorMessage)
} actions: {
Button("Try Again") {
Task { await model.loadRecentlyPlayed(forceRefresh: true) }
}
.tint(.red)
}
} else if model.recentlyPlayedAlbums.isEmpty {
Text("Albums you play will appear here.")
.font(.subheadline)
.foregroundStyle(.secondary)
.padding(.vertical, 8)
} else {
ScrollView(.horizontal) {
LazyHStack(alignment: .top, spacing: 14) {
ForEach(model.recentlyPlayedAlbums) { album in
NavigationLink {
AlbumDetailView(albumID: album.id)
} label: {
recentAlbumCard(album)
}
.buttonStyle(.plain)
}
}
.padding(.vertical, 2)
}
.scrollIndicators(.hidden)
}
}
private func recentAlbumCard(_ album: RecentAlbum) -> some View {
VStack(alignment: .leading, spacing: 5) {
AlbumArtworkView(url: model.artworkURL(for: album))
.frame(width: 170)
Text(album.name)
.font(.subheadline.weight(.medium))
.lineLimit(2)
.foregroundStyle(.primary)
Text(artistNames(album.track.artists))
.font(.footnote)
.lineLimit(1)
.foregroundStyle(.secondary)
}
.frame(width: 170, alignment: .leading)
.accessibilityElement(children: .combine)
}
private func artistNames(_ references: [APIReference<Artist>]) -> String {
let names = references.compactMap { reference -> String? in
guard case .value(let artist) = reference else { return nil }
return artist.name
}
return names.isEmpty ? "Unknown Artist" : names.joined(separator: ", ")
}
}
struct LibraryView_Previews: PreviewProvider {
static var previews: some View {
LibraryView()
.environmentObject(PlayerManager())
}
}