Add album detail and track listing
This commit is contained in:
1 parent
c415380336
commit
39a64bebf2
4 files changed
+347
-3
No files matched your search
@@ -79,9 +79,14 @@ public final class APIClient: @unchecked Sendable {
|
||||
body: Body? = nil,
|
||||
response: Response.Type = Response.self
|
||||
) async throws -> Response {
|
||||
try await perform(
|
||||
do {
|
||||
return try await perform(
|
||||
method, path: path, query: query, body: body, response: response,
|
||||
refreshAfterUnauthorized: true)
|
||||
} catch {
|
||||
print("[APIClient] \(method) \(path) failed: \(error.localizedDescription)")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func perform<Response: Decodable & Sendable, Body: Encodable & Sendable>(
|
||||
@@ -156,7 +161,7 @@ public final class APIClient: @unchecked Sendable {
|
||||
return try decoder.decode(Response.self, from: Data("null".utf8))
|
||||
}
|
||||
return try decoder.decode(Response.self, from: data)
|
||||
} catch { throw APIError.decoding(error.localizedDescription) }
|
||||
} catch { throw APIError.decoding(String(describing: error)) }
|
||||
} catch let error as APIError { throw error } catch {
|
||||
throw APIError.transport(error.localizedDescription)
|
||||
}
|
||||
|
||||
+11
-1
@@ -46,6 +46,16 @@ nonisolated public struct Album: Decodable, Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct TrackAlbum: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let file: String
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "_id"
|
||||
case name, file
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct Lyrics: Decodable, Sendable {
|
||||
public let synced: Bool
|
||||
public let text: String
|
||||
@@ -54,7 +64,7 @@ nonisolated public struct Lyrics: Decodable, Sendable {
|
||||
nonisolated public struct Track: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let album: APIReference<Album>
|
||||
public let album: APIReference<TrackAlbum>
|
||||
public let artists: [APIReference<Artist>]
|
||||
public let fileDir: String
|
||||
public let durationInSeconds: Double
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,11 +75,16 @@ private struct HomeAlbumCarousel: View {
|
||||
ScrollView(.horizontal) {
|
||||
LazyHStack(alignment: .top, spacing: 14) {
|
||||
ForEach(section.albums) { album in
|
||||
NavigationLink {
|
||||
AlbumDetailView(albumID: album.id)
|
||||
} label: {
|
||||
HomeAlbumCard(album: album, artworkURL: artworkURL(album))
|
||||
.containerRelativeFrame(.horizontal) { length, _ in
|
||||
(length - 40 - 28) / 2.2
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
.scrollTargetLayout()
|
||||
.padding(.horizontal, 20)
|
||||
@@ -92,9 +97,11 @@ private struct HomeAlbumCarousel: View {
|
||||
|
||||
private struct HomeAlbumCarousel_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationStack {
|
||||
HomeAlbumCarousel(section: HomeViewModel.preview.sections[0]) { _ in nil }
|
||||
.padding(.vertical, 24)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct HomeAlbumCard: View {
|
||||
|
||||
Reference in new issue
Block a user