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

493 lines
18 KiB
Swift
Executable File

// SearchView — the Search tab root: one query fanned out to four result kinds
// (tracks / albums / playlists / people), ported from
// lib/screens/search_screen.dart (SearchScreen).
//
// Port notes:
// - Search fires on SUBMIT, exactly like the Dart screen: its TextField
// only searched via onSubmitted (onChanged merely refreshed the clear
// button), so there is no debounce-as-you-type to invent here.
// - One submit runs all four kind searches in parallel (the Dart
// Future.wait) and each kind keeps its own next_href cursor. The chip
// row only switches which cached list is SHOWN — it never refetches.
// - Pagination is "last row appears → fetch the next page". Because
// onAppear also fires for rows already on screen, a first page too short
// to scroll pulls the next page by itself — subsuming the Dart screen's
// _maybeAutoFill post-frame dance. Load-more is single-flight PER KIND;
// a trigger swallowed while that kind's own page is in flight is
// remembered and re-fired when the page lands (or on the next chip
// switch), so pagination can never stall for good.
// - PERSISTENT STATE: everything lives in plain @State and the body has no
// .task, so nothing reloads or resets when the shell brings the tab back
// (iOS TabView and the macOS keep-alive ZStack both keep this view
// mounted). Query, results, cursors and the selected kind all survive
// tab switches — Flutter's IndexedStack behavior.
// - No .refreshable: the Dart screen has no RefreshIndicator; re-submitting
// the query IS its refresh.
//
// MARK: Skipped this phase — multi-select / Selection Mode (Flutter's
// long-press flow on track tiles), download buttons (none on this branch), Android Auto /
// glasses / Tuneshine hooks, visualizer hooks.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct SearchView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
/// The Dart `_SearchTab` enum, same members and order. Named "kind" here
/// because the shell already owns the word "tab".
private enum ResultKind: Int, CaseIterable, Identifiable {
case tracks, albums, playlists, people
var id: Int { rawValue }
var title: String {
switch self {
case .tracks: "Tracks"
case .albums: "Albums"
case .playlists: "Playlists"
case .people: "People"
}
}
}
// MARK: - State (all @State on purpose — it survives tab switches, see header)
@State private var query = ""
@State private var kind: ResultKind = .tracks
@State private var isLoading = false
/// Load-more in-flight tracking PER KIND: a shared bool let one kind's
/// in-flight page swallow another kind's last-row trigger (chip switch
/// mid-flight), and nothing ever re-fired — a permanent stall.
@State private var loadingMore: Set<ResultKind> = []
/// Kinds whose load-more trigger was swallowed while their OWN page was in
/// flight. Drained when that page lands (loadMore chains the next page) or
/// on a chip switch (the Dart _maybeAutoFill on tab taps).
@State private var pendingMore: Set<ResultKind> = []
@State private var errorMessage: String?
/// A search has happened — gates the chip row and the per-kind empty
/// states (the Dart `_searched`).
@State private var hasSearched = false
/// The trimmed query the current results belong to. Load-more keeps using
/// it even after the field text has been edited but not resubmitted (the
/// Dart `_lastQuery`).
@State private var lastQuery: String?
/// Bumped by every fresh search (and by Clear). In-flight responses compare
/// against it before touching state, so a slow old query can never
/// overwrite a newer one — the Dart screen carried this race; the counter
/// closes it for free.
@State private var searchGeneration = 0
@State private var tracks: [SCTrack] = []
@State private var tracksNextHref: String?
@State private var albums: [SCPlaylist] = []
@State private var albumsNextHref: String?
@State private var playlists: [SCPlaylist] = []
@State private var playlistsNextHref: String?
@State private var users: [SCUser] = []
@State private var usersNextHref: String?
public init() {}
// MARK: - Body
@ObserveInjection var inject
public var body: some View {
VStack(spacing: 0) {
header(p)
searchField(p)
if hasSearched {
kindChips(p)
}
results(p)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(p.bg)
// Result lists cover most of the screen on iOS; the first scroll should
// put the keyboard away instead of fighting it. No-op on macOS.
.scrollDismissesKeyboard(.immediately)
.enableInjection()
}
// MARK: - Header (the family's page title + AccentBar, as LikesView renders)
private func header(_ p: RwPalette) -> some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old hand-set
// 28/heavy).
Text("Search")
.rw(.headlineLarge)
AccentBar(width: 40)
}
Spacer(minLength: RwSizes.gap)
ShellHeaderControls()
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
// MARK: - Search field
/// The Dart pill-shaped TextField, re-rendered SQUARE (the library's
/// no-corners rule) with palette tokens: 2pt hair outline, red search glyph,
/// trailing clear button while there is text. The field sets no font of
/// its own so it inherits the theme's Raleway environment font.
private func searchField(_ p: RwPalette) -> some View {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(p.red)
TextField("Search tracks, artists, playlists…", text: $query)
.textFieldStyle(.plain) // no AppKit bezel on macOS
.autocorrectionDisabled()
.submitLabel(.search)
.onSubmit { Task { await runSearch(query) } }
if !query.isEmpty {
Button {
clearSearch()
} label: {
// Passive chrome icon → iconInactive (gray textMuted reads off-brand on icons).
Image(systemName: "xmark.circle.fill")
.font(.system(size: 14))
.foregroundStyle(p.iconInactive)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, RwSizes.pagePadding)
.frame(height: RwSizes.controlHeight)
// An outline, not a well: no field draws a fill (Outlined.swift).
.outlined(p.hair)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
// MARK: - Kind chips (the Dart _TabChip row — shown only after a search)
private func kindChips(_ p: RwPalette) -> some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(ResultKind.allCases) { k in
chip(k, palette: p)
}
}
.padding(.horizontal, RwSizes.pagePadding)
}
.padding(.bottom, RwSizes.gap)
}
private func chip(_ k: ResultKind, palette p: RwPalette) -> some View {
let selected = kind == k
// Switching never refetches: each kind's list and cursor are already
// cached. The fresh list's own last-row onAppear covers the normal fill,
// but a trigger swallowed while this kind's page was in flight has no
// row left to re-appear — so re-fire it here (the Dart _maybeAutoFill
// on tab taps).
// .rw(selected:) IS the library's chip idiom: inverted (solid red)
// while selected, page-colored otherwise — the old hand-built capsule.
return Button {
kind = k
maybeAutoFill(k)
} label: {
Text(k.title)
}
.buttonStyle(.bare(selected: selected))
}
// MARK: - Results
@ViewBuilder
private func results(_ p: RwPalette) -> some View {
if isLoading {
LoadingView()
} else if let errorMessage {
// The Dart screen only said "Search failed"; the foundation error view
// adds the message and a Retry that re-runs the same query.
ErrorStateView(message: errorMessage) {
if let lastQuery {
Task { await runSearch(lastQuery) }
}
}
} else if !hasSearched {
EmptyStateView(
icon: "magnifyingglass",
title: "Search SoundCloud",
message: "Find tracks, albums, playlists and people.")
} else {
switch kind {
case .tracks:
trackList(p)
case .albums:
playlistList(albums, kind: .albums, emptyIcon: "opticaldisc", emptyTitle: "No albums found", palette: p)
case .playlists:
playlistList(
playlists, kind: .playlists, emptyIcon: "music.note.list", emptyTitle: "No playlists found",
palette: p)
case .people:
peopleList(p)
}
}
}
@ViewBuilder
private func trackList(_ p: RwPalette) -> some View {
if tracks.isEmpty {
EmptyStateView(icon: "music.note", title: "No tracks found")
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(tracks) { track in
// The WHOLE result list is the play context: next/prev/autoplay
// walk the search results, never a one-track dead end.
TrackRow(track: track, in: tracks)
.onAppear {
if track.id == tracks.last?.id {
Task { await loadMore(.tracks) }
}
}
hairline(p)
}
if loadingMore.contains(.tracks) {
moreSpinner(p)
}
}
}
}
}
/// Albums and playlists share this list: both are SCPlaylist (isAlbum
/// distinguishes them, as in the Dart) — only the cursor differs, so the
/// caller names which kind to page.
@ViewBuilder
private func playlistList(
_ list: [SCPlaylist], kind k: ResultKind, emptyIcon: String, emptyTitle: String,
palette p: RwPalette
) -> some View {
if list.isEmpty {
EmptyStateView(icon: emptyIcon, title: emptyTitle)
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(list) { playlist in
// Pure navigation: the detail screen back-fills v2's ~5-track
// partial hydration before any bulk action (see PlaylistRow).
// The subtitle names the owner, as the Dart search rows did —
// its "•" rendered with this row family's "·" separator.
PlaylistRow(
playlist: playlist,
subtitle: "\(playlist.user.username) · \(playlist.isAlbum ? "Album" : "Playlist")"
)
.onAppear {
if playlist.id == list.last?.id {
Task { await loadMore(k) }
}
}
hairline(p)
}
if loadingMore.contains(k) {
moreSpinner(p)
}
}
}
}
}
@ViewBuilder
private func peopleList(_ p: RwPalette) -> some View {
if users.isEmpty {
EmptyStateView(icon: "person.2", title: "No people found")
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(users) { user in
UserRow(user: user)
.onAppear {
if user.id == users.last?.id {
Task { await loadMore(.people) }
}
}
hairline(p)
}
if loadingMore.contains(.people) {
moreSpinner(p)
}
}
}
}
}
/// Hair separators are the list's job, not the row's (LikesView's rule).
private func hairline(_ p: RwPalette) -> some View {
Rectangle()
.fill(p.hair)
.frame(height: 1)
.padding(.leading, RwSizes.pagePadding)
}
/// The Dart _loadingSpinner: a small centered spinner under the last row
/// while the next page is in flight.
private func moreSpinner(_ p: RwPalette) -> some View {
ProgressView()
// .color: ProgressView only honors the Color overload of .tint.
.tint(p.red.color)
.controlSize(.small)
.frame(maxWidth: .infinity)
.padding(.vertical, RwSizes.gap)
}
// MARK: - Actions
/// The Dart _search: reset the cursors, fan the query out to all four kind
/// endpoints at once, and replace every list from the fresh page.
private func runSearch(_ raw: String) async {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
searchGeneration += 1
let generation = searchGeneration
lastQuery = trimmed
isLoading = true
// Swallowed load-more triggers belong to the OLD results — re-firing
// them against the fresh lists would fetch pages nobody asked for.
pendingMore = []
errorMessage = nil
hasSearched = true
CSLog.shared.log("search", "search \"\(trimmed)\" (gen \(generation))")
do {
// Future.wait, Swift-shaped: four structured child tasks, one throw
// fails the whole batch into the error state (the Dart behavior).
async let trackPage = services.api.searchTracks(trimmed, limit: 20)
async let albumPage = services.api.searchAlbums(trimmed, limit: 20)
async let playlistPage = services.api.searchPlaylists(trimmed, limit: 20)
async let userPage = services.api.searchUsers(trimmed, limit: 20)
let (t, a, pl, u) = try await (trackPage, albumPage, playlistPage, userPage)
guard generation == searchGeneration else { return } // a newer search won
tracks = t.tracks
tracksNextHref = t.nextHref
albums = a.playlists
albumsNextHref = a.nextHref
playlists = pl.playlists
playlistsNextHref = pl.nextHref
users = u.users
usersNextHref = u.nextHref
isLoading = false
CSLog.shared.log(
"search",
"\"\(trimmed)\": \(t.tracks.count) tracks, \(a.playlists.count) albums, "
+ "\(pl.playlists.count) playlists, \(u.users.count) people")
} catch {
guard generation == searchGeneration else { return }
CSLog.shared.log("search", "search \"\(trimmed)\" failed: \(error.localizedDescription)")
errorMessage = error.localizedDescription
isLoading = false
}
}
/// The Dart _loadMore, keyed by kind instead of the visible tab so a page
/// that lands after the user switched chips still appends to the RIGHT
/// list. Single-flight PER KIND: a duplicate trigger for the same kind is
/// remembered in pendingMore instead of dropped, because the last row's
/// onAppear will not fire again while it stays on screen — a dropped
/// trigger used to stall pagination for good.
private func loadMore(_ k: ResultKind) async {
guard let q = lastQuery else { return }
guard !loadingMore.contains(k) else {
pendingMore.insert(k)
return
}
let generation = searchGeneration
loadingMore.insert(k)
do {
// `break` (not return) on the early exits so the remove + re-fire
// below always runs — an early return would strand k in loadingMore.
switch k {
case .tracks:
guard let next = tracksNextHref else { break }
let page = try await services.api.searchTracks(q, nextHref: next)
guard generation == searchGeneration else { break }
tracks += dedup(page.tracks, against: tracks)
tracksNextHref = page.nextHref
case .albums:
guard let next = albumsNextHref else { break }
let page = try await services.api.searchAlbums(q, nextHref: next)
guard generation == searchGeneration else { break }
albums += dedup(page.playlists, against: albums)
albumsNextHref = page.nextHref
case .playlists:
guard let next = playlistsNextHref else { break }
let page = try await services.api.searchPlaylists(q, nextHref: next)
guard generation == searchGeneration else { break }
playlists += dedup(page.playlists, against: playlists)
playlistsNextHref = page.nextHref
case .people:
guard let next = usersNextHref else { break }
let page = try await services.api.searchUsers(q, nextHref: next)
guard generation == searchGeneration else { break }
users += dedup(page.users, against: users)
usersNextHref = page.nextHref
}
} catch {
// The Dart screen swallowed load-more failures (catch (_) {}): the
// list keeps what it has and the cursor stays put, so scrolling to the
// bottom again retries the same page.
CSLog.shared.log("search", "load more (\(k.title)) failed: \(error.localizedDescription)")
}
loadingMore.remove(k)
// A trigger for this kind arrived while its page was in flight — the
// list still wants more, so chain the next page now that the cursor
// moved (each pending entry re-fires at most once: remove drains it).
if generation == searchGeneration, pendingMore.remove(k) != nil {
await loadMore(k)
}
}
/// The Dart _maybeAutoFill on tab taps: a trigger swallowed while kind k's
/// page was in flight has no last row left to re-appear once that list is
/// shown again, so a chip switch re-fires it. While the page is STILL in
/// flight, loadMore's own completion chain handles it instead.
private func maybeAutoFill(_ k: ResultKind) {
guard pendingMore.contains(k), !loadingMore.contains(k) else { return }
pendingMore.remove(k)
Task { await loadMore(k) }
}
/// The Dart clear button: wipe the field, the results and the "searched"
/// flag so the placeholder returns. Bumping the generation also cancels
/// (result-drops) anything still in flight.
private func clearSearch() {
searchGeneration += 1
query = ""
hasSearched = false
isLoading = false
loadingMore = []
pendingMore = []
errorMessage = nil
lastQuery = nil
tracks = []
tracksNextHref = nil
albums = []
albumsNextHref = nil
playlists = []
playlistsNextHref = nil
users = []
usersNextHref = nil
}
/// Appended pages can overlap the previous one (SoundCloud's next_href
/// windows drift while results update), and duplicate ids would both break
/// ForEach identity and freeze TrackRow's per-row @State copy — so appends
/// drop anything already listed. The Dart ListView tolerated duplicates;
/// SwiftUI does not.
private func dedup<T: Identifiable>(_ new: [T], against existing: [T]) -> [T] {
let known = Set(existing.map(\.id))
return new.filter { !known.contains($0.id) }
}
}