react-native-audio-browser 0.2.0-next.61 → 0.2.0-next.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +16 -6
  2. package/android/src/main/java/com/audiobrowser/player/PlaybackStateMachine.kt +9 -6
  3. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +0 -5
  4. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerInvalidationTest.kt +14 -0
  5. package/android/src/test/java/com/audiobrowser/player/PlaybackStateMachineTest.kt +7 -6
  6. package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +35 -0
  7. package/ios/Browser/BrowserManager.swift +22 -7
  8. package/ios/HybridAudioBrowser+Options.swift +14 -0
  9. package/ios/HybridAudioBrowser.swift +4 -1
  10. package/ios/Player/DeferredSeek.swift +4 -1
  11. package/ios/Player/Player.swift +10 -7
  12. package/ios/Tests/DeferredSeekTests.swift +12 -4
  13. package/ios/Tests/PlayerPolicyTests.swift +86 -0
  14. package/lib/commonjs/CLAUDE.md +2 -2
  15. package/lib/commonjs/features/sleepTimer.js +8 -12
  16. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  17. package/lib/commonjs/utils/LazyNativeEmitter.js +3 -3
  18. package/lib/commonjs/utils/NativeUpdatedValue.js +10 -13
  19. package/lib/commonjs/utils/NativeUpdatedValue.js.map +1 -1
  20. package/lib/commonjs/utils/useNativeUpdatedValue.js +12 -20
  21. package/lib/commonjs/utils/useNativeUpdatedValue.js.map +1 -1
  22. package/lib/commonjs/utils/useNativeValueRefreshedBy.js +10 -5
  23. package/lib/commonjs/utils/useNativeValueRefreshedBy.js.map +1 -1
  24. package/lib/module/CLAUDE.md +2 -2
  25. package/lib/module/features/sleepTimer.js +9 -13
  26. package/lib/module/features/sleepTimer.js.map +1 -1
  27. package/lib/module/utils/LazyNativeEmitter.js +3 -3
  28. package/lib/module/utils/NativeUpdatedValue.js +10 -13
  29. package/lib/module/utils/NativeUpdatedValue.js.map +1 -1
  30. package/lib/module/utils/useNativeUpdatedValue.js +13 -21
  31. package/lib/module/utils/useNativeUpdatedValue.js.map +1 -1
  32. package/lib/module/utils/useNativeValueRefreshedBy.js +11 -6
  33. package/lib/module/utils/useNativeValueRefreshedBy.js.map +1 -1
  34. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  35. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts +3 -3
  36. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts +4 -13
  37. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts.map +1 -1
  38. package/lib/typescript/src/utils/useNativeUpdatedValue.d.ts +4 -4
  39. package/lib/typescript/src/utils/useNativeUpdatedValue.d.ts.map +1 -1
  40. package/lib/typescript/src/utils/useNativeValueRefreshedBy.d.ts +3 -4
  41. package/lib/typescript/src/utils/useNativeValueRefreshedBy.d.ts.map +1 -1
  42. package/package.json +1 -1
  43. package/src/CLAUDE.md +2 -2
  44. package/src/features/sleepTimer.test.ts +25 -26
  45. package/src/features/sleepTimer.ts +9 -9
  46. package/src/utils/LazyNativeEmitter.ts +3 -3
  47. package/src/utils/NativeUpdatedValue.ts +10 -13
  48. package/src/utils/useNativeUpdatedValue.test.ts +30 -22
  49. package/src/utils/useNativeUpdatedValue.ts +13 -17
  50. package/src/utils/useNativeValueRefreshedBy.test.ts +68 -0
  51. package/src/utils/useNativeValueRefreshedBy.ts +13 -6
