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

geesawra.industries/hydraulophone

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

0
0
main
759 lines · 24.4 KB Raw History
import AVKit
import Combine
import Foundation
import HydraulophoneCore
import SwiftUI

/// The environment wrapper preserves the existing `NowPlayingView()` call
/// site. The screen observes structural playback changes; transport and lyrics
/// observe the clock independently so it does not rebuild scrolling content.
struct NowPlayingView: View {
  @EnvironmentObject private var model: AppModel

  var body: some View {
    ObservedNowPlayingView(
      playback: model.playback, lyricsService: model.musicService as? any LyricsProviding
    )
    .id(model.catalogSessionID)
  }
}

private struct ObservedNowPlayingView: View {
  @EnvironmentObject private var model: AppModel
  @Environment(\.dismiss) private var dismiss
  private let playback: PlaybackController
  @StateObject private var screenState: NowPlayingScreenState
  @Namespace private var artworkTransition
  @Environment(\.accessibilityReduceMotion) private var reduceMotion
  @Environment(\.dynamicTypeSize) private var dynamicTypeSize
  @State private var queueScrollRequest = 0
  @State private var queueEditMode: EditMode = .inactive
  @State private var showingLyrics = false
  @StateObject private var lyrics: LyricsViewModel

  init(playback: PlaybackController, lyricsService: (any LyricsProviding)?) {
    self.playback = playback
    _screenState = StateObject(wrappedValue: NowPlayingScreenState(playback: playback))
    _lyrics = StateObject(wrappedValue: LyricsViewModel(service: lyricsService))
  }

