Task grouping: prune gone lists, refresh at midnight, tidy up (#71)

This commit is contained in:
makiolaj committed 2026-11-17 11:15:42 +01:00
1 parent a94b5be885
commit 761f3f5b3d
8 files changed
+113 -52

No files matched your search

@@ -228,11 +228,14 @@ class SettingsPrefs @Inject constructor(
p[GROUPINGS] = if (grouping == TaskGrouping.DUE) kept else kept + "${grouping.name}$GROUPING_SEPARATOR$key"
}
/** Drops what was remembered about a deleted list, 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] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key }
p[COLLAPSED_SECTIONS]?.let { p[COLLAPSED_SECTIONS] = it - 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) }
}
suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name }
@@ -429,6 +432,20 @@ 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
@@ -82,7 +82,7 @@ object TaskGroups {
/** The groupings worth offering for [filter]: ones that can change what it shows. */
fun offeredFor(filter: TaskFilter, savedFilter: SavedFilter? = null): List<TaskGrouping> {
val dropped = when (filter) {
val dropped: Set<TaskGrouping> = when (filter) {
// Every task in it is done, and done tasks always share one group.
is TaskFilter.Smart -> when (filter.list) {
SmartList.COMPLETED -> return emptyList()
@@ -91,8 +91,15 @@ object TaskGroups {
SmartList.ALL, SmartList.UPCOMING -> emptySet()
}
// A single list is one list already.
is TaskFilter.OfList, is TaskFilter.OfLists -> setOf(TaskGrouping.LIST)
is TaskFilter.Saved -> if (savedFilter?.listIds?.size == 1) setOf(TaskGrouping.LIST) else emptySet()
is TaskFilter.OfList -> setOf(TaskGrouping.LIST)
// No task-list screen, so nowhere to remember a grouping.
is TaskFilter.OfLists -> return emptyList()
is TaskFilter.Saved -> buildSet {
if (savedFilter?.listIds?.size == 1) add(TaskGrouping.LIST)
// Due windows without Upcoming leave no later days to split.
val due = savedFilter?.due.orEmpty()
if (due.isNotEmpty() && DueWindow.UPCOMING !in due) add(TaskGrouping.DAY)
}
is TaskFilter.Tagged -> emptySet()
}
return TaskGrouping.entries - dropped
@@ -129,7 +136,7 @@ object TaskGroups {
/** The key a view's grouping is remembered under; `null` for views that have no task-list screen. */
fun TaskFilter.groupingKey(): String? = when (this) {
is TaskFilter.OfList -> "list:$listId"
is TaskFilter.OfList -> "${TaskGroupKey.LIST_PREFIX}$listId"
is TaskFilter.Smart -> "smart:${list.name}"
is TaskFilter.Tagged -> "tag:$tag"
is TaskFilter.Saved -> "saved:$id"
@@ -23,12 +23,10 @@ data class SectionedTasks(val section: TaskSection, val tasks: List<Task>)
*/
object TaskSections {
fun of(tasks: List<Task>, todayStart: Instant, todayEnd: Instant, todayList: Boolean = false): List<SectionedTasks> {
val bySection = tasks.groupBy { sectionOf(it, todayStart, todayEnd, todayList) }
return TaskSection.entries.mapNotNull { section ->
bySection[section]?.takeIf { it.isNotEmpty() }?.let { SectionedTasks(section, it) }
fun of(tasks: List<Task>, todayStart: Instant, todayEnd: Instant, todayList: Boolean = false): List<SectionedTasks> =
TaskGroups.of(tasks, TaskGrouping.DUE, todayStart, todayEnd, todayList).map { group ->
SectionedTasks((group.key as TaskGroupKey.Section).section, group.tasks)
}
}
fun sectionOf(
task: Task,
@@ -84,7 +84,6 @@ import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
@@ -108,7 +107,6 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.floret.time.DayWindow
import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import de.jeanlucmakiola.agendula.domain.Priority
@@ -135,7 +133,6 @@ import de.jeanlucmakiola.floret.components.pastelize
import de.jeanlucmakiola.floret.components.positionOf
import java.time.LocalDate
import java.time.ZoneId
import kotlin.time.Clock
/**
* The tasks for one [TaskFilter]: collapsible group headers, grouped tonal rows
@@ -320,7 +317,6 @@ fun TaskListScreen(
ViewOptionsPicker(
sortOrder = content.sortOrder,
grouping = content.grouping,
// A real list is one list already; grouping it by list would only add a header.
groupings = content.groupings,
tags = content.availableTags,
selectedTags = content.selectedTags,
@@ -380,15 +376,8 @@ private fun TaskListBody(
viewModel: TaskListViewModel,
onClearCompleted: (() -> Unit)? = null,
) {
// Bumped at midnight, so day groups and their labels move on with the date.
var dayTick by remember { mutableIntStateOf(0) }
val (todayStart, todayEnd) = remember(state.tasks, dayTick) {
DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
}
LaunchedEffect(todayEnd) {
delay((todayEnd - Clock.System.now()).inWholeMilliseconds.coerceAtLeast(0) + 1_000)
dayTick++
}
val todayStart = state.todayStart
val todayEnd = state.todayEnd
// A parent represents its children via a progress chip (counts come from the
// repository, over the full set), so drop children from the flat list — unless
// their parent isn't in this view (can happen in smart lists), where we keep
@@ -547,6 +536,7 @@ private fun TaskListBody(
position = r.position,
lastInRun = lastInRun,
showListName = showListName,
showPriority = state.grouping != TaskGrouping.PRIORITY,
subtaskDone = row.task.subtaskDone,
subtaskTotal = row.task.subtaskTotal,
expanded = row.expanded,
@@ -681,6 +671,7 @@ private fun TaskRow(
position: Position,
lastInRun: Boolean,
showListName: Boolean,
showPriority: Boolean,
subtaskDone: Int,
subtaskTotal: Int,
expanded: Boolean,
@@ -716,7 +707,10 @@ private fun TaskRow(
// A read-only share takes neither swipe: both are writes the server refuses.
gesturesEnabled = !task.isReadOnly,
) {
TaskRowContent(task, position, showListName, subtaskDone, subtaskTotal, expanded, onToggleExpand, onToggle, onClick)
TaskRowContent(
task, position, showListName, subtaskDone, subtaskTotal, expanded, onToggleExpand, onToggle, onClick,
showPriority = showPriority,
)
}
}
@@ -732,6 +726,7 @@ internal fun TaskRowContent(
onToggleExpand: (() -> Unit)?,
onToggle: () -> Unit,
onClick: () -> Unit,
showPriority: Boolean = true,
) {
val interaction = remember { MutableInteractionSource() }
val pressed by interaction.collectIsPressedAsState()
@@ -741,7 +736,9 @@ internal fun TaskRowContent(
val due = task.due?.formatDateTimeCompact(task.isAllDay, LocalUse24HourFormat.current)
val listName = task.listName?.takeIf { showListName && it.isNotBlank() }
// Everything secondary collapses into one quiet supporting line below the title.
val hasMeta = task.priority != Priority.NONE || due != null || subtaskTotal > 0 ||
// Under a priority header the row's own priority would only repeat it.
val priority = if (showPriority) task.priority else Priority.NONE
val hasMeta = priority != Priority.NONE || due != null || subtaskTotal > 0 ||
listName != null || task.isOccurrence || task.tags.isNotEmpty()
Surface(
@@ -790,7 +787,7 @@ internal fun TaskRowContent(
if (hasMeta) {
Spacer(Modifier.height(3.dp))
TaskMetaLine(
priority = task.priority,
priority = priority,
due = due,
recurring = task.isOccurrence,
subtaskDone = subtaskDone,
@@ -1390,7 +1387,7 @@ private fun dayLabel(date: LocalDate, todayStart: kotlin.time.Instant): String {
val today = remember(todayStart) {
java.time.Instant.ofEpochMilli(todayStart.toEpochMilliseconds()).atZone(ZoneId.systemDefault()).toLocalDate()
}
if (date == today.plusDays(1)) return stringResource(R.string.home_due_tomorrow)
if (date == today.plusDays(1)) return stringResource(R.string.group_tomorrow)
val locale = currentLocale()
val sameYear = date.year == today.year
val formatter = remember(locale, sameYear) {
@@ -1402,7 +1399,7 @@ private fun dayLabel(date: LocalDate, todayStart: kotlin.time.Instant): String {
private fun groupingLabels(grouping: TaskGrouping): Pair<Int, Int> = when (grouping) {
TaskGrouping.DUE -> R.string.group_due to R.string.group_due_summary
TaskGrouping.DAY -> R.string.group_day to R.string.group_day_summary
TaskGrouping.PRIORITY -> R.string.sort_priority to R.string.group_priority_summary
TaskGrouping.PRIORITY -> R.string.group_priority to R.string.group_priority_summary
TaskGrouping.LIST -> R.string.group_list to R.string.group_list_summary
}
@@ -28,6 +28,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
@@ -36,12 +37,18 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
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.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import de.jeanlucmakiola.floret.time.DayWindow
import java.time.ZoneId
import javax.inject.Inject
import kotlin.time.Clock
import kotlin.time.Instant
sealed interface TaskListUiState {
data object Loading : TaskListUiState
@@ -66,6 +73,9 @@ sealed interface TaskListUiState {
val groupings: List<TaskGrouping> = emptyList(),
/** List ids in the Lists screen's order, which list groups follow. */
val listOrder: List<Long> = emptyList(),
/** Today's bounds the rows are grouped against. */
val todayStart: Instant = Instant.DISTANT_PAST,
val todayEnd: Instant = Instant.DISTANT_PAST,
/** Ids of the groups whose rows are folded under their header. */
val collapsedGroups: Set<String> = DEFAULT_COLLAPSED_GROUPS,
/** This real list is kept out of the smart lists. */
@@ -125,20 +135,44 @@ 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>> =
flow {
while (true) {
val window = today()
emit(window)
delay((window.second - Clock.System.now()).inWholeMilliseconds.coerceAtLeast(0) + 1_000)
}
}.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) } }
}
val state: StateFlow<TaskListUiState> =
filter.filterNotNull()
.flatMapLatest { f ->
val tasks = repository.tasks(f)
val content: kotlinx.coroutines.flow.Flow<TaskListUiState> = when (f) {
val lists = repository.taskLists().onEach(::retainLists)
val content: Flow<TaskListUiState> = when (f) {
is TaskFilter.OfList ->
combine(tasks, repository.taskLists()) { rows, lists ->
TaskListUiState.Content(rows, lists.firstOrNull { it.id == f.listId })
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 ->
tasks.map { TaskListUiState.Content(it) }
combine(dayWindow.flatMapLatest { repository.tasks(f) }, lists) { rows, all ->
TaskListUiState.Content(rows, listOrder = all.map { it.id })
}
is TaskFilter.Saved ->
repository.filteredTasks(f).map {
TaskListUiState.Content(it.tasks, savedFilter = it.savedFilter)
combine(dayWindow.flatMapLatest { repository.filteredTasks(f) }, lists) { found, all ->
TaskListUiState.Content(found.tasks, savedFilter = found.savedFilter, listOrder = all.map { it.id })
}
// Several lists at once only exists for the widget, which never routes here.
is TaskFilter.OfLists -> error("OfLists has no task-list screen")
@@ -146,8 +180,7 @@ class TaskListViewModel @Inject constructor(
// 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).
val listOrder = repository.taskLists().map { lists -> lists.map { it.id } }
combine(content, pendingDeletes, settingsPrefs.settings, tagFilter, listOrder) { st, pending, settings, tags, order ->
combine(content, pendingDeletes, settingsPrefs.settings, tagFilter, dayWindow) { st, pending, settings, tags, window ->
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)
@@ -168,7 +201,8 @@ class TaskListViewModel @Inject constructor(
sortOrder = settings.sortOrder,
grouping = settings.groupingFor(f).takeIf { it in groupings } ?: TaskGrouping.DUE,
groupings = groupings,
listOrder = order,
todayStart = window.first,
todayEnd = window.second,
collapsedGroups = settings.collapsedGroups,
hiddenFromSmartLists = st.list?.id?.let { it in settings.hiddenFromSmartLists } ?: false,
)
@@ -378,10 +412,7 @@ class TaskListViewModel @Inject constructor(
fun deleteList(listId: Long, accountId: Long?) = viewModelScope.launch {
if (accountId == null) {
runCatching { repository.deleteList(listId) }
.onSuccess {
settingsPrefs.forgetList(listId)
_listDeleted.value = true
}
.onSuccess { _listDeleted.value = true }
.onFailure { _listWriteFailure.value = ListWriteFailure.DELETE }
return@launch
}
@@ -393,12 +424,7 @@ class TaskListViewModel @Inject constructor(
val outcome = runCatching { remoteLists.delete(listId) }
.getOrElse { RemoteLists.Outcome.Unreachable }
val failure = outcome.asFailure(ListWriteFailure.DELETE)
if (failure == null) {
settingsPrefs.forgetList(listId)
_listDeleted.value = true
} else {
_listWriteFailure.value = failure
}
if (failure == null) _listDeleted.value = true else _listWriteFailure.value = failure
}
/** Inline "add subtask" from an expanded list group — files it under [parent]. */
+2
View File
@@ -52,9 +52,11 @@
<string name="group_due_summary">Overdue, today, upcoming</string>
<string name="group_day">Day</string>
<string name="group_day_summary">A group for each day</string>
<string name="group_priority">Priority</string>
<string name="group_priority_summary">Highest priority first</string>
<string name="group_list">List</string>
<string name="group_list_summary">A group for each list</string>
<string name="group_tomorrow">Tomorrow</string>
<string name="group_priority_high">High priority</string>
<string name="group_priority_medium">Medium priority</string>
<string name="group_priority_low">Low priority</string>
@@ -38,6 +38,17 @@ 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)
@@ -120,6 +120,9 @@ class TaskGroupsTest {
assertThat(TaskGroups.offeredFor(TaskFilter.Tagged("x"))).isEqualTo(all)
val oneList = SavedFilter(id = 1, name = "f", listIds = setOf(3L))
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(1), oneList)).doesNotContain(TaskGrouping.LIST)
val overdueOnly = SavedFilter(id = 2, name = "g", due = setOf(DueWindow.OVERDUE))
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(2), overdueOnly)).doesNotContain(TaskGrouping.DAY)
assertThat(TaskGroups.offeredFor(TaskFilter.OfLists(setOf(1, 2)))).isEmpty()
}
@Test