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

582 lines
23 KiB
Swift
Executable File

// AppShell — the navigation frame around the screens, built on the library's
// RwShell (the bottom tab bar it replaced is gone).
//
// The tab set mirrors the Flutter home_screen.dart (minus Downloads): Home,
// Search, Playlists, Profile. Each tab is its own NavigationStack carrying ONE
// navigationDestination(for: AppDestination.self) registration, so every
// screen pushes plain values and the value→view mapping lives in exactly one
// place (destinationView below).
//
// RwShell gives both platforms one layout instead of the two this file used
// to carry:
// - Narrow (phone, < RwSizes.compactBreakpoint): the sidebar is a slide-in
// DRAWER opened by RwShellMenuButton — the hamburger. No tab bar.
// - Wide (Mac): the sidebar is always visible and the same button collapses
// it to an icon rail.
// Profile rides in footerDestinations (pinned to the bottom of the drawer)
// with an iconBuilder drawing the signed-in avatar — exactly what the Flutter
// shell did with RwDestination.iconBuilder → _AvatarIcon.
//
// showAppBar: false — every tab root already draws the family page header
// (title + AccentBar + ShellHeaderControls, which hosts the hamburger), so
// the shell's own RwAppBar would just repeat the title underneath it.
//
// Keep-alive: RwShell renders ONE content view, so the IndexedStack behaviour
// the Flutter shell had (and that the old iOS TabView got for free) is now
// explicit on both platforms — every tab root stays mounted, only the
// selected one is visible, hit-testable and focusable. Search results, scroll
// positions and half-loaded screens survive tab switches.
//
// The MiniPlayerBar lives here via .safeAreaInset(edge: .bottom), applied
// once around the keep-alive stack; pages inside the stacks get matching room
// from MiniPlayerClearance, because on iOS that inset does not pass through a
// NavigationStack. Tapping the bar itself slides up the full player
// (nowPlayingLayer), which covers the page and the bar but not the sidebar;
// the bar's own transport buttons keep working because a Button inside the
// bar wins the tap over the container's onTapGesture.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct AppShell: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
/// The four tabs, in Flutter's order (home_screen.dart `_titles`).
private enum AppTab: Int, CaseIterable, Identifiable {
case home, search, playlists, profile
var id: Int { rawValue }
var title: String {""}
/// SF Symbol standing in for the Material icon each Flutter tab used.
var icon: String {""}
/// Selected-state symbol. NOT `icon + ".fill"` — that was the bug: SF
/// Symbols has no `magnifyingglass.fill` or `music.note.list.fill`, and a
/// missing symbol renders as nothing, so Search and Playlists went blank
/// exactly when active. Use the filled variant only where one exists; fall
/// back to the outline symbol otherwise (still legible, just not filled).
var selectedIcon: String {""}
/// Everything except Profile, which is pinned to the drawer's footer.
/// Profile draws the signed-in avatar through RwDestination.iconBuilder,
/// the same hook the Flutter shell used (_AvatarIcon); everything else is
/// a symbol. The builder runs on every shell update, so the avatar
/// appears as soon as getMe lands.
@MainActor
func destination(services: AppServices) -> RwDestination {
guard self == .profile else {
return RwDestination(
systemImage: icon, selectedSystemImage: selectedIcon, label: title)
}
return RwDestination(
iconBuilder: { color, _ in
AnyView(ShellAvatarIcon(url: services.currentUser?.avatarUrl, fallbackColor: color))
},
label: title)
}
}
/// RwShell drives an Int (footerDestinations continue the index count, so
/// Profile is index 3 — the same order AppTab declares).
/// Selection lives in an @Observable rather than a plain @State Int so the
/// screens BELOW the shell can drive it: the header avatar switches to the
/// Profile TAB. AppDestination.profile would push a second ProfileView
/// instead — a NavigationLink cannot select a tab.
@State private var nav = ShellNavigator(profileIndex: AppTab.profile.rawValue)
private var selectedTab: AppTab { AppTab(rawValue: nav.index) ?? .home }
/// Mini-player (background) tap → full now-playing sheet.
/// The shell's sidebar/drawer state, planted by RwShell. Optional: the
/// shell is above us, but the environment read has to tolerate its absence
/// (previews, tests).
@Environment(RwShellModel.self) private var shell: RwShellModel?
@State private var showNowPlaying = false
/// The MiniPlayerBar's live height (0 with no track), mirrored into every
/// page inside the stacks — see MiniPlayerClearance.
@State private var miniPlayerHeight: CGFloat = 0
/// One page stack per tab, plus the full player's under `playerStack`.
/// Typed, not NavigationPath: forward needs to know which pages were left,
/// and a NavigationPath can't say what it just dropped. Menu rows push
/// through \.appPush (see AppPush.swift) because RwMenuItem is action-only —
/// it cannot carry a NavigationLink.
@State private var paths: [Int: [AppDestination]] = [:]
/// Per stack, the pages gone back from — what forward walks into, newest
/// last. Any new page clears it, as in a browser.
@State private var forward: [Int: [AppDestination]] = [:]
/// The full player's key in `paths` / `forward` (tabs are 0…4).
private static let playerStack = -1
public init() {}
@ObserveInjection var inject
public var body: some View {
keepAliveContent.overlay { nowPlayingLayer }
.background(p.bg)
#if os(macOS)
// The title bar, drawn by RedWhiteUI as the top of this content —
// above every page stack, so no push or hidden back button can
// touch it (SwiftUI's own toolbar could not do that: a pushed
// page that hides the system back button loses ALL its toolbar
// items). Solid page colour, no line under it.
.rwTitleBar(divider: false) {
RwBackForward(
canGoBack: pageHistory.canGoBack,
canGoForward: pageHistory.canGoForward,
onBack: pageHistory.back,
onForward: pageHistory.forward)
} trailing: {
ShellHeaderControls()
.environment(\.inPushBar, true)
}
// For the title bar, which sits above the stacks: its links push
// onto the stack on screen (each stack sets its own \.appPush for
// its pages), and its avatar selects the Profile tab.
.environment(\.appPush) { push($0, onto: visibleStack) }
.environment(nav)
// SwiftUI's own (now empty) window toolbar: no glass.
.toolbarBackground(.hidden, for: .windowToolbar)
#endif
// Nothing left to show (the queue was cleared): fold the player away.
.onChange(of: services.queue.currentTrack == nil) { _, gone in
if gone, showNowPlaying { closeNowPlaying() }
}
.enableInjection()
}
// MARK: - Tabs
/// A sidebar (or drawer) pick.
///
/// On the Mac it always lands on that tab's ROOT: each tab keeps its own
/// NavigationStack, so without the reset, Home → a playlist → Search → Home
/// came back to the playlist, not Home. Re-picking the tab you are on pops
/// to its root too (RwShell sets the selection even when it is unchanged).
/// iOS keeps each tab's place, the platform's usual tab behaviour.
///
/// Picking anything also folds the full player away, so the choice is what
/// you see.
private func selectTab(_ index: Int) {
#if os(macOS)
paths[index] = []
forward[index] = []
#endif
if showNowPlaying { closeNowPlaying() }
nav.index = index
}
// MARK: - Full player
/// The full-screen player: TrackDetailView live on the current track,
/// sliding up over the page area and the mini player (the whole screen on
/// iPhone; everything but the sidebar on a wide window) — the Apple Music /
/// Spotify now-playing view, in place of the old system sheet that covered
/// the sidebar too and was a card on iPhone.
///
/// It carries its own NavigationStack with the shell's single
/// destinationView switch, so links inside (artist, comment authors,
/// related tracks) push here rather than dying against no stack.
@ViewBuilder
private var nowPlayingLayer: some View {
if showNowPlaying, let track = services.queue.currentTrack {
NavigationStack(path: pathBinding(Self.playerStack)) {
VStack(spacing: 0) {
nowPlayingBar
TrackDetailView(track: track, opensOnComments: true)
}
// No empty system bar above our row at the ROOT; pushed screens get
// the library's flat bar from destinationView.
.rwHideSystemPushChrome()
.navigationDestination(for: AppDestination.self) { destination in
destinationView(destination)
}
}
// On the stack, not its root page: see tabStack.
.environment(\.appPush) { push($0, onto: Self.playerStack) }
// Opaque all the way up, so the page never shows through under the
// status bar / title bar.
.background(p.bg.color.ignoresSafeArea())
.transition(.move(edge: .bottom))
}
}
/// Close (⌄) on the left, the title centred against a matching spacer.
/// Escape closes on the Mac; on iPhone a downward drag on this row does.
private var nowPlayingBar: some View {
HStack {
Button {
closeNowPlaying()
} label: {
Image(systemName: "chevron.down")
.font(.system(size: 15, weight: .semibold))
}
.buttonStyle(.bareIcon())
.keyboardShortcut(.cancelAction)
.help("Close")
.accessibilityLabel("Close player")
Spacer()
Text("Now Playing").rw(.labelSmall)
Spacer()
// The close button's width, so the title sits dead centre.
Color.clear.frame(width: 40, height: 1)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 6)
#if os(iOS)
.contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 12).onEnded { value in
if value.translation.height > 60 { closeNowPlaying() }
})
#endif
}
private func openNowPlaying() {
// Every opening starts at the player itself, not wherever a link inside
// it led last time.
paths[Self.playerStack] = []
forward[Self.playerStack] = []
withAnimation(.spring(response: 0.38, dampingFraction: 0.9)) { showNowPlaying = true }
}
private func closeNowPlaying() {
withAnimation(.easeInOut(duration: 0.28)) { showNowPlaying = false }
}
// MARK: - Page history (back / forward)
/// A stack's path, as the NavigationStack sees it. Writes from the stack
/// itself — a NavigationLink pushing, the edge swipe or ⌘[ popping — are
/// read for history: a pop keeps what it unwound for forward, anything else
/// is a new page and clears forward.
private func pathBinding(_ key: Int) -> Binding<[AppDestination]> {
Binding(
get: { paths[key] ?? [] },
set: { new in
let old = paths[key] ?? []
if new.count < old.count, Array(old.prefix(new.count)) == new {
// Reversed: the page nearest the new top is the next forward.
forward[key, default: []].append(contentsOf: old[new.count...].reversed())
} else if new != old {
forward[key] = []
}
paths[key] = new
})
}
private func push(_ destination: AppDestination, onto key: Int) {
paths[key, default: []].append(destination)
forward[key] = []
}
private func goBack(_ key: Int) {
guard let page = paths[key]?.popLast() else { return }
forward[key, default: []].append(page)
}
private func goForward(_ key: Int) {
guard let page = forward[key]?.popLast() else { return }
paths[key, default: []].append(page)
}
/// The stack on screen: the full player's while it is up, else the tab's.
private var visibleStack: Int { showNowPlaying ? Self.playerStack : nav.index }
/// What the Mac title bar's back / forward chevrons drive.
private var pageHistory: PageHistory {
let key = visibleStack
return PageHistory(
canGoBack: !(paths[key] ?? []).isEmpty,
canGoForward: !(forward[key] ?? []).isEmpty,
back: { goBack(key) },
forward: { goForward(key) })
}
/// Flutter's IndexedStack: every tab root stays mounted; only the selected
/// one is visible, hit-testable and focusable.
private var keepAliveContent: some View {
ZStack {
ForEach(AppTab.allCases) { tab in
tabStack(tab)
.opacity(selectedTab == tab ? 1 : 0)
.allowsHitTesting(selectedTab == tab)
// Hidden ≠ unfocusable: .allowsHitTesting only blocks the pointer,
// so Tab traversal could still land keyboard focus in an invisible
// SearchView text field. .disabled takes the hidden stacks out of
// the key loop as well.
.disabled(selectedTab != tab)
}
}
.safeAreaInset(edge: .bottom) {
// Measured on an always-present wrapper so the height drops back to 0
// when the bar goes away (a removed view reports nothing).
VStack(spacing: 0) { miniPlayer }
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: {
miniPlayerHeight = $0
}
}
// Reaches every tab root (and so every ShellHeaderControls) — the avatar
// needs it to select the Profile tab.
.environment(nav)
// Through the environment, not a captured value: a navigationDestination
// closure keeps the value it had at push time, so a page pushed before
// the bar appeared would never get its room. Environment changes reach
// pushed pages live.
.environment(\.miniPlayerClearance, miniPlayerHeight)
}
// MARK: - Tab stacks
/// One tab = one NavigationStack over the tab's root, carrying the single
/// AppDestination registration for everything pushed inside it.
private func tabStack(_ tab: AppTab) -> some View {
NavigationStack(path: pathBinding(tab.rawValue)) {
rootView(tab)
.modifier(MiniPlayerClearance())
// At the ROOT of a stack there is nothing to go back to, so the same
// edge swipe opens the drawer instead — the gesture means "reveal
// what is to my left" either way. RwShellModel.toggle() collapses the
// sidebar on wide windows, so this is gated on compact: on a Mac or
// an iPad the swipe would otherwise fold the sidebar away.
.leadingEdgeSwipe {
if let shell, shell.compact { shell.toggle() }
}
.navigationDestination(for: AppDestination.self) { destination in
destinationView(destination)
}
}
// On the STACK, not its root page. A value set on the root stops there:
// pages pushed on top don't inherit it (measured on iOS: the root saw
// it, a pushed page saw nil), so every menu row that pushes — the
// header ⋯, a track's Go to Artist — came up empty on any pushed page.
.environment(\.appPush) { push($0, onto: tab.rawValue) }
}
@ViewBuilder
private func rootView(_ tab: AppTab) -> some View {
switch tab {
case .home: DiscoverView()
case .search: SearchView()
case .playlists: PlaylistsView()
case .profile: ProfileView()
}
}
/// THE destination switch — the only place AppDestination values become
/// concrete screens. Screens push values, never each other's types.
///
/// Also the one place push chrome is applied: every pushed screen gets the
/// library's flat back bar (rwPushChrome) and no system navigation bar,
/// because the system back button is Liquid Glass and cannot be restyled.
/// No title goes in: AppDestination carries none, and every pushed screen
/// already draws its own header (ArtistView's avatar + name, the cover on
/// PlaylistDetailView, the settings screens' header) — a bar title would be
/// a second copy of it. The visualizer is the exception — it is
/// deliberately immersive and carries its own flat close button.
@ViewBuilder
private func destinationView(_ destination: AppDestination) -> some View {
Group {
if destination == .visualizer {
destinationBody(destination)
} else {
destinationBody(destination)
#if os(iOS)
// The header's own controls where the back arrow would be; back
// is the edge swipe.
.rwPushChrome(backButton: .hidden, divider: false) {
ShellHeaderControls(overFlowMenu: {})
.environment(\.inPushBar, true)
}
#else
// A Mac: no bar and no arrow — the controls and the back /
// forward chevrons are in the title bar (rwTitleBar, in body).
.rwHideSystemPushChrome()
#endif
.modifier(PushSwipeBack())
.environment(\.isPushedPage, true)
}
}
.modifier(MiniPlayerClearance())
}
@ViewBuilder
private func destinationBody(_ destination: AppDestination) -> some View {
switch destination {
case .artist(let user):
ArtistView(user: user)
case .playlist(let playlist):
PlaylistDetailView(playlist: playlist)
case .track(let track):
TrackDetailView(track: track)
case .likes:
// Reuse the existing likes screen as-is: the shell supplies what its
// init needs, so a push stays the plain value .likes and the full
// loaded list still becomes the play context (next/prev/autoplay walk
// the likes).
LikesView(api: services.api) { track, allTracks in
await services.queue.playTrack(track, newQueue: allTracks)
}
case .following:
FollowingView()
case .history:
HistoryView()
case .ambience:
AmbienceView()
case .myReposts:
MyRepostsView()
case .myAlbums:
MyAlbumsView()
case .myTracks:
MyTracksView()
case .lastfm:
LastFMView()
case .radioTuner:
RadioTunerView()
case .console:
ConsoleView()
case .services:
ServicesView()
case .equalizer:
EqualizerView()
case .visualizer:
VisualizerView()
case .visualizerSettings:
VisualizerSettingsView()
case .devices:
DevicesView()
case .themes:
// Reads the app-wide RwAppearanceController out of the environment
// (CrossSoundScene plants it above AppRoot), so there is nothing to
// hand it here — same shape as every other zero-argument screen.
ThemesView()
case .tuneshine:
TuneshineView()
case .update:
UpdateView()
case .discover:
DiscoverView()
case .search:
SearchView()
case .playlists:
PlaylistsView()
case .profile:
ProfileView()
case .queue:
QueueView()
case .notifications:
NotificationsView()
case .stations:
StationsView()
case .radio:
RadioView()
}
}
// MARK: - Mini player
/// currentTrack (not engine state) gates the bar: a restored session sits
/// paused with NOTHING loaded (engine idle) and must still show, exactly
/// like the Flutter cold start — the same rule AppRoot applied before the
/// bar moved here.
@ViewBuilder
private var miniPlayer: some View {
if services.queue.currentTrack != nil {
MiniPlayerBar(engine: services.engine, controller: services.queue)
.contentShape(Rectangle())
.onTapGesture { openNowPlaying() }
}
}
}
/// Back by edge swipe as well as by the bar's chevron. The library's
/// rwPushChrome draws the bar and hides the system one but brings no gesture
/// of its own, so the swipe stays here — a gesture helper, not a look. It is
/// a ViewModifier for the `dismiss` read: resolved inside the pushed screen's
/// hierarchy it pops THAT screen; read on AppShell it would be the shell's.
/// SwiftUI's NavigationStack keeps its own interactive pop when the bar is
/// hidden, so this is belt and braces — both call the same dismiss, and a
/// second dismiss on an already-popped screen is a no-op.
/// Room for the MiniPlayerBar at the bottom of a page INSIDE a tab's
/// NavigationStack.
///
/// The bar itself is a `.safeAreaInset(edge: .bottom)` on the ZStack OUTSIDE
/// the stacks, so it stays put while pages push and pop. But on iOS that inset
/// does not reach through a NavigationStack: measured on the iOS 27 simulator,
/// a ScrollView inside the stack got only the home-indicator inset, so the
/// last ~63pt of every page (Settings' Log out row, the selection bars) sat
/// under the bar and rubber-banded back there. `.safeAreaPadding` on the stack
/// does not get through either; an inset applied to the page itself does. So
/// each page gets an invisible inset of the bar's measured height — 0 when no
/// track is loaded. Page-level insets (selection bars, notices) stack above
/// it, which is where they belong.
///
/// iOS only: that is where the gap was measured. macOS has not been checked,
/// and adding this there while the outer inset DID propagate would double the
/// space.
private struct MiniPlayerClearance: ViewModifier {
@Environment(\.miniPlayerClearance) private var height
func body(content: Content) -> some View {
#if os(iOS)
content.safeAreaInset(edge: .bottom, spacing: 0) {
Color.clear.frame(height: height)
}
#else
content
#endif
}
}
extension EnvironmentValues {
/// The MiniPlayerBar's height, for MiniPlayerClearance.
@Entry fileprivate var miniPlayerClearance: CGFloat = 0
}
private struct PushSwipeBack: ViewModifier {
@Environment(\.dismiss) private var dismiss
func body(content: Content) -> some View {
content.leadingEdgeSwipe { dismiss() }
}
}
/// The drawer's Profile icon: the signed-in avatar, falling back to the
/// symbol while it loads (or when signed out). Drawn inside RwNavItem's
/// icon box, so it sizes itself to the space it is given.
@MainActor
struct ShellAvatarIcon: View {
@Environment(\.rw) private var p
let url: String?
let fallbackColor: Color
@ObserveInjection var inject
var body: some View {
AsyncImage(url: url.flatMap(URL.init(string:))) { image in
image.resizable().scaledToFill()
} placeholder: {
Image(systemName: "person.crop.circle")
.resizable()
.scaledToFit()
.foregroundStyle(fallbackColor)
}
// 18 + 1pt gap + a 2pt ring keeps the whole thing inside RwNavItem's
// icon box; the Electron avatar is 38 with the same 2px ring.
.frame(width: 18, height: 18)
.clipShape(Circle())
.padding(1)
// The ring sits OUTSIDE the image, like the web build's
// `box-shadow: 0 0 0 2px var(--ink)` — an inset border would eat the
// photo's edge. --ink is the main red, so this follows the accent and
// stays customisable through the appearance settings.
.overlay(Circle().stroke(p.red, lineWidth: 2))
.enableInjection()
}
}