  var body: some View {
    TrackNavigationStack {
      Group {
        if let song = screenState.snapshot.song {
          GeometryReader { proxy in
            let artworkSide = max(0, min(proxy.size.width - 48, proxy.size.height * 0.55, 520))
            ZStack {
              if showingLyrics {
                VStack(spacing: 12) {
                  lyricsHeader(for: song)
                    .dynamicTypeSize(...DynamicTypeSize.xxxLarge)
                  NowPlayingLyricsViewport(playback: playback, lyrics: lyrics, song: song)
                    .id(song.id)
                  if let errorMessage = playback.errorMessage {
                    playbackError(message: errorMessage)
                      .lineLimit(2)
                      .dynamicTypeSize(...DynamicTypeSize.xxxLarge)
                  }
                }
                .padding(.vertical, 12)
                .transition(.opacity)
              } else {
                ScrollViewReader { scroll in
                  List {
                    nowPlayingIdentity(
                      for: song,
                      artworkSide: dynamicTypeSize.isAccessibilitySize
                        ? min(artworkSide, 120) : artworkSide
                    )
                    .frame(maxWidth: .infinity)
                    .listRowInsets(EdgeInsets())
                    .listRowSeparator(.hidden)
                    .listRowBackground(Color.clear)
                    fixedControls
                      .buttonStyle(.plain)
                      .listRowInsets(EdgeInsets())
                      .listRowSeparator(.hidden)
                      .listRowBackground(Color.clear)
                    NowPlayingQueueContent(
                      entries: screenState.snapshot.entries,
                      currentID: screenState.snapshot.currentID, playback: playback
                    )
                  }
                  .listStyle(.plain)
                  .scrollContentBackground(.hidden)
                  .environment(\.editMode, $queueEditMode)
                  .accessibilityIdentifier("playback.scroll")
                  .task(id: queueScrollRequest) {
                    guard queueScrollRequest > 0 else { return }
                    await Task.yield()
                    withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.25)) {
                      scroll.scrollTo("playback.queue", anchor: .top)
                    }
                  }
                }
                .scrollIndicators(.hidden)
                .transition(.opacity)
              }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .padding(.horizontal, 24)
            .clipped()
          }
          .safeAreaInset(edge: .bottom, spacing: 0) {
            if showingLyrics {
              fixedControls
                // Keep a readable lyric viewport at accessibility text sizes.
                // Lyrics themselves retain the listener's full Dynamic Type size.
                .dynamicTypeSize(showingLyrics ? min(dynamicTypeSize, .xxxLarge) : dynamicTypeSize)
            }
          }
        } else {
          ContentUnavailableView(
            "Nothing is playing",
            systemImage: "waveform",
            description: Text("Search for a song and tap it to start listening.")
          )
        }
      }
      .background(HydraulophoneTheme.groupedBackground)
      .navigationTitle("Now Playing")
      .navigationBarTitleDisplayMode(.inline)
      .toolbar {
        #if targetEnvironment(macCatalyst)
          ToolbarItem(placement: .topBarTrailing) {
            Button("Done") {
              dismiss()
            }
            .keyboardShortcut(.cancelAction)
          }
        #endif
        ToolbarItem(placement: .topBarLeading) {
          sleepTimerMenu
        }
        if !showingLyrics, playback.currentSong != nil {
          ToolbarItem(placement: .topBarTrailing) {
            showLyricsButton
          }
        }
      }
    }
    .tint(HydraulophoneTheme.accent)
    .accessibilityAction(.escape) { dismiss() }

  }

  private func nowPlayingIdentity(for song: Song, artworkSide: CGFloat) -> some View {
    VStack(spacing: 16) {
      ArtworkView(
        url: model.downloads.resolvedArtworkURL(for: song), size: artworkSide, cornerRadius: 18,
        imageRequestSize: 520
      )
      .equatable()
      .matchedGeometryEffect(id: "player.artwork", in: artworkTransition)
      .shadow(color: .black.opacity(0.12), radius: 12, y: 6)
      .accessibilityElement()
      .accessibilityLabel("\(song.title) artwork")
      .accessibilityIdentifier("playback.artwork.full")
      songDetails(for: song)
      if let errorMessage = playback.errorMessage {
        playbackError(message: errorMessage)
      }
    }
    .padding(.vertical, 12)
  }

  private var showLyricsButton: some View {
    Button {
      setShowingLyrics(true)
    } label: {
      Image(systemName: "quote.bubble")
        .font(.system(size: 20, weight: .medium))
        .frame(minWidth: 44, minHeight: 44)
    }
    .accessibilityLabel("Show lyrics")
    .accessibilityIdentifier("playback.lyrics.toggle")
  }

  private func lyricsHeader(for song: Song) -> some View {
    HStack(spacing: 12) {
      Button {
        setShowingLyrics(false)
      } label: {
        ArtworkView(
          url: model.downloads.resolvedArtworkURL(for: song), size: 48, cornerRadius: 12,
          imageRequestSize: 520
        )
        .equatable()
        .matchedGeometryEffect(id: "player.artwork", in: artworkTransition)
        .contentShape(Rectangle())
      }
      .buttonStyle(.plain)
      .accessibilityLabel("Show album artwork")
      .accessibilityHint("Returns to the full size album cover")
      .accessibilityIdentifier("playback.artwork")

      VStack(alignment: .leading, spacing: 3) {
        Text(song.title)
          .font(.headline)
          .lineLimit(2)
        ArtistNameLinks(artists: song.artistReferences ?? [], fallback: song.artist, compact: true)
          .font(.subheadline.weight(.semibold))
          .foregroundStyle(.secondary)
          .lineLimit(1)
        if let album = song.album, !album.isEmpty {
          AlbumNameLink(album: song.navigationAlbum, fallback: album, compact: true)
            .font(.caption.weight(.medium))
            .foregroundStyle(.secondary)
            .lineLimit(1)
        }
      }
      .accessibilityElement(children: .contain)
      Spacer(minLength: 0)
    }
  }

  private func setShowingLyrics(_ value: Bool) {
    withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.25)) {
      showingLyrics = value
    }
  }

  private var fixedControls: some View {
    VStack(spacing: 10) {
      NowPlayingPlaybackControls(playback: playback)
      if showingLyrics { queueDock }
    }
  }

  private var sleepTimerMenu: some View {
    Menu {
      ForEach(PlaybackSleepTimer.allCases) { timer in
        Button {
          playback.setSleepTimer(timer)
        } label: {
          if playback.sleepTimer == timer {
            Label(timer.label, systemImage: "checkmark")
          } else {
            Text(timer.label)
          }
        }
      }
      if playback.sleepTimer != nil {
        Button("Cancel Sleep Timer", role: .destructive) { playback.setSleepTimer(nil) }
      }
    } label: {
      Image(systemName: playback.sleepTimer == nil ? "moon.zzz" : "moon.zzz.fill")
        .font(.system(size: 20))
        .frame(minWidth: 44, minHeight: 44)
    }
    .accessibilityLabel("Sleep timer")
    .accessibilityValue(playback.sleepTimer?.label ?? "Off")
  }

  private func songDetails(for song: Song) -> some View {
    VStack(spacing: 5) {
      Text(song.title)
        .font(.title2.weight(.bold))
        .multilineTextAlignment(.center)
        .lineLimit(3)
      VStack(spacing: 3) {
        ArtistNameLinks(
          artists: song.artistReferences ?? [], fallback: song.artist, labelAlignment: .bottom
        )
        .font(.title3.weight(.semibold))
        .foregroundStyle(.secondary)
        .multilineTextAlignment(.center)
        .lineLimit(2)
        if let album = song.album, !album.isEmpty {
          AlbumNameLink(album: song.navigationAlbum, fallback: album, labelAlignment: .top)
            .font(.body.weight(.medium))
            .foregroundStyle(.secondary)
            .multilineTextAlignment(.center)
            .lineLimit(2)
        }
      }
    }
    .frame(maxWidth: .infinity)
    .accessibilityElement(children: .contain)
  }

  private var queueDock: some View {
    Button {
      openQueue()
    } label: {
      HStack(spacing: 12) {
        Image(systemName: "list.bullet")
          .font(.system(size: 22))
        Text("Up Next")
          .font(.subheadline.weight(.semibold))
          .lineLimit(1)
          .minimumScaleFactor(0.8)
        Spacer()
        if !dynamicTypeSize.isAccessibilitySize {
          Text(queueCountLabel)
            .font(.subheadline)
            .foregroundStyle(.secondary)
            .lineLimit(1)
        }
        Image(systemName: "chevron.down")
          .font(.system(size: 12, weight: .semibold))
      }
      .padding(.horizontal, 24)
      .padding(.top, 9)
      .padding(.bottom, 12)
      .frame(maxWidth: .infinity)
    }
    .buttonStyle(.plain)
    .accessibilityLabel("Up Next, \(queueCountLabel)")
    .accessibilityHint("Scrolls to the play queue")
  }

  private func openQueue() {
    setShowingLyrics(false)
    queueScrollRequest += 1
  }

  private var queueCountLabel: String {
    let count = upcomingQueueEntries.count
    return count == 1 ? "1 song" : "\(count) songs"
  }

  private var upcomingQueueEntries: [PlaybackQueueEntry] {
    guard let id = playback.currentQueueEntryID,
      let index = playback.queueEntries.firstIndex(where: { $0.id == id })
    else { return [] }
    return Array(playback.queueEntries.dropFirst(index + 1))
  }

  private func playbackError(message: String) -> some View {
    Text(message)
      .font(.footnote)
      .foregroundStyle(.red)
      .multilineTextAlignment(.center)
      .frame(maxWidth: .infinity)
  }

}