@@ -81,10 +81,12 @@ class BrowserManager {
81
81
 
82
82
  private val contentCache = LruCache<String, ResolvedTrack>(20)
83
83
 
84
- // Moves on clearContentCache, so a fetch that outlives one caches nothing. Separate from
85
- // layerGeneration, which also moves on every path change. Car browses run on IO threads and the
86
- // clear on the JS thread: each check and its write hold [cacheLock].
84
+ // Moves on clearContentCache, so a fetch that outlives one caches nothing; [pageGenerations]
85
+ // does the same for one path, and is cleared only together with a move of this. Separate from
86
+ // layerGeneration, which also moves on every path change. Car browses run on IO threads and
87
+ // the clear on the JS thread: each check and its write hold [cacheLock].
87
88
  @Volatile private var contentGeneration = 0
89
+ private val pageGenerations = HashMap<String, Int>()
88
90
  private var tabsGeneration = -1
89
91
  private val cacheLock = Any()
90
92
 
@@ -453,11 +455,13 @@ class BrowserManager {
453
455
  Timber.d("Content cache MISS for path='$normalizedPath'")
454
456
  }
455
457
 
456
- val generation = contentGeneration
458
+ val generation = synchronized(cacheLock) { pageGeneration(normalizedPath) }
457
459
  val resolvedTrack = resolveUncached(normalizedPath)
458
460
 
459
461
  synchronized(cacheLock) {
460
- if (generation == contentGeneration) contentCache.put(normalizedPath, resolvedTrack)
462
+ if (generation == pageGeneration(normalizedPath)) {
463
+ contentCache.put(normalizedPath, resolvedTrack)
464
+ }
461
465
  }
462
466
 
463
467
  cacheChildren(resolvedTrack)
@@ -470,10 +474,15 @@ class BrowserManager {
470
474
  require(!BrowserPathHelper.isContextual(path)) {
471
475
  "invalidateContentCache() expects a container path, not a contextual path: $path"
472
476
  }
473
- contentCache.remove(path)
477
+ synchronized(cacheLock) {
478
+ pageGenerations[path] = (pageGenerations[path] ?: 0) + 1
479
+ contentCache.remove(path)
480
+ }
474
481
  Timber.d("Invalidated content cache for path='$path'")
475
482
  }
476
483
 
484
+ private fun pageGeneration(path: String) = contentGeneration to pageGenerations[path]
485
+
477
486
  /**
478
487
  * Clears every cached page and the last search, which nothing else evicts, and re-resolves the
479
488
  * tabs, resolver layers and "view more" title on the next request. A fetch in flight caches
@@ -482,6 +491,7 @@ class BrowserManager {
482
491
  fun clearContentCache() {
483
492
  synchronized(cacheLock) {
484
493
  contentGeneration += 1
494
+ pageGenerations.clear()
485
495
  contentCache.evictAll()
486
496
  lastSearch = null
487
497
  }
@@ -64,7 +64,10 @@ object PlaybackStateMachine {
64
64
  }
65
65
  is PlaybackEvent.MediaItemTransition ->
66
66
  when {
67
- !event.hasTrack -> emptyList()
67
+ // An emptied queue. STOPPED holds: the service clears the queue just before stop(), and
68
+ // the events arrive after it.
69
+ !event.hasTrack ->
70
+ if (current == PlaybackState.STOPPED) emptyList() else listOf(PlaybackState.NONE)
68
71
  // Already playing (gapless auto-advance): no IsPlayingChanged follows, so run the whole
69
72
  // sequence here or the state sticks on LOADING.
70
73
  event.isPlaying ->
@@ -74,11 +77,11 @@ object PlaybackStateMachine {
74
77
  is PlaybackEvent.ShouldPlayWhenReadyChanged ->
75
78
  when {
76
79
  // stop() and a natural end both clear the intent themselves; STOPPED and ENDED must not
77
- // turn into PAUSED.
78
- !event.shouldPlayWhenReady &&
79
- current != PlaybackState.STOPPED &&
80
- current != PlaybackState.ENDED -> listOf(PlaybackState.PAUSED)
81
- !event.shouldPlayWhenReady -> emptyList()
80
+ // turn into PAUSED. A pause holds ERROR, as on iOS.
81
+ !event.shouldPlayWhenReady ->
82
+ if (current in setOf(PlaybackState.STOPPED, PlaybackState.ENDED, PlaybackState.ERROR))
83
+ emptyList()
84
+ else listOf(PlaybackState.PAUSED)
82
85
  // Resuming while ExoPlayer still buffers: no state change of its own follows, and the
83
86
  // READY after it is dropped while playing, so report the load now.
84
87
  current == PlaybackState.PAUSED && event.exoState == MediaPlayer.STATE_BUFFERING ->
@@ -150,11 +150,6 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
150
150
  override fun onEvents(media3Player: MediaPlayer, events: MediaPlayer.Events) {
151
151
  // In event order: each setPlaybackState emits.
152
152
  for (i in 0 until events.size()) {
153
- // A new item clears the prior error even when no state transition follows (queue emptied).
154
- if (events[i] == MediaPlayer.EVENT_MEDIA_ITEM_TRANSITION) {
155
- player.playbackError = null
156
- }
157
-
158
153
  val event =
159
154
  when (events[i]) {
160
155
  MediaPlayer.EVENT_PLAYBACK_STATE_CHANGED ->
@@ -139,6 +139,20 @@ class BrowserManagerInvalidationTest {
139
139
  assertNull(browserManager.getTabs())
140
140
  }
141
141
 
142
+ @Test
143
+ fun `a page in flight across invalidateContentCache of its path is not cached`() {
144
+ across({ browserManager.invalidateContentCache("/page") }) { browserManager.resolve("/page") }
145
+
146
+ assertEquals("nl", runBlocking { browserManager.resolve("/page") }.title)
147
+ }
148
+
149
+ @Test
150
+ fun `a page in flight across invalidateContentCache of another path is cached`() {
151
+ across({ browserManager.invalidateContentCache("/other") }) { browserManager.resolve("/page") }
152
+
153
+ assertEquals("en", runBlocking { browserManager.resolve("/page") }.title)
154
+ }
155
+
142
156
  @Test
143
157
  fun `a page in flight across a config change is cached`() {
144
158
  across({ browserManager.config = config() }) { browserManager.resolve("/page") }
@@ -146,17 +146,17 @@ class PlaybackStateMachineTest {
146
146
  }
147
147
 
148
148
  @Test
149
- fun `a transition without a track is suppressed`() {
150
- assertEquals(
151
- emptyList<PlaybackState>(),
152
- on(PlaybackEvent.MediaItemTransition(hasTrack = false, isPlaying = true)),
153
- )
149
+ fun `a transition without a track is none, except from stopped`() {
150
+ val emptied = PlaybackEvent.MediaItemTransition(hasTrack = false, isPlaying = false)
151
+ assertEquals(listOf(PlaybackState.NONE), on(emptied, from = PlaybackState.ERROR))
152
+ assertEquals(listOf(PlaybackState.NONE), on(emptied, from = PlaybackState.ENDED))
153
+ assertEquals(emptyList<PlaybackState>(), on(emptied, from = PlaybackState.STOPPED))
154
154
  }
155
155
 
156
156
  // MARK: shouldPlayWhenReady / isPlaying
157
157
 
158
158
  @Test
159
- fun `losing shouldPlayWhenReady pauses except from stopped or ended`() {
159
+ fun `losing shouldPlayWhenReady pauses except from stopped, ended or error`() {
160
160
  val paused =
161
161
  PlaybackEvent.ShouldPlayWhenReadyChanged(
162
162
  shouldPlayWhenReady = false,
@@ -165,6 +165,7 @@ class PlaybackStateMachineTest {
165
165
  assertEquals(listOf(PlaybackState.PAUSED), on(paused, from = PlaybackState.PLAYING))
166
166
  assertEquals(emptyList<PlaybackState>(), on(paused, from = PlaybackState.STOPPED))
167
167
  assertEquals(emptyList<PlaybackState>(), on(paused, from = PlaybackState.ENDED))
168
+ assertEquals(emptyList<PlaybackState>(), on(paused, from = PlaybackState.ERROR))
168
169
  assertEquals(
169
170
  emptyList<PlaybackState>(),
170
171
  on(
@@ -33,6 +33,8 @@ import org.junit.rules.TemporaryFolder
33
33
  import org.junit.runner.RunWith
34
34
  import org.mockito.Mockito.mock
35
35
  import org.mockito.Mockito.mockingDetails
36
+ import org.mockito.Mockito.never
37
+ import org.mockito.Mockito.verify
36
38
  import org.robolectric.RobolectricTestRunner
37
39
  import org.robolectric.RuntimeEnvironment
38
40
  import org.robolectric.Shadows.shadowOf
@@ -89,6 +91,30 @@ class PlayerRetryTest {
89
91
  assertFalse(player.hasPlayedCache)
90
92
  }
91
93
 
94
+ @Test
95
+ fun `a pause keeps a terminal error`() {
96
+ failTerminally()
97
+ val failed = player.getPlayback()
98
+
99
+ player.pause()
100
+ shadowOf(Looper.getMainLooper()).idle()
101
+
102
+ assertEquals(failed, player.getPlayback())
103
+ verify(callbacks, never()).onPlaybackError(null)
104
+ }
105
+
106
+ @Test
107
+ fun `emptying the queue clears a terminal error`() {
108
+ failTerminally()
109
+
110
+ player.clear()
111
+ shadowOf(Looper.getMainLooper()).idle()
112
+
113
+ assertEquals(Playback(PlaybackState.NONE, null), player.getPlayback())
114
+ verify(callbacks).onPlaybackError(null)
115
+ verify(callbacks).onPlaybackChanged(Playback(PlaybackState.NONE, null))
116
+ }
117
+
92
118
  @Test
93
119
  fun `a player that gave up stays stopped when the network returns`() {
94
120
  connectivity.setNetworkCapabilities(wifi, capabilities(validated = false))
@@ -120,6 +146,15 @@ class PlayerRetryTest {
120
146
  assertEquals(PlaybackState.ERROR, player.playbackState)
121
147
  }
122
148
 
149
+ /** A closed port: the load fails at once, and with no retries the failure is terminal. */
150
+ private fun failTerminally() {
151
+ play("https://127.0.0.1:9/stream", RetryPolicy.Limited(maxRetries = 0))
152
+ idleUntil("a terminal error") {
153
+ ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
154
+ player.playbackState == PlaybackState.ERROR
155
+ }
156
+ }
157
+
123
158
  private fun play(src: String, retryPolicy: RetryPolicy = RetryPolicy.Default) {
124
159
  player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
125
160
  player.setCallbacks(callbacks)
@@ -18,8 +18,10 @@ final class BrowserManager {
18
18
 
19
19
  // Entries are unhydrated; `resolve` hydrates favorites on the way out.
20
20
  private let contentCache = LRUCache<String, ResolvedTrack>(maxSize: 20)
21
- // Moves on `invalidateAll`, so a fetch that outlives one caches nothing.
21
+ // Moves on `clearContent`, so a fetch that outlives one caches nothing; `pageGenerations` does
22
+ // the same for one path, and is cleared only together with a move of this.
22
23
  private var contentGeneration = 0
24
+ private var pageGenerations: [String: Int] = [:]
23
25
 
24
26
  // Raw results, never hydrated ones: `FavoriteSet.hydrate` skips a track whose `favorited` is
25
27
  // already set, so a hydrated slot would keep the favorites of the first search.
@@ -145,10 +147,12 @@ final class BrowserManager {
145
147
  return favorites.hydrate(cached)
146
148
  }
147
149
 
148
- let generation = contentGeneration
150
+ let generation = pageGeneration(normalizedPath)
149
151
  let resolvedTrack = try await pages.resolve(normalizedPath)
150
152
 
151
- if generation == contentGeneration { contentCache.set(normalizedPath, value: resolvedTrack) }
153
+ if generation == pageGeneration(normalizedPath) {
154
+ contentCache.set(normalizedPath, value: resolvedTrack)
155
+ }
152
156
 
153
157
  return favorites.hydrate(resolvedTrack)
154
158
  }
@@ -160,18 +164,20 @@ final class BrowserManager {
160
164
  "invalidateContentCache() expects a container path, not a contextual path: \(path)",
161
165
  )
162
166
  }
167
+ pageGenerations[path, default: 0] += 1
163
168
  contentCache.remove(path)
164
169
  }
