CustomButtonsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/CustomButtonsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.player23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.database.DbCustomButton6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.util.nowMillis8import kotlinx.coroutines.flow.MutableStateFlow9import kotlinx.coroutines.flow.StateFlow10import kotlinx.coroutines.flow.asStateFlow11import kotlinx.coroutines.flow.distinctUntilChangedBy12import kotlinx.coroutines.launch1314/** Custom player buttons, ordered by position. */15internal class CustomButtonsViewModel(private val database: YokanDatabase) : ViewModel() {16 private val _buttons = MutableStateFlow(load())17 val buttons: StateFlow<List<DbCustomButton>> = _buttons.asStateFlow()1819 init {20 // The player and the add-button deep link write buttons too.21 viewModelScope.launch { database.snapshots().distinctUntilChangedBy { it.customButtons }.collect { reload() } }22 }2324 fun save(button: DbCustomButton) = write { database.upsertCustomButton(button.copy(updatedAt = nowMillis())) }2526 fun remove(buttonId: Long) = write { database.removeCustomButton(buttonId) }2728 /** Makes [buttonId] the only favourite. */29 fun setFavourite(buttonId: Long) = write {30 _buttons.value.forEach { database.upsertCustomButton(it.copy(isFavourite = it.id == buttonId, updatedAt = nowMillis())) }31 }3233 fun move(buttonId: Long, targetIndex: Int) = write {34 val ordered = _buttons.value.toMutableList()35 val index = ordered.indexOfFirst { it.id == buttonId }36 val target = targetIndex.coerceIn(0, ordered.lastIndex.coerceAtLeast(0))37 if (index < 0 || target == index) return@write38 ordered.add(target, ordered.removeAt(index))39 ordered.forEachIndexed { newIndex, button ->40 if (button.position != newIndex) database.upsertCustomButton(button.copy(position = newIndex, updatedAt = nowMillis()))41 }42 }4344 // Writes publish synchronously so a dropped drag row never snaps back for a frame.45 private inline fun write(block: () -> Unit) {46 block()47 reload()48 }4950 private fun reload() {51 _buttons.value = load()52 }5354 private fun load(): List<DbCustomButton> = database.customButtons().sortedBy { it.position }55}56