fix: handle invalid index in centerItem and return null for out-of-range subtitle indices

This commit is contained in:
2026-06-22 19:16:24 +02:00
parent 8926b3237b
commit feb3896727
3 changed files with 5 additions and 3 deletions
@@ -4,5 +4,5 @@ class GetCurrentSubtitleIndexUseCase {
operator fun invoke( operator fun invoke(
subtitle: Subtitle, subtitle: Subtitle,
progressMs: Long, progressMs: Long,
): Int = subtitle.lines.indexOfLast { it.startMs <= progressMs } ): Int? = subtitle.lines.indexOfLast { it.startMs <= progressMs }.takeIf { it >= 0 }
} }
@@ -21,7 +21,7 @@ class GetCurrentSubtitleIndexUseCaseTest {
@Test @Test
fun returns_minus_one_before_the_first_cue() { fun returns_minus_one_before_the_first_cue() {
assertEquals(-1, getCurrentSubtitleIndex(subtitle, progressMs = -1)) assertEquals(null, getCurrentSubtitleIndex(subtitle, progressMs = -1))
} }
@Test @Test
@@ -39,6 +39,6 @@ class GetCurrentSubtitleIndexUseCaseTest {
@Test @Test
fun returns_minus_one_for_an_empty_subtitle() { fun returns_minus_one_for_an_empty_subtitle() {
assertEquals(-1, getCurrentSubtitleIndex(Subtitle(emptyList()), progressMs = 1_000)) assertEquals(null, getCurrentSubtitleIndex(Subtitle(emptyList()), progressMs = 1_000))
} }
} }
@@ -98,6 +98,8 @@ fun SubtitleList(
} }
private suspend fun LazyListState.centerItem(index: Int) { private suspend fun LazyListState.centerItem(index: Int) {
if (index < 0 || index >= this.layoutInfo.totalItemsCount) return
val info = this.layoutInfo val info = this.layoutInfo
val viewportCenter = (info.viewportStartOffset + info.viewportEndOffset) / 2 val viewportCenter = (info.viewportStartOffset + info.viewportEndOffset) / 2
val item = info.visibleItemsInfo.firstOrNull { it.index == index } val item = info.visibleItemsInfo.firstOrNull { it.index == index }