Files

122 lines
4.5 KiB
Swift

import SwiftUI
struct HomeView: View {
@StateObject private var viewModel: HomeViewModel
init(viewModel: HomeViewModel? = nil) {
_viewModel = StateObject(wrappedValue: viewModel ?? HomeViewModel())
}
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Text("Home")
.font(.system(size: 34, weight: .bold))
.padding(.horizontal, 20)
.padding(.top, 4)
.padding(.bottom, 16)
Group {
if viewModel.sections.isEmpty, viewModel.isLoading {
ProgressView()
.tint(.red)
.frame(maxWidth: .infinity)
.padding(.top, 72)
} else if viewModel.sections.isEmpty, let errorMessage = viewModel.errorMessage
{
ContentUnavailableView {
Label("Couldn't Load Home", systemImage: "wifi.exclamationmark")
} description: {
Text(errorMessage)
} actions: {
Button("Try Again") {
Task { await viewModel.load(forceRefresh: true) }
}
.tint(.red)
}
.padding(.top, 48)
} else if viewModel.sections.isEmpty {
ContentUnavailableView(
"No Albums Yet",
systemImage: "square.stack",
description: Text("There are no albums to show right now.")
)
.padding(.top, 48)
} else {
LazyVStack(alignment: .leading, spacing: 26) {
ForEach(viewModel.sections) { section in
HomeAlbumCarousel(section: section) { album in
viewModel.artworkURL(for: album)
}
}
}
.padding(.vertical, 20)
}
}
}
}
.scrollIndicators(.hidden)
.refreshable {
await viewModel.load(forceRefresh: true)
}
.toolbar(.hidden, for: .navigationBar)
.tint(.red)
}
.task {
await viewModel.load()
}
}
}
private struct HomeAlbumCarousel: View {
let section: HomeGenreSection
let artworkURL: (Album) -> URL?
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(section.genre.name)
.font(.title3.weight(.semibold))
.padding(.horizontal, 20)
ScrollView(.horizontal) {
LazyHStack(alignment: .top, spacing: 14) {
ForEach(section.albums) { album in
NavigationLink {
AlbumDetailView(albumID: album.id)
} label: {
AlbumCardView(album: album, artworkURL: artworkURL(album))
.frame(maxWidth: 150)
.containerRelativeFrame(.horizontal) { length, _ in
(length - 40 - 28) / 2.2
}
}
.buttonStyle(.plain)
}
}
.scrollTargetLayout()
.padding(.horizontal, 20)
}
.scrollIndicators(.hidden)
.scrollTargetBehavior(.viewAligned)
}
}
}
private struct HomeAlbumCarousel_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
HomeAlbumCarousel(section: HomeViewModel.preview.sections[0]) { _ in nil }
.padding(.vertical, 24)
}
.environmentObject(PlayerManager())
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView(viewModel: .preview)
.environmentObject(PlayerManager())
}
}