Yandex Music client for Apple TV

tvOS 17+ SwiftUI client for the unofficial Yandex Music API: rotor stations
with feedback, library, search, artist and album pages, synced lyrics, and
system Now Playing integration.
This commit is contained in:
2026-09-17 20:38:19 +03:00
commit acd50280bc
70 changed files with 4588 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
import SwiftUI
struct AlbumView: View {
let album: Album
@EnvironmentObject private var player: PlayerController
@State private var full: Album?
@State private var tracks: [Track] = []
@State private var isLoading = true
private var resolved: Album { full ?? album }
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 40) {
header
if isLoading {
LoadingState(text: "Загружаем альбом…").frame(height: 300)
} else {
LazyVStack(spacing: 6) {
ForEach(Array(tracks.enumerated()), id: \.offset) { pair in
HStack(spacing: 0) {
Text("\(pair.offset + 1)")
.font(.headline.monospacedDigit())
.foregroundStyle(.white.opacity(0.35))
.frame(width: 60, alignment: .trailing)
TrackRow(
track: pair.element,
isCurrent: player.current?.trackID == pair.element.trackID
) {
play(from: pair.offset)
}
}
}
}
}
}
.padding(.top, 120)
.padding(.bottom, 60)
}
.background(backdrop)
.task { await load() }
}
private var backdrop: some View {
BlurredBackdrop(url: resolved.coverURL(size: 200))
}
private var header: some View {
HStack(alignment: .top, spacing: 50) {
CoverImage(url: resolved.coverURL(size: 400), corner: 16)
.frame(width: 340, height: 340)
VStack(alignment: .leading, spacing: 14) {
Text(resolved.displayTitle)
.font(.system(size: 52, weight: .bold))
.lineLimit(3)
if let artist = resolved.artists?.first {
NavigationLink(value: MusicRoute.artist(artist)) {
Text(resolved.artistNames)
.font(.title3)
.foregroundStyle(Color.ymAccent)
}
.buttonStyle(RowButtonStyle())
.fixedSize()
} else {
Text(resolved.artistNames)
.font(.title3)
.foregroundStyle(.white.opacity(0.6))
}
if !resolved.subtitleLine.isEmpty {
Text(resolved.subtitleLine)
.font(.body)
.foregroundStyle(.white.opacity(0.55))
}
HStack(spacing: 20) {
Button { play(from: 0) } label: {
Label("Слушать", systemImage: "play.fill")
}
.disabled(tracks.isEmpty)
Button {
player.play(
tracks: tracks.shuffled(),
startAt: 0,
source: .collection(resolved.displayTitle)
)
} label: {
Label("Вперемешку", systemImage: "shuffle")
}
.disabled(tracks.isEmpty)
}
.padding(.top, 10)
if let description = resolved.shortDescription, !description.isEmpty {
Text(description)
.font(.callout)
.foregroundStyle(.white.opacity(0.6))
.frame(maxWidth: 900, alignment: .leading)
.padding(.top, 8)
}
}
Spacer(minLength: 0)
}
}
private func play(from index: Int) {
guard !tracks.isEmpty else { return }
player.play(tracks: tracks, startAt: index, source: .collection(resolved.displayTitle))
}
private func load() async {
isLoading = true
defer { isLoading = false }
do {
let loaded = try await YMClient.shared.album(albumID: album.id.value)
full = loaded
tracks = (loaded.volumes ?? []).flatMap { $0 }
} catch {
log.error("\(error.localizedDescription)")
}
}
}
+190
View File
@@ -0,0 +1,190 @@
import SwiftUI
struct ArtistView: View {
let artist: Artist
@EnvironmentObject private var player: PlayerController
@State private var info: ArtistBriefInfo?
@State private var isLoading = true
@State private var showAllTracks = false
private var resolved: Artist { info?.artist ?? artist }
private var popular: [Track] { info?.popularTracks ?? [] }
private var albums: [Album] { info?.albums ?? [] }
private var alsoAlbums: [Album] { info?.alsoAlbums ?? [] }
private var similar: [Artist] { info?.similarArtists ?? [] }
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 50) {
header
if isLoading {
LoadingState(text: "Загружаем исполнителя…").frame(height: 300)
} else {
if !popular.isEmpty { popularSection }
if !albums.isEmpty { albumShelf("Альбомы", albums) }
if !alsoAlbums.isEmpty { albumShelf("Сборники и участие", alsoAlbums) }
if !similar.isEmpty { similarSection }
if let text = resolved.description?.text, !text.isEmpty { about(text) }
}
}
.padding(.top, 120)
.padding(.bottom, 60)
}
.background(backdrop)
.task { await load() }
}
// MARK: - Header
private var backdrop: some View {
BlurredBackdrop(url: resolved.coverURL(size: 200))
}
private var header: some View {
HStack(alignment: .center, spacing: 50) {
CoverImage(url: resolved.coverURL(size: 400), corner: 160)
.frame(width: 320, height: 320)
VStack(alignment: .leading, spacing: 14) {
Text(resolved.name)
.font(.system(size: 60, weight: .bold))
.lineLimit(2)
if let genres = resolved.genres, !genres.isEmpty {
Text(genres.prefix(3).joined(separator: " · ").capitalized)
.font(.title3)
.foregroundStyle(Color.ymAccent)
}
if let counts = resolved.countsLine {
Text(counts)
.font(.body)
.foregroundStyle(.white.opacity(0.6))
}
HStack(spacing: 20) {
Button {
play(popular, title: resolved.name)
} label: {
Label("Слушать", systemImage: "play.fill")
}
.disabled(popular.isEmpty)
Button {
player.startRotor(
station: "artist:\(resolved.id.value)",
name: "Волна: \(resolved.name)"
)
} label: {
Label("Волна артиста", systemImage: "dot.radiowaves.left.and.right")
}
Button {
playAllTracks()
} label: {
Label("Все треки", systemImage: "music.note.list")
}
}
.padding(.top, 10)
}
Spacer(minLength: 0)
}
}
// MARK: - Sections
private var popularSection: some View {
VStack(alignment: .leading, spacing: 20) {
HStack(alignment: .firstTextBaseline) {
Text("Популярные треки").font(.title2.weight(.semibold))
Spacer()
if popular.count > 8 {
Button(showAllTracks ? "Свернуть" : "Показать все") {
showAllTracks.toggle()
}
.buttonStyle(.plain)
.font(.callout)
}
}
let shown = showAllTracks ? popular : Array(popular.prefix(8))
LazyVStack(spacing: 6) {
ForEach(Array(shown.enumerated()), id: \.offset) { pair in
TrackRow(
track: pair.element,
isCurrent: player.current?.trackID == pair.element.trackID
) {
play(popular, startAt: pair.offset, title: resolved.name)
}
}
}
}
}
private func albumShelf(_ title: String, _ list: [Album]) -> some View {
Shelf(title: title) {
ForEach(list, id: \.id) { album in
PosterLink(
title: album.displayTitle,
subtitle: album.subtitleLine,
imageURL: album.coverURL(size: 200),
route: .album(album)
)
}
}
}
private var similarSection: some View {
Shelf(title: "Похожие исполнители") {
ForEach(similar, id: \.id) { other in
PosterLink(
title: other.name,
subtitle: nil,
imageURL: other.coverURL(size: 200),
route: .artist(other),
circular: true
)
}
}
}
private func about(_ text: String) -> some View {
VStack(alignment: .leading, spacing: 16) {
Text("Об исполнителе").font(.title2.weight(.semibold))
Text(text)
.font(.body)
.foregroundStyle(.white.opacity(0.7))
.frame(maxWidth: 1200, alignment: .leading)
}
}
// MARK: - Actions
private func play(_ list: [Track], startAt: Int = 0, title: String) {
guard !list.isEmpty else { return }
player.play(tracks: list, startAt: startAt, source: .collection(title))
}
private func playAllTracks() {
Task {
do {
let all = try await YMClient.shared.artistTracks(artistID: resolved.id.value)
play(all, title: resolved.name)
} catch {
log.error("\(error.localizedDescription)")
}
}
}
private func load() async {
isLoading = true
defer { isLoading = false }
do {
info = try await YMClient.shared.artistBriefInfo(artistID: artist.id.value)
} catch {
log.error("\(error.localizedDescription)")
}
}
}
+189
View File
@@ -0,0 +1,189 @@
import SwiftUI
/// Yandex Music yellow, used sparingly as the single accent.
extension Color {
static let ymAccent = Color(red: 1.0, green: 0.87, blue: 0.16)
static let ymCard = Color.white.opacity(0.08)
}
struct CoverImage: View {
let url: URL?
var corner: CGFloat = 12
@ViewBuilder
var body: some View {
let image = AsyncImage(url: url) { phase in
switch phase {
case let .success(image):
image.resizable().aspectRatio(contentMode: .fill)
default:
Color.ymCard
}
}
if corner > 0 {
image.clipShape(RoundedRectangle(cornerRadius: corner))
} else {
image.clipped()
}
}
}
/// A poster-style button used for playlists and stations.
struct CardButton: View {
let title: String
let subtitle: String?
let imageURL: URL?
var width: CGFloat = 280
let action: () -> Void
var body: some View {
Button(action: action) {
CoverImage(url: imageURL, corner: 12)
.frame(width: width, height: width)
}
.buttonStyle(CardButtonStyle())
.overlay(alignment: .bottomLeading) {
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.caption)
.lineLimit(1)
if let subtitle {
Text(subtitle)
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
.frame(width: width, alignment: .leading)
.offset(y: width * 0.22)
}
.padding(.bottom, subtitle == nil ? 46 : 66)
}
}
struct TrackRow: View {
let track: Track
let isCurrent: Bool
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 20) {
CoverImage(url: track.coverURL(size: 100))
.frame(width: 70, height: 70)
VStack(alignment: .leading, spacing: 4) {
Text(track.displayTitle)
.font(.headline)
.lineLimit(1)
Text(track.artistNames)
.font(.subheadline)
.foregroundStyle(.secondary)
.lineLimit(1)
}
Spacer(minLength: 12)
if isCurrent {
Image(systemName: "waveform")
.foregroundStyle(Color.ymAccent)
}
if track.available == false {
Image(systemName: "nosign").foregroundStyle(.secondary)
} else {
Text(formatTime(track.duration))
.font(.subheadline.monospacedDigit())
.foregroundStyle(.secondary)
}
}
.padding(.vertical, 6)
}
.buttonStyle(RowButtonStyle())
}
}
/// A list row that actually shows where the focus is — `.plain` on tvOS does not.
struct RowButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
StyleBody(configuration: configuration)
}
private struct StyleBody: View {
@Environment(\.isFocused) private var isFocused
let configuration: ButtonStyleConfiguration
var body: some View {
configuration.label
.padding(.horizontal, 24)
.padding(.vertical, 8)
.background {
RoundedRectangle(cornerRadius: 16, style: .continuous)
.fill(.white.opacity(isFocused ? 0.16 : 0))
}
// No scaling here: a row that grows on focus spills over its
// neighbours in a tightly packed list.
.opacity(configuration.isPressed ? 0.7 : 1)
.animation(.easeOut(duration: 0.15), value: isFocused)
}
}
}
/// Round artwork (artists) that focuses without a square card behind it.
struct CircleCardStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
StyleBody(configuration: configuration)
}
private struct StyleBody: View {
@Environment(\.isFocused) private var isFocused
let configuration: ButtonStyleConfiguration
var body: some View {
configuration.label
.overlay {
if isFocused {
Circle().strokeBorder(.white.opacity(0.95), lineWidth: 5)
}
}
.scaleEffect(configuration.isPressed ? 0.96 : (isFocused ? 1.05 : 1))
.animation(.spring(response: 0.3, dampingFraction: 0.7), value: isFocused)
}
}
}
struct ErrorBanner: View {
let message: String
var body: some View {
HStack(alignment: .top, spacing: 12) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
Text(message)
.font(.footnote)
.foregroundStyle(.white.opacity(0.9))
.multilineTextAlignment(.leading)
Spacer(minLength: 0)
}
.padding(16)
.background(Color.white.opacity(0.1), in: RoundedRectangle(cornerRadius: 12, style: .continuous))
}
}
struct LoadingState: View {
let text: String
var body: some View {
VStack(spacing: 16) {
ProgressView()
Text(text).foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
func formatTime(_ seconds: Double) -> String {
guard seconds.isFinite, seconds >= 0 else { return "--:--" }
let total = Int(seconds.rounded())
return String(format: "%d:%02d", total / 60, total % 60)
}
+144
View File
@@ -0,0 +1,144 @@
import SwiftUI
import UIKit
/// Four colours sampled from the corners of a cover, already darkened.
struct CoverPalette: Equatable {
let topLeading: Color
let topTrailing: Color
let bottomLeading: Color
let bottomTrailing: Color
static let dark = CoverPalette(
topLeading: Color(white: 0.09),
topTrailing: Color(white: 0.06),
bottomLeading: Color(white: 0.05),
bottomTrailing: Color(white: 0.03)
)
}
/// Downloads artwork for the backdrop and the Now Playing card.
///
/// Artwork in the interface goes through `AsyncImage`; this exists for the two
/// places that need the bitmap itself.
@MainActor
final class ImageCache {
static let shared = ImageCache()
private var palettes: [URL: CoverPalette] = [:]
private init() {}
func image(for url: URL) async -> UIImage? {
guard let (data, response) = try? await URLSession.shared.data(from: url) else { return nil }
if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) {
return nil
}
return UIImage(data: data)
}
func palette(for url: URL) async -> CoverPalette {
if let hit = palettes[url] { return hit }
guard let image = await image(for: url) else { return .dark }
let palette = await Task.detached(priority: .utility) {
Self.palette(from: image)
}.value
palettes[url] = palette
if palettes.count > 40 { palettes.removeAll() }
return palette
}
/// Squash the cover down to 2x2 and read the four pixels. A gradient built
/// from those reads as an out-of-focus version of the artwork without
/// drawing, blurring or stretching a single bitmap.
nonisolated private static func palette(from image: UIImage) -> CoverPalette {
let size = CGSize(width: 2, height: 2)
var pixels = [UInt8](repeating: 0, count: 16)
guard let space = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: &pixels,
width: 2,
height: 2,
bitsPerComponent: 8,
bytesPerRow: 8,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
),
let cg = image.cgImage
else { return .dark }
context.interpolationQuality = .medium
context.draw(cg, in: CGRect(origin: .zero, size: size))
func colour(_ index: Int) -> Color {
let base = index * 4
return darkened(
red: Double(pixels[base]) / 255,
green: Double(pixels[base + 1]) / 255,
blue: Double(pixels[base + 2]) / 255
)
}
// CGContext origin is bottom-left, so rows come back flipped.
return CoverPalette(
topLeading: colour(2),
topTrailing: colour(3),
bottomLeading: colour(0),
bottomTrailing: colour(1)
)
}
/// Pulls every colour down to a dark ceiling, so a mostly white sleeve does
/// not turn the whole screen into a lightbox.
nonisolated private static func darkened(red: Double, green: Double, blue: Double) -> Color {
let luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue
let ceiling = 0.20
let scale = luminance > 0.001 ? min(1, ceiling / luminance) : 1
return Color(
.sRGB,
red: red * scale,
green: green * scale,
blue: blue * scale,
opacity: 1
)
}
}
/// The ambient wash behind the player, artist and album screens.
///
/// A gradient rather than a blurred bitmap: no decode, no stretching, and a
/// single fill for the compositor.
struct BlurredBackdrop: View {
let url: URL?
@State private var palette: CoverPalette = .dark
var body: some View {
ZStack {
Color.black
LinearGradient(
stops: [
.init(color: palette.topLeading, location: 0),
.init(color: palette.topTrailing, location: 0.38),
.init(color: palette.bottomLeading, location: 0.72),
.init(color: palette.bottomTrailing, location: 1),
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
}
.ignoresSafeArea()
.animation(.easeInOut(duration: 0.6), value: palette)
.task(id: url) {
guard let url else {
palette = .dark
return
}
let loaded = await ImageCache.shared.palette(for: url)
guard !Task.isCancelled else { return }
palette = loaded
}
}
}
+104
View File
@@ -0,0 +1,104 @@
import SwiftUI
struct LikesView: View {
@EnvironmentObject private var player: PlayerController
@State private var tracks: [Track] = []
@State private var isLoading = true
var body: some View {
NavigationStack {
content
.musicDestinations()
}
.task { await load() }
}
/// A real `List` rather than a `ScrollView` + `LazyVStack`: on tvOS the list
/// recycles its rows and owns the focus animation, where a lazy stack of a
/// hundred and fifty custom buttons does neither.
private var content: some View {
VStack(alignment: .leading, spacing: 0) {
// Everything on this screen shares the tighter margin.
// Outside the List on purpose: inside a section header SwiftUI
// paints everything as secondary, which greys out the buttons.
header
.padding(.top, 30)
.padding(.bottom, 24)
List {
ForEach(Array(tracks.enumerated()), id: \.offset) { pair in
TrackRow(
track: pair.element,
isCurrent: player.current?.trackID == pair.element.trackID
) {
player.play(
tracks: tracks,
startAt: pair.offset,
source: .collection("Мне нравится")
)
}
}
}
.listStyle(.plain)
.overlay {
if isLoading {
LoadingState(text: "Загружаем вашу коллекцию…")
}
}
}
}
private var header: some View {
VStack(alignment: .leading, spacing: 20) {
HStack(alignment: .firstTextBaseline) {
Text("Мне нравится")
.font(.system(size: 56, weight: .bold))
Spacer()
if !tracks.isEmpty {
Text("\(tracks.count) треков").foregroundStyle(.secondary)
}
}
if !tracks.isEmpty {
HStack(spacing: 20) {
Button {
player.play(tracks: tracks, startAt: 0, source: .collection("Мне нравится"))
} label: {
Label("Слушать", systemImage: "play.fill")
}
Button {
player.play(
tracks: tracks.shuffled(),
startAt: 0,
source: .collection("Мне нравится")
)
} label: {
Label("Вперемешку", systemImage: "shuffle")
}
}
}
}
}
/// The whole library, a hundred at a time, so a big collection starts
/// showing immediately instead of after every batch has arrived.
private func load() async {
guard tracks.isEmpty else { return }
isLoading = true
defer { isLoading = false }
do {
let keys = try await YMClient.shared.likedTrackKeys()
for chunk in stride(from: 0, to: keys.count, by: 100).map({
Array(keys[$0 ..< min($0 + 100, keys.count)])
}) {
let batch = try await YMClient.shared.tracks(keys: chunk)
guard !Task.isCancelled else { return }
tracks.append(contentsOf: batch)
isLoading = false
}
} catch {
log.error("\(error.localizedDescription)")
}
}
}
+147
View File
@@ -0,0 +1,147 @@
import CoreImage.CIFilterBuiltins
import SwiftUI
import UIKit
struct LoginView: View {
@EnvironmentObject private var state: AppState
@State private var code: DeviceCode?
@State private var error: String?
@State private var status = "Запрашиваем код…"
@State private var manualToken = ""
@State private var pollTask: Task<Void, Never>?
@State private var showManual = false
var body: some View {
ZStack {
LinearGradient(
colors: [Color(red: 0.08, green: 0.07, blue: 0.11), .black],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.ignoresSafeArea()
HStack(spacing: 80) {
VStack(alignment: .leading, spacing: 20) {
Text("YaMusek")
.font(.system(size: 76, weight: .heavy, design: .rounded))
.foregroundStyle(Color.ymAccent)
Text("Неофициальный клиент Яндекс.Музыки для Apple TV")
.font(.title3)
.foregroundStyle(.secondary)
.frame(maxWidth: 520, alignment: .leading)
if let error {
ErrorBanner(message: error).frame(maxWidth: 520)
}
Spacer(minLength: 0)
VStack(alignment: .leading, spacing: 16) {
Button("Запросить код заново") { startDeviceFlow() }
Button(showManual ? "Скрыть ручной ввод" : "Ввести токен вручную") {
showManual.toggle()
}
if showManual {
TextField("OAuth-токен", text: $manualToken)
.frame(maxWidth: 520)
Button("Войти с этим токеном") {
Task { await state.signIn(with: manualToken) }
}
.disabled(manualToken.trimmingCharacters(in: .whitespaces).isEmpty)
}
}
}
.frame(maxWidth: 620, alignment: .leading)
VStack(spacing: 24) {
if let code {
Text("Откройте на телефоне")
.font(.title3)
.foregroundStyle(.secondary)
Text(code.verificationUrl)
.font(.title2.weight(.semibold))
if let qr = qrImage(for: code.verificationUrl) {
Image(uiImage: qr)
.interpolation(.none)
.resizable()
.frame(width: 260, height: 260)
.padding(12)
.background(.white, in: RoundedRectangle(cornerRadius: 16))
}
Text("и введите код")
.font(.title3)
.foregroundStyle(.secondary)
Text(code.userCode)
.font(.system(size: 64, weight: .bold, design: .monospaced))
.foregroundStyle(Color.ymAccent)
} else {
ProgressView()
}
Text(status)
.font(.footnote)
.foregroundStyle(.secondary)
}
.frame(width: 520)
.padding(40)
.background(Color.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 28, style: .continuous))
}
.padding(80)
}
.onAppear { startDeviceFlow() }
.onDisappear { pollTask?.cancel() }
}
private func qrImage(for string: String) -> UIImage? {
let filter = CIFilter.qrCodeGenerator()
filter.message = Data(string.utf8)
filter.correctionLevel = "M"
guard let output = filter.outputImage else { return nil }
let scaled = output.transformed(by: CGAffineTransform(scaleX: 10, y: 10))
let context = CIContext()
guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil }
return UIImage(cgImage: cgImage)
}
private func startDeviceFlow() {
pollTask?.cancel()
code = nil
error = nil
status = "Запрашиваем код…"
pollTask = Task {
do {
let received = try await DeviceAuth.requestCode()
guard !Task.isCancelled else { return }
code = received
status = "Ждём подтверждения…"
let interval = Double(received.interval ?? 5)
let deadline = Date().addingTimeInterval(Double(received.expiresIn))
while !Task.isCancelled, Date() < deadline {
try await Task.sleep(nanoseconds: UInt64(interval * 1_000_000_000))
guard !Task.isCancelled else { return }
switch try await DeviceAuth.poll(deviceCode: received.deviceCode) {
case .pending:
continue
case let .token(token):
status = "Готово!"
await state.signIn(with: token)
return
}
}
if !Task.isCancelled {
status = "Код истёк"
error = "Код истёк — запросите новый."
}
} catch is CancellationError {
return
} catch {
guard !Task.isCancelled else { return }
self.error = error.localizedDescription
status = "Ошибка"
}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
import SwiftUI
/// Everything that can be pushed onto a tab's navigation stack.
enum MusicRoute: Hashable {
case artist(Artist)
case album(Album)
}
extension View {
/// Attach once per NavigationStack so artist and album links work anywhere
/// inside that tab, including recursively (artist → album → artist → …).
func musicDestinations() -> some View {
navigationDestination(for: MusicRoute.self) { route in
switch route {
case let .artist(artist):
ArtistView(artist: artist)
case let .album(album):
AlbumView(album: album)
}
}
}
}
/// Poster tile that pushes a route instead of running an action.
struct PosterLink: View {
let title: String
let subtitle: String?
let imageURL: URL?
let route: MusicRoute
var circular = false
var body: some View {
NavigationLink(value: route) {
CoverImage(url: imageURL, corner: circular ? 140 : 12)
.frame(width: 280, height: 280)
}
.buttonStyle(circular ? AnyButtonStyle(CircleCardStyle()) : AnyButtonStyle(CardButtonStyle()))
.overlay(alignment: circular ? .bottom : .bottomLeading) {
VStack(alignment: circular ? .center : .leading, spacing: 2) {
Text(title)
.font(.caption)
.lineLimit(1)
if let subtitle, !subtitle.isEmpty {
Text(subtitle)
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
.frame(width: 280, alignment: circular ? .center : .leading)
.offset(y: 62)
}
.padding(.bottom, 70)
}
}
/// Type eraser so one view can pick between two button styles.
struct AnyButtonStyle: ButtonStyle {
private let makeBodyClosure: (Configuration) -> AnyView
init<S: ButtonStyle>(_ style: S) {
makeBodyClosure = { AnyView(style.makeBody(configuration: $0)) }
}
func makeBody(configuration: Configuration) -> some View {
makeBodyClosure(configuration)
}
}
/// The stock tvOS card treatment, wrapped so it can be erased alongside others.
struct CardButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
StyleBody(configuration: configuration)
}
private struct StyleBody: View {
@Environment(\.isFocused) private var isFocused
let configuration: ButtonStyleConfiguration
var body: some View {
configuration.label
.overlay {
if isFocused {
RoundedRectangle(cornerRadius: 12)
.strokeBorder(.white.opacity(0.95), lineWidth: 5)
}
}
.scaleEffect(configuration.isPressed ? 0.97 : (isFocused ? 1.05 : 1))
.animation(.spring(response: 0.3, dampingFraction: 0.7), value: isFocused)
}
}
}
/// Horizontal shelf used by the artist and album pages.
struct Shelf<Content: View>: View {
let title: String
@ViewBuilder let content: Content
var body: some View {
VStack(alignment: .leading, spacing: 20) {
Text(title).font(.title2.weight(.semibold))
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 60) {
content
}
.padding(.vertical, 24)
}
.scrollClipDisabled()
}
}
}
/// Applies the focus shadow only while focused, so unfocused cells cost nothing.
struct FocusShadow: ViewModifier {
let active: Bool
func body(content: Content) -> some View {
if active {
content.shadow(color: .black.opacity(0.5), radius: 24, y: 12)
} else {
content
}
}
}
+208
View File
@@ -0,0 +1,208 @@
import SwiftUI
struct MyWaveView: View {
@EnvironmentObject private var player: PlayerController
@EnvironmentObject private var state: AppState
@State private var stations: [Station] = []
@State private var isLoading = true
@State private var showSignOut = false
// Six across, as asked; the cards size themselves to the columns.
private let columns = Array(repeating: GridItem(.flexible(), spacing: 28), count: 6)
var body: some View {
NavigationStack {
content
.musicDestinations()
}
.task { await load() }
}
private var content: some View {
ScrollView {
VStack(alignment: .leading, spacing: 44) {
header
WaveHeroButton {
player.startRotor(station: "user:onyourwave", name: "Моя волна")
}
if isLoading {
LoadingState(text: "Загружаем станции…").frame(height: 300)
} else if !stations.isEmpty {
VStack(alignment: .leading, spacing: 24) {
Text("Станции")
.font(.title2.weight(.semibold))
LazyVGrid(columns: columns, spacing: 40) {
ForEach(stations, id: \.id) { station in
CardButton(
title: station.name ?? station.id.tag,
subtitle: nil,
imageURL: YMImage.url(station.icon?.imageUrl, size: 200),
width: 250
) {
player.startRotor(
station: station.id.stringValue,
name: station.name ?? station.id.tag
)
}
}
}
}
}
}
.padding(.vertical, 40)
}
}
private var header: some View {
HStack(alignment: .firstTextBaseline) {
Text("Волна")
.font(.system(size: 56, weight: .bold))
Spacer()
if showSignOut {
Button("Выйти", role: .destructive) { state.signOut() }
} else {
Button {
showSignOut = true
} label: {
Label(
state.accountName.isEmpty ? "Аккаунт" : state.accountName,
systemImage: "person.crop.circle"
)
.font(.callout)
}
.buttonStyle(.plain)
}
}
}
private func load() async {
isLoading = true
defer { isLoading = false }
do {
let dashboard = try await YMClient.shared.rotorDashboard()
var all = dashboard.stations.map(\.station)
if let list = try? await YMClient.shared.rotorStations() {
let known = Set(all.map(\.id.stringValue))
all += list.map(\.station).filter { !known.contains($0.id.stringValue) }
}
stations = all
} catch {
log.error("\(error.localizedDescription)")
}
}
}
/// The one thing people actually come to this screen for, so it gets to be big.
struct WaveHeroButton: View {
let action: () -> Void
var body: some View {
Button(action: action) {
EmptyView()
}
.buttonStyle(WaveHeroStyle())
}
}
private struct WaveHeroStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
StyleBody(configuration: configuration)
}
private struct StyleBody: View {
@Environment(\.isFocused) private var isFocused
let configuration: ButtonStyleConfiguration
var body: some View {
ZStack(alignment: .leading) {
LinearGradient(
colors: [
Color(red: 0.42, green: 0.16, blue: 0.62),
Color(red: 0.75, green: 0.22, blue: 0.35),
Color(red: 0.95, green: 0.62, blue: 0.13),
],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
HStack(spacing: 40) {
VStack(alignment: .leading, spacing: 14) {
Label("Радио", systemImage: "dot.radiowaves.left.and.right")
.font(.caption.weight(.semibold))
.foregroundStyle(.white.opacity(0.85))
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(.white.opacity(0.18), in: Capsule())
Text("Моя волна")
.font(.system(size: 68, weight: .heavy))
.foregroundStyle(.white)
Text("Бесконечный поток под ваш вкус")
.font(.title3)
.foregroundStyle(.white.opacity(0.8))
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 0)
EqualizerBars(animating: isFocused)
.frame(width: 180, height: 130)
ZStack {
Circle()
.fill(.white)
.frame(width: 110, height: 110)
Image(systemName: "play.fill")
.font(.system(size: 42, weight: .bold))
.foregroundStyle(Color(red: 0.42, green: 0.16, blue: 0.62))
}
}
.padding(.horizontal, 56)
.padding(.vertical, 48)
}
.frame(height: 300)
.clipShape(RoundedRectangle(cornerRadius: 28))
.overlay {
if isFocused {
RoundedRectangle(cornerRadius: 28).strokeBorder(.white.opacity(0.9), lineWidth: 5)
}
}
// Shadow only while focused, and no scaling: both are offscreen
// render passes on a card this large, and scaling a focused view is
// what makes tvOS swap in a snapshot of the screen.
.modifier(FocusShadow(active: isFocused))
.opacity(configuration.isPressed ? 0.85 : 1)
.animation(.easeOut(duration: 0.15), value: isFocused)
}
}
}
/// Five bars that idle flat and start dancing once the card takes focus.
struct EqualizerBars: View {
let animating: Bool
private let heights: [CGFloat] = [0.45, 0.95, 0.65, 1.0, 0.55]
var body: some View {
TimelineView(.animation(minimumInterval: 1.0 / 20, paused: !animating)) { timeline in
let t = timeline.date.timeIntervalSinceReferenceDate
GeometryReader { geo in
HStack(alignment: .center, spacing: 14) {
ForEach(heights.indices, id: \.self) { index in
let phase = t * 2.4 + Double(index) * 0.7
// At rest the bars still read as an equaliser, just frozen.
let wobble = animating ? (sin(phase) * 0.35 + 0.65) : 0.75
Capsule()
.fill(.white.opacity(0.9))
.frame(height: geo.size.height * heights[index] * wobble)
}
}
.frame(width: geo.size.width, height: geo.size.height, alignment: .center)
}
}
}
}
+159
View File
@@ -0,0 +1,159 @@
import SwiftUI
/// Synced lyrics, with a run-in before the first line.
struct LyricsPane: View {
let lyrics: Lyrics?
/// Intros longer than this get dots for their whole length; shorter ones
/// only for the last few seconds.
private let longIntro: Double = 5
private let shortLead: Double = 4
/// Words appear this far before the dots run out, so the first line is
/// already on screen and rolls away instead of appearing from nothing.
private let wordsLead: Double = 1
@ObservedObject private var clock = PlayerController.shared.clock
init(lyrics: Lyrics?) {
self.lyrics = lyrics
}
var body: some View {
// Dots and words share an origin, so the first line lands exactly where
// the dots were.
ZStack(alignment: .topLeading) {
if !linesVisible, let range = countdownRange {
CountdownDots(start: range.start, end: range.end)
.transition(.opacity)
}
if linesVisible {
LyricsLines(
lyrics: lyrics,
activeID: lyrics?.activeIndex(at: clock.currentTime),
armed: armed
)
.equatable()
.transition(.opacity)
}
}
.animation(.easeInOut(duration: 0.45), value: linesVisible)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private var firstLineTime: Double? {
lyrics?.lines.first(where: { !$0.isBlank })?.time
}
private var countdownStart: Double {
guard let first = firstLineTime else { return 0 }
return first > longIntro ? 0 : max(first - shortLead, 0)
}
private var countdownRange: (start: Double, end: Double)? {
guard let first = firstLineTime else { return nil }
let now = clock.currentTime
guard now >= countdownStart, now < first else { return nil }
return (countdownStart, first)
}
private var linesVisible: Bool {
guard let first = firstLineTime else { return true }
return clock.currentTime >= first - wordsLead
}
private var armed: Bool {
guard firstLineTime != nil else { return true }
return clock.currentTime >= countdownStart
}
}
/// Three dots filling one after another across the run-in. Each fills all the
/// way before the next one starts.
private struct CountdownDots: View {
let start: Double
let end: Double
@ObservedObject private var clock = PlayerController.shared.clock
init(start: Double, end: Double) {
self.start = start
self.end = end
}
private var progress: Double {
let span = max(end - start, 0.001)
return min(max((clock.currentTime - start) / span, 0), 1)
}
var body: some View {
HStack(spacing: 22) {
ForEach(0 ..< 3, id: \.self) { index in
let fill = min(max(progress * 3 - Double(index), 0), 1)
Circle()
.fill(.white.opacity(0.18 + 0.77 * fill))
.frame(width: 30, height: 30)
}
}
.padding(.top, 26)
// The clock ticks five times a second; this rides between the ticks.
.animation(.linear(duration: 0.2), value: progress)
}
}
/// The line being sung sits at the top, the lines still to come fade away below
/// it, and everything already sung is gone.
///
/// Not a ScrollView: driving a scroll offset from a timer made the highlight
/// drift out of view.
private struct LyricsLines: View, Equatable {
let lyrics: Lyrics?
let activeID: Int?
let armed: Bool
private let window = 6
/// Equatable collapses five ticks a second into one rebuild per line.
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.activeID == rhs.activeID
&& lhs.armed == rhs.armed
&& lhs.lyrics == rhs.lyrics
}
var body: some View {
rolling
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private var visible: [LyricsLine] {
guard armed else { return [] }
let sung = (lyrics?.lines ?? []).filter { !$0.isBlank }
guard let anchor = activeID ?? sung.first?.id else { return [] }
return Array(sung.filter { $0.id >= anchor }.prefix(window))
}
private var rolling: some View {
VStack(alignment: .leading, spacing: 34) {
ForEach(visible) { line in
Text(line.text)
.font(.system(size: line.id == activeID ? 96 : 76, weight: .bold))
.foregroundStyle(.white.opacity(opacity(for: line)))
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
.transition(.opacity)
}
Spacer(minLength: 0)
}
.animation(.easeInOut(duration: 0.35), value: activeID)
.clipped()
}
/// The sung line is solid; each line further ahead is dimmer than the last.
private func opacity(for line: LyricsLine) -> Double {
guard let activeID else { return 0.4 }
if line.id == activeID { return 1 }
let position = visible.firstIndex(where: { $0.id == line.id }) ?? 0
return max(0.08, 0.32 - Double(position) * 0.07)
}
}
+210
View File
@@ -0,0 +1,210 @@
import SwiftUI
/// The player screen.
///
/// Every width and height here is a constant. Whether a track has lyrics comes
/// from its metadata, which arrives with the track, so the two columns are
/// placed once per song and never move while it plays.
struct NowPlayingView: View {
@EnvironmentObject private var player: PlayerController
private enum Control: Hashable { case chrome, scrubber, previous, play, next, like }
private let stageHeight: CGFloat = 620
private let detailsWidth: CGFloat = 430
private let lyricsWidth: CGFloat = 1150
@State private var likeBusy = false
@FocusState private var focus: Control?
var body: some View {
ZStack {
BlurredBackdrop(url: player.current?.coverURL(size: 200))
if let track = player.current {
content(for: track)
} else {
idle
}
}
}
private var idle: some View {
VStack(spacing: 16) {
Image(systemName: "music.note")
.font(.system(size: 80))
.foregroundStyle(.secondary)
Text("Ничего не играет")
.font(.title2)
.foregroundStyle(.secondary)
}
}
// MARK: - Layout
private func content(for track: Track) -> some View {
VStack(spacing: 0) {
// The tab bar floats over the content: this strip reserves room for
// it and gives focus a step on the way back up to it.
Color.clear
.frame(height: 96)
.contentShape(Rectangle())
.focusable()
.focused($focus, equals: .chrome)
HStack(alignment: .top, spacing: showsLyrics ? 72 : 0) {
details(for: track)
.frame(width: detailsWidth, height: stageHeight, alignment: .top)
.clipped()
LyricsPane(lyrics: player.lyricsState == .ready ? player.lyrics : nil)
.frame(
width: showsLyrics ? lyricsWidth : 0,
height: stageHeight,
alignment: .topLeading
)
.clipped()
.opacity(showsLyrics ? 1 : 0)
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: showsLyrics ? .topLeading : .top
)
transportBar
}
.padding(.bottom, 24)
}
private var showsLyrics: Bool {
player.current?.lyricsInfo?.hasSynced ?? true
}
private func details(for track: Track) -> some View {
VStack(alignment: .leading, spacing: 24) {
CoverImage(url: track.coverURL(size: 400), corner: 18)
.frame(width: 390, height: 390)
VStack(alignment: .leading, spacing: 8) {
sourceLabel
Text(track.displayTitle)
.font(.system(size: 40, weight: .bold))
.lineLimit(2)
Text(track.artistNames)
.font(.system(size: 26))
.foregroundStyle(.white.opacity(0.65))
.lineLimit(1)
}
Spacer(minLength: 0)
}
}
@ViewBuilder
private var sourceLabel: some View {
switch player.source {
case let .rotor(_, name):
Label(name.uppercased(), systemImage: "dot.radiowaves.left.and.right")
.font(.caption.weight(.semibold))
.foregroundStyle(Color.ymAccent)
case let .collection(name):
Text(name.uppercased())
.font(.caption.weight(.semibold))
.foregroundStyle(Color.ymAccent)
case .none:
EmptyView()
}
}
// MARK: - Transport
private var transportBar: some View {
VStack(alignment: .trailing, spacing: 16) {
HStack(spacing: 20) {
Spacer(minLength: 0)
Button { player.previous() } label: {
Image(systemName: "backward.fill")
}
.buttonStyle(GlyphButtonStyle())
.focused($focus, equals: .previous)
Button { player.togglePlayPause() } label: {
Image(systemName: player.isPlaying ? "pause.fill" : "play.fill")
}
.buttonStyle(GlyphButtonStyle(prominent: true))
.focused($focus, equals: .play)
Button { player.next() } label: {
Image(systemName: "forward.fill")
}
.buttonStyle(GlyphButtonStyle())
.focused($focus, equals: .next)
Button { toggleLike() } label: {
Image(systemName: isLiked ? "heart.fill" : "heart")
}
.buttonStyle(GlyphButtonStyle(tinted: isLiked))
.focused($focus, equals: .like)
.disabled(likeBusy)
}
Scrubber(
seek: { player.seek(to: $0) },
togglePlayPause: { player.togglePlayPause() }
)
.focused($focus, equals: .scrubber)
}
.focusSection()
}
private var isLiked: Bool { player.isLiked(player.current) }
private func toggleLike() {
likeBusy = true
Task {
await player.toggleLikeCurrent()
likeBusy = false
}
}
}
/// A glyph that takes a solid disc on focus. No scaling: growing a focused view
/// makes tvOS swap in a snapshot of the screen.
private struct GlyphButtonStyle: ButtonStyle {
var tinted = false
var prominent = false
func makeBody(configuration: Configuration) -> some View {
StyleBody(configuration: configuration, tinted: tinted, prominent: prominent)
}
private struct StyleBody: View {
@Environment(\.isFocused) private var isFocused
@Environment(\.isEnabled) private var isEnabled
let configuration: ButtonStyleConfiguration
let tinted: Bool
let prominent: Bool
private var foreground: Color {
if isFocused { return .black }
return tinted ? .ymAccent : .white
}
var body: some View {
configuration.label
.font(.system(size: prominent ? 34 : 28, weight: .semibold))
.foregroundStyle(foreground)
.opacity(isEnabled ? (configuration.isPressed ? 0.7 : 1) : 0.3)
.frame(width: prominent ? 88 : 72, height: prominent ? 88 : 72)
.background {
Circle().fill(
isFocused
? AnyShapeStyle(.white)
: AnyShapeStyle(.white.opacity(prominent ? 0.22 : 0.12))
)
}
.animation(.easeOut(duration: 0.15), value: isFocused)
}
}
}
+112
View File
@@ -0,0 +1,112 @@
import SwiftUI
/// Full-width transport bar.
///
/// Swipes in the same direction build up speed, the target is previewed while
/// scrubbing, and the seek is committed once the swiping stops.
struct Scrubber: View {
let seek: (Double) -> Void
let togglePlayPause: () -> Void
private let steps: [Double] = [5, 10, 20, 30, 45, 60]
private let streakWindow: TimeInterval = 0.4
private let commitDelay: UInt64 = 500_000_000
@ObservedObject private var clock = PlayerController.shared.clock
@FocusState private var focused: Bool
@State private var preview: Double?
@State private var lastMove = Date.distantPast
@State private var streak = 0
@State private var commitTask: Task<Void, Never>?
private var position: Double { preview ?? clock.currentTime }
private var fraction: Double {
guard clock.duration > 0 else { return 0 }
return min(max(position / clock.duration, 0), 1)
}
var body: some View {
VStack(spacing: 12) {
bar.frame(height: 16)
HStack {
Text(formatTime(position))
Spacer()
Text("-" + formatTime(max(clock.duration - position, 0)))
}
.font(.system(size: 24, weight: .medium).monospacedDigit())
.foregroundStyle(.white.opacity(focused ? 0.95 : 0.55))
}
.padding(.vertical, 10)
.contentShape(Rectangle())
.focusable()
.focused($focused)
.onMoveCommand { direction in
switch direction {
case .left: nudge(-1)
case .right: nudge(1)
default: break
}
}
.onExitCommand { cancelScrub() }
.onPlayPauseCommand { togglePlayPause() }
.onChange(of: focused) { _, isFocused in
if !isFocused { cancelScrub() }
}
}
/// Fixed height; only the drawing inside reacts to focus, so taking focus
/// never re-lays-out the screen.
private var bar: some View {
GeometryReader { geo in
let height: CGFloat = focused ? 14 : 8
let knob: CGFloat = preview == nil ? 26 : 34
ZStack(alignment: .leading) {
Capsule()
.fill(.white.opacity(focused ? 0.32 : 0.2))
.frame(height: height)
Capsule()
.fill(.white)
.frame(width: geo.size.width * fraction, height: height)
if focused {
Circle()
.fill(.white)
.frame(width: knob, height: knob)
.offset(x: geo.size.width * fraction - knob / 2)
}
}
.frame(width: geo.size.width, height: geo.size.height, alignment: .leading)
}
}
private func nudge(_ direction: Double) {
guard clock.duration > 0 else { return }
let now = Date()
streak = now.timeIntervalSince(lastMove) < streakWindow
? min(streak + 1, steps.count - 1)
: 0
lastMove = now
let target = (preview ?? clock.currentTime) + direction * steps[streak]
preview = min(max(target, 0), clock.duration)
commitTask?.cancel()
commitTask = Task {
try? await Task.sleep(nanoseconds: commitDelay)
guard !Task.isCancelled, let target = preview else { return }
seek(target)
preview = nil
streak = 0
}
}
private func cancelScrub() {
commitTask?.cancel()
preview = nil
streak = 0
}
}
+27
View File
@@ -0,0 +1,27 @@
import SwiftUI
struct RootView: View {
@EnvironmentObject private var player: PlayerController
@State private var selection = 0
var body: some View {
TabView(selection: $selection) {
MyWaveView()
.tabItem { Label("Волна", systemImage: "dot.radiowaves.left.and.right") }
.tag(0)
LikesView()
.tabItem { Label("Мне нравится", systemImage: "heart.fill") }
.tag(1)
NowPlayingView()
.tabItem { Label("Сейчас играет", systemImage: "play.circle.fill") }
.tag(2)
SearchView()
.tabItem { Image(systemName: "magnifyingglass") }
.tag(3)
}
.onPlayPauseCommand { player.togglePlayPause() }
}
}
+157
View File
@@ -0,0 +1,157 @@
import SwiftUI
struct SearchView: View {
@EnvironmentObject private var player: PlayerController
@State private var query = ""
@State private var tracks: [Track] = []
@State private var albums: [Album] = []
@State private var artists: [Artist] = []
@State private var isSearching = false
@State private var searchTask: Task<Void, Never>?
private let grid = [GridItem(.adaptive(minimum: 280), spacing: 60)]
var body: some View {
NavigationStack {
results
// tvOS turns this into the system search scene: keyboard on the
// left, these results on the right, exactly like Apple Music.
.searchable(text: $query, prompt: "Исполнители, треки, альбомы")
.musicDestinations()
}
.onChange(of: query) { _, new in scheduleSearch(for: new) }
}
@ViewBuilder
private var results: some View {
ScrollView {
VStack(alignment: .leading, spacing: 50) {
if isSearching {
LoadingState(text: "Ищем…").frame(height: 400)
} else if query.trimmingCharacters(in: .whitespaces).isEmpty {
placeholder
} else if tracks.isEmpty, albums.isEmpty, artists.isEmpty {
placeholder
} else {
if !artists.isEmpty { artistSection.focusSection() }
if !tracks.isEmpty { trackSection.focusSection() }
if !albums.isEmpty { albumSection.focusSection() }
}
}
.padding(.vertical, 40)
}
}
private var placeholder: some View {
VStack(spacing: 16) {
Image(systemName: "magnifyingglass")
.font(.system(size: 72))
.foregroundStyle(.secondary)
Text(query.isEmpty ? "Что послушаем?" : "Ничего не нашлось")
.font(.title2)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.top, 120)
}
private var artistSection: some View {
VStack(alignment: .leading, spacing: 20) {
Text("Исполнители").font(.title2.weight(.semibold))
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 60) {
ForEach(artists.prefix(12), id: \.id) { artist in
PosterLink(
title: artist.name,
subtitle: nil,
imageURL: artist.coverURL(size: 200),
route: .artist(artist),
circular: true
)
}
}
.padding(.vertical, 24)
}
.scrollClipDisabled()
}
}
private var trackSection: some View {
VStack(alignment: .leading, spacing: 20) {
HStack(alignment: .firstTextBaseline) {
Text("Треки").font(.title2.weight(.semibold))
Spacer()
Button {
play(tracks, from: 0, title: "Поиск: \(query)")
} label: {
Label("Слушать всё", systemImage: "play.fill").font(.callout)
}
.buttonStyle(.plain)
}
LazyVGrid(columns: grid, spacing: 60) {
ForEach(Array(tracks.prefix(24).enumerated()), id: \.offset) { pair in
CardButton(
title: pair.element.displayTitle,
subtitle: pair.element.artistNames,
imageURL: pair.element.coverURL(size: 200)
) {
play(tracks, from: pair.offset, title: "Поиск: \(query)")
}
}
}
}
}
private var albumSection: some View {
VStack(alignment: .leading, spacing: 20) {
Text("Альбомы").font(.title2.weight(.semibold))
LazyVGrid(columns: grid, spacing: 60) {
ForEach(albums.prefix(12), id: \.id) { album in
PosterLink(
title: album.displayTitle,
subtitle: album.artistNames,
imageURL: album.coverURL(size: 200),
route: .album(album)
)
}
}
}
}
// MARK: - Actions
private func play(_ list: [Track], from index: Int, title: String) {
player.play(tracks: list, startAt: index, source: .collection(title))
}
// MARK: - Search
private func scheduleSearch(for text: String) {
searchTask?.cancel()
let trimmed = text.trimmingCharacters(in: .whitespaces)
guard trimmed.count >= 2 else {
tracks = []; albums = []; artists = []
isSearching = false
return
}
isSearching = true
searchTask = Task {
// Let the on-screen keyboard settle before hitting the API.
try? await Task.sleep(nanoseconds: 450_000_000)
guard !Task.isCancelled else { return }
do {
let result = try await YMClient.shared.search(trimmed, type: "all")
guard !Task.isCancelled else { return }
tracks = result.tracks?.results ?? []
albums = result.albums?.results ?? []
artists = result.artists?.results ?? []
} catch {
guard !Task.isCancelled else { return }
log.error("\(error.localizedDescription)")
}
isSearching = false
}
}
}