From 4c261cdb9d4e80cfe64324995106b8c98d90c8f3 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:00:43 +0100 Subject: [PATCH 1/4] Group tasks by due date, day, priority or list (#71) --- CHANGELOG.md | 6 + .../agendula/data/prefs/SettingsPrefs.kt | 66 ++++++++-- .../agendula/domain/TaskGroups.kt | 113 +++++++++++++++++ .../agendula/ui/tasklist/TaskListScreen.kt | 94 ++++++++++++-- .../agendula/ui/tasklist/TaskListViewModel.kt | 22 ++-- app/src/main/res/values/strings.xml | 15 +++ .../data/prefs/TaskGroupingPrefsTest.kt | 42 +++++++ .../agendula/domain/TaskGroupsTest.kt | 119 ++++++++++++++++++ 8 files changed, 447 insertions(+), 30 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c3d4b..7de47f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- Task lists can be grouped by due date (Overdue, Today, Upcoming), by day, + by priority or, in smart lists, tags and filters, by list. Pick it under + "Group by" in the list's sort and filter options; each list and view + remembers its own choice (#71). + ## [1.3.2] - 2026-11-13 ### Added diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index 3022a99..d8dc02f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -15,7 +15,10 @@ import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskFormField import de.jeanlucmakiola.agendula.domain.TaskReminder +import de.jeanlucmakiola.agendula.domain.TaskGroupKey +import de.jeanlucmakiola.agendula.domain.TaskGrouping import de.jeanlucmakiola.agendula.domain.TaskSection +import de.jeanlucmakiola.agendula.domain.groupingKey import de.jeanlucmakiola.agendula.domain.asTaskReminder import de.jeanlucmakiola.agendula.domain.asReminderLead import de.jeanlucmakiola.agendula.domain.TaskSortOrder @@ -28,6 +31,7 @@ import de.jeanlucmakiola.floret.reminders.reminderLeadsFor import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import java.time.DayOfWeek +import java.time.LocalDate import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Singleton @@ -58,7 +62,8 @@ fun TimeFormatPref.is24Hour(systemIs24Hour: Boolean): Boolean = when (this) { enum class ReminderDescription { HIDDEN, SHORT, FULL } const val DEFAULT_SNOOZE_MINUTES = 10 -/** Done starts folded away, to keep the open tasks in focus. */ val DEFAULT_COLLAPSED_SECTIONS: Set = setOf(TaskSection.COMPLETED) +/** Done starts folded away, to keep the open tasks in focus. */ +val DEFAULT_COLLAPSED_GROUPS: Set = setOf(TaskGroupKey.Section(TaskSection.COMPLETED).id) /** The snooze lengths Settings offers. */ val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) @@ -120,9 +125,14 @@ data class Settings( val hiddenFromSmartLists: Set = emptySet(), /** Pre-fill a new task's start with today's date. */ val defaultStartToday: Boolean = false, - /** Task-list sections folded away; Done starts folded. */ - val collapsedSections: Set = DEFAULT_COLLAPSED_SECTIONS, + /** Ids of the task-list groups folded away ([TaskGroupKey.id]); Done starts folded. */ + val collapsedGroups: Set = DEFAULT_COLLAPSED_GROUPS, + /** Each view's chosen grouping, keyed by [groupingKey]; absent = [TaskGrouping.DUE]. */ + val groupings: Map = emptyMap(), ) { + fun groupingFor(filter: TaskFilter): TaskGrouping = + filter.groupingKey()?.let { groupings[it] } ?: TaskGrouping.DUE + /** [tasks] as [filter] shows them: a smart list drops the lists kept out of it. */ fun visibleIn(filter: TaskFilter, tasks: List): List = if (filter is TaskFilter.Smart && hiddenFromSmartLists.isNotEmpty()) { @@ -198,16 +208,22 @@ class SettingsPrefs @Inject constructor( .toSet() }, defaultStartToday = p[DEFAULT_START_TODAY] ?: false, - collapsedSections = p[COLLAPSED_SECTIONS] - ?.mapNotNull { name -> runCatching { TaskSection.valueOf(name) }.getOrNull() } - ?.toSet() - ?: DEFAULT_COLLAPSED_SECTIONS, + collapsedGroups = p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, + groupings = decodeGroupings(p[GROUPINGS].orEmpty(), modeOf(p).name), ) } - suspend fun setSectionCollapsed(section: TaskSection, collapsed: Boolean) = dataStore.edit { p -> - val current = p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_SECTIONS.mapTo(HashSet()) { it.name } - p[COLLAPSED_SECTIONS] = if (collapsed) current + section.name else current - section.name + /** Folds or unfolds the group with [id]; day groups that have passed are dropped on the way. */ + suspend fun setGroupCollapsed(id: String, collapsed: Boolean) = dataStore.edit { p -> + val current = dropPastDays(p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, LocalDate.now()) + p[COLLAPSED_SECTIONS] = if (collapsed) current + id else current - id + } + + /** Remembers [grouping] for [filter]'s view. */ + suspend fun setGrouping(filter: TaskFilter, grouping: TaskGrouping) = dataStore.edit { p -> + val key = storedGroupingKey(filter, modeOf(p).name) ?: return@edit + val kept = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key } + p[GROUPINGS] = if (grouping == TaskGrouping.DUE) kept else kept + "${grouping.name}$GROUPING_SEPARATOR$key" } suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name } @@ -372,6 +388,7 @@ class SettingsPrefs @Inject constructor( val SMART_LIST_HIDDEN = stringSetPreferencesKey("smart_list_hidden") val DEFAULT_START_TODAY = booleanPreferencesKey("default_start_today") val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections") + val GROUPINGS = stringSetPreferencesKey("task_groupings") val SAVED_FILTERS = stringPreferencesKey("saved_filters") val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id") } @@ -394,3 +411,32 @@ private fun parseLeads(stored: String): List = */ private fun List.inWholeDays(): List = map { it.asTaskReminder().inWholeDays().asReminderLead() }.normalizeReminders() + +private const val GROUPING_SEPARATOR = '|' + +/** List ids belong to one store, so a list's key carries the store's [mode]: `list:OWN:5`. */ +private fun storedGroupingKey(filter: TaskFilter, mode: String): String? { + val key = filter.groupingKey() ?: return null + return if (filter is TaskFilter.OfList) "list:$mode:${filter.listId}" else key +} + +/** `GROUPING|key` entries → view key to grouping, keeping only the lists of the current [mode]. */ +internal fun decodeGroupings(entries: Set, mode: String): Map = + entries.mapNotNull { entry -> + val grouping = runCatching { TaskGrouping.valueOf(entry.substringBefore(GROUPING_SEPARATOR)) } + .getOrNull() ?: return@mapNotNull null + val stored = entry.substringAfter(GROUPING_SEPARATOR, "") + val key = when { + stored.isEmpty() -> null + stored.startsWith("list:") -> stored.removePrefix("list:$mode:").takeIf { it != stored }?.let { "list:$it" } + else -> stored + } + key?.let { it to grouping } + }.toMap() + +/** [collapsed] without the day groups before [today], which can never show again. */ +internal fun dropPastDays(collapsed: Set, today: LocalDate): Set = + collapsed.filterTo(HashSet()) { entry -> + if (!entry.startsWith(TaskGroupKey.DAY_PREFIX)) return@filterTo true + runCatching { !LocalDate.parse(entry.removePrefix(TaskGroupKey.DAY_PREFIX)).isBefore(today) }.getOrDefault(false) + } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt new file mode 100644 index 0000000..3230674 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt @@ -0,0 +1,113 @@ +package de.jeanlucmakiola.agendula.domain + +import java.time.LocalDate +import java.time.ZoneId +import kotlin.time.Instant + +/** How a task list groups its rows (#71). [DUE] is the classic Overdue / Today / Upcoming split. */ +enum class TaskGrouping { DUE, DAY, PRIORITY, LIST } + +/** What a group of rows is headed by. [id] is stable and is what collapse state keys on. */ +sealed interface TaskGroupKey { + val id: String + + /** A due-date bucket; its id is the section's name, as earlier versions stored it. */ + data class Section(val section: TaskSection) : TaskGroupKey { + override val id: String get() = section.name + } + + /** Open tasks due on [date], a day after today. */ + data class Day(val date: LocalDate) : TaskGroupKey { + override val id: String get() = "$DAY_PREFIX$date" + } + + data class OfPriority(val priority: Priority) : TaskGroupKey { + override val id: String get() = "priority:${priority.name}" + } + + data class OfList(val listId: Long, val name: String?) : TaskGroupKey { + override val id: String get() = "list:$listId" + } + + companion object { + const val DAY_PREFIX = "day:" + } +} + +/** A non-empty run of tasks under one [TaskGroupKey], already in display order. */ +data class TaskGroup(val key: TaskGroupKey, val tasks: List) + +/** + * Groups already-sorted tasks for display. Completed tasks always close the list + * in their own group, whatever the grouping; within a group the incoming order is + * kept. [todayStart] / [todayEnd] bound the local day (see [DayWindow]); in the + * Today list ([todayList]) the date groupings put every open task under Today. + */ +object TaskGroups { + + fun of( + tasks: List, + grouping: TaskGrouping, + todayStart: Instant, + todayEnd: Instant, + todayList: Boolean = false, + zone: ZoneId = ZoneId.systemDefault(), + ): List { + val (completed, open) = tasks.partition { it.isCompleted } + val keyed: List>> = when (grouping) { + TaskGrouping.DUE, TaskGrouping.DAY -> open + .groupBy { dueKey(it, grouping == TaskGrouping.DAY, todayStart, todayEnd, todayList, zone) } + .toList() + .sortedWith(compareBy({ dueRank(it.first) }, { (it.first as? TaskGroupKey.Day)?.date })) + TaskGrouping.PRIORITY -> open + .groupBy { TaskGroupKey.OfPriority(it.priority) } + .toList() + .sortedByDescending { it.first.priority.ordinal } + TaskGrouping.LIST -> open + .groupBy { it.listId } + .map { (listId, rows) -> TaskGroupKey.OfList(listId, rows.first().listName) to rows } + .sortedWith(compareBy({ it.first.name.orEmpty().lowercase() }, { it.first.listId })) + } + val groups = keyed.map { (key, rows) -> TaskGroup(key, rows) } + return if (completed.isEmpty()) groups else groups + TaskGroup(TaskGroupKey.Section(TaskSection.COMPLETED), completed) + } + + private fun dueKey( + task: Task, + perDay: Boolean, + todayStart: Instant, + todayEnd: Instant, + todayList: Boolean, + zone: ZoneId, + ): TaskGroupKey { + val window = if (todayList) DueWindow.TODAY else dueWindowOf(task, todayStart, todayEnd, zone) + return when (window) { + DueWindow.OVERDUE -> TaskGroupKey.Section(TaskSection.OVERDUE) + DueWindow.TODAY -> TaskGroupKey.Section(TaskSection.TODAY) + DueWindow.NO_DATE -> TaskGroupKey.Section(TaskSection.NO_DATE) + DueWindow.UPCOMING -> + if (perDay) TaskGroupKey.Day(localDueDate(task, zone)) else TaskGroupKey.Section(TaskSection.UPCOMING) + } + } + + /** Overdue → Today → Upcoming (or each later day) → No date. */ + private fun dueRank(key: TaskGroupKey): Int = when (key) { + is TaskGroupKey.Day -> TaskSection.UPCOMING.ordinal + is TaskGroupKey.Section -> key.section.ordinal + else -> Int.MAX_VALUE + } + + private fun localDueDate(task: Task, zone: ZoneId): LocalDate { + val due = requireNotNull(task.wallClock(task.due, zone)) + return java.time.Instant.ofEpochMilli(due.toEpochMilliseconds()).atZone(zone).toLocalDate() + } +} + +/** 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.Smart -> "smart:${list.name}" + is TaskFilter.Tagged -> "tag:$tag" + is TaskFilter.Saved -> "saved:$id" + is TaskFilter.OfLists -> null +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index a6efcd5..03abe3f 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 @@ -113,7 +113,9 @@ import de.jeanlucmakiola.agendula.domain.SmartList 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.TaskGroupKey +import de.jeanlucmakiola.agendula.domain.TaskGrouping +import de.jeanlucmakiola.agendula.domain.TaskGroups import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.agendula.ui.common.SyncPullBox import de.jeanlucmakiola.agendula.ui.common.ignoringEdgeSwipes @@ -128,11 +130,14 @@ import de.jeanlucmakiola.floret.components.SnackChipMargin import de.jeanlucmakiola.floret.time.formatDateTimeCompact import de.jeanlucmakiola.floret.components.pastelize import de.jeanlucmakiola.floret.components.positionOf +import java.time.LocalDate import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale import kotlin.time.Clock /** - * The tasks for one [TaskFilter]: due-date section headers, grouped tonal rows + * The tasks for one [TaskFilter]: collapsible group headers, grouped tonal rows * with a leading checkbox, swipe-to-complete (start→end) / swipe-to-delete * (end→start), and — for a real list — an inline add field. Renders against the * M1 [TaskListViewModel]; actions are fire-and-forget and flow back live. @@ -313,9 +318,13 @@ fun TaskListScreen( if (showSort && content != null) { ViewOptionsPicker( sortOrder = content.sortOrder, + grouping = content.grouping, + // A real list is one list already; grouping it by list would only add a header. + groupings = TaskGrouping.entries.filter { it != TaskGrouping.LIST || filter !is TaskFilter.OfList }, tags = content.availableTags, selectedTags = content.selectedTags, onSortOrder = viewModel::setSortOrder, + onGrouping = viewModel::setGrouping, onToggleTag = viewModel::toggleTagFilter, onClearTags = viewModel::clearTagFilter, onDismiss = { showSort = false }, @@ -379,10 +388,17 @@ private fun TaskListBody( val present = state.tasks.mapTo(HashSet()) { it.taskId } state.tasks.filter { (it.parentId ?: 0L) <= 0L || it.parentId !in present } } - val sections = remember(displayTasks, todayStart) { - TaskSections.of(displayTasks, todayStart, todayEnd, todayList = filter == TaskFilter.Smart(SmartList.TODAY)) + val groups = remember(displayTasks, todayStart, state.grouping) { + TaskGroups.of( + displayTasks, + state.grouping, + todayStart, + todayEnd, + todayList = filter == TaskFilter.Smart(SmartList.TODAY), + ) } - val showHeaders = sections.size > 1 + // A grouping the user picked keeps its header even when everything lands in one group. + val showHeaders = groups.size > 1 || (groups.isNotEmpty() && state.grouping != TaskGrouping.DUE) 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 both are redundant. @@ -436,17 +452,18 @@ private fun TaskListBody( item(key = "empty") { EmptyState(stringResource(R.string.task_list_empty)) } } - sections.forEach { section -> + groups.forEach { group -> // Every header folds its section away (#91); Done starts folded. - val expanded = !showHeaders || section.section !in state.collapsedSections + val groupId = group.key.id + val expanded = !showHeaders || groupId !in state.collapsedGroups if (showHeaders) { - stickyHeader(key = "hdr-${section.section}") { + stickyHeader(key = "hdr-$groupId") { CollapsibleSectionHeader( - label = sectionLabel(section.section), - count = section.tasks.size, + label = groupLabel(group.key, todayStart), + count = group.tasks.size, expanded = expanded, - onToggle = { viewModel.setSectionCollapsed(section.section, expanded) }, - onClear = onClearCompleted.takeIf { section.section == TaskSection.COMPLETED }, + onToggle = { viewModel.setGroupCollapsed(groupId, expanded) }, + onClear = onClearCompleted.takeIf { group.key == TaskGroupKey.Section(TaskSection.COMPLETED) }, ) } } @@ -458,7 +475,7 @@ private fun TaskListBody( // full-width, connecting to the parent above (small top corners), // and the run rounds off (full corners) only at its genuine ends. val rows = buildList { - val topLevel = section.tasks + val topLevel = group.tasks topLevel.forEachIndexed { p, task -> // The full child set — already in this view for a real list, // or fetched on demand for a smart list (childrenOf). A parent @@ -1234,9 +1251,12 @@ private fun CenteredMessage(text: String, inner: PaddingValues) { @Composable private fun ViewOptionsPicker( sortOrder: TaskSortOrder, + grouping: TaskGrouping, + groupings: List, tags: List, selectedTags: Set, onSortOrder: (TaskSortOrder) -> Unit, + onGrouping: (TaskGrouping) -> Unit, onToggleTag: (String) -> Unit, onClearTags: () -> Unit, onDismiss: () -> Unit, @@ -1261,6 +1281,20 @@ private fun ViewOptionsPicker( onClick = { onSortOrder(order) }, ) } + Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(stringResource(R.string.group_title)) + groupings.forEachIndexed { index, option -> + val isSelected = option == grouping + val (title, summary) = groupingLabels(option) + GroupedRow( + title = stringResource(title), + summary = stringResource(summary), + position = positionOf(index, groupings.size), + selected = isSelected, + trailing = if (isSelected) ({ SelectedCheck() }) else null, + onClick = { onGrouping(option) }, + ) + } if (tags.isNotEmpty()) { Spacer(Modifier.height(8.dp)) GroupedSectionHeader(stringResource(R.string.view_filter_tags)) @@ -1309,6 +1343,40 @@ private fun sectionLabel(section: TaskSection): String = stringResource( }, ) +@Composable +private fun groupLabel(key: TaskGroupKey, todayStart: kotlin.time.Instant): String = when (key) { + is TaskGroupKey.Section -> sectionLabel(key.section) + is TaskGroupKey.Day -> { + val today = java.time.Instant.ofEpochMilli(todayStart.toEpochMilliseconds()) + .atZone(ZoneId.systemDefault()).toLocalDate() + if (key.date == today.plusDays(1)) stringResource(R.string.group_tomorrow) else dayLabel(key.date, today) + } + is TaskGroupKey.OfPriority -> stringResource( + when (key.priority) { + Priority.HIGH -> R.string.group_priority_high + Priority.MEDIUM -> R.string.group_priority_medium + Priority.LOW -> R.string.group_priority_low + Priority.NONE -> R.string.group_priority_none + }, + ) + is TaskGroupKey.OfList -> key.name?.takeIf { it.isNotBlank() } ?: stringResource(R.string.group_list_unnamed) +} + +/** A day header in the locale's own order, e.g. "Friday, 21 November"; the year only when it isn't this one's. */ +private fun dayLabel(date: LocalDate, today: LocalDate): String { + val locale = Locale.getDefault() + val skeleton = if (date.year == today.year) "EEEEMMMMd" else "EEEEMMMMdy" + val pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton) + return date.format(DateTimeFormatter.ofPattern(pattern, locale)) +} + +private fun groupingLabels(grouping: TaskGrouping): Pair = 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.group_priority to R.string.group_priority_summary + TaskGrouping.LIST -> R.string.group_list to R.string.group_list_summary +} + @Composable internal fun priorityLabel(priority: Priority): String = stringResource( when (priority) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index b74fece..b9bfb7a 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 @@ -3,7 +3,7 @@ package de.jeanlucmakiola.agendula.ui.tasklist import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel -import de.jeanlucmakiola.agendula.data.prefs.DEFAULT_COLLAPSED_SECTIONS +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.TasksRepository @@ -15,7 +15,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFiltering import de.jeanlucmakiola.agendula.domain.tagsInUse import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskList -import de.jeanlucmakiola.agendula.domain.TaskSection +import de.jeanlucmakiola.agendula.domain.TaskGrouping import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.agendula.domain.comparator import de.jeanlucmakiola.agendula.ui.lists.ListWriteFailure @@ -59,8 +59,10 @@ sealed interface TaskListUiState { /** Whether a real list uses the bottom quick-add bar instead of the FAB. */ val bottomAddBar: Boolean = false, val sortOrder: TaskSortOrder = TaskSortOrder.DUE, - /** Sections whose rows are folded under their header. */ - val collapsedSections: Set = DEFAULT_COLLAPSED_SECTIONS, + /** How this view groups its rows. */ + val grouping: TaskGrouping = TaskGrouping.DUE, + /** Ids of the groups whose rows are folded under their header. */ + val collapsedGroups: Set = DEFAULT_COLLAPSED_GROUPS, /** This real list is kept out of the smart lists. */ val hiddenFromSmartLists: Boolean = false, /** Tags the unnarrowed view carries, offered as filter chips. */ @@ -157,7 +159,8 @@ class TaskListViewModel @Inject constructor( showAddSubtaskRow = settings.showAddSubtaskRow, bottomAddBar = settings.bottomAddBar, sortOrder = settings.sortOrder, - collapsedSections = settings.collapsedSections, + grouping = settings.groupingFor(f), + collapsedGroups = settings.collapsedGroups, hiddenFromSmartLists = st.list?.id?.let { it in settings.hiddenFromSmartLists } ?: false, ) } else { @@ -291,8 +294,13 @@ class TaskListViewModel @Inject constructor( fun setHiddenFromSmartLists(listId: Long, hidden: Boolean) = viewModelScope.launch { settingsPrefs.setHiddenFromSmartLists(listId, hidden) } - fun setSectionCollapsed(section: TaskSection, collapsed: Boolean) = - viewModelScope.launch { settingsPrefs.setSectionCollapsed(section, collapsed) } + fun setGroupCollapsed(id: String, collapsed: Boolean) = + viewModelScope.launch { settingsPrefs.setGroupCollapsed(id, collapsed) } + + fun setGrouping(grouping: TaskGrouping) { + val f = filter.value ?: return + viewModelScope.launch { settingsPrefs.setGrouping(f, grouping) } + } fun setSortOrder(order: TaskSortOrder) = viewModelScope.launch { settingsPrefs.setSortOrder(order) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5211b6b..2452da2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -47,6 +47,21 @@ Priority Title Recently added + Group by + Due date + Overdue, today, upcoming + Day + A group for each day + Priority + Highest priority first + List + A group for each list + Tomorrow + High priority + Medium priority + Low priority + No priority + Unnamed list Clear Clear completed tasks? diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt new file mode 100644 index 0000000..317134d --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt @@ -0,0 +1,42 @@ +package de.jeanlucmakiola.agendula.data.prefs + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.TaskGrouping +import org.junit.jupiter.api.Test +import java.time.LocalDate + +class TaskGroupingPrefsTest { + + @Test + fun `groupings decode per view and keep only the current store's lists`() { + val decoded = decodeGroupings( + setOf("DAY|smart:UPCOMING", "PRIORITY|list:OWN:5", "LIST|list:PROVIDER:5", "DAY|tag:work", "BOGUS|saved:1", "DAY|"), + mode = "OWN", + ) + assertThat(decoded).containsExactly( + "smart:UPCOMING", TaskGrouping.DAY, + "list:5", TaskGrouping.PRIORITY, + "tag:work", TaskGrouping.DAY, + ) + } + + @Test + fun `a view without a stored grouping groups by due date`() { + val settings = Settings(groupings = mapOf("list:5" to TaskGrouping.PRIORITY)) + assertThat(settings.groupingFor(TaskFilter.OfList(5))).isEqualTo(TaskGrouping.PRIORITY) + assertThat(settings.groupingFor(TaskFilter.OfList(6))).isEqualTo(TaskGrouping.DUE) + assertThat(settings.groupingFor(TaskFilter.Smart(SmartList.ALL))).isEqualTo(TaskGrouping.DUE) + } + + @Test + fun `collapsed day groups that have passed are dropped`() { + val today = LocalDate.of(2026, 11, 17) + val kept = dropPastDays( + setOf("COMPLETED", "priority:LOW", "day:2026-11-16", "day:2026-11-18", "day:garbage"), + today, + ) + assertThat(kept).containsExactly("COMPLETED", "priority:LOW", "day:2026-11-18") + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt new file mode 100644 index 0000000..633e0ae --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt @@ -0,0 +1,119 @@ +package de.jeanlucmakiola.agendula.domain + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.ZoneOffset +import kotlin.time.Instant + +class TaskGroupsTest { + + private val dayMs = 86_400_000L + private val todayStart = Instant.fromEpochMilliseconds(1000 * dayMs) + private val todayEnd = Instant.fromEpochMilliseconds(1001 * dayMs) + private val today = LocalDate.ofEpochDay(1000) + + private fun at(millis: Long) = Instant.fromEpochMilliseconds(millis) + + private fun groups(tasks: List, grouping: TaskGrouping, todayList: Boolean = false) = + TaskGroups.of(tasks, grouping, todayStart, todayEnd, todayList, ZoneOffset.UTC) + + private fun keys(tasks: List, grouping: TaskGrouping, todayList: Boolean = false) = + groups(tasks, grouping, todayList).map { it.key } + + @Test + fun `due grouping keeps the classic sections`() { + val tasks = listOf( + testTask(id = 1, due = at(1002 * dayMs)), + testTask(id = 2, due = at(1000 * dayMs - 1)), + testTask(id = 3), + testTask(id = 4, status = TaskStatus.COMPLETED), + testTask(id = 5, due = at(1000 * dayMs + 1)), + ) + assertThat(keys(tasks, TaskGrouping.DUE)).containsExactly( + TaskGroupKey.Section(TaskSection.OVERDUE), + TaskGroupKey.Section(TaskSection.TODAY), + TaskGroupKey.Section(TaskSection.UPCOMING), + TaskGroupKey.Section(TaskSection.NO_DATE), + TaskGroupKey.Section(TaskSection.COMPLETED), + ).inOrder() + } + + @Test + fun `day grouping splits upcoming into one group per day in date order`() { + val tasks = listOf( + testTask(id = 1, due = at(1003 * dayMs + 5)), + testTask(id = 2, due = at(1001 * dayMs + 5)), + testTask(id = 3, due = at(1003 * dayMs + 9)), + testTask(id = 4, due = at(1000 * dayMs + 5)), + testTask(id = 5, due = at(999 * dayMs)), + testTask(id = 6), + ) + val result = groups(tasks, TaskGrouping.DAY) + assertThat(result.map { it.key }).containsExactly( + TaskGroupKey.Section(TaskSection.OVERDUE), + TaskGroupKey.Section(TaskSection.TODAY), + TaskGroupKey.Day(today.plusDays(1)), + TaskGroupKey.Day(today.plusDays(3)), + TaskGroupKey.Section(TaskSection.NO_DATE), + ).inOrder() + assertThat(result[3].tasks.map { it.taskId }).containsExactly(1L, 3L).inOrder() + } + + @Test + fun `day grouping reads an all-day due as its calendar date`() { + val allDay = testTask(due = at(1002 * dayMs), isAllDay = true) + assertThat(keys(listOf(allDay), TaskGrouping.DAY)).containsExactly(TaskGroupKey.Day(today.plusDays(2))) + } + + @Test + fun `the Today list keeps open tasks under Today for date groupings`() { + val tasks = listOf(testTask(id = 1, start = at(1000 * dayMs + 1), due = at(1003 * dayMs))) + assertThat(keys(tasks, TaskGrouping.DAY, todayList = true)) + .containsExactly(TaskGroupKey.Section(TaskSection.TODAY)) + } + + @Test + fun `priority grouping runs from high to none and keeps completed last`() { + val tasks = listOf( + testTask(id = 1, priority = Priority.LOW), + testTask(id = 2, priority = Priority.NONE), + testTask(id = 3, priority = Priority.HIGH, status = TaskStatus.COMPLETED), + testTask(id = 4, priority = Priority.HIGH), + ) + assertThat(keys(tasks, TaskGrouping.PRIORITY)).containsExactly( + TaskGroupKey.OfPriority(Priority.HIGH), + TaskGroupKey.OfPriority(Priority.LOW), + TaskGroupKey.OfPriority(Priority.NONE), + TaskGroupKey.Section(TaskSection.COMPLETED), + ).inOrder() + } + + @Test + fun `list grouping orders lists by name and keeps the incoming order inside`() { + val tasks = listOf( + testTask(id = 1, listId = 2).copy(listName = "work"), + testTask(id = 2, listId = 1).copy(listName = "Home"), + testTask(id = 3, listId = 2).copy(listName = "work"), + ) + val result = groups(tasks, TaskGrouping.LIST) + assertThat(result.map { it.key }).containsExactly( + TaskGroupKey.OfList(1, "Home"), + TaskGroupKey.OfList(2, "work"), + ).inOrder() + assertThat(result[1].tasks.map { it.taskId }).containsExactly(1L, 3L).inOrder() + } + + @Test + fun `group ids stay stable and match the stored section names`() { + assertThat(TaskGroupKey.Section(TaskSection.COMPLETED).id).isEqualTo("COMPLETED") + assertThat(TaskGroupKey.Day(LocalDate.of(2026, 11, 20)).id).isEqualTo("day:2026-11-20") + assertThat(TaskGroupKey.OfPriority(Priority.HIGH).id).isEqualTo("priority:HIGH") + assertThat(TaskGroupKey.OfList(7, "x").id).isEqualTo("list:7") + } + + @Test + fun `empty input yields no groups`() { + TaskGrouping.entries.forEach { assertThat(groups(emptyList(), it)).isEmpty() } + } +} From a94b5be8855d087c5132594078ec6e039a1c02a6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:07:34 +0100 Subject: [PATCH 2/4] Address review on task grouping (#71) --- CHANGELOG.md | 3 +- .../agendula/data/prefs/SettingsPrefs.kt | 37 ++++--- .../agendula/domain/TaskGroups.kt | 54 ++++++--- .../agendula/domain/TaskSections.kt | 11 +- .../agendula/ui/tasklist/TaskListScreen.kt | 103 +++++++++++------- .../agendula/ui/tasklist/TaskListViewModel.kt | 25 ++++- app/src/main/res/values/strings.xml | 3 +- .../data/prefs/TaskGroupingPrefsTest.kt | 8 ++ .../agendula/domain/TaskGroupsTest.kt | 38 +++++-- 9 files changed, 198 insertions(+), 84 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7de47f9..073654c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ All notable changes to this project are documented here. The format follows - Task lists can be grouped by due date (Overdue, Today, Upcoming), by day, by priority or, in smart lists, tags and filters, by list. Pick it under "Group by" in the list's sort and filter options; each list and view - remembers its own choice (#71). + remembers its own choice. Folded groups stay folded across views, as the + due-date sections already did (#71). ## [1.3.2] - 2026-11-13 diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index d8dc02f..7a1897f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -208,24 +208,33 @@ class SettingsPrefs @Inject constructor( .toSet() }, defaultStartToday = p[DEFAULT_START_TODAY] ?: false, - collapsedGroups = p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, + collapsedGroups = (p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS) + .mapNotNullTo(HashSet()) { unscopeListKey(it, modeOf(p).name) }, groupings = decodeGroupings(p[GROUPINGS].orEmpty(), modeOf(p).name), ) } /** Folds or unfolds the group with [id]; day groups that have passed are dropped on the way. */ suspend fun setGroupCollapsed(id: String, collapsed: Boolean) = dataStore.edit { p -> + val stored = scopeListKey(id, modeOf(p).name) val current = dropPastDays(p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, LocalDate.now()) - p[COLLAPSED_SECTIONS] = if (collapsed) current + id else current - id + p[COLLAPSED_SECTIONS] = if (collapsed) current + stored else current - stored } /** Remembers [grouping] for [filter]'s view. */ suspend fun setGrouping(filter: TaskFilter, grouping: TaskGrouping) = dataStore.edit { p -> - val key = storedGroupingKey(filter, modeOf(p).name) ?: return@edit + val key = filter.groupingKey()?.let { scopeListKey(it, modeOf(p).name) } ?: return@edit val kept = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key } 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 } + } + suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name } suspend fun setSnoozeMinutes(minutes: Int) = dataStore.edit { it[SNOOZE_MINUTES] = minutes.coerceAtLeast(1) } @@ -355,6 +364,8 @@ class SettingsPrefs @Inject constructor( suspend fun deleteFilter(id: Long) = dataStore.edit { p -> p[SAVED_FILTERS] = SavedFilterCodec.remove(p[SAVED_FILTERS], id) + val key = TaskFilter.Saved(id).groupingKey() + p[GROUPINGS] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key } } suspend fun setDefaultEditFields(fields: Set) = dataStore.edit { @@ -414,10 +425,15 @@ private fun List.inWholeDays(): List = private const val GROUPING_SEPARATOR = '|' -/** List ids belong to one store, so a list's key carries the store's [mode]: `list:OWN:5`. */ -private fun storedGroupingKey(filter: TaskFilter, mode: String): String? { - val key = filter.groupingKey() ?: return null - return if (filter is TaskFilter.OfList) "list:$mode:${filter.listId}" else key +/** List ids belong to one store, so a stored list key carries the store's [mode]: `list:5` → `list:OWN:5`. */ +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 + +/** 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 + val id = stored.removePrefix("${TaskGroupKey.LIST_PREFIX}$mode:").takeIf { it != stored } ?: return null + return "${TaskGroupKey.LIST_PREFIX}$id" } /** `GROUPING|key` entries → view key to grouping, keeping only the lists of the current [mode]. */ @@ -426,12 +442,7 @@ internal fun decodeGroupings(entries: Set, mode: String): Map null - stored.startsWith("list:") -> stored.removePrefix("list:$mode:").takeIf { it != stored }?.let { "list:$it" } - else -> stored - } - key?.let { it to grouping } + stored.takeIf { it.isNotEmpty() }?.let { unscopeListKey(it, mode) }?.let { it to grouping } }.toMap() /** [collapsed] without the day groups before [today], which can never show again. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt index 3230674..2855849 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt @@ -25,12 +25,14 @@ sealed interface TaskGroupKey { override val id: String get() = "priority:${priority.name}" } - data class OfList(val listId: Long, val name: String?) : TaskGroupKey { - override val id: String get() = "list:$listId" + data class OfList(val listId: Long, val name: String?, val accountName: String?) : TaskGroupKey { + override val id: String get() = "$LIST_PREFIX$listId" } companion object { const val DAY_PREFIX = "day:" + const val LIST_PREFIX = "list:" + val COMPLETED: TaskGroupKey = Section(TaskSection.COMPLETED) } } @@ -42,6 +44,7 @@ data class TaskGroup(val key: TaskGroupKey, val tasks: List) * in their own group, whatever the grouping; within a group the incoming order is * kept. [todayStart] / [todayEnd] bound the local day (see [DayWindow]); in the * Today list ([todayList]) the date groupings put every open task under Today. + * List groups follow [listOrder] (the Lists screen's order); lists not in it go last. */ object TaskGroups { @@ -51,6 +54,7 @@ object TaskGroups { todayStart: Instant, todayEnd: Instant, todayList: Boolean = false, + listOrder: List = emptyList(), zone: ZoneId = ZoneId.systemDefault(), ): List { val (completed, open) = tasks.partition { it.isCompleted } @@ -63,13 +67,35 @@ object TaskGroups { .groupBy { TaskGroupKey.OfPriority(it.priority) } .toList() .sortedByDescending { it.first.priority.ordinal } - TaskGrouping.LIST -> open - .groupBy { it.listId } - .map { (listId, rows) -> TaskGroupKey.OfList(listId, rows.first().listName) to rows } - .sortedWith(compareBy({ it.first.name.orEmpty().lowercase() }, { it.first.listId })) + TaskGrouping.LIST -> { + val rank = listOrder.withIndex().associate { (i, id) -> id to i } + open.groupBy { it.listId } + .map { (listId, rows) -> + TaskGroupKey.OfList(listId, rows.first().listName, rows.first().accountName) to rows + } + .sortedWith(compareBy({ rank[it.first.listId] ?: Int.MAX_VALUE }, { it.first.listId })) + } } val groups = keyed.map { (key, rows) -> TaskGroup(key, rows) } - return if (completed.isEmpty()) groups else groups + TaskGroup(TaskGroupKey.Section(TaskSection.COMPLETED), completed) + return if (completed.isEmpty()) groups else groups + TaskGroup(TaskGroupKey.COMPLETED, completed) + } + + /** The groupings worth offering for [filter]: ones that can change what it shows. */ + fun offeredFor(filter: TaskFilter, savedFilter: SavedFilter? = null): List { + val dropped = 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() + // Today puts everything under Today; Overdue and No date have no later days. + SmartList.TODAY, SmartList.OVERDUE, SmartList.NO_DATE -> setOf(TaskGrouping.DAY) + 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.Tagged -> emptySet() + } + return TaskGrouping.entries - dropped } private fun dueKey( @@ -80,13 +106,11 @@ object TaskGroups { todayList: Boolean, zone: ZoneId, ): TaskGroupKey { - val window = if (todayList) DueWindow.TODAY else dueWindowOf(task, todayStart, todayEnd, zone) - return when (window) { - DueWindow.OVERDUE -> TaskGroupKey.Section(TaskSection.OVERDUE) - DueWindow.TODAY -> TaskGroupKey.Section(TaskSection.TODAY) - DueWindow.NO_DATE -> TaskGroupKey.Section(TaskSection.NO_DATE) - DueWindow.UPCOMING -> - if (perDay) TaskGroupKey.Day(localDueDate(task, zone)) else TaskGroupKey.Section(TaskSection.UPCOMING) + val section = TaskSections.sectionOf(task, todayStart, todayEnd, todayList, zone) + return if (perDay && section == TaskSection.UPCOMING) { + TaskGroupKey.Day(localDueDate(task, zone)) + } else { + TaskGroupKey.Section(section) } } @@ -94,7 +118,7 @@ object TaskGroups { private fun dueRank(key: TaskGroupKey): Int = when (key) { is TaskGroupKey.Day -> TaskSection.UPCOMING.ordinal is TaskGroupKey.Section -> key.section.ordinal - else -> Int.MAX_VALUE + is TaskGroupKey.OfPriority, is TaskGroupKey.OfList -> error("not a due-date group: $key") } private fun localDueDate(task: Task, zone: ZoneId): LocalDate { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt index 181de9f..82ec6fe 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.agendula.domain +import java.time.ZoneId import kotlin.time.Instant /** A due-date bucket a task list groups its rows under. */ @@ -29,10 +30,16 @@ object TaskSections { } } - fun sectionOf(task: Task, todayStart: Instant, todayEnd: Instant, todayList: Boolean = false): TaskSection { + fun sectionOf( + task: Task, + todayStart: Instant, + todayEnd: Instant, + todayList: Boolean = false, + zone: ZoneId = ZoneId.systemDefault(), + ): TaskSection { if (task.isCompleted) return TaskSection.COMPLETED if (todayList) return TaskSection.TODAY - return when (dueWindowOf(task, todayStart, todayEnd)) { + return when (dueWindowOf(task, todayStart, todayEnd, zone)) { DueWindow.OVERDUE -> TaskSection.OVERDUE DueWindow.TODAY -> TaskSection.TODAY DueWindow.UPCOMING -> TaskSection.UPCOMING 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 03abe3f..cdf529d 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 @@ -84,6 +84,7 @@ 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,6 +109,8 @@ 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 import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task @@ -132,8 +135,6 @@ import de.jeanlucmakiola.floret.components.pastelize import de.jeanlucmakiola.floret.components.positionOf import java.time.LocalDate import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.util.Locale import kotlin.time.Clock /** @@ -320,7 +321,7 @@ fun TaskListScreen( sortOrder = content.sortOrder, grouping = content.grouping, // A real list is one list already; grouping it by list would only add a header. - groupings = TaskGrouping.entries.filter { it != TaskGrouping.LIST || filter !is TaskFilter.OfList }, + groupings = content.groupings, tags = content.availableTags, selectedTags = content.selectedTags, onSortOrder = viewModel::setSortOrder, @@ -379,7 +380,15 @@ private fun TaskListBody( viewModel: TaskListViewModel, onClearCompleted: (() -> Unit)? = null, ) { - val (todayStart, todayEnd) = remember(state.tasks) { DayWindow.today(Clock.System.now(), ZoneId.systemDefault()) } + // 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++ + } // 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 @@ -388,22 +397,32 @@ private fun TaskListBody( val present = state.tasks.mapTo(HashSet()) { it.taskId } state.tasks.filter { (it.parentId ?: 0L) <= 0L || it.parentId !in present } } - val groups = remember(displayTasks, todayStart, state.grouping) { + val groups = remember(displayTasks, todayStart, state.grouping, state.listOrder) { TaskGroups.of( displayTasks, state.grouping, todayStart, todayEnd, todayList = filter == TaskFilter.Smart(SmartList.TODAY), + listOrder = state.listOrder, ) } - // A grouping the user picked keeps its header even when everything lands in one group. - val showHeaders = groups.size > 1 || (groups.isNotEmpty() && state.grouping != TaskGrouping.DUE) + // A grouping the user picked keeps its header even when everything lands in + // one group — unless that group is Done, which starts folded. + val showHeaders = groups.size > 1 || + (state.grouping != TaskGrouping.DUE && groups.singleOrNull()?.key.let { it != null && it != TaskGroupKey.COMPLETED }) + // Lists sharing a name (one per account) are told apart by their account. + val sharedListNames = remember(groups) { + groups.mapNotNull { (it.key as? TaskGroupKey.OfList)?.name }.groupingBy { it }.eachCount() + .filterValues { it > 1 }.keys + } 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 both are redundant. - val showListName = filter is TaskFilter.Smart || filter is TaskFilter.Tagged || - (filter is TaskFilter.Saved && state.savedFilter?.listIds?.size != 1) + // 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) + ) // 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()) } @@ -459,11 +478,11 @@ private fun TaskListBody( if (showHeaders) { stickyHeader(key = "hdr-$groupId") { CollapsibleSectionHeader( - label = groupLabel(group.key, todayStart), + label = groupLabel(group.key, todayStart, sharedListNames), count = group.tasks.size, expanded = expanded, onToggle = { viewModel.setGroupCollapsed(groupId, expanded) }, - onClear = onClearCompleted.takeIf { group.key == TaskGroupKey.Section(TaskSection.COMPLETED) }, + onClear = onClearCompleted.takeIf { group.key == TaskGroupKey.COMPLETED }, ) } } @@ -1281,8 +1300,10 @@ private fun ViewOptionsPicker( onClick = { onSortOrder(order) }, ) } - Spacer(Modifier.height(8.dp)) - GroupedSectionHeader(stringResource(R.string.group_title)) + if (groupings.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(stringResource(R.string.group_title)) + } groupings.forEachIndexed { index, option -> val isSelected = option == grouping val (title, summary) = groupingLabels(option) @@ -1344,36 +1365,44 @@ private fun sectionLabel(section: TaskSection): String = stringResource( ) @Composable -private fun groupLabel(key: TaskGroupKey, todayStart: kotlin.time.Instant): String = when (key) { - is TaskGroupKey.Section -> sectionLabel(key.section) - is TaskGroupKey.Day -> { - val today = java.time.Instant.ofEpochMilli(todayStart.toEpochMilliseconds()) - .atZone(ZoneId.systemDefault()).toLocalDate() - if (key.date == today.plusDays(1)) stringResource(R.string.group_tomorrow) else dayLabel(key.date, today) +private fun groupLabel(key: TaskGroupKey, todayStart: kotlin.time.Instant, sharedListNames: Set): String = + when (key) { + is TaskGroupKey.Section -> sectionLabel(key.section) + is TaskGroupKey.Day -> dayLabel(key.date, todayStart) + is TaskGroupKey.OfPriority -> stringResource( + when (key.priority) { + Priority.HIGH -> R.string.group_priority_high + Priority.MEDIUM -> R.string.group_priority_medium + Priority.LOW -> R.string.group_priority_low + Priority.NONE -> R.string.group_priority_none + }, + ) + is TaskGroupKey.OfList -> { + val name = key.name?.takeIf { it.isNotBlank() } ?: stringResource(R.string.group_list_unnamed) + val account = key.accountName?.takeIf { key.name in sharedListNames && it.isNotBlank() } + if (account == null) name else stringResource(R.string.group_list_in_account, name, account) + } } - is TaskGroupKey.OfPriority -> stringResource( - when (key.priority) { - Priority.HIGH -> R.string.group_priority_high - Priority.MEDIUM -> R.string.group_priority_medium - Priority.LOW -> R.string.group_priority_low - Priority.NONE -> R.string.group_priority_none - }, - ) - is TaskGroupKey.OfList -> key.name?.takeIf { it.isNotBlank() } ?: stringResource(R.string.group_list_unnamed) -} -/** A day header in the locale's own order, e.g. "Friday, 21 November"; the year only when it isn't this one's. */ -private fun dayLabel(date: LocalDate, today: LocalDate): String { - val locale = Locale.getDefault() - val skeleton = if (date.year == today.year) "EEEEMMMMd" else "EEEEMMMMdy" - val pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton) - return date.format(DateTimeFormatter.ofPattern(pattern, locale)) +/** "Tomorrow", else the date in the locale's own order, e.g. "Friday, 21 November"; the year only when it isn't this one. */ +@Composable +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) + val locale = currentLocale() + val sameYear = date.year == today.year + val formatter = remember(locale, sameYear) { + localizedDateFormatter(locale, if (sameYear) "EEEEMMMMd" else "EEEEMMMMdy") + } + return date.format(formatter) } private fun groupingLabels(grouping: TaskGrouping): Pair = 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.group_priority to R.string.group_priority_summary + TaskGrouping.PRIORITY -> R.string.sort_priority to R.string.group_priority_summary TaskGrouping.LIST -> R.string.group_list to R.string.group_list_summary } 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 b9bfb7a..492c177 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 @@ -16,6 +16,7 @@ import de.jeanlucmakiola.agendula.domain.tagsInUse import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.TaskGrouping +import de.jeanlucmakiola.agendula.domain.TaskGroups import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.agendula.domain.comparator import de.jeanlucmakiola.agendula.ui.lists.ListWriteFailure @@ -61,6 +62,10 @@ sealed interface TaskListUiState { val sortOrder: TaskSortOrder = TaskSortOrder.DUE, /** How this view groups its rows. */ val grouping: TaskGrouping = TaskGrouping.DUE, + /** The groupings the view options offer here. */ + val groupings: List = emptyList(), + /** List ids in the Lists screen's order, which list groups follow. */ + val listOrder: List = emptyList(), /** Ids of the groups whose rows are folded under their header. */ val collapsedGroups: Set = DEFAULT_COLLAPSED_GROUPS, /** This real list is kept out of the smart lists. */ @@ -141,7 +146,8 @@ 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). - combine(content, pendingDeletes, settingsPrefs.settings, tagFilter) { st, pending, settings, tags -> + val listOrder = repository.taskLists().map { lists -> lists.map { it.id } } + combine(content, pendingDeletes, settingsPrefs.settings, tagFilter, listOrder) { st, pending, settings, tags, order -> 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) @@ -149,6 +155,7 @@ class TaskListViewModel @Inject constructor( // for good rather than narrowing again when it comes back. val selected = tags.filterTo(LinkedHashSet()) { it in available } if (selected.size != tags.size) tagFilter.value = selected + val groupings = TaskGroups.offeredFor(f, st.savedFilter) st.copy( filter = f, tasks = visible @@ -159,7 +166,9 @@ class TaskListViewModel @Inject constructor( showAddSubtaskRow = settings.showAddSubtaskRow, bottomAddBar = settings.bottomAddBar, sortOrder = settings.sortOrder, - grouping = settings.groupingFor(f), + grouping = settings.groupingFor(f).takeIf { it in groupings } ?: TaskGrouping.DUE, + groupings = groupings, + listOrder = order, collapsedGroups = settings.collapsedGroups, hiddenFromSmartLists = st.list?.id?.let { it in settings.hiddenFromSmartLists } ?: false, ) @@ -369,7 +378,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 { + settingsPrefs.forgetList(listId) + _listDeleted.value = true + } .onFailure { _listWriteFailure.value = ListWriteFailure.DELETE } return@launch } @@ -381,7 +393,12 @@ 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) { + settingsPrefs.forgetList(listId) + _listDeleted.value = true + } else { + _listWriteFailure.value = failure + } } /** Inline "add subtask" from an expanded list group — files it under [parent]. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2452da2..24c5d52 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -52,16 +52,15 @@ Overdue, today, upcoming Day A group for each day - Priority Highest priority first List A group for each list - Tomorrow High priority Medium priority Low priority No priority Unnamed list + %1$s (%2$s) Clear Clear completed tasks? diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt index 317134d..4be383f 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt @@ -30,6 +30,14 @@ class TaskGroupingPrefsTest { assertThat(settings.groupingFor(TaskFilter.Smart(SmartList.ALL))).isEqualTo(TaskGrouping.DUE) } + @Test + fun `stored list keys only read back in their own store`() { + assertThat(unscopeListKey("list:OWN:5", "OWN")).isEqualTo("list:5") + assertThat(unscopeListKey("list:PROVIDER:5", "OWN")).isNull() + assertThat(unscopeListKey("COMPLETED", "OWN")).isEqualTo("COMPLETED") + assertThat(unscopeListKey("priority:HIGH", "OWN")).isEqualTo("priority:HIGH") + } + @Test fun `collapsed day groups that have passed are dropped`() { val today = LocalDate.of(2026, 11, 17) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt index 633e0ae..7a5ad93 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt @@ -15,8 +15,12 @@ class TaskGroupsTest { private fun at(millis: Long) = Instant.fromEpochMilliseconds(millis) - private fun groups(tasks: List, grouping: TaskGrouping, todayList: Boolean = false) = - TaskGroups.of(tasks, grouping, todayStart, todayEnd, todayList, ZoneOffset.UTC) + private fun groups( + tasks: List, + grouping: TaskGrouping, + todayList: Boolean = false, + listOrder: List = emptyList(), + ) = TaskGroups.of(tasks, grouping, todayStart, todayEnd, todayList, listOrder, ZoneOffset.UTC) private fun keys(tasks: List, grouping: TaskGrouping, todayList: Boolean = false) = groups(tasks, grouping, todayList).map { it.key } @@ -90,18 +94,32 @@ class TaskGroupsTest { } @Test - fun `list grouping orders lists by name and keeps the incoming order inside`() { + fun `list grouping follows the lists' own order and keeps the incoming order inside`() { val tasks = listOf( - testTask(id = 1, listId = 2).copy(listName = "work"), + testTask(id = 1, listId = 2).copy(listName = "Work", accountName = "cloud"), testTask(id = 2, listId = 1).copy(listName = "Home"), - testTask(id = 3, listId = 2).copy(listName = "work"), + testTask(id = 3, listId = 2).copy(listName = "Work", accountName = "cloud"), + testTask(id = 4, listId = 9).copy(listName = "Unknown"), ) - val result = groups(tasks, TaskGrouping.LIST) + val result = groups(tasks, TaskGrouping.LIST, listOrder = listOf(2, 1)) assertThat(result.map { it.key }).containsExactly( - TaskGroupKey.OfList(1, "Home"), - TaskGroupKey.OfList(2, "work"), + TaskGroupKey.OfList(2, "Work", "cloud"), + TaskGroupKey.OfList(1, "Home", null), + TaskGroupKey.OfList(9, "Unknown", null), ).inOrder() - assertThat(result[1].tasks.map { it.taskId }).containsExactly(1L, 3L).inOrder() + assertThat(result[0].tasks.map { it.taskId }).containsExactly(1L, 3L).inOrder() + } + + @Test + fun `only groupings that can change a view are offered`() { + val all = TaskGrouping.entries + assertThat(TaskGroups.offeredFor(TaskFilter.Smart(SmartList.ALL))).isEqualTo(all) + assertThat(TaskGroups.offeredFor(TaskFilter.Smart(SmartList.COMPLETED))).isEmpty() + assertThat(TaskGroups.offeredFor(TaskFilter.Smart(SmartList.TODAY))).doesNotContain(TaskGrouping.DAY) + assertThat(TaskGroups.offeredFor(TaskFilter.OfList(1))).doesNotContain(TaskGrouping.LIST) + 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) } @Test @@ -109,7 +127,7 @@ class TaskGroupsTest { assertThat(TaskGroupKey.Section(TaskSection.COMPLETED).id).isEqualTo("COMPLETED") assertThat(TaskGroupKey.Day(LocalDate.of(2026, 11, 20)).id).isEqualTo("day:2026-11-20") assertThat(TaskGroupKey.OfPriority(Priority.HIGH).id).isEqualTo("priority:HIGH") - assertThat(TaskGroupKey.OfList(7, "x").id).isEqualTo("list:7") + assertThat(TaskGroupKey.OfList(7, "x", null).id).isEqualTo("list:7") } @Test From 761f3f5b3dc046879ffa585d6026542a4ec03519 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:15:42 +0100 Subject: [PATCH 3/4] Task grouping: prune gone lists, refresh at midnight, tidy up (#71) --- .../agendula/data/prefs/SettingsPrefs.kt | 27 ++++++-- .../agendula/domain/TaskGroups.kt | 15 +++-- .../agendula/domain/TaskSections.kt | 8 +-- .../agendula/ui/tasklist/TaskListScreen.kt | 33 +++++----- .../agendula/ui/tasklist/TaskListViewModel.kt | 66 +++++++++++++------ app/src/main/res/values/strings.xml | 2 + .../data/prefs/TaskGroupingPrefsTest.kt | 11 ++++ .../agendula/domain/TaskGroupsTest.kt | 3 + 8 files changed, 113 insertions(+), 52 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index 7a1897f..40291fa 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -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) = 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, + mode: String, + listIds: Set, + keyOf: (String) -> String = { it }, +): Set = 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 diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt index 2855849..4001e7e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt @@ -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 { - val dropped = when (filter) { + val dropped: Set = 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" diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt index 82ec6fe..9b66d93 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt @@ -23,12 +23,10 @@ data class SectionedTasks(val section: TaskSection, val tasks: List) */ object TaskSections { - fun of(tasks: List, todayStart: Instant, todayEnd: Instant, todayList: Boolean = false): List { - 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, todayStart: Instant, todayEnd: Instant, todayList: Boolean = false): List = + TaskGroups.of(tasks, TaskGrouping.DUE, todayStart, todayEnd, todayList).map { group -> + SectionedTasks((group.key as TaskGroupKey.Section).section, group.tasks) } - } fun sectionOf( task: Task, 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 cdf529d..84eec2e 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 @@ -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 = 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 } 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 492c177..69604c8 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 @@ -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 = emptyList(), /** List ids in the Lists screen's order, which list groups follow. */ val listOrder: List = 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 = DEFAULT_COLLAPSED_GROUPS, /** This real list is kept out of the smart lists. */ @@ -125,20 +135,44 @@ class TaskListViewModel @Inject constructor( val undo: StateFlow = _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> = + 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? = null + + /** Forgets groupings and folds of lists that are gone; runs only when the set of lists changes. */ + private fun retainLists(lists: List) { + val ids = lists.mapTo(HashSet()) { it.id } + if (ids.isEmpty() || ids == retainedLists) return + retainedLists = ids + viewModelScope.launch { runCatching { settingsPrefs.retainLists(ids) } } + } + val state: StateFlow = filter.filterNotNull() .flatMapLatest { f -> - val tasks = repository.tasks(f) - val content: kotlinx.coroutines.flow.Flow = when (f) { + val lists = repository.taskLists().onEach(::retainLists) + val content: Flow = 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]. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 24c5d52..b05238d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -52,9 +52,11 @@ Overdue, today, upcoming Day A group for each day + Priority Highest priority first List A group for each list + Tomorrow High priority Medium priority Low priority diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt index 4be383f..e6a83bd 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt @@ -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) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt index 7a5ad93..ec8e846 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt @@ -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 From 367e04fa72ec891433db9ace42c34ed05a6cb221 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:21:44 +0100 Subject: [PATCH 4/4] Task grouping: keep rows and day window together, safer list cleanup (#71) --- .../agendula/data/prefs/SettingsPrefs.kt | 27 ++----- .../agendula/ui/tasklist/TaskListScreen.kt | 14 ++-- .../agendula/ui/tasklist/TaskListViewModel.kt | 79 ++++++++++--------- .../data/prefs/TaskGroupingPrefsTest.kt | 11 --- 4 files changed, 55 insertions(+), 76 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index 40291fa..1997dc6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -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) = 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, - mode: String, - listIds: Set, - keyOf: (String) -> String = { it }, -): Set = 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 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 84eec2e..8ed3ce9 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 @@ -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()) } @@ -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, 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 69604c8..6f50d8c 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 @@ -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 = _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> = + /** + * 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> = 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? = null - - /** Forgets groupings and folds of lists that are gone; runs only when the set of lists changes. */ - private fun retainLists(lists: List) { - 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 = filter.filterNotNull() .flatMapLatest { f -> - val lists = repository.taskLists().onEach(::retainLists) - val content: Flow = 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 = 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 = 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]. */ diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt index e6a83bd..4be383f 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt @@ -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)