fix: 浮动按钮在边界状态下越界崩溃

This commit is contained in:
HapeLee
2026-06-12 15:33:25 +08:00
parent 1a99cdbac3
commit 4e33693627
2 changed files with 29 additions and 7 deletions
@@ -29,8 +29,8 @@ fun ReadBookSearchBar(
val searchVisible = state.isShowingSearchResult &&
!(state.menuVisible && state.menuState.currentRoute != ReadBookMenuRoute.Main)
val hasResults = state.searchResultList.isNotEmpty()
val currentIndex = state.searchResultIndex
val totalResults = state.searchResultList.size
val currentIndex = state.searchResultIndex.coerceIn(0, (totalResults - 1).coerceAtLeast(0))
Box(Modifier.fillMaxSize()) {
// Left FAB - previous result
@@ -45,9 +45,11 @@ fun ReadBookSearchBar(
AppFloatingActionButton(
onClick = {
val prevIndex = currentIndex - 1
val result = state.searchResultList.getOrNull(prevIndex)
?: return@AppFloatingActionButton
onIntent(
ReadBookIntent.NavigateToSearchResult(
state.searchResultList[prevIndex], prevIndex
result, prevIndex
)
)
},
@@ -75,9 +77,11 @@ fun ReadBookSearchBar(
AppFloatingActionButton(
onClick = {
val nextIndex = currentIndex + 1
val result = state.searchResultList.getOrNull(nextIndex)
?: return@AppFloatingActionButton
onIntent(
ReadBookIntent.NavigateToSearchResult(
state.searchResultList[nextIndex], nextIndex
result, nextIndex
)
)
},
@@ -231,9 +231,11 @@ class ReadBookViewModel(
is ReadBookIntent.HideSearchMenu -> _uiState.update { it.copy(searchMenuVisible = false) }
is ReadBookIntent.SetSearchResults -> {
_uiState.update {
val results = intent.results.toImmutableList()
val index = intent.index.coerceSearchResultIndex(results.size)
it.copy(
searchResultList = intent.results.toImmutableList(),
searchResultIndex = intent.index,
searchResultList = results,
searchResultIndex = index,
isShowingSearchResult = true,
searchMenuVisible = true,
menuState = ReadBookMenuState(),
@@ -243,7 +245,13 @@ class ReadBookViewModel(
}
is ReadBookIntent.SetSearchResultIndex -> {
_uiState.update { it.copy(searchResultIndex = intent.index) }
_uiState.update {
it.copy(
searchResultIndex = intent.index.coerceSearchResultIndex(
it.searchResultList.size
)
)
}
}
is ReadBookIntent.SetShowingSearchResult -> {
@@ -252,7 +260,13 @@ class ReadBookViewModel(
is ReadBookIntent.NavigateToSearchResult -> {
ReadBook.saveCurrentBookProgress()
_uiState.update { it.copy(searchResultIndex = intent.index) }
_uiState.update {
it.copy(
searchResultIndex = intent.index.coerceSearchResultIndex(
it.searchResultList.size
)
)
}
navigateToSearchResult(intent.result)
}
@@ -3466,3 +3480,7 @@ private const val TITLE_BAR_ICON_KEY = "icons"
private const val TOOL_BUTTON_PREFS = "tool_button_config"
private const val TOOL_BUTTON_KEY = "tool_buttons"
private const val DEFAULT_ENABLED_BUTTON_COUNT = 5
private fun Int.coerceSearchResultIndex(resultSize: Int): Int {
return if (resultSize <= 0) 0 else coerceIn(0, resultSize - 1)
}