git.iko.soy/opencode-android
on f9ed438 help sign in
75 lines 2.5 kB history raw
1package soy.iko.opencode.ui.server
3import androidx.lifecycle.ViewModel
4import androidx.lifecycle.viewModelScope
5import soy.iko.opencode.data.model.ServerProfile
6import soy.iko.opencode.di.AppContainer
7import kotlinx.coroutines.flow.MutableStateFlow
8import kotlinx.coroutines.flow.StateFlow
9import kotlinx.coroutines.flow.asStateFlow
10import kotlinx.coroutines.flow.first
11import kotlinx.coroutines.launch
12import java.util.UUID
14data class ServerEditState(
15 val id: String? = null,
16 val label: String = "",
17 val baseUrl: String = "",
18 val username: String = "",
19 val password: String = "",
20 val loaded: Boolean = false,
21) {
22 val canSave: Boolean get() = baseUrl.isNotBlank()
23 val isNew: Boolean get() = id == null
26class ServerEditViewModel(
27 private val container: AppContainer,
28 private val profileId: String?,
29) : ViewModel() {
31 private val _state = MutableStateFlow(ServerEditState(id = profileId))
32 val state: StateFlow<ServerEditState> = _state.asStateFlow()
34 init {
35 viewModelScope.launch {
36 if (profileId != null) {
37 val existing = container.profileStore.profiles.first().firstOrNull { it.id == profileId }
38 if (existing != null) {
39 _state.value = ServerEditState(
40 id = existing.id,
41 label = existing.label,
42 baseUrl = existing.baseUrl,
43 username = existing.username.orEmpty(),
44 password = existing.password.orEmpty(),
45 loaded = true,
46 )
47 return@launch
48 }
49 }
50 _state.value = _state.value.copy(loaded = true)
51 }
52 }
54 fun update(transform: (ServerEditState) -> ServerEditState) {
55 _state.value = transform(_state.value)
56 }
58 fun save(onDone: () -> Unit) {
59 val s = _state.value
60 if (!s.canSave) return
61 viewModelScope.launch {
62 container.profileStore.save(
63 ServerProfile(
64 id = s.id ?: UUID.randomUUID().toString(),
65 label = s.label.trim(),
66 baseUrl = s.baseUrl.trim(),
67 username = s.username.trim().takeIf { it.isNotBlank() },
68 password = s.password.takeIf { it.isNotEmpty() },
69 lastUsed = 0,
70 ),
71 )
72 onDone()
73 }
74 }