323 lines
11 KiB
Swift
323 lines
11 KiB
Swift
import Combine
|
|
import SwiftUI
|
|
|
|
@MainActor
|
|
final class AlbumDetailViewModel: ObservableObject {
|
|
@Published private(set) var album: Album?
|
|
@Published private(set) var tracks: [Track]
|
|
@Published private(set) var isLoading: Bool
|
|
@Published private(set) var errorMessage: String?
|
|
|
|
private let albumID: String
|
|
private let api: MusicAPI
|
|
private var hasLoaded: Bool
|
|
|
|
init(
|
|
albumID: String,
|
|
api: MusicAPI? = nil,
|
|
album: Album? = nil,
|
|
tracks: [Track] = []
|
|
) {
|
|
self.albumID = albumID
|
|
self.api = api ?? MusicAPI()
|
|
self.album = album
|
|
self.tracks = tracks
|
|
isLoading = false
|
|
hasLoaded = album != nil
|
|
}
|
|
|
|
static var preview: AlbumDetailViewModel {
|
|
let artist = Artist(id: "artist-preview", name: "Example Artist", file: nil)
|
|
let album = Album(
|
|
id: "album-preview",
|
|
name: "First Light",
|
|
artists: [.value(artist)],
|
|
file: nil,
|
|
genre: nil
|
|
)
|
|
let trackAlbum = TrackAlbum(id: album.id, name: album.name, file: "")
|
|
let tracks = [
|
|
Track(
|
|
id: "track-preview-1",
|
|
name: "Morning Light",
|
|
album: .value(trackAlbum),
|
|
artists: [.value(artist)],
|
|
fileDir: "",
|
|
durationInSeconds: 218,
|
|
lyrics: nil
|
|
),
|
|
Track(
|
|
id: "track-preview-2",
|
|
name: "Open Roads",
|
|
album: .value(trackAlbum),
|
|
artists: [.value(artist)],
|
|
fileDir: "",
|
|
durationInSeconds: 194,
|
|
lyrics: nil
|
|
),
|
|
Track(
|
|
id: "track-preview-3",
|
|
name: "Between the Lines",
|
|
album: .value(trackAlbum),
|
|
artists: [.value(artist)],
|
|
fileDir: "",
|
|
durationInSeconds: 243,
|
|
lyrics: nil
|
|
),
|
|
]
|
|
return AlbumDetailViewModel(albumID: album.id, album: album, tracks: tracks)
|
|
}
|
|
|
|
func load(forceRefresh: Bool = false) async {
|
|
guard !isLoading, forceRefresh || !hasLoaded else { return }
|
|
isLoading = true
|
|
errorMessage = nil
|
|
defer { isLoading = false }
|
|
|
|
do {
|
|
async let albumRequest = api.album(id: albumID)
|
|
async let tracksRequest = loadAllTracks()
|
|
album = try await albumRequest
|
|
tracks = try await tracksRequest
|
|
hasLoaded = true
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func artworkURL(for album: Album) -> URL? {
|
|
guard let file = album.file else { return nil }
|
|
return api.client.configuration.mediaURL(for: file)
|
|
}
|
|
|
|
private func loadAllTracks() async throws -> [Track] {
|
|
let pageSize = 100
|
|
var allTracks: [Track] = []
|
|
var skip = 0
|
|
|
|
while true {
|
|
let page = try await api.albumTracks(id: albumID, limit: pageSize, skip: skip)
|
|
allTracks.append(contentsOf: page)
|
|
guard page.count == pageSize else { return allTracks }
|
|
skip += page.count
|
|
}
|
|
}
|
|
}
|
|
|
|
struct AlbumDetailView: View {
|
|
@StateObject private var viewModel: AlbumDetailViewModel
|
|
|
|
init(albumID: String) {
|
|
_viewModel = StateObject(wrappedValue: AlbumDetailViewModel(albumID: albumID))
|
|
}
|
|
|
|
init(viewModel: AlbumDetailViewModel) {
|
|
_viewModel = StateObject(wrappedValue: viewModel)
|
|
}
|
|
|
|
var body: some View {
|
|
Group {
|
|
if viewModel.isLoading && viewModel.album == nil {
|
|
ProgressView()
|
|
.tint(.red)
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
} else if let errorMessage = viewModel.errorMessage, viewModel.album == nil {
|
|
ContentUnavailableView {
|
|
Label("Couldn't Load Album", systemImage: "wifi.exclamationmark")
|
|
} description: {
|
|
Text(errorMessage)
|
|
} actions: {
|
|
Button("Try Again") {
|
|
Task { await viewModel.load(forceRefresh: true) }
|
|
}
|
|
.tint(.red)
|
|
}
|
|
} else if let album = viewModel.album {
|
|
albumContent(album)
|
|
} else {
|
|
ContentUnavailableView(
|
|
"Album Not Found",
|
|
systemImage: "square.stack",
|
|
description: Text("This album may no longer be available.")
|
|
)
|
|
}
|
|
}
|
|
.navigationTitle(viewModel.album?.name ?? "Album")
|
|
.navigationBarTitleDisplayMode(.inline)
|
|
.tint(.red)
|
|
.task {
|
|
await viewModel.load()
|
|
}
|
|
}
|
|
|
|
private func albumContent(_ album: Album) -> some View {
|
|
ScrollView {
|
|
VStack(alignment: .leading, spacing: 24) {
|
|
albumHeader(album)
|
|
|
|
if let errorMessage = viewModel.errorMessage {
|
|
ContentUnavailableView {
|
|
Label("Couldn't Load Songs", systemImage: "wifi.exclamationmark")
|
|
} description: {
|
|
Text(errorMessage)
|
|
} actions: {
|
|
Button("Try Again") {
|
|
Task { await viewModel.load(forceRefresh: true) }
|
|
}
|
|
.tint(.red)
|
|
}
|
|
.frame(maxWidth: .infinity)
|
|
.padding(.top, 16)
|
|
} else if viewModel.isLoading && viewModel.tracks.isEmpty {
|
|
ProgressView()
|
|
.tint(.red)
|
|
.frame(maxWidth: .infinity)
|
|
.padding(.top, 28)
|
|
} else if viewModel.tracks.isEmpty && !viewModel.isLoading {
|
|
ContentUnavailableView(
|
|
"No Songs",
|
|
systemImage: "music.note.list",
|
|
description: Text("This album doesn't have any songs yet.")
|
|
)
|
|
.frame(maxWidth: .infinity)
|
|
.padding(.top, 16)
|
|
} else {
|
|
LazyVStack(spacing: 0) {
|
|
ForEach(viewModel.tracks.indices, id: \.self) { index in
|
|
let track = viewModel.tracks[index]
|
|
AlbumTrackRow(track: track, index: index)
|
|
if index < viewModel.tracks.count - 1 {
|
|
Divider()
|
|
.padding(.leading, 42)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
.padding(.horizontal, 20)
|
|
.padding(.top, 16)
|
|
.padding(.bottom, 24)
|
|
}
|
|
.scrollIndicators(.hidden)
|
|
.refreshable {
|
|
await viewModel.load(forceRefresh: true)
|
|
}
|
|
}
|
|
|
|
private func albumHeader(_ album: Album) -> some View {
|
|
VStack(alignment: .leading, spacing: 12) {
|
|
AsyncImage(url: viewModel.artworkURL(for: album)) { phase in
|
|
switch phase {
|
|
case .success(let image):
|
|
image
|
|
.resizable()
|
|
.scaledToFill()
|
|
case .empty:
|
|
artworkPlaceholder
|
|
.overlay { ProgressView().tint(.red) }
|
|
case .failure:
|
|
artworkPlaceholder
|
|
@unknown default:
|
|
artworkPlaceholder
|
|
}
|
|
}
|
|
.frame(maxWidth: .infinity)
|
|
.containerRelativeFrame(.horizontal) { length, _ in
|
|
min(280, length - 40)
|
|
}
|
|
.aspectRatio(1, contentMode: .fit)
|
|
.clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
|
|
.frame(maxWidth: .infinity)
|
|
.accessibilityLabel("\(album.name) album artwork")
|
|
|
|
Text(album.name)
|
|
.font(.title2.weight(.bold))
|
|
.fixedSize(horizontal: false, vertical: true)
|
|
|
|
if !artistNames(for: album.artists).isEmpty {
|
|
Text(artistNames(for: album.artists))
|
|
.font(.subheadline)
|
|
.foregroundStyle(.secondary)
|
|
}
|
|
|
|
Text("\(viewModel.tracks.count) \(viewModel.tracks.count == 1 ? "song" : "songs")")
|
|
.font(.footnote)
|
|
.foregroundStyle(.secondary)
|
|
}
|
|
.frame(maxWidth: .infinity, alignment: .leading)
|
|
}
|
|
|
|
private var artworkPlaceholder: some View {
|
|
Image(systemName: "music.note")
|
|
.font(.system(size: 48, weight: .light))
|
|
.foregroundStyle(.secondary)
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
.background(.quaternary)
|
|
}
|
|
|
|
private func artistNames(for artists: [APIReference<Artist>]) -> String {
|
|
artists.compactMap { reference in
|
|
guard case .value(let artist) = reference else { return nil }
|
|
return artist.name
|
|
}
|
|
.joined(separator: ", ")
|
|
}
|
|
}
|
|
|
|
private struct AlbumTrackRow: View {
|
|
let track: Track
|
|
let index: Int
|
|
|
|
private var artistNames: String {
|
|
track.artists.compactMap { reference in
|
|
guard case .value(let artist) = reference else { return nil }
|
|
return artist.name
|
|
}
|
|
.joined(separator: ", ")
|
|
}
|
|
|
|
private var duration: String {
|
|
let seconds = max(0, Int(track.durationInSeconds))
|
|
return String(format: "%d:%02d", seconds / 60, seconds % 60)
|
|
}
|
|
|
|
var body: some View {
|
|
HStack(spacing: 14) {
|
|
Text("\(index + 1)")
|
|
.font(.footnote.monospacedDigit())
|
|
.foregroundStyle(.secondary)
|
|
.frame(width: 28, alignment: .trailing)
|
|
|
|
VStack(alignment: .leading, spacing: 3) {
|
|
Text(track.name)
|
|
.font(.body)
|
|
.foregroundStyle(.primary)
|
|
.lineLimit(1)
|
|
|
|
if !artistNames.isEmpty {
|
|
Text(artistNames)
|
|
.font(.footnote)
|
|
.foregroundStyle(.secondary)
|
|
.lineLimit(1)
|
|
}
|
|
}
|
|
|
|
Spacer(minLength: 8)
|
|
|
|
Text(duration)
|
|
.font(.footnote.monospacedDigit())
|
|
.foregroundStyle(.secondary)
|
|
}
|
|
.padding(.vertical, 12)
|
|
.accessibilityElement(children: .combine)
|
|
}
|
|
}
|
|
|
|
struct AlbumDetailView_Previews: PreviewProvider {
|
|
static var previews: some View {
|
|
NavigationStack {
|
|
AlbumDetailView(viewModel: .preview)
|
|
}
|
|
}
|
|
}
|