Address third review of list search (#95)
This commit is contained in:
1 parent
0e9923fcbd
commit
a3024c8a24
5 files changed
+118
-65
No files matched your search
@@ -32,8 +32,11 @@ object TaskSearch {
|
||||
*/
|
||||
fun currentOccurrences(tasks: List<Task>): List<Task> =
|
||||
tasks.sortedWith(
|
||||
compareBy<Task>({ it.isClosed }, { abs(it.distanceFromCurrent ?: 0) })
|
||||
.thenByDescending { it.completedAt },
|
||||
compareBy<Task>(
|
||||
{ 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. */
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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<Long>) { 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<Boolean> = 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<Set<String>>(emptySet())
|
||||
|
||||
private val _searchReceipt = MutableStateFlow<SearchReceipt?>(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?> = _searchReceipt.asStateFlow()
|
||||
private var searchReceiptTimer: Job? = null
|
||||
|
||||
private fun searchable(): List<Task> = (state.value as? TaskListUiState.Content)?.searchable.orEmpty()
|
||||
/** The searchable tasks, but only once [state] is for the filter now bound. */
|
||||
private fun searchable(): List<Task> =
|
||||
(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<ListSearchResult> =
|
||||
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]. */
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user