From 711db920d21f1c4fd365c704984879b7d571556a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 00:42:15 +0100 Subject: [PATCH 1/6] Search a list and add or reopen tasks from it (#95) --- CHANGELOG.md | 6 + .../agendula/domain/TaskSearch.kt | 53 +++++ .../agendula/ui/tasklist/TaskListScreen.kt | 173 +++++++++++---- .../agendula/ui/tasklist/TaskListSearch.kt | 210 ++++++++++++++++++ .../agendula/ui/tasklist/TaskListViewModel.kt | 11 + app/src/main/res/values/strings.xml | 10 + .../agendula/domain/TaskSearchTest.kt | 109 +++++++++ .../agendula/ui/tasklist/SearchSubmitTest.kt | 36 +++ 8 files changed, 560 insertions(+), 48 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c3d4b..a76eec8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- A list can be searched from its top bar, completed tasks included. A + completed match can be reopened with its checkbox, and a title the list + doesn't have yet can be added straight from the search; pressing enter + reopens or adds the typed task (#95). + ## [1.3.2] - 2026-11-13 ### Added diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt new file mode 100644 index 0000000..2c69c83 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt @@ -0,0 +1,53 @@ +package de.jeanlucmakiola.agendula.domain + +import kotlin.math.abs + +/** What a search inside one list turns up for a query. */ +data class ListSearchResult( + val open: List, + val completed: List, + /** The task already titled exactly as the query, open or completed, if any. */ + val exactMatch: Task?, + /** The query is not blank and no task carries it as its title yet. */ + val offerCreate: Boolean, +) { + companion object { + val Empty = ListSearchResult(emptyList(), emptyList(), exactMatch = null, offerCreate = false) + } +} + +/** + * Search over one list's tasks, open and completed alike, so an old task can be + * reopened instead of typed again (#95). + */ +object TaskSearch { + + fun inList(tasks: List, query: String): ListSearchResult { + val q = query.trim() + if (q.isEmpty()) return ListSearchResult.Empty + val matches = tasks + .filter { it.title.contains(q, ignoreCase = true) } + // A series matches once, on its current occurrence. + .sortedBy { abs(it.distanceFromCurrent ?: 0) } + .distinctBy { it.seriesId ?: it.taskId } + val open = matches.filter { !it.isClosed }.sortedWith(relevance(q)) + // A title already open needs no completed twin, and a title done many + // times shows once: the most recently completed one. + val openTitles = open.mapTo(HashSet()) { titleKey(it.title) } + val completed = matches + .filter { it.isCompleted && titleKey(it.title) !in openTitles } + .sortedByDescending { it.completedAt } + .distinctBy { titleKey(it.title) } + .sortedWith(relevance(q)) + val key = titleKey(q) + val exact = open.firstOrNull { titleKey(it.title) == key } + ?: completed.firstOrNull { titleKey(it.title) == key } + return ListSearchResult(open, completed, exact, offerCreate = exact == null) + } + + private fun titleKey(title: String) = title.trim().lowercase() + + /** Titles starting with the query first, then alphabetical. */ + private fun relevance(q: String): Comparator = + compareBy({ !it.title.trim().startsWith(q, ignoreCase = true) }, { it.title.trim().lowercase() }) +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index a6efcd5..5428c24 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.agendula.ui.tasklist +import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState @@ -64,6 +65,7 @@ import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material.icons.rounded.Repeat +import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Sell import androidx.compose.material.icons.rounded.Tune import androidx.compose.material3.AlertDialog @@ -114,6 +116,7 @@ import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskSection import de.jeanlucmakiola.agendula.domain.TaskSections +import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.agendula.ui.common.SyncPullBox import de.jeanlucmakiola.agendula.ui.common.ignoringEdgeSwipes @@ -193,53 +196,105 @@ 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 + val closeSearch = { + query = "" + searchActive = false + } + BackHandler(enabled = searching, onBack = closeSearch) + val canCreate = listId != null && list != null && !list.isReadOnly + val searchResult = remember(query, content?.searchable) { + TaskSearch.inList(content?.searchable.orEmpty(), query) + } + // Feedback for an add or reopen from search, which clears the field at once. + var searchReceipt by remember { mutableStateOf(null) } + LaunchedEffect(searchReceipt) { + if (searchReceipt != null) { + delay(4_000) + searchReceipt = null + } + } + val addedMessage = stringResource(R.string.task_search_added) + val reopenedMessage = stringResource(R.string.task_search_reopened) + fun runSearchAction(action: SearchSubmit) { + when (action) { + is SearchSubmit.Reopen -> { + viewModel.reopen(action.task) + searchReceipt = reopenedMessage.format(action.task.title.trim()) + } + is SearchSubmit.Create -> { + if (listId == null) return + viewModel.quickAdd(action.title, listId) + searchReceipt = addedMessage.format(action.title) + } + } + query = "" + } + Scaffold( modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - MediumTopAppBar( - title = { Text(titleFor(filter, listName ?: savedFilter?.name)) }, - navigationIcon = { - IconButton(onClick = onBack) { - Icon( - Icons.AutoMirrored.Rounded.ArrowBack, - contentDescription = stringResource(R.string.back), - ) - } - }, - actions = { - IconButton(onClick = { showSort = true }, enabled = content != null) { - BadgedBox(badge = { if (content?.selectedTags?.isNotEmpty() == true) Badge() }) { - Icon(Icons.Rounded.Tune, contentDescription = stringResource(R.string.view_options_title)) - } - } - if (savedFilter != null) { - IconButton(onClick = { onEditFilter(savedFilter.id) }) { - Icon(Icons.Rounded.Edit, contentDescription = stringResource(R.string.filter_edit_title)) - } - } - if (list != null) { - IconButton( - onClick = { - if (list.isReadOnly) readOnlyHint = true else editingList = true - }, - ) { + if (searching) { + TaskSearchBar( + query = query, + onQueryChange = { query = it }, + onSubmit = { searchResult.submitAction(query, canCreate)?.let(::runSearchAction) }, + onClose = closeSearch, + ) + } else { + MediumTopAppBar( + title = { Text(titleFor(filter, listName ?: savedFilter?.name)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon( - Icons.Rounded.Edit, - contentDescription = stringResource(R.string.list_edit_title), - tint = if (list.isReadOnly) { - LocalContentColor.current.copy(alpha = 0.38f) - } else { - LocalContentColor.current - }, + Icons.AutoMirrored.Rounded.ArrowBack, + contentDescription = stringResource(R.string.back), ) } - } - }, - scrollBehavior = scrollBehavior, - ) + }, + actions = { + if (listId != null) { + IconButton(onClick = { searchActive = true }, enabled = content != null) { + Icon(Icons.Rounded.Search, contentDescription = stringResource(R.string.task_search_action)) + } + } + IconButton(onClick = { showSort = true }, enabled = content != null) { + BadgedBox(badge = { if (content?.selectedTags?.isNotEmpty() == true) Badge() }) { + Icon(Icons.Rounded.Tune, contentDescription = stringResource(R.string.view_options_title)) + } + } + if (savedFilter != null) { + IconButton(onClick = { onEditFilter(savedFilter.id) }) { + Icon(Icons.Rounded.Edit, contentDescription = stringResource(R.string.filter_edit_title)) + } + } + if (list != null) { + IconButton( + onClick = { + if (list.isReadOnly) readOnlyHint = true else editingList = true + }, + ) { + Icon( + Icons.Rounded.Edit, + contentDescription = stringResource(R.string.list_edit_title), + tint = if (list.isReadOnly) { + LocalContentColor.current.copy(alpha = 0.38f) + } else { + LocalContentColor.current + }, + ) + } + } + }, + scrollBehavior = scrollBehavior, + ) + } }, floatingActionButton = { - if (!showBottomAddBar) { + if (!showBottomAddBar && !searching) { ExtendedFloatingActionButton( onClick = onNewTask, icon = { Icon(Icons.Rounded.Add, contentDescription = null) }, @@ -248,14 +303,14 @@ fun TaskListScreen( } }, bottomBar = { - if (showBottomAddBar) { + if (showBottomAddBar && !searching) { QuickAddBar(onAdd = { title -> viewModel.quickAdd(title, listId) }) } }, ) { inner -> Box(modifier = Modifier.fillMaxSize()) { SyncPullBox( - available = syncAvailable, + available = syncAvailable && !searching, syncing = syncing, onSync = viewModel::syncAll, modifier = Modifier.fillMaxSize(), @@ -264,21 +319,42 @@ fun TaskListScreen( when (val s = state) { TaskListUiState.Loading -> Unit // brief; avoids a flash before first emission TaskListUiState.Failure -> CenteredMessage(stringResource(R.string.task_list_failure), inner) - is TaskListUiState.Content -> TaskListBody( - s, filter, inner, onOpenTask, onRequestDelete, viewModel, - onClearCompleted = if (listId != null && list?.isReadOnly != true) ({ confirmClear = true }) else null, - ) + is TaskListUiState.Content -> if (searching) { + TaskSearchResults( + query = query, + result = searchResult, + canCreate = canCreate, + inner = inner, + onCreate = { runSearchAction(SearchSubmit.Create(it)) }, + onToggle = viewModel::toggleComplete, + onOpenTask = onOpenTask, + ) + } else { + TaskListBody( + s, filter, inner, onOpenTask, onRequestDelete, viewModel, + onClearCompleted = if (listId != null && list?.isReadOnly != true) ({ confirmClear = true }) else null, + ) + } } } // A FAB-height band anchored at the bottom-start with the FAB's own // margin; centring the chip in it lines the chip up beside the bottom-end // FAB at exactly its height, rather than sitting a touch above it. + // While searching the keyboard is up, so the chip rides on it instead. Box( modifier = Modifier .align(Alignment.BottomStart) - .padding( - start = SnackChipMargin, - bottom = inner.calculateBottomPadding() + SnackChipMargin, + .then( + if (searching) { + Modifier + .windowInsetsPadding(WindowInsets.ime.union(WindowInsets.navigationBars)) + .padding(start = SnackChipMargin, bottom = SnackChipMargin) + } else { + Modifier.padding( + start = SnackChipMargin, + bottom = inner.calculateBottomPadding() + SnackChipMargin, + ) + }, ) .height(SnackChipHeight), contentAlignment = Alignment.CenterStart, @@ -301,6 +377,7 @@ fun TaskListScreen( visible = true, message = stringResource(listWriteFailureMessage(failure)), ) + searchReceipt != null -> SnackChip(visible = true, message = searchReceipt.orEmpty()) else -> SnackChip( visible = readOnlyHint, message = stringResource(R.string.list_read_only), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt new file mode 100644 index 0000000..cc56ff1 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt @@ -0,0 +1,210 @@ +package de.jeanlucmakiola.agendula.ui.tasklist + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsBottomHeight +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +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.Close +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.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +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.style.TextAlign +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.ListSearchResult +import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.InlineTextField +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf + +/** What submitting a search does: reopen the completed task of that title, or add a new one. */ +internal sealed interface SearchSubmit { + data class Reopen(val task: Task) : SearchSubmit + data class Create(val title: String) : SearchSubmit +} + +internal fun ListSearchResult.submitAction(query: String, canCreate: Boolean): SearchSubmit? { + val exact = exactMatch + return when { + exact != null -> if (exact.isCompleted && !exact.isReadOnly) SearchSubmit.Reopen(exact) else null + offerCreate && canCreate -> SearchSubmit.Create(query.trim()) + else -> null + } +} + +/** + * The task list's top bar while searching: back closes the search, and the + * field sits in the same tonal pill as the home search. + */ +@Composable +internal fun TaskSearchBar( + query: String, + onQueryChange: (String) -> Unit, + onSubmit: () -> Unit, + onClose: () -> Unit, +) { + val focusRequester = remember { FocusRequester() } + LaunchedEffect(Unit) { focusRequester.requestFocus() } + Surface(color = MaterialTheme.colorScheme.surface) { + Row( + modifier = Modifier + .fillMaxWidth() + .windowInsetsPadding(TopAppBarDefaults.windowInsets) + .height(72.dp) + .padding(start = 4.dp, end = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onClose) { + Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = stringResource(R.string.back)) + } + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier.weight(1f).height(52.dp), + ) { + Row( + modifier = Modifier.padding(start = 18.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InlineTextField( + value = query, + onValueChange = onQueryChange, + placeholder = stringResource(R.string.task_search_hint), + textStyle = MaterialTheme.typography.bodyLarge, + imeAction = ImeAction.Done, + onImeAction = onSubmit, + modifier = Modifier.weight(1f).focusRequester(focusRequester), + ) + if (query.isNotEmpty()) { + IconButton(onClick = { onQueryChange("") }) { + Icon(Icons.Rounded.Close, contentDescription = stringResource(R.string.home_search_clear)) + } + } else { + Spacer(Modifier.width(18.dp)) + } + } + } + } + } +} + +/** + * Search hits for one list: an "Add …" row while no task carries the typed + * title, then the open matches and the completed ones, each a grouped run of + * the list's own rows. Checking a completed hit off reopens it. + */ +@Composable +internal fun TaskSearchResults( + query: String, + result: ListSearchResult, + canCreate: Boolean, + inner: PaddingValues, + onCreate: (String) -> Unit, + onToggle: (Task) -> Unit, + onOpenTask: (Task) -> Unit, +) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) { + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(top = inner.calculateTopPadding() + 8.dp), + ) { + val q = query.trim() + 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)) } + } + if (showCreate) { + item(key = "create") { + GroupedRow( + title = stringResource(R.string.task_search_add, q), + position = Position.Alone, + leading = { Icon(Icons.Rounded.Add, contentDescription = null, tint = MaterialTheme.colorScheme.primary) }, + minHeight = 64.dp, + onClick = { onCreate(q) }, + ) + } + } + hitSection("open", R.string.task_search_open, result.open, onToggle, onOpenTask) + hitSection("completed", R.string.section_completed, result.completed, onToggle, onOpenTask) + item(key = "bottom-inset") { + Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars.union(WindowInsets.ime))) + } + } + } +} + +private fun LazyListScope.hitSection( + key: String, + label: Int, + tasks: List, + onToggle: (Task) -> Unit, + onOpenTask: (Task) -> Unit, +) { + if (tasks.isEmpty()) return + item(key = "hdr-$key") { GroupedSectionHeader(stringResource(label)) } + itemsIndexed(tasks, key = { _, t -> "$key-${t.occurrenceKey}" }) { index, task -> + Box( + Modifier + .padding(horizontal = GroupedListInset) + .padding(bottom = if (index == tasks.lastIndex) 0.dp else 2.dp), + ) { + TaskRowContent( + task = task, + position = positionOf(index, tasks.size), + showListName = false, + subtaskDone = task.subtaskDone, + subtaskTotal = task.subtaskTotal, + expanded = false, + onToggleExpand = null, + onToggle = { onToggle(task) }, + onClick = { onOpenTask(task) }, + ) + } + } +} + +@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), + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index b74fece..cab509e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -71,6 +71,8 @@ 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. */ + val searchable: List = emptyList(), ) : TaskListUiState } @@ -154,6 +156,7 @@ class TaskListViewModel @Inject constructor( .sortedWith(settings.sortOrder.comparator()), availableTags = available, selectedTags = selected, + searchable = visible, showAddSubtaskRow = settings.showAddSubtaskRow, bottomAddBar = settings.bottomAddBar, sortOrder = settings.sortOrder, @@ -314,6 +317,14 @@ class TaskListViewModel @Inject constructor( } } + /** Marks a completed [task] open again, e.g. a search hit picked instead of retyping it (#95). */ + fun reopen(task: Task) { + if (!task.isCompleted || task.isReadOnly) return + viewModelScope.launch { + runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) } + } + } + /** Inline "add task" — title only, into [listId]. */ fun quickAdd(title: String, listId: Long) = viewModelScope.launch { if (title.isBlank() || listId <= 0L) return@launch diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5211b6b..4353ba1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -329,6 +329,16 @@ Clear search No tasks match “%1$s” + + Search this list + Search or add a task + Find any task in this list, completed ones included. If it isn’t here yet, add it from here. + + Add “%1$s” + Open + Added “%1$s” + Reopened “%1$s” + Due %1$s diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt new file mode 100644 index 0000000..1704da4 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt @@ -0,0 +1,109 @@ +package de.jeanlucmakiola.agendula.domain + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import kotlin.time.Instant + +class TaskSearchTest { + + private fun at(millis: Long) = Instant.fromEpochMilliseconds(millis) + + private fun done(id: Long, title: String, completedAt: Long) = + testTask(id = id, title = title, status = TaskStatus.COMPLETED, completedAt = at(completedAt)) + + @Test + fun `a blank query finds nothing and offers nothing`() { + val result = TaskSearch.inList(listOf(testTask(title = "Bread")), " ") + + assertThat(result).isEqualTo(ListSearchResult.Empty) + } + + @Test + fun `matches open and completed tasks by title, ignoring case`() { + val open = testTask(id = 1, title = "Brown bread") + val completed = done(2, "Bread", 10) + val other = testTask(id = 3, title = "Milk") + + val result = TaskSearch.inList(listOf(open, completed, other), "BREAD") + + assertThat(result.open).containsExactly(open) + assertThat(result.completed).containsExactly(completed) + } + + @Test + fun `titles starting with the query rank first`() { + val inside = testTask(id = 1, title = "Brown bread") + val starts = testTask(id = 2, title = "Bread rolls") + + val result = TaskSearch.inList(listOf(inside, starts), "bread") + + assertThat(result.open).containsExactly(starts, inside).inOrder() + } + + @Test + fun `a title completed many times shows once, the latest`() { + val older = done(1, "Bread", 10) + val newer = done(2, "bread ", 20) + + val result = TaskSearch.inList(listOf(older, newer), "bread") + + assertThat(result.completed).containsExactly(newer) + } + + @Test + fun `a completed task already open again is left out`() { + val open = testTask(id = 1, title = "Bread") + val completed = done(2, "bread", 10) + + val result = TaskSearch.inList(listOf(open, completed), "bre") + + assertThat(result.open).containsExactly(open) + assertThat(result.completed).isEmpty() + } + + @Test + fun `an exact title, open or completed, is the match and blocks creating`() { + val completed = done(2, "Bread", 10) + + val reopenable = TaskSearch.inList(listOf(completed), " bread ") + assertThat(reopenable.exactMatch).isEqualTo(completed) + assertThat(reopenable.offerCreate).isFalse() + + val open = testTask(id = 1, title = "Bread") + val alreadyOpen = TaskSearch.inList(listOf(open, completed), "bread") + assertThat(alreadyOpen.exactMatch).isEqualTo(open) + assertThat(alreadyOpen.offerCreate).isFalse() + } + + @Test + fun `a new title is offered for creating`() { + val result = TaskSearch.inList(listOf(done(1, "Bread rolls", 10)), "Bread") + + assertThat(result.exactMatch).isNull() + assertThat(result.offerCreate).isTrue() + } + + @Test + fun `cancelled tasks are not search hits`() { + val cancelled = testTask(id = 1, title = "Bread", status = TaskStatus.CANCELLED) + + val result = TaskSearch.inList(listOf(cancelled), "bread") + + assertThat(result.open).isEmpty() + assertThat(result.completed).isEmpty() + assertThat(result.offerCreate).isTrue() + } + + @Test + fun `a series matches once, on its current occurrence`() { + val past = testTask(id = 2, title = "Water plants", status = TaskStatus.COMPLETED, completedAt = at(5)) + .copy(seriesId = 1, occurrenceStart = at(100), distanceFromCurrent = -1) + val current = testTask(id = 3, title = "Water plants") + .copy(seriesId = 1, occurrenceStart = at(200), distanceFromCurrent = 0) + + val result = TaskSearch.inList(listOf(past, current), "water") + + assertThat(result.open).containsExactly(current) + assertThat(result.completed).isEmpty() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt new file mode 100644 index 0000000..375e8e7 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt @@ -0,0 +1,36 @@ +package de.jeanlucmakiola.agendula.ui.tasklist + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.domain.TaskSearch +import de.jeanlucmakiola.agendula.domain.TaskStatus +import de.jeanlucmakiola.agendula.domain.testTask +import org.junit.jupiter.api.Test + +class SearchSubmitTest { + + private val completed = testTask(id = 1, title = "Bread", status = TaskStatus.COMPLETED) + + @Test + fun `submitting a completed title reopens it`() { + val result = TaskSearch.inList(listOf(completed), "bread") + + assertThat(result.submitAction("bread", canCreate = true)).isEqualTo(SearchSubmit.Reopen(completed)) + } + + @Test + fun `submitting a new title creates it, trimmed`() { + val result = TaskSearch.inList(listOf(completed), " Milk ") + + assertThat(result.submitAction(" Milk ", canCreate = true)).isEqualTo(SearchSubmit.Create("Milk")) + assertThat(result.submitAction(" Milk ", canCreate = false)).isNull() + } + + @Test + fun `submitting an open title or a read-only one does nothing`() { + val open = testTask(id = 2, title = "Milk") + assertThat(TaskSearch.inList(listOf(open), "milk").submitAction("milk", canCreate = true)).isNull() + + val readOnly = completed.copy(isReadOnly = true) + assertThat(TaskSearch.inList(listOf(readOnly), "bread").submitAction("bread", canCreate = true)).isNull() + } +} From 9618431f648c59679f65c6c167adefc6c9e40435 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 10:53:58 +0100 Subject: [PATCH 2/6] Address review of list search (#95) --- .../agendula/domain/TaskSearch.kt | 63 +++++++++----- .../agendula/ui/common/SearchPill.kt | 85 +++++++++++++++++++ .../agendula/ui/lists/ListsScreen.kt | 79 ++--------------- .../agendula/ui/tasklist/TaskListScreen.kt | 54 ++++++------ .../agendula/ui/tasklist/TaskListSearch.kt | 58 +++---------- .../agendula/ui/tasklist/TaskListViewModel.kt | 84 ++++++++++++++++-- app/src/main/res/values/strings.xml | 1 + .../agendula/domain/TaskSearchTest.kt | 23 +++++ .../agendula/ui/tasklist/SearchSubmitTest.kt | 10 +-- 9 files changed, 277 insertions(+), 180 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt index 2c69c83..849c450 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt @@ -4,15 +4,17 @@ import kotlin.math.abs /** What a search inside one list turns up for a query. */ data class ListSearchResult( + /** The trimmed query this result answers. */ + val query: String, val open: List, val completed: List, - /** The task already titled exactly as the query, open or completed, if any. */ + /** The top-level task already titled exactly as the query, open or completed, if any. */ val exactMatch: Task?, - /** The query is not blank and no task carries it as its title yet. */ + /** The query is not blank and no top-level task carries it as its title yet. */ val offerCreate: Boolean, ) { companion object { - val Empty = ListSearchResult(emptyList(), emptyList(), exactMatch = null, offerCreate = false) + val Empty = ListSearchResult("", emptyList(), emptyList(), exactMatch = null, offerCreate = false) } } @@ -22,32 +24,47 @@ data class ListSearchResult( */ object TaskSearch { - fun inList(tasks: List, query: String): ListSearchResult { + /** One task per series, on its current occurrence; other tasks as they are. */ + fun currentOccurrences(tasks: List): List = + tasks.sortedBy { abs(it.distanceFromCurrent ?: 0) }.distinctBy { it.seriesId ?: it.taskId } + + /** + * [pendingTitles] are titles just added whose task has not shown up in + * [tasks] yet; they count as taken so the same title is not offered twice. + */ + fun inList(tasks: List, query: String, pendingTitles: Set = emptySet()): ListSearchResult { val q = query.trim() if (q.isEmpty()) return ListSearchResult.Empty - val matches = tasks - .filter { it.title.contains(q, ignoreCase = true) } - // A series matches once, on its current occurrence. - .sortedBy { abs(it.distanceFromCurrent ?: 0) } - .distinctBy { it.seriesId ?: it.taskId } - val open = matches.filter { !it.isClosed }.sortedWith(relevance(q)) + 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 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 openTitles = open.mapTo(HashSet()) { titleKey(it.title) } - val completed = matches - .filter { it.isCompleted && titleKey(it.title) !in openTitles } - .sortedByDescending { it.completedAt } - .distinctBy { titleKey(it.title) } - .sortedWith(relevance(q)) - val key = titleKey(q) - val exact = open.firstOrNull { titleKey(it.title) == key } - ?: completed.firstOrNull { titleKey(it.title) == key } - return ListSearchResult(open, completed, exact, offerCreate = exact == null) + 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 } + return ListSearchResult( + query = q, + open = open.map { it.task }, + completed = completed.map { it.task }, + exactMatch = exact, + offerCreate = exact == null && !pending, + ) } - private fun titleKey(title: String) = title.trim().lowercase() + fun titleKey(title: String): String = title.trim().lowercase() + + private class Hit(val task: Task, val key: String, val prefix: Boolean) { + val dedupKey = key to task.isSubtask + } /** Titles starting with the query first, then alphabetical. */ - private fun relevance(q: String): Comparator = - compareBy({ !it.title.trim().startsWith(q, ignoreCase = true) }, { it.title.trim().lowercase() }) + private val relevance = compareBy({ !it.prefix }, { it.key }) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt new file mode 100644 index 0000000..18a1101 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt @@ -0,0 +1,85 @@ +package de.jeanlucmakiola.agendula.ui.common + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.Alignment +import androidx.compose.ui.Modifier +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.unit.Dp +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.floret.components.InlineTextField + +/** + * The tonal search pill shared by the home and task-list searches: the query + * field and a clear button once there is text. It takes focus when it first + * appears, but not again when the screen comes back from another one. + * [trailingReserve] leaves room at the end for an icon a caller lays over it. + */ +@Composable +fun SearchPill( + query: String, + onQueryChange: (String) -> Unit, + placeholder: String, + modifier: Modifier = Modifier, + imeAction: ImeAction = ImeAction.Search, + onImeAction: (() -> Unit)? = null, + trailingReserve: Dp = 0.dp, +) { + val focusRequester = remember { FocusRequester() } + var focusedOnce by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(Unit) { + if (!focusedOnce) { + focusRequester.requestFocus() + focusedOnce = true + } + } + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = modifier.height(52.dp), + ) { + Row( + modifier = Modifier.padding(start = 18.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InlineTextField( + value = query, + onValueChange = onQueryChange, + placeholder = placeholder, + textStyle = MaterialTheme.typography.bodyLarge, + imeAction = imeAction, + onImeAction = onImeAction, + modifier = Modifier.weight(1f).focusRequester(focusRequester), + ) + if (query.isNotEmpty()) { + IconButton(onClick = { onQueryChange("") }) { + Icon(Icons.Rounded.Close, contentDescription = stringResource(R.string.home_search_clear)) + } + } else if (trailingReserve == 0.dp) { + Spacer(Modifier.width(18.dp)) + } + Spacer(Modifier.width(trailingReserve)) + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 6cfc0d3..3d66ab8 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -41,14 +41,10 @@ import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ListAlt import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.ChevronRight -import androidx.compose.material.icons.rounded.Close import androidx.compose.material.icons.rounded.ErrorOutline import androidx.compose.material.icons.rounded.Flag import androidx.compose.material.icons.rounded.Search @@ -73,16 +69,12 @@ 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.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.SolidColor 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.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -92,6 +84,7 @@ import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.Priority import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.ui.common.ActionShapes import de.jeanlucmakiola.floret.components.GroupedRow @@ -102,6 +95,7 @@ import de.jeanlucmakiola.floret.components.SnackChipMargin import kotlinx.coroutines.delay import de.jeanlucmakiola.agendula.ui.common.ListColorChip import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat +import de.jeanlucmakiola.agendula.ui.common.SearchPill import de.jeanlucmakiola.agendula.ui.common.ShapedActionButton import de.jeanlucmakiola.agendula.ui.common.SyncPullBox import de.jeanlucmakiola.agendula.ui.common.priorityAccent @@ -568,10 +562,13 @@ 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(), + trailingReserve = 48.dp, ) } // Always on top, at the end — the bar's fixed search icon and toggle. @@ -586,66 +583,6 @@ private fun SearchSlot( } } -/** - * The expanding search input pill: the query field (auto-focused on open) and a - * clear button once there is text. Its trailing 48dp is left empty for the search - * icon that [SearchSlot] overlays at the end. - */ -@Composable -private fun SearchPill( - query: String, - onQueryChange: (String) -> Unit, - modifier: Modifier = Modifier, -) { - val focusRequester = remember { FocusRequester() } - LaunchedEffect(Unit) { focusRequester.requestFocus() } - Surface( - shape = RoundedCornerShape(28.dp), - color = MaterialTheme.colorScheme.surfaceContainerHigh, - modifier = modifier.height(52.dp), - ) { - Row( - modifier = Modifier.padding(start = 18.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - BasicTextField( - value = query, - onValueChange = onQueryChange, - singleLine = true, - textStyle = MaterialTheme.typography.bodyLarge.copy( - color = MaterialTheme.colorScheme.onSurface, - ), - cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(), - modifier = Modifier.weight(1f).focusRequester(focusRequester), - decorationBox = { innerField -> - Box(contentAlignment = Alignment.CenterStart) { - if (query.isEmpty()) { - Text( - stringResource(R.string.home_search_hint), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - innerField() - } - }, - ) - if (query.isNotEmpty()) { - IconButton(onClick = { onQueryChange("") }) { - Icon( - Icons.Rounded.Close, - contentDescription = stringResource(R.string.home_search_clear), - ) - } - } - // Space reserved for the search icon SearchSlot overlays at the end. - Spacer(Modifier.width(48.dp)) - } - } -} - /** * Search results overlaying the home content: tasks whose title matches the query, * across every list (completed included), open ones first. A blank query renders @@ -661,11 +598,9 @@ private fun SearchResults( if (query.isBlank()) return val results = remember(query, allTasks) { val q = query.trim() - allTasks + val hits = allTasks .filter { t -> listOfNotNull(t.title, t.description, t.location).any { it.contains(q, ignoreCase = true) } } - // A series matches once, on its current occurrence. - .sortedBy { kotlin.math.abs(it.distanceFromCurrent ?: 0) } - .distinctBy { it.seriesId ?: it.taskId } + TaskSearch.currentOccurrences(hits) .sortedWith(compareBy({ it.isCompleted }, { it.title.lowercase() })) } Surface(modifier = modifier, color = MaterialTheme.colorScheme.surface) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index 5428c24..2b37684 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -206,42 +206,32 @@ fun TaskListScreen( } BackHandler(enabled = searching, onBack = closeSearch) val canCreate = listId != null && list != null && !list.isReadOnly - val searchResult = remember(query, content?.searchable) { - TaskSearch.inList(content?.searchable.orEmpty(), query) - } - // Feedback for an add or reopen from search, which clears the field at once. - var searchReceipt by remember { mutableStateOf(null) } + 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. + 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 + } + if (done != null && TaskSearch.titleKey(query) == TaskSearch.titleKey(done)) query = "" if (searchReceipt != null) { delay(4_000) - searchReceipt = null + viewModel.clearSearchReceipt() } } - val addedMessage = stringResource(R.string.task_search_added) - val reopenedMessage = stringResource(R.string.task_search_reopened) - fun runSearchAction(action: SearchSubmit) { - when (action) { - is SearchSubmit.Reopen -> { - viewModel.reopen(action.task) - searchReceipt = reopenedMessage.format(action.task.title.trim()) - } - is SearchSubmit.Create -> { - if (listId == null) return - viewModel.quickAdd(action.title, listId) - searchReceipt = addedMessage.format(action.title) - } - } - query = "" - } Scaffold( - modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection), + // The search bar replaces the collapsing one, so it must not take the scroll. + modifier = if (searching) modifier else modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { if (searching) { TaskSearchBar( query = query, onQueryChange = { query = it }, - onSubmit = { searchResult.submitAction(query, canCreate)?.let(::runSearchAction) }, + onSubmit = { viewModel.submitSearch(query, listId, canCreate) }, onClose = closeSearch, ) } else { @@ -321,11 +311,10 @@ fun TaskListScreen( TaskListUiState.Failure -> CenteredMessage(stringResource(R.string.task_list_failure), inner) is TaskListUiState.Content -> if (searching) { TaskSearchResults( - query = query, result = searchResult, canCreate = canCreate, inner = inner, - onCreate = { runSearchAction(SearchSubmit.Create(it)) }, + onCreate = { title -> viewModel.addFromSearch(title, listId) }, onToggle = viewModel::toggleComplete, onOpenTask = onOpenTask, ) @@ -361,8 +350,8 @@ fun TaskListScreen( ) { // One chip, one anchor, in priority order: the undo receipt first, // then a refused list write once the undo window is clear, then the - // read-only edit hint — the quietest of the three, so it never - // outranks something the other two are actually reporting. + // outcome of an add or reopen from search, then the read-only edit + // hint — the quietest, so it never outranks what the others report. val failure = listWriteFailure when { undo != null -> SnackChip( @@ -377,7 +366,14 @@ fun TaskListScreen( visible = true, message = stringResource(listWriteFailureMessage(failure)), ) - searchReceipt != null -> SnackChip(visible = true, message = searchReceipt.orEmpty()) + searchReceipt != null -> SnackChip( + visible = true, + 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) + else -> stringResource(R.string.edit_save_failed) + }, + ) else -> SnackChip( visible = readOnlyHint, message = stringResource(R.string.list_read_only), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt index cc56ff1..331d461 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt @@ -12,17 +12,14 @@ import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.union -import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed -import androidx.compose.foundation.shape.RoundedCornerShape 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.Close import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -30,12 +27,8 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -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.style.TextAlign @@ -43,10 +36,10 @@ import androidx.compose.ui.unit.dp import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.ListSearchResult import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.ui.common.SearchPill import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader -import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf @@ -56,19 +49,16 @@ internal sealed interface SearchSubmit { data class Create(val title: String) : SearchSubmit } -internal fun ListSearchResult.submitAction(query: String, canCreate: Boolean): SearchSubmit? { +internal fun ListSearchResult.submitAction(canCreate: Boolean): SearchSubmit? { val exact = exactMatch return when { exact != null -> if (exact.isCompleted && !exact.isReadOnly) SearchSubmit.Reopen(exact) else null - offerCreate && canCreate -> SearchSubmit.Create(query.trim()) + offerCreate && canCreate -> SearchSubmit.Create(query) else -> null } } -/** - * The task list's top bar while searching: back closes the search, and the - * field sits in the same tonal pill as the home search. - */ +/** The task list's top bar while searching: back closes the search. */ @Composable internal fun TaskSearchBar( query: String, @@ -76,8 +66,6 @@ internal fun TaskSearchBar( onSubmit: () -> Unit, onClose: () -> Unit, ) { - val focusRequester = remember { FocusRequester() } - LaunchedEffect(Unit) { focusRequester.requestFocus() } Surface(color = MaterialTheme.colorScheme.surface) { Row( modifier = Modifier @@ -90,33 +78,14 @@ internal fun TaskSearchBar( IconButton(onClick = onClose) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = stringResource(R.string.back)) } - Surface( - shape = RoundedCornerShape(28.dp), - color = MaterialTheme.colorScheme.surfaceContainerHigh, - modifier = Modifier.weight(1f).height(52.dp), - ) { - Row( - modifier = Modifier.padding(start = 18.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - InlineTextField( - value = query, - onValueChange = onQueryChange, - placeholder = stringResource(R.string.task_search_hint), - textStyle = MaterialTheme.typography.bodyLarge, - imeAction = ImeAction.Done, - onImeAction = onSubmit, - modifier = Modifier.weight(1f).focusRequester(focusRequester), - ) - if (query.isNotEmpty()) { - IconButton(onClick = { onQueryChange("") }) { - Icon(Icons.Rounded.Close, contentDescription = stringResource(R.string.home_search_clear)) - } - } else { - Spacer(Modifier.width(18.dp)) - } - } - } + SearchPill( + query = query, + onQueryChange = onQueryChange, + placeholder = stringResource(R.string.task_search_hint), + imeAction = ImeAction.Done, + onImeAction = onSubmit, + modifier = Modifier.weight(1f), + ) } } } @@ -128,7 +97,6 @@ internal fun TaskSearchBar( */ @Composable internal fun TaskSearchResults( - query: String, result: ListSearchResult, canCreate: Boolean, inner: PaddingValues, @@ -141,7 +109,7 @@ internal fun TaskSearchResults( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = inner.calculateTopPadding() + 8.dp), ) { - val q = query.trim() + val q = result.query val showCreate = result.offerCreate && canCreate when { q.isEmpty() -> item(key = "prompt") { SearchMessage(stringResource(R.string.task_search_prompt)) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index cab509e..647d870 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -8,6 +8,7 @@ import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.agendula.data.sync.RemoteLists import de.jeanlucmakiola.agendula.data.tasks.TasksRepository import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure +import de.jeanlucmakiola.agendula.domain.ListSearchResult import de.jeanlucmakiola.agendula.domain.SavedFilter import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter @@ -15,6 +16,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFiltering import de.jeanlucmakiola.agendula.domain.tagsInUse import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.TaskSection import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.agendula.domain.comparator @@ -24,6 +26,7 @@ import de.jeanlucmakiola.agendula.data.di.ApplicationScope import de.jeanlucmakiola.agendula.data.sync.ManualSync import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -32,9 +35,11 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart @@ -88,6 +93,13 @@ sealed interface UndoReceipt { data class Completed(override val task: Task, val subtasks: List = emptyList()) : UndoReceipt } +/** How an add or reopen from the list search went. */ +sealed interface SearchReceipt { + data class Added(val title: String) : SearchReceipt + data class Reopened(val title: String) : SearchReceipt + data object Failed : SearchReceipt +} + private const val UNDO_WINDOW_MS = 4_000L @OptIn(ExperimentalCoroutinesApi::class) @@ -214,9 +226,7 @@ class TaskListViewModel @Inject constructor( fun toggleComplete(task: Task) { if (task.isCompleted) { - viewModelScope.launch { - runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) } - } + viewModelScope.launch { reopenNow(task) } return } viewModelScope.launch { @@ -317,11 +327,73 @@ class TaskListViewModel @Inject constructor( } } - /** Marks a completed [task] open again, e.g. a search hit picked instead of retyping it (#95). */ - fun reopen(task: Task) { + private suspend fun reopenNow(task: Task): Boolean = + runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) }.isSuccess + + private val searchQuery = MutableStateFlow("") + + /** Titles added from search whose task has not reached [state] yet. */ + private val pendingAdds = MutableStateFlow>(emptySet()) + + private val _searchReceipt = MutableStateFlow(null) + + /** The outcome of the last add or reopen from search; the screen shows it and clears it. */ + val searchReceipt: StateFlow = _searchReceipt.asStateFlow() + + private val searchable = state + .map { (it as? TaskListUiState.Content)?.searchable.orEmpty() } + .distinctUntilChanged() + + /** The list search for the query the screen last set (#95). */ + val search: StateFlow = + 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 + } + TaskSearch.inList(tasks, query, pending) + } + .flowOn(Dispatchers.Default) + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListSearchResult.Empty) + + fun setSearchQuery(query: String) { searchQuery.value = query } + + fun clearSearchReceipt() { _searchReceipt.value = null } + + /** + * 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. + */ + fun submitSearch(query: String, listId: Long, canCreate: Boolean) { + when (val action = searchNow(query).submitAction(canCreate)) { + is SearchSubmit.Reopen -> reopenFromSearch(action.task) + is SearchSubmit.Create -> addFromSearch(action.title, listId) + null -> Unit + } + } + + /** 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 + 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 + } + } + + 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 { - runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) } + _searchReceipt.value = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4353ba1..9124ef4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -335,6 +335,7 @@ Find any task in this list, completed ones included. If it isn’t here yet, add it from here. Add “%1$s” + Open Added “%1$s” Reopened “%1$s” diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt index 1704da4..7b2db5d 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt @@ -106,4 +106,27 @@ class TaskSearchTest { assertThat(result.open).containsExactly(current) assertThat(result.completed).isEmpty() } + + @Test + fun `a subtask's title does not stand in for a top-level task`() { + val sub = done(2, "Milk", 10).copy(parentId = 1) + + val result = TaskSearch.inList(listOf(sub), "milk") + + assertThat(result.completed).containsExactly(sub) + assertThat(result.exactMatch).isNull() + assertThat(result.offerCreate).isTrue() + } + + @Test + fun `a title just added is not offered again`() { + val result = TaskSearch.inList(emptyList(), "milk", pendingTitles = setOf("Milk")) + + assertThat(result.offerCreate).isFalse() + } + + @Test + fun `the result carries the trimmed query`() { + assertThat(TaskSearch.inList(emptyList(), " Milk ").query).isEqualTo("Milk") + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt index 375e8e7..a68749e 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/tasklist/SearchSubmitTest.kt @@ -14,23 +14,23 @@ class SearchSubmitTest { fun `submitting a completed title reopens it`() { val result = TaskSearch.inList(listOf(completed), "bread") - assertThat(result.submitAction("bread", canCreate = true)).isEqualTo(SearchSubmit.Reopen(completed)) + assertThat(result.submitAction(canCreate = true)).isEqualTo(SearchSubmit.Reopen(completed)) } @Test fun `submitting a new title creates it, trimmed`() { val result = TaskSearch.inList(listOf(completed), " Milk ") - assertThat(result.submitAction(" Milk ", canCreate = true)).isEqualTo(SearchSubmit.Create("Milk")) - assertThat(result.submitAction(" Milk ", canCreate = false)).isNull() + assertThat(result.submitAction(canCreate = true)).isEqualTo(SearchSubmit.Create("Milk")) + assertThat(result.submitAction(canCreate = false)).isNull() } @Test fun `submitting an open title or a read-only one does nothing`() { val open = testTask(id = 2, title = "Milk") - assertThat(TaskSearch.inList(listOf(open), "milk").submitAction("milk", canCreate = true)).isNull() + assertThat(TaskSearch.inList(listOf(open), "milk").submitAction(canCreate = true)).isNull() val readOnly = completed.copy(isReadOnly = true) - assertThat(TaskSearch.inList(listOf(readOnly), "bread").submitAction("bread", canCreate = true)).isNull() + assertThat(TaskSearch.inList(listOf(readOnly), "bread").submitAction(canCreate = true)).isNull() } } From 75e0adfaa884800d7d0e769dc464977c61e126be Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:02:05 +0100 Subject: [PATCH 3/6] Address second review of list search (#95) --- .../agendula/domain/TaskSearch.kt | 40 +++++--- .../agendula/ui/common/SearchPill.kt | 3 + .../agendula/ui/lists/ListsScreen.kt | 7 +- .../agendula/ui/navigation/AdaptiveLayout.kt | 3 +- .../agendula/ui/tasklist/TaskListScreen.kt | 15 +-- .../agendula/ui/tasklist/TaskListSearch.kt | 22 ++--- .../agendula/ui/tasklist/TaskListViewModel.kt | 92 +++++++++++-------- app/src/main/res/values/strings.xml | 1 + .../agendula/domain/TaskSearchTest.kt | 32 +++++++ 9 files changed, 139 insertions(+), 76 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt index 849c450..6dbce8f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt @@ -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): List = - tasks.sortedBy { abs(it.distanceFromCurrent ?: 0) }.distinctBy { it.seriesId ?: it.taskId } + tasks.sortedWith( + compareBy({ 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({ !it.prefix }, { it.key }) + private val relevance = compareBy({ it.rank }, { it.key }) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt index 18a1101..41d99cd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt @@ -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), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 3d66ab8..997e2d2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -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) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AdaptiveLayout.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AdaptiveLayout.kt index 1edee7e..b2fd0cc 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AdaptiveLayout.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AdaptiveLayout.kt @@ -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), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index 2b37684..2a3a168 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -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), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt index 331d461..049219c 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt @@ -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), - ) -} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index 647d870..92b81ba 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -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 = emptyList(), ) : TaskListUiState } @@ -93,13 +95,16 @@ sealed interface UndoReceipt { data class Completed(override val task: Task, val subtasks: List = 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(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.asStateFlow() - private val searchable = state - .map { (it as? TaskListUiState.Content)?.searchable.orEmpty() } - .distinctUntilChanged() + private fun searchable(): List = (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 = - 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]. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9124ef4..2619cfa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -339,6 +339,7 @@ Open Added “%1$s” Reopened “%1$s” + “%1$s” is already open Due %1$s diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt index 7b2db5d..5addf0e 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt @@ -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 From 0e9923fcbdbddc7874f169144badbd79d52d0ae7 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:02:11 +0100 Subject: [PATCH 4/6] Changelog wording for list search (#95) --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a76eec8..3643496 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,10 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] ### Added -- A list can be searched from its top bar, completed tasks included. A - completed match can be reopened with its checkbox, and a title the list - doesn't have yet can be added straight from the search; pressing enter - reopens or adds the typed task (#95). +- A list can be searched from its top bar by title, notes or location, + completed tasks included. A completed match can be reopened with its + checkbox, and a title the list doesn't have yet can be added straight from + the search; pressing enter reopens or adds the typed task (#95). ## [1.3.2] - 2026-11-13 From a3024c8a24d1b413cb4cd51812dc550a0d987614 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:10:10 +0100 Subject: [PATCH 5/6] Address third review of list search (#95) --- .../agendula/domain/TaskSearch.kt | 7 +- .../agendula/ui/tasklist/TaskListScreen.kt | 60 ++++++------- .../agendula/ui/tasklist/TaskListSearch.kt | 16 ++-- .../agendula/ui/tasklist/TaskListViewModel.kt | 88 +++++++++++++------ .../agendula/domain/TaskSearchTest.kt | 12 +++ 5 files changed, 118 insertions(+), 65 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt index 6dbce8f..9233643 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt @@ -32,8 +32,11 @@ object TaskSearch { */ fun currentOccurrences(tasks: List): List = tasks.sortedWith( - compareBy({ it.isClosed }, { abs(it.distanceFromCurrent ?: 0) }) - .thenByDescending { it.completedAt }, + compareBy( + { it.isClosed }, + { it.status == TaskStatus.CANCELLED }, + { if (it.isClosed) 0 else abs(it.distanceFromCurrent ?: 0) }, + ).thenByDescending { it.completedAt }, ).distinctBy { it.seriesId ?: it.taskId } /** Whether [query] appears in [task]'s title, description or location. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index 2a3a168..cb87261 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -198,31 +198,24 @@ fun TaskListScreen( var showSort by rememberSaveable { mutableStateOf(false) } var confirmClear by rememberSaveable { mutableStateOf(false) } - var searchActive by rememberSaveable { mutableStateOf(false) } - var query by rememberSaveable { mutableStateOf("") } + // Held by the view model, so a search survives the switch between one and two panes. + val searchActive by viewModel.searchActive.collectAsStateWithLifecycle() + var query by remember { mutableStateOf(viewModel.searchQuery) } + LaunchedEffect(query) { viewModel.setSearchQuery(query) } + LaunchedEffect(searchActive) { if (!searchActive) query = "" } val searching = searchActive && listId != null - val closeSearch = { - query = "" - searchActive = false - } - BackHandler(enabled = searching, onBack = closeSearch) + BackHandler(enabled = searching, onBack = viewModel::closeSearch) val canCreate = listId != null && list != null && !list.isReadOnly val keyboard = LocalSoftwareKeyboardController.current - LaunchedEffect(query) { viewModel.setSearchQuery(query) } val searchResult by viewModel.search.collectAsStateWithLifecycle() - // 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 - else -> null + is SearchReceipt.AlreadyOpen, is SearchReceipt.Failed, null -> null } if (done != null && TaskSearch.titleKey(query) == TaskSearch.titleKey(done)) query = "" - if (searchReceipt != null) { - delay(4_000) - viewModel.clearSearchReceipt() - } } Scaffold( @@ -234,7 +227,7 @@ fun TaskListScreen( query = query, onQueryChange = { query = it }, onSubmit = { if (!viewModel.submitSearch(query, listId, canCreate)) keyboard?.hide() }, - onClose = closeSearch, + onClose = viewModel::closeSearch, ) } else { MediumTopAppBar( @@ -249,7 +242,7 @@ fun TaskListScreen( }, actions = { if (listId != null) { - IconButton(onClick = { searchActive = true }, enabled = content != null) { + IconButton(onClick = viewModel::openSearch, enabled = content != null) { Icon(Icons.Rounded.Search, contentDescription = stringResource(R.string.task_search_action)) } } @@ -302,7 +295,7 @@ fun TaskListScreen( ) { inner -> Box(modifier = Modifier.fillMaxSize()) { SyncPullBox( - available = syncAvailable && !searching, + available = syncAvailable, syncing = syncing, onSync = viewModel::syncAll, modifier = Modifier.fillMaxSize(), @@ -311,23 +304,24 @@ fun TaskListScreen( when (val s = state) { TaskListUiState.Loading -> Unit // brief; avoids a flash before first emission TaskListUiState.Failure -> CenteredMessage(stringResource(R.string.task_list_failure), inner) - is TaskListUiState.Content -> if (searching) { - TaskSearchResults( - result = searchResult, - canCreate = canCreate, - inner = inner, - onCreate = { title -> viewModel.addFromSearch(title, listId) }, - onToggle = viewModel::toggleComplete, - onOpenTask = onOpenTask, - ) - } else { - TaskListBody( - s, filter, inner, onOpenTask, onRequestDelete, viewModel, - onClearCompleted = if (listId != null && list?.isReadOnly != true) ({ confirmClear = true }) else null, - ) - } + is TaskListUiState.Content -> TaskListBody( + s, filter, inner, onOpenTask, onRequestDelete, viewModel, + onClearCompleted = if (listId != null && list?.isReadOnly != true) ({ confirmClear = true }) else null, + ) } } + // Laid over the list rather than swapped in, so the list keeps its scroll and expanded groups. + if (searching && content != null) { + TaskSearchResults( + query = query, + result = searchResult, + canCreate = canCreate, + inner = inner, + onCreate = { title -> viewModel.addFromSearch(title, listId) }, + onToggle = viewModel::toggleComplete, + onOpenTask = onOpenTask, + ) + } // A FAB-height band anchored at the bottom-start with the FAB's own // margin; centring the chip in it lines the chip up beside the bottom-end // FAB at exactly its height, rather than sitting a touch above it. @@ -374,7 +368,7 @@ fun TaskListScreen( 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) + is SearchReceipt.Failed, null -> stringResource(R.string.edit_save_failed) }, ) else -> SnackChip( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt index 049219c..ccc4da6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt @@ -92,10 +92,13 @@ internal fun TaskSearchBar( /** * Search hits for one list: an "Add …" row while no task carries the typed * title, then the open matches and the completed ones, each a grouped run of - * the list's own rows. Checking a completed hit off reopens it. + * the list's own rows. Checking a completed hit off reopens it. [result] is + * worked out off the main thread, so until it catches up with [query] only its + * hits show, never an action for an older query. */ @Composable internal fun TaskSearchResults( + query: String, result: ListSearchResult, canCreate: Boolean, inner: PaddingValues, @@ -108,13 +111,14 @@ internal fun TaskSearchResults( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = inner.calculateTopPadding() + 8.dp), ) { - val q = result.query - val showCreate = result.offerCreate && canCreate + val q = query.trim() + val fresh = result.query == q + val showCreate = fresh && canCreate && (result.offerCreate || result.adding) when { 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() -> + fresh && !showCreate && result.open.isEmpty() && result.completed.isEmpty() -> item(key = "empty") { EmptyState(stringResource(R.string.home_search_empty, q), icon = Icons.Rounded.Search) } } if (showCreate) { @@ -122,12 +126,14 @@ internal fun TaskSearchResults( GroupedRow( title = stringResource(R.string.task_search_add, q), position = Position.Alone, + dimmed = result.adding, leading = { Icon(Icons.Rounded.Add, contentDescription = null, tint = MaterialTheme.colorScheme.primary) }, minHeight = 64.dp, - onClick = { onCreate(q) }, + onClick = if (result.adding) null else ({ onCreate(q) }), ) } } + if (q.isEmpty()) return@LazyColumn hitSection("open", R.string.task_search_open, result.open, onToggle, onOpenTask) hitSection("completed", R.string.section_completed, result.completed, onToggle, onOpenTask) item(key = "bottom-inset") { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index 92b81ba..032270e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.agendula.ui.tasklist +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -103,7 +104,9 @@ sealed interface SearchReceipt { class Failed : SearchReceipt } -private const val PENDING_ADD_TIMEOUT_MS = 10_000L +private const val PENDING_ADD_TIMEOUT_MS = 30_000L +private const val KEY_SEARCH_ACTIVE = "task_search_active" +private const val KEY_SEARCH_QUERY = "task_search_query" private const val UNDO_WINDOW_MS = 4_000L @@ -115,6 +118,7 @@ class TaskListViewModel @Inject constructor( private val remoteLists: RemoteLists, private val manualSync: ManualSync, @ApplicationScope private val appScope: CoroutineScope, + private val savedState: SavedStateHandle, ) : ViewModel() { /** Pull to sync (#73); off without an account. */ @@ -221,7 +225,13 @@ class TaskListViewModel @Inject constructor( /** The screen reports which expanded parents need their children fetched. */ fun setLazyChildParents(ids: Set) { lazyChildParents.value = ids } - fun bind(taskFilter: TaskFilter) { filter.value = taskFilter } + fun bind(taskFilter: TaskFilter) { + if (filter.value != null && filter.value != taskFilter) { + closeSearch() + pendingAdds.value = emptySet() + } + filter.value = taskFilter + } fun toggleTagFilter(tag: String) { tagFilter.value = if (tag in tagFilter.value) tagFilter.value - tag else tagFilter.value + tag @@ -335,37 +345,65 @@ class TaskListViewModel @Inject constructor( private suspend fun reopenNow(task: Task): Boolean = runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) }.isSuccess - private val searchQuery = MutableStateFlow("") + /** Whether the list search is open; kept here so it outlives the screen's own composition. */ + val searchActive: StateFlow = savedState.getStateFlow(KEY_SEARCH_ACTIVE, false) + + /** The last query the screen set, to seed its field when it is composed afresh. */ + val searchQuery: String get() = savedState[KEY_SEARCH_QUERY] ?: "" + + private val query = savedState.getStateFlow(KEY_SEARCH_QUERY, "") /** Titles added from search whose task has not reached [state] yet. */ private val pendingAdds = MutableStateFlow>(emptySet()) private val _searchReceipt = MutableStateFlow(null) - /** The outcome of the last action from search; the screen shows it and clears it. */ + /** The outcome of the last action from search, shown for a few seconds. */ val searchReceipt: StateFlow = _searchReceipt.asStateFlow() + private var searchReceiptTimer: Job? = null - private fun searchable(): List = (state.value as? TaskListUiState.Content)?.searchable.orEmpty() + /** The searchable tasks, but only once [state] is for the filter now bound. */ + private fun searchable(): List = + (state.value as? TaskListUiState.Content)?.takeIf { it.filter == filter.value }?.searchable.orEmpty() - /** The list search for the query the screen last set (#95); idle while the query is blank. */ + /** The list search for the current query (#95); idle while the query is blank. */ val search: StateFlow = - searchQuery + query .map { it.trim() } .distinctUntilChanged() - .flatMapLatest { query -> - if (query.isEmpty()) { + .flatMapLatest { q -> + if (q.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) } + val tasks = state + .map { st -> (st as? TaskListUiState.Content)?.takeIf { it.filter == filter.value }?.searchable.orEmpty() } + .distinctUntilChanged { a, b -> a === b } + combine(tasks, pendingAdds) { list, pending -> TaskSearch.inList(list, q, pending) } } } .flowOn(Dispatchers.Default) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListSearchResult.Empty) - fun setSearchQuery(query: String) { searchQuery.value = query } + fun openSearch() { savedState[KEY_SEARCH_ACTIVE] = true } - fun clearSearchReceipt() { _searchReceipt.value = null } + fun closeSearch() { + savedState[KEY_SEARCH_ACTIVE] = false + savedState[KEY_SEARCH_QUERY] = "" + showSearchReceipt(null) + } + + fun setSearchQuery(query: String) { savedState[KEY_SEARCH_QUERY] = query } + + private fun showSearchReceipt(receipt: SearchReceipt?) { + searchReceiptTimer?.cancel() + _searchReceipt.value = receipt + if (receipt != null) { + searchReceiptTimer = viewModelScope.launch { + delay(UNDO_WINDOW_MS) + _searchReceipt.value = null + } + } + } /** * Enter in the search field: reopens the completed task titled [query], or @@ -380,7 +418,7 @@ class TaskListViewModel @Inject constructor( is SearchSubmit.Create -> add(action.title, listId) null -> { val open = result.exactMatch?.takeIf { !it.isClosed } ?: return false - _searchReceipt.value = SearchReceipt.AlreadyOpen(open.title.trim()) + showSearchReceipt(SearchReceipt.AlreadyOpen(open.title.trim())) } } return true @@ -392,27 +430,27 @@ class TaskListViewModel @Inject constructor( if (result.offerCreate) add(result.query, listId) } + /** + * Runs in the application scope so leaving the screen right after cannot + * cancel the write. The title stays pending until the new task shows up. + */ private fun add(title: String, listId: Long) { if (listId <= 0L) return pendingAdds.update { it + title } - viewModelScope.launch { - 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) + appScope.launch { + val id = runCatching { repository.createTask(TaskForm(title = title, listId = listId)) }.getOrNull() + showSearchReceipt(if (id != null) SearchReceipt.Added(title) else SearchReceipt.Failed()) + if (id != null) { withTimeoutOrNull(PENDING_ADD_TIMEOUT_MS) { - state.first { st -> - (st as? TaskListUiState.Content)?.searchable.orEmpty() - .any { !it.isClosed && !it.isSubtask && TaskSearch.titleKey(it.title) == key } - } + state.first { st -> (st as? TaskListUiState.Content)?.searchable.orEmpty().any { it.taskId == id } } } } pendingAdds.update { it - title } } } - private fun reopenFromSearch(task: Task) = viewModelScope.launch { - _searchReceipt.value = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed() + private fun reopenFromSearch(task: Task) = appScope.launch { + showSearchReceipt(if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed()) } /** Inline "add task" — title only, into [listId]. */ diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt index 5addf0e..4d8e5e0 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt @@ -147,6 +147,18 @@ class TaskSearchTest { assertThat(TaskSearch.inList(listOf(older, newer), "water").completed).containsExactly(newer) } + @Test + fun `an ended series is found by its last completion, not a later skipped occurrence`() { + val completed = done(2, "Water plants", 50).copy(seriesId = 1, occurrenceStart = at(100), distanceFromCurrent = -1) + val skipped = testTask(id = 3, title = "Water plants", status = TaskStatus.CANCELLED) + .copy(seriesId = 1, occurrenceStart = at(200), distanceFromCurrent = 0) + + val result = TaskSearch.inList(listOf(completed, skipped), "water plants") + + assertThat(result.completed).containsExactly(completed) + assertThat(result.exactMatch).isEqualTo(completed) + } + @Test fun `description and location match too, after title matches`() { val byNote = testTask(id = 1, title = "Call landlord").copy(description = "about the rent") From 634a89224c97b8a735609b154366745ace936c71 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:11:05 +0100 Subject: [PATCH 6/6] Post search receipts on the main thread (#95) --- .../agendula/ui/tasklist/TaskListViewModel.kt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index 032270e..31f4369 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -47,6 +47,7 @@ import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject @@ -439,7 +440,9 @@ class TaskListViewModel @Inject constructor( pendingAdds.update { it + title } appScope.launch { val id = runCatching { repository.createTask(TaskForm(title = title, listId = listId)) }.getOrNull() - showSearchReceipt(if (id != null) SearchReceipt.Added(title) else SearchReceipt.Failed()) + withContext(Dispatchers.Main) { + showSearchReceipt(if (id != null) SearchReceipt.Added(title) else SearchReceipt.Failed()) + } if (id != null) { withTimeoutOrNull(PENDING_ADD_TIMEOUT_MS) { state.first { st -> (st as? TaskListUiState.Content)?.searchable.orEmpty().any { it.taskId == id } } @@ -450,7 +453,8 @@ class TaskListViewModel @Inject constructor( } private fun reopenFromSearch(task: Task) = appScope.launch { - showSearchReceipt(if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed()) + val receipt = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed() + withContext(Dispatchers.Main) { showSearchReceipt(receipt) } } /** Inline "add task" — title only, into [listId]. */