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

193 lines
6.7 KiB
Swift
Executable File

// FollowingView — the artists the user follows (port of the Flutter
// following_screen.dart).
//
// Data flow matches the Dart FollowingScreen: one getFollowing(limit: 100)
// fetch on appear, pull-to-refresh refetches, UserRow pushes the artist page
// through AppDestination (the Dart _UserTile pushed ArtistScreen).
//
// The Dart file also carried a sibling WhoToFollowScreen (getSuggestedUsers).
// The shell has no destination for a separate suggestions screen, so it is
// folded in here as a trailing "Who to Follow" section: best-effort — a
// failed or empty suggestions fetch just hides the section and never gates
// the following list, mirroring how the two Dart screens failed
// independently of each other.
//
// No pagination on purpose: getFollowing (like the Dart api) returns a single
// page with no next_href, and the Flutter screen never paged either.
//
// MARK: Selection Mode (multi-select) is not ported — later phase.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
public struct FollowingView: 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
@State private var next: String?
@State private var loadingMore = false
/// One-shot guard for the initial load; reset on cancellation so a torn
/// down .task retries on the next appearance (the Dart screen was
/// keep-alive, so it never reloaded on re-entry either).
@State private var hasLoaded = false
/// "Who to Follow" suggestions — kept outside Phase because they load (and
/// fail) independently of the following list.
@State private var suggested: [SCUser] = []
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 users) where users.isEmpty && suggested.isEmpty:
EmptyStateView(
icon: "person.2",
title: "You're not following anyone yet",
message: "Artists you follow on SoundCloud show up here.")
case .loaded(let users):
list(users, palette: p)
}
}
.background(p.bg)
.task {
// One-shot: .task re-runs on every reappear (pop back from a push,
// tab re-entry), and reloading would drop the list and scroll
// position. Pull-to-refresh is the deliberate reload path.
guard !hasLoaded else { return }
hasLoaded = true
await load()
}
.enableInjection()
}
// MARK: - Loading
private func load() async {
phase = .loading
await fetch()
}
/// Shared fetch for first load and pull-to-refresh. Refresh deliberately
/// does NOT flip the phase back to .loading: .refreshable shows its own
/// indicator (Flutter's RefreshIndicator kept the list visible too). Both
/// lists fetch concurrently; only the following list gates the phase.
private func fetch() async {
async let suggestions = fetchSuggested()
do {
let page = try await services.api.getFollowingPage(limit: 100)
CSLog.shared.log("following", "loaded \(page.users.count) followed users")
next = page.nextHref
phase = .loaded(page.users)
} catch is CancellationError {
// The .task was torn down mid-load (view left before the fetch
// landed): rearm the one-shot guard so the next appearance retries
// instead of sitting on a stale spinner.
hasLoaded = false
} catch {
CSLog.shared.log("following", "load failed: \(error.localizedDescription)")
phase = .failed(error.localizedDescription)
}
suggested = await suggestions
}
/// Best-effort: a throw hides the section instead of failing the screen —
/// suggestions are decoration next to the list the user actually came for.
private func loadMore() async {
guard !loadingMore, let cursor = next, case .loaded(let existing) = phase else { return }
loadingMore = true
defer { loadingMore = false }
do {
let page = try await services.api.getFollowingPage(limit: 100, nextHref: cursor)
next = page.nextHref
let seen = Set(existing.map(\.id))
phase = .loaded(existing + page.users.filter { !seen.contains($0.id) })
} catch {
CSLog.shared.log("following", "load-more failed: \(error.localizedDescription)")
}
}
private func fetchSuggested() async -> [SCUser] {
do {
return try await services.api.getSuggestedUsers(limit: 20)
} catch {
CSLog.shared.log(
"following", "suggested users failed: \(error.localizedDescription) — hiding section")
return []
}
}
// MARK: - List
private func list(_ users: [SCUser], palette p: RwPalette) -> some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
// The family's page header (28pt title + AccentBar), same as LikesView.
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old hand-set
// 28/heavy).
Text("Following")
.rw(.headlineLarge)
AccentBar(width: 40)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
if users.isEmpty {
// Following is empty but suggestions exist: an inline notice keeps
// the "Who to Follow" section reachable instead of burying it
// behind the full-screen empty state.
Text("You're not following anyone yet")
.rw(.bodySmall)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, RwSizes.gap)
} else {
ForEach(users) { user in
UserRow(user: user)
hairline(p)
}
InfiniteScrollFooter(hasMore: next != nil, isLoading: loadingMore) {
await loadMore()
}
}
if !suggested.isEmpty {
RwSectionHeader("Who to Follow", subtitle: "Suggested for you")
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.section)
.padding(.bottom, RwSizes.gap)
ForEach(suggested) { user in
UserRow(user: user)
hairline(p)
}
}
}
}
.pullToRefresh { await fetch() }
}
/// Hair separators are the list's job, not the row's (see LikesView).
private func hairline(_ p: RwPalette) -> some View {
Rectangle()
.fill(p.hair)
.frame(height: 1)
.padding(.leading, RwSizes.pagePadding)
}
}