feat: v0.2 - polish, favourites, search, colours, checklists, signing

v0.2 bundles all four phases from the planning session into a single
shippable release. versionCode 2 -> 3, versionName 0.1.1 -> 0.2.

DOMAIN
  - Add NoteColor enum (NONE / BLUE / GREEN / AMBER / RED / PURPLE).
  - Note: isFavorite + color fields; checklistCounts / checklistSummary
    helpers parsing '- [ ]' / '- [x]' lines.
  - NoteRepository: new search(query) + setFavorite(id, value) methods.

DATA
  - NoteEntity: additive @Index isFavorite + colorKey (Short).
  - NoteRepositoryImpl: search uses ObjectBox 'contains' case-insensitive;
    observeAll + search sort favourites-first then updatedAt DESC.

UI
  - NoteListViewModel: debounced(150ms) query -> repository.search;
    openSearch / closeSearch helpers; toggleFavorite.
  - NoteListScreen: search bar in top app bar; star icon + 4dp colour
    stripe per card; checklist summary line ('N open - M done').
  - NoteEditorViewModel: toggleFavorite + setColor; initial-snapshot
    fields captured on first non-null observeById for dirty detection.
  - NoteEditorScreen: BackHandler + AlertDialog 'Discard changes?' on
    unsaved edits; star toggle in top bar; LazyRow of colour swatches.

POLISH
  - Discard-confirm dialog implements Development Plan §5.2.
  - Real release signing config (signingConfigs.release pointing at the
    dev keystore in keystore/); keystore/release.jks gitignored;
    keystore/README.md documents generation & rotation.
  - KMP migration deferred to v0.5 (tracked in plan §10).

COMMUNITY / GITEA
  - .gitea/workflows/build.yml: assembleDebug on push & PR, APK as
    artefact.
  - CONTRIBUTING.md, CODE_OF_CONDUCT.md (Contributor Covenant v2.1),
    .gitea/ISSUE_TEMPLATE/{bug_report,feature_request}.yml,
    .gitea/PULL_REQUEST_TEMPLATE.md.
  - README: v0.2 changelog + Gitea remote-setup instructions.

VERIFIED
  - ./gradlew assembleDebug assembleRelease both green.
  - Debug APK 25.6 MB, release 19.8 MB, both v0.2 / versionCode 3.
  - apksigner verify: 'Verifies' / v2 scheme true.
  - No INTERNET permission in either APK (privacy posture unchanged).
This commit is contained in:
Incido Developer committed 2026-08-14 23:27:27 +12:00
1 parent 2215c3447b
commit 5e1b77bedf
21 files changed
+1242 -118

No files matched your search

