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

984 lines
37 KiB
Swift
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// DevicesView — the cross-device remote screen (port of the Flutter
// devices_screen.dart, Phase 7).
//
// Spotify-Connect–style: lists every other device signed into the same
// SoundCloud account (RemoteService's RTDB tree, namespaced by the SC uid)
// and drives their playback with transport commands. The Dart screen's
// ListView maps onto this app's Rw chrome (ServicesView's section/card/row
// grammar) with the same content top-to-bottom: this device (rename), the
// connection diagnostics panel, the sync toggle, then a card per peer with a
// now-playing line + progress, the Resume-here handoff, transport, and the
// live remote-queue sheet.
//
// Everything READS off services.remote (@Observable here — the Dart screen
// wrapped the same reads in a ListenableBuilder) and SENDS through
// sendCommand/removeDevice. Adoption ("Resume here") goes through
// RemoteAdoption.adopt (AppRoot.swift) — the shared app-layer port of Dart's
// RemoteService.adoptFrom — and deliberately BYPASSES the divergedFromSync
// gate (the spec: divergedFromSync gates auto-adopt only, never the manual
// button).
//
// MARK: The Dart screen's SnackBar ("Resuming from X…") is not ported — this
// app has no toast layer; adoption progress surfaces as the mini player
// re-pointing, and failures land in QueueController.lastError, which the
// shell's banner already watches.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct DevicesView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
@State private var showRename = false
@State private var renameText = ""
/// Diagnostics panel expansion (the Dart _Diagnostics ExpansionTile).
@State private var diagnosticsOpen = false
/// The peer whose queue sheet is up — id only, never a device snapshot: the
/// sheet re-finds the live device on every render so peer-side queue edits
/// (and this sheet's own commands, echoed back through the peer's forced
/// state publish) stream straight in, like the Dart sheet rebuilding from
/// remote.devices inside its ListenableBuilder.
@State private var queueSheetFor: RemoteQueueTarget?
/// "Sign in on Apple Watch": in flight, and what the last press did.
@State private var sendingToWatch = false
@State private var watchStatus: String?
public init() {}
@ObserveInjection var inject
public var body: some View {
let remote = services.remote
let scUid: String? = remote.scUid
ScrollView {
VStack(alignment: .leading, spacing: 0) {
header(p)
thisDeviceSection(p, remote: remote)
diagnostics(p, remote: remote)
syncSection(p, remote: remote)
#if os(iOS)
watchSection(p)
#endif
if scUid == nil {
// Dart's remote == null body: the service only starts once a
// SoundCloud session names the RTDB namespace. Diagnostics above
// stay visible — "(none)" rows are exactly what explains this.
notSignedIn(p)
} else {
otherDevicesSection(p, remote: remote)
}
}
.padding(.bottom, RwSizes.section)
}
.background(p.bg)
// The library's INPUT dialog: one .rw TextField between the message and
// the buttons, in the same square panel as a plain confirm. It dismisses
// itself before either action runs, and keeps Save (and Return) disabled
// while the name is blank — so no empty guard here, only the trim, since
// the library checks the text but hands it over untrimmed. It never
// writes renameText; the Rename button below prefills it from
// remote.myName on every open, so there is nothing to clear on Cancel
// (which a scrim tap or Escape now triggers too).
.rwDialog(
isPresented: $showRename,
title: "Name this device",
message: "Every other device sees this name.",
text: $renameText,
prompt: "e.g. Phone, Tablet, Desktop",
actions: [
RwDialogAction("Save") {
let name = renameText.trimmingCharacters(in: .whitespacesAndNewlines)
remote.setDeviceName(name)
},
.cancel(),
]
)
.sheet(item: $queueSheetFor) { target in
RemoteQueueSheet(deviceId: target.id)
.presentationDetents([.medium, .large])
.presentationDragIndicator(.visible)
}
.enableInjection()
}
// MARK: - Header
/// The family's page header (28pt title + AccentBar) — pushed screens in
/// this app carry their titles in-content (ServicesView's pattern; Flutter
/// gave this screen an RwAppBar).
private func header(_ p: RwPalette) -> some View {
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old hand-set
// 28/heavy).
Text("Devices")
.rw(.headlineLarge)
AccentBar(width: 40)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
}
// MARK: - This device
private func thisDeviceSection(_ p: RwPalette, remote: RemoteService) -> some View {
section("This Device", palette: p) {
HStack(spacing: RwSizes.gap) {
Image(systemName: Self.thisDeviceIcon)
.font(.system(size: 17))
.foregroundStyle(p.red)
.frame(width: 28)
VStack(alignment: .leading, spacing: 2) {
Text(remote.myName)
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
Text("This device")
.rw(.labelMedium, color: p.textMuted.color)
}
Spacer(minLength: RwSizes.gap)
Button {
renameText = remote.myName
showRename = true
} label: {
LitPalette { p in
HStack(spacing: 4) {
Image(systemName: "pencil")
.font(.system(size: 11, weight: .semibold))
// .rw bakes its color in, so the HStack's red below only reaches
// the glyph — the label takes it explicitly.
Text("Rename")
.rw(.labelMedium, color: p.red.color)
}
.foregroundStyle(p.red)
.padding(.horizontal, 10)
.frame(height: 28)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
}
}
/// What THIS device is, for its own row — peers see us through the platform
/// string RemoteService publishes; this icon is purely local decoration.
private static var thisDeviceIcon: String {
#if os(macOS)
"desktopcomputer"
#else
"iphone"
#endif
}
// MARK: - Diagnostics (the Dart _Diagnostics ExpansionTile)
/// Live connection diagnostics — makes silent pairing failures (denied
/// writes, failed anon sign-in, uid mismatch) visible instead of an empty
/// device list.
private func diagnostics(_ p: RwPalette, remote: RemoteService) -> some View {
let err: String? = remote.lastError
let authUid: String? = remote.authUid
let scUid: String? = remote.scUid
let connected = remote.dbConnected
let ok = connected && err == nil && authUid != nil
// RwColor now: the palette's tokens draw directly as ShapeStyles. The
// "Connecting…" state splits by token: textMuted is for secondary TEXT and
// reads gray on a glyph, so the icon takes iconInactive instead.
let headColor: RwColor = err != nil ? p.red : (ok ? p.success : p.textMuted)
let headIcon: RwColor = err != nil ? p.red : (ok ? p.success : p.iconInactive)
let headText =
err != nil
? "Connection problem — tap for details"
: (connected ? "Connected" : "Connecting…")
return VStack(alignment: .leading, spacing: 0) {
RwCard(padding: EdgeInsets()) {
VStack(spacing: 0) {
Button {
withAnimation { diagnosticsOpen.toggle() }
} label: {
HStack(spacing: RwSizes.gap) {
Image(
systemName: err != nil
? "exclamationmark.triangle" : "dot.radiowaves.left.and.right"
)
.font(.system(size: 15))
.foregroundStyle(headIcon)
.frame(width: 28)
Text(headText)
.rw(.titleSmall, color: headColor.color)
Spacer(minLength: RwSizes.gap)
Image(systemName: "chevron.down")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(p.iconInactive)
.rotationEffect(.degrees(diagnosticsOpen ? 180 : 0))
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
if diagnosticsOpen {
VStack(alignment: .leading, spacing: 4) {
diagRow(
"RTDB connected", connected ? "yes" : "no",
tint: connected ? p.success : p.red, palette: p)
diagRow(
"Auth uid (anon)", authUid ?? "(none — anon sign-in failed)",
tint: authUid == nil ? p.red : nil, palette: p)
diagRow("SC uid (namespace)", scUid ?? "(none)", palette: p)
diagRow(
"This device id",
remote.deviceId.isEmpty ? "(none)" : remote.deviceId, palette: p)
diagRow(
"Device keys seen",
remote.rawKeys.isEmpty
? "(none — read denied or empty)"
: remote.rawKeys.joined(separator: ", "),
palette: p)
if let err {
diagRow("Last error", err, tint: p.red, palette: p)
// The rules hint, verbatim from the Dart screen — the ONE
// failure users actually hit (permission-denied) has a
// non-obvious cause: the tree is namespaced by the SoundCloud
// uid while auth is anonymous, so uid-matching rules always
// deny.
Text(
"If this says permission-denied, your database rules block "
+ "writes under users/\(scUid ?? "?"). Rules must allow any "
+ "signed-in user (auth != null) here — NOT auth.uid == $uid, "
+ "because the path uses your SoundCloud id, not the anonymous "
+ "auth uid."
)
.rw(.labelMedium, color: p.textMuted.color)
.padding(.top, 6)
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
}
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
}
/// One key/value diagnostics line — 130pt key column over a selectable
/// monospaced value, matching the Dart row() metrics.
private func diagRow(
_ key: String, _ value: String, tint: RwColor? = nil, palette p: RwPalette
) -> some View {
HStack(alignment: .top, spacing: RwSizes.gap) {
Text(key)
.rw(.labelMedium, color: p.textMuted.color)
.frame(width: 130, alignment: .leading)
Text(value)
.font(.system(size: 12, design: .monospaced))
.foregroundStyle(tint ?? p.text)
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
}
// MARK: - Sync toggle
private func syncSection(_ p: RwPalette, remote: RemoteService) -> some View {
let isOn = Binding(
get: { remote.syncEnabled },
set: { remote.setSyncEnabled($0) })
return section("Sync", palette: p) {
HStack(spacing: RwSizes.gap) {
Image(systemName: "arrow.triangle.2.circlepath")
.font(.system(size: 17))
.foregroundStyle(p.red)
.frame(width: 28)
VStack(alignment: .leading, spacing: 2) {
Text("Sync playback across devices")
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
Text(
"Pick up where you left off on another device. Pressing play here "
+ "continues the most-recent session and pauses the other device."
)
.rw(.labelMedium, color: p.textMuted.color)
.multilineTextAlignment(.leading)
}
Spacer(minLength: RwSizes.gap)
// The library's flat switch — the system Toggle is glass and can't be
// restyled.
Toggle("", isOn: isOn)
.labelsHidden()
.toggleStyle(.rwSwitch)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
.contentShape(Rectangle())
// Row tap flips it too, matching the Dart SwitchListTile.
.onTapGesture { remote.setSyncEnabled(!remote.syncEnabled) }
}
}
// MARK: - Apple Watch (iOS)
#if os(iOS)
/// The watch app can't show SoundCloud's login (no web view on watchOS),
/// so this iPhone hands its own over — WatchLink.sendLoginNow. Shown only
/// with a paired watch.
@ViewBuilder
private func watchSection(_ p: RwPalette) -> some View {
let link = WatchLink.shared
if link.isPaired {
section("Apple Watch", palette: p) {
Button {
Task { await sendLoginToWatch() }
} label: {
HStack(spacing: RwSizes.gap) {
Image(systemName: "applewatch")
.font(.system(size: 17))
.foregroundStyle(p.red)
.frame(width: 28)
VStack(alignment: .leading, spacing: 2) {
Text("Sign in on Apple Watch")
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
Text(
watchStatus
?? (link.watchAppInstalled
? "Sends this iPhone's SoundCloud login to CrossSound on your watch. "
+ "After that the watch works on its own."
: "Install CrossSound on your watch from the Watch app first.")
)
.rw(.labelMedium, color: p.textMuted.color)
.multilineTextAlignment(.leading)
}
Spacer(minLength: RwSizes.gap)
if sendingToWatch {
ProgressView()
.tint(p.red.color)
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
.buttonStyle(.bareRow())
.disabled(sendingToWatch || !link.watchAppInstalled)
}
}
}
private func sendLoginToWatch() async {
sendingToWatch = true
defer { sendingToWatch = false }
watchStatus =
switch await WatchLink.shared.sendLoginNow() {
case .sent: "Sent — your watch is signing in."
case .queued: "Sent — your watch signs in the next time CrossSound opens on it."
case .noWatch: "No Apple Watch is paired with this iPhone."
case .notInstalled: "Install CrossSound on your watch from the Watch app first."
case .signedOut: "Sign in on this iPhone first."
case .unavailable: "Couldn't reach your watch. Try again in a moment."
}
}
#endif
// MARK: - Other devices
@ViewBuilder
private func otherDevicesSection(_ p: RwPalette, remote: RemoteService) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
RwSectionHeader("Other Devices")
if remote.devices.isEmpty {
emptyCard(
p, icon: "laptopcomputer.and.iphone", title: "No other devices",
body: "Open CrossSound on your computer or another phone — signed "
+ "into the same SoundCloud account — and it will appear here "
+ "automatically.")
} else {
ForEach(remote.devices) { device in
deviceCard(device, palette: p, remote: remote)
}
}
}
.padding(.horizontal, RwSizes.pagePadding)
}
private func notSignedIn(_ p: RwPalette) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
RwSectionHeader("Other Devices")
emptyCard(
p, icon: "person.crop.circle.badge.questionmark",
title: "Remote control unavailable",
body: "Sign in to SoundCloud to control your other devices.")
}
.padding(.horizontal, RwSizes.pagePadding)
}
private func emptyCard(
_ p: RwPalette, icon: String, title: String, body: String
) -> some View {
RwCard {
VStack(spacing: RwSizes.gap) {
// Inactive chrome, not text: iconInactive keeps the glyph on-brand.
Image(systemName: icon)
.font(.system(size: 40))
.foregroundStyle(p.iconInactive)
Text(title)
.rw(.bodyLarge, color: p.text.color)
.multilineTextAlignment(.center)
Text(body)
.rw(.labelMedium, color: p.textMuted.color)
.multilineTextAlignment(.center)
}
.frame(maxWidth: .infinity)
.padding(.vertical, RwSizes.gap)
}
}
// MARK: - Device card
private func deviceCard(
_ device: RemoteDevice, palette p: RwPalette, remote: RemoteService
) -> some View {
// Local optional promotions: these fields are nullable in the published
// node (Dart RemoteDevice), and the promotion keeps this file compiling
// whether the Kit models them as String or String?.
let title: String? = device.title
let artist: String? = device.artist
let artworkUrl: String? = device.artworkUrl
let hasTrack = !(title ?? "").isEmpty
let dur = device.durationMs
// Dart: pos.clamp(0, dur == 0 ? pos : dur) — never past the end, never
// negative, and a missing duration doesn't zero the position label.
let pos = max(0, dur > 0 ? min(device.positionMs, dur) : device.positionMs)
let progress = dur > 0 ? Double(pos) / Double(dur) : 0.0
return RwCard(padding: EdgeInsets()) {
VStack(alignment: .leading, spacing: 0) {
// Name + presence row.
HStack(spacing: 8) {
Image(systemName: Self.platformIcon(device.platform))
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(p.red)
.frame(width: 22)
Text(device.name)
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
.layoutPriority(1)
// Which app ("Mac app", "Desktop app"), so two apps on one machine
// read apart. Absent from apps that predate it.
if let app = device.app {
Text(app)
.rw(.labelMedium, color: p.textMuted.color)
.lineLimit(1)
}
Spacer(minLength: 8)
// Presence dot — an indicator, one of the few round shapes the
// square contract allows.
Circle()
.fill(device.online ? p.success : p.hairStrong)
.frame(width: 9, height: 9)
Text(device.online ? "Online" : "Offline")
.rw(.labelMedium, color: p.textMuted.color)
if !device.online {
// Forget an offline device — clears stale/duplicate entries from
// old rebuilds/reinstalls (the reader-side prune only fires after
// 2 days; a real device republishes itself on next launch).
Button {
Task { await remote.removeDevice(device.id) }
} label: {
Image(systemName: "xmark")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(p.iconInactive)
.padding(6)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.help("Forget this device")
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.gap)
// Now-playing line.
HStack(spacing: RwSizes.gap) {
artworkThumb(artworkUrl, palette: p, size: 52)
VStack(alignment: .leading, spacing: 2) {
Text(hasTrack ? (title ?? "") : "Nothing playing")
.rw(.titleSmall, color: hasTrack ? p.text.color : p.textMuted.color)
.lineLimit(1)
if hasTrack {
Text(artist ?? "")
.rw(.labelMedium, color: p.textMuted.color)
.lineLimit(1)
}
}
Spacer(minLength: 0)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.gap)
if hasTrack && dur > 0 {
VStack(spacing: 4) {
GeometryReader { geo in
ZStack(alignment: .leading) {
Rectangle().fill(p.bg2)
Rectangle().fill(p.red)
.frame(width: max(0.0, min(1.0, progress)) * geo.size.width)
}
}
.frame(height: 3)
HStack {
Text(Self.mmss(pos))
Spacer()
Text(Self.mmss(dur))
}
.font(.system(size: 11).monospacedDigit())
.foregroundStyle(p.textMuted)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, 8)
}
// Resume here — pick up this device's session locally (handoff). The
// Dart gate verbatim: my sync toggle AND the peer online AND the peer
// has something worth adopting.
if remote.syncEnabled && device.online && device.hasSession {
Button {
CSLog.shared.log("remote", "resume-here tapped for \(device.name)")
Task {
await RemoteAdoption.adopt(
from: device, remote: remote, queue: services.queue,
api: services.api)
}
} label: {
LitPalette { p in
HStack(spacing: 6) {
Image(systemName: "arrow.down.circle")
.font(.system(size: 14, weight: .semibold))
// Explicit red: .rw bakes bodySmall's muted color in otherwise.
Text("Resume here from \(device.name)")
.rw(.bodySmall, color: p.red.color)
.lineLimit(1)
}
.foregroundStyle(p.red)
.frame(maxWidth: .infinity)
.frame(height: 34)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.gap)
}
// Transport — enabled iff online (commands to an offline device would
// just queue up in its inbox and replay all at once on reconnect).
HStack(spacing: RwSizes.gap) {
Spacer(minLength: 0)
transportButton(
"backward.end.fill", size: 16, enabled: device.online, palette: p
) {
send(remote, device.id, "prev")
}
Button {
// Absolute play/pause picked from the peer's CURRENT state — the
// receiver's guards make a stale/replayed one harmless.
send(remote, device.id, device.isPlaying ? "pause" : "play")
} label: {
// No solid tile: buttons draw no background (BareButtons.swift).
// Offline dims to the inactive tone, like the buttons beside it.
LitPalette { p in
Image(systemName: device.isPlaying ? "pause.fill" : "play.fill")
.font(.system(size: 18, weight: .semibold))
.foregroundStyle(device.online ? p.red : p.red.withAlpha(0.4))
.frame(width: 44, height: 44)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.disabled(!device.online)
transportButton(
"forward.end.fill", size: 16, enabled: device.online, palette: p
) {
send(remote, device.id, "next")
}
// Like, beside next — only for a device that says whether its song
// is liked, which is also how it says it takes the command. The
// like happens ON THE DEVICE; its next publish moves the heart here.
if let liked = device.isLiked {
let canLike = device.online && hasTrack
Button {
send(remote, device.id, "like", device.likeArgs)
} label: {
LitPalette { p in
Image(systemName: liked ? "heart.fill" : "heart")
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(canLike ? p.red : p.red.withAlpha(0.4))
.frame(width: 40, height: 40)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow(active: liked))
.disabled(!canLike)
.help(liked ? "Unlike" : "Like")
.accessibilityLabel(liked ? "Unlike" : "Like")
}
Button {
queueSheetFor = RemoteQueueTarget(id: device.id)
} label: {
LitPalette { p in
Image(systemName: "list.bullet")
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(device.online ? p.text : p.red.withAlpha(0.4))
.frame(width: 40, height: 40)
.overlay(alignment: .topTrailing) {
if device.queueTotal > 0 {
// Primary on the page colour in a 1pt primary edge — the
// badge look (Outlined.swift), no fill.
Text("\(device.queueTotal)")
.rw(.labelSmall)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(p.bg.color)
.outlined(p.red, width: 1)
}
}
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.disabled(!device.online)
.help("Queue")
Spacer(minLength: 0)
}
.padding(.vertical, RwSizes.gap)
}
// Dart dimmed the whole card at 0.5; buttons above are also disabled,
// so this is purely visual and the Forget button stays tappable.
.opacity(device.online ? 1.0 : 0.55)
}
}
/// Dart's _platformIcon switch: 'desktop' → computer, 'ios' → iPhone,
/// 'watch' (the Apple Watch app; new here) → a watch, anything else (the
/// Flutter Android build publishes 'android') → the generic smartphone glyph.
static func platformIcon(_ platform: String) -> String {
switch platform {
case "desktop": "desktopcomputer"
case "ios": "iphone"
case "watch": "applewatch"
default: "smartphone"
}
}
private func transportButton(
_ symbol: String, size: CGFloat, enabled: Bool, palette p: RwPalette,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
LitPalette { p in
Image(systemName: symbol)
.font(.system(size: size, weight: .semibold))
.foregroundStyle(enabled ? p.text : p.red.withAlpha(0.4))
.frame(width: 40, height: 40)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.disabled(!enabled)
}
// MARK: - Section chrome (private copies of ServicesView's grammar)
private func section(
_ title: String, palette p: RwPalette, @ViewBuilder rows: () -> some View
) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
RwSectionHeader(title)
// Zero insets: the rows own their padding (the old CGFloat 0 spelled
// in the library's EdgeInsets vocabulary).
RwCard(padding: EdgeInsets()) {
VStack(spacing: 0) { rows() }
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
}
static func mmss(_ ms: Int) -> String {
let s = Int((Double(ms) / 1000).rounded())
return "\(s / 60):" + String(format: "%02d", s % 60)
}
}
// MARK: - Queue sheet
/// Sheet currency: the id alone, never a device snapshot (see queueSheetFor).
private struct RemoteQueueTarget: Identifiable {
let id: String
}
/// Live view of another device's up-next queue with jump / remove / move —
/// the Dart _RemoteQueueSheet. Renders the published (60-item-capped) queue;
/// "Showing X of Y" appears when the peer's real queue is longer.
@MainActor
struct RemoteQueueSheet: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
@Environment(\.dismiss) private var dismiss
let deviceId: String
/// Optimistic overlay: a move/remove applies HERE immediately (animated)
/// while the command round-trips device → RTDB → peer → RTDB → us. The
/// next live queue publish replaces it (onChange below). Without this the
/// row only moved after the full Firebase round-trip — the "moving list
/// items" jank.
@State private var optimistic: [RemoteQueueItem]?
@ObserveInjection var inject
var body: some View {
Group {
let remote = services.remote
let device = remote.devices.first { $0.id == deviceId }
let liveItems = device?.queue ?? []
let items = optimistic ?? liveItems
let currentIndex = device?.queueIndex ?? 0
let total = device?.queueTotal ?? 0
VStack(spacing: 0) {
HStack(spacing: RwSizes.gap) {
VStack(alignment: .leading, spacing: 2) {
Text(device.map { "\($0.name) · Queue" } ?? "Queue")
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
if total > items.count {
Text("Showing \(items.count) of \(total)")
.rw(.labelMedium, color: p.textMuted.color)
}
}
Spacer(minLength: RwSizes.gap)
if !items.isEmpty {
Button {
send(remote, "clearQueue")
} label: {
LitPalette { p in
HStack(spacing: 4) {
Image(systemName: "clear")
.font(.system(size: 11, weight: .semibold))
// Explicit red — the HStack's tint below only reaches the glyph.
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.
Button {
dismiss()
} label: {
Image(systemName: "xmark")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(p.iconInactive)
.padding(6)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.keyboardShortcut(.cancelAction)
#endif
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, RwSizes.gap)
Rectangle().fill(p.hair).frame(height: 1)
if items.isEmpty {
Text("Queue is empty")
.rw(.bodySmall, color: p.textMuted.color)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView {
LazyVStack(spacing: 0) {
// Occurrence-keyed identity (trackId + nth duplicate): positional
// identity made SwiftUI see a reorder as "same rows, shuffled
// contents" — no move animation, rows appearing to swap. Identity
// must FOLLOW the row for moves to animate; the occurrence
// ordinal keeps legitimate duplicate tracks distinct.
ForEach(Self.keyed(items)) { entry in
queueRow(
entry.item, index: entry.index, count: items.count,
isCurrent: entry.index == currentIndex, palette: p, remote: remote)
}
}
}
// Live truth replaces the optimistic overlay as soon as the peer
// republishes (or the sheet retargets).
.onChange(of: liveItems.map(\.trackId)) { optimistic = nil }
}
}
.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()
}
/// One row per queue entry, keyed by trackId + occurrence ordinal.
private struct KeyedEntry: Identifiable {
let id: String
let index: Int
let item: RemoteQueueItem
}
private static func keyed(_ items: [RemoteQueueItem]) -> [KeyedEntry] {
var seen: [String: Int] = [:]
return items.enumerated().map { i, item in
let tid = item.trackId ?? "?" // RTDB nowPlaying fields are nullable
let n = seen[tid, default: 0]
seen[tid] = n + 1
return KeyedEntry(id: "\(tid)#\(n)", index: i, item: item)
}
}
/// Optimistic move: animate locally NOW, command the peer, reconcile on its
/// next publish. Sequential taps are safe — the peer applies the commands
/// in order, so displayed indices always match what it will hold when each
/// command lands.
private func applyMove(from: Int, to: Int, remote: RemoteService) {
let current = optimistic ?? (remote.devices.first { $0.id == deviceId }?.queue ?? [])
guard current.indices.contains(from), current.indices.contains(to) else { return }
var next = current
next.insert(next.remove(at: from), at: to)
withAnimation(.snappy(duration: 0.25)) { optimistic = next }
send(remote, "reorder", ["from": from, "to": to])
}
private func applyRemove(at index: Int, remote: RemoteService) {
let current = optimistic ?? (remote.devices.first { $0.id == deviceId }?.queue ?? [])
guard current.indices.contains(index) else { return }
var next = current
next.remove(at: index)
withAnimation(.snappy(duration: 0.25)) { optimistic = next }
send(remote, "removeAt", ["index": index])
}
private func queueRow(
_ item: RemoteQueueItem, index i: Int, count: Int, isCurrent: Bool,
palette p: RwPalette, remote: RemoteService
) -> some View {
// Optional promotions, same reason as the device card's.
let title: String? = item.title
let artist: String? = item.artist
let art: String? = item.artworkUrl
return HStack(spacing: RwSizes.gap) {
artworkThumb(art, palette: p, size: 40)
VStack(alignment: .leading, spacing: 2) {
// Now-playing is carried by the BOLD role (titleSmall and bodyMedium
// are both 14pt, so the row never shifts): p.red and p.text are the
// same red, so the old color ternary was a no-op — and .rw bakes its
// font in, so a .fontWeight chained after it would not take.
Text(title ?? "")
.rw(isCurrent ? .titleSmall : .bodyMedium, color: p.text.color)
.lineLimit(1)
Text(artist ?? "")
.rw(.labelMedium, color: p.textMuted.color)
.lineLimit(1)
}
Spacer(minLength: RwSizes.gap)
rowButton("chevron.up", enabled: i > 0, palette: p) {
applyMove(from: i, to: i - 1, remote: remote)
}
rowButton("chevron.down", enabled: i < count - 1, palette: p) {
applyMove(from: i, to: i + 1, remote: remote)
}
// Can't remove the playing row — the receiver refuses index ==
// queueIndex too; the disabled button just says so up front.
rowButton("xmark", enabled: !isCurrent, palette: p) {
applyRemove(at: i, remote: remote)
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 6)
.contentShape(Rectangle())
// Row tap jumps; the buttons above win their own taps (Button beats the
// container's onTapGesture — the MiniPlayerBar convention).
.onTapGesture { send(remote, "jump", ["index": i]) }
}
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))
.foregroundStyle(enabled ? p.text : p.red.withAlpha(0.4))
.frame(width: 28, height: 28)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.disabled(!enabled)
}
private func send(
_ remote: RemoteService, _ cmd: String, _ args: [String: Any]? = nil
) {
Task { await remote.sendCommand(to: deviceId, cmd: cmd, args: args) }
}
}
// MARK: - Shared bits
/// Fire-and-forget command send — the Dart screen never awaited these either;
/// delivery is observed through the peer's next forced state publish.
@MainActor
private func send(
_ remote: RemoteService, _ deviceId: String, _ cmd: String,
_ args: [String: Any]? = nil
) {
Task { await remote.sendCommand(to: deviceId, cmd: cmd, args: args) }
}
/// Artwork thumb with the tinted-note placeholder (TrackRow's degrade path —
/// remote peers publish artworkUrl straight from tracks that may have none).
@MainActor
private func artworkThumb(_ url: String?, palette p: RwPalette, size: CGFloat)
-> some View
{
AsyncImage(url: url.flatMap(URL.init(string:))) { image in
image.resizable().scaledToFill()
} placeholder: {
ZStack {
p.bg2.color
Image(systemName: "music.note")
.font(.system(size: size * 0.35))
.foregroundStyle(p.iconInactive)
}
}
.frame(width: size, height: size)
// Square crop — scaledToFill still has to be clipped to the frame.
.clipped()
.rwBorder(.accent, width: 2)
}