/// A value snapshot keeps playback-clock publications out of queue row rendering.
private struct NowPlayingQueueContent: View, Equatable {
  let entries: [PlaybackQueueEntry]
  let currentID: UUID?
  let playback: PlaybackController
  @State private var confirmingClearQueue = false

  static func == (lhs: Self, rhs: Self) -> Bool {
    lhs.entries == rhs.entries && lhs.currentID == rhs.currentID && lhs.playback === rhs.playback
  }

  private let upcomingQueueEntries: [PlaybackQueueEntry]

  init(entries: [PlaybackQueueEntry], currentID: UUID?, playback: PlaybackController) {
    self.entries = entries
    self.currentID = currentID
    self.playback = playback
    // Derive rows once per structural update. Keep zero-based indices for
    // List's move offsets instead of rebuilding this array during traversal.
    if let index = entries.firstIndex(where: { $0.id == currentID }) {
      upcomingQueueEntries = Array(entries.dropFirst(index + 1))
    } else {
      upcomingQueueEntries = []
    }
  }

  @ViewBuilder var body: some View {
    Section {
      if upcomingQueueEntries.isEmpty {
        Text("No songs queued")
          .foregroundStyle(.secondary)
      } else {
        ForEach(upcomingQueueEntries) { entry in
          NowPlayingQueueRow(entry: entry, playback: playback)
            .equatable()
            .swipeActions {
              Button("Remove", role: .destructive) {
                playback.removeQueueEntry(id: entry.id)
              }
            }
        }
        .onMove { playback.moveUpcoming(from: $0, to: $1) }
      }
    } header: {
      HStack {
        Text("Up Next")
          .font(.title3.weight(.semibold))
          .accessibilityAddTraits(.isHeader)
        Spacer()
        EditButton().disabled(upcomingQueueEntries.isEmpty)
      }
      .textCase(nil)
      .id("playback.queue")
    }
    .listRowBackground(Color.clear)
    if !upcomingQueueEntries.isEmpty {
      Button("Clear Up Next", role: .destructive) { confirmingClearQueue = true }
        .listRowBackground(Color.clear)
        .confirmationDialog("Clear upcoming songs?", isPresented: $confirmingClearQueue) {
          Button("Clear Up Next", role: .destructive) { playback.clearUpcoming() }
        } message: {
          Text("The current song will keep playing.")
        }
    }
  }

}

