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

geesawra.industries/hydraulophone

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

0
0
main
434 lines · 12.8 KB Raw History
import HydraulophoneCore
import SwiftUI

/// The first screen's inputs are supplied by the app shell once session
/// restoration is wired there. Defaults keep `HomeView()` a valid, previewable
/// screen and allow the view to observe the shared `AppModel` from the
/// environment.
struct HomeView: View {
  @EnvironmentObject private var model: AppModel
  @StateObject private var viewModel: HomeViewModel

  private let catalogSessionID: Int
  private let isSessionTransitioning: Bool

  init(
    viewModel: HomeViewModel? = nil,
    catalogSessionID: Int = 0,
    isSessionTransitioning: Bool = false
  ) {
    _viewModel = StateObject(wrappedValue: viewModel ?? HomeViewModel())
    self.catalogSessionID = catalogSessionID
    self.isSessionTransitioning = isSessionTransitioning
  }

  var body: some View {
    TrackNavigationStack {
      Group {
        if model.isRestoringSession {
          restoringState
        } else if isSessionTransitioning {
          transitionState
        } else {
          homeContent
        }
      }
      .background(HydraulophoneTheme.groupedBackground)
      .navigationTitle("Home")
      .navigationBarTitleDisplayMode(.large)
      .task(id: requestKey) {
        await synchronize()
      }
      .onChange(of: model.session?.isAuthenticated) { _, _ in
        // This is synchronous and happens before the next catalog request, so
        // signing out cannot leave the previous audience visible.
        viewModel.clear()
      }
      .onChange(of: catalogSessionID) { _, _ in
        viewModel.clear()
      }
      .onChange(of: isSessionTransitioning) { _, transitioning in
        if transitioning {
          viewModel.clear()
        }
      }
      .navigationDestination(for: Playlist.self) { playlist in
        // CollectionTracksView is supplied by the shared collection screen.
        CollectionTracksView(playlist: playlist)
      }
      .navigationDestination(for: Album.self) { album in
        // Albums retain their server-provided browse ID; no VL prefix is
        // manufactured in Home.
        CollectionTracksView(album: album)
      }
    }
    .tint(HydraulophoneTheme.accent)
  }

  private var requestKey: HomeRequestKey {
    HomeRequestKey(
      isRestoringSession: model.isRestoringSession,
      isAuthenticated: model.session?.isAuthenticated == true,
      catalogSessionID: catalogSessionID,
      isSessionTransitioning: isSessionTransitioning
    )
  }

  private func synchronize() async {
    guard
      !model.isRestoringSession,
      !isSessionTransitioning,
      model.session?.isAuthenticated == true
    else {
      viewModel.clear()
      return
    }

    let catalogService = model.musicService as? any PaginatedCatalogMusicService
    viewModel.setService(catalogService)
    await viewModel.load(
      audience: .authenticated,
      sessionID: catalogSessionID,
      policy: .cacheFirst
    )
  }

  private func reload() async {
    guard
      !model.isRestoringSession,
      !isSessionTransitioning,
      model.session?.isAuthenticated == true
    else { return }
    await viewModel.load(
      audience: .authenticated,
      sessionID: catalogSessionID,
      policy: .reload
    )
  }

  private var restoringState: some View {
    VStack(spacing: 14) {
      ProgressView()
        .controlSize(.large)
      Text("Restoring your music session…")
        .font(.subheadline)
        .foregroundStyle(.secondary)
    }
    .frame(maxWidth: .infinity, minHeight: 280)
    .accessibilityElement(children: .combine)
    .accessibilityLabel("Restoring your music session")
  }

  private var transitionState: some View {
    VStack(spacing: 14) {
      ProgressView()
        .controlSize(.large)
      Text("Switching music sessions…")
        .font(.subheadline)
        .foregroundStyle(.secondary)
    }
    .frame(maxWidth: .infinity, minHeight: 280)
    .accessibilityElement(children: .combine)
    .accessibilityLabel("Switching music sessions")
  }

  private var homeContent: some View {
    ScrollView {
      LazyVStack(alignment: .leading, spacing: 28) {
        content
      }
      .padding(.horizontal, 20)
      .padding(.bottom, 28)
    }
    .refreshable {
      await reload()
    }
  }

