~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
276 lines · 8.3 KB Raw History
import HydraulophoneCore
import SwiftUI

struct ContentView: View {
  @EnvironmentObject private var model: AppModel

  var body: some View {
    Group {
      if model.isRestoringSession || model.isSessionTransitioning {
        VStack(spacing: 14) {
          ProgressView()
            .controlSize(.large)
          Text("Preparing your music session…")
            .font(.subheadline)
            .foregroundStyle(.secondary)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(HydraulophoneTheme.groupedBackground)
      } else if model.session?.isAuthenticated == true {
        AppContentView(
          musicService: model.musicService,
          playback: model.playback
        )
        .sheet(isPresented: $model.showingLogin) {
          LoginView()
            .environmentObject(model)
        }
      } else {
        LoginView(isRequired: true)
          .environmentObject(model)
      }
    }
    .environment(\.offlineOnly, model.isOfflineOnly)
  }
}

/// Only song availability changes the shell layout. Observing the entire player
/// here would rebuild navigation and the presented queue on every playback tick.
private struct AppContentView: View {
  @EnvironmentObject private var model: AppModel
  @Environment(\.horizontalSizeClass) private var horizontalSizeClass
  private let playback: PlaybackController
  @State private var hasCurrentSong: Bool
  private let musicService: any MusicService
  @State private var selectedSection: AppSection = .home
  @State private var isShowingNowPlaying = false
  @State private var pendingDestination: TrackDestination?
  @StateObject private var searchInput = CatalogSearchInput()

  init(musicService: any MusicService, playback: PlaybackController) {
    self.musicService = musicService
    self.playback = playback
    _hasCurrentSong = State(initialValue: playback.currentSong != nil)
    #if DEBUG
      let arguments = ProcessInfo.processInfo.arguments
      if arguments.contains("-HydraulophoneOfflineFixture") {
        if arguments.contains("-HydraulophonePreviewSettings") {
          _selectedSection = State(initialValue: .settings)
        } else if arguments.contains("-HydraulophonePreviewDownloads")
          || arguments.contains("-HydraulophonePreviewLibrary")
        {
          _selectedSection = State(initialValue: .library)
        }
        _isShowingNowPlaying = State(
          initialValue: arguments.contains("-HydraulophonePreviewPlayer"))
      }
    #endif
  }

  var body: some View {
    Group {
      #if targetEnvironment(macCatalyst)
        splitNavigation
      #else
        if horizontalSizeClass == .regular {
          splitNavigation
        } else {
          tabs
        }
      #endif
    }
    .environmentObject(searchInput)
    .environment(\.catalogTrackDestination, openCatalog)
    .onChange(of: searchInput.submission) { _, _ in
      if !searchInput.query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        selectedSection = .search
      }
    }
    .tint(HydraulophoneTheme.accent)
    .sensoryFeedback(.selection, trigger: selectedSection)
    .onReceive(playback.$currentSong) { song in
      hasCurrentSong = song != nil
      guard !model.isOfflineOnly, let song else { return }
      Task { await model.downloads.cacheArtwork(for: song) }
    }
    .task(id: model.isOfflineOnly) {
      guard !model.isOfflineOnly else { return }
      let cached = await model.trackCache.cachedTracks()
      let knownSongs = OfflineLibraryTracks.songs(
        cached: cached, downloaded: model.downloads.availableSongs)
      for song in knownSongs {
        guard !Task.isCancelled, !model.isOfflineOnly else { return }
        await model.downloads.cacheArtwork(for: song)
      }
    }
    .sheet(isPresented: $isShowingNowPlaying) {
      NowPlayingView()
        .environmentObject(model)
        .environment(\.playerTrackDestination, openCatalog)
        .environment(\.pendingTrackDestination, nil)
        .presentationDetents([.large])
        .presentationDragIndicator(.visible)
    }
  }