/// Queue rows compare their occurrence and song metadata, keeping loaded artwork
/// and row layout stable when unrelated player or shell state changes.
private struct NowPlayingQueueRow: View, Equatable {
  let entry: PlaybackQueueEntry
  let playback: PlaybackController

  static func == (lhs: Self, rhs: Self) -> Bool {
    lhs.entry == rhs.entry && lhs.playback === rhs.playback
  }

  var body: some View {
    Button {
      playback.playQueueEntry(id: entry.id)
    } label: {
      HStack(spacing: 12) {
        ArtworkView(url: entry.song.thumbnailURL, size: 48, cornerRadius: 7)
          .equatable()
        VStack(alignment: .leading, spacing: 3) {
          Text(entry.song.title)
            .font(.subheadline.weight(.medium))
            .foregroundStyle(.primary)
            .lineLimit(1)
          Text(entry.song.artist)
            .font(.caption)
            .foregroundStyle(.secondary)
            .lineLimit(1)
          if let album = entry.song.album, !album.isEmpty {
            Text(album)
              .font(.caption)
              .foregroundStyle(.secondary)
              .lineLimit(1)
          }
        }
        Spacer(minLength: 8)
      }
      .frame(minHeight: 52)
      .contentShape(Rectangle())
      .accessibilityElement(children: .combine)
      .accessibilityLabel("Play \(metadata) next")
    }
    .buttonStyle(.plain)
    .songActions(entry.song)
  }

  private var metadata: String {
    [entry.song.title, entry.song.artist, entry.song.album]
      .compactMap { $0 }
      .filter { !$0.isEmpty }
      .joined(separator: ", ")
  }
}

private struct PlaybackRoutePicker: UIViewRepresentable {
  func makeUIView(context: Context) -> AVRoutePickerView {
    let picker = AVRoutePickerView()
    picker.tintColor = UIColor(HydraulophoneTheme.accent)
    picker.activeTintColor = UIColor(HydraulophoneTheme.accent)
    picker.prioritizesVideoDevices = false
    return picker
  }

  func updateUIView(_ uiView: AVRoutePickerView, context: Context) {}
}

/// Only transport controls subscribe to the playback clock. The scrolling list
/// and artwork layout update on song, queue, error, or timer changes instead.
private struct NowPlayingPlaybackControls: View {
  @ObservedObject var playback: PlaybackController
  @Environment(\.accessibilityReduceMotion) private var reduceMotion
  @State private var transportFeedback = 0
  @State private var sliderPreviewPosition: TimeInterval?
  @State private var isSliderEditing = false
  var body: some View {
    VStack(spacing: 10) {
      if let timer = playback.sleepTimer {
        HStack(spacing: 4) {
          Image(systemName: "moon.zzz.fill")
          if let deadline = playback.sleepDeadline {
            Text("Sleep in")
            Text(deadline, style: .timer).monospacedDigit()
          } else {
            Text("Sleep at \(timer.label.lowercased())")
          }
        }
        .font(.caption)
        .foregroundStyle(.secondary)
        .lineLimit(1)
        .minimumScaleFactor(0.75)
      }
      timeline
      transportControls
      playbackModeControls
    }
    .padding(.top, 8)
    .buttonStyle(.plain)
    .onChange(of: playback.currentSong?.id) { _, _ in cancelSliderPreview() }
  }

