diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ed560b..abc79a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,11 @@ All notable changes to this project are documented here. The format follows completed tasks included. A completed match can be reopened with its checkbox, and a title the list doesn't have yet can be added straight from the search; pressing enter reopens or adds the typed task (#95). +- 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. 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 eaa1597..573bb52 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 @@ -21,7 +21,10 @@ import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.calendarDate 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 @@ -74,7 +77,8 @@ enum class ListPersistence { INHERIT, ALWAYS, NEVER } 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) @@ -144,14 +148,19 @@ data class Settings( val defaultDueDate: DefaultDueDate = DefaultDueDate.NONE, /** The start date a new task's form starts with. */ val defaultStartDate: DefaultStartDate = DefaultStartDate.NONE, - /** 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(), /** How far ahead the Upcoming smart list reaches. */ val upcomingRange: UpcomingRange = UpcomingRange.ALL, ) { /** Whether a save rings the reminders it puts in the past (#106). */ val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave + 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, * and Upcoming whatever is due past [upcomingRange]. @@ -289,20 +298,29 @@ class SettingsPrefs @Inject constructor( // The "start today" switch of earlier versions carries over until a start is picked. defaultStartDate = p[DEFAULT_START_DATE]?.let { runCatching { DefaultStartDate.valueOf(it) }.getOrNull() } ?: if (p[DEFAULT_START_TODAY] == true) DefaultStartDate.TODAY else DefaultStartDate.NONE, - collapsedSections = p[COLLAPSED_SECTIONS] - ?.mapNotNull { name -> runCatching { TaskSection.valueOf(name) }.getOrNull() } - ?.toSet() - ?: DEFAULT_COLLAPSED_SECTIONS, + collapsedGroups = (p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS) + .mapNotNullTo(HashSet()) { unscopeListKey(it, modeOf(p).name) }, + groupings = decodeGroupings(p[GROUPINGS].orEmpty(), modeOf(p).name), upcomingRange = p[UPCOMING_RANGE]?.let { runCatching { UpcomingRange.valueOf(it) }.getOrNull() } ?: UpcomingRange.ALL, ) } - 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 stored = scopeListKey(id, modeOf(p).name) + val current = dropPastDays(p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, LocalDate.now()) + 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 = 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 list deleted here, so a later list given its id starts fresh. */ suspend fun setUpcomingRange(range: UpcomingRange) = dataStore.edit { it[UPCOMING_RANGE] = range.name } suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name } @@ -330,6 +348,9 @@ class SettingsPrefs @Inject constructor( p[LIST_PERSISTENT_REMINDERS] = p[LIST_PERSISTENT_REMINDERS].orEmpty() .filterNotTo(HashSet()) { it.startsWith(listPersistencePrefix(mode, listId)) } p[SMART_LIST_HIDDEN] = p[SMART_LIST_HIDDEN].orEmpty() - "$mode:$listId" + val key = scopeListKey("${TaskGroupKey.LIST_PREFIX}$listId", mode) + 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 setSyncIntervalMinutes(minutes: Int) = dataStore.edit { it[SYNC_INTERVAL] = minutes } @@ -461,6 +482,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 { @@ -500,6 +523,7 @@ class SettingsPrefs @Inject constructor( val REMIND_PAST_ON_SAVE = booleanPreferencesKey("remind_past_on_save") val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections") val UPCOMING_RANGE = stringPreferencesKey("upcoming_range") + val GROUPINGS = stringSetPreferencesKey("task_groupings") val SAVED_FILTERS = stringPreferencesKey("saved_filters") val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id") } @@ -537,3 +561,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 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]. */ +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, "") + 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. */ +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..86155da --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskGroups.kt @@ -0,0 +1,144 @@ +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?, 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) + } +} + +/** 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. + * List groups follow [listOrder] (the Lists screen's order); lists not in it go last. + */ +object TaskGroups { + + fun of( + tasks: List, + grouping: TaskGrouping, + todayStart: Instant, + todayEnd: Instant, + todayList: Boolean = false, + listOrder: List = emptyList(), + 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 -> { + 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.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: 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() + // 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 -> 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 + } + + private fun dueKey( + task: Task, + perDay: Boolean, + todayStart: Instant, + todayEnd: Instant, + todayList: Boolean, + zone: ZoneId, + ): TaskGroupKey { + val section = TaskSections.sectionOf(task, todayStart, todayEnd, todayList, zone) + return if (perDay && section == TaskSection.UPCOMING) { + TaskGroupKey.Day(localDueDate(task, zone)) + } else { + TaskGroupKey.Section(section) + } + } + + /** 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 + is TaskGroupKey.OfPriority, is TaskGroupKey.OfList -> error("not a due-date group: $key") + } + + private fun localDueDate(task: Task, zone: ZoneId): LocalDate { + val due = requireNotNull(task.wallClock(TaskEnd.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 -> "${TaskGroupKey.LIST_PREFIX}$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/domain/TaskSections.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSections.kt index 181de9f..9b66d93 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. */ @@ -22,17 +23,21 @@ 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, 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 05fdb98..270cea6 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,8 @@ 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 import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task @@ -121,6 +122,9 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskSection import de.jeanlucmakiola.agendula.domain.TaskSections import de.jeanlucmakiola.agendula.domain.TaskSearch +import de.jeanlucmakiola.agendula.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 @@ -135,11 +139,11 @@ 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 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. @@ -388,9 +392,12 @@ fun TaskListScreen( sortOrder = content.sortOrder, upcomingRange = content.upcomingRange.takeIf { filter == TaskFilter.Smart(SmartList.UPCOMING) }, onUpcomingRange = viewModel::setUpcomingRange, + grouping = content.grouping, + groupings = content.groupings, tags = content.availableTags, selectedTags = content.selectedTags, onSortOrder = viewModel::setSortOrder, + onGrouping = viewModel::setGrouping, onToggleTag = viewModel::toggleTagFilter, onClearTags = viewModel::clearTagFilter, onDismiss = { showSort = false }, @@ -445,7 +452,8 @@ private fun TaskListBody( viewModel: TaskListViewModel, onClearCompleted: (() -> Unit)? = null, ) { - val (todayStart, todayEnd) = remember(state.tasks) { DayWindow.today(Clock.System.now(), ZoneId.systemDefault()) } + 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 @@ -454,14 +462,29 @@ 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, 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 — 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 showHeaders = sections.size > 1 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 || + 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. @@ -516,17 +539,22 @@ private fun TaskListBody( item(key = "empty") { EmptyState(stringResource(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 + // 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-${section.section}") { + stickyHeader(key = "hdr-$groupId") { CollapsibleSectionHeader( - label = sectionLabel(section.section), - count = section.tasks.size, + label = groupLabel(group.key, todayStart, sharedListNames), + 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.COMPLETED }, ) } } @@ -538,7 +566,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 @@ -591,6 +619,7 @@ private fun TaskListBody( position = r.position, lastInRun = lastInRun, showListName = showListName, + showPriority = showPriority, subtaskDone = row.task.subtaskDone, subtaskTotal = row.task.subtaskTotal, expanded = row.expanded, @@ -725,6 +754,7 @@ private fun TaskRow( position: Position, lastInRun: Boolean, showListName: Boolean, + showPriority: Boolean, subtaskDone: Int, subtaskTotal: Int, expanded: Boolean, @@ -760,7 +790,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, + ) } } @@ -776,6 +809,7 @@ internal fun TaskRowContent( onToggleExpand: (() -> Unit)?, onToggle: () -> Unit, onClick: () -> Unit, + showPriority: Boolean = true, ) { val interaction = remember { MutableInteractionSource() } val pressed by interaction.collectIsPressedAsState() @@ -785,7 +819,9 @@ internal fun TaskRowContent( val due = task.shownValue(TaskEnd.DUE)?.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), 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( @@ -834,7 +870,7 @@ internal fun TaskRowContent( if (hasMeta) { Spacer(Modifier.height(3.dp)) TaskMetaLine( - priority = task.priority, + priority = priority, due = due, recurring = task.isOccurrence, subtaskDone = subtaskDone, @@ -1317,9 +1353,12 @@ private fun ViewOptionsPicker( sortOrder: TaskSortOrder, upcomingRange: UpcomingRange?, onUpcomingRange: (UpcomingRange) -> Unit, + grouping: TaskGrouping, + groupings: List, tags: List, selectedTags: Set, onSortOrder: (TaskSortOrder) -> Unit, + onGrouping: (TaskGrouping) -> Unit, onToggleTag: (String) -> Unit, onClearTags: () -> Unit, onDismiss: () -> Unit, @@ -1358,6 +1397,22 @@ private fun ViewOptionsPicker( ) } } + 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) + 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)) @@ -1415,6 +1470,48 @@ private fun sectionLabel(section: TaskSection): String = stringResource( }, ) +@Composable +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) + } + } + +/** "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.group_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.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 5be4f2f..ef0a826 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 @@ -4,9 +4,10 @@ import androidx.lifecycle.SavedStateHandle 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.FilteredTasks import de.jeanlucmakiola.agendula.data.tasks.TasksRepository import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure import de.jeanlucmakiola.agendula.domain.ListSearchResult @@ -19,6 +20,8 @@ import de.jeanlucmakiola.agendula.domain.tagsInUse import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.TaskSection +import de.jeanlucmakiola.agendula.domain.TaskGrouping +import de.jeanlucmakiola.agendula.domain.TaskGroups import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.agendula.domain.UpcomingRange import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater @@ -33,6 +36,7 @@ import kotlinx.coroutines.Dispatchers 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 @@ -43,16 +47,21 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import 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 @@ -74,8 +83,17 @@ sealed interface TaskListUiState { val upcomingRange: UpcomingRange = UpcomingRange.ALL, /** Upcoming's time frame is hiding tasks due further ahead. */ val hiddenByRange: Boolean = false, - /** 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, + /** 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(), + /** 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. */ val hiddenFromSmartLists: Boolean = false, /** Tags the unnarrowed view carries, offered as filter chips. */ @@ -153,24 +171,41 @@ class TaskListViewModel @Inject constructor( val undo: StateFlow = _undo.asStateFlow() private var undoTimer: Job? = null + /** + * 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 = DayWindow.today(Clock.System.now(), ZoneId.systemDefault()) + emit(window) + delay((window.second - Clock.System.now()).inWholeMilliseconds.coerceIn(0, 60_000) + 1) + } + }.distinctUntilChanged() + val state: StateFlow = filter.filterNotNull() .flatMapLatest { f -> - val tasks = repository.tasks(f) - val content: kotlinx.coroutines.flow.Flow = when (f) { - is TaskFilter.OfList -> - combine(tasks, repository.taskLists()) { rows, lists -> - TaskListUiState.Content(rows, lists.firstOrNull { it.id == f.listId }) - } - is TaskFilter.Smart, is TaskFilter.Tagged -> - tasks.map { TaskListUiState.Content(it) } - is TaskFilter.Saved -> - repository.filteredTasks(f).map { - TaskListUiState.Content(it.tasks, savedFilter = it.savedFilter) - } + 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). @@ -186,6 +221,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 @@ -199,7 +235,9 @@ class TaskListViewModel @Inject constructor( sortOrder = settings.sortOrder, upcomingRange = settings.upcomingRange, hiddenByRange = hiddenByRange, - collapsedSections = settings.collapsedSections, + grouping = settings.groupingFor(f).takeIf { it in groupings } ?: TaskGrouping.DUE, + groupings = groupings, + collapsedGroups = settings.collapsedGroups, hiddenFromSmartLists = st.list?.id?.let { it in settings.hiddenFromSmartLists } ?: false, ) } else { @@ -337,8 +375,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) } @@ -527,8 +570,8 @@ class TaskListViewModel @Inject constructor( if (accountId == null) { runCatching { repository.deleteList(listId) } .onSuccess { - forgetListSettings(listId) _listDeleted.value = true + forgetList(listId) } .onFailure { _listWriteFailure.value = ListWriteFailure.DELETE } return@launch @@ -542,15 +585,16 @@ class TaskListViewModel @Inject constructor( .getOrElse { RemoteLists.Outcome.Unreachable } val failure = outcome.asFailure(ListWriteFailure.DELETE) if (failure == null) { - forgetListSettings(listId) _listDeleted.value = true + forgetList(listId) } else { _listWriteFailure.value = failure } } - private suspend fun forgetListSettings(listId: Long) { - runCatching { settingsPrefs.forgetList(listId) } + /** 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/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 129d8ee..4d77665 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -55,6 +55,22 @@ 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 + %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 new file mode 100644 index 0000000..4be383f --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/TaskGroupingPrefsTest.kt @@ -0,0 +1,50 @@ +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 `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) + 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..ec8e846 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskGroupsTest.kt @@ -0,0 +1,140 @@ +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, + 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 } + + @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 follows the lists' own order and keeps the incoming order inside`() { + val tasks = listOf( + 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", accountName = "cloud"), + testTask(id = 4, listId = 9).copy(listName = "Unknown"), + ) + val result = groups(tasks, TaskGrouping.LIST, listOrder = listOf(2, 1)) + assertThat(result.map { it.key }).containsExactly( + TaskGroupKey.OfList(2, "Work", "cloud"), + TaskGroupKey.OfList(1, "Home", null), + TaskGroupKey.OfList(9, "Unknown", null), + ).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) + 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 + 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", null).id).isEqualTo("list:7") + } + + @Test + fun `empty input yields no groups`() { + TaskGrouping.entries.forEach { assertThat(groups(emptyList(), it)).isEmpty() } + } +}