geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import HydraulophoneCore
import SwiftUI
@MainActor
final class ArtistViewModel: ObservableObject {
@Published private(set) var sections: [HomeSection] = []
@Published private(set) var header: CatalogPageHeader?
@Published private(set) var isLoading = false
@Published private(set) var isLoadingMore = false
@Published private(set) var errorMessage: String?
@Published private(set) var hasMore = false
private let artist: Artist
private let service: any MusicService
private var continuation: PaginationToken?
private var seenContinuations: Set<String> = []
private var requestID = UUID()
private var requestTask: Task<HomePage, Error>?
init(artist: Artist, service: any MusicService) {
self.artist = artist
self.service = service
}
var artworkURL: URL? { header?.thumbnailURL ?? artist.thumbnailURL }
var songs: [Song] {
var seen = Set<String>()
return sections.flatMap(\.items).compactMap { item in
guard case .song(let song) = item, seen.insert(song.id).inserted else { return nil }
return song
}
}
deinit { requestTask?.cancel() }
func load(reload: Bool = false) async {
if !reload, !sections.isEmpty { return }
await request(appending: false, policy: reload ? .reload : .cacheFirst)
}
func loadMore() async {
guard hasMore, !isLoading, !isLoadingMore else { return }
await request(appending: true, policy: .cacheFirst)
}
private func request(appending: Bool, policy: CatalogLoadPolicy) async {
requestTask?.cancel()
let id = UUID()
requestID = id
isLoading = !appending
isLoadingMore = appending
errorMessage = nil
let token = appending ? continuation : nil
let artist = artist
let service = service
let task = Task {
guard let browser = service as? any ArtistBrowsingMusicService else {
throw InnerTubeError.invalidResponse("Artist browsing is unavailable.")
}
return try await browser.artistPage(artist, continuation: token, policy: policy)
}
requestTask = task
defer {
if requestID == id {
isLoading = false
isLoadingMore = false
requestTask = nil
}
}
do {
let page = try await withTaskCancellationHandler {
try await task.value
} onCancel: {
task.cancel()
}
try Task.checkCancellation()
guard requestID == id else { return }
if !appending {
header = page.header?.fillingMissingValues(from: header) ?? header
sections = []
seenContinuations = []
}
// Prefix section identity by page to keep repeated renderer indices unique.
let prefix = sections.count
sections += page.sections.enumerated().map { index, section in
HomeSection(
id: "artist-\(prefix)-\(index)", title: section.title,
subtitle: section.subtitle, items: section.items)
}
if let token { seenContinuations.insert(token.rawValue) }
if let next = page.next, seenContinuations.contains(next.rawValue) {
continuation = nil
hasMore = false
errorMessage = "More results could not be loaded. Pull to refresh and try again."
} else {
continuation = page.next
hasMore = page.next != nil
}
} catch is CancellationError {
// Leaving the page or replacing a request does not create an error state.
} catch {
guard requestID == id, !Task.isCancelled else { return }
errorMessage = error.localizedDescription
}
}
}
struct ArtistView: View {
@EnvironmentObject private var model: AppModel
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.horizontalSizeClass) private var sizeClass
@Environment(\.dynamicTypeSize) private var typeSize
@StateObject private var viewModel: ArtistViewModel
let artist: Artist
init(artist: Artist, service: any MusicService) {
self.artist = artist
_viewModel = StateObject(wrappedValue: ArtistViewModel(artist: artist, service: service))
}
var body: some View {
Group {
if model.isOfflineOnly {
ContentUnavailableView(
"Artist browsing is offline", systemImage: "wifi.slash",
description: Text("Turn off Offline Only in Settings to browse this artist."))
} else {
catalog
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(HydraulophoneTheme.groupedBackground)
.navigationTitle(artist.title)
.navigationBarTitleDisplayMode(.inline)
.task(id: model.isOfflineOnly) {
guard !model.isOfflineOnly else { return }
await viewModel.load()
}
}
private var catalog: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 28) {
artistHeader
MusicPlaybackActions(
isEnabled: !viewModel.songs.isEmpty,
play: { play(shuffle: false) }, shuffle: { play(shuffle: true) })
if viewModel.isLoading, viewModel.sections.isEmpty {
ProgressView("Loading artist…").frame(maxWidth: .infinity, minHeight: 160)
} else if let message = viewModel.errorMessage, viewModel.sections.isEmpty {
HydraulophoneErrorState(
title: "Could not load artist", message: message,
retry: { Task { await viewModel.load(reload: true) } })
} else if viewModel.sections.allSatisfy({ $0.items.isEmpty }) {
ContentUnavailableView(
"No music available", systemImage: "music.note",
description: Text("This artist’s page has no available songs or albums."))
}
ForEach(viewModel.sections.filter { !$0.items.isEmpty }) { section in
artistSection(section)
}
paginationFooter
}
.padding(.horizontal, 20)
.padding(.bottom, 24)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.2), value: viewModel.sections)
.frame(maxWidth: 860)
.frame(maxWidth: .infinity)
}
.refreshable { await viewModel.load(reload: true) }
}
private var artistHeader: some View {
VStack(spacing: 18) {
ArtworkView(
url: viewModel.artworkURL, size: typeSize.isAccessibilitySize ? 140 : 220,
cornerRadius: typeSize.isAccessibilitySize ? 70 : 110
)
.shadow(color: .black.opacity(0.14), radius: 18, y: 10)
VStack(spacing: 6) {
Text("ARTIST")
.font(.caption.weight(.semibold)).tracking(2).foregroundStyle(.secondary)
Text(artist.title)
.font(.largeTitle.bold()).multilineTextAlignment(.center)
.accessibilityAddTraits(.isHeader)
}
}
.padding(.top, 24)
.frame(maxWidth: .infinity)
.accessibilityIdentifier("artist.header")
}
private func artistSection(_ section: HomeSection) -> some View {
VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
Text(section.title).font(.title2.bold()).accessibilityAddTraits(.isHeader)
if let subtitle = section.subtitle, !subtitle.isEmpty {
Text(subtitle).font(.subheadline).foregroundStyle(.secondary)
}
}
let songs = section.items.compactMap { item -> Song? in
guard case .song(let song) = item else { return nil }
return song
}
if !songs.isEmpty {
LazyVStack(spacing: 0) {
ForEach(songs) { song in
SongRow(song: song) {
guard let index = viewModel.songs.firstIndex(where: { $0.id == song.id }) else {
return
}
model.playback.setQueue(viewModel.songs, startAt: index, shuffle: false)
}
Divider().padding(.leading, 68)
}
}
}
let releases = section.items.filter {
if case .song = $0 { return false }
return true
}
if !releases.isEmpty {
ScrollView(.horizontal) {
HStack(alignment: .top, spacing: 16) {
ForEach(releases) { item in
releaseTile(item)
}
}
.padding(.bottom, 4)
}
.scrollIndicators(.hidden)
}
}
}
@ViewBuilder private func releaseTile(_ item: CatalogItem) -> some View {
switch item {
case .album(let album):
NavigationLink(value: TrackDestination.album(album)) {
releaseLabel(item)
}
.buttonStyle(.plain)
.accessibilityLabel("Open album \(album.title)")
.accessibilityIdentifier("artist.album.\(album.id)")
case .playlist(let playlist):
NavigationLink(value: TrackDestination.playlist(playlist)) {
releaseLabel(item)
}
.buttonStyle(.plain)
.accessibilityLabel("Open playlist \(playlist.title)")
case .song:
EmptyView()
}
}
private func releaseLabel(_ item: CatalogItem) -> some View {
let side: CGFloat = typeSize.isAccessibilitySize ? 220 : (sizeClass == .regular ? 192 : 164)
return VStack(alignment: .leading, spacing: 8) {
ArtworkView(url: item.thumbnailURL, size: side, cornerRadius: 10)
Text(item.title).font(.headline).foregroundStyle(.primary).lineLimit(3)
if let subtitle = item.subtitle, !subtitle.isEmpty {
Text(subtitle).font(.subheadline).foregroundStyle(.secondary).lineLimit(2)
}
}
.frame(width: side, alignment: .leading)
.contentShape(Rectangle())
}
@ViewBuilder private var paginationFooter: some View {
if let message = viewModel.errorMessage, !viewModel.sections.isEmpty {
VStack(alignment: .leading, spacing: 8) {
Text(message).font(.footnote).foregroundStyle(.secondary)
Button("Retry") {
Task {
if viewModel.hasMore {
await viewModel.loadMore()
} else {
await viewModel.load(reload: true)
}
}
}
.frame(minHeight: 44)
}
} else if viewModel.hasMore {
Button {
Task { await viewModel.loadMore() }
} label: {
if viewModel.isLoadingMore { ProgressView("Loading more…") } else { Text("Load more") }
}
.frame(maxWidth: .infinity, minHeight: 44)
.disabled(viewModel.isLoadingMore)
}
}
private func play(shuffle: Bool) {
guard !viewModel.songs.isEmpty else { return }
model.playback.setQueue(viewModel.songs, startAt: 0, shuffle: shuffle)
}
}