  @ViewBuilder
  private var content: some View {
    if viewModel.isLoading && viewModel.sections.isEmpty {
      HomeLoadingSkeleton()
    } else if let errorMessage = viewModel.errorMessage, viewModel.sections.isEmpty {
      HydraulophoneErrorState(
        title: "Home could not load",
        message: errorMessage,
        retry: {
          Task { await reload() }
        }
      )
      .frame(maxWidth: .infinity, minHeight: 260)
    } else if viewModel.sections.isEmpty {
      ContentUnavailableView(
        "Nothing to play yet",
        systemImage: "music.note.list",
        description: Text("Your music service has not provided any Home shelves yet.")
      )
      .frame(maxWidth: .infinity, minHeight: 260)
    } else {
      if let errorMessage = viewModel.errorMessage {
        HomeRefreshErrorBanner(
          message: errorMessage,
          retry: {
            Task { await reload() }
          }
        )
      }

      ForEach(viewModel.sections) { section in
        HomeSectionView(
          section: section,
          play: play,
          playNext: { model.playback.enqueueNext($0) },
          addToQueue: { model.playback.enqueue($0) }
        )
      }

      paginationFooter
    }
  }

  @ViewBuilder
  private var paginationFooter: some View {
    if viewModel.isLoadingMore {
      ProgressView("Loading more…")
        .frame(maxWidth: .infinity)
        .padding(.vertical, 10)
        .accessibilityElement(children: .combine)
        .accessibilityLabel("Loading more Home content")
    } else if let errorMessage = viewModel.loadMoreErrorMessage {
      VStack(spacing: 8) {
        Text(errorMessage)
          .font(.footnote)
          .foregroundStyle(.secondary)
          .multilineTextAlignment(.center)
        Button("Try Again") {
          Task { await viewModel.retryLoadMore() }
        }
        .buttonStyle(.bordered)
      }
      .frame(maxWidth: .infinity)
      .padding(.vertical, 8)
      .accessibilityElement(children: .contain)
      .accessibilityLabel("Could not load more Home content")
    } else if viewModel.hasMore {
      ProgressView("Loading more Home content…")
        .frame(maxWidth: .infinity)
        .padding(.vertical, 10)
        .accessibilityElement(children: .combine)
        .accessibilityLabel("Loading more Home content")
        .onAppear {
          Task { await viewModel.loadMore() }
        }
    }
  }

  private func play(_ song: Song, in section: HomeSection) {
    let songs = section.items.compactMap { item -> Song? in
      guard case .song(let song) = item else { return nil }
      return song
    }
    guard let index = songs.firstIndex(of: song) else { return }
    model.playback.setQueue(songs, startAt: index)
  }
}

private struct HomeRequestKey: Hashable {
  let isRestoringSession: Bool
  let isAuthenticated: Bool
  let catalogSessionID: Int
  let isSessionTransitioning: Bool
}

private struct HomeSectionView: View {
  let section: HomeSection
  let play: (Song, HomeSection) -> Void
  let playNext: (Song) -> Void
  let addToQueue: (Song) -> Void

  var body: some View {
    VStack(alignment: .leading, spacing: 12) {
      VStack(alignment: .leading, spacing: 3) {
        Text(section.title)
          .font(.title3.weight(.bold))
        if let subtitle = section.subtitle, !subtitle.isEmpty {
          Text(subtitle)
            .font(.subheadline)
            .foregroundStyle(.secondary)
            .lineLimit(2)
        }
      }
      .frame(maxWidth: .infinity, alignment: .leading)

      ScrollView(.horizontal, showsIndicators: false) {
        LazyHStack(alignment: .top, spacing: 14) {
          ForEach(section.items) { item in
            HomeCatalogCard(
              item: item,
              play: {
                if case .song(let song) = item {
                  play(song, section)
                }
              },
              playNext: playNext,
              addToQueue: addToQueue
            )
          }
        }
        .padding(.vertical, 2)
      }
      .scrollClipDisabled()
    }
  }
}

private struct HomeCatalogCard: View {
  @EnvironmentObject private var model: AppModel
  let item: CatalogItem
  let play: () -> Void
  let playNext: (Song) -> Void
  let addToQueue: (Song) -> Void