  private var timeline: some View {
    VStack(spacing: 4) {
      Slider(
        value: sliderValue,
        in: sliderRange,
        onEditingChanged: handleSliderEditingChanged
      )
      .tint(HydraulophoneTheme.accent)
      .accessibilityIdentifier(HydraulophoneAccessibilityID.playbackSeek)
      .accessibilityLabel("Playback position")
      .accessibilityValue(timelineAccessibilityValue)
      .disabled(!isSeekAvailable)
      HStack {
        Text(elapsedLabel)
        Spacer()
        Text(durationLabel)
      }
      .font(.caption)
      .foregroundStyle(.secondary)
      .monospacedDigit()
      .accessibilityHidden(true)
      if playback.hasDurationMismatch {
        Text("Full-track seeking is unavailable for this stream.")
          .font(.caption)
          .foregroundStyle(.secondary)
      }
    }
    .frame(maxWidth: .infinity)
    .padding(.horizontal, 24)
  }

  private var isSeekAvailable: Bool {
    playback.isSeekAvailable
  }

  private var sliderRange: ClosedRange<TimeInterval> {
    playback.duration.isFinite && playback.duration > 0 ? 0...playback.duration : 0...1
  }

  private var sliderValue: Binding<TimeInterval> {
    Binding(
      get: {
        guard playback.elapsedTime.isFinite else { return 0 }
        let position = sliderPreviewPosition ?? playback.pendingSeekTarget ?? playback.elapsedTime
        return min(max(position, 0), sliderRange.upperBound)
      },
      set: { value in
        guard isSeekAvailable, value.isFinite else { return }
        let target = min(max(value, 0), playback.duration)
        if isSliderEditing {
          sliderPreviewPosition = target
        } else {
          sliderPreviewPosition = nil
          playback.seek(to: target)
        }
      }
    )
  }

  private var elapsedLabel: String {
    guard displayedElapsedTime.isFinite, displayedElapsedTime >= 0 else {
      return "0:00"
    }
    return timeString(displayedElapsedTime)
  }

  private var displayedElapsedTime: TimeInterval {
    sliderPreviewPosition ?? playback.pendingSeekTarget ?? playback.elapsedTime
  }

  private func handleSliderEditingChanged(_ editing: Bool) {
    if editing {
      guard isSeekAvailable else { return }
      isSliderEditing = true
      return
    }

    guard isSliderEditing else { return }
    isSliderEditing = false
    let target = sliderPreviewPosition
    sliderPreviewPosition = nil
    guard isSeekAvailable, let target else { return }
    playback.seek(to: target)
  }

  private func cancelSliderPreview() {
    isSliderEditing = false
    sliderPreviewPosition = nil
  }

  private var durationLabel: String {
    guard playback.duration.isFinite, playback.duration > 0 else {
      return "--:--"
    }
    return timeString(playback.duration)
  }

  private var timelineAccessibilityValue: String {
    if playback.isLoading {
      return "Loading playback position"
    }
    guard playback.duration.isFinite, playback.duration > 0 else {
      return "Playback position unavailable"
    }
    return "\(elapsedLabel) of \(durationLabel)"
  }

