Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
435 lines
19 KiB
Swift
Executable File
435 lines
19 KiB
Swift
Executable File
// TrackRow — the shared track list row (the Components twin of the private row
|
|
// LikesView grew first; that one stays as-is until screens migrate).
|
|
//
|
|
// Behavior contract (screens rely on this):
|
|
// - Tapping the row plays via services.queue.playTrack(track, newQueue: list)
|
|
// so next/prev/autoplay walk the WHOLE list the row was rendered from — a
|
|
// row is never a dead-end single-track queue.
|
|
// - The context menu carries the Flutter track_tile action set (play next /
|
|
// add to queue / send to device / add to playlist / station / like / go to
|
|
// artist / go to track page / copy link, in that order).
|
|
// - "Add to Playlist…" opens the SHARED AddToPlaylistSheet (the port of
|
|
// showPlaylistPickerFor) with this one track, and the row performs the write
|
|
// the sheet hands back — a Task started inside a sheet that is dismissing can
|
|
// be torn down with it, which is why that sheet never writes itself.
|
|
// - Like is optimistic: flip locally, confirm with the API, revert on throw
|
|
// (QueueController.toggleLike's pattern). SCTrack is a value type, so the
|
|
// row keeps its own @State copy — the flip renders instantly here while
|
|
// the server round-trip settles. A parent re-render with fresher data
|
|
// recreates the row (ForEach identity) and resets the copy.
|
|
// - Hair separators are the LIST's job, not the row's — rows butt together
|
|
// cleanly inside cards, sections and plain lists alike (see LikesView).
|
|
//
|
|
// Selection Mode (see Components/SelectionMode.swift) is OPTIONAL and rides
|
|
// the environment: a list that injects `.trackSelection(holder)` gets
|
|
// multi-select for free, and a list that doesn't is byte-identical to before
|
|
// (every branch below is guarded on a nil holder). While the holder is ACTIVE:
|
|
// - a row tap toggles the tick instead of playing — playback is
|
|
// deliberately unreachable from a row, like the Dart's selectable tile,
|
|
// - the row grows a leading checkmark and the accent wash,
|
|
// - the context menu goes away entirely (tap = toggle, and an empty
|
|
// `.contextMenu` still opens an empty sheet on iOS).
|
|
// While it is INACTIVE the menu gains one item, `Select`, as its first entry.
|
|
// That is the long-press entry point on iOS: a bare `.onLongPressGesture`
|
|
// pre-empts `UIContextMenuInteraction`, which would delete the row's whole
|
|
// action menu — so long press opens the menu and `Select` is the first thing
|
|
// in it, exactly how Photos/Files/Mail enter multi-select.
|
|
|
|
import CrossSoundKit
|
|
import Inject
|
|
import RedWhiteUI
|
|
import SwiftUI
|
|
|
|
#if canImport(UIKit)
|
|
import UIKit
|
|
#elseif canImport(AppKit)
|
|
import AppKit
|
|
#endif
|
|
|
|
@MainActor
|
|
public struct TrackRow: View {
|
|
// The palette around the row; the row paints with `p` below.
|
|
@Environment(\.rw) private var base
|
|
@Environment(AppServices.self) private var services
|
|
/// Published by the hosting NavigationStack (AppPush.swift). RwMenuItem is
|
|
/// action-only, so the rows that used to be NavigationLinks push through
|
|
/// this instead; nil means no stack hosts us and those rows are omitted.
|
|
@Environment(\.appPush) private var push
|
|
/// The enclosing list's multi-select holder, or nil on lists that don't
|
|
/// offer selection (the default — see the header note).
|
|
@Environment(\.trackSelection) private var selection
|
|
/// The station this list is, when it is one (PlayingStation.swift): playing
|
|
/// from it starts the station, not just a list.
|
|
@Environment(\.stationContext) private var stationContext
|
|
|
|
/// The row's data, straight from the list — NOT a @State copy. A @State
|
|
/// copy is initialized once per view identity and never refreshed, so when
|
|
/// a list replaced its contents at the same identity (the playlist
|
|
/// back-fill: ~5 hydrated stubs → the full list) the row kept rendering
|
|
/// the OLD track while its neighbours updated — rows visibly overlapping /
|
|
/// shuffling. Identity-stable lists plus this value fix that class of bug.
|
|
private let source: SCTrack
|
|
/// The play context handed to playTrack: the full list this row lives in.
|
|
private let list: [SCTrack]
|
|
|
|
//Set by a playlist the user can edit; nil everywhere else, so the item
|
|
//only shows up there
|
|
|
|
private let onRemoveFromPlaylist: (() -> Void)?
|
|
|
|
public init (track: SCTrack, in list: [SCTrack], onRemoveFromPlaylist: (()-> Void)? = nil) {
|
|
self.source = track
|
|
self.list = list
|
|
self.onRemoveFromPlaylist = onRemoveFromPlaylist
|
|
}
|
|
|
|
/// Optimistic like flip only, reset whenever the row is handed a different
|
|
/// track (see body) so it can never leak across a reused view identity.
|
|
@State private var likeOverride: Bool?
|
|
@State private var likeOverrideTrackId: String?
|
|
/// The playlist picker's presentation. Hosted on the ROW, not on the menu:
|
|
/// menu content is torn down the moment an item is tapped, so a `.sheet`
|
|
/// attached in there never gets to present.
|
|
@State private var showPlaylistPicker = false
|
|
|
|
/// What the row draws: the handed-in track, with the pending like flip
|
|
/// applied when it belongs to THIS track.
|
|
private var track: SCTrack {
|
|
guard let liked = pendingLike else { return source }
|
|
var copy = source
|
|
copy.isLiked = liked
|
|
return copy
|
|
}
|
|
|
|
/// The pending like flip for THIS track. The shared holder's wins when a
|
|
/// list screen provides one, so a bulk Like from the selection bar paints
|
|
/// every row it touched; without a holder the row's own @State is the only
|
|
/// store, exactly as before.
|
|
private var pendingLike: Bool? {
|
|
if let shared = selection?.likeOverride(for: source.id) { return shared }
|
|
guard likeOverrideTrackId == source.id else { return nil }
|
|
return likeOverride
|
|
}
|
|
|
|
/// Selection is ON for this list. Read once per body so the tap action, the
|
|
/// chrome and the menu can never disagree mid-render.
|
|
private var selecting: Bool { selection?.isActive == true }
|
|
/// Pointer over the row (Mac, iPad pointer).
|
|
@State private var hovering = false
|
|
/// The track the player is on: the row's "active" state, and its outline.
|
|
private var isCurrent: Bool { services.queue.currentTrack?.id == source.id }
|
|
/// What the row paints with: the hover colour when exactly one of hover /
|
|
/// active is true (BareButtons.swift). Active is playing, or ticked while
|
|
/// selecting — the ticked row's wash went with the backgrounds. Read here
|
|
/// AND planted for the subtree, so the explicit colours below (duration,
|
|
/// heart) follow as well as the `.rw()` text and the ⋯ menu.
|
|
private var p: RwPalette {
|
|
base.lit(isLit(active: isCurrent || (selecting && isSelected), hovering: hovering))
|
|
}
|
|
private var isSelected: Bool { selection?.isSelected(source.id) == true }
|
|
|
|
@ObserveInjection var inject
|
|
|
|
public var body: some View {
|
|
// HStack + a Button for the tap area, not one Button wrapping the whole
|
|
// row: a Button nested inside another Button's label never receives the
|
|
// tap. PlaylistRow is shaped this way for the same reason.
|
|
HStack(spacing: 0) {
|
|
Button {
|
|
// While selecting, the whole row is the checkbox (the Dart tile's
|
|
// `onTap: selectable ? toggle : play`).
|
|
if let selection, selection.isActive {
|
|
selection.toggle(source.id)
|
|
} else {
|
|
Task { await services.queue.playTrack(track, newQueue: list, station: stationContext) }
|
|
}
|
|
} label: {
|
|
HStack(spacing: RwSizes.gap) {
|
|
if selecting {
|
|
SelectionCheckmark(selected: isSelected)
|
|
}
|
|
artwork(p)
|
|
VStack(alignment: .leading, spacing: 2) {
|
|
// No color override: the role supplies it from the row's palette,
|
|
// which follows hover and the playing track.
|
|
Text(track.title)
|
|
.rw(.bodyLarge)
|
|
.lineLimit(1)
|
|
Text(track.user.username)
|
|
.rw(.labelMedium)
|
|
.lineLimit(1)
|
|
}
|
|
Spacer(minLength: RwSizes.gap)
|
|
if track.isGoPlusOnly {
|
|
OutlinedBadge("GO+")
|
|
}
|
|
Text(track.durationFormatted)
|
|
.font(.system(size: 12).monospacedDigit())
|
|
.foregroundStyle(p.textMuted)
|
|
}
|
|
.padding(.leading, RwSizes.pagePadding)
|
|
// No trailing page padding while the accessories are up: they own
|
|
// that edge, and doubling the inset shoves the duration inward
|
|
// (PlaylistRow's rule).
|
|
.padding(.trailing, selecting ? RwSizes.pagePadding : RwSizes.gap)
|
|
.padding(.vertical, 8)
|
|
.contentShape(Rectangle())
|
|
}
|
|
.buttonStyle(.plain)
|
|
|
|
// Hidden while selecting: the row IS the checkbox then, and a like or a
|
|
// menu would be a second meaning for the same tap.
|
|
if !selecting {
|
|
likeButton
|
|
// RwMenu, not Menu: the system menu renders out of process as
|
|
// translucent glass on iOS 26+ and no modifier turns it off. Same
|
|
// items as press-and-hold — a second door to them, not a second set.
|
|
RwMenu(menuItems) {
|
|
Image(systemName: "ellipsis")
|
|
.font(.system(size: 13, weight: .semibold))
|
|
}
|
|
.padding(.trailing, RwSizes.pagePadding - 8)
|
|
.accessibilityLabel("Track actions")
|
|
}
|
|
}
|
|
.environment(\.rw, p)
|
|
.onHover { hovering = $0 }
|
|
.animation(.easeOut(duration: 0.12), value: hovering)
|
|
.nowPlayingBorder(isCurrent)
|
|
.accessibilityAddTraits(selecting && isSelected ? .isSelected : [])
|
|
.rwContextMenuUnlessSelecting(selecting, items: menuItems)
|
|
.sheet(isPresented: $showPlaylistPicker) {
|
|
// The same picker the selection bar and PlaylistDetailView open; it hands
|
|
// the decision back rather than writing (see its header).
|
|
AddToPlaylistSheet(
|
|
trackCount: 1,
|
|
onPick: { target in Task { await addToPlaylist(target) } },
|
|
onCreate: { newTitle, isPublic in
|
|
Task { await createPlaylistWithTrack(title: newTitle, isPublic: isPublic) }
|
|
})
|
|
}
|
|
.enableInjection()
|
|
}
|
|
|
|
/// The like heart, mirroring the menu's Like/Unlike item. Optimistic the
|
|
/// same way: `track` already reads through likeOverride, so the glyph flips
|
|
/// on tap and settles when the API confirms (or reverts).
|
|
private var likeButton: some View {
|
|
Button {
|
|
Task { await toggleLike() }
|
|
} label: {
|
|
// No colour here: liked is the toggle's active state, so the bare
|
|
// style gives it (the hover colour when liked, flipping on hover).
|
|
Image(systemName: track.isLiked ? "heart.fill" : "heart")
|
|
.font(.system(size: 14))
|
|
.frame(width: 32, height: 32)
|
|
.contentShape(Rectangle())
|
|
}
|
|
.buttonStyle(.bareRow(active: track.isLiked))
|
|
.accessibilityLabel(track.isLiked ? "Unlike" : "Like")
|
|
}
|
|
|
|
// MARK: - Artwork
|
|
|
|
private func artwork(_ p: RwPalette) -> some View {
|
|
// 'large' (100x100) is the list-row size; a missing/failed image degrades
|
|
// to a tinted note (SoundCloud leaves artwork_url null on plenty of
|
|
// tracks, and the model's avatar fallback can be null too).
|
|
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: 16))
|
|
// Inactive chrome, not secondary text: iconInactive keeps the note
|
|
// on-brand where textMuted would read gray (the palette's note).
|
|
.foregroundStyle(p.iconInactive)
|
|
}
|
|
}
|
|
.frame(width: 44, height: 44)
|
|
// Square, like every other corner in the app (the design system's radius
|
|
// is 0 on purpose). The clip itself stays: scaledToFill overflows the
|
|
// 44pt frame without it.
|
|
.clipShape(Rectangle())
|
|
.rwBorder(.accent, width: 2)
|
|
}
|
|
|
|
// MARK: - Context menu
|
|
|
|
/// The row's menu as DATA. RwMenuItem carries a label, a symbol and an
|
|
/// action — no submenus and no links — so two things changed shape versus
|
|
/// the system menu this replaces:
|
|
/// - "Send to Device" was a submenu; online peers are now flattened into
|
|
/// "Send to <name>" rows between separators.
|
|
/// - "Go to Artist" / "Go to Track Page" were NavigationLinks; they push
|
|
/// through \.appPush and are omitted when no stack hosts the row.
|
|
private var menuItems: [RwMenuItem] {
|
|
var items: [RwMenuItem] = []
|
|
|
|
// Multi-select entry, first so a long press lands on it. Ticks this row
|
|
// on the way in — entering with nothing selected reads as "nothing
|
|
// happened".
|
|
if let selection, !selection.isActive {
|
|
items.append(
|
|
RwMenuItem("Select", systemImage: "checkmark.circle") {
|
|
selection.begin(selecting: source.id)
|
|
})
|
|
items.append(.separator)
|
|
}
|
|
|
|
items.append(
|
|
RwMenuItem("Play", systemImage: "play.fill") {
|
|
Task { await services.queue.playTrack(track, newQueue: list, station: stationContext) }
|
|
})
|
|
items.append(
|
|
RwMenuItem("Play Next", systemImage: "text.line.first.and.arrowtriangle.forward") {
|
|
services.queue.addToNextUp(track)
|
|
})
|
|
items.append(
|
|
RwMenuItem("Add to Queue", systemImage: "text.append") {
|
|
Task { await services.queue.addTracksToQueue([track]) }
|
|
})
|
|
|
|
// Cross-device queueing — the Dart track_tile's per-device "Add to
|
|
// {name} queue" entries. Only ONLINE peers (the Dart filtered the same
|
|
// way); no online peer → no rows and no separators. The receiver-side
|
|
// `enqueue` appends the ids in order and starts playback when the peer is
|
|
// idle — see RemoteService's command vocabulary.
|
|
let onlinePeers = services.remote.devices.filter(\.online)
|
|
if !onlinePeers.isEmpty {
|
|
items.append(.separator)
|
|
for d in onlinePeers {
|
|
items.append(
|
|
RwMenuItem("Send to \(d.name)", systemImage: DevicesView.platformIcon(d.platform)) {
|
|
Task {
|
|
await services.remote.sendCommand(
|
|
to: d.id, cmd: "enqueue", args: ["trackIds": [track.id]])
|
|
}
|
|
})
|
|
}
|
|
items.append(.separator)
|
|
}
|
|
|
|
// Dart order: the picker sat between the device entries and Station.
|
|
items.append(
|
|
RwMenuItem("Add to Playlist…", systemImage: "text.badge.plus") {
|
|
showPlaylistPicker = true
|
|
})
|
|
items.append(
|
|
RwMenuItem("Start Radio", systemImage: "dot.radiowaves.left.and.right") {
|
|
// Result deliberately dropped: the row has nowhere to surface
|
|
// "station found nothing" — failures land in QueueController
|
|
// .lastError, which the shell's banner already watches.
|
|
Task { _ = await services.queue.startRadio(seed: track) }
|
|
})
|
|
// Only when THIS row is the track already playing. keepPlaying swaps the
|
|
// station in behind the playing seed instead of going through playTrack;
|
|
// on any other row there is nothing to keep playing, so the two entries
|
|
// would do exactly the same thing and one of them would be a lie.
|
|
if services.queue.currentTrack?.id == source.id {
|
|
items.append(
|
|
RwMenuItem("Start Radio (Keep Playing)", systemImage: "dot.radiowaves.forward") {
|
|
Task { _ = await services.queue.startRadio(seed: track, keepPlaying: true) }
|
|
})
|
|
}
|
|
|
|
items.append(.separator)
|
|
items.append(
|
|
RwMenuItem(
|
|
track.isLiked ? "Unlike" : "Like",
|
|
systemImage: track.isLiked ? "heart.slash" : "heart"
|
|
) { Task { await toggleLike() } })
|
|
|
|
if let push {
|
|
items.append(.separator)
|
|
items.append(
|
|
RwMenuItem("Go to Artist", systemImage: "person") { push(.artist(track.user)) })
|
|
items.append(
|
|
RwMenuItem("Go to Track Page", systemImage: "music.note") { push(.track(track)) })
|
|
}
|
|
if let link = track.permalinkUrl {
|
|
items.append(
|
|
RwMenuItem("Copy Link", systemImage: "link") { copyToPasteboard(link) })
|
|
}
|
|
if let onRemoveFromPlaylist {
|
|
items.append(.separator)
|
|
items.append(
|
|
RwMenuItem("Remove from Playlist", systemImage: "minus.circle", destructive: true,
|
|
action: onRemoveFromPlaylist))
|
|
}
|
|
return items
|
|
}
|
|
|
|
// MARK: - Actions
|
|
|
|
/// Optimistic flip with revert on throw — the QueueController.toggleLike
|
|
/// pattern, scoped to this row's local copy (the controller only manages
|
|
/// the CURRENT track's like state; list rows manage their own).
|
|
private func toggleLike() async {
|
|
let nowLiked = !track.isLiked
|
|
setPendingLike(nowLiked)
|
|
do {
|
|
if nowLiked {
|
|
try await services.api.likeTrack(track.id)
|
|
} else {
|
|
try await services.api.unlikeTrack(track.id)
|
|
}
|
|
CSLog.shared.log("row", "\(nowLiked ? "liked" : "unliked") \(track.id) OK")
|
|
} catch {
|
|
CSLog.shared.log(
|
|
"row", "\(nowLiked ? "like" : "unlike") \(track.id) FAILED: \(error) — reverting")
|
|
setPendingLike(!nowLiked)
|
|
}
|
|
}
|
|
|
|
/// addTracksToPlaylist is one GET + one PUT: it re-fetches the TARGET playlist
|
|
/// fully hydrated, appends the id if it isn't already there and PUTs the
|
|
/// complete list — v1's PUT replaces a playlist's whole track list, so a
|
|
/// partially-hydrated target would otherwise be truncated to its ~5-track head.
|
|
/// Outcome goes to the log: a row has no notice surface of its own (the same
|
|
/// reason its like failures are logged rather than surfaced).
|
|
private func addToPlaylist(_ target: SCPlaylist) async {
|
|
do {
|
|
try await services.api.addTracksToPlaylist(target.id, trackIds: [track.id])
|
|
CSLog.shared.log("row", "added \(track.id) to playlist \(target.id)")
|
|
} catch {
|
|
CSLog.shared.log("row", "add to playlist failed for \(track.id): \(error)")
|
|
}
|
|
}
|
|
|
|
/// New playlist WITH the track in one call — create-then-add would leave an
|
|
/// empty playlist behind when the add failed (the Dart picker's "New" did the
|
|
/// same thing for the same reason).
|
|
private func createPlaylistWithTrack(title: String, isPublic: Bool) async {
|
|
do {
|
|
_ = try await services.api.createPlaylist(
|
|
title: title, trackIds: [track.id], isPublic: isPublic)
|
|
CSLog.shared.log("row", "created playlist \"\(title)\" with \(track.id)")
|
|
} catch {
|
|
CSLog.shared.log("row", "create-and-add failed for \(track.id): \(error)")
|
|
}
|
|
}
|
|
|
|
/// One writer for the optimistic flip: the list's shared holder when there
|
|
/// is one (so the bar's bulk Like and a row's own menu toggle can't disagree
|
|
/// about the same track), the row's own @State otherwise.
|
|
private func setPendingLike(_ liked: Bool) {
|
|
if let selection {
|
|
selection.setLikeOverride(liked, for: source.id)
|
|
return
|
|
}
|
|
likeOverrideTrackId = source.id
|
|
likeOverride = liked
|
|
}
|
|
|
|
private func copyToPasteboard(_ string: String) {
|
|
#if canImport(UIKit)
|
|
UIPasteboard.general.string = string
|
|
#elseif canImport(AppKit)
|
|
NSPasteboard.general.clearContents()
|
|
NSPasteboard.general.setString(string, forType: .string)
|
|
#endif
|
|
}
|
|
}
|