165
170
 
171
+ private func pageGeneration(_ path: String) -> (Int, Int?) {
172
+ (contentGeneration, pageGenerations[path])
173
+ }
174
+
166
175
  /// Clears every cache and the resolved request layers, then re-queries the tabs and reloads
167
176
  /// the current path, independently: a failed reload goes to `reloadFailed` with its path, and
168
177
  /// a failed tabs query keeps the current tabs.
169
178
  func invalidateAll(reloadFailed: @escaping @MainActor (Error, String) async -> Void) {
170
- contentCache.clear()
171
- contentGeneration &+= 1
179
+ clearContent()
172
180
  requests.invalidateLayers()
173
- lastSearchKey = nil
174
- lastSearchResults = nil
175
181
  Task { _ = try? await queryTabs() }
176
182
  Task {
177
183
  do {
@@ -182,6 +188,15 @@ final class BrowserManager {
182
188
  }
183
189
  }
184
190
 
191
+ /// Clears the cached pages and the last search; a fetch in flight caches nothing.
192
+ func clearContent() {
193
+ contentCache.clear()
194
+ contentGeneration &+= 1
195
+ pageGenerations.removeAll()
196
+ lastSearchKey = nil
197
+ lastSearchResults = nil
198
+ }
199
+
185
200
  /// The app's `formatNavigationError` result, or the default when it has none or it fails.
186
201
  func formatted(_ error: NavigationError, path: String) async -> FormattedNavigationError {
187
202
  let fallback = error.defaultFormatted()
@@ -16,6 +16,8 @@ public extension HybridAudioBrowser {
16
16
  self.audioSession.configure(options.ios)
17
17
 
18
18
  // A re-setup replaces the player, so the outgoing one is torn down first. No-op on first setup.
19
+ let oldPlayer = player
20
+ oldPlayer?.sleepTimerManager.clear()
19
21
  destroyPlayer()
20
22
 
21
23
  let newEngine = AVPlayerEngine(
@@ -43,6 +45,18 @@ public extension HybridAudioBrowser {
43
45
  if let mode = options.repeatMode { pendingRepeatMode = mode }
44
46
  if let intent = options.playWhenReady { pendingPlayWhenReady = intent }
45
47
  applyPendingPlayerState()
48
+ // The new player starts at its defaults without emitting them; listeners still hold the old values.
49
+ if let oldPlayer {
50
+ if oldPlayer.repeatMode != newPlayer.repeatMode {
51
+ playerDidChangeRepeatMode(RepeatModeChangedEvent(repeatMode: newPlayer.repeatMode))
52
+ }
53
+ if oldPlayer.shuffleEnabled != newPlayer.shuffleEnabled {
54
+ playerDidChangeShuffleEnabled(newPlayer.shuffleEnabled)
55
+ }
56
+ if oldPlayer.playWhenReady != newPlayer.playWhenReady {
57
+ playerDidChangePlayWhenReady(newPlayer.playWhenReady)
58
+ }
59
+ }
46
60
  // The stored options outlive the player, so a re-setup applies them to the new one.
47
61
  applyOptions()
48
62
  playerAndConfiguredBrowser.check()
@@ -121,7 +121,10 @@ public class HybridAudioBrowser: HybridAudioBrowserSpec, @unchecked Sendable {
121
121
  // Copied on the setter's thread: the Task below outlives this call, and Nitro can reassign
122
122
  // `configuration` (a C++ struct holding std::string/std::function) from the JS thread.
123
123
  let configuredPath = configuration.path
124
- onMainActor { browserManager.config = BrowserConfig(from: configuration) }
124
+ onMainActor {
125
+ browserManager.config = BrowserConfig(from: configuration)
126
+ browserManager.clearContent()
127
+ }
125
128
 
126
129
  Task { @MainActor in
127
130
  playerAndConfiguredBrowser.check()
@@ -50,7 +50,10 @@ struct DeferredSeek {
50
50
  return time
51
51
  }
52
52
 
53
- mutating func land() -> Landing {
53
+ /// A seek cut short, as when its item fails, keeps the target for the reload; a seek that cut it
54
+ /// short lands in its place.
55
+ mutating func land(finished: Bool) -> Landing {
56
+ guard finished else { return .none }
54
57
  switch state {
55
58
  case .inFlight:
56
59
  state = .idle
@@ -384,6 +384,7 @@ final class Player {
384
384
  shouldResumeAfterInterruption = false
385
385
  transition(.stopped)
386
386
  setPlayWhenReady(false)
387
+ deferredSeek.reset()
387
388
  if currentTrack?.live != true { seek(to: 0) }
388
389
  }
389
390
 
@@ -665,7 +666,7 @@ final class Player {
665
666
  func seekToLiveEdge() {
666
667
  guard currentTrack?.live == true, engine.hasItem else { return }
667
668
  if let edge = engine.liveEdge {
668
- engine.seek(to: edge) { _ in }
669
+ seek(to: edge)
669
670
  } else {
670
671
  reloadResolving(startFromCurrentTime: false)
671
672
  }
@@ -680,7 +681,7 @@ final class Player {
680
681
  completion(false)
681
682
  return
682
683
  }
683
- seekDidLand()
684
+ seekDidLand(finished: finished)
684
685
  completion(finished)
685
686
  }
686
687
  }
@@ -692,8 +693,8 @@ final class Player {
692
693
  return true
693
694
  }
694
695
 
695
- private func seekDidLand() {
696
- switch deferredSeek.land() {
696
+ private func seekDidLand(finished: Bool) {
697
+ switch deferredSeek.land(finished: finished) {
697
698
  case .done:
698
699
  if state == .loading { transition(.loadSeekCompleted) }
699
700
  case let .reseek(time):
@@ -719,10 +720,12 @@ final class Player {
719
720
  }
720
721
 
721
722
  /// A restart from a terminal error begins a new Load on a new AVPlayer; automatic retries
722
- /// never get here in .error, since the retry loop keeps the state non-terminal. `time` is held
723
- /// as the deferred seek before the loading transition saves the snapshot.
723
+ /// never get here in .error, since the retry loop keeps the state non-terminal. `time`, else the
724
+ /// pending target, is held as the deferred seek before the loading transition saves the snapshot.
724
725
  private func prepareForReload(resumingAt time: TimeInterval?) {
725
726
  load?.reloadOnPlay = false
727
+ let target = time ?? deferredSeek.target
728
+ deferredSeek.reset()
726
729
  if state == .error {
727
730
  beginLoad()
728
731
  clearItem()
@@ -732,7 +735,7 @@ final class Player {
732
735
  engine.dropAsset()
733
736
  engine.pause()
734
737
  }
735
- if let time { deferredSeek.capture(time) }
738
+ if let target { deferredSeek.capture(target) }
736
739
  transition(.trackLoading)
737
740
  }
738
741
 
@@ -18,7 +18,7 @@ struct DeferredSeekTests {
18
18
  #expect(seek.begin() == 30)
19
19
  #expect(seek.state == .inFlight(30))
20
20
  #expect(seek.defersReady)
21
- #expect(seek.land() == .done)
21
+ #expect(seek.land(finished: true) == .done)
22
22
  #expect(seek.state == .idle)
23
23
  #expect(!seek.defersReady)
24
24
  }
@@ -45,15 +45,23 @@ struct DeferredSeekTests {
45
45
  _ = seek.begin()
46
46
  seek.capture(50)
47
47
  #expect(seek.state == .pending(50))
48
- #expect(seek.land() == .reseek(50))
48
+ #expect(seek.land(finished: true) == .reseek(50))
49
49
  #expect(seek.state == .inFlight(50))
50
- #expect(seek.land() == .done)
50
+ #expect(seek.land(finished: true) == .done)
51
+ }
52
+
53
+ @Test func anUnfinishedLandingKeepsTheTarget() {
54
+ var seek = DeferredSeek()
55
+ seek.capture(30)
56
+ _ = seek.begin()
57
+ #expect(seek.land(finished: false) == .none)
58
+ #expect(seek.state == .inFlight(30))
51
59
  }
52
60
 
53
61
  /// A seek issued while playing is never deferred, so its landing has nothing to do.
54
62
  @Test func aLandingWithNothingInFlightIsNone() {
55
63
  var seek = DeferredSeek()
56
- #expect(seek.land() == .none)
64
+ #expect(seek.land(finished: true) == .none)
57
65
  }
58
66
 
59
67
  @Test func resetDropsTheTargetAndInvalidatesSeeksInFlight() {
@@ -74,6 +74,92 @@ struct PlayerSeekingTests {
74
74
  #expect(player.state == .loading)
75
75
  }
76
76
 
77
+ @Test func aCompletionFromBeforeAReloadIsDropped() throws {
78
+ let engine = MockPlayerEngine()
79
+ let player = makePlayer(engine: engine, retries: false)
80
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], startPositionMs: 25000)
81
+ engine.seekResult = nil
82
+ engine.hasItem = true
83
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
84
+
85
+ player.reloadResolving(startFromCurrentTime: true)
86
+ engine.completeSeeks(true)
87
+ engine.completeSeeks(true)
88
+
89
+ #expect(player.state == .loading)
90
+ #expect(player.deferredSeek.target == 25)
91
+ #expect(engine.seekCalls == [25])
92
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
93
+ #expect(engine.seekCalls == [25, 25])
94
+ }
95
+
96
+ @Test func aStartSeekCutShortWaitsForTheNextItem() throws {
97
+ let engine = MockPlayerEngine()
98
+ let player = makePlayer(engine: engine, retries: false)
99
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], startPositionMs: 25000)
100
+ engine.seekResult = nil
101
+ engine.hasItem = true
102
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
103
+
104
+ engine.completeSeeks(false)
105
+
106
+ #expect(player.state == .loading)
107
+ #expect(player.deferredSeek.target == 25)
108
+ #expect(engine.seekCalls == [25])
109
+ }
110
+
111
+ /// A media-load retry passes no position, so the start in flight is what it resumes from.
112
+ @Test func aReloadThatDoesNotResumeKeepsTheStartInFlight() throws {
113
+ let engine = MockPlayerEngine()
114
+ let player = makePlayer(engine: engine, retries: false)
115
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], startPositionMs: 25000)
116
+ engine.seekResult = nil
117
+ engine.hasItem = true
118
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
119
+
120
+ player.reloadResolving(startFromCurrentTime: false)
121
+ engine.completeSeeks(true)
122
+
123
+ #expect(player.state == .loading)
124
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
125
+ #expect(engine.seekCalls == [25, 25])
126
+ }
127
+
128
+ @Test func aPlayRightAfterAStopDuringTheStartSeekStartsOver() throws {
129
+ let engine = MockPlayerEngine()
130
+ let player = makePlayer(engine: engine, retries: false)
131
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], startPositionMs: 25000)
132
+ engine.seekResult = nil
133
+ engine.hasItem = true
134
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
135
+
136
+ player.stop()
137
+ player.play()
138
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
139
+
140
+ #expect(engine.seekCalls == [25, 0])
141
+ #expect(player.deferredSeek.target == nil)
142
+ }
143
+
144
+ @Test func theLiveEdgeDuringALoadWaitsForTheStartSeek() throws {
145
+ let engine = MockPlayerEngine()
146
+ let player = makePlayer(engine: engine, retries: false)
147
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.m3u8", title: "T", live: true)], startPositionMs: 25000)
148
+ engine.seekResult = nil
149
+ engine.hasItem = true
150
+ engine.hasLoadedAsset = true
151
+ engine.liveEdge = 120
152
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
153
+
154
+ player.seekToLiveEdge()
155
+ #expect(engine.seekCalls == [25])
156
+ engine.completeSeeks(true)
157
+ engine.completeSeeks(true)
158
+
159
+ #expect(engine.seekCalls == [25, 120])
160
+ #expect(player.state != .loading)
161
+ }
162
+
77
163
  @Test func theLiveEdgeIsTheSeekableWindowsEnd_orAReconnectWithoutOne() throws {
78
164
  let (player, engine, _) = try makePlaying(live: true)
79
165
  engine.liveEdge = 120
@@ -39,8 +39,8 @@ error until it was unified.
39
39
  Two emitter classes, picked by what the event _is_:
40
40
 
41
41
  - `NativeUpdatedValue` — state with a current value (playback, options,
42
- progress). Subscribes to native at module load so no update is missed, and
43
- caches `lastValue` so hooks can read synchronously.
42
+ progress). Subscribes to native at module load so no update is missed; hooks
43
+ read the matching getter, never a cached payload.
44
44
  - `LazyNativeEmitter` — discrete events with no current value (remote controls,
45
45
  gate hits). Assigns the native callback on the first `addListener`, so an
46
46
  event nobody listens to costs nothing.
@@ -94,15 +94,12 @@ const onSleepTimerChanged = exports.onSleepTimerChanged = _NativeUpdatedValue.Na
94
94
  * @returns true if any sleep timer is active, false otherwise
95
95
  */
96
96
  function useSleepTimerActive() {
97
+ const eventCountAtRender = (0, _react.useRef)(onSleepTimerChanged.eventCount);
97
98
  const [isActive, setIsActive] = (0, _react.useState)(() => getSleepTimer() !== null);
98
99
  (0, _react.useEffect)(() => {
99
- // Re-sync before subscribing: a change between the initial read above and this effect would
100
- // otherwise be missed for good. `undefined` means nothing has fired yet, whereas `null` is a
101
- // real value — the timer being cleared — so it has to re-sync too.
102
- const {
103
- lastValue
104
- } = onSleepTimerChanged;
105
- if (lastValue !== undefined) setIsActive(lastValue !== null);
100
+ if (onSleepTimerChanged.eventCount !== eventCountAtRender.current) {
101
+ setIsActive(getSleepTimer() !== null);
102
+ }
106
103
  return onSleepTimerChanged.addListener(timer => {
107
104
  setIsActive(timer !== null);
108
105
  });
@@ -123,17 +120,16 @@ function useSleepTimerActive() {
123
120
  function useSleepTimer(params) {
124
121
  const updateInterval = params?.updateInterval ?? 1000;
125
122
  const inactive = params?.inactive ?? false;
123
+ const eventCountAtRender = (0, _react.useRef)(onSleepTimerChanged.eventCount);
126
124
  const [state, setState] = (0, _react.useState)(() => {
127
125
  const timerState = getSleepTimer();
128
126
  return addSecondsLeft(timerState);
129
127
  });
130
128
  const time = state && 'time' in state ? state.time : undefined;
131
129
  (0, _react.useEffect)(() => {
132
- // Re-sync before subscribing — see useSleepTimerActive.
133
- const {
134
- lastValue
135
- } = onSleepTimerChanged;
136
- if (lastValue !== undefined) setState(addSecondsLeft(lastValue));
130
+ if (onSleepTimerChanged.eventCount !== eventCountAtRender.current) {
131
+ setState(addSecondsLeft(getSleepTimer()));
132
+ }
137
133
  return onSleepTimerChanged.addListener(event => {
138
134
  setState(addSecondsLeft(event));
139
135
  });
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_native","_NativeUpdatedValue","getSleepTimer","nativeBrowser","setSleepTimer","seconds","options","fadeDuration","setSleepTimerToEndOfTrack","clearSleepTimer","onSleepTimerChanged","exports","NativeUpdatedValue","emitterize","cb","useSleepTimerActive","isActive","setIsActive","useState","useEffect","lastValue","undefined","addListener","timer","useSleepTimer","params","updateInterval","inactive","state","setState","timerState","addSecondsLeft","time","event","update","sleepTimer","result","secondsLeft","clear","initialTimeoutId","setTimeout","intervalId","setInterval","clearTimeout","clearInterval","Math","max","round","Date","now"],"sourceRoot":"../../../src","sources":["features/sleepTimer.ts"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,mBAAA,GAAAF,OAAA;AAEA;;AAEA;AACA;AACA;;AAMA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;;AAGA;;AAEA;AACA;AACA;AACO,SAASG,aAAaA,CAAA,EAAe;EAC1C,OAAOC,qBAAa,CAACD,aAAa,CAAC,CAAC;AACtC;;AAEA;AACA;AACA;;AAaA;AACA;AACA;AACA;AACA;AACO,SAASE,aAAaA,CAC3BC,OAAe,EACfC,OAA2B,EACrB;EACNH,qBAAa,CAACC,aAAa,CAACC,OAAO,EAAEC,OAAO,EAAEC,YAAY,CAAC;AAC7D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,yBAAyBA,CAAA,EAAS;EAChDL,qBAAa,CAACK,yBAAyB,CAAC,CAAC;AAC3C;;AAEA;AACA;AACA;AACA;AACO,SAASC,eAAeA,CAAA,EAAY;EACzC,OAAON,qBAAa,CAACM,eAAe,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AEpC,OAAOE,KAAK;AACd;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAKA,SAASG,cAAcA,CAACH,KAAiB,EAA+B;EACtE,IAAI,CAACA,KAAK,EAAE,OAAOP,SAAS;EAC5B,IAAI,MAAM,IAAIO,KAAK,EAAE;IACnB,OAAO;MACL,GAAGA,KAAK;MACRS,WAAW,EAAEQ,IAAI,CAACC,GAAG,CAAC,CAAC,EAAED,IAAI,CAACE,KAAK,CAAC,CAACnB,KAAK,CAACI,IAAI,GAAGgB,IAAI,CAACC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;IACvE,CAAC;EACH;EACA,OAAOrB,KAAK;AACd","ignoreList":[]}
1
+ {"version":3,"names":["_react","require","_native","_NativeUpdatedValue","getSleepTimer","nativeBrowser","setSleepTimer","seconds","options","fadeDuration","setSleepTimerToEndOfTrack","clearSleepTimer","onSleepTimerChanged","exports","NativeUpdatedValue","emitterize","cb","useSleepTimerActive","eventCountAtRender","useRef","eventCount","isActive","setIsActive","useState","useEffect","current","addListener","timer","useSleepTimer","params","updateInterval","inactive","state","setState","timerState","addSecondsLeft","time","undefined","event","update","sleepTimer","result","secondsLeft","clear","initialTimeoutId","setTimeout","intervalId","setInterval","clearTimeout","clearInterval","Math","max","round","Date","now"],"sourceRoot":"../../../src","sources":["features/sleepTimer.ts"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,mBAAA,GAAAF,OAAA;AAEA;;AAEA;AACA;AACA;;AAMA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;;AAGA;;AAEA;AACA;AACA;AACO,SAASG,aAAaA,CAAA,EAAe;EAC1C,OAAOC,qBAAa,CAACD,aAAa,CAAC,CAAC;AACtC;;AAEA;AACA;AACA;;AAaA;AACA;AACA;AACA;AACA;AACO,SAASE,aAAaA,CAC3BC,OAAe,EACfC,OAA2B,E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AAGC,UAAU,CACjC,MAAM;MACJN,MAAM,CAAC,CAAC;MACRO,UAAU,GAAGC,WAAW,CAACR,MAAM,EAAET,cAAc,CAAC;IAClD,CAAC,EACDA,cAAc,GAAIM,IAAI,GAAGN,cAC3B,CAAC;IACD,IAAIgB,UAAsD;IAC1D,MAAMH,KAAK,GAAGA,CAAA,KAAM;MAClBK,YAAY,CAACJ,gBAAgB,CAAC;MAC9B,IAAIE,UAAU,EAAEG,aAAa,CAACH,UAAU,CAAC;IAC3C,CAAC;IACDP,MAAM,CAAC,CAAC;IACR,OAAOI,KAAK;EACd,CAAC,EAAE,CAACZ,QAAQ,EAAEK,IAAI,EAAEN,cAAc,CAAC,CAAC;EAEpC,OAAOE,KAAK;AACd;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAKA,SAASG,cAAcA,CAACH,KAAiB,EAA+B;EACtE,IAAI,CAACA,KAAK,EAAE,OAAOK,SAAS;EAC5B,IAAI,MAAM,IAAIL,KAAK,EAAE;IACnB,OAAO;MACL,GAAGA,KAAK;MACRU,WAAW,EAAEQ,IAAI,CAACC,GAAG,CAAC,CAAC,EAAED,IAAI,CAACE,KAAK,CAAC,CAACpB,KAAK,CAACI,IAAI,GAAGiB,IAAI,CAACC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;IACvE,CAAC;EACH;EACA,OAAOtB,KAAK;AACd","ignoreList":[]}
@@ -9,9 +9,9 @@ exports.LazyNativeEmitter = void 0;
9
9
  * `onRemoteSeek`, …) and `onGate`. Subscribe with {@link addListener}; the
10
10
  * returned function unsubscribes. The emitter is not callable itself.
11
11
  *
12
- * Native starts delivering the event only once the first listener is added,
13
- * and nothing is cached: there is no `lastValue`. The other `on*` exports use
14
- * `NativeUpdatedValue`, which listens from module load.
12
+ * Native starts delivering the event only once the first listener is added.
13
+ * The other `on*` exports use `NativeUpdatedValue`, which listens from module
14
+ * load.
15
15
  *
16
16
  * @example
17
17
  * ```typescript