  private var transportControls: some View {
    HStack(spacing: 22) {
      Button {
        transportFeedback += 1
        playback.previous()
      } label: {
        Image(systemName: "backward.fill")
          .font(.system(size: 22))
          .frame(minWidth: 44, minHeight: 44)
      }
      .accessibilityIdentifier(HydraulophoneAccessibilityID.playbackPrevious)
      .accessibilityLabel("Previous track")
      .disabled(!playback.canSkipPrevious)

      Button {
        transportFeedback += 1
        playback.togglePlayPause()
      } label: {
        Image(systemName: playback.isPlaying || playback.isLoading ? "pause.fill" : "play.fill")
          .font(.system(size: 32, weight: .semibold))
          .frame(width: 68, height: 68)
          .background(HydraulophoneTheme.accent, in: Circle())
          .foregroundStyle(.white)
      }
      .accessibilityIdentifier(HydraulophoneAccessibilityID.playbackPlayPause)
      .accessibilityLabel(playback.isPlaying || playback.isLoading ? "Pause" : "Play")
      .accessibilityHint(
        playback.isPlaying || playback.isLoading ? "Pauses playback" : "Resumes playback"
      )

      Button {
        transportFeedback += 1
        playback.next()
      } label: {
        Image(systemName: "forward.fill")
          .font(.system(size: 22))
          .frame(minWidth: 44, minHeight: 44)
      }
      .accessibilityIdentifier(HydraulophoneAccessibilityID.playbackNext)
      .accessibilityLabel("Next track")
      .disabled(!playback.canSkipNext)
    }
    .frame(maxWidth: .infinity)
    .padding(.horizontal, 24)
    .animation(reduceMotion ? nil : .default, value: playback.isPlaying)
    .sensoryFeedback(.impact(weight: .light), trigger: transportFeedback)
  }

  private var playbackModeControls: some View {
    HStack {
      Button {
        playback.toggleShuffle()
      } label: {
        Image(systemName: "shuffle")
          .font(.system(size: 22))
          .frame(minWidth: 44, minHeight: 44)
      }
      .foregroundStyle(playback.isShuffling ? HydraulophoneTheme.accent : Color.secondary)
      .accessibilityLabel("Shuffle")
      .accessibilityValue(playback.isShuffling ? "On" : "Off")

      Spacer()

      PlaybackRoutePicker()
        .frame(width: 44, height: 44)
        .accessibilityLabel("Audio output")

      Spacer()

      Button {
        playback.cycleRepeatMode()
      } label: {
        Image(systemName: playback.repeatMode == .one ? "repeat.1" : "repeat")
          .font(.system(size: 22))
          .frame(minWidth: 44, minHeight: 44)
      }
      .foregroundStyle(
        playback.repeatMode == .off ? Color.secondary : HydraulophoneTheme.accent
      )
      .accessibilityLabel("Repeat")
      .accessibilityValue(repeatAccessibilityValue)
    }
    .padding(.horizontal, 24)
  }

  private var repeatAccessibilityValue: String {
    switch playback.repeatMode {
    case .off: return "Off"
    case .all: return "All songs"
    case .one: return "Current song"
    }
  }

  private func timeString(_ value: TimeInterval) -> String {
    guard value.isFinite, value >= 0 else { return "0:00" }
    let totalSeconds = Int(value.rounded(.down))
    return "\(totalSeconds / 60):\(String(format: "%02d", totalSeconds % 60))"
  }
}

private struct NowPlayingLyricsViewport: View {
  @ObservedObject var playback: PlaybackController
  @ObservedObject var lyrics: LyricsViewModel
  let song: Song

  var body: some View {
    NowPlayingLyricsView(
      model: lyrics, song: song,
      elapsedTime: playback.pendingSeekTarget ?? playback.elapsedTime,
      canSeek: playback.isSeekAvailable,
      seek: { playback.seek(to: $0) }
    )
  }
}

@MainActor private final class NowPlayingScreenState: ObservableObject {
  struct Snapshot: Equatable {
    let song: Song?
    let entries: [PlaybackQueueEntry]
    let currentID: UUID?
    let error: String?
    let timer: PlaybackSleepTimer?
    let deadline: Date?

    @MainActor init(_ playback: PlaybackController) {
      song = playback.currentSong
      entries = playback.queueEntries
      currentID = playback.currentQueueEntryID
      error = playback.errorMessage
      timer = playback.sleepTimer
      deadline = playback.sleepDeadline
    }
  }

  @Published private(set) var snapshot: Snapshot
  private var subscription: AnyCancellable?

  init(playback: PlaybackController) {
    snapshot = Snapshot(playback)
    // objectWillChange fires before the mutation; delivery on the run loop
    // reads the completed value and coalesces identical screen snapshots.
    subscription = playback.objectWillChange
      .receive(on: RunLoop.main)
      .map { _ in Snapshot(playback) }
      .removeDuplicates()
      .sink { [weak self] in self?.snapshot = $0 }
  }
}