Files
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

255 lines
9.8 KiB
Swift
Executable File

// QueueView — the LOCAL play queue (Up Next), presented as a sheet from the
// mini player's queue button.
//
// This is the destination the queue-editing actions finally have: TrackRow's
// "Play Next" / "Add to Queue" menu items, the selection bar's bulk versions of
// the same, autoplay's related-track refills and a radio station all write into
// QueueController.queue, and until now nothing in the app rendered that array —
// the user's only queue view was DevicesView's RemoteQueueSheet, which shows
// ANOTHER device's queue.
//
// It is that sheet's twin pointed at this device, and the differences are all
// consequences of the queue being local rather than published over RTDB:
// - No 60-item cap and so no "Showing X of Y": the published remote snapshot
// is trimmed, the real queue here is not.
// - No optimistic overlay. RemoteQueueSheet keeps one because its move is a
// command that round-trips device → RTDB → peer → RTDB → us, so the row
// would otherwise sit still for the whole flight. Here every mutation is a
// synchronous call on the @Observable controller, so the next render
// already holds the new order and `withAnimation` is the entire story.
// - Same identity rule though, for the same reason: occurrenceKeyed (track id
// + which occurrence) so a move ANIMATES as a move instead of rows swapping
// contents, and so a queue legitimately holding the same track twice (no
// queue writer dedupes — Dart parity) keeps those rows distinct.
//
// Row actions map 1:1 onto the controller's queue-editing surface — the same
// entry points the cross-device receiver calls (AppRoot.runRemoteCommand), so
// their guards are shared and already proven: playQueueIndex (jump),
// reorderQueue (move), removeQueueAt (remove, which REFUSES the playing row)
// and clearQueue.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct QueueView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme(); sheets
// inherit it, like RemoteQueueSheet).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
@Environment(\.dismiss) private var dismiss
public init() {}
@ObserveInjection var inject
public var body: some View {
Group {
let queue = services.queue
// Read both halves ONCE per render: a row's highlight and its remove-button
// enablement must never disagree about which index is playing.
let tracks = queue.queue
let currentIndex = queue.queueIndex
VStack(spacing: 0) {
header(p, tracks: tracks, currentIndex: currentIndex, queue: queue)
Rectangle().fill(p.hair).frame(height: 1)
if tracks.isEmpty {
// Reachable while something is still PLAYING: clearQueue empties the
// list without stopping the current track (the mini player stays up),
// so this is an empty up-next list, not an idle player.
Text("Queue is empty")
.rw(.bodySmall)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView {
LazyVStack(spacing: 0) {
ForEach(occurrenceKeyed(tracks, id: \.id)) { entry in
row(
entry.value, index: entry.index, count: tracks.count,
isCurrent: entry.index == currentIndex, palette: p, queue: queue)
}
}
}
}
}
.background(p.bg)
#if os(macOS)
.frame(minWidth: 440, minHeight: 480)
#endif
// Opaque, square sheet panel (no-op when this view is pushed).
.rwFlatSheet()
}
.enableInjection()
}
// MARK: - Header
private func header(
_ p: RwPalette, tracks: [SCTrack], currentIndex: Int, queue: QueueController
) -> some View {
HStack(spacing: RwSizes.gap) {
VStack(alignment: .leading, spacing: 2) {
Text("Queue")
.rw(.titleSmall, color: p.text.color)
.lineLimit(1)
if !tracks.isEmpty {
// Position, not a cap notice: the local queue is never trimmed, so
// "X of Y" here means where playback sits, unlike the remote sheet's
// "Showing X of Y". Index guarded — a queue edit can outrun it.
Text("\(min(max(currentIndex, 0), tracks.count - 1) + 1) of \(tracks.count)")
.rw(.labelMedium)
}
}
Spacer(minLength: RwSizes.gap)
if !tracks.isEmpty {
Button {
// Empties the up-next list; the current track keeps playing (see the
// empty state above).
withAnimation(.snappy(duration: 0.25)) { queue.clearQueue() }
} label: {
LitPalette { p in
HStack(spacing: 4) {
Image(systemName: "clear")
.font(.system(size: 11, weight: .semibold))
Text("Clear")
.rw(.labelMedium, color: p.red.color)
}
.foregroundStyle(p.red)
.padding(.horizontal, 10)
.frame(height: 28)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
}
#if os(macOS)
// No pull-to-dismiss on macOS sheets (RemoteQueueSheet's rule).
Button {
dismiss()
} label: {
Image(systemName: "xmark")
.font(.system(size: 11, weight: .semibold))
// Chrome, not text: iconInactive stays on-brand where textMuted
// reads gray on an icon.
.foregroundStyle(p.iconInactive)
.padding(6)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.keyboardShortcut(.cancelAction)
#endif
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, RwSizes.gap)
}
// MARK: - Row
private func row(
_ track: SCTrack, index i: Int, count: Int, isCurrent: Bool,
palette p: RwPalette, queue: QueueController
) -> some View {
HStack(spacing: RwSizes.gap) {
artwork(track, palette: p)
VStack(alignment: .leading, spacing: 2) {
// No colour override: the playing row is told apart by litRow's
// active colour and the outline (TrackRow's rules).
Text(track.title)
.rw(.bodyLarge)
.lineLimit(1)
Text(track.user.username)
.rw(.labelMedium)
.lineLimit(1)
}
Spacer(minLength: RwSizes.gap)
// Worth the space in a QUEUE specifically: a Go+ track is the one that
// can fail to start when the account can't stream it.
if track.isGoPlusOnly {
OutlinedBadge("GO+")
}
rowButton("chevron.up", enabled: i > 0, palette: p) {
move(queue, from: i, to: i - 1)
}
rowButton("chevron.down", enabled: i < count - 1, palette: p) {
move(queue, from: i, to: i + 1)
}
// Mirrors removeQueueAt's own refusal (index == queueIndex is a no-op, so
// playback is never yanked out from under itself): the disabled button
// says so up front instead of swallowing the tap.
rowButton("xmark", enabled: !isCurrent, palette: p) {
withAnimation(.snappy(duration: 0.25)) { queue.removeQueueAt(i) }
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 6)
.contentShape(Rectangle())
.litRow(active: isCurrent)
.nowPlayingBorder(isCurrent)
// Row tap jumps; the buttons above win their own taps (a Button beats the
// container's onTapGesture — the MiniPlayerBar convention). The sheet stays
// open on purpose, like the remote queue sheet: jumping around a queue is
// usually more than one press.
.onTapGesture { Task { await queue.playQueueIndex(i) } }
}
/// 'large' (100x100) with the tinted-note degrade, TrackRow's artwork rules at
/// the 40pt size the remote queue sheet uses.
private func artwork(_ track: SCTrack, palette p: RwPalette) -> some View {
AsyncImage(url: track.artworkUrlSmall.flatMap(URL.init(string:))) { image in
image.resizable().scaledToFill()
} placeholder: {
ZStack {
p.bg2.color
Image(systemName: "music.note")
.font(.system(size: 14))
// Inactive chrome, not secondary text (TrackRow's note).
.foregroundStyle(p.iconInactive)
}
}
.frame(width: 40, height: 40)
// scaledToFill overflows the frame, so a clip is still needed — a square
// one; corners are 0 everywhere.
.clipShape(Rectangle())
.rwBorder(.accent, width: 2)
}
private func rowButton(
_ symbol: String, enabled: Bool, palette p: RwPalette,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
LitPalette { p in
Image(systemName: symbol)
.font(.system(size: 12, weight: .semibold))
// Disabled dims to 40% primary (the disabled tone; the old pastel is
// primary now, BareButtons.swift).
.foregroundStyle(enabled ? p.text : p.red.withAlpha(0.4))
.frame(width: 28, height: 28)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.disabled(!enabled)
}
// MARK: - Mutations
/// Move one row. reorderQueue validates both ends (and re-finds queueIndex by
/// the playing track's id afterwards), so the button enablement above is the
/// affordance and the controller is the authority.
///
/// WHY no optimistic overlay, unlike RemoteQueueSheet.applyMove: that one's
/// move is a command in flight over RTDB, so it paints the result locally and
/// reconciles on the peer's next publish. This call mutates the local
/// @Observable queue synchronously — the reconcile and the optimism are the
/// same render — and withAnimation plus occurrence-keyed identity is what
/// makes it read as a row MOVING rather than two rows exchanging contents.
private func move(_ queue: QueueController, from: Int, to: Int) {
withAnimation(.snappy(duration: 0.25)) { queue.reorderQueue(from: from, to: to) }
}
}