diff --git a/CHANGELOG.md b/CHANGELOG.md index d9b5870..1ed560b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,10 @@ All notable changes to this project are documented here. The format follows - A "Remind right away when past" setting under Notifications: saving a task whose reminder time has already passed, such as one starting now, notifies at once instead of leaving the reminder out (#106). +- 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 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..9233643 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSearch.kt @@ -0,0 +1,89 @@ +package de.jeanlucmakiola.agendula.domain + +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 top-level task already titled exactly as the query, open or completed, if any. */ + 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) + } +} + +/** + * Search over one list's tasks, open and completed alike, so an old task can be + * reopened instead of typed again (#95). + */ +object TaskSearch { + + /** + * 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.sortedWith( + 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. */ + 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 + * [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 key = titleKey(q) + val hits = currentOccurrences(tasks.filter { matches(it, q) }).map { Hit(it, q) } + val open = hits.filter { !it.task.isClosed }.sortedWith(relevance) + 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) + val exact = (open + completed).firstOrNull { it.key == key && !it.task.isSubtask }?.task + 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 && !adding, + adding = adding, + ) + } + + fun titleKey(title: String): String = title.trim().lowercase() + + 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 + } + } + + 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 new file mode 100644 index 0000000..41d99cd --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/SearchPill.kt @@ -0,0 +1,88 @@ +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.text.input.KeyboardCapitalization +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, + capitalization: KeyboardCapitalization = KeyboardCapitalization.Sentences, + 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, + capitalization = capitalization, + 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 dd0c277..d62ca87 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,13 @@ 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.input.KeyboardCapitalization import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -93,6 +86,7 @@ import de.jeanlucmakiola.agendula.domain.TaskEnd 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 @@ -103,6 +97,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 @@ -572,7 +567,10 @@ private fun SearchSlot( SearchPill( query = query, onQueryChange = onQueryChange, + placeholder = stringResource(R.string.home_search_hint), modifier = Modifier.fillMaxWidth(), + capitalization = KeyboardCapitalization.None, + trailingReserve = 48.dp, ) } // Always on top, at the end — the bar's fixed search icon and toggle. @@ -587,66 +585,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 @@ -662,11 +600,7 @@ private fun SearchResults( if (query.isBlank()) return val results = remember(query, allTasks) { val q = query.trim() - 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(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 dd12e96..05fdb98 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 @@ -95,10 +97,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 @@ -116,6 +120,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 @@ -195,54 +200,89 @@ fun TaskListScreen( var showSort by rememberSaveable { mutableStateOf(false) } var confirmClear by rememberSaveable { mutableStateOf(false) } + // 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 + BackHandler(enabled = searching, onBack = viewModel::closeSearch) + val canCreate = listId != null && list != null && !list.isReadOnly + val keyboard = LocalSoftwareKeyboardController.current + val searchResult by viewModel.search.collectAsStateWithLifecycle() + val searchReceipt by viewModel.searchReceipt.collectAsStateWithLifecycle() + LaunchedEffect(searchReceipt) { + val done = when (val r = searchReceipt) { + is SearchReceipt.Added -> r.title + is SearchReceipt.Reopened -> r.title + is SearchReceipt.AlreadyOpen, is SearchReceipt.Failed, null -> null + } + if (done != null && TaskSearch.titleKey(query) == TaskSearch.titleKey(done)) 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 = { - 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) { - val narrowed = content?.selectedTags?.isNotEmpty() == true || content?.upcomingLimited == true - BadgedBox(badge = { if (narrowed) 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 = { if (!viewModel.submitSearch(query, listId, canCreate)) keyboard?.hide() }, + onClose = viewModel::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 = viewModel::openSearch, enabled = content != null) { + Icon(Icons.Rounded.Search, contentDescription = stringResource(R.string.task_search_action)) + } + } + IconButton(onClick = { showSort = true }, enabled = content != null) { + val narrowed = content?.selectedTags?.isNotEmpty() == true || content?.upcomingLimited == true + BadgedBox(badge = { if (narrowed) 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) }, @@ -251,7 +291,7 @@ fun TaskListScreen( } }, bottomBar = { - if (showBottomAddBar) { + if (showBottomAddBar && !searching) { QuickAddBar(onAdd = { title -> viewModel.quickAdd(title, listId) }) } }, @@ -273,23 +313,44 @@ fun TaskListScreen( ) } } + // 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. + // 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, ) { // 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( @@ -304,6 +365,15 @@ fun TaskListScreen( visible = true, message = stringResource(listWriteFailureMessage(failure)), ) + 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) + is SearchReceipt.AlreadyOpen -> stringResource(R.string.task_search_already_open, r.title) + is SearchReceipt.Failed, null -> stringResource(R.string.edit_save_failed) + }, + ) else -> SnackChip( visible = readOnlyHint, message = stringResource(R.string.list_read_only), @@ -1201,13 +1271,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 new file mode 100644 index 0000000..ccc4da6 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListSearch.kt @@ -0,0 +1,174 @@ +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.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.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.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.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.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(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) + else -> null + } +} + +/** The task list's top bar while searching: back closes the search. */ +@Composable +internal fun TaskSearchBar( + query: String, + onQueryChange: (String) -> Unit, + onSubmit: () -> Unit, + onClose: () -> Unit, +) { + 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)) + } + SearchPill( + query = query, + onQueryChange = onQueryChange, + placeholder = stringResource(R.string.task_search_hint), + imeAction = ImeAction.Done, + onImeAction = onSubmit, + modifier = Modifier.weight(1f), + ) + } + } +} + +/** + * 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. [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, + 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 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) + } + 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) { + item(key = "create") { + 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 = 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") { + 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) }, + ) + } + } +} 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 595f659..5be4f2f 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 @@ -8,6 +9,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.SmartList import de.jeanlucmakiola.agendula.domain.Task @@ -15,6 +17,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskFiltering import de.jeanlucmakiola.agendula.domain.tagsInUse 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.UpcomingRange @@ -26,6 +29,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 @@ -34,14 +38,19 @@ 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 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 import kotlin.time.Clock @@ -77,6 +86,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, + /** A real list's tasks before the tag filter narrows them, which its search looks through; empty elsewhere. */ + val searchable: List = emptyList(), ) : TaskListUiState { /** Upcoming, narrowed to a time frame the user picked. */ val upcomingLimited: Boolean @@ -96,6 +107,18 @@ sealed interface UndoReceipt { data class Completed(override val task: Task, val subtasks: List = emptyList()) : UndoReceipt } +/** How an action from the list search went. Not data classes: a repeat must still re-emit. */ +sealed interface 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 = 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 @OptIn(ExperimentalCoroutinesApi::class) @@ -107,6 +130,7 @@ class TaskListViewModel @Inject constructor( private val manualSync: ManualSync, private val widgetUpdater: TaskWidgetUpdater, @ApplicationScope private val appScope: CoroutineScope, + private val savedState: SavedStateHandle, ) : ViewModel() { /** Pull to sync (#73); off without an account. */ @@ -169,6 +193,7 @@ class TaskListViewModel @Inject constructor( .sortedWith(settings.sortOrder.comparator()), availableTags = available, selectedTags = selected, + searchable = if (f is TaskFilter.OfList) visible else emptyList(), showAddSubtaskRow = settings.showAddSubtaskRow, bottomAddBar = settings.bottomAddBar, sortOrder = settings.sortOrder, @@ -218,7 +243,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 @@ -228,9 +259,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 { @@ -336,6 +365,120 @@ class TaskListViewModel @Inject constructor( } } + private suspend fun reopenNow(task: Task): Boolean = + runCatching { repository.setCompleted(task.taskId, task.occurrenceStart, false) }.isSuccess + + /** 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, shown for a few seconds. */ + val searchReceipt: StateFlow = _searchReceipt.asStateFlow() + private var searchReceiptTimer: Job? = null + + /** 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 current query (#95); idle while the query is blank. */ + val search: StateFlow = + query + .map { it.trim() } + .distinctUntilChanged() + .flatMapLatest { q -> + if (q.isEmpty()) { + flowOf(ListSearchResult.Empty) + } else { + 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 openSearch() { savedState[KEY_SEARCH_ACTIVE] = true } + + 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 + * 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): Boolean { + val result = TaskSearch.inList(searchable(), query, pendingAdds.value) + when (val action = result.submitAction(canCreate)) { + is SearchSubmit.Reopen -> reopenFromSearch(action.task) + is SearchSubmit.Create -> add(action.title, listId) + null -> { + val open = result.exactMatch?.takeIf { !it.isClosed } ?: return false + showSearchReceipt(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 = TaskSearch.inList(searchable(), title, pendingAdds.value) + 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 } + appScope.launch { + val id = runCatching { repository.createTask(settingsPrefs.settings.first().quickTask(title, listId)) }.getOrNull() + 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 } } + } + } + pendingAdds.update { it - title } + } + } + + private fun reopenFromSearch(task: Task) = appScope.launch { + val receipt = if (reopenNow(task)) SearchReceipt.Reopened(task.title.trim()) else SearchReceipt.Failed() + withContext(Dispatchers.Main) { showSearchReceipt(receipt) } + } + /** Inline "add task" — a title into [listId], with the default dates. */ 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 fc18199..129d8ee 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -358,6 +358,18 @@ 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” + “%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 new file mode 100644 index 0000000..4d8e5e0 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSearchTest.kt @@ -0,0 +1,176 @@ +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() + } + + @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() + 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 `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") + val byTitle = testTask(id = 2, title = "Pay rent") + + val result = TaskSearch.inList(listOf(byNote, byTitle), "rent") + + assertThat(result.open).containsExactly(byTitle, byNote).inOrder() + } + + @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 new file mode 100644 index 0000000..a68749e --- /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(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(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(canCreate = true)).isNull() + + val readOnly = completed.copy(isReadOnly = true) + assertThat(TaskSearch.inList(listOf(readOnly), "bread").submitAction(canCreate = true)).isNull() + } +}