Address second review of list search (#95)

This commit is contained in:
makiolaj committed 2026-11-17 11:02:05 +01:00
1 parent 9618431f64
commit 75e0adfaa8
9 files changed
+139 -76

No files matched your search

@@ -12,6 +12,8 @@ data class ListSearchResult(
val exactMatch: Task?,
/** The query is not blank and no top-level task carries it as its title yet. */
val offerCreate: Boolean,
/** A task titled as the query is being added and has not shown up yet. */
val adding: Boolean = false,
) {
companion object {
val Empty = ListSearchResult("", emptyList(), emptyList(), exactMatch = null, offerCreate = false)
@@ -24,9 +26,19 @@ data class ListSearchResult(
*/
object TaskSearch {
/** One task per series, on its current occurrence; other tasks as they are. */
/**
* One task per series: its open occurrence nearest the current one, or,
* with none open, the latest completed. Other tasks as they are.
*/
fun currentOccurrences(tasks: List<Task>): List<Task> =
tasks.sortedBy { abs(it.distanceFromCurrent ?: 0) }.distinctBy { it.seriesId ?: it.taskId }
tasks.sortedWith(
compareBy<Task>({ it.isClosed }, { abs(it.distanceFromCurrent ?: 0) })
.thenByDescending { it.completedAt },
).distinctBy { it.seriesId ?: it.taskId }
/** Whether [query] appears in [task]'s title, description or location. */
fun matches(task: Task, query: String): Boolean =
listOfNotNull(task.title, task.description, task.location).any { it.contains(query, ignoreCase = true) }
/**
* [pendingTitles] are titles just added whose task has not shown up in
@@ -36,35 +48,39 @@ object TaskSearch {
val q = query.trim()
if (q.isEmpty()) return ListSearchResult.Empty
val key = titleKey(q)
val hits = currentOccurrences(tasks.filter { it.title.contains(q, ignoreCase = true) })
.map { Hit(it, titleKey(it.title), it.title.trim().startsWith(q, ignoreCase = true)) }
val hits = currentOccurrences(tasks.filter { matches(it, q) }).map { Hit(it, q) }
val open = hits.filter { !it.task.isClosed }.sortedWith(relevance)
// A title already open needs no completed twin, and a title done many
// times shows once: the most recently completed one.
val openKeys = open.mapTo(HashSet()) { it.dedupKey }
val completed = hits
.filter { it.task.isCompleted && it.dedupKey !in openKeys }
.sortedByDescending { it.task.completedAt }
.distinctBy { it.dedupKey }
.sortedWith(relevance)
// Adding makes a top-level task, so only a top-level one can stand in for it.
val exact = (open + completed).firstOrNull { it.key == key && !it.task.isSubtask }?.task
val pending = pendingTitles.any { titleKey(it) == key }
val adding = exact == null && pendingTitles.any { titleKey(it) == key }
return ListSearchResult(
query = q,
open = open.map { it.task },
completed = completed.map { it.task },
exactMatch = exact,
offerCreate = exact == null && !pending,
offerCreate = exact == null && !adding,
adding = adding,
)
}
fun titleKey(title: String): String = title.trim().lowercase()
private class Hit(val task: Task, val key: String, val prefix: Boolean) {
private class Hit(val task: Task, query: String) {
val key = titleKey(task.title)
val dedupKey = key to task.isSubtask
/** 0: title starts with the query, 1: title contains it, 2: only the description or location does. */
val rank = when {
key.startsWith(query, ignoreCase = true) -> 0
key.contains(query, ignoreCase = true) -> 1
else -> 2
}
}
/** Titles starting with the query first, then alphabetical. */
private val relevance = compareBy<Hit>({ !it.prefix }, { it.key })
private val relevance = compareBy<Hit>({ it.rank }, { it.key })
}
@@ -25,6 +25,7 @@ import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.agendula.R
@@ -43,6 +44,7 @@ fun SearchPill(
placeholder: String,
modifier: Modifier = Modifier,
imeAction: ImeAction = ImeAction.Search,
capitalization: KeyboardCapitalization = KeyboardCapitalization.Sentences,
onImeAction: (() -> Unit)? = null,
trailingReserve: Dp = 0.dp,
) {
@@ -68,6 +70,7 @@ fun SearchPill(
onValueChange = onQueryChange,
placeholder = placeholder,
textStyle = MaterialTheme.typography.bodyLarge,
capitalization = capitalization,
imeAction = imeAction,
onImeAction = onImeAction,
modifier = Modifier.weight(1f).focusRequester(focusRequester),
@@ -75,6 +75,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -562,12 +563,12 @@ private fun SearchSlot(
enter = expandHorizontally(tween(300), expandFrom = Alignment.End) + fadeIn(tween(280)),
exit = shrinkHorizontally(tween(220), shrinkTowards = Alignment.End) + fadeOut(tween(140)),
) {
// The trailing 48dp stays free for the search icon laid over it below.
SearchPill(
query = query,
onQueryChange = onQueryChange,
placeholder = stringResource(R.string.home_search_hint),
modifier = Modifier.fillMaxWidth(),
capitalization = KeyboardCapitalization.None,
trailingReserve = 48.dp,
)
}
@@ -598,9 +599,7 @@ private fun SearchResults(
if (query.isBlank()) return
val results = remember(query, allTasks) {
val q = query.trim()
val hits = allTasks
.filter { t -> listOfNotNull(t.title, t.description, t.location).any { it.contains(q, ignoreCase = true) } }
TaskSearch.currentOccurrences(hits)
TaskSearch.currentOccurrences(allTasks.filter { TaskSearch.matches(it, q) })
.sortedWith(compareBy({ it.isCompleted }, { it.title.lowercase() }))
}
Surface(modifier = modifier, color = MaterialTheme.colorScheme.surface) {
@@ -84,7 +84,6 @@ internal fun TaskListDetailPanes(
selectedOccurrence = task.occurrenceStart?.toEpochMilliseconds() ?: Dest.NO_ID
}
val clear = { selectedId = Dest.NO_ID }
BackHandler(enabled = selectedId != Dest.NO_ID, onBack = clear)
// Each pane clears only the side insets of the screen edge it touches, and
// consumes the other so its scaffold doesn't pad for it again.
@@ -102,6 +101,8 @@ internal fun TaskListDetailPanes(
.windowInsetsPadding(start)
.consumeWindowInsets(end),
) { list(select) }
// Registered after the list, so back closes the detail before the list's own search.
BackHandler(enabled = selectedId != Dest.NO_ID, onBack = clear)
Surface(
color = MaterialTheme.colorScheme.surfaceContainerLow,
shape = RoundedCornerShape(topStart = 28.dp, bottomStart = 28.dp),
@@ -95,10 +95,12 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
@@ -196,7 +198,6 @@ fun TaskListScreen(
var showSort by rememberSaveable { mutableStateOf(false) }
var confirmClear by rememberSaveable { mutableStateOf(false) }
// Search covers a real list only, open and completed tasks alike (#95).
var searchActive by rememberSaveable { mutableStateOf(false) }
var query by rememberSaveable { mutableStateOf("") }
val searching = searchActive && listId != null
@@ -206,15 +207,16 @@ fun TaskListScreen(
}
BackHandler(enabled = searching, onBack = closeSearch)
val canCreate = listId != null && list != null && !list.isReadOnly
val keyboard = LocalSoftwareKeyboardController.current
LaunchedEffect(query) { viewModel.setSearchQuery(query) }
val searchResult by viewModel.search.collectAsStateWithLifecycle()
// An add or reopen clears the field once it has landed, unless something new was typed meanwhile.
// Clears the field once an add or reopen has landed, unless something else was typed meanwhile.
val searchReceipt by viewModel.searchReceipt.collectAsStateWithLifecycle()
LaunchedEffect(searchReceipt) {
val done = when (val r = searchReceipt) {
is SearchReceipt.Added -> r.title
is SearchReceipt.Reopened -> r.title
SearchReceipt.Failed, null -> null
else -> null
}
if (done != null && TaskSearch.titleKey(query) == TaskSearch.titleKey(done)) query = ""
if (searchReceipt != null) {
@@ -231,7 +233,7 @@ fun TaskListScreen(
TaskSearchBar(
query = query,
onQueryChange = { query = it },
onSubmit = { viewModel.submitSearch(query, listId, canCreate) },
onSubmit = { if (!viewModel.submitSearch(query, listId, canCreate)) keyboard?.hide() },
onClose = closeSearch,
)
} else {
@@ -371,6 +373,7 @@ fun TaskListScreen(
message = when (val r = searchReceipt) {
is SearchReceipt.Added -> stringResource(R.string.task_search_added, r.title)
is SearchReceipt.Reopened -> stringResource(R.string.task_search_reopened, r.title)
is SearchReceipt.AlreadyOpen -> stringResource(R.string.task_search_already_open, r.title)
else -> stringResource(R.string.edit_save_failed)
},
)
@@ -1264,13 +1267,13 @@ private fun CollapsibleSectionHeader(
/** Icon + message for an empty list — the Calendula agenda-empty pattern. */
@Composable
private fun EmptyState(text: String) {
internal fun EmptyState(text: String, icon: ImageVector = Icons.Rounded.Checklist) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 64.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
imageVector = Icons.Rounded.Checklist,
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(48.dp),
@@ -20,18 +20,17 @@ import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.domain.ListSearchResult
@@ -112,9 +111,11 @@ internal fun TaskSearchResults(
val q = result.query
val showCreate = result.offerCreate && canCreate
when {
q.isEmpty() -> item(key = "prompt") { SearchMessage(stringResource(R.string.task_search_prompt)) }
!showCreate && result.open.isEmpty() && result.completed.isEmpty() ->
item(key = "empty") { SearchMessage(stringResource(R.string.home_search_empty, q)) }
q.isEmpty() -> item(key = "prompt") {
EmptyState(stringResource(R.string.task_search_prompt), icon = Icons.Rounded.Search)
}
!showCreate && !result.adding && result.open.isEmpty() && result.completed.isEmpty() ->
item(key = "empty") { EmptyState(stringResource(R.string.home_search_empty, q), icon = Icons.Rounded.Search) }
}
if (showCreate) {
item(key = "create") {
@@ -165,14 +166,3 @@ private fun LazyListScope.hitSection(
}
}
}
@Composable
private fun SearchMessage(text: String) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 24.dp),
)
}
@@ -44,7 +44,9 @@ import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
sealed interface TaskListUiState {
@@ -76,7 +78,7 @@ sealed interface TaskListUiState {
val savedFilter: SavedFilter? = null,
/** The filter this content was built for; a reused screen briefly holds the previous one's. */
val filter: TaskFilter? = null,
/** Every task the view holds before the tag filter narrows it — what a search looks through. */
/** A real list's tasks before the tag filter narrows them, which its search looks through; empty elsewhere. */
val searchable: List<Task> = emptyList(),
) : TaskListUiState
}
@@ -93,13 +95,16 @@ sealed interface UndoReceipt {
data class Completed(override val task: Task, val subtasks: List<Task> = emptyList()) : UndoReceipt
}
/** How an add or reopen from the list search went. */
/** How an action from the list search went. Not data classes: a repeat must still re-emit. */
sealed interface SearchReceipt {
data class Added(val title: String) : SearchReceipt
data class Reopened(val title: String) : SearchReceipt
data object Failed : SearchReceipt
class Added(val title: String) : SearchReceipt
class Reopened(val title: String) : SearchReceipt
class AlreadyOpen(val title: String) : SearchReceipt
class Failed : SearchReceipt
}
private const val PENDING_ADD_TIMEOUT_MS = 10_000L
private const val UNDO_WINDOW_MS = 4_000L
@OptIn(ExperimentalCoroutinesApi::class)
@@ -168,7 +173,7 @@ class TaskListViewModel @Inject constructor(
.sortedWith(settings.sortOrder.comparator()),
availableTags = available,
selectedTags = selected,
searchable = visible,
searchable = if (f is TaskFilter.OfList) visible else emptyList(),
showAddSubtaskRow = settings.showAddSubtaskRow,
bottomAddBar = settings.bottomAddBar,
sortOrder = settings.sortOrder,
@@ -337,23 +342,24 @@ class TaskListViewModel @Inject constructor(
private val _searchReceipt = MutableStateFlow<SearchReceipt?>(null)
/** The outcome of the last add or reopen from search; the screen shows it and clears it. */
/** The outcome of the last action from search; the screen shows it and clears it. */
val searchReceipt: StateFlow<SearchReceipt?> = _searchReceipt.asStateFlow()
private val searchable = state
.map { (it as? TaskListUiState.Content)?.searchable.orEmpty() }
.distinctUntilChanged()
private fun searchable(): List<Task> = (state.value as? TaskListUiState.Content)?.searchable.orEmpty()
/** The list search for the query the screen last set (#95). */
/** The list search for the query the screen last set (#95); idle while the query is blank. */
val search: StateFlow<ListSearchResult> =
combine(searchable, searchQuery, pendingAdds) { tasks, query, pending ->
if (pending.isNotEmpty()) {
val arrived = tasks.filter { !it.isClosed && !it.isSubtask }.mapTo(HashSet()) { TaskSearch.titleKey(it.title) }
val waiting = pending.filterTo(HashSet()) { TaskSearch.titleKey(it) !in arrived }
if (waiting.size != pending.size) pendingAdds.value = waiting
searchQuery
.map { it.trim() }
.distinctUntilChanged()
.flatMapLatest { query ->
if (query.isEmpty()) {
flowOf(ListSearchResult.Empty)
} else {
val tasks = state.map { (it as? TaskListUiState.Content)?.searchable.orEmpty() }.distinctUntilChanged()
combine(tasks, pendingAdds) { list, pending -> TaskSearch.inList(list, query, pending) }
}
}
TaskSearch.inList(tasks, query, pending)
}
.flowOn(Dispatchers.Default)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListSearchResult.Empty)
@@ -365,36 +371,48 @@ class TaskListViewModel @Inject constructor(
* Enter in the search field: reopens the completed task titled [query], or
* adds it to [listId] when nothing carries that title. Searches afresh, so a
* result the screen has not caught up with yet cannot pick the wrong action.
* Returns false when there was nothing to do.
*/
fun submitSearch(query: String, listId: Long, canCreate: Boolean) {
when (val action = searchNow(query).submitAction(canCreate)) {
fun submitSearch(query: String, listId: Long, canCreate: Boolean): Boolean {
val result = TaskSearch.inList(searchable(), query, pendingAdds.value)
when (val action = result.submitAction(canCreate)) {
is SearchSubmit.Reopen -> reopenFromSearch(action.task)
is SearchSubmit.Create -> addFromSearch(action.title, listId)
null -> Unit
is SearchSubmit.Create -> add(action.title, listId)
null -> {
val open = result.exactMatch?.takeIf { !it.isClosed } ?: return false
_searchReceipt.value = SearchReceipt.AlreadyOpen(open.title.trim())
}
}
return true
}
/** The "Add …" row: adds [title] to [listId] unless a task with that title turned up meanwhile. */
fun addFromSearch(title: String, listId: Long) {
val result = searchNow(title)
if (!result.offerCreate || listId <= 0L) return
val trimmed = result.query
pendingAdds.value += trimmed
val result = TaskSearch.inList(searchable(), title, pendingAdds.value)
if (result.offerCreate) add(result.query, listId)
}
private fun add(title: String, listId: Long) {
if (listId <= 0L) return
pendingAdds.update { it + title }
viewModelScope.launch {
val added = runCatching { repository.createTask(TaskForm(title = trimmed, listId = listId)) }.isSuccess
if (!added) pendingAdds.value -= trimmed
_searchReceipt.value = if (added) SearchReceipt.Added(trimmed) else SearchReceipt.Failed
val added = runCatching { repository.createTask(TaskForm(title = title, listId = listId)) }.isSuccess
_searchReceipt.value = if (added) SearchReceipt.Added(title) else SearchReceipt.Failed()
if (added) {
val key = TaskSearch.titleKey(title)
withTimeoutOrNull(PENDING_ADD_TIMEOUT_MS) {
state.first { st ->
(st as? TaskListUiState.Content)?.searchable.orEmpty()
.any { !it.isClosed && !it.isSubtask && TaskSearch.titleKey(it.title) == key }
}
}
}
pendingAdds.update { it - title }
}
}
private fun searchNow(query: String): ListSearchResult =
TaskSearch.inList((state.value as? TaskListUiState.Content)?.searchable.orEmpty(), query, pendingAdds.value)
private fun reopenFromSearch(task: Task) {
if (!task.isCompleted || task.isReadOnly) return
viewModelScope.launch {
_searchReceipt.value = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed
}
private fun reopenFromSearch(task: Task) = viewModelScope.launch {
_searchReceipt.value = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed()
}
/** Inline "add task" — title only, into [listId]. */
+1
View File
@@ -339,6 +339,7 @@
<string name="task_search_open">Open</string>
<string name="task_search_added">Added “%1$s”</string>
<string name="task_search_reopened">Reopened “%1$s”</string>
<string name="task_search_already_open">“%1$s” is already open</string>
<!-- Reminders -->
<string name="reminder_due_at">Due %1$s</string>
@@ -123,6 +123,38 @@ class TaskSearchTest {
val result = TaskSearch.inList(emptyList(), "milk", pendingTitles = setOf("Milk"))
assertThat(result.offerCreate).isFalse()
assertThat(result.adding).isTrue()
}
@Test
fun `a series shows its open occurrence even when the current one is done`() {
val today = testTask(id = 2, title = "Water plants", status = TaskStatus.COMPLETED, completedAt = at(5))
.copy(seriesId = 1, occurrenceStart = at(100), distanceFromCurrent = 0)
val tomorrow = testTask(id = 3, title = "Water plants")
.copy(seriesId = 1, occurrenceStart = at(200), distanceFromCurrent = 1)
val result = TaskSearch.inList(listOf(today, tomorrow), "water")
assertThat(result.open).containsExactly(tomorrow)
assertThat(result.completed).isEmpty()
}
@Test
fun `a closed series shows its latest completion`() {
val older = done(2, "Water plants", 5).copy(seriesId = 1, occurrenceStart = at(100))
val newer = done(3, "Water plants", 50).copy(seriesId = 1, occurrenceStart = at(200))
assertThat(TaskSearch.inList(listOf(older, newer), "water").completed).containsExactly(newer)
}
@Test
fun `description and location match too, after title matches`() {
val byNote = testTask(id = 1, title = "Call landlord").copy(description = "about the rent")
val byTitle = testTask(id = 2, title = "Pay rent")
val result = TaskSearch.inList(listOf(byNote, byTitle), "rent")
assertThat(result.open).containsExactly(byTitle, byNote).inOrder()
}
@Test