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

geesawra.industries/hydraulophone

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

0
0
main
297 lines · 10.6 KB Raw History
import HydraulophoneCore
import SwiftUI

/// Lyrics use the playback clock supplied by the player. There is no second
/// timer to drift during a pause, seek, interruption, or stream replacement.
struct NowPlayingLyricsView: View {
  @ObservedObject var model: LyricsViewModel
  let song: Song
  let elapsedTime: TimeInterval
  let canSeek: Bool
  let seek: (TimeInterval) -> Void

  @Environment(\.accessibilityReduceMotion) private var reduceMotion
  @Environment(\.accessibilityVoiceOverEnabled) private var voiceOverEnabled
  @State private var retryID = 0
  @State private var lastFollowedIndex: Int?

  var body: some View {
    Group {
      switch model.songID == song.id ? model.state : .idle {
      case .idle, .loading:
        status(title: "Finding the words…", systemImage: "quote.bubble") {
          ProgressView().accessibilityLabel("Loading lyrics")
        }
      case .loaded(let lyrics):
        lyricsContent(lyrics)
      case .unavailable:
        status(title: "Just the music", systemImage: "music.note") {
          Text("Lyrics aren’t available for this song.")
            .font(.subheadline)
            .foregroundStyle(.secondary)
        }
      case .failed(let message):
        status(title: "Couldn’t load lyrics", systemImage: "quote.bubble") {
          Text(message)
            .font(.subheadline)
            .foregroundStyle(.secondary)
          Button("Try Again") { retryID += 1 }
            .font(.subheadline.weight(.semibold))
            .padding(.horizontal, 18)
            .frame(minHeight: 44)
            .lyricsGlass()
            .accessibilityIdentifier("lyrics.retry")
        }
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .task(id: LoadIdentity(songID: song.id, retryID: retryID)) {
      if retryID > 0 {
        await model.retry(song: song)
      } else {
        await model.load(song: song)
      }
    }
  }

  private func lyricsContent(_ lyrics: SongLyrics) -> some View {
    let activeIndex = lyrics.activeLineIndex(at: elapsedTime)
    return ScrollViewReader { scroll in
      VStack(spacing: 0) {
        HStack(spacing: 8) {
          Label(
            lyrics.isSynchronized ? "Live Lyrics" : "Lyrics",
            systemImage: lyrics.isSynchronized ? "waveform" : "quote.bubble"
          )
          .font(.caption.weight(.semibold))
          .foregroundStyle(.secondary)
          Spacer(minLength: 0)
          if lyrics.isSynchronized && !model.isFollowing && !voiceOverEnabled {
            Button {
              model.resumeFollowing()
            } label: {
              Label("Follow Along", systemImage: "play.fill")
                .font(.caption.weight(.semibold))
                .padding(.horizontal, 12)
                .frame(minHeight: 44)
                .lyricsGlass()
            }
            .buttonStyle(.plain)
            .accessibilityIdentifier("lyrics.follow")
            .transition(.opacity)
          } else {
            Text(lyrics.isSynchronized && !voiceOverEnabled ? "" : "Scroll to read")
              .font(.caption)
              .foregroundStyle(.secondary)
          }
        }
        .frame(minHeight: 44)
        .dynamicTypeSize(...DynamicTypeSize.xxxLarge)
        .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: model.isFollowing)

        GeometryReader { geometry in
          ScrollView {
            VStack(alignment: .leading, spacing: lyrics.isSynchronized ? 22 : 16) {
              ForEach(Array(lyrics.lines.enumerated()), id: \.element.id) { index, line in
                NowPlayingLyricRow(
                  line: line, synchronized: lyrics.isSynchronized,
                  active: activeIndex == index,
                  activeWordIndex: activeIndex == index
                    ? line.activeWordIndex(at: elapsedTime) : nil,
                  canSeek: canSeek,
                  seek: { position in
                    seek(position)
                    model.resumeFollowing()
                  }
                )
                .equatable()
                .id(line.id)
              }
              if let source = lyrics.source, !source.isEmpty {
                Text(source)
                  .font(.footnote)
                  .foregroundStyle(.secondary)
                  .padding(.top, 12)
                  .textSelection(.enabled)
              }
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 6)
            .padding(.top, lyrics.isSynchronized ? geometry.size.height * 0.3 : 16)
            .padding(.bottom, lyrics.isSynchronized ? geometry.size.height * 0.5 : 24)
          }
          .scrollIndicators(.hidden)
          .accessibilityIdentifier("lyrics.scroll")
          .modifier(
            LyricsManualScrollObserver {
              if lyrics.isSynchronized { model.userDidScroll() }
            }
          )
          // Small edge overlays avoid masking and compositing the entire
          // scrolling text surface on every animation frame.
          .overlay(alignment: .top) { edgeFade(top: true) }
          .overlay(alignment: .bottom) { edgeFade(top: false) }
          .onAppear {
            follow(lyrics, activeIndex: activeIndex, scroll: scroll, animated: false, force: true)
          }
          .onChange(of: activeIndex) { _, _ in
            follow(lyrics, activeIndex: activeIndex, scroll: scroll)
          }
          .onChange(of: model.isFollowing) { _, following in
            if following { follow(lyrics, activeIndex: activeIndex, scroll: scroll, force: true) }
          }
        }
      }
    }
  }

  private func edgeFade(top: Bool) -> some View {
    LinearGradient(
      colors: top
        ? [HydraulophoneTheme.groupedBackground, .clear]
        : [.clear, HydraulophoneTheme.groupedBackground],
      startPoint: .top, endPoint: .bottom
    )
    .frame(height: top ? 10 : 16)
    .allowsHitTesting(false)
    .accessibilityHidden(true)
  }

  private func follow(
    _ lyrics: SongLyrics, activeIndex: Int?, scroll: ScrollViewProxy,
    animated: Bool = true, force: Bool = false
  ) {
    guard lyrics.isSynchronized, model.isFollowing, !voiceOverEnabled, !lyrics.lines.isEmpty
    else { return }
    // An instrumental gap has no highlighted line, but stays near the last
    // cue instead of sending the reader back to the start of the song.
    let index =
      activeIndex
      ?? lyrics.lines.lastIndex(where: { ($0.startTime ?? 0) <= elapsedTime }) ?? 0
    let previousIndex = lastFollowedIndex
    guard force || previousIndex != index else { return }
    lastFollowedIndex = index
    // Natural cue advances get one short scroll. Seeks and returning from
    // manual browsing land directly, without sweeping through intermediate lines.
    let isAdjacentCue = previousIndex.map { abs($0 - index) == 1 } ?? false
    withAnimation(
      animated && !force && !reduceMotion && isAdjacentCue ? .easeOut(duration: 0.28) : nil
    ) {
      scroll.scrollTo(lyrics.lines[index].id, anchor: .center)
    }
  }

  private func status<Content: View>(
    title: String, systemImage: String, @ViewBuilder content: () -> Content
  ) -> some View {
    ScrollView {
      VStack(spacing: 14) {
        Image(systemName: systemImage)
          .font(.system(size: 32, weight: .light))
          .foregroundStyle(HydraulophoneTheme.accent)
          .accessibilityHidden(true)
        Text(title).font(.title3.weight(.semibold))
        content()
      }
      .multilineTextAlignment(.center)
      .frame(maxWidth: .infinity)
      .padding(.vertical, 32)
    }
    .scrollBounceBehavior(.basedOnSize)
  }

  private struct LoadIdentity: Equatable {
    let songID: String
    let retryID: Int
  }
}

/// Only the newly active line, previous line, or current word needs a text
/// update. Other rows remain stable as the playback clock publishes ticks.
private struct NowPlayingLyricRow: View, Equatable {
  let line: LyricsLine
  let synchronized: Bool
  let active: Bool
  let activeWordIndex: Int?
  let canSeek: Bool
  let seek: (TimeInterval) -> Void

