Task grouping: keep rows and day window together, safer list cleanup (#71)

This commit is contained in:
makiolaj committed 2026-11-17 11:21:44 +01:00
1 parent 761f3f5b3d
commit 367e04fa72
4 files changed
+55 -76

No files matched your search

@@ -228,14 +228,11 @@ class SettingsPrefs @Inject constructor(
p[GROUPINGS] = if (grouping == TaskGrouping.DUE) kept else kept + "${grouping.name}$GROUPING_SEPARATOR$key"
}
/**
* Drops the groupings and folds remembered for lists of the current store
* that are gone, however they went, so a later list given the same id starts fresh.
*/
suspend fun retainLists(listIds: Set<Long>) = dataStore.edit { p ->
val mode = modeOf(p).name
p[GROUPINGS]?.let { p[GROUPINGS] = keepLiveLists(it, mode, listIds) { e -> e.substringAfter(GROUPING_SEPARATOR) } }
p[COLLAPSED_SECTIONS]?.let { p[COLLAPSED_SECTIONS] = keepLiveLists(it, mode, listIds) }
/** Drops what was remembered about a list deleted here, so a later list given its id starts fresh. */
suspend fun forgetList(listId: Long) = dataStore.edit { p ->
val key = scopeListKey("${TaskGroupKey.LIST_PREFIX}$listId", modeOf(p).name)
p[GROUPINGS]?.let { all -> p[GROUPINGS] = all.filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key } }
p[COLLAPSED_SECTIONS]?.let { p[COLLAPSED_SECTIONS] = it - key }
}
suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name }
@@ -432,20 +429,6 @@ private const val GROUPING_SEPARATOR = '|'
private fun scopeListKey(key: String, mode: String): String =
if (key.startsWith(TaskGroupKey.LIST_PREFIX)) "${TaskGroupKey.LIST_PREFIX}$mode:${key.removePrefix(TaskGroupKey.LIST_PREFIX)}" else key
/** [entries] without those naming a list of the [mode] store that is not in [listIds]; [keyOf] finds an entry's key. */
internal fun keepLiveLists(
entries: Set<String>,
mode: String,
listIds: Set<Long>,
keyOf: (String) -> String = { it },
): Set<String> = entries.filterTo(HashSet()) { entry ->
val id = unscopeListKey(keyOf(entry), mode)
?.takeIf { it.startsWith(TaskGroupKey.LIST_PREFIX) }
?.removePrefix(TaskGroupKey.LIST_PREFIX)
?.toLongOrNull()
id == null || id in listIds
}
/** The reverse of [scopeListKey]; `null` for a list of another store. */
internal fun unscopeListKey(stored: String, mode: String): String? {
if (!stored.startsWith(TaskGroupKey.LIST_PREFIX)) return stored
@@ -407,11 +407,9 @@ private fun TaskListBody(
}
val listId = (filter as? TaskFilter.OfList)?.listId
// In a mixed view (a smart list) the list colour bar + name disambiguate
// rows; inside a single real list, or under a list's own header, the name is redundant.
val showListName = state.grouping != TaskGrouping.LIST && (
filter is TaskFilter.Smart || filter is TaskFilter.Tagged ||
(filter is TaskFilter.Saved && state.savedFilter?.listIds?.size != 1)
)
// rows; inside a single real list both are redundant.
val mixedView = filter is TaskFilter.Smart || filter is TaskFilter.Tagged ||
(filter is TaskFilter.Saved && state.savedFilter?.listIds?.size != 1)
// Parents the user expanded to reveal their subtasks inline. Children are
// grouped from the same flat task set the list already holds.
var expandedParents by rememberSaveable { mutableStateOf(emptySet<Long>()) }
@@ -463,6 +461,10 @@ private fun TaskListBody(
groups.forEach { group ->
// Every header folds its section away (#91); Done starts folded.
val groupId = group.key.id
// Under a list's or a priority's own header the row needn't repeat it; Done mixes them all.
val inDone = group.key == TaskGroupKey.COMPLETED
val showListName = mixedView && (state.grouping != TaskGrouping.LIST || inDone)
val showPriority = state.grouping != TaskGrouping.PRIORITY || inDone
val expanded = !showHeaders || groupId !in state.collapsedGroups
if (showHeaders) {
stickyHeader(key = "hdr-$groupId") {
@@ -536,7 +538,7 @@ private fun TaskListBody(
position = r.position,
lastInRun = lastInRun,
showListName = showListName,
showPriority = state.grouping != TaskGrouping.PRIORITY,
showPriority = showPriority,
subtaskDone = row.task.subtaskDone,
subtaskTotal = row.task.subtaskTotal,
expanded = row.expanded,
@@ -6,6 +6,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.agendula.data.prefs.DEFAULT_COLLAPSED_GROUPS
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.sync.RemoteLists
import de.jeanlucmakiola.agendula.data.tasks.FilteredTasks
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
import de.jeanlucmakiola.agendula.domain.SavedFilter
@@ -40,7 +41,7 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@@ -135,52 +136,45 @@ class TaskListViewModel @Inject constructor(
val undo: StateFlow<UndoReceipt?> = _undo.asStateFlow()
private var undoTimer: Job? = null
/** Today's bounds, moving on at midnight; the lists re-read then, as their date windows shift. */
private val dayWindow: StateFlow<Pair<Instant, Instant>> =
/**
* Today's bounds. Checked every minute rather than slept on until midnight, so a
* time-zone or clock change moves them too; the rows re-read whenever they move.
*/
private val dayWindow: Flow<Pair<Instant, Instant>> =
flow {
while (true) {
val window = today()
val window = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
emit(window)
delay((window.second - Clock.System.now()).inWholeMilliseconds.coerceAtLeast(0) + 1_000)
delay((window.second - Clock.System.now()).inWholeMilliseconds.coerceIn(0, 60_000) + 1)
}
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), today())
private fun today() = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
private var retainedLists: Set<Long>? = null
/** Forgets groupings and folds of lists that are gone; runs only when the set of lists changes. */
private fun retainLists(lists: List<TaskList>) {
val ids = lists.mapTo(HashSet()) { it.id }
if (ids.isEmpty() || ids == retainedLists) return
retainedLists = ids
viewModelScope.launch { runCatching { settingsPrefs.retainLists(ids) } }
}
}.distinctUntilChanged()
val state: StateFlow<TaskListUiState> =
filter.filterNotNull()
.flatMapLatest { f ->
val lists = repository.taskLists().onEach(::retainLists)
val content: Flow<TaskListUiState> = when (f) {
is TaskFilter.OfList ->
combine(dayWindow.flatMapLatest { repository.tasks(f) }, lists) { rows, all ->
TaskListUiState.Content(rows, all.firstOrNull { it.id == f.listId }, listOrder = all.map { it.id })
}
is TaskFilter.Smart, is TaskFilter.Tagged ->
combine(dayWindow.flatMapLatest { repository.tasks(f) }, lists) { rows, all ->
TaskListUiState.Content(rows, listOrder = all.map { it.id })
}
is TaskFilter.Saved ->
combine(dayWindow.flatMapLatest { repository.filteredTasks(f) }, lists) { found, all ->
TaskListUiState.Content(found.tasks, savedFilter = found.savedFilter, listOrder = all.map { it.id })
}
val source: Flow<FilteredTasks> = when (f) {
is TaskFilter.Saved -> repository.filteredTasks(f)
is TaskFilter.OfList, is TaskFilter.Smart, is TaskFilter.Tagged ->
repository.tasks(f).map { FilteredTasks(it) }
// Several lists at once only exists for the widget, which never routes here.
is TaskFilter.OfLists -> error("OfLists has no task-list screen")
}
// Each read carries the day it was made for, so rows and groups always agree.
val rows = dayWindow.flatMapLatest { window -> source.map { window to it } }
val content: Flow<TaskListUiState> = combine(rows, repository.taskLists()) { (window, found), lists ->
TaskListUiState.Content(
tasks = found.tasks,
list = (f as? TaskFilter.OfList)?.let { of -> lists.firstOrNull { it.id == of.listId } },
savedFilter = found.savedFilter,
listOrder = lists.map { it.id },
todayStart = window.first,
todayEnd = window.second,
)
}
// Drop rows pending an undoable delete so the row vanishes on swipe
// while the actual provider delete waits for the snackbar to commit,
// and fold in the live UI settings (add-subtask row, bottom add bar).
combine(content, pendingDeletes, settingsPrefs.settings, tagFilter, dayWindow) { st, pending, settings, tags, window ->
combine(content, pendingDeletes, settingsPrefs.settings, tagFilter) { st, pending, settings, tags ->
if (st is TaskListUiState.Content) {
val visible = settings.visibleIn(f, st.tasks).filter { it.occurrenceKey !in pending }
val available = tagsInUse(visible) - setOfNotNull((f as? TaskFilter.Tagged)?.tag)
@@ -201,8 +195,6 @@ class TaskListViewModel @Inject constructor(
sortOrder = settings.sortOrder,
grouping = settings.groupingFor(f).takeIf { it in groupings } ?: TaskGrouping.DUE,
groupings = groupings,
todayStart = window.first,
todayEnd = window.second,
collapsedGroups = settings.collapsedGroups,
hiddenFromSmartLists = st.list?.id?.let { it in settings.hiddenFromSmartLists } ?: false,
)
@@ -412,7 +404,10 @@ class TaskListViewModel @Inject constructor(
fun deleteList(listId: Long, accountId: Long?) = viewModelScope.launch {
if (accountId == null) {
runCatching { repository.deleteList(listId) }
.onSuccess { _listDeleted.value = true }
.onSuccess {
_listDeleted.value = true
forgetList(listId)
}
.onFailure { _listWriteFailure.value = ListWriteFailure.DELETE }
return@launch
}
@@ -424,7 +419,17 @@ class TaskListViewModel @Inject constructor(
val outcome = runCatching { remoteLists.delete(listId) }
.getOrElse { RemoteLists.Outcome.Unreachable }
val failure = outcome.asFailure(ListWriteFailure.DELETE)
if (failure == null) _listDeleted.value = true else _listWriteFailure.value = failure
if (failure == null) {
_listDeleted.value = true
forgetList(listId)
} else {
_listWriteFailure.value = failure
}
}
/** In the app scope: the screen leaves as soon as the list is gone. */
private fun forgetList(listId: Long) {
appScope.launch { runCatching { settingsPrefs.forgetList(listId) } }
}
/** Inline "add subtask" from an expanded list group — files it under [parent]. */
@@ -38,17 +38,6 @@ class TaskGroupingPrefsTest {
assertThat(unscopeListKey("priority:HIGH", "OWN")).isEqualTo("priority:HIGH")
}
@Test
fun `entries for lists that are gone are dropped, other stores' lists kept`() {
val kept = keepLiveLists(
setOf("DAY|list:OWN:5", "LIST|list:OWN:6", "PRIORITY|list:PROVIDER:6", "DAY|smart:ALL"),
mode = "OWN",
listIds = setOf(5L),
) { it.substringAfter('|') }
assertThat(kept).containsExactly("DAY|list:OWN:5", "PRIORITY|list:PROVIDER:6", "DAY|smart:ALL")
assertThat(keepLiveLists(setOf("COMPLETED", "list:OWN:9"), "OWN", setOf(5L))).containsExactly("COMPLETED")
}
@Test
fun `collapsed day groups that have passed are dropped`() {
val today = LocalDate.of(2026, 11, 17)