  var body: some View {
    switch item {
    case .song(let song):
      Button(action: play) {
        HomeSongCard(song: song)
      }
      .buttonStyle(.plain)
      .accessibilityIdentifier("home.song.\(song.id)")
      .accessibilityLabel("Play \(song.title) by \(song.artist)")
      .accessibilityHint("Starts playback with this Home shelf")
      .songActions(
        song, playNext: { playNext(song) }, addToQueue: { addToQueue(song) })
    case .playlist(let playlist):
      NavigationLink(value: playlist) {
        HomeCollectionCard(
          artworkURL: playlist.thumbnailURL,
          title: playlist.title,
          subtitle: playlist.subtitle,
          kind: "Playlist"
        )
      }
      .buttonStyle(.plain)
      .accessibilityIdentifier("home.playlist.\(playlist.id)")
      .accessibilityLabel("Open playlist \(playlist.title)")
      .accessibilityHint("Shows the songs in this playlist")
    case .album(let album):
      NavigationLink(value: album) {
        HomeCollectionCard(
          artworkURL: album.thumbnailURL,
          title: album.title,
          subtitle: album.subtitle,
          kind: "Album"
        )
      }
      .buttonStyle(.plain)
      .accessibilityIdentifier("home.album.\(album.id)")
      .accessibilityLabel("Open album \(album.title)")
      .accessibilityHint("Shows the songs in this album")
    }
  }
}

private struct HomeSongCard: View {
  let song: Song

  var body: some View {
    VStack(alignment: .leading, spacing: 8) {
      ArtworkView(url: song.thumbnailURL, size: 148, cornerRadius: 14)
      Text(song.title)
        .font(.body.weight(.semibold))
        .lineLimit(2)
        .multilineTextAlignment(.leading)
      Text(song.artist)
        .font(.subheadline)
        .foregroundStyle(.secondary)
        .lineLimit(1)
    }
    .frame(width: 148, alignment: .leading)
    .contentShape(Rectangle())
  }
}

private struct HomeCollectionCard: View {
  let artworkURL: URL?
  let title: String
  let subtitle: String?
  let kind: String

  var body: some View {
    VStack(alignment: .leading, spacing: 8) {
      ArtworkView(url: artworkURL, size: 148, cornerRadius: 14)
      Text(title)
        .font(.body.weight(.semibold))
        .lineLimit(2)
        .multilineTextAlignment(.leading)
      Text(subtitle.flatMap { $0.isEmpty ? nil : $0 } ?? kind)
        .font(.subheadline)
        .foregroundStyle(.secondary)
        .lineLimit(1)
    }
    .frame(width: 148, alignment: .leading)
    .contentShape(Rectangle())
  }
}

private struct HomeLoadingSkeleton: View {
  var body: some View {
    VStack(alignment: .leading, spacing: 26) {
      ForEach(0..<2, id: \.self) { section in
        VStack(alignment: .leading, spacing: 12) {
          RoundedRectangle(cornerRadius: 5)
            .fill(HydraulophoneTheme.cardFill)
            .frame(width: section == 0 ? 155 : 185, height: 22)
          ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 14) {
              ForEach(0..<3, id: \.self) { _ in
                VStack(alignment: .leading, spacing: 8) {
                  RoundedRectangle(cornerRadius: 14)
                    .fill(HydraulophoneTheme.cardFill)
                    .frame(width: 148, height: 148)
                  RoundedRectangle(cornerRadius: 4)
                    .fill(HydraulophoneTheme.cardFill)
                    .frame(width: 120, height: 16)
                  RoundedRectangle(cornerRadius: 4)
                    .fill(HydraulophoneTheme.cardFill)
                    .frame(width: 88, height: 14)
                }
              }
            }
          }
        }
      }
    }
    .redacted(reason: .placeholder)
    .accessibilityElement(children: .combine)
    .accessibilityLabel("Loading Home shelves")
  }
}

private struct HomeRefreshErrorBanner: View {
  let message: String
  let retry: () -> Void

  var body: some View {
    HStack(alignment: .top, spacing: 10) {
      Image(systemName: "exclamationmark.triangle.fill")
        .foregroundStyle(.orange)
        .accessibilityHidden(true)
      Text(message)
        .font(.footnote)
        .foregroundStyle(.secondary)
        .frame(maxWidth: .infinity, alignment: .leading)
      Button("Retry", action: retry)
        .font(.footnote.weight(.semibold))
        .frame(minWidth: 44, minHeight: 44)
    }
    .padding(.horizontal, 12)
    .padding(.vertical, 8)
    .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
    .accessibilityElement(children: .combine)
    .accessibilityLabel("Home refresh failed. \(message)")
  }
}