Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
634 lines
26 KiB
Swift
Executable File
634 lines
26 KiB
Swift
Executable File
// SelectionMode — the one multi-select story every track list shares: a holder
|
|
// a screen owns, a bottom action bar, and the row chrome TrackRow renders.
|
|
//
|
|
// PORT PROVENANCE (and why this file is a generalization, not a transcription):
|
|
// Flutter's Selection Mode lived in exactly ONE screen —
|
|
// playlist_detail_screen.dart hand-rolled `bool _selectionMode`,
|
|
// `Set<String> _selectedIds`, `_enterSelection/_exitSelection`, `_toggleTrack`
|
|
// and a bottom bar whose ONLY action was "Add to playlist". Every other Dart
|
|
// track list (likes, history, my tracks, search, artist…) passed no
|
|
// `selectable` flag at all, so it had no checkboxes and no entry point. The
|
|
// desktop Electron app had the same shape from the other side: one `_sel` bag
|
|
// re-mounted per view (app.js `mountSelectionBar`), again with Add-to-playlist
|
|
// as its single action. This file lifts those four members out of the screen
|
|
// so ANY list can adopt selection; the bar keeps Add-to-playlist as its primary
|
|
// action and adds the bulk actions both ports were missing around it.
|
|
//
|
|
// CONTRACTS carried over deliberately:
|
|
// - IDS ONLY. The holder never stores SCTrack values; the tracks are
|
|
// resolved from the list at ACTION time (`resolve(from:)`). That is what
|
|
// lets a list replace its contents under the user's feet — the playlist
|
|
// back-fill (~5 hydrated stubs → the full list), a pull-to-refresh — and
|
|
// keep every tick. It also means a track that appears TWICE in a list
|
|
// (history repeat plays) is one selection, and `resolve` de-dupes so the
|
|
// action runs once per track rather than once per row.
|
|
// - Selection is screen-local and ephemeral: no AppServices slot, no disk,
|
|
// no UserDefaults. The holder is `@State` on the screen, so popping the
|
|
// route drops mode and ticks (the Dart lost them with the State object).
|
|
// It deliberately does NOT clear itself in `onDisappear`: on iOS a TAB
|
|
// SWITCH disappears the whole stack, and the Dart's IndexedStack kept
|
|
// selection alive across tab switches.
|
|
// - "Deselect all" / "Clear" only clears ticks; it never leaves selection
|
|
// mode. Leaving is the ✕ (or Done).
|
|
// - Every bulk action stays disabled at zero ticks.
|
|
//
|
|
// DELIBERATE DIVERGENCES from the Dart, each documented at its call site:
|
|
// - The bar keeps ADD TO PLAYLIST as its primary action — the Dart's only
|
|
// one — and adds queue / play-next / like around it. Those three do NOT
|
|
// exit selection mode: the Dart exited right after opening the picker
|
|
// because that was the whole feature, and a bar with four actions has to
|
|
// let you queue a set AND like it. Add to Playlist DOES exit,
|
|
// like `_addSelectedToPlaylist` — on the screens that take its handoff (see
|
|
// `onAddToPlaylist`, and PlaylistDetailView, which is the screen the Dart
|
|
// had); when the bar has to present the picker itself, it reports into its
|
|
// own count slot instead and leaves the ✕ as the way out, because that slot
|
|
// and the sheet both die with the bar.
|
|
// - Bulk LIKE runs with a bounded fan-out (likeBatchSize) instead of Dart's
|
|
// 8-wide pool, because every job is a separate write to the same account.
|
|
|
|
import CrossSoundKit
|
|
import Inject
|
|
import RedWhiteUI
|
|
import SwiftUI
|
|
|
|
// MARK: - The holder
|
|
|
|
/// Multi-select state for ONE list screen: which rows are ticked, whether the
|
|
/// mode is on, and the optimistic like flips bulk actions made (so every row
|
|
/// that shares this holder renders the new heart state).
|
|
///
|
|
/// A screen owns one as `@State` and hands it to its rows through the
|
|
/// environment (`.trackSelection(_:)`); `TrackRow` reads it and needs no
|
|
/// parameters. Rows on screens that never inject one see `nil` and behave
|
|
/// exactly as they did before selection existed.
|
|
@MainActor
|
|
@Observable
|
|
public final class TrackSelection {
|
|
/// Mode flag. While true a row tap toggles instead of playing.
|
|
public private(set) var isActive = false
|
|
|
|
/// The ticked track ids. Ids, never tracks — see the file header.
|
|
public private(set) var selectedIds: Set<String> = []
|
|
|
|
/// Optimistic like flips keyed by track id, written by the bar's bulk
|
|
/// Like/Unlike and by `TrackRow`'s own menu toggle whenever a holder exists.
|
|
/// They live on the HOLDER rather than in each row so one bulk Like paints
|
|
/// every row it touched; they outlive selection mode (the holder is the
|
|
/// screen's @State) and die with the screen, like the rows' own overrides did.
|
|
private var likeOverrides: [String: Bool] = [:]
|
|
|
|
public init() {}
|
|
|
|
public var count: Int { selectedIds.count }
|
|
|
|
/// Enter selection mode, optionally ticking the row that asked for it (the
|
|
/// row's own "Select" menu item — entering with nothing ticked would make
|
|
/// the long-press feel like it did nothing).
|
|
public func begin(selecting id: String? = nil) {
|
|
isActive = true
|
|
if let id { selectedIds.insert(id) }
|
|
}
|
|
|
|
/// Leave selection mode AND drop the ticks (the Dart `_exitSelection`).
|
|
public func end() {
|
|
isActive = false
|
|
selectedIds.removeAll()
|
|
}
|
|
|
|
/// Drop the ticks, STAY in selection mode (the Dart "Deselect all").
|
|
public func clear() {
|
|
selectedIds.removeAll()
|
|
}
|
|
|
|
public func toggle(_ id: String) {
|
|
if selectedIds.contains(id) {
|
|
selectedIds.remove(id)
|
|
} else {
|
|
selectedIds.insert(id)
|
|
}
|
|
}
|
|
|
|
public func isSelected(_ id: String) -> Bool { selectedIds.contains(id) }
|
|
|
|
public func selectAll(in tracks: [SCTrack]) {
|
|
selectedIds.formUnion(tracks.lazy.map(\.id))
|
|
}
|
|
|
|
/// Every id in `tracks` is ticked. NOT the Dart's
|
|
/// `_selectedIds.length >= _tracks.length`: a list with the same track twice
|
|
/// (history) can never reach that count, so the Dart test would have left
|
|
/// "Select all" permanently offering itself.
|
|
public func allSelected(in tracks: [SCTrack]) -> Bool {
|
|
guard !tracks.isEmpty else { return false }
|
|
return tracks.allSatisfy { selectedIds.contains($0.id) }
|
|
}
|
|
|
|
/// The selected tracks, in LIST order, one entry per track. Order matters
|
|
/// (it becomes queue order); the de-dupe matters because a list may render
|
|
/// the same id twice and an action must not run twice on it.
|
|
public func resolve(from tracks: [SCTrack]) -> [SCTrack] {
|
|
var seen = Set<String>()
|
|
return tracks.filter { selectedIds.contains($0.id) && seen.insert($0.id).inserted }
|
|
}
|
|
|
|
// MARK: Like overrides
|
|
|
|
/// `track.isLiked` with this holder's pending flip applied.
|
|
public func liked(_ track: SCTrack) -> Bool { likeOverrides[track.id] ?? track.isLiked }
|
|
|
|
public func likeOverride(for id: String) -> Bool? { likeOverrides[id] }
|
|
|
|
public func setLikeOverride(_ liked: Bool, for id: String) { likeOverrides[id] = liked }
|
|
|
|
/// Revert to whatever the list's own value says (used when the API throws).
|
|
public func clearLikeOverride(for id: String) { likeOverrides.removeValue(forKey: id) }
|
|
}
|
|
|
|
// MARK: - Environment plumbing
|
|
|
|
extension EnvironmentValues {
|
|
/// The enclosing list's selection holder, or nil on lists that don't offer
|
|
/// selection. Optional on purpose: it keeps every selection branch in
|
|
/// `TrackRow` a `guard`, so an un-adopted screen is untouched.
|
|
@Entry public var trackSelection: TrackSelection? = nil
|
|
}
|
|
|
|
extension View {
|
|
/// Hand this subtree's rows a selection holder.
|
|
public func trackSelection(_ selection: TrackSelection?) -> some View {
|
|
environment(\.trackSelection, selection)
|
|
}
|
|
}
|
|
|
|
// MARK: - Row chrome
|
|
|
|
/// The leading tick a selectable row grows. A filled accent circle when
|
|
/// ticked, an empty pastel ring when not — the row never RESERVES this gutter
|
|
/// while selection is off, exactly like the Dart tile only adding its
|
|
/// Checkbox to the leading Row in selectable mode. The unticked ring wears
|
|
/// `iconInactive`, the library's token for unselected ICON chrome (textMuted
|
|
/// is for secondary text and reads gray on a glyph).
|
|
public struct SelectionCheckmark: View {
|
|
@Environment(\.rw) private var p
|
|
private let selected: Bool
|
|
|
|
public init(selected: Bool) {
|
|
self.selected = selected
|
|
}
|
|
|
|
@ObserveInjection var inject
|
|
|
|
public var body: some View {
|
|
Image(systemName: selected ? "checkmark.circle.fill" : "circle")
|
|
.font(.system(size: 20, weight: selected ? .semibold : .regular))
|
|
.foregroundStyle(selected ? p.red : p.iconInactive)
|
|
.frame(width: 24, height: 24)
|
|
// The row itself carries the .isSelected trait; the glyph would only
|
|
// read out a second time.
|
|
.accessibilityHidden(true)
|
|
.enableInjection()
|
|
}
|
|
}
|
|
|
|
extension View {
|
|
/// A context menu that DISAPPEARS while selecting. It has to be the
|
|
/// modifier that goes away, not just its items: a `.contextMenu` whose
|
|
/// builder produces nothing still opens an empty blurred sheet on iOS.
|
|
@ViewBuilder
|
|
public func rwContextMenuUnlessSelecting(
|
|
_ selecting: Bool, items: [RwMenuItem]
|
|
) -> some View {
|
|
if selecting {
|
|
self
|
|
} else {
|
|
// rwContextMenu, not .contextMenu: the system menu is rendered out of
|
|
// process as translucent glass on iOS 26+ and cannot be styled.
|
|
rwContextMenu(items)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Entry point
|
|
|
|
/// The "Select tracks" affordance a list screen puts in its page header — the
|
|
/// Dart's app-bar `RwAction(icon: Icons.checklist, label: 'Select tracks')`.
|
|
/// These screens draw their own headers and have no system navigation bar, so
|
|
/// there is no toolbar slot to land in (the same reason ShellHeaderControls is
|
|
/// a header row). Rows offer the second entry point through their menu.
|
|
public struct SelectionEnterButton: View {
|
|
@Environment(\.rw) private var p
|
|
private let selection: TrackSelection
|
|
|
|
public init(selection: TrackSelection) {
|
|
self.selection = selection
|
|
}
|
|
|
|
@ObserveInjection var inject
|
|
|
|
public var body: some View {
|
|
Button {
|
|
selection.begin()
|
|
} label: {
|
|
Image(systemName: "checklist")
|
|
.font(.system(size: 15, weight: .semibold))
|
|
}
|
|
// rwIcon: the library's square icon button, same chrome as the sibling
|
|
// refresh button in LikesView's header.
|
|
.buttonStyle(.bareIcon())
|
|
.accessibilityLabel("Select tracks")
|
|
.help("Select tracks")
|
|
.enableInjection()
|
|
}
|
|
}
|
|
|
|
// MARK: - Action bar
|
|
|
|
/// The bottom bar while selecting: ✕, the count, and the bulk actions.
|
|
///
|
|
/// Hosted with `.safeAreaInset(edge: .bottom)` by the screen, NOT by swapping
|
|
/// the transport out the way the Dart swapped `bottomNavigationBar` — AppShell
|
|
/// owns MiniPlayerBar through its own bottom inset, so a nested inset stacks
|
|
/// the bar ABOVE the transport instead of deleting it (the spec's warning for
|
|
/// any screen that shows a player bar).
|
|
///
|
|
/// Layout: icon buttons plus one overflow menu, never a `Row` of labelled
|
|
/// buttons. Five bulk actions with text labels overflow an iPhone at 320pt —
|
|
/// the spec's own note about the Dart bar's `Row` + `Spacer`. Add to Playlist
|
|
/// is still the primary action by position, but no longer wears a fill:
|
|
/// buttons draw no background (BareButtons.swift).
|
|
@MainActor
|
|
public struct SelectionActionBar: View {
|
|
@Environment(\.rw) private var p
|
|
@Environment(AppServices.self) private var services
|
|
|
|
private let selection: TrackSelection
|
|
/// The list the ticks are resolved against — always the screen's CURRENT
|
|
/// list, so a refresh that lands mid-selection acts on fresh values.
|
|
private let tracks: [SCTrack]
|
|
/// For lists that are only PARTIALLY loaded when the user can already touch
|
|
/// them — SoundCloud v2 hydrates ~5 tracks of a playlist and ships the rest
|
|
/// as stubs. A screen with a back-fill passes its `ensureFullyLoaded()`
|
|
/// here; "Select all" and every bulk action then await it and use its RETURN
|
|
/// VALUE, never the captured head. Nil (the default) means `tracks` is
|
|
/// already the whole list, which is true of every page-at-a-time screen
|
|
/// (Likes, My Tracks, History).
|
|
private let ensureLoaded: (() async -> [SCTrack])?
|
|
/// A host that owns a playlist-picker ROUTE of its own takes the Add-to-
|
|
/// Playlist handoff instead of the bar, and that is the only way to reproduce
|
|
/// the Dart's ordering literally (`showPlaylistPickerFor(...)` then
|
|
/// `_exitSelection()` on the very next line, neither awaited): the bar's own
|
|
/// `.sheet` — and its notice line — are torn down the instant `isActive`
|
|
/// flips false, so a bar that both presented the picker and left selection
|
|
/// would dismiss the sheet it just opened. Hosts pass this and call
|
|
/// `selection.end()` themselves; screens that don't (the default) get the
|
|
/// bar's self-presented picker, which reports the write into the count slot
|
|
/// and leaves the ✕ as the way out, like the bar's other three actions.
|
|
private let onAddToPlaylist: (([SCTrack]) -> Void)?
|
|
|
|
/// Transient result line, shown in place of the count (the Dart snackbars).
|
|
@State private var notice: String?
|
|
/// Sticky notices survive until the next flash.
|
|
@State private var noticeToken = 0
|
|
/// A bulk action is running: actions grey out so a second tap can't double
|
|
/// queue/like the same set.
|
|
@State private var busy = false
|
|
/// The set the self-presented picker was opened with. Held here rather than
|
|
/// re-resolved in the sheet: the ticks are cleared while the sheet is up on
|
|
/// some paths, and the picker must write what the user actually chose.
|
|
@State private var picker: PickerRequest?
|
|
|
|
/// How many bulk LIKES run at once. Dart's own pool was 8 wide; a narrower
|
|
/// window here because every job is a write to the same account and a
|
|
/// 100-track Likes list would otherwise open 100 sockets and starve the one
|
|
/// that is playing.
|
|
private static let likeBatchSize = 4
|
|
|
|
/// `.sheet(item:)` needs an Identifiable; a fresh id per request also means
|
|
/// re-opening the picker on the same set presents again.
|
|
private struct PickerRequest: Identifiable {
|
|
let id = UUID()
|
|
let tracks: [SCTrack]
|
|
}
|
|
|
|
public init(
|
|
selection: TrackSelection, tracks: [SCTrack],
|
|
ensureLoaded: (() async -> [SCTrack])? = nil,
|
|
onAddToPlaylist: (([SCTrack]) -> Void)? = nil
|
|
) {
|
|
self.selection = selection
|
|
self.tracks = tracks
|
|
self.ensureLoaded = ensureLoaded
|
|
self.onAddToPlaylist = onAddToPlaylist
|
|
}
|
|
|
|
@ObserveInjection var inject
|
|
|
|
public var body: some View {
|
|
// DISPLAY state only: what is enabled, and whether the heart offers Like
|
|
// or Unlike. The ACTIONS re-resolve against ensureLoaded()'s return value,
|
|
// so a partially-hydrated list can never act on its stub head.
|
|
let chosen = selection.resolve(from: tracks)
|
|
let ready = !chosen.isEmpty && !busy
|
|
// "Like" while ANY ticked track is unliked, else "Unlike" — the spec's
|
|
// recommended force-on/force-off, which is predictable on a mixed set in
|
|
// a way a per-track toggle is not.
|
|
let liking = chosen.contains { !selection.liked($0) }
|
|
|
|
VStack(spacing: 0) {
|
|
Rectangle()
|
|
.fill(p.hair)
|
|
.frame(height: 1)
|
|
HStack(spacing: 2) {
|
|
iconButton("xmark", label: "Cancel") { selection.end() }
|
|
|
|
Text(notice ?? "\(selection.count) selected")
|
|
// The color rides INSIDE .rw(): the role bakes its own color in, so
|
|
// a .foregroundStyle chained after it would be ignored.
|
|
.rw(.bodySmall, color: notice == nil ? p.text.color : p.red.color)
|
|
.lineLimit(1)
|
|
.minimumScaleFactor(0.7)
|
|
|
|
Spacer(minLength: 4)
|
|
|
|
// FIRST and filled: the Dart bar's one and only action.
|
|
iconButton(
|
|
"text.badge.plus", label: "Add to Playlist", enabled: ready
|
|
) {
|
|
Task { await openAddToPlaylist() }
|
|
}
|
|
iconButton("text.append", label: "Add to Queue", enabled: ready) {
|
|
Task { await addToQueue() }
|
|
}
|
|
iconButton(
|
|
"text.line.first.and.arrowtriangle.forward", label: "Play Next", enabled: ready
|
|
) {
|
|
Task { await playNext() }
|
|
}
|
|
iconButton(
|
|
liking ? "heart" : "heart.slash", label: liking ? "Like" : "Unlike", enabled: ready
|
|
) {
|
|
Task { await setLiked(liking) }
|
|
}
|
|
overflowMenu(chosen)
|
|
}
|
|
.padding(.horizontal, RwSizes.gap)
|
|
.padding(.vertical, 6)
|
|
}
|
|
.background(p.bgSoft)
|
|
// Only reached when no host took the handoff (see onAddToPlaylist): the
|
|
// sheet lives on the bar, so the bar must outlive it.
|
|
.sheet(item: $picker) { request in
|
|
// The SAME picker the row menus and PlaylistDetailView open — it never
|
|
// writes, it hands the decision back (see its header for why).
|
|
AddToPlaylistSheet(
|
|
trackCount: request.tracks.count,
|
|
onPick: { target in Task { await add(request.tracks, to: target) } },
|
|
onCreate: { newTitle, isPublic in
|
|
Task { await createAndAdd(request.tracks, title: newTitle, isPublic: isPublic) }
|
|
})
|
|
}
|
|
.enableInjection()
|
|
}
|
|
|
|
// MARK: - Chrome
|
|
|
|
private func iconButton(
|
|
_ systemName: String, label: String, enabled: Bool = true,
|
|
action: @escaping () -> Void
|
|
) -> some View {
|
|
Button(action: action) {
|
|
// A strip of bare glyphs: no fill on any of them (BareButtons.swift),
|
|
// and the style supplies the colour, the hover rule and the disabled
|
|
// dim.
|
|
Image(systemName: systemName)
|
|
.font(.system(size: 15, weight: .semibold))
|
|
.frame(width: 36, height: 36)
|
|
.contentShape(Rectangle())
|
|
}
|
|
.buttonStyle(.bareRow())
|
|
.disabled(!enabled)
|
|
.accessibilityLabel(label)
|
|
.help(label)
|
|
}
|
|
|
|
/// Select all / Clear / Done. The all-vs-none button flips its own label,
|
|
/// like the Dart's single `Icons.select_all` ↔ `Icons.deselect` action.
|
|
private func overflowMenu(_ chosen: [SCTrack]) -> some View {
|
|
let all = selection.allSelected(in: tracks)
|
|
// RwMenu, not Menu: the system menu is out-of-process glass on iOS 26+.
|
|
// RwMenuItem disables a row by having no action, which is how the
|
|
// empty-selection / busy states are expressed here.
|
|
return RwMenu(
|
|
[
|
|
RwMenuItem(
|
|
all ? "Deselect All" : "Select All",
|
|
systemImage: all ? "circle.dashed" : "checklist",
|
|
action: tracks.isEmpty || busy
|
|
? nil
|
|
: {
|
|
// Select-all is the one action that must see the WHOLE list
|
|
// before it runs, so it goes through the hydration gate too.
|
|
if all { selection.clear() } else { Task { await selectAll() } }
|
|
}),
|
|
RwMenuItem(
|
|
"Clear Selection", systemImage: "xmark.circle",
|
|
action: chosen.isEmpty || busy ? nil : { selection.clear() }),
|
|
.separator,
|
|
RwMenuItem("Done", systemImage: "checkmark") { selection.end() },
|
|
]
|
|
) {
|
|
Image(systemName: "ellipsis")
|
|
.font(.system(size: 15, weight: .semibold))
|
|
}
|
|
.accessibilityLabel("More selection actions")
|
|
}
|
|
|
|
// MARK: - Bulk actions
|
|
//
|
|
// Every one of them starts by re-resolving the ticks against `selected()`,
|
|
// never against the `chosen` array body computed for display — that is the
|
|
// hydration rule (use the RETURN VALUE, not a captured list).
|
|
// Only Add to Playlist leaves selection mode (the Dart's one action did);
|
|
// see the file header's divergence note for why the other three don't.
|
|
|
|
/// The ticked tracks, resolved against the fully-loaded list.
|
|
private func selected() async -> [SCTrack] {
|
|
guard let ensureLoaded else { return selection.resolve(from: tracks) }
|
|
return selection.resolve(from: await ensureLoaded())
|
|
}
|
|
|
|
private func selectAll() async {
|
|
guard let ensureLoaded else {
|
|
selection.selectAll(in: tracks)
|
|
return
|
|
}
|
|
selection.selectAll(in: await ensureLoaded())
|
|
}
|
|
|
|
// MARK: Add to Playlist (the Dart bar's one action)
|
|
|
|
/// `_addSelectedToPlaylist`: resolve the ticks (through the hydration gate, so
|
|
/// a partially-loaded playlist can't ship its stub head), then hand the set to
|
|
/// the picker. The Dart awaited NEITHER the picker nor the PUT before calling
|
|
/// `_exitSelection()`, and a host that takes the handoff keeps that exactly —
|
|
/// the bar's own presentation cannot, because the sheet and the notice line
|
|
/// both hang off the bar (see `onAddToPlaylist`).
|
|
private func openAddToPlaylist() async {
|
|
let chosen = await selected()
|
|
guard !chosen.isEmpty else { return }
|
|
if let onAddToPlaylist {
|
|
onAddToPlaylist(chosen)
|
|
return
|
|
}
|
|
picker = PickerRequest(tracks: chosen)
|
|
}
|
|
|
|
/// addTracksToPlaylist is one GET + one PUT: it re-fetches the TARGET playlist
|
|
/// fully hydrated, appends the ids that aren't already there and PUTs the
|
|
/// complete list, so a partially-hydrated target can't be truncated.
|
|
private func add(_ chosen: [SCTrack], to target: SCPlaylist) async {
|
|
do {
|
|
try await services.api.addTracksToPlaylist(target.id, trackIds: chosen.map(\.id))
|
|
flash(
|
|
chosen.count == 1
|
|
? "Added to \(target.title)" : "Added \(chosen.count) tracks to \(target.title)")
|
|
CSLog.shared.log("selection", "added \(chosen.count) tracks to \(target.id)")
|
|
} catch {
|
|
CSLog.shared.log("selection", "add to playlist failed: \(error.localizedDescription)")
|
|
// Either way the bar stays: on failure the ticks are the retry, and on
|
|
// success the count slot is the only place the outcome can be read.
|
|
flash("Failed to add tracks")
|
|
}
|
|
}
|
|
|
|
/// New playlist WITH the tracks 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 createAndAdd(_ chosen: [SCTrack], title: String, isPublic: Bool) async {
|
|
do {
|
|
_ = try await services.api.createPlaylist(
|
|
title: title, trackIds: chosen.map(\.id), isPublic: isPublic)
|
|
flash(countPhrase(chosen.count, "to \"\(title)\"", verb: "Added"))
|
|
CSLog.shared.log("selection", "created \"\(title)\" with \(chosen.count) tracks")
|
|
} catch {
|
|
CSLog.shared.log("selection", "create-and-add failed: \(error.localizedDescription)")
|
|
flash("Failed to create playlist")
|
|
}
|
|
}
|
|
|
|
private func addToQueue() async {
|
|
let chosen = await selected()
|
|
guard !chosen.isEmpty else { return }
|
|
// addTracksToQueue starts playback itself when nothing is loaded, so this
|
|
// is also the "play these" path on a cold queue.
|
|
await services.queue.addTracksToQueue(chosen)
|
|
flash(countPhrase(chosen.count, "to queue", verb: "Added"))
|
|
}
|
|
|
|
private func playNext() async {
|
|
let chosen = await selected()
|
|
guard !chosen.isEmpty else { return }
|
|
// Nothing loaded ⇒ there is no "next" to insert before; hand the set to
|
|
// addTracksToQueue, which starts it. (The Dart's single-track addToNextUp
|
|
// silently filled a queue nobody was playing.)
|
|
guard services.queue.currentTrack != nil else {
|
|
await addToQueue()
|
|
return
|
|
}
|
|
// QueueController only has the single-track addToNextUp (insert at
|
|
// queueIndex + 1), so the set is inserted in REVERSE: every insert lands
|
|
// in the same slot, and last-first leaves the selection in LIST order
|
|
// right after the current track. (A real addTracksToNextUp on the
|
|
// controller is the integrator's call — it owns that file.)
|
|
for track in chosen.reversed() {
|
|
services.queue.addToNextUp(track)
|
|
}
|
|
flash(countPhrase(chosen.count, "to Next Up", verb: "Added"))
|
|
}
|
|
|
|
/// Force-on / force-off (never per-track toggle), optimistic with per-track
|
|
/// revert — the family's like pattern, widened to a set. The flips go into
|
|
/// the HOLDER so every ticked row repaints its heart; the rows' own
|
|
/// `likeOverride` never sees them.
|
|
private func setLiked(_ liked: Bool) async {
|
|
let targets = await selected().filter { selection.liked($0) != liked }
|
|
guard !targets.isEmpty else {
|
|
flash(liked ? "Already liked" : "None of these are liked")
|
|
return
|
|
}
|
|
busy = true
|
|
for track in targets {
|
|
selection.setLikeOverride(liked, for: track.id)
|
|
}
|
|
// Hoisted out of the child tasks: SoundCloudAPI is an actor (Sendable),
|
|
// AppServices is not.
|
|
let api = services.api
|
|
var failed = 0
|
|
for batch in Self.batches(targets, of: Self.likeBatchSize) {
|
|
var jobs: [Task<(String, Bool), Never>] = []
|
|
for track in batch {
|
|
let id = track.id
|
|
jobs.append(
|
|
Task {
|
|
do {
|
|
if liked {
|
|
try await api.likeTrack(id)
|
|
} else {
|
|
try await api.unlikeTrack(id)
|
|
}
|
|
return (id, true)
|
|
} catch {
|
|
return (id, false)
|
|
}
|
|
})
|
|
}
|
|
for job in jobs {
|
|
let (id, ok) = await job.value
|
|
if !ok {
|
|
// Back to whatever the list says, so a failed row doesn't lie.
|
|
selection.clearLikeOverride(for: id)
|
|
failed += 1
|
|
}
|
|
}
|
|
}
|
|
busy = false
|
|
let verb = liked ? "Liked" : "Unliked"
|
|
let ok = targets.count - failed
|
|
flash(failed == 0 ? countPhrase(ok, verb: verb) : "\(verb) \(ok) of \(targets.count) tracks")
|
|
CSLog.shared.log("selection", "bulk \(verb.lowercased()): \(ok)/\(targets.count)")
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
/// "Added 12 tracks to queue" / "Added 1 track to queue".
|
|
private func countPhrase(_ n: Int, _ tail: String = "", verb: String) -> String {
|
|
let noun = n == 1 ? "1 track" : "\(n) tracks"
|
|
return tail.isEmpty ? "\(verb) \(noun)" : "\(verb) \(noun) \(tail)"
|
|
}
|
|
|
|
/// Fixed-size slices rather than a sliding window: the difference is a few
|
|
/// idle sockets at the tail of a batch, and this version is obviously
|
|
/// correct at a glance.
|
|
private static func batches(_ tracks: [SCTrack], of size: Int) -> [[SCTrack]] {
|
|
guard size > 0, tracks.count > size else { return tracks.isEmpty ? [] : [tracks] }
|
|
return stride(from: 0, to: tracks.count, by: size).map {
|
|
Array(tracks[$0..<min($0 + size, tracks.count)])
|
|
}
|
|
}
|
|
|
|
/// The Dart snackbars, re-rendered in the bar's own count slot — these
|
|
/// screens have no notice overlay, and a bar that already owns a line of
|
|
/// text doesn't need one. `sticky` holds until the next flash.
|
|
private func flash(_ message: String, sticky: Bool = false) {
|
|
notice = message
|
|
noticeToken += 1
|
|
guard !sticky else { return }
|
|
let token = noticeToken
|
|
Task {
|
|
try? await Task.sleep(for: .seconds(2))
|
|
// Only the flash that armed this timer may clear the line.
|
|
if noticeToken == token { notice = nil }
|
|
}
|
|
}
|
|
}
|