Compare commits

..
10 Commits
10 changed files with 795 additions and 72 deletions

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ The iOS client is closed source for now. It targets iOS only and uses SwiftUI fo
- **Catalog pages:** album pages show artwork, title, artists, Play and Shuffle actions, and the album’s tracks. Artist pages show artist artwork/name, Play and Shuffle actions, the artist’s tracks, and albums. A separate artist Songs page lists that artist’s tracks. Tracks link to their album and artist pages. - **Catalog pages:** album pages show artwork, title, artists, Play and Shuffle actions, and the album’s tracks. Artist pages show artist artwork/name, Play and Shuffle actions, the artist’s tracks, and albums. A separate artist Songs page lists that artist’s tracks. Tracks link to their album and artist pages.
- **Personal library:** tracks can be saved to and removed from the signed-in user’s Library. Library navigation has Songs, Albums, and Artists views. Songs can be played in order or shuffled and removed from the Library. The Albums and Artists lists are derived from the user’s saved tracks; they are not separately saved collections. - **Personal library:** tracks can be saved to and removed from the signed-in user’s Library. Library navigation has Songs, Albums, and Artists views. Songs can be played in order or shuffled and removed from the Library. The Albums and Artists lists are derived from the user’s saved tracks; they are not separately saved collections.
- **Playback:** provide persistent playback controls for current track/artwork and artist, play/pause, previous/next, shuffle, repeat, seek with elapsed/remaining time, volume, queue access, and fullscreen player access. Track actions include playing only that track, playing next, adding to queue, saving/removing from Library, and navigating to the track’s artist or album. The queue can be reordered and tracks in it can be selected for playback. Preserve appropriate iOS background/audio-session and system media-control behavior when implementing the equivalent native experience. - **Playback:** provide persistent playback controls for current track/artwork and artist, play/pause, previous/next, shuffle, repeat, seek with elapsed/remaining time, volume, queue access, and fullscreen player access. Track actions include playing only that track, playing next, adding to queue, saving/removing from Library, and navigating to the track’s artist or album. The queue can be reordered and tracks in it can be selected for playback. Preserve appropriate iOS background/audio-session and system media-control behavior when implementing the equivalent native experience.
- **Playback handoff:** after authentication, restore the unexpired playback handoff only if the player is empty. Save current track, position, queue, history, repeat mode, and playing state through `/api/user/playback-handoff`; refresh position every 15 seconds while playing and save on meaningful state changes or app backgrounding. Consume the handoff only after a successful playing or paused restore, and clear it when the player is cleared. Handoff failures must not interrupt local playback.
- **Fullscreen player and lyrics:** show artwork, track and artist, playback controls, seek and volume controls over an animated, artwork-derived color wash. Display plain lyrics when available. For synced lyrics, highlight and follow the current line and allow tapping a line to seek to its timestamp. Lyrics may be absent or unsynced. - **Fullscreen player and lyrics:** show artwork, track and artist, playback controls, seek and volume controls over an animated, artwork-derived color wash. Display plain lyrics when available. For synced lyrics, highlight and follow the current line and allow tapping a line to seek to its timestamp. Lyrics may be absent or unsynced.
- **Admin catalog tools:** the web app exposes an admin-only panel with tables for genres, artists, albums, and songs, plus create/edit forms. Forms support artist artwork, album artwork/artists/genre, and song audio/artists/album plus lyrics and synced-lyrics metadata. Song creation can create a single album as part of the flow. The backend has delete APIs, but the current web table delete buttons are unimplemented; do not present deletion as an existing user-facing flow unless the web UI implements it. Keep administration restricted to admin accounts. - **Admin catalog tools:** the web app exposes an admin-only panel with tables for genres, artists, albums, and songs, plus create/edit forms. Forms support artist artwork, album artwork/artists/genre, and song audio/artists/album plus lyrics and synced-lyrics metadata. Song creation can create a single album as part of the flow. The backend has delete APIs, but the current web table delete buttons are unimplemented; do not present deletion as an existing user-facing flow unless the web UI implements it. Keep administration restricted to admin accounts.
+10
View File
@@ -1,6 +1,8 @@
import SwiftUI import SwiftUI
struct ContentView: View { struct ContentView: View {
@EnvironmentObject private var player: PlayerManager
@Environment(\.scenePhase) private var scenePhase
@StateObject private var session: AuthSessionStore @StateObject private var session: AuthSessionStore
private let restoresSession: Bool private let restoresSession: Bool
@@ -28,6 +30,7 @@ struct ContentView: View {
} }
} }
.task { .task {
player.setAuthenticated(session.state == .signedIn)
guard restoresSession else { return } guard restoresSession else { return }
#if DEBUG #if DEBUG
print("[ContentView] session restore task started") print("[ContentView] session restore task started")
@@ -36,6 +39,13 @@ struct ContentView: View {
} }
#endif #endif
await session.restoreSession() await session.restoreSession()
player.setAuthenticated(session.state == .signedIn)
}
.onChange(of: session.state) { _, state in
player.setAuthenticated(state == .signedIn)
}
.onChange(of: scenePhase) { _, phase in
if phase == .background { player.saveHandoffForBackground() }
} }
} }
} }
-6
View File
@@ -110,9 +110,6 @@ public final class APIClient: @unchecked Sendable {
guard let url = components.url else { throw APIError.invalidURL } guard let url = components.url else { throw APIError.invalidURL }
if let cookieStorage = session.configuration.httpCookieStorage { if let cookieStorage = session.configuration.httpCookieStorage {
AuthCookiePersistence.restore(into: cookieStorage, for: url) AuthCookiePersistence.restore(into: cookieStorage, for: url)
if path.hasPrefix("auth/") {
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "before \(path)")
}
} }
var request = URLRequest(url: url) var request = URLRequest(url: url)
request.httpMethod = method request.httpMethod = method
@@ -130,9 +127,6 @@ public final class APIClient: @unchecked Sendable {
let (data, rawResponse) = try await session.data(for: request) let (data, rawResponse) = try await session.data(for: request)
if let cookieStorage = session.configuration.httpCookieStorage { if let cookieStorage = session.configuration.httpCookieStorage {
AuthCookiePersistence.save(from: cookieStorage, for: url) AuthCookiePersistence.save(from: cookieStorage, for: url)
if path.hasPrefix("auth/") {
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "after \(path)")
}
} }
guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse } guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse }
guard (200..<300).contains(http.statusCode) else { guard (200..<300).contains(http.statusCode) else {
+1 -23
View File
@@ -9,19 +9,16 @@ enum AuthCookiePersistence {
static func restore(into storage: HTTPCookieStorage, for url: URL) { static func restore(into storage: HTTPCookieStorage, for url: URL) {
guard let data = read() else { guard let data = read() else {
debug("restore: no Keychain record for host=\(url.host ?? "?")")
return return
} }
guard let properties = try? PropertyListSerialization.propertyList( guard let properties = try? PropertyListSerialization.propertyList(
from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else { from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else {
debug("restore: Keychain data could not be decoded (\(data.count) bytes)")
return return
} }
let cookies = properties.compactMap(HTTPCookie.init(properties:)) let cookies = properties.compactMap(HTTPCookie.init(properties:))
.filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true } .filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true }
storage.setCookies(cookies, for: url, mainDocumentURL: nil) storage.setCookies(cookies, for: url, mainDocumentURL: nil)
debug("restore: loaded \(cookies.count) cookies [\(cookieNames(cookies))] for host=\(url.host ?? "?")")
} }
static func save(from storage: HTTPCookieStorage, for url: URL) { static func save(from storage: HTTPCookieStorage, for url: URL) {
@@ -31,7 +28,6 @@ enum AuthCookiePersistence {
guard let data = try? PropertyListSerialization.data( guard let data = try? PropertyListSerialization.data(
fromPropertyList: properties, format: .binary, options: 0) fromPropertyList: properties, format: .binary, options: 0)
else { else {
debug("save: cookie properties could not be encoded [\(cookieNames(storage.cookies(for: url) ?? []))]")
return return
} }
@@ -46,16 +42,10 @@ enum AuthCookiePersistence {
var insert = query var insert = query
insert[kSecValueData as String] = data insert[kSecValueData as String] = data
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let addStatus = SecItemAdd(insert as CFDictionary, nil) SecItemAdd(insert as CFDictionary, nil)
debug("save: insert status=\(addStatus), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
} else {
debug("save: update status=\(status), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
} }
} }
static func logRequestCookies(from storage: HTTPCookieStorage, for url: URL, phase: String) {
debug("\(phase): request cookie names [\(cookieNames(storage.cookies(for: url) ?? []))] host=\(url.host ?? "?")")
}
static func clear() { static func clear() {
SecItemDelete([ SecItemDelete([
@@ -77,20 +67,8 @@ enum AuthCookiePersistence {
var result: CFTypeRef? var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result) let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess else { guard status == errSecSuccess else {
debug("read: Keychain status=\(status)")
return nil return nil
} }
debug("read: Keychain success")
return result as? Data return result as? Data
} }
private static func cookieNames(_ cookies: [HTTPCookie]) -> String {
cookies.map(\.name).sorted().joined(separator: ",")
}
private static func debug(_ message: String) {
#if DEBUG
print("[AuthCookiePersistence] pid=\(ProcessInfo.processInfo.processIdentifier) bundle=\(Bundle.main.bundleIdentifier ?? "?") \(message)")
#endif
}
} }
+62
View File
@@ -100,4 +100,66 @@ nonisolated public struct SearchResults: Decodable, Sendable {
} }
nonisolated public struct TrackMembership: Decodable, Sendable { public let contains: Bool } nonisolated public struct TrackMembership: Decodable, Sendable { public let contains: Bool }
nonisolated public struct PlaybackHandoff: Decodable, Sendable {
public let currentTrackId: String
public let position: Double
public let queueTrackIds: [String]
public let remainingTrackIds: [String]
public let historyTrackIds: [String]
public let repeatEnabled: Bool
public let repeatOnce: Bool
public let wasPlaying: Bool
enum CodingKeys: String, CodingKey {
case currentTrackId, position, queueTrackIds, remainingTrackIds, historyTrackIds
case repeatEnabled = "repeat"
case repeatOnce, wasPlaying
}
}
nonisolated public struct PlaybackHandoffBody: Encodable, Sendable {
public let currentTrackId: String
public let position: Double
public let queueTrackIds: [String]
public let remainingTrackIds: [String]
public let historyTrackIds: [String]
public let repeatEnabled: Bool
public let repeatOnce: Bool
public let wasPlaying: Bool
enum CodingKeys: String, CodingKey {
case currentTrackId, position, queueTrackIds, remainingTrackIds, historyTrackIds
case repeatEnabled = "repeat"
case repeatOnce, wasPlaying
}
public init(
currentTrackId: String,
position: Double,
queueTrackIds: [String],
remainingTrackIds: [String],
historyTrackIds: [String],
repeatEnabled: Bool,
repeatOnce: Bool,
wasPlaying: Bool
) {
self.currentTrackId = currentTrackId
self.position = position
self.queueTrackIds = queueTrackIds
self.remainingTrackIds = remainingTrackIds
self.historyTrackIds = historyTrackIds
self.repeatEnabled = repeatEnabled
self.repeatOnce = repeatOnce
self.wasPlaying = wasPlaying
}
}
nonisolated public struct PlaybackHandoffSaveResponse: Decodable, Sendable {
public let saved: Bool
public let expiresAt: String
}
nonisolated public struct PlaybackHandoffDeleteResponse: Decodable, Sendable {
public let deleted: Bool
}
nonisolated public enum SearchType: String, Sendable { case track, album, artist, `default` } nonisolated public enum SearchType: String, Sendable { case track, album, artist, `default` }
+12
View File
@@ -109,6 +109,18 @@ public struct MusicAPI: Sendable {
let _: APIClient.EmptyResponse = try await client.request( let _: APIClient.EmptyResponse = try await client.request(
"DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) "DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) })
} }
public func playbackHandoff() async throws -> PlaybackHandoff? {
try await client.request("GET", path: "user/playback-handoff")
}
@discardableResult
public func savePlaybackHandoff(_ body: PlaybackHandoffBody) async throws
-> PlaybackHandoffSaveResponse
{
try await client.request("PUT", path: "user/playback-handoff", body: body)
}
public func deletePlaybackHandoff() async throws -> PlaybackHandoffDeleteResponse {
try await client.request("DELETE", path: "user/playback-handoff")
}
public func tracks(ids: [String]) async throws -> [Track] { public func tracks(ids: [String]) async throws -> [Track] {
try await client.request( try await client.request(
"GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) "GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) })
+355 -1
View File
@@ -21,7 +21,10 @@ final class PlayerManager: ObservableObject {
@Published private(set) var duration: TimeInterval = 0 @Published private(set) var duration: TimeInterval = 0
@Published private(set) var errorMessage: String? @Published private(set) var errorMessage: String?
@Published var repeatMode: PlayerRepeatMode = .off { @Published var repeatMode: PlayerRepeatMode = .off {
didSet { applyRepeatMode() } didSet {
applyRepeatMode()
scheduleHandoffSave()
}
} }
@Published var volume: Double { @Published var volume: Double {
didSet { didSet {
@@ -38,8 +41,20 @@ final class PlayerManager: ObservableObject {
private static let volumeStorageKey = "music-v2-player-volume" private static let volumeStorageKey = "music-v2-player-volume"
private let player = QueuedAudioPlayer() private let player = QueuedAudioPlayer()
private let apiConfiguration: APIConfiguration private let apiConfiguration: APIConfiguration
private let api = MusicAPI()
private var tracksByItemID: [ObjectIdentifier: Track] = [:] private var tracksByItemID: [ObjectIdentifier: Track] = [:]
private var playbackIntent: Bool? private var playbackIntent: Bool?
private var isAuthenticated = false
private var handoffRestoreAttempted = false
private var handoffRestoreInProgress = false
private var handoffGeneration = 0
private var handoffSaveInFlight = false
private var handoffSavePending = false
private var handoffSaveTask: Task<Void, Never>?
private var handoffPositionTask: Task<Void, Never>?
private var handoffSeekSaveTask: Task<Void, Never>?
private var handoffLastSavedAt = Date.distantPast
private static let handoffSyncInterval: TimeInterval = 15
init() { init() {
self.apiConfiguration = APIConfiguration() self.apiConfiguration = APIConfiguration()
@@ -64,12 +79,18 @@ final class PlayerManager: ObservableObject {
errorMessage = error.localizedDescription errorMessage = error.localizedDescription
} }
refreshState() refreshState()
updateHandoffPositionTimer()
scheduleHandoffSave()
} }
func pause() { func pause() {
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = nil
playbackIntent = false playbackIntent = false
isPlaying = false isPlaying = false
player.pause() player.pause()
updateHandoffPositionTimer()
scheduleHandoffSave()
} }
func play(_ track: Track) { func play(_ track: Track) {
@@ -77,6 +98,9 @@ final class PlayerManager: ObservableObject {
} }
func play(_ tracks: [Track], startingAt index: Int = 0, shuffled: Bool = false) { func play(_ tracks: [Track], startingAt index: Int = 0, shuffled: Bool = false) {
invalidatePendingHandoffRestore()
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = nil
guard !tracks.isEmpty else { clear(); return } guard !tracks.isEmpty else { clear(); return }
guard tracks.indices.contains(index) else { return } guard tracks.indices.contains(index) else { return }
let orderedTracks: [Track] let orderedTracks: [Track]
@@ -101,12 +125,14 @@ final class PlayerManager: ObservableObject {
player.add(items: items, playWhenReady: true) player.add(items: items, playWhenReady: true)
refreshState() refreshState()
loadArtwork(for: player.currentItem) loadArtwork(for: player.currentItem)
scheduleHandoffSave()
} }
func next() { func next() {
player.next() player.next()
refreshState() refreshState()
loadArtwork(for: player.currentItem) loadArtwork(for: player.currentItem)
scheduleHandoffSave()
} }
func previous() { func previous() {
@@ -116,15 +142,24 @@ final class PlayerManager: ObservableObject {
player.previous() player.previous()
refreshState() refreshState()
loadArtwork(for: player.currentItem) loadArtwork(for: player.currentItem)
scheduleHandoffSave()
} }
} }
func seek(to seconds: TimeInterval) { func seek(to seconds: TimeInterval) {
player.seek(to: min(max(0, seconds), max(duration, 0))) player.seek(to: min(max(0, seconds), max(duration, 0)))
elapsedTime = min(max(0, seconds), max(duration, 0)) elapsedTime = min(max(0, seconds), max(duration, 0))
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = Task { [weak self] in
try? await Task.sleep(for: .milliseconds(500))
guard let self, !Task.isCancelled else { return }
self.handoffSeekSaveTask = nil
self.scheduleHandoffSave()
}
} }
func addToQueue(_ track: Track) { func addToQueue(_ track: Track) {
if currentTrack == nil { invalidatePendingHandoffRestore() }
guard let item = makeAudioItem(for: track) else { return } guard let item = makeAudioItem(for: track) else { return }
if player.currentItem == nil { if player.currentItem == nil {
player.add(item: item, playWhenReady: false) player.add(item: item, playWhenReady: false)
@@ -132,13 +167,16 @@ final class PlayerManager: ObservableObject {
player.add(item: item) player.add(item: item)
} }
refreshState() refreshState()
scheduleHandoffSave()
} }
func playNext(_ track: Track) { func playNext(_ track: Track) {
if currentTrack == nil { invalidatePendingHandoffRestore() }
guard let item = makeAudioItem(for: track) else { return } guard let item = makeAudioItem(for: track) else { return }
guard player.currentItem != nil else { guard player.currentItem != nil else {
player.add(item: item, playWhenReady: true) player.add(item: item, playWhenReady: true)
refreshState() refreshState()
scheduleHandoffSave()
return return
} }
do { do {
@@ -147,44 +185,58 @@ final class PlayerManager: ObservableObject {
errorMessage = error.localizedDescription errorMessage = error.localizedDescription
} }
refreshState() refreshState()
scheduleHandoffSave()
} }
func playQueuedTrack(at index: Int) { func playQueuedTrack(at index: Int) {
invalidatePendingHandoffRestore()
guard player.items.indices.contains(index) else { return } guard player.items.indices.contains(index) else { return }
do { do {
try player.jumpToItem(atIndex: index, playWhenReady: true) try player.jumpToItem(atIndex: index, playWhenReady: true)
refreshState() refreshState()
loadArtwork(for: player.currentItem) loadArtwork(for: player.currentItem)
scheduleHandoffSave()
} catch { } catch {
errorMessage = error.localizedDescription errorMessage = error.localizedDescription
} }
} }
func moveQueuedTrack(from sourceIndex: Int, to destinationIndex: Int) { func moveQueuedTrack(from sourceIndex: Int, to destinationIndex: Int) {
invalidatePendingHandoffRestore()
guard player.items.indices.contains(sourceIndex), guard player.items.indices.contains(sourceIndex),
player.items.indices.contains(destinationIndex) player.items.indices.contains(destinationIndex)
else { return } else { return }
do { do {
try player.moveItem(fromIndex: sourceIndex, toIndex: destinationIndex) try player.moveItem(fromIndex: sourceIndex, toIndex: destinationIndex)
refreshState() refreshState()
scheduleHandoffSave()
} catch { } catch {
errorMessage = error.localizedDescription errorMessage = error.localizedDescription
} }
} }
func removeQueuedTrack(at index: Int) { func removeQueuedTrack(at index: Int) {
invalidatePendingHandoffRestore()
guard player.items.indices.contains(index) else { return } guard player.items.indices.contains(index) else { return }
let item = player.items[index] let item = player.items[index]
do { do {
_ = try player.removeItem(at: index) _ = try player.removeItem(at: index)
tracksByItemID.removeValue(forKey: ObjectIdentifier(item as AnyObject)) tracksByItemID.removeValue(forKey: ObjectIdentifier(item as AnyObject))
refreshState() refreshState()
scheduleHandoffSave()
} catch { } catch {
errorMessage = error.localizedDescription errorMessage = error.localizedDescription
} }
} }
func clear() { func clear() {
invalidatePendingHandoffRestore()
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = nil
let pendingSave = handoffSaveTask
pendingSave?.cancel()
handoffSaveTask = nil
handoffSavePending = false
playbackIntent = nil playbackIntent = nil
player.clear() player.clear()
tracksByItemID.removeAll() tracksByItemID.removeAll()
@@ -195,6 +247,13 @@ final class PlayerManager: ObservableObject {
elapsedTime = 0 elapsedTime = 0
duration = 0 duration = 0
errorMessage = nil errorMessage = nil
if isAuthenticated {
Task {
await pendingSave?.value
guard isAuthenticated else { return }
_ = try? await api.deletePlaybackHandoff()
}
}
} }
func artworkURL(for track: Track) -> URL? { func artworkURL(for track: Track) -> URL? {
@@ -203,6 +262,7 @@ final class PlayerManager: ObservableObject {
} }
func shuffleUpcoming() { func shuffleUpcoming() {
invalidatePendingHandoffRestore()
let currentIndex = player.currentIndex let currentIndex = player.currentIndex
guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return } guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return }
@@ -218,6 +278,7 @@ final class PlayerManager: ObservableObject {
} }
} }
refreshState() refreshState()
scheduleHandoffSave()
} }
func cycleRepeat() { func cycleRepeat() {
@@ -236,6 +297,286 @@ final class PlayerManager: ObservableObject {
} }
} }
func setAuthenticated(_ authenticated: Bool) {
guard isAuthenticated != authenticated else { return }
isAuthenticated = authenticated
logHandoff("authentication changed; signedIn=\(authenticated)")
if authenticated {
handoffRestoreAttempted = false
restorePlaybackHandoffIfNeeded()
updateHandoffPositionTimer()
scheduleHandoffSave()
} else {
handoffGeneration &+= 1
handoffRestoreTask?.cancel()
handoffRestoreTask = nil
if handoffRestoreInProgress { discardUnsuccessfulHandoffRestore() }
handoffRestoreAttempted = false
handoffSaveTask?.cancel()
handoffSaveTask = nil
handoffSavePending = false
handoffPositionTask?.cancel()
handoffPositionTask = nil
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = nil
}
}
func saveHandoffForBackground() {
handoffSeekSaveTask?.cancel()
handoffSeekSaveTask = nil
scheduleHandoffSave()
}
private var handoffRestoreTask: Task<Void, Never>?
private func invalidatePendingHandoffRestore() {
guard handoffRestoreTask != nil || handoffRestoreInProgress else { return }
handoffGeneration &+= 1
handoffRestoreTask?.cancel()
handoffRestoreTask = nil
handoffRestoreInProgress = false
}
private func restorePlaybackHandoffIfNeeded() {
guard isAuthenticated, !handoffRestoreAttempted, currentTrack == nil else { return }
handoffRestoreAttempted = true
handoffGeneration &+= 1
let generation = handoffGeneration
handoffRestoreTask = Task { [weak self] in
await self?.restorePlaybackHandoff(generation: generation)
}
}
private func restorePlaybackHandoff(generation: Int) async {
do {
guard let handoff = try await api.playbackHandoff(),
generation == handoffGeneration,
isAuthenticated,
currentTrack == nil
else { return }
let ids = Array(Set(
[handoff.currentTrackId] + handoff.queueTrackIds
+ handoff.remainingTrackIds + handoff.historyTrackIds
))
let hydratedTracks = try await api.tracks(ids: ids)
guard generation == handoffGeneration,
isAuthenticated,
currentTrack == nil
else { return }
let tracksByID = Dictionary(hydratedTracks.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
guard let restoredCurrent = tracksByID[handoff.currentTrackId] else { return }
func restoredTracks(_ ids: [String]) -> [Track] {
ids.compactMap { tracksByID[$0] }
}
// The web client stores history newest-first; SwiftAudioEx expects it in queue order.
let orderedHistory = Array(restoredTracks(handoff.historyTrackIds).reversed())
let restoredIndex = orderedHistory.count
let orderedQueue = orderedHistory + [restoredCurrent]
+ restoredTracks(handoff.remainingTrackIds)
guard !orderedQueue.isEmpty, orderedQueue.indices.contains(restoredIndex) else { return }
handoffRestoreInProgress = true
isApplyingHandoff = true
player.clear()
tracksByItemID.removeAll()
let restoredItems = orderedQueue.compactMap(makeAudioItem(for:))
guard restoredItems.count == orderedQueue.count,
restoredItems.indices.contains(restoredIndex)
else {
isApplyingHandoff = false
handoffRestoreInProgress = false
return
}
player.add(items: restoredItems, playWhenReady: false)
try player.jumpToItem(atIndex: restoredIndex, playWhenReady: false)
repeatMode = handoff.repeatEnabled ? .all : (handoff.repeatOnce ? .one : .off)
applyRepeatMode()
let ready = await waitForRestoredItem(generation: generation)
guard ready, generation == handoffGeneration, isAuthenticated else {
if generation == handoffGeneration {
discardUnsuccessfulHandoffRestore()
} else {
isApplyingHandoff = false
handoffRestoreInProgress = false
}
return
}
let requestedPosition = max(0, handoff.position)
let seekPosition = duration > 0 ? min(requestedPosition, duration) : requestedPosition
player.seek(to: seekPosition)
refreshState()
loadArtwork(for: player.currentItem)
if handoff.wasPlaying {
do {
try AudioSessionController.shared.set(category: .playback)
try AudioSessionController.shared.activateSession()
playbackIntent = true
player.play()
} catch {
errorMessage = error.localizedDescription
isApplyingHandoff = false
handoffRestoreInProgress = false
return
}
let started = await waitForRestoredPlayback(generation: generation)
guard started, generation == handoffGeneration else {
if generation == handoffGeneration {
discardUnsuccessfulHandoffRestore()
} else {
isApplyingHandoff = false
handoffRestoreInProgress = false
}
return
}
}
isApplyingHandoff = false
handoffRestoreInProgress = false
handoffRestoreTask = nil
updateHandoffPositionTimer()
_ = try? await api.deletePlaybackHandoff()
} catch is CancellationError {
if generation == handoffGeneration {
isApplyingHandoff = false
handoffRestoreInProgress = false
handoffRestoreTask = nil
}
} catch {
if generation == handoffGeneration {
isApplyingHandoff = false
handoffRestoreInProgress = false
handoffRestoreTask = nil
}
}
}
private var isApplyingHandoff = false
private func discardUnsuccessfulHandoffRestore() {
isApplyingHandoff = true
playbackIntent = nil
player.clear()
tracksByItemID.removeAll()
currentTrack = nil
upcomingTracks = []
previousTracks = []
isPlaying = false
elapsedTime = 0
duration = 0
isApplyingHandoff = false
handoffRestoreInProgress = false
handoffRestoreTask = nil
}
private func waitForRestoredItem(generation: Int) async -> Bool {
for _ in 0..<150 {
guard !Task.isCancelled, generation == handoffGeneration else { return false }
switch player.playerState {
case .ready, .paused, .playing:
return true
case .failed, .stopped, .ended:
return false
default:
try? await Task.sleep(for: .milliseconds(100))
}
}
return false
}
private func waitForRestoredPlayback(generation: Int) async -> Bool {
for _ in 0..<100 {
guard !Task.isCancelled, generation == handoffGeneration else { return false }
if player.playerState == .playing || player.playerState == .buffering { return true }
if player.playerState == .failed || player.playerState == .ended { return false }
try? await Task.sleep(for: .milliseconds(100))
}
return false
}
private func scheduleHandoffSave() {
guard isAuthenticated, !isApplyingHandoff, !handoffRestoreInProgress,
let currentTrack
else {
logHandoff(
"save skipped; signedIn=\(isAuthenticated), hasTrack=\(currentTrack != nil), "
+ "applyingRestore=\(isApplyingHandoff), restoring=\(handoffRestoreInProgress)"
)
return
}
if !handoffSavePending {
logHandoff("save queued; track=\(currentTrack.id), playing=\(isPlaying)")
}
handoffSavePending = true
guard !handoffSaveInFlight, handoffSaveTask == nil else { return }
handoffSaveTask = Task { [weak self] in
guard let self else { return }
await self.drainHandoffSaves()
self.handoffSaveTask = nil
if self.handoffSavePending { self.scheduleHandoffSave() }
}
}
private func drainHandoffSaves() async {
guard !handoffSaveInFlight else { return }
handoffSaveInFlight = true
defer { handoffSaveInFlight = false }
while !Task.isCancelled, handoffSavePending, isAuthenticated, !isApplyingHandoff,
!handoffRestoreInProgress, let currentTrack
{
handoffSavePending = false
logHandoff("PUT starting; track=\(currentTrack.id)")
let body = PlaybackHandoffBody(
currentTrackId: currentTrack.id,
position: max(0, elapsedTime),
queueTrackIds: player.items.compactMap { track(for: $0)?.id },
remainingTrackIds: upcomingTracks.map(\.id),
historyTrackIds: previousTracks.reversed().map(\.id),
repeatEnabled: repeatMode == .all,
repeatOnce: repeatMode == .one,
wasPlaying: isPlaying
)
do {
try Task.checkCancellation()
let response = try await api.savePlaybackHandoff(body)
handoffLastSavedAt = Date()
#if DEBUG
print("[PlayerManager] playback handoff PUT completed; saved=\(response.saved)")
#endif
} catch {
// Handoff synchronization must never interrupt playback.
logHandoff("PUT failed; \(error.localizedDescription)")
}
}
}
private func logHandoff(_ message: String) {
#if DEBUG
print("[PlayerManager] playback handoff: \(message)")
#endif
}
private func updateHandoffPositionTimer() {
guard isAuthenticated, isPlaying else {
handoffPositionTask?.cancel()
handoffPositionTask = nil
return
}
guard handoffPositionTask == nil else { return }
handoffPositionTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(15))
guard let self, !Task.isCancelled else { return }
guard self.isAuthenticated, self.isPlaying else { return }
if Date().timeIntervalSince(self.handoffLastSavedAt) >= Self.handoffSyncInterval {
self.scheduleHandoffSave()
}
}
}
}
private func makeAudioItem(for track: Track) -> DefaultAudioItem? { private func makeAudioItem(for track: Track) -> DefaultAudioItem? {
guard let url = apiConfiguration.audioURL(for: track) else { return nil } guard let url = apiConfiguration.audioURL(for: track) else { return nil }
let artistNames = track.artists.compactMap { reference -> String? in let artistNames = track.artists.compactMap { reference -> String? in
@@ -263,6 +604,8 @@ final class PlayerManager: ObservableObject {
player.event.stateChange.addListener(self) { [weak self] state in player.event.stateChange.addListener(self) { [weak self] state in
Task { @MainActor [weak self] in Task { @MainActor [weak self] in
guard let self else { return } guard let self else { return }
let previousTrackID = self.currentTrack?.id
let wasPlaying = self.isPlaying
switch state { switch state {
case .playing: case .playing:
if self.playbackIntent != false { if self.playbackIntent != false {
@@ -281,12 +624,19 @@ final class PlayerManager: ObservableObject {
break break
} }
self.refreshState() self.refreshState()
if previousTrackID != self.currentTrack?.id || wasPlaying != self.isPlaying {
self.scheduleHandoffSave()
}
} }
} }
player.event.currentItem.addListener(self) { [weak self] _ in player.event.currentItem.addListener(self) { [weak self] _ in
Task { @MainActor [weak self] in Task { @MainActor [weak self] in
let previousTrackID = self?.currentTrack?.id
self?.refreshState() self?.refreshState()
self?.loadArtwork(for: self?.player.currentItem) self?.loadArtwork(for: self?.player.currentItem)
if previousTrackID != self?.currentTrack?.id {
self?.scheduleHandoffSave()
}
} }
} }
player.event.secondElapse.addListener(self) { [weak self] elapsed in player.event.secondElapse.addListener(self) { [weak self] elapsed in
@@ -300,8 +650,11 @@ final class PlayerManager: ObservableObject {
} }
player.event.fail.addListener(self) { [weak self] error in player.event.fail.addListener(self) { [weak self] error in
Task { @MainActor [weak self] in Task { @MainActor [weak self] in
let wasPlaying = self?.isPlaying ?? false
self?.errorMessage = error?.localizedDescription ?? "Playback failed." self?.errorMessage = error?.localizedDescription ?? "Playback failed."
self?.isPlaying = false self?.isPlaying = false
self?.updateHandoffPositionTimer()
if wasPlaying { self?.scheduleHandoffSave() }
} }
} }
} }
@@ -313,6 +666,7 @@ final class PlayerManager: ObservableObject {
elapsedTime = player.currentTime elapsedTime = player.currentTime
duration = player.duration duration = player.duration
isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering) isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering)
updateHandoffPositionTimer()
} }
private func track(for item: AudioItem?) -> Track? { private func track(for item: AudioItem?) -> Track? {
+333 -40
View File
@@ -4,6 +4,22 @@ struct FullscreenPlayerView: View {
@EnvironmentObject private var player: PlayerManager @EnvironmentObject private var player: PlayerManager
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@State private var seekPosition: Double? @State private var seekPosition: Double?
@State private var expandedSlider: SliderKind?
@State private var displayedIsPlaying = false
@State private var playIconScale: CGFloat = 1
@State private var dragOffset: CGFloat = 0
@State private var isFinishingDragDismissal = false
@State private var hasCheckedDismissDragStart = false
@State private var isActiveDismissDrag = false
@State private var isQueuePresented = false
@State private var isShuffleEnabled = false
@State private var isAutoplayEnabled = false
@Namespace private var queueArtworkNamespace
private enum SliderKind {
case progress
case volume
}
private var track: Track? { player.currentTrack } private var track: Track? { player.currentTrack }
@@ -19,6 +35,12 @@ struct FullscreenPlayerView: View {
var body: some View { var body: some View {
GeometryReader { geometry in GeometryReader { geometry in
let size = geometry.size let size = geometry.size
let artworkLength = artworkSize(in: size)
let playerOrigin = geometry.frame(in: .global).origin
let activeDragArea = CGRect(
origin: playerOrigin,
size: CGSize(width: size.width, height: size.height * 0.3)
)
ZStack(alignment: .topLeading) { ZStack(alignment: .topLeading) {
LinearGradient( LinearGradient(
@@ -31,39 +53,54 @@ struct FullscreenPlayerView: View {
.fill(.white.opacity(0.55)) .fill(.white.opacity(0.55))
.frame(width: 58, height: 4) .frame(width: 58, height: 4)
.position(x: size.width * 0.5, y: size.height * 0.08) .position(x: size.width * 0.5, y: size.height * 0.08)
.contentShape(Rectangle().inset(by: -18))
.gesture(
DragGesture(minimumDistance: 12)
.onEnded { value in
if value.translation.height > 50 { dismiss() }
}
)
.accessibilityLabel("Swipe down to close player") .accessibilityLabel("Swipe down to close player")
artwork if isQueuePresented {
.frame(width: artworkSize(in: size), height: artworkSize(in: size)) Button {
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) withAnimation(.spring(response: 0.42, dampingFraction: 0.88)) {
.shadow(color: .black.opacity(0.16), radius: 26, y: 18) isQueuePresented = false
.position(x: size.width * 0.5, y: size.height * 0.31) }
} label: {
queueArtwork(for: track, size: 56)
.matchedGeometryEffect(
id: "fullscreen-current-artwork",
in: queueArtworkNamespace,
isSource: isQueuePresented
)
}
.buttonStyle(.plain)
.accessibilityLabel("Show player")
.position(x: size.width * 0.08 + 28, y: size.height * 0.12 + 39)
} else {
artwork
.frame(width: artworkLength, height: artworkLength)
.matchedGeometryEffect(
id: "fullscreen-current-artwork",
in: queueArtworkNamespace,
isSource: !isQueuePresented
)
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.shadow(color: .black.opacity(0.16), radius: 26, y: 18)
.position(x: size.width * 0.5, y: size.height * 0.31)
}
Image(systemName: "ellipsis") if isQueuePresented {
.font(.system(size: 18, weight: .semibold)) queueDetails(size: size)
.frame(width: size.width - 72, alignment: .trailing) .transition(
.foregroundStyle(.white) .asymmetric(
.position(x: size.width * 0.5, y: size.height * 0.60) insertion: .offset(y: -24).combined(with: .opacity),
removal: .offset(y: 34).combined(with: .opacity)
VStack(alignment: .leading, spacing: 6) { )
Text(track?.name ?? "") )
.font(.system(size: 20, weight: .bold)) } else {
.lineLimit(1) playerDetails(size: size)
Text(artistNames) .transition(
.font(.system(size: 16)) .asymmetric(
.foregroundStyle(.white.opacity(0.68)) insertion: .offset(y: -18).combined(with: .opacity),
.lineLimit(1) removal: .offset(y: 18).combined(with: .opacity)
)
)
} }
.foregroundStyle(.white)
.frame(width: size.width * 0.68, alignment: .leading)
.position(x: size.width * 0.41, y: size.height * 0.60)
seekControls seekControls
.frame(width: size.width * 0.86) .frame(width: size.width * 0.86)
@@ -89,18 +126,45 @@ struct FullscreenPlayerView: View {
Spacer() Spacer()
Image(systemName: "airplay.audio") Image(systemName: "airplay.audio")
Spacer() Spacer()
Image(systemName: "list.bullet") Button {
withAnimation(.spring(response: 0.42, dampingFraction: 0.88)) {
isQueuePresented.toggle()
}
} label: {
Image(systemName: "list.bullet")
.frame(width: 36, height: 36)
.background {
if isQueuePresented {
Circle().fill(.white.opacity(0.85))
}
}
.foregroundStyle(isQueuePresented ? Color(white: 0.38) : .white.opacity(0.85))
}
.buttonStyle(.plain)
.accessibilityLabel(isQueuePresented ? "Hide queue" : "Show queue")
} }
.font(.system(size: 18, weight: .medium)) .font(.system(size: 16, weight: .medium))
.foregroundStyle(.white.opacity(0.85)) .foregroundStyle(.white.opacity(0.85))
.frame(width: size.width * 0.58) .frame(width: size.width * 0.58)
.position(x: size.width * 0.5, y: size.height * 0.94) .position(x: size.width * 0.5, y: size.height * 0.94)
} }
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
.clipped() .clipped()
.simultaneousGesture(
dragToDismissGesture(screenHeight: size.height, activeArea: activeDragArea)
)
.offset(y: dragOffset)
} }
.ignoresSafeArea() .ignoresSafeArea()
.preferredColorScheme(.dark) .preferredColorScheme(.dark)
.onAppear { displayedIsPlaying = player.isPlaying }
.onChange(of: player.isPlaying) { _, newValue in
withAnimation(.easeOut(duration: 0.12)) { playIconScale = 0 }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) {
displayedIsPlaying = newValue
withAnimation(.easeOut(duration: 0.12)) { playIconScale = 1 }
}
}
} }
@ViewBuilder @ViewBuilder
@@ -126,10 +190,181 @@ struct FullscreenPlayerView: View {
.background(.ultraThinMaterial) .background(.ultraThinMaterial)
} }
@ViewBuilder
private func playerDetails(size: CGSize) -> some View {
Image(systemName: "ellipsis")
.font(.system(size: 16, weight: .semibold))
.frame(width: size.width - 72, alignment: .trailing)
.foregroundStyle(.white)
.position(x: size.width * 0.5, y: size.height * 0.60)
VStack(alignment: .leading, spacing: 6) {
Text(track?.name ?? "")
.font(.system(size: 20, weight: .bold))
.lineLimit(1)
Text(artistNames)
.font(.system(size: 16))
.foregroundStyle(.white.opacity(0.68))
.lineLimit(1)
}
.foregroundStyle(.white)
.frame(width: size.width * 0.68, alignment: .leading)
.position(x: size.width * 0.41, y: size.height * 0.60)
}
private func queueDetails(size: CGSize) -> some View {
VStack(alignment: .leading, spacing: 18) {
HStack(spacing: 14) {
Color.clear
.frame(width: 56, height: 56)
VStack(alignment: .leading, spacing: 3) {
Text(track?.name ?? "")
.font(.system(size: 18, weight: .semibold))
.lineLimit(1)
Text(artistNames)
.font(.system(size: 14))
.foregroundStyle(.white.opacity(0.68))
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
Image(systemName: "ellipsis")
.font(.system(size: 16, weight: .semibold))
.frame(width: 32)
}
.foregroundStyle(.white)
.frame(height: 78)
HStack(spacing: 12) {
queueModeButton(symbol: "shuffle", isSelected: isShuffleEnabled) {
isShuffleEnabled.toggle()
if isShuffleEnabled { player.shuffleUpcoming() }
}
queueModeButton(
symbol: player.repeatMode == .one ? "repeat.1" : "repeat",
isSelected: player.repeatMode != .off
) {
player.cycleRepeat()
}
queueModeButton(symbol: "infinity", isSelected: isAutoplayEnabled) {
isAutoplayEnabled.toggle()
}
queueModeButton(symbol: "shuffle", isSelected: false, action: {})
.opacity(0.35)
.disabled(true)
}
Text("Continue Playing")
.font(.system(size: 20, weight: .semibold))
.foregroundStyle(.white)
.padding(.top, 4)
ScrollView {
LazyVStack(spacing: 10) {
ForEach(Array(player.upcomingTracks.enumerated()), id: \.offset) { index, queuedTrack in
Button {
player.playQueuedTrack(at: player.previousTracks.count + index + 1)
} label: {
HStack(spacing: 14) {
queueArtwork(for: queuedTrack, size: 46)
VStack(alignment: .leading, spacing: 2) {
Text(queuedTrack.name)
.font(.system(size: 18, weight: .medium))
.foregroundStyle(.white)
.lineLimit(1)
Text(artistNames(for: queuedTrack))
.font(.system(size: 15))
.foregroundStyle(.white.opacity(0.68))
.lineLimit(1)
}
Spacer(minLength: 8)
Image(systemName: "line.3.horizontal")
.font(.system(size: 16, weight: .medium))
.foregroundStyle(.white.opacity(0.35))
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
if player.upcomingTracks.isEmpty {
Text("No more songs in the queue")
.font(.system(size: 15))
.foregroundStyle(.white.opacity(0.65))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 18)
}
}
}
.scrollIndicators(.hidden)
}
.padding(.horizontal, size.width * 0.08)
.padding(.top, size.height * 0.12)
.frame(maxWidth: .infinity, alignment: .topLeading)
.frame(height: size.height * 0.66, alignment: .top)
.foregroundStyle(.white)
.animation(.spring(response: 0.42, dampingFraction: 0.88), value: isQueuePresented)
}
private func queueModeButton(
symbol: String,
isSelected: Bool,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
Image(systemName: symbol)
.font(.system(size: 18, weight: .semibold))
.foregroundStyle(isSelected ? Color(white: 0.4) : .white)
.frame(maxWidth: .infinity)
.frame(height: 44)
.background(isSelected ? Color.white.opacity(0.88) : Color.white.opacity(0.14))
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
@ViewBuilder
private func queueArtwork(for track: Track?, size: CGFloat) -> some View {
if let url = track.flatMap({ player.artworkURL(for: $0) }) {
AsyncImage(url: url) { phase in
if let image = phase.image {
image.resizable().scaledToFill()
} else {
queueArtworkPlaceholder
}
}
.frame(width: size, height: size)
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
} else {
queueArtworkPlaceholder
.frame(width: size, height: size)
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
}
}
private var queueArtworkPlaceholder: some View {
Image(systemName: "music.note")
.font(.system(size: 22, weight: .light))
.foregroundStyle(.white.opacity(0.75))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.white.opacity(0.12))
}
private func artistNames(for track: Track) -> String {
let names = track.artists.compactMap { reference -> String? in
guard case .value(let artist) = reference else { return nil }
return artist.name
}
return names.isEmpty ? "Unknown Artist" : names.joined(separator: ", ")
}
private var seekControls: some View { private var seekControls: some View {
VStack(spacing: 10) { VStack(spacing: 10) {
GeometryReader { geometry in GeometryReader { geometry in
let progress = min(max((seekPosition ?? player.elapsedTime) / max(player.duration, 1), 0), 1) let progress = min(max((seekPosition ?? player.elapsedTime) / max(player.duration, 1), 0), 1)
let isExpanded = expandedSlider == .progress
Capsule() Capsule()
.fill(.white.opacity(0.3)) .fill(.white.opacity(0.3))
.overlay(alignment: .leading) { .overlay(alignment: .leading) {
@@ -137,12 +372,16 @@ struct FullscreenPlayerView: View {
.fill(.white.opacity(0.9)) .fill(.white.opacity(0.9))
.frame(width: geometry.size.width * progress) .frame(width: geometry.size.width * progress)
} }
.frame(height: 7) .frame(height: 12)
.frame(maxHeight: .infinity) .scaleEffect(y: isExpanded ? 1 : 7.0 / 12.0, anchor: .center)
.animation(.easeOut(duration: 0.16), value: isExpanded)
.offset(y: -2)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.contentShape(Rectangle().inset(by: -10)) .contentShape(Rectangle().inset(by: -10))
.gesture( .gesture(
DragGesture(minimumDistance: 0) DragGesture(minimumDistance: 0)
.onChanged { value in .onChanged { value in
expandedSlider = .progress
let fraction = min(max(value.location.x / geometry.size.width, 0), 1) let fraction = min(max(value.location.x / geometry.size.width, 0), 1)
seekPosition = player.duration * fraction seekPosition = player.duration * fraction
} }
@@ -150,6 +389,7 @@ struct FullscreenPlayerView: View {
let fraction = min(max(value.location.x / geometry.size.width, 0), 1) let fraction = min(max(value.location.x / geometry.size.width, 0), 1)
player.seek(to: player.duration * fraction) player.seek(to: player.duration * fraction)
seekPosition = nil seekPosition = nil
expandedSlider = nil
} }
) )
} }
@@ -167,6 +407,7 @@ struct FullscreenPlayerView: View {
private var volumeBar: some View { private var volumeBar: some View {
GeometryReader { geometry in GeometryReader { geometry in
let isExpanded = expandedSlider == .volume
Capsule() Capsule()
.fill(.white.opacity(0.3)) .fill(.white.opacity(0.3))
.overlay(alignment: .leading) { .overlay(alignment: .leading) {
@@ -174,14 +415,19 @@ struct FullscreenPlayerView: View {
.fill(.white.opacity(0.9)) .fill(.white.opacity(0.9))
.frame(width: geometry.size.width * player.volume) .frame(width: geometry.size.width * player.volume)
} }
.frame(height: 7) .frame(height: 12)
.frame(maxHeight: .infinity) .scaleEffect(y: isExpanded ? 1 : 7.0 / 12.0, anchor: .center)
.animation(.easeOut(duration: 0.16), value: isExpanded)
.offset(y: -2)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.contentShape(Rectangle().inset(by: -10)) .contentShape(Rectangle().inset(by: -10))
.gesture( .gesture(
DragGesture(minimumDistance: 0) DragGesture(minimumDistance: 0)
.onChanged { value in .onChanged { value in
expandedSlider = .volume
player.volume = min(max(value.location.x / geometry.size.width, 0), 1) player.volume = min(max(value.location.x / geometry.size.width, 0), 1)
} }
.onEnded { _ in expandedSlider = nil }
) )
} }
.frame(height: 8) .frame(height: 8)
@@ -200,7 +446,7 @@ struct FullscreenPlayerView: View {
HStack { HStack {
Button(action: player.previous) { Button(action: player.previous) {
Image(systemName: "backward.end.fill") Image(systemName: "backward.end.fill")
.font(.system(size: 30, weight: .semibold)) .font(.system(size: 26, weight: .semibold))
.frame(width: 64, height: 64) .frame(width: 64, height: 64)
} }
.accessibilityLabel("Previous track") .accessibilityLabel("Previous track")
@@ -210,9 +456,10 @@ struct FullscreenPlayerView: View {
Button { Button {
if player.isPlaying { player.pause() } else { player.play() } if player.isPlaying { player.pause() } else { player.play() }
} label: { } label: {
Image(systemName: player.isPlaying ? "pause.fill" : "play.fill") Image(systemName: displayedIsPlaying ? "pause.fill" : "play.fill")
.font(.system(size: 36, weight: .semibold)) .font(.system(size: 32, weight: .semibold))
.frame(width: 76, height: 76) .frame(width: 76, height: 76)
.scaleEffect(playIconScale)
} }
.accessibilityLabel(player.isPlaying ? "Pause" : "Play") .accessibilityLabel(player.isPlaying ? "Pause" : "Play")
@@ -220,7 +467,7 @@ struct FullscreenPlayerView: View {
Button(action: player.next) { Button(action: player.next) {
Image(systemName: "forward.end.fill") Image(systemName: "forward.end.fill")
.font(.system(size: 30, weight: .semibold)) .font(.system(size: 26, weight: .semibold))
.frame(width: 64, height: 64) .frame(width: 64, height: 64)
} }
.accessibilityLabel("Next track") .accessibilityLabel("Next track")
@@ -236,8 +483,54 @@ struct FullscreenPlayerView: View {
return String(format: "%d:%02d", totalSeconds / 60, totalSeconds % 60) return String(format: "%d:%02d", totalSeconds / 60, totalSeconds % 60)
} }
private func finishDragDismissal(screenHeight: CGFloat) {
guard !isFinishingDragDismissal else { return }
isFinishingDragDismissal = true
withAnimation(.easeIn(duration: 0.22)) {
dragOffset = screenHeight
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.22) {
dismiss()
}
}
private func dragToDismissGesture(screenHeight: CGFloat, activeArea: CGRect) -> some Gesture {
DragGesture(minimumDistance: 12, coordinateSpace: .global)
.onChanged { value in
guard !isFinishingDragDismissal else { return }
if !hasCheckedDismissDragStart {
hasCheckedDismissDragStart = true
isActiveDismissDrag = activeArea.contains(value.startLocation)
}
guard isActiveDismissDrag else { return }
dragOffset = max(0, value.translation.height)
if dragOffset >= screenHeight * 0.85 {
finishDragDismissal(screenHeight: screenHeight)
}
}
.onEnded { value in
defer {
hasCheckedDismissDragStart = false
isActiveDismissDrag = false
}
guard !isFinishingDragDismissal else { return }
guard isActiveDismissDrag else { return }
let projectedDistance = max(
value.translation.height,
value.predictedEndTranslation.height
)
if projectedDistance >= screenHeight * 0.25 {
finishDragDismissal(screenHeight: screenHeight)
} else {
withAnimation(.spring(response: 0.38, dampingFraction: 0.86)) {
dragOffset = 0
}
}
}
}
private func artworkSize(in size: CGSize) -> CGFloat { private func artworkSize(in size: CGSize) -> CGFloat {
min(280, size.width - 40) size.width * 0.86
} }
} }
+20 -2
View File
@@ -10,6 +10,8 @@ struct MiniPlayerView: View {
let onNext: () -> Void let onNext: () -> Void
let onOpen: () -> Void let onOpen: () -> Void
@State private var displayedIsPlaying: Bool @State private var displayedIsPlaying: Bool
@State private var playIconScale: CGFloat = 1
@State private var pendingIsPlaying: Bool?
init( init(
track: Track?, track: Track?,
@@ -71,12 +73,13 @@ struct MiniPlayerView: View {
.onTapGesture(perform: onOpen) .onTapGesture(perform: onOpen)
Button { Button {
displayedIsPlaying.toggle() animatePlayIcon(to: !(pendingIsPlaying ?? displayedIsPlaying))
onTogglePlayback() onTogglePlayback()
} label: { } label: {
Image(systemName: displayedIsPlaying ? "pause.fill" : "play.fill") Image(systemName: displayedIsPlaying ? "pause.fill" : "play.fill")
.font(.system(size: usesCompactLayout ? 18 : 21, weight: .medium)) .font(.system(size: usesCompactLayout ? 18 : 21, weight: .medium))
.frame(width: usesCompactLayout ? 34 : 42, height: 32) .frame(width: usesCompactLayout ? 34 : 42, height: 32)
.scaleEffect(playIconScale)
.contentShape(Rectangle()) .contentShape(Rectangle())
} }
.buttonStyle(.plain) .buttonStyle(.plain)
@@ -99,11 +102,26 @@ struct MiniPlayerView: View {
.frame(height: 52) .frame(height: 52)
.foregroundStyle(.primary) .foregroundStyle(.primary)
.onChange(of: isPlaying) { _, newValue in .onChange(of: isPlaying) { _, newValue in
displayedIsPlaying = newValue animatePlayIcon(to: newValue)
} }
.accessibilityElement(children: .contain) .accessibilityElement(children: .contain)
} }
private func animatePlayIcon(to newValue: Bool) {
guard (pendingIsPlaying ?? displayedIsPlaying) != newValue else { return }
pendingIsPlaying = newValue
withAnimation(.easeOut(duration: 0.12)) {
playIconScale = 0
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) {
displayedIsPlaying = newValue
pendingIsPlaying = nil
withAnimation(.easeOut(duration: 0.12)) {
playIconScale = 1
}
}
}
@ViewBuilder @ViewBuilder
private var artwork: some View { private var artwork: some View {
if let artworkURL { if let artworkURL {
@@ -29,6 +29,7 @@ struct PlayerBottomAccessoryView: View {
.fullScreenCover(isPresented: $isFullscreenPresented) { .fullScreenCover(isPresented: $isFullscreenPresented) {
FullscreenPlayerView() FullscreenPlayerView()
.environmentObject(player) .environmentObject(player)
.presentationBackground(.clear)
} }
} }