  static func == (lhs: Self, rhs: Self) -> Bool {
    lhs.line == rhs.line && lhs.synchronized == rhs.synchronized
      && lhs.active == rhs.active && lhs.activeWordIndex == rhs.activeWordIndex
      && lhs.canSeek == rhs.canSeek
    // The seek intent targets the same player for this song view's lifetime.
  }

  var body: some View {
    if synchronized, let startTime = line.startTime, canSeek {
      Button {
        seek(startTime)
      } label: {
        lyricText
      }
      .buttonStyle(.plain)
      .accessibilityLabel(line.text.isEmpty ? "Instrumental" : line.text)
      .accessibilityValue(active ? "Current line" : "")
      .accessibilityHint("Plays from this line")
      .accessibilityIdentifier("lyrics.line.\(line.id)")
    } else {
      lyricText
        .accessibilityLabel(line.text.isEmpty && synchronized ? "Instrumental" : line.text)
        .accessibilityValue(active && synchronized ? "Current line" : "")
        .accessibilityIdentifier("lyrics.line.\(line.id)")
        .accessibilityHidden(!synchronized && line.text.isEmpty)
    }
  }

  private var lyricText: some View {
    renderedText
      .font(synchronized ? .title2.weight(.bold) : .title3.weight(.medium))
      .multilineTextAlignment(.leading)
      .fixedSize(horizontal: false, vertical: true)
      .frame(maxWidth: .infinity, minHeight: synchronized ? 44 : 0, alignment: .leading)
      .contentShape(Rectangle())
  }

  private var renderedText: Text {
    guard synchronized, active, !line.words.isEmpty else {
      return Text(line.text.isEmpty ? (synchronized ? "♪" : " ") : line.text)
        .foregroundColor(synchronized && !active ? .secondary : .primary)
    }
    var text = AttributedString()
    for (index, word) in line.words.enumerated() {
      var segment = AttributedString(word.text)
      segment.foregroundColor = index == activeWordIndex ? HydraulophoneTheme.accent : Color.primary
      text.append(segment)
    }
    return Text(text)
  }
}

/// User tracking is distinct from the programmatic scroll animation. On iOS 17
/// a simultaneous drag observes intent without replacing the scroll gesture.
private struct LyricsManualScrollObserver: ViewModifier {
  let onManualScroll: () -> Void

  func body(content: Content) -> some View {
    if #available(iOS 18.0, *) {
      content.onScrollPhaseChange { _, phase in
        if phase == .tracking || phase == .interacting { onManualScroll() }
      }
    } else {
      content.simultaneousGesture(
        DragGesture(minimumDistance: 8).onChanged { _ in onManualScroll() })
    }
  }
}

extension View {
  @ViewBuilder
  func lyricsGlass() -> some View {
    if #available(iOS 26.0, *) {
      glassEffect(.regular.interactive(), in: Capsule())
    } else {
      background(.regularMaterial, in: Capsule())
    }
  }
}