Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music9// File : Features/Playlists/PlaylistViews.swift10// Description : Playlists: list, detail with reordering, add-to-playlist11// sheet.12// Module : Features13// Repository : https://git.spboucher.ai/sp-music-ios14// Created : 2026-11-1715// Last Modified : 2026-11-1716//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import SPMusicCore90import SwiftUI9192struct PlaylistsView: View {93 @Environment(AppEnvironment.self) private var env94 @State private var playlists: [Playlist] = []95 @State private var loaded = false96 @State private var creating = false97 @State private var name = ""9899 var body: some View {100 List(playlists) { p in101 NavigationLink(value: Route.playlist(p.id)) {102 HStack(spacing: 12) {103 MosaicArtwork(ids: p.artworkIds, side: 56, corner: 8)104 VStack(alignment: .leading, spacing: 2) { Text(p.name).lineLimit(1); Text("\(p.trackCount) titre\(p.trackCount > 1 ? "s" : "")").font(.footnote).foregroundStyle(Color.spMuted) }105 }106 }107 .listRowBackground(Color.spBackground)108 }109 .listStyle(.plain).scrollContentBackground(.hidden).background(Color.spBackground)110 .overlay {111 if loaded && playlists.isEmpty {112 ContentUnavailableView { Label("Aucune liste de lecture", systemImage: "music.note.list") } description: { Text("Créez une liste, puis ajoutez-y des titres depuis leur menu.") }113 actions: { Button("Nouvelle liste") { creating = true }.buttonStyle(.borderedProminent) }114 }115 }116 .navigationTitle("Listes de lecture")117 .toolbar { Button { creating = true } label: { Image(systemName: "plus") }.accessibilityLabel("Nouvelle liste de lecture") }118 .alert("Nouvelle liste de lecture", isPresented: $creating) {119 TextField("Nom", text: $name)120 Button("Créer") { let n = name.trimmingCharacters(in: .whitespaces); name = ""; if !n.isEmpty { Task { _ = await env.playlistEdit { _ = try await $0.createPlaylist(name: n) } } } }121 Button("Annuler", role: .cancel) { name = "" }122 }123 .task(id: env.reloadKey()) { playlists = await env.db.playlists(); loaded = true }124 }125}126127struct PlaylistDetailView: View {128 @Environment(AppEnvironment.self) private var env129 @Environment(\.dismiss) private var dismiss130 let playlistId: String131 @State private var playlist: Playlist?132 @State private var tracks: [Track] = []133 @State private var loaded = false134 @State private var renaming = false135 @State private var name = ""136 @State private var confirmDelete = false137 @State private var playlistFor: Track?138139 var body: some View {140 List {141 if let playlist {142 VStack(spacing: 12) {143 MosaicArtwork(ids: playlist.artworkIds, side: 200, corner: 14).shadow(radius: 14, y: 8)144 Text(playlist.name).font(.title2.bold()).multilineTextAlignment(.center).accessibilityIdentifier("playlist-title")145 Text("\(tracks.count) titre\(tracks.count > 1 ? "s" : "") · \(Format.longDuration(ms: tracks.reduce(0) { $0 + $1.durationMs }))").font(.footnote).foregroundStyle(Color.spMuted)146 if !tracks.isEmpty {147 PlayShuffleButtons(tracks: tracks).frame(maxWidth: 420)148 DownloadButton(kind: .playlist, id: playlist.id, label: "Télécharger la liste").buttonStyle(.bordered).tint(Color.spEmber)149 }150 }151 .frame(maxWidth: .infinity).listRowSeparator(.hidden).listRowBackground(Color.spBackground)152 ForEach(Array(tracks.enumerated()), id: \.offset) { i, t in153 TrackRow(track: t, onAddToPlaylist: { playlistFor = $0 }) { env.play(tracks, startAt: i) }.listRowBackground(Color.spBackground)154 }155 .onMove { from, to in reorder { $0.move(fromOffsets: from, toOffset: to) } }156 .onDelete { idx in reorder { $0.remove(atOffsets: idx) } }157 }158 }159 .listStyle(.plain).scrollContentBackground(.hidden).background(Color.spBackground)160 .overlay {161 if loaded && playlist == nil { ContentUnavailableView("Liste introuvable", systemImage: "music.note.list") }162 else if loaded && tracks.isEmpty { ContentUnavailableView("Liste vide", systemImage: "music.note.list", description: Text("Ajoutez des titres depuis leur menu « … ».")).padding(.top, 260) }163 }164 .navigationBarTitleDisplayMode(.inline)165 .toolbar {166 if playlist != nil {167 EditButton().disabled(!env.isOnline || tracks.isEmpty)168 Menu {169 Button { name = playlist?.name ?? ""; renaming = true } label: { Label("Renommer", systemImage: "pencil") }170 Button(role: .destructive) { confirmDelete = true } label: { Label("Supprimer la liste", systemImage: "trash") }171 } label: { Image(systemName: "ellipsis.circle") }.accessibilityLabel("Actions de la liste")172 }173 }174 .alert("Renommer la liste", isPresented: $renaming) {175 TextField("Nom", text: $name)176 Button("Renommer") { let n = name.trimmingCharacters(in: .whitespaces); if !n.isEmpty { Task { _ = await env.playlistEdit { try await $0.renamePlaylist(id: playlistId, name: n) } } } }177 Button("Annuler", role: .cancel) {}178 }179 .confirmationDialog("Supprimer cette liste de lecture ?", isPresented: $confirmDelete, titleVisibility: .visible) {180 Button("Supprimer", role: .destructive) { Task { if await env.playlistEdit({ try await $0.deletePlaylist(id: playlistId) }) { await env.removeDownload(.playlist, playlistId); dismiss() } } }181 } message: { Text("Les titres restent dans la bibliothèque.") }182 .sheet(item: $playlistFor) { AddToPlaylistSheet(tracks: [$0]) }183 .dropDestination(for: String.self) { items, _ in184 let ids = items.compactMap { $0.hasPrefix("spmusic-track:") ? String($0.dropFirst(14)) : nil }185 guard !ids.isEmpty else { return false }186 Task { _ = await env.playlistEdit { try await $0.addToPlaylist(id: playlistId, trackIds: ids) } }187 return true188 }189 .task(id: env.reloadKey(playlistId)) {190 playlist = await env.db.playlist(id: playlistId)191 tracks = await env.db.playlistTracks(id: playlistId, downloadedOnly: env.downloadedOnly)192 loaded = true193 }194 }195196 /// The server takes the whole new order as entry identifiers; entries left out are removed.197 private func reorder(_ change: (inout [Track]) -> Void) {198 var next = tracks199 change(&next)200 let before = tracks201 tracks = next202 let entries = next.compactMap(\.entryId)203 Task { if !(await env.playlistEdit { try await $0.orderPlaylist(id: playlistId, entryIds: entries) }) { tracks = before } }204 }205}206207struct AddToPlaylistSheet: View {208 @Environment(AppEnvironment.self) private var env209 @Environment(\.dismiss) private var dismiss210 let tracks: [Track]211 @State private var playlists: [Playlist] = []212 @State private var name = ""213214 var body: some View {215 NavigationStack {216 List {217 Section("Nouvelle liste") {218 HStack {219 TextField("Nom de la liste", text: $name).submitLabel(.done).onSubmit(create)220 Button("Créer", action: create).disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)221 }222 }223 if !playlists.isEmpty {224 Section("Ajouter à") {225 ForEach(playlists) { p in226 Button {227 let ids = tracks.map(\.id)228 Task { if await env.playlistEdit({ try await $0.addToPlaylist(id: p.id, trackIds: ids) }) { env.toast = "Ajouté à « \(p.name) »" }; dismiss() }229 } label: {230 HStack(spacing: 12) { MosaicArtwork(ids: p.artworkIds, side: 44, corner: 6); Text(p.name).foregroundStyle(.primary); Spacer(); Text("\(p.trackCount)").foregroundStyle(Color.spMuted) }231 }232 }233 }234 }235 }236 .navigationTitle("Ajouter à une liste").navigationBarTitleDisplayMode(.inline)237 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } }238 .task { playlists = await env.db.playlists() }239 }240 .presentationDetents([.medium, .large])241 }242 private func create() {243 let n = name.trimmingCharacters(in: .whitespaces)244 guard !n.isEmpty else { return }245 let ids = tracks.map(\.id)246 Task { if await env.playlistEdit({ _ = try await $0.createPlaylist(name: n, trackIds: ids) }) { env.toast = "Liste « \(n) » créée" }; dismiss() }247 }248}249extension Track: @retroactive Transferable {250 public static var transferRepresentation: some TransferRepresentation { ProxyRepresentation(exporting: { "spmusic-track:\($0.id)" }) }251}252