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

373 lines
14 KiB
Swift
Executable File

// ProfileView — the Profile tab root: the signed-in user's header plus the
// library hub (Phase 3 port of profile_screen.dart).
//
// The Flutter profile was a NestedScrollView with TEN swipeable tabs
// (Popular, Tracks, Reposts, Albums, Playlists, Spotlight, Likes, Following,
// Who to Follow, History) under a pinned header. Re-rendered natively, that
// strip becomes a hub: the same header on top, and each sub-page a ROW that
// pushes an AppDestination value through the shell's single
// navigationDestination switch — pushed screens with real back navigation are
// the platform idiom where Flutter used a TabBarView, and each destination
// screen owns its own loading exactly like the Dart tabs self-loaded.
//
// What maps where (vs. the Dart tab strip):
// - Likes / Following / History → .likes / .following / .history.
// - Popular + Tracks + Spotlight (all views over the user's own uploads)
// → the one .myTracks page.
// - Who to Follow → folded into .following (suggested users live with the
// followed users, per the FollowingView writer's contract).
// - Tools that Flutter kept in the app drawer (radio tuner, debug console,
// services/settings) → .radioTuner / .console / .services, with the
// settings-ish entries all routing to .services.
// - Reposts + Albums → .myReposts / .myAlbums. These were parked "Soon" rows
// until those screens landed; every row in this hub is a live push now, so
// the local soonRow helper is gone (ServicesView still owns that
// convention for the one feature genuinely parked there).
// MARK: The Playlists tab is not linked — the shell's Playlists TAB covers
// the user's own playlist listing.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct ProfileView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
private enum Phase {
case loading
case failed(String)
case loaded(SCUser)
}
@State private var phase: Phase = .loading
/// The Sign Out row's "are you sure?".
@State private var confirmSignOut = false
public init() {}
@ObserveInjection var inject
public var body: some View {
Group {
switch phase {
case .loading:
LoadingView()
case .failed(let message):
ErrorStateView(message: message) {
Task { await load() }
}
case .loaded(let user):
content(user, palette: p)
}
}
.background(p.bg)
// The library dialog (an overlay, hence attached at the screen root)
// dismisses itself before the action runs.
.rwDialog(
isPresented: $confirmSignOut,
title: "Sign out of SoundCloud?",
message: "Playback stops and the sign-in screen appears. Your Apple Watch signs out too.",
actions: [
.cancel(),
.destructive("Sign Out") { Task { await services.signOut() } },
])
.task { await load() }
.enableInjection()
}
// MARK: - Load
/// getMe(), the Dart `_loadFreshUser`. The .task re-runs on every tab
/// re-entry (iOS TabView keeps the view but cancels/restarts tasks), so a
/// loaded header is kept over both the spinner AND a transient failure —
/// stats silently refresh when the refetch succeeds, exactly like the Dart
/// screen falling back to the cached currentUser.
private func load() async {
if case .loaded = phase {
// keep the header visible; refresh in place below
} else {
phase = .loading
}
do {
let me = try await services.api.getMe()
CSLog.shared.log("profile", "loaded profile for \(me.username)")
phase = .loaded(me)
services.currentUser = me // refresh the shell avatar's source too
} catch {
CSLog.shared.log("profile", "getMe failed: \(error.localizedDescription)")
if case .loaded = phase { return }
phase = .failed(error.localizedDescription)
}
}
// MARK: - Loaded content
private func content(_ user: SCUser, palette p: RwPalette) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
// Page title — the family's tab-root header (28pt heavy + AccentBar),
// same as LikesView.
HStack(alignment: .top, spacing: RwSizes.gap) {
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old
// hand-set 28/heavy).
Text("Profile")
.rw(.headlineLarge)
AccentBar(width: 40)
}
Spacer(minLength: RwSizes.gap)
ShellHeaderControls{await load()}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
header(user, palette: p)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
section("Library", palette: p) {
ProfileRow(
icon: "heart", title: "Likes",
subtitle: "Liked tracks and playlists", destination: .likes)
hairline(p)
ProfileRow(
icon: "antenna.radiowaves.left.and.right", title: "Stations",
subtitle: "Stations you've liked", destination: .stations)
hairline(p)
ProfileRow(
icon: "person.2", title: "Following",
subtitle: "Artists you follow", destination: .following)
hairline(p)
ProfileRow(
icon: "clock.arrow.circlepath", title: "History",
subtitle: "Recently played", destination: .history)
hairline(p)
ProfileRow(
icon: "music.note", title: "My Tracks",
subtitle: "Your uploads", destination: .myTracks)
hairline(p)
ProfileRow(
icon: "arrow.2.squarepath", title: "Reposts",
subtitle: "Tracks you've reposted", destination: .myReposts)
hairline(p)
ProfileRow(
icon: "square.stack", title: "Albums",
subtitle: "Your album releases", destination: .myAlbums)
}
section("Tools", palette: p) {
ProfileRow(
icon: "dot.radiowaves.left.and.right", title: "Radio Tuner",
subtitle: "Start a station from a seed", destination: .radioTuner)
hairline(p)
ProfileRow(
icon: "terminal", title: "Console",
subtitle: "Diagnostic log", destination: .console)
hairline(p)
ProfileRow(
icon: "gearshape", title: "Services & Settings",
subtitle: "Connections and app settings", destination: .services)
}
section("Account", palette: p) {
signOutRow(p)
}
// Selection Mode (multi-select) lives on the pushed list screens that
// actually hold track rows (Likes, My Tracks, History — see
// Components/SelectionMode.swift); this hub has no track rows, so
// there is nothing here to select.
}
.padding(.bottom, RwSizes.section)
}
}
// MARK: - Header (avatar + name + stats, the Dart _buildHeader)
private func header(_ user: SCUser, palette p: RwPalette) -> some View {
RwCard {
VStack(spacing: 10) {
avatar(user, palette: p)
Text(user.username)
.rw(.titleLarge, color: p.text.color)
.lineLimit(1)
// Followers | Following | Tracks with hair dividers — the Dart stat
// row. Missing counts render as 0, matching the Dart `?? 0`.
HStack(spacing: 0) {
stat(compactCount(user.followersCount ?? 0), "Followers", palette: p)
statDivider(p)
stat(compactCount(user.followingsCount ?? 0), "Following", palette: p)
statDivider(p)
stat(compactCount(user.trackCount ?? 0), "Tracks", palette: p)
}
}
.frame(maxWidth: .infinity)
}
}
private func avatar(_ user: SCUser, palette p: RwPalette) -> some View {
// The stored avatarUrl is already t500x500 (decode rewrote it) — plenty
// for the 84pt circle, so no size rewrite here.
AsyncImage(url: user.avatarUrl.flatMap(URL.init(string:))) { image in
image.resizable().scaledToFill()
} placeholder: {
ZStack {
p.bg2.color
// A placeholder glyph is icon chrome → iconInactive (textMuted reads
// gray on glyphs; the text* tokens are for text).
Image(systemName: "person.fill")
.font(.system(size: 36))
.foregroundStyle(p.iconInactive)
}
}
.frame(width: 84, height: 84)
.clipShape(Circle())
// Ring in the main brand color, so it follows the theme changer.
.overlay(Circle().strokeBorder(p.red, lineWidth: 2))
}
private func stat(_ value: String, _ label: String, palette p: RwPalette) -> some View {
VStack(spacing: 2) {
Text(value)
.font(.system(size: 15, weight: .bold).monospacedDigit())
.foregroundStyle(p.text)
Text(label)
.rw(.labelMedium, color: p.textMuted.color)
}
.frame(maxWidth: .infinity)
}
private func statDivider(_ p: RwPalette) -> some View {
Rectangle()
.fill(p.hair)
.frame(width: 1, height: 28)
}
/// Dart _fmt: 1_234_567 → "1.2M", 12_400 → "12.4K", 999 → "999".
private func compactCount(_ n: Int) -> String {
if n >= 1_000_000 { return String(format: "%.1fM", Double(n) / 1_000_000) }
if n >= 1000 { return String(format: "%.1fK", Double(n) / 1000) }
return "\(n)"
}
// MARK: - Sections
/// A titled RwCard of rows — the hub's grouping unit. Rows butt together
/// with hairlines between them (the list's job, per the row components'
/// convention), inside the family's hair-bordered card.
private func section<Rows: View>(
_ title: String, palette p: RwPalette, @ViewBuilder rows: () -> Rows
) -> 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)
}
private func hairline(_ p: RwPalette) -> some View {
Rectangle()
.fill(p.hair)
.frame(height: 1)
.padding(.leading, RwSizes.gap + 32 + RwSizes.gap) // align past the icon tile
}
// The local `soonRow` helper is deliberately GONE: Reposts and Albums were
// its only two callers and both are live ProfileRow pushes now, so it was
// dead code. ServicesView keeps its own copy — that hub still has one
// genuinely parked feature (Meta Glasses).
// MARK: - Sign-out
/// Asks first, then AppServices.signOut(): credentials cleared, playback
/// stopped, queue emptied, this device off the device list, and AppRoot
/// back on its signed-out screen — the hook this row sat disabled waiting
/// for. The same action as Services → Log out.
private func signOutRow(_ p: RwPalette) -> some View {
Button {
confirmSignOut = true
} label: {
HStack(spacing: RwSizes.gap) {
// A bare glyph, no tile: buttons draw no background (BareButtons.swift),
// and the style colours it.
Image(systemName: "rectangle.portrait.and.arrow.right")
.font(.system(size: 14, weight: .semibold))
.frame(width: 32, height: 32)
Text("Sign Out")
.rw(.bodyLarge)
Spacer(minLength: RwSizes.gap)
}
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
.buttonStyle(.bareRow())
}
}
// MARK: - Row
/// One hub row: icon tile, title/subtitle, chevron — a value-based
/// NavigationLink so the push routes through AppShell's single destination
/// switch like every other link in the app.
private struct ProfileRow: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
let icon: String
let title: String
/// Defaulted so a row without one reads `ProfileRow(icon:title:destination:)`.
var subtitle: String? = nil
let destination: AppDestination
/// Overrides the row title's color. Nil keeps the hub default (the role's
/// primary, which follows hover); pass any palette token's `.color`.
var titleColor: Color? = nil
@ObserveInjection var inject
var body: some View {
NavigationLink(value: destination) {
HStack(spacing: RwSizes.gap) {
// A bare glyph, no tile: buttons draw no background (BareButtons.swift),
// and the style colours it.
Image(systemName: icon)
.font(.system(size: 14, weight: .semibold))
.frame(width: 32, height: 32)
VStack(alignment: .leading, spacing: 2) {
// The role's colour unless a caller overrides it — which also opts
// the title out of the hover colour.
Text(title)
.rw(.bodyLarge, color: titleColor)
.lineLimit(1)
if let subtitle {
Text(subtitle)
.rw(.labelMedium)
.lineLimit(1)
}
}
Spacer(minLength: RwSizes.gap)
// Passive chrome icon → iconInactive (the text* tokens are for text),
// the same tint UserRow gives its chevron.
Image(systemName: "chevron.right")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(p.iconInactive)
}
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
.buttonStyle(.bareRow())
.enableInjection()
}
}