@@ -0,0 +1,40 @@
package org.incido.compose.ui.editor
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.graphics.Color
import org.incido.domain.model.NoteColor
/**
* Maps a [NoteColor] enum to a Compose [Color] using Material 3 tokens so
* the swatches adapt to light/dark theme automatically.
*/
@Composable
@ReadOnlyComposable
fun NoteColor.toComposeColor(): Color = when (this) {
NoteColor.NONE -> Color.Transparent
NoteColor.BLUE -> Color(0xFF4A6FA5)
NoteColor.GREEN -> Color(0xFF4F8A5B)
NoteColor.AMBER -> Color(0xFFB8862B)
NoteColor.RED -> Color(0xFFB14B4B)
NoteColor.PURPLE -> Color(0xFF7B5BA6)
}
val AllNoteColors: List<NoteColor> = listOf(
NoteColor.NONE,
NoteColor.BLUE,
NoteColor.GREEN,
NoteColor.AMBER,
NoteColor.RED,
NoteColor.PURPLE,
)
/**
* A swatch surface colour for a swatch button — used to give the
* selected swatch a visible border by reading the theme's outline.
*/
val swatchBorderColor: Color
@Composable
@ReadOnlyComposable
get() = MaterialTheme.colorScheme.outline
@@ -1,34 +1,52 @@
package org.incido.compose.ui.editor
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.input.ImeAction
@@ -36,6 +54,7 @@ import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.domain.model.NoteColor
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -50,10 +69,10 @@ fun NoteEditorScreen(
val state by viewModel.state.collectAsStateWithLifecycle()
val focusRequester = remember { FocusRequester() }
var menuExpanded by remember { mutableStateOf(false) }
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(state.isLoading) {
if (!state.isLoading && state.existing != null) {
// Focus the field so the user can immediately edit existing notes.
focusRequester.requestFocus()
}
}
@@ -61,6 +80,43 @@ fun NoteEditorScreen(
if (noteId == null) focusRequester.requestFocus()
}
fun isDirty(): Boolean {
if (state.isLoading) return false
return state.isDirty(
initialContent = viewModel.initialContent,
initialFavorite = viewModel.initialFavorite,
initialColor = viewModel.initialColor,
)
}
fun tryClose() {
if (isDirty()) showDiscardDialog = true else onClose()
}
// Intercept hardware / gesture back to honour the same discard rule.
BackHandler(enabled = true) { tryClose() }
if (showDiscardDialog) {
AlertDialog(
onDismissRequest = { showDiscardDialog = false },
title = { Text("Discard changes?") },
text = { Text("You have unsaved edits. Leaving now will discard them.") },
confirmButton = {
TextButton(onClick = {
showDiscardDialog = false
onClose()
}) {
Text("Discard")
}
},
dismissButton = {
TextButton(onClick = { showDiscardDialog = false }) {
Text("Keep editing")
}
},
)
}
Scaffold(
// Union systemBars + IME insets so the Scaffold's contentPadding
// shrinks the available area when the soft keyboard opens. With
@@ -72,11 +128,19 @@ fun NoteEditorScreen(
TopAppBar(
title = { Text(if (state.isEditing) "Edit note" else "New note") },
navigationIcon = {
IconButton(onClick = onClose) {
IconButton(onClick = { tryClose() }) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { viewModel.toggleFavorite() }) {
Icon(
imageVector = if (state.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = if (state.isFavorite) "Unfavorite" else "Favorite",
tint = if (state.isFavorite) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(
onClick = { viewModel.save(onClose) },
enabled = state.canSave,
@@ -107,17 +171,33 @@ fun NoteEditorScreen(
)
},
) { padding ->
Box(
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
// Colour-picker row (above the editor).
LazyRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
items(items = AllNoteColors, key = { it.storageKey.toInt() }) { color ->
ColorSwatch(
color = color,
selected = state.color == color,
onClick = { viewModel.setColor(color) },
)
}
}
OutlinedTextField(
value = state.content,
onValueChange = viewModel::onContentChange,
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.padding(horizontal = 16.dp)
.padding(bottom = 16.dp)
.focusRequester(focusRequester),
placeholder = { Text("Write something…") },
keyboardOptions = KeyboardOptions(
@@ -128,3 +208,31 @@ fun NoteEditorScreen(
}
}
}
private fun androidx.compose.foundation.lazy.LazyListScope.items(
items: List<NoteColor>,
key: (NoteColor) -> Any,
itemContent: @Composable (NoteColor) -> Unit,
) {
items(items.size, key = { key(items[it]) }) { idx -> itemContent(items[idx]) }
}
@Composable
private fun ColorSwatch(
color: NoteColor,
selected: Boolean,
onClick: () -> Unit,
) {
val fillColor = color.toComposeColor()
val border = if (selected) swatchBorderColor else MaterialTheme.colorScheme.outlineVariant
val borderWidth = if (selected) 2.dp else 1.dp
Box(
modifier = Modifier
.size(36.dp)
.clip(CircleShape)
.background(fillColor)
.border(borderWidth, border, CircleShape)
.clickable(onClick = onClick),
)
}
@@ -4,7 +4,6 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.flow.MutableStateFlow
@@ -14,6 +13,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.repository.NoteRepository
/**
@@ -23,12 +23,25 @@ import org.incido.domain.repository.NoteRepository
data class NoteEditorUiState(
val existing: Note? = null,
val content: String = "",
val isFavorite: Boolean = false,
val color: NoteColor = NoteColor.NONE,
val isLoading: Boolean = true,
val isSaving: Boolean = false,
val isDeleted: Boolean = false,
) {
val canSave: Boolean get() = content.isNotBlank() && !isSaving
val isEditing: Boolean get() = existing != null
/**
* True when the editor has changes that haven't been saved. Used by
* the discard-confirm dialog in [NoteEditorScreen] to decide whether
* to prompt before closing.
*/
fun isDirty(initialContent: String, initialFavorite: Boolean, initialColor: NoteColor): Boolean {
return content != initialContent ||
isFavorite != initialFavorite ||
color != initialColor
}
}
class NoteEditorViewModel(
@@ -39,6 +52,17 @@ class NoteEditorViewModel(
private val _state = MutableStateFlow(NoteEditorUiState())
val state: StateFlow<NoteEditorUiState> = _state.asStateFlow()
/**
* Snapshot of the initial state when the editor loaded. Used by
* [NoteEditorScreen] to compute the discard-confirm predicate.
*/
var initialContent: String = ""
private set
var initialFavorite: Boolean = false
private set
var initialColor: NoteColor = NoteColor.NONE
private set
init {
if (noteId == null || noteId == 0L) {
// New note
@@ -46,10 +70,18 @@ class NoteEditorViewModel(
} else {
viewModelScope.launch {
repository.observeById(noteId).collect { note ->
if (note != null && _state.value.isLoading) {
// First non-null load — capture the initial snapshot.
initialContent = note.content
initialFavorite = note.isFavorite
initialColor = note.color
}
_state.update {
it.copy(
existing = note,
content = note?.content ?: it.content,
isFavorite = note?.isFavorite ?: it.isFavorite,
color = note?.color ?: it.color,
isLoading = false,
)
}
@@ -62,17 +94,30 @@ class NoteEditorViewModel(
_state.update { it.copy(content = newContent) }
}
fun toggleFavorite() {
_state.update { it.copy(isFavorite = !it.isFavorite) }
}
fun setColor(color: NoteColor) {
_state.update { it.copy(color = color) }
}
fun save(onDone: () -> Unit) {
val current = _state.value
if (!current.canSave) return
_state.update { it.copy(isSaving = true) }
viewModelScope.launch {
val toPersist = current.existing?.copy(content = current.content)
?: Note(
content = current.content,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(),
)
val toPersist = current.existing?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
) ?: Note(
content = current.content,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(),
isFavorite = current.isFavorite,
color = current.color,
)
repository.upsert(toPersist)
_state.update { it.copy(isSaving = false) }
onDone()
@@ -1,5 +1,6 @@
package org.incido.compose.ui.notelist
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -9,30 +10,44 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.compose.ui.editor.toComposeColor
import org.incido.compose.util.rememberRelativeTimestamp
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -41,36 +56,67 @@ fun NoteListScreen(
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
var localQuery by remember { mutableStateOf("") }
Scaffold(
topBar = {
TopAppBar(title = { Text("Incido") })
TopAppBar(
title = { Text("Incido") },
actions = {
IconButton(onClick = {
if (state.isSearchActive) viewModel.closeSearch() else viewModel.openSearch()
localQuery = ""
}) {
Icon(Icons.Default.Search, contentDescription = "Search notes")
}
},
)
},
floatingActionButton = {
FloatingActionButton(onClick = { onOpenEditor(null) }) {
Icon(Icons.Default.Add, contentDescription = "New note")
if (!state.isSearchActive) {
FloatingActionButton(onClick = { onOpenEditor(null) }) {
Icon(Icons.Default.Add, contentDescription = "New note")
}
}
},
) { padding ->
when {
state.isLoading -> Unit // briefly blank on first composition
state.isEmpty -> EmptyState(padding)
else -> NoteList(
notes = state.notes,
contentPadding = padding,
onClick = { onOpenEditor(it.id) },
onDelete = viewModel::delete,
)
Column(modifier = Modifier.padding(padding)) {
if (state.isSearchActive) {
OutlinedTextField(
value = localQuery,
onValueChange = {
localQuery = it
viewModel.onQueryChange(it)
},
placeholder = { Text("Search notes…") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
when {
state.isLoading -> Unit
state.isEmpty -> EmptyState()
state.noResults -> NoResultsState()
else -> NoteList(
notes = state.notes,
onClick = { onOpenEditor(it.id) },
onDelete = viewModel::delete,
onToggleFavorite = viewModel::toggleFavorite,
)
}
}
}
}
@Composable
private fun EmptyState(padding: PaddingValues) {
private fun EmptyState() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(24.dp),
contentAlignment = Alignment.Center,
) {
@@ -82,18 +128,34 @@ private fun EmptyState(padding: PaddingValues) {
}
}
@Composable
private fun NoResultsState() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = "No matching notes.",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun NoteList(
notes: List<Note>,
contentPadding: PaddingValues,
onClick: (Note) -> Unit,
onDelete: (Long) -> Unit,
onToggleFavorite: (Long, Boolean) -> Unit,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(
top = contentPadding.calculateTopPadding() + 8.dp,
bottom = contentPadding.calculateBottomPadding() + 88.dp, // FAB clearance
top = 8.dp,
bottom = 88.dp, // FAB clearance
start = 16.dp,
end = 16.dp,
),
@@ -104,6 +166,7 @@ private fun NoteList(
note = note,
onClick = { onClick(note) },
onDelete = { onDelete(note.id) },
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
)
}
}
@@ -114,52 +177,94 @@ private fun NoteCard(
note: Note,
onClick: () -> Unit,
onDelete: () -> Unit,
onToggleFavorite: () -> Unit,
) {
val (title, body) = Note.titleAndBody(note.content)
val bodyPreview = Note.bodyPreview(body)
val checklistSummary = Note.checklistSummary(note.content)
val stripeColor = note.color.toComposeColor()
Card(
onClick = onClick,
modifier = Modifier.fillMaxWidth(),
) {
Column(
modifier = Modifier.padding(16.dp),
) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
Row(modifier = Modifier.fillMaxWidth()) {
// 4dp coloured accent stripe on the left.
Box(
modifier = Modifier
.size(width = 4.dp, height = 96.dp)
.background(stripeColor),
)
if (bodyPreview.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
Text(
text = bodyPreview,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
Spacer(modifier = Modifier.padding(top = 8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = rememberRelativeTimestamp(note.updatedAt),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
IconButton(onClick = onDelete) {
Icon(
Icons.Default.Delete,
contentDescription = "Delete note",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
IconButton(onClick = onToggleFavorite) {
Icon(
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
tint = if (note.isFavorite) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (bodyPreview.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
Text(
text = bodyPreview,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
if (checklistSummary.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Default.CheckBox,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(modifier = Modifier.size(6.dp))
Text(
text = checklistSummary,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Spacer(modifier = Modifier.padding(top = 8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = rememberRelativeTimestamp(note.updatedAt),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
IconButton(onClick = onDelete) {
Icon(
Icons.Default.Delete,
contentDescription = "Delete note",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
}
@@ -6,9 +6,14 @@ import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.AP
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
@@ -23,27 +28,72 @@ import org.incido.domain.repository.NoteRepository
data class NoteListUiState(
val notes: List<Note> = emptyList(),
val isLoading: Boolean = true,
val searchQuery: String = "",
val isSearchActive: Boolean = false,
) {
val isEmpty: Boolean get() = !isLoading && notes.isEmpty()
val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive
val noResults: Boolean get() = !isLoading && notes.isEmpty() && isSearchActive
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteListViewModel(
private val repository: NoteRepository,
) : ViewModel() {
private val rawQuery = MutableStateFlow("")
private val _isSearchActive = MutableStateFlow(false)
val isSearchActive: StateFlow<Boolean> = _isSearchActive.asStateFlow()
val uiState: StateFlow<NoteListUiState> =
repository.observeAll()
.map { NoteListUiState(notes = it, isLoading = false) }
rawQuery
.debounce(150)
.flatMapLatest { q ->
if (q.isBlank()) {
repository.observeAll()
} else {
repository.search(q)
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
initialValue = emptyList(),
)
.let { notesFlow ->
kotlinx.coroutines.flow.MutableStateFlow(NoteListUiState())
.also { state ->
viewModelScope.launch {
notesFlow.collect { latest ->
state.value = state.value.copy(
notes = latest,
isLoading = false,
)
}
}
}
}
fun onQueryChange(q: String) {
rawQuery.value = q
}
fun openSearch() {
_isSearchActive.value = true
}
fun closeSearch() {
_isSearchActive.value = false
rawQuery.value = ""
}
fun delete(id: Long) {
viewModelScope.launch { repository.delete(id) }
}
fun toggleFavorite(id: Long, isFavorite: Boolean) {
viewModelScope.launch { repository.setFavorite(id, isFavorite) }
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {