| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103 |
- import SwiftData
- import SwiftUI
- /// Navigation destination within the cloud browser — managed manually to avoid
- /// NavigationSplitView capturing nested NavigationLink pushes on macOS.
- enum CloudNavDestination: Hashable {
- case category(ChadCategoryType)
- case album(ChadAlbum)
- case filter(CategoryFilter)
- case search(query: String)
- }
- /// Cloud library browser — navigate categories → albums → tracks from Chad Music server.
- struct CloudBrowserView: View {
- /// Which library section to start at (nil = root category grid).
- let initialDestination: LibraryDestination?
- @Environment(PlayerViewModel.self) private var playerVM
- @EnvironmentObject private var theme: AppTheme
- @State private var apiClient = ChadMusicAPIClient.shared
- @State private var uploadService = UploadService.shared
- @State private var orchestrator = SoulseekOrchestrator.shared
- @State private var navStack: [CloudNavDestination] = []
- init(initialDestination: LibraryDestination? = nil) {
- self.initialDestination = initialDestination
- }
- var body: some View {
- if !apiClient.isConfigured {
- CloudNotConfiguredView()
- } else {
- VStack(spacing: 0) {
- if let current = navStack.last {
- // Back button header for all detail views
- CloudNavHeader(navStack: $navStack, title: {
- switch current {
- case .category(let cat): cat.displayName
- case .album(let album): album.title
- case .filter(let filter): filter.value
- case .search(let query): "Search: \(query)"
- }
- }())
- Divider()
- switch current {
- case .category(let cat):
- CategoryDetailView(apiClient: apiClient, category: cat, navStack: $navStack)
- case .album(let album):
- AlbumDetailView(apiClient: apiClient, album: album, navStack: $navStack)
- case .filter(let filter):
- FilteredAlbumsView(apiClient: apiClient, filter: filter, navStack: $navStack)
- case .search(let query):
- UnifiedSearchResultsView(query: query, navStack: $navStack)
- }
- } else {
- CategoryListView(apiClient: apiClient, uploadService: uploadService, navStack: $navStack)
- }
- // Soulseek status banner — appears at bottom during active pipeline
- SoulseekStatusBanner(orchestrator: orchestrator)
- }
- .onAppear {
- if let dest = initialDestination {
- navStack = dest.initialNavStack
- }
- }
- }
- }
- }
- // MARK: - Not Configured Prompt
- private struct CloudNotConfiguredView: View {
- var body: some View {
- VStack(spacing: 16) {
- Spacer()
- Image(systemName: "cloud.fill")
- .font(.system(size: 48))
- .foregroundStyle(.tertiary)
- Text("Chad Music Not Configured")
- .font(.title3)
- .foregroundStyle(.secondary)
- Text("Set your server URL and API key in Settings → Chad Music.")
- .font(.callout)
- .foregroundStyle(.tertiary)
- .multilineTextAlignment(.center)
- Spacer()
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- }
- }
- // MARK: - Navigation Header (back button + title)
- private struct CloudNavHeader: View {
- @Binding var navStack: [CloudNavDestination]
- let title: String
- @EnvironmentObject private var theme: AppTheme
- var body: some View {
- HStack(spacing: 6) {
- Button {
- navStack.removeLast()
- } label: {
- Image(systemName: "chevron.left")
- .font(.system(size: 14, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- }
- .buttonStyle(.plain)
- Text(title)
- .font(.system(size: 13, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- .lineLimit(1)
- Spacer()
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
- }
- }
- // MARK: - Category List
- private struct CategoryListView: View {
- let apiClient: ChadMusicAPIClient
- let uploadService: UploadService
- @Binding var navStack: [CloudNavDestination]
- @State private var searchText: String = ""
- @EnvironmentObject private var theme: AppTheme
- /// Show albums and artists by default — the most useful categories.
- private let defaultCategories: [ChadCategoryType] = [.album, .artist, .genre, .year]
- var body: some View {
- VStack(alignment: .leading, spacing: 0) {
- // Header with stats + upload button
- CloudHeaderView(apiClient: apiClient, uploadService: uploadService)
- // Search bar
- HStack(spacing: 8) {
- Image(systemName: "magnifyingglass")
- .font(.system(size: 12))
- .foregroundStyle(theme.tertiaryText)
- TextField("Search library & Soulseek...", text: $searchText)
- .textFieldStyle(.plain)
- .font(.system(size: 13))
- .onSubmit {
- let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
- guard query.count >= 2 else { return }
- navStack.append(.search(query: query))
- }
- if !searchText.isEmpty {
- Button {
- searchText = ""
- } label: {
- Image(systemName: "xmark.circle.fill")
- .font(.system(size: 12))
- .foregroundStyle(theme.tertiaryText)
- }
- .buttonStyle(.plain)
- }
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
- .background(theme.toolbarBackground.opacity(0.3))
- Divider()
- List {
- Section("Browse") {
- ForEach(defaultCategories) { category in
- Button {
- navStack.append(.category(category))
- } label: {
- Label(category.displayName, systemImage: category.icon)
- }
- .buttonStyle(.plain)
- }
- }
- Section("More") {
- ForEach(ChadCategoryType.allCases.filter { !defaultCategories.contains($0) }) { category in
- Button {
- navStack.append(.category(category))
- } label: {
- Label(category.displayName, systemImage: category.icon)
- }
- .buttonStyle(.plain)
- }
- }
- }
- .listStyle(.sidebar)
- }
- }
- }
- // MARK: - Cloud Header (stats bar + upload)
- private struct CloudHeaderView: View {
- let apiClient: ChadMusicAPIClient
- let uploadService: UploadService
- @State private var stats: ChadStats?
- @State private var statsError = false
- @State private var showUploadError = false
- var body: some View {
- HStack(spacing: 8) {
- Image(systemName: "cloud.fill")
- .foregroundStyle(.secondary)
- if statsError {
- Text("Could not load stats")
- .font(.caption)
- .foregroundStyle(.tertiary)
- } else if let stats {
- let parts = [
- stats.tracks.map { "\($0) tracks" },
- stats.albums.map { "\($0) albums" },
- stats.artists.map { "\($0) artists" },
- ].compactMap { $0 }
- Text(parts.joined(separator: " · "))
- .font(.caption)
- .foregroundStyle(.secondary)
- } else {
- Text("Loading...")
- .font(.caption)
- .foregroundStyle(.tertiary)
- }
- Spacer()
- uploadControl
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- .background(.bar)
- .task {
- do {
- stats = try await apiClient.fetchStats()
- } catch {
- statsError = true
- }
- }
- .onChange(of: uploadService.state) { _, newState in
- if case .success = newState {
- Task { stats = try? await apiClient.fetchStats() }
- }
- }
- .alert("Upload Failed", isPresented: $showUploadError) {
- Button("OK") { uploadService.dismiss() }
- } message: {
- if case .error(let msg) = uploadService.state {
- Text(msg)
- }
- }
- }
- @ViewBuilder
- private var uploadControl: some View {
- switch uploadService.state {
- case .idle:
- Button { chooseFile() } label: {
- Label("Upload", systemImage: "arrow.up.to.cloud")
- .font(.caption)
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- .help("Upload to Cloud")
- case .uploading(let fileName):
- HStack(spacing: 6) {
- ProgressView(value: uploadService.progress)
- .progressViewStyle(.linear)
- .frame(width: 60)
- Button { uploadService.cancel() } label: {
- Image(systemName: "xmark.circle.fill")
- .font(.system(size: 10))
- .foregroundStyle(.secondary)
- }
- .buttonStyle(.plain)
- .help("Cancel upload of \(fileName)")
- }
- case .success(let added, _):
- HStack(spacing: 4) {
- Image(systemName: "checkmark.circle.fill")
- .foregroundStyle(.green)
- .font(.caption)
- Text("\(added) added")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- .onAppear {
- Task {
- try? await Task.sleep(for: .seconds(3))
- uploadService.dismiss()
- }
- }
- case .error:
- Button { showUploadError = true } label: {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(.red)
- }
- .buttonStyle(.plain)
- .help("Upload failed — click for details")
- .onAppear { showUploadError = true }
- }
- }
- private func chooseFile() {
- let panel = NSOpenPanel()
- panel.title = "Choose Audio File to Upload"
- panel.allowedContentTypes = UploadService.allowedTypes
- panel.allowsMultipleSelection = false
- panel.canChooseDirectories = false
- guard panel.runModal() == .OK, let url = panel.url else { return }
- uploadService.startUpload(fileURL: url, apiClient: apiClient)
- }
- }
- // MARK: - Filtered Albums View (artist/genre/year → albums)
- private struct FilteredAlbumsView: View {
- let apiClient: ChadMusicAPIClient
- let filter: CategoryFilter
- @Binding var navStack: [CloudNavDestination]
- @State private var albums: [ChadAlbum] = []
- @State private var isLoading = true
- @State private var error: String?
- @State private var albumSearchText: String = ""
- @Environment(\.modelContext) private var modelContext
- @Query(sort: \Playlist.dateModified, order: .reverse) private var allPlaylists: [Playlist]
- /// Client-side filtered albums based on search text.
- private var filteredAlbums: [ChadAlbum] {
- guard !albumSearchText.isEmpty else { return albums }
- let query = albumSearchText.lowercased()
- return albums.filter { $0.title.lowercased().contains(query) }
- }
- var body: some View {
- Group {
- if isLoading {
- ProgressView("Loading albums...")
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if let error {
- VStack(spacing: 8) {
- Image(systemName: "exclamationmark.triangle")
- .font(.title)
- .foregroundStyle(.secondary)
- Text(error)
- .foregroundStyle(.secondary)
- Button("Retry") { loadAlbums() }
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if albums.isEmpty {
- Text("No albums found")
- .foregroundStyle(.secondary)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else {
- List {
- // Search field for filtering albums
- TextField("Search albums...", text: $albumSearchText)
- .textFieldStyle(.roundedBorder)
- .listRowSeparator(.hidden)
- .padding(.vertical, 4)
- // Header — draggable to add all albums by this artist/genre/etc.
- HStack {
- VStack(alignment: .leading, spacing: 2) {
- Text(filter.value)
- .font(.title2.bold())
- Text("\(albums.count) albums")
- .font(.caption)
- .foregroundStyle(.tertiary)
- }
- Spacer()
- Menu {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAllAlbumsToPlaylist(playlist: playlist)
- }
- }
- } label: {
- Label("Add All", systemImage: "plus.circle")
- .font(.caption)
- }
- .menuStyle(.borderlessButton)
- .fixedSize()
- }
- .listRowSeparator(.hidden)
- .padding(.vertical, 4)
- .contextMenu {
- Menu("Add All to Playlist") {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAllAlbumsToPlaylist(playlist: playlist)
- }
- }
- }
- }
- // Album rows
- if filteredAlbums.isEmpty && !albumSearchText.isEmpty {
- // No match — offer Soulseek search
- VStack(spacing: 12) {
- Text("\"\(albumSearchText)\" not in \(filter.value)'s library")
- .font(.callout)
- .foregroundStyle(.secondary)
- .multilineTextAlignment(.center)
- if SlskdAPIClient.shared.isConfigured {
- Button {
- navStack.append(.search(query: "\(filter.value) - \(albumSearchText)"))
- } label: {
- Label("Search Soulseek", systemImage: "magnifyingglass")
- }
- .buttonStyle(.bordered)
- .controlSize(.regular)
- }
- }
- .frame(maxWidth: .infinity)
- .padding(.vertical, 20)
- .listRowSeparator(.hidden)
- } else {
- ForEach(filteredAlbums) { album in
- Button {
- navStack.append(.album(album))
- } label: {
- HStack {
- VStack(alignment: .leading, spacing: 2) {
- Text(album.title)
- .lineLimit(1)
- if let artist = album.artist {
- Text(artist)
- .font(.caption)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- }
- Spacer()
- if let count = album.trackCount {
- Text("\(count)")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- Image(systemName: "chevron.right")
- .font(.caption2)
- .foregroundStyle(.tertiary)
- }
- }
- .buttonStyle(.plain)
- .contextMenu {
- Menu("Add Album to Playlist") {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAlbumToPlaylist(album, playlist: playlist)
- }
- }
- }
- }
- .draggable(album)
- }
- } // end else (filtered albums not empty)
- }
- .listStyle(.inset)
- }
- }
- .task { loadAlbums() }
- }
- private func loadAlbums() {
- isLoading = true
- error = nil
- Task {
- do {
- albums = try await apiClient.fetchAlbums(filteredBy: filter.category.rawValue, value: filter.value)
- } catch {
- self.error = error.localizedDescription
- }
- isLoading = false
- }
- }
- private func addAlbumToPlaylist(_ album: ChadAlbum, playlist: Playlist) {
- Task.detached {
- guard let tracks = try? await apiClient.fetchAlbumTracks(albumId: album.id) else { return }
- await MainActor.run {
- let descriptor = FetchDescriptor<Track>(predicate: #Predicate<Track> { $0.isCloud == true })
- let existing = (try? modelContext.fetch(descriptor)) ?? []
- let existingById = Dictionary(uniqueKeysWithValues: existing.compactMap { t in
- t.cloudTrackId.map { ($0, t) }
- })
- for chadTrack in tracks {
- let track = existingById[chadTrack.id] ?? {
- let t = Track.fromCloud(chadTrack)
- modelContext.insert(t)
- return t
- }()
- playlist.addTrack(track)
- }
- }
- }
- }
- private func addAllAlbumsToPlaylist(playlist: Playlist) {
- for album in albums {
- addAlbumToPlaylist(album, playlist: playlist)
- }
- }
- }
- // MARK: - Category Detail (list of albums/artists/etc.)
- private struct CategoryDetailView: View {
- let apiClient: ChadMusicAPIClient
- let category: ChadCategoryType
- @Binding var navStack: [CloudNavDestination]
- @State private var items: [ChadCategory] = []
- @State private var albums: [ChadAlbum] = []
- @State private var isLoading = true
- @State private var error: String?
- @State private var bulkAddingAlbum: String? // album ID being bulk-added
- @Environment(\.modelContext) private var modelContext
- @Query(sort: \Playlist.dateModified, order: .reverse) private var allPlaylists: [Playlist]
- /// Album category returns [ChadAlbum], all others return [ChadCategory].
- private var isAlbumCategory: Bool { category == .album }
- var body: some View {
- Group {
- if isLoading {
- ProgressView("Loading \(category.displayName)...")
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if let error {
- VStack(spacing: 8) {
- Image(systemName: "exclamationmark.triangle")
- .font(.title)
- .foregroundStyle(.secondary)
- Text(error)
- .foregroundStyle(.secondary)
- Button("Retry") { loadItems() }
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if isAlbumCategory {
- List(albums) { album in
- Button {
- navStack.append(.album(album))
- } label: {
- HStack {
- VStack(alignment: .leading, spacing: 2) {
- Text(album.title)
- .lineLimit(1)
- if let artist = album.artist {
- Text(artist)
- .font(.caption)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- }
- Spacer()
- if bulkAddingAlbum == album.id {
- ProgressView()
- .controlSize(.small)
- } else if let count = album.trackCount {
- Text("\(count)")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- Image(systemName: "chevron.right")
- .font(.caption2)
- .foregroundStyle(.tertiary)
- }
- }
- .buttonStyle(.plain)
- .contextMenu {
- Menu("Add Album to Playlist") {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAlbumToPlaylist(album, playlist: playlist)
- }
- }
- }
- }
- .draggable(album)
- }
- .listStyle(.inset)
- } else {
- List(items) { item in
- Button {
- navStack.append(.filter(CategoryFilter(category: category, value: item.name)))
- } label: {
- HStack {
- categoryRow(item)
- Image(systemName: "chevron.right")
- .font(.caption2)
- .foregroundStyle(.tertiary)
- }
- }
- .buttonStyle(.plain)
- }
- .listStyle(.inset)
- }
- }
- .task { loadItems() }
- }
- private func categoryRow(_ item: ChadCategory) -> some View {
- HStack {
- Text(item.name)
- Spacer()
- if let count = item.count {
- Text("\(count)")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- }
- }
- private func loadItems() {
- isLoading = true
- error = nil
- Task {
- do {
- if isAlbumCategory {
- albums = try await apiClient.fetchAlbums()
- } else {
- items = try await apiClient.fetchCategory(category)
- }
- } catch {
- self.error = error.localizedDescription
- }
- isLoading = false
- }
- }
- private func addAlbumToPlaylist(_ album: ChadAlbum, playlist: Playlist) {
- bulkAddingAlbum = album.id
- Task.detached {
- let chadTracks: [ChadTrack]
- do {
- chadTracks = try await apiClient.fetchAlbumTracks(albumId: album.id)
- } catch {
- print("CloudBrowser: Failed to fetch album tracks: \(error)")
- await MainActor.run { bulkAddingAlbum = nil }
- return
- }
- await MainActor.run {
- bulkInsertCloudTracks(chadTracks, into: playlist)
- bulkAddingAlbum = nil
- }
- }
- }
- private func bulkInsertCloudTracks(_ chadTracks: [ChadTrack], into playlist: Playlist) {
- // Batch dedup: fetch all existing cloud tracks in one query
- let ids = chadTracks.map(\.id)
- let descriptor = FetchDescriptor<Track>(predicate: #Predicate<Track> { track in
- track.isCloud == true
- })
- let existingTracks = (try? modelContext.fetch(descriptor)) ?? []
- let existingById = Dictionary(uniqueKeysWithValues: existingTracks.compactMap { t in
- t.cloudTrackId.map { ($0, t) }
- })
- for chadTrack in chadTracks {
- let track = existingById[chadTrack.id] ?? {
- let newTrack = Track.fromCloud(chadTrack)
- modelContext.insert(newTrack)
- return newTrack
- }()
- playlist.addTrack(track)
- }
- }
- }
- // MARK: - Album Detail (track list with play buttons)
- private struct AlbumDetailView: View {
- let apiClient: ChadMusicAPIClient
- let album: ChadAlbum
- @Binding var navStack: [CloudNavDestination]
- @Environment(PlayerViewModel.self) private var playerVM
- @Environment(\.modelContext) private var modelContext
- @Query(sort: \Playlist.dateModified, order: .reverse) private var allPlaylists: [Playlist]
- @State private var tracks: [ChadTrack] = []
- @State private var isLoading = true
- @State private var error: String?
- @AppStorage("playbackMode") private var playbackMode: String = "queue"
- @State private var downloadManager = DownloadManager.shared
- /// Persisted Track objects for cloud tracks (used for download state tracking).
- @State private var persistedTracks: [String: Track] = [:]
- var body: some View {
- Group {
- if isLoading {
- ProgressView("Loading tracks...")
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if let error {
- VStack(spacing: 8) {
- Image(systemName: "exclamationmark.triangle")
- .font(.title)
- .foregroundStyle(.secondary)
- Text(error)
- .foregroundStyle(.secondary)
- Button("Retry") { loadTracks() }
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else {
- List {
- // Album header — draggable to add whole album to playlist
- VStack(alignment: .leading, spacing: 4) {
- Text(album.title)
- .font(.title2.bold())
- if let artist = album.artist {
- Text(artist)
- .font(.title3)
- .foregroundStyle(.secondary)
- }
- HStack {
- Text("\(tracks.count) tracks")
- .font(.caption)
- .foregroundStyle(.tertiary)
- Spacer()
- AlbumDownloadButton(
- tracks: Array(persistedTracks.values),
- apiClient: apiClient
- )
- Menu {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAllToPlaylist(playlist: playlist)
- }
- }
- } label: {
- Label("Add All", systemImage: "plus.circle")
- .font(.caption)
- }
- .menuStyle(.borderlessButton)
- .fixedSize()
- }
- }
- .listRowSeparator(.hidden)
- .padding(.vertical, 8)
- .draggable(album)
- .contextMenu {
- if playbackMode == "queue" {
- Button {
- for track in tracks {
- playerVM.playNextInQueue(QueueEntry.from(cloudTrack: track))
- }
- } label: {
- Label("Play Album Next", systemImage: "text.line.first.and.arrowtriangle.forward")
- }
- Button {
- for track in tracks {
- playerVM.addToQueue(QueueEntry.from(cloudTrack: track))
- }
- } label: {
- Label("Add Album to Queue", systemImage: "text.append")
- }
- Divider()
- }
- Menu("Add Album to Playlist") {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addAllToPlaylist(playlist: playlist)
- }
- }
- }
- Divider()
- Button {
- let persisted = tracks.map { ensurePersistedTrack(for: $0) }
- downloadManager.downloadBatch(tracks: persisted, apiClient: apiClient)
- } label: {
- Label("Download All", systemImage: "arrow.down.circle")
- }
- }
- // Track rows
- ForEach(tracks) { track in
- CloudTrackRow(
- track: track,
- isPlaying: playerVM.isCloudPlayback && (
- playerVM.currentCloudTrack?.id == track.id ||
- playerVM.currentTrack?.cloudTrackId == track.id
- ),
- persistedTrack: persistedTracks[track.id],
- onDownload: {
- let persisted = ensurePersistedTrack(for: track)
- downloadManager.download(track: persisted, apiClient: apiClient)
- }
- )
- .contentShape(Rectangle())
- .onTapGesture {
- playCloudTrack(track)
- }
- .onDrag {
- let data = try? JSONEncoder().encode(track)
- let provider = NSItemProvider()
- if let data {
- provider.registerDataRepresentation(
- forTypeIdentifier: "com.mixboard.chad-track",
- visibility: .all
- ) { completion in
- completion(data, nil)
- return nil
- }
- }
- return provider
- }
- .contextMenu {
- Button {
- playCloudTrack(track)
- } label: {
- Label("Play", systemImage: "play")
- }
- Divider()
- if playbackMode == "queue" {
- Button {
- playerVM.playNextInQueue(QueueEntry.from(cloudTrack: track))
- } label: {
- Label("Play Next", systemImage: "text.line.first.and.arrowtriangle.forward")
- }
- Button {
- playerVM.addToQueue(QueueEntry.from(cloudTrack: track))
- } label: {
- Label("Add to Queue", systemImage: "text.append")
- }
- Divider()
- }
- // Download actions
- if let persisted = persistedTracks[track.id] {
- downloadContextMenuItems(for: persisted)
- Divider()
- } else {
- Button {
- let persisted = ensurePersistedTrack(for: track)
- downloadManager.download(track: persisted, apiClient: apiClient)
- } label: {
- Label("Download", systemImage: "arrow.down.circle")
- }
- Divider()
- }
- Menu("Add to Playlist") {
- ForEach(allPlaylists) { playlist in
- Button(playlist.name) {
- addToPlaylist(track, playlist: playlist)
- }
- }
- }
- }
- }
- }
- .listStyle(.inset)
- }
- }
- .task {
- loadTracks()
- loadPersistedTracks()
- }
- }
- private func loadTracks() {
- isLoading = true
- error = nil
- Task {
- do {
- tracks = try await apiClient.fetchAlbumTracks(albumId: album.id)
- loadPersistedTracks()
- } catch {
- self.error = error.localizedDescription
- }
- isLoading = false
- }
- }
- private func loadPersistedTracks() {
- let descriptor = FetchDescriptor<Track>(predicate: #Predicate<Track> { $0.isCloud == true })
- guard let existing = try? modelContext.fetch(descriptor) else { return }
- var map: [String: Track] = [:]
- for t in existing {
- if let id = t.cloudTrackId {
- map[id] = t
- }
- }
- persistedTracks = map
- }
- /// Ensure a ChadTrack has a persisted SwiftData Track. Returns the persisted track.
- private func ensurePersistedTrack(for chadTrack: ChadTrack) -> Track {
- if let existing = persistedTracks[chadTrack.id] {
- return existing
- }
- let track = Track.fromCloud(chadTrack)
- modelContext.insert(track)
- persistedTracks[chadTrack.id] = track
- return track
- }
- @ViewBuilder
- private func downloadContextMenuItems(for track: Track) -> some View {
- switch track.downloadState {
- case .none:
- Button {
- downloadManager.download(track: track, apiClient: apiClient)
- } label: {
- Label("Download", systemImage: "arrow.down.circle")
- }
- case .downloading:
- Button {
- downloadManager.cancel(track: track)
- } label: {
- Label("Cancel Download", systemImage: "stop.circle")
- }
- case .downloaded:
- Button(role: .destructive) {
- downloadManager.removeDownload(track: track)
- } label: {
- Label("Remove Download", systemImage: "trash")
- }
- case .error:
- Button {
- downloadManager.download(track: track, apiClient: apiClient)
- } label: {
- Label("Retry Download", systemImage: "arrow.clockwise")
- }
- }
- }
- private func playCloudTrack(_ track: ChadTrack) {
- guard let url = apiClient.streamURL(for: track.url) else {
- print("CloudBrowser: Failed to build stream URL for \(track.url)")
- return
- }
- playerVM.loadAndPlayCloud(track, streamURL: url, authHeaders: apiClient.authHeaders)
- }
- private func addToPlaylist(_ chadTrack: ChadTrack, playlist: Playlist) {
- let cloudId = chadTrack.id
- let descriptor = FetchDescriptor<Track>(predicate: #Predicate { $0.cloudTrackId == cloudId })
- let existing = try? modelContext.fetch(descriptor).first
- let track = existing ?? Track.fromCloud(chadTrack)
- if existing == nil {
- modelContext.insert(track)
- }
- playlist.addTrack(track)
- }
- private func addAllToPlaylist(playlist: Playlist) {
- for chadTrack in tracks {
- addToPlaylist(chadTrack, playlist: playlist)
- }
- }
- }
- // MARK: - Cloud Track Row
- private struct CloudTrackRow: View {
- let track: ChadTrack
- let isPlaying: Bool
- var persistedTrack: Track?
- var onDownload: (() -> Void)? = nil
- var body: some View {
- HStack(spacing: 12) {
- // Track number or playing indicator
- Group {
- if isPlaying {
- Image(systemName: "speaker.wave.2.fill")
- .foregroundStyle(Color.accentColor)
- } else if let num = track.trackNumber {
- Text("\(num)")
- .foregroundStyle(.secondary)
- } else {
- Text("—")
- .foregroundStyle(.tertiary)
- }
- }
- .font(.system(size: 12, design: .monospaced))
- .frame(width: 28, alignment: .trailing)
- // Title + artist
- VStack(alignment: .leading, spacing: 1) {
- Text(track.title)
- .font(.system(size: 13))
- .foregroundStyle(isPlaying ? Color.accentColor : .primary)
- .lineLimit(1)
- if let artist = track.artist {
- Text(artist)
- .font(.system(size: 11))
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- }
- Spacer()
- // Upload / download indicator for cloud tracks
- if let persistedTrack {
- DownloadIndicator(track: persistedTrack)
- } else {
- Button {
- onDownload?()
- } label: {
- Image(systemName: "arrow.down.circle")
- .font(.system(size: 14))
- .foregroundStyle(.tertiary)
- .frame(width: 20, height: 20)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .help("Download for offline playback")
- }
- // Duration
- Text(track.formattedDuration)
- .font(.system(size: 12, design: .monospaced))
- .foregroundStyle(.secondary)
- .frame(width: 40, alignment: .trailing)
- }
- .padding(.vertical, 2)
- }
- }
- // MARK: - Soulseek Status Banner
- /// Persistent overlay at the bottom of CloudBrowserView showing Soulseek pipeline status.
- private struct SoulseekStatusBanner: View {
- let orchestrator: SoulseekOrchestrator
- var body: some View {
- let state = orchestrator.state
- if state != .idle {
- HStack(spacing: 10) {
- // Progress indicator
- if state.isActive {
- if case .downloading(let progress) = state {
- ProgressView(value: progress)
- .progressViewStyle(.circular)
- .controlSize(.small)
- } else {
- ProgressView()
- .controlSize(.small)
- }
- } else if case .complete = state {
- Image(systemName: "checkmark.circle.fill")
- .foregroundStyle(.green)
- } else if case .failed = state {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(.red)
- }
- // Status text
- Text(state.statusText)
- .font(.system(size: 12))
- .foregroundStyle(state.isActive ? .primary : .secondary)
- .lineLimit(1)
- Spacer()
- // Action button
- if state.isActive {
- Button("Cancel") {
- orchestrator.cancel()
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- } else {
- Button("Dismiss") {
- orchestrator.dismiss()
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- }
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
- .background(.ultraThinMaterial)
- .transition(.move(edge: .bottom).combined(with: .opacity))
- .animation(.easeInOut(duration: 0.3), value: state != .idle)
- }
- }
- }
|