From 3dcefe6feda23db87b32e66d5c6bf34f4adf0f63 Mon Sep 17 00:00:00 2001 From: Nebojsa Vuksic Date: Wed, 30 Jul 2025 14:33:53 +0200 Subject: [PATCH] Fix: Preselecting location in MyLocations list --- .../services/MyLocationsViewModel.kt | 2 ++ .../weatherApp/ui/WeatherAppSample.kt | 24 ++++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/MyLocationsViewModel.kt b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/MyLocationsViewModel.kt index c876b86..9297b27 100644 --- a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/MyLocationsViewModel.kt +++ b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/MyLocationsViewModel.kt @@ -84,6 +84,8 @@ internal class MyLocationsViewModel(cs: CoroutineScope) : MyLocationsViewModelAp } override fun onLocationSelected(selectedLocationIndex: Int) { + if (this.selectedLocationIndex.value == selectedLocationIndex) return + this.selectedLocationIndex.value = selectedLocationIndex onReloadWeatherForecast() diff --git a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/ui/WeatherAppSample.kt b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/ui/WeatherAppSample.kt index f355fa3..d617b09 100644 --- a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/ui/WeatherAppSample.kt +++ b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/ui/WeatherAppSample.kt @@ -80,12 +80,24 @@ private fun LeftColumn( val listState = rememberSelectableLazyListState() - // TODO Check why preselection isn't working + // JEWEL-938 This will trigger on SelectableLazyColum's `onSelectedIndexesChange` callback LaunchedEffect(myLocations) { - listState - .selectedKeys = myLocations - .mapIndexedNotNull { index, item -> if (item.isSelected) index else null } - .toSet() + var lastActiveItemIndex = -1 + val selectedItemKeys = mutableSetOf() + myLocations.forEachIndexed { index, location -> + if (location.isSelected) { + if (lastActiveItemIndex == -1) { + // Only the first selected item should be active + lastActiveItemIndex = index + } + // Must match the key used in the `items()` call's `key` parameter to ensure correct item identity. + selectedItemKeys.add(location.location.label) + } + } + // Sets the first selected item as an active item to avoid triggering on click event when user clocks on it + listState.lastActiveItemIndex = lastActiveItemIndex + // Sets keys of selected items + listState.selectedKeys = selectedItemKeys } SelectableLazyColumn( @@ -99,7 +111,7 @@ private fun LeftColumn( ) { items( items = myLocations, - key = { item -> item }, + key = { item -> item.location.label }, ) { item -> ContentItemRow(