  private var splitNavigation: some View {
    NavigationSplitView {
      List(selection: sidebarSelection) {
        Section("Listen") {
          NavigationLink(value: AppSection.home) {
            Label("Home", systemImage: "house")
          }
          NavigationLink(value: AppSection.search) {
            Label("Search", systemImage: "magnifyingglass")
          }
        }
        Section("Your music") {
          NavigationLink(value: AppSection.library) {
            Label("Library", systemImage: "rectangle.stack")
          }
        }
        Section {
          NavigationLink(value: AppSection.settings) {
            Label("Settings", systemImage: "gearshape")
          }
        }
      }
      .listStyle(.sidebar)
      .navigationTitle("Hydraulophone")
      .navigationSplitViewColumnWidth(min: 210, ideal: 250, max: 320)
    } detail: {
      sectionPage(selectedSection)
    }
    .navigationSplitViewStyle(.balanced)
    .modifier(CatalogSearchField(input: searchInput))
    .safeAreaInset(edge: .bottom, spacing: 0) { floatingPlayer }
  }

  private var sidebarSelection: Binding<AppSection?> {
    Binding(
      get: { selectedSection },
      set: { if let section = $0 { selectedSection = section } }
    )
  }

  private var tabs: some View {
    TabView(selection: $selectedSection) {
      sectionPage(.home)
        .tabItem {
          Label("Home", systemImage: "house")
        }
        .tag(AppSection.home)

      sectionPage(.search)
        .tabItem {
          Label("Search", systemImage: "magnifyingglass")
        }
        .tag(AppSection.search)

      sectionPage(.library)
        .tabItem {
          Label("Library", systemImage: "rectangle.stack")
        }
        .tag(AppSection.library)

      sectionPage(.settings)
        .tabItem {
          Label("Settings", systemImage: "gearshape")
        }
        .tag(AppSection.settings)
    }
  }

  @ViewBuilder
  private func sectionPage(_ section: AppSection) -> some View {
    Group {
      switch section {
      case .home:
        if model.isOfflineOnly {
          TrackNavigationStack {
            DownloadsView(downloads: model.downloads, offlineOnly: true, title: "Home")
          }
        } else {
          HomeView(
            catalogSessionID: model.catalogSessionID,
            isSessionTransitioning: model.isSessionTransitioning
          )
          .id(model.catalogSessionID)
        }
      case .search:
        if model.isOfflineOnly {
          TrackNavigationStack {
            DownloadsView(downloads: model.downloads, offlineOnly: true, title: "Search")
          }
        } else {
          SearchView(service: musicService)
            .id(model.catalogSessionID)
        }
      case .library:
        if previewDownloads {
          TrackNavigationStack {
            DownloadsView(downloads: model.downloads, offlineOnly: true, title: "Library")
          }
        } else {
          LibraryView(service: musicService, downloads: model.downloads)
            .id(model.catalogSessionID)
        }
      case .settings:
        SettingsView()
      }
    }
    .environment(\.pendingTrackDestination, section == selectedSection ? $pendingDestination : nil)
    .safeAreaInset(edge: .bottom, spacing: 0) {
      if needsTabPlayer { floatingPlayer }
    }
  }

  private var needsTabPlayer: Bool {
    #if targetEnvironment(macCatalyst)
      false
    #else
      return horizontalSizeClass != .regular
    #endif
  }

  private var previewDownloads: Bool {
    #if DEBUG
      ProcessInfo.processInfo.arguments.contains("-HydraulophoneOfflineFixture")
        && ProcessInfo.processInfo.arguments.contains("-HydraulophonePreviewDownloads")
    #else
      false
    #endif
  }

  private var floatingPlayer: some View {
    Group {
      if hasCurrentSong {
        MiniPlayerView(playback: playback, open: openPlayer)
          .environment(\.openTrackDestination, openCatalog)
          .frame(maxWidth: 720)
          .padding(.horizontal, 16)
          .padding(.vertical, 8)
          .frame(maxWidth: .infinity)
      }
    }
  }

  private func openCatalog(_ destination: TrackDestination) {
    #if DEBUG
      traceCatalogNavigation("shell request")
    #endif
    isShowingNowPlaying = false
    pendingDestination = destination
  }

  private func openPlayer() {
    isShowingNowPlaying = true
  }
}

private enum AppSection: Hashable {
  case home
  case search
  case library
  case settings
}