Base saved filters on the rule tree, stored in a v2 format (#172)

This commit is contained in:
makiolaj committed 2026-11-26 16:23:50 +01:00
1 parent 697e2e8554
commit ceaff3183c
18 files changed
+645 -236

No files matched your search

@@ -1,21 +1,33 @@
package de.jeanlucmakiola.agendula.data.prefs
import de.jeanlucmakiola.agendula.domain.DueSpec
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.Rule
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.TagMatch
import de.jeanlucmakiola.agendula.domain.withoutLists
import java.net.URLDecoder
import java.net.URLEncoder
/**
* Stored form of the saved filters: one line per filter,
* `id|name|due|lists|tags|match|priority`, with name and tags URL-encoded and
* list ids qualified by the store they belong to (`OWN:3`), since each store
* numbers its lists on its own. Fixed once released — don't change without a
* data migration.
* Stored form of the saved filters: one line per filter, `v2|id|name|rule`.
* The rule is written as nested calls: `and(…)`, `or(…)`, `not(…)`,
* `list(OWN%3A3,…)`, `tag(…)`, `prio(HIGH)`, `due(TODAY)` and
* `range(today|week|month)` or `range(next,7)`. Names, tags and list refs are
* URL-encoded, and list ids are qualified by the store they belong to
* (`OWN:3`), since each store numbers its lists on its own.
*
* Lines without the `v2` mark are the flat format of 1.4 and earlier,
* `id|name|due|lists|tags|match|priority`, and still read.
*
* Fixed once released — don't change without a data migration.
*/
internal object SavedFilterCodec {
private const val V2 = "v2"
/** The filters in [raw], with only the list ids of [mode]'s store. */
fun decode(raw: String?, mode: String): List<SavedFilter> =
lines(raw).mapNotNull { runCatching { decodeLine(it, mode) }.getOrNull() }
@@ -24,30 +36,20 @@ internal object SavedFilterCodec {
fun upsert(raw: String?, filter: SavedFilter, mode: String): String {
val existing = lines(raw)
val index = existing.indexOfFirst { idOf(it) == filter.id }
// Keep the lists another store contributed, so switching stores and back
// doesn't widen a filter that was edited in between, unless "any list"
// was chosen here, which drops them on purpose.
val foreign = if (filter.anyList) {
emptyList()
} else {
existing.getOrNull(index)?.let(::fields)?.getOrNull(3)
?.let(::splitList)?.filterNot { it.startsWith("$mode:") }.orEmpty()
}
val line = encodeLine(filter, mode, foreign)
val line = encodeLine(filter, mode)
val updated = if (index >= 0) existing.toMutableList().also { it[index] = line } else existing + line
return updated.joinToString("\n")
}
/**
* [raw] without the lists of [mode]'s store [gone] names. A filter left
* without lists matches any, as a read of it already did with them gone.
* [raw] without the lists of [mode]'s store [gone] names. A list condition
* left without lists drops out, as a read of it already did with them gone.
*/
fun withoutLists(raw: String?, mode: String, gone: (Long) -> Boolean): String =
lines(raw).joinToString("\n") { line ->
val f = fields(line)
if (f.size < 7) return@joinToString line
val kept = splitList(f[3]).filterNot { it.startsWith("$mode:") && it.removePrefix("$mode:").toLongOrNull()?.let(gone) == true }
f.toMutableList().also { it[3] = kept.joinToString(",") }.joinToString("|")
val filter = runCatching { decodeLine(line, mode) }.getOrNull() ?: return@joinToString line
val pruned = filter.copy(rule = filter.rule.withoutLists(gone) ?: Rule.Everything)
if (pruned == filter) line else encodeLine(pruned, mode)
}
fun remove(raw: String?, id: Long): String = lines(raw).filterNot { idOf(it) == id }.joinToString("\n")
@@ -56,37 +58,121 @@ internal object SavedFilterCodec {
private fun fields(line: String): List<String> = line.split('|')
private fun idOf(line: String): Long? = fields(line).firstOrNull()?.toLongOrNull()
private fun isV2(line: String): Boolean = line.startsWith("$V2|")
private fun idOf(line: String): Long? = fields(line).getOrNull(if (isV2(line)) 1 else 0)?.toLongOrNull()
private fun splitList(value: String): List<String> = value.split(',').filter { it.isNotEmpty() }
private fun encodeLine(filter: SavedFilter, mode: String, foreignLists: List<String>): String =
listOf(
filter.id.toString(),
encode(filter.name),
filter.due.sorted().joinToString(",") { it.name },
(filter.listIds.sorted().map { "$mode:$it" } + foreignLists).joinToString(","),
filter.tags.sorted().joinToString(",") { encode(it) },
filter.tagMatch.name,
filter.minPriority.name,
).joinToString("|")
private fun encodeLine(filter: SavedFilter, mode: String): String =
listOf(V2, filter.id.toString(), encode(filter.name), encodeRule(filter.rule, mode)).joinToString("|")
private fun decodeLine(line: String, mode: String): SavedFilter? {
if (!isV2(line)) return decodeFlatLine(line, mode)
val f = fields(line)
if (f.size != 4) return null
val id = f[1].toLongOrNull() ?: return null
// A list condition with none of its lists readable drops out, as a flat filter's did.
val rule = RuleParser(f[3], mode).parse().withoutLists { false } ?: Rule.Everything
return SavedFilter(id = id, name = decode(f[2]), rule = rule)
}
private fun decodeFlatLine(line: String, mode: String): SavedFilter? {
val f = fields(line)
if (f.size < 7) return null
val id = f[0].toLongOrNull() ?: return null
val lists = splitList(f[3])
val here = lists.filter { it.startsWith("$mode:") }.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet()
return SavedFilter(
id = id,
name = decode(f[1]),
val (here, elsewhere) = splitRefs(splitList(f[3]), mode)
val criteria = FilterCriteria(
due = splitList(f[2]).mapNotNull { runCatching { DueWindow.valueOf(it) }.getOrNull() }.toSet(),
listIds = here,
listsElsewhere = lists.any { !it.startsWith("$mode:") },
listsElsewhere = elsewhere,
tags = splitList(f[4]).map(::decode).toSet(),
tagMatch = runCatching { TagMatch.valueOf(f[5]) }.getOrDefault(TagMatch.ANY),
minPriority = runCatching { Priority.valueOf(f[6]) }.getOrDefault(Priority.NONE),
)
return SavedFilter(id = id, name = decode(f[1]), criteria = criteria)
}
/** [refs] split into [mode]'s list ids and the other stores' refs as they are. */
private fun splitRefs(refs: List<String>, mode: String): Pair<Set<Long>, Set<String>> {
val (here, elsewhere) = refs.partition { it.startsWith("$mode:") }
return here.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet() to elsewhere.toSet()
}
private fun encodeRule(rule: Rule, mode: String): String = when (rule) {
is Rule.All -> "and(${rule.children.joinToString(",") { encodeRule(it, mode) }})"
is Rule.Any -> "or(${rule.children.joinToString(",") { encodeRule(it, mode) }})"
is Rule.Not -> "not(${encodeRule(rule.child, mode)})"
is Rule.InList -> {
val refs = rule.listIds.sorted().map { "$mode:$it" } + rule.elsewhere.sorted()
"list(${refs.joinToString(",") { encode(it) }})"
}
is Rule.HasTag -> "tag(${encode(rule.tag)})"
is Rule.MinPriority -> "prio(${rule.priority.name})"
is Rule.Due -> when (val spec = rule.window) {
is DueSpec.Window -> "due(${spec.window.name})"
DueSpec.Today -> "range(today)"
DueSpec.ThisWeek -> "range(week)"
DueSpec.ThisMonth -> "range(month)"
is DueSpec.NextDays -> "range(next,${spec.days})"
}
}
/** Reads what [encodeRule] writes; throws on anything else. */
private class RuleParser(private val text: String, private val mode: String) {
private var at = 0
fun parse(): Rule = rule().also { require(at == text.length) { "Trailing input at $at" } }
private fun rule(): Rule {
val name = atom()
expect('(')
val rule = when (name) {
"and" -> Rule.All(list(::rule))
"or" -> Rule.Any(list(::rule))
"not" -> Rule.Not(rule())
"list" -> splitRefs(list(::atom).map(::decode), mode).let { (here, elsewhere) -> Rule.InList(here, elsewhere) }
"tag" -> Rule.HasTag(decode(atom()))
"prio" -> Rule.MinPriority(Priority.valueOf(atom()))
"due" -> Rule.Due(DueSpec.Window(DueWindow.valueOf(atom())))
"range" -> Rule.Due(range(list(::atom)))
else -> throw IllegalArgumentException("Unknown rule $name")
}
expect(')')
return rule
}
private fun range(args: List<String>): DueSpec.Range = when {
args == listOf("today") -> DueSpec.Today
args == listOf("week") -> DueSpec.ThisWeek
args == listOf("month") -> DueSpec.ThisMonth
args.size == 2 && args[0] == "next" -> DueSpec.NextDays(args[1].toInt())
else -> throw IllegalArgumentException("Unknown range $args")
}
/** Comma-separated [item]s up to the closing parenthesis, which stays unread. */
private fun <T> list(item: () -> T): List<T> {
if (peek() == ')') return emptyList()
val items = mutableListOf(item())
while (peek() == ',') {
at++
items += item()
}
return items
}
private fun atom(): String {
val start = at
while (at < text.length && text[at] !in "(),") at++
return text.substring(start, at)
}
private fun peek(): Char? = text.getOrNull(at)
private fun expect(c: Char) {
require(peek() == c) { "Expected $c at $at" }
at++
}
}
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
@@ -21,6 +21,7 @@ import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.TaskSorting
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
@@ -31,12 +32,16 @@ import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.DayOfWeek
import java.time.ZoneId
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
@@ -84,12 +89,13 @@ class TasksRepositoryImpl @Inject constructor(
override fun filteredTasks(filter: TaskFilter): Flow<FilteredTasks> = when (filter) {
// A deleted filter shows nothing rather than failing the screen or widget on it.
is TaskFilter.Saved -> settingsPrefs.savedFilter(filter.id)
.flatMapLatest { saved ->
.combine(settingsPrefs.settings.map { it.weekStart ?: localeWeekStart() }.distinctUntilChanged(), ::Pair)
.flatMapLatest { (saved, weekStart) ->
if (saved == null) flowOf(FilteredTasks(emptyList()))
else observing {
// A deleted list's id would otherwise leave the filter quietly empty.
val current = saved.withListsIn(dataSource.taskLists().mapTo(HashSet()) { it.id })
FilteredTasks(loadTasks(filter, current), current)
FilteredTasks(loadTasks(filter, current, weekStart), current)
}
}
else -> observing { FilteredTasks(loadTasks(filter)) }
@@ -113,7 +119,7 @@ class TasksRepositoryImpl @Inject constructor(
}
}
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null): List<Task> {
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null, weekStart: DayOfWeek = localeWeekStart()): List<Task> {
val query = when (filter) {
is TaskFilter.OfList -> TaskQuery(listId = filter.listId, includeCompleted = true)
// Read completed tasks too, then let [TaskFiltering.matches] enforce each
@@ -137,7 +143,7 @@ class TasksRepositoryImpl @Inject constructor(
(if (t.isCompleted) done + 1 else done) to (total + 1)
}
return all
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved) }
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved, weekStart = weekStart) }
.map { task ->
progress[task.taskId]?.let { (done, total) ->
task.copy(subtaskDone = done, subtaskTotal = total)
@@ -0,0 +1,93 @@
package de.jeanlucmakiola.agendula.domain
/**
* The flat form of a filter, as the filter editor shows it: every criterion
* must hold, and an empty one doesn't narrow. No [due] windows means any due
* date, no lists any list, no [tags] any tag, [Priority.NONE] any priority.
*
* [listsElsewhere] are the filter's lists in other task stores, as stored (see
* [Rule.InList.elsewhere]). With some of them but no [listIds] the filter
* matches nothing here rather than every list.
*/
data class FilterCriteria(
val due: Set<DueWindow> = emptySet(),
val listIds: Set<Long> = emptySet(),
val listsElsewhere: Set<String> = emptySet(),
val tags: Set<String> = emptySet(),
val tagMatch: TagMatch = TagMatch.ANY,
val minPriority: Priority = Priority.NONE,
) {
/** Whether the filter narrows by list at all. */
val anyList: Boolean get() = listIds.isEmpty() && listsElsewhere.isEmpty()
/** These criteria as a rule: an [Rule.All] of the criteria that narrow. */
fun toRule(): Rule = Rule.All(
buildList {
if (due.isNotEmpty()) add(Rule.Any(DueWindow.entries.filter { it in due }.map { Rule.Due(DueSpec.Window(it)) }))
if (!anyList) add(Rule.InList(listIds, listsElsewhere))
if (minPriority != Priority.NONE) add(Rule.MinPriority(minPriority))
if (tags.isNotEmpty()) {
val each = tags.sorted().map(Rule::HasTag)
add(if (tagMatch == TagMatch.ALL) Rule.All(each) else Rule.Any(each))
}
},
)
companion object {
/**
* [rule] in flat form, or `null` when it has none: a [Rule.Not], a
* relative due range, a group that mixes kinds of criteria, or one kind
* given twice.
*/
fun of(rule: Rule): FilterCriteria? {
val parts = if (rule is Rule.All) rule.children else listOf(rule)
var criteria = FilterCriteria()
var seen = emptySet<String>()
fun claim(kind: String): Boolean = (kind !in seen).also { seen = seen + kind }
for (part in parts) {
criteria = when {
part is Rule.Due && part.window is DueSpec.Window -> {
if (!claim("due")) return null
criteria.copy(due = setOf(part.window.window))
}
part is Rule.InList -> {
if (!claim("lists") || part.listIds.isEmpty() && part.elsewhere.isEmpty()) return null
criteria.copy(listIds = part.listIds, listsElsewhere = part.elsewhere)
}
part is Rule.MinPriority -> {
if (!claim("priority")) return null
criteria.copy(minPriority = part.priority)
}
part is Rule.HasTag -> {
if (!claim("tags")) return null
criteria.copy(tags = setOf(part.tag), tagMatch = TagMatch.ALL)
}
else -> {
val group = groupOf(part) ?: return null
val windows = group.mapNotNull { ((it as? Rule.Due)?.window as? DueSpec.Window)?.window }
val tags = group.mapNotNull { (it as? Rule.HasTag)?.tag }
when {
part is Rule.Any && windows.size == group.size -> {
if (!claim("due")) return null
criteria.copy(due = windows.toSet())
}
tags.size == group.size -> {
if (!claim("tags")) return null
criteria.copy(tags = tags.toSet(), tagMatch = if (part is Rule.All) TagMatch.ALL else TagMatch.ANY)
}
else -> return null
}
}
}
}
return criteria
}
/** The children of a non-empty [Rule.All] or [Rule.Any]; `null` for anything else. */
private fun groupOf(rule: Rule): List<Rule>? = when (rule) {
is Rule.All -> rule.children
is Rule.Any -> rule.children
else -> null
}?.takeIf { it.isNotEmpty() }
}
}
@@ -82,7 +82,7 @@ fun NewTaskDates.showsIn(
): Boolean {
val probe = openTaskDated(start, due, isAllDay)
return when {
savedFilter != null -> savedFilter.due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in savedFilter.due
savedFilter != null -> savedFilter.admitsDueOf(probe, todayStart, todayEnd)
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd, upcomingEnd = upcomingEnd)
else -> true
}
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.agendula.domain
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.ZoneId
import kotlin.time.Instant
@@ -10,41 +11,37 @@ enum class DueWindow { OVERDUE, TODAY, UPCOMING, NO_DATE }
/** How a [SavedFilter] with several tags reads them. */
enum class TagMatch { ANY, ALL }
/**
* A user-made view over the open tasks. An empty criterion doesn't narrow:
* no [due] windows means any due date, no [listIds] any list, no [tags] any tag.
* [minPriority] [Priority.NONE] lets every priority through.
*
* [listsElsewhere] is set when the filter also has lists in another task store.
* With none of its lists here it then matches nothing rather than every list.
*/
/** A user-made view over the open tasks: the ones that pass [rule]. */
data class SavedFilter(
val id: Long,
val name: String,
val due: Set<DueWindow> = emptySet(),
val listIds: Set<Long> = emptySet(),
val tags: Set<String> = emptySet(),
val tagMatch: TagMatch = TagMatch.ANY,
val minPriority: Priority = Priority.NONE,
val listsElsewhere: Boolean = false,
val rule: Rule = Rule.Everything,
) {
/** Whether the filter narrows by list at all. */
val anyList: Boolean get() = listIds.isEmpty() && !listsElsewhere
constructor(id: Long, name: String, criteria: FilterCriteria) : this(id, name, criteria.toRule())
/** [rule] in the flat form the filter editor shows; `null` when it has none. */
val criteria: FilterCriteria? get() = FilterCriteria.of(rule)
/** This filter without the list ids missing from [existing], e.g. lists since deleted. */
fun withListsIn(existing: Set<Long>): SavedFilter = copy(listIds = listIds intersect existing)
fun withListsIn(existing: Set<Long>): SavedFilter =
copy(rule = rule.withoutLists { it !in existing } ?: Rule.Everything)
fun matches(task: Task, todayStart: Instant, todayEnd: Instant): Boolean {
if (task.isClosed) return false
if (listsElsewhere && listIds.isEmpty()) return false
if (listIds.isNotEmpty() && task.listId !in listIds) return false
if (task.priority < minPriority) return false
if (due.isNotEmpty() && dueWindowOf(task, todayStart, todayEnd) !in due) return false
return when {
tags.isEmpty() -> true
tagMatch == TagMatch.ALL -> task.tags.containsAll(tags)
else -> task.tags.any { it in tags }
}
fun matches(task: Task, clock: RuleClock): Boolean = !task.isClosed && rule.matches(task, clock)
fun matches(
task: Task,
todayStart: Instant,
todayEnd: Instant,
weekStart: DayOfWeek = localeWeekStart(),
): Boolean = matches(task, RuleClock(todayStart, todayEnd, weekStart = weekStart))
/**
* Whether an open task dated like [probe] passes this filter's due windows.
* A filter without a flat form isn't read this way and lets any date through.
*/
fun admitsDueOf(probe: Task, todayStart: Instant, todayEnd: Instant): Boolean {
val due = criteria?.due.orEmpty()
return due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in due
}
}
@@ -92,8 +89,7 @@ val SmartList.dueWindows: Set<DueWindow>
/** [end] as a local instant: a date without a time is read as the start of its day. */
fun Task.wallClock(end: TaskEnd, zone: ZoneId = ZoneId.systemDefault()): Instant? {
if (hasTime(end)) return valueOf(end)
val date = dateOf(end, zone) ?: return null
return Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli())
return dateOf(end, zone)?.let { startOfDay(it, zone) }
}
/** What a task created from a [SavedFilter] starts with, so it lands in that filter. */
@@ -104,13 +100,19 @@ data class NewTaskPreset(
val priority: Priority = Priority.NONE,
)
/** The preset for a new task in this filter; its due is [presetDue]. */
fun SavedFilter.newTaskPreset(today: LocalDate): NewTaskPreset = NewTaskPreset(
listIds = listIds,
tags = when {
tagMatch == TagMatch.ALL -> tags.sorted()
else -> listOfNotNull(tags.minOrNull())
},
dueDate = due.presetDue(today),
priority = minPriority,
)
/**
* The preset for a new task in this filter; its due is [presetDue]. A filter
* without a flat form presets nothing.
*/
fun SavedFilter.newTaskPreset(today: LocalDate): NewTaskPreset {
val criteria = criteria ?: return NewTaskPreset()
return NewTaskPreset(
listIds = criteria.listIds,
tags = when {
criteria.tagMatch == TagMatch.ALL -> criteria.tags.sorted()
else -> listOfNotNull(criteria.tags.minOrNull())
},
dueDate = criteria.due.presetDue(today),
priority = criteria.minPriority,
)
}
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.agendula.domain
import java.time.DayOfWeek
import java.time.ZoneId
import kotlin.time.Instant
@@ -35,6 +36,7 @@ object TaskFiltering {
/**
* [saved] is the definition behind a [TaskFilter.Saved]; without one it matches nothing.
* [upcomingEnd] caps Upcoming to dues before it (see [UpcomingRange.end]); `null` = no cap.
* [weekStart] is where a saved filter's weeks begin.
*/
fun matches(
task: Task,
@@ -43,13 +45,14 @@ object TaskFiltering {
todayEnd: Instant,
saved: SavedFilter? = null,
upcomingEnd: Instant? = null,
weekStart: DayOfWeek = localeWeekStart(),
): Boolean =
when (filter) {
is TaskFilter.OfList -> task.listId == filter.listId
is TaskFilter.OfLists -> task.listId in filter.listIds
is TaskFilter.Smart -> matchesSmart(task, filter.list, todayStart, todayEnd, upcomingEnd)
is TaskFilter.Tagged -> filter.tag in task.tags
is TaskFilter.Saved -> saved?.takeIf { it.id == filter.id }?.matches(task, todayStart, todayEnd) ?: false
is TaskFilter.Saved -> saved?.takeIf { it.id == filter.id }?.matches(task, todayStart, todayEnd, weekStart) ?: false
}
/**
@@ -95,9 +95,10 @@ object TaskGroups {
// 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)
val criteria = savedFilter?.criteria
if (criteria?.listIds?.size == 1) add(TaskGrouping.LIST)
// Due windows without Upcoming leave no later days to split.
val due = savedFilter?.due.orEmpty()
val due = criteria?.due.orEmpty()
if (due.isNotEmpty() && DueWindow.UPCOMING !in due) add(TaskGrouping.DAY)
}
is TaskFilter.Tagged -> emptySet()
@@ -25,9 +25,11 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.TagMatch
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
import de.jeanlucmakiola.agendula.ui.common.NameField
import de.jeanlucmakiola.floret.components.CollapsingScaffold
@@ -41,7 +43,8 @@ import de.jeanlucmakiola.floret.components.positionOf
/**
* Creates or edits a [SavedFilter]: a name, then due windows, priority, lists and
* tags. Each multi-choice section leads with an "any" row that is selected while
* nothing in it is, so an untouched section visibly doesn't narrow.
* nothing in it is, so an untouched section visibly doesn't narrow. A filter
* whose rule has no flat form can only be renamed or deleted here.
*/
@Composable
fun FilterEditScreen(
@@ -54,6 +57,7 @@ fun FilterEditScreen(
val draft by viewModel.draft.collectAsStateWithLifecycle()
val lists by viewModel.lists.collectAsStateWithLifecycle()
val tagsInUse by viewModel.tags.collectAsStateWithLifecycle()
val criteria by viewModel.criteria.collectAsStateWithLifecycle()
val filter = draft
var choosingPriority by rememberSaveable { mutableStateOf(false) }
var confirmDelete by rememberSaveable { mutableStateOf(false) }
@@ -77,98 +81,17 @@ fun FilterEditScreen(
name = filter.name,
placeholder = stringResource(R.string.filter_name_hint),
autoFocus = isNew,
onNameChange = { name -> viewModel.update { it.copy(name = name) } },
onNameChange = viewModel::rename,
onImeAction = save,
)
GroupedSectionHeader(stringResource(R.string.filter_section_due))
val windows = DueWindow.entries
ChoiceRow(
title = stringResource(R.string.filter_any_due),
position = positionOf(0, windows.size + 1),
selected = filter.due.isEmpty(),
onClick = { viewModel.update { it.copy(due = emptySet()) } },
)
windows.forEachIndexed { index, window ->
ChoiceRow(
title = dueWindowLabel(window),
position = positionOf(index + 1, windows.size + 1),
selected = window in filter.due,
onClick = { viewModel.update { it.copy(due = it.due.toggle(window)) } },
)
}
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
GroupedRow(
title = minPriorityLabel(filter.minPriority),
position = Position.Alone,
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
onClick = { choosingPriority = true },
)
if (lists.isNotEmpty()) {
GroupedSectionHeader(stringResource(R.string.filter_section_lists))
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
ChoiceRow(
title = stringResource(R.string.filter_any_list),
position = positionOf(0, lists.size + 1),
selected = filter.anyList,
onClick = { viewModel.update { it.copy(listIds = emptySet(), listsElsewhere = false) } },
)
lists.forEachIndexed { index, list ->
ChoiceRow(
title = list.name,
summary = list.accountName.takeIf { showAccount },
position = positionOf(index + 1, lists.size + 1),
selected = list.id in filter.listIds,
leading = { ListColorChip(list.color) },
onClick = { viewModel.update { it.copy(listIds = it.listIds.toggle(list.id)) } },
)
}
}
// A tag no open task carries any more stays listed while the filter uses
// it, so it can still be unticked.
val tags = remember(tagsInUse, filter.tags) {
(tagsInUse + filter.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
}
if (tags.isNotEmpty()) {
GroupedSectionHeader(stringResource(R.string.filter_section_tags))
ChoiceRow(
title = stringResource(R.string.filter_any_tag),
position = positionOf(0, tags.size + 1),
selected = filter.tags.isEmpty(),
onClick = { viewModel.update { it.copy(tags = emptySet()) } },
)
tags.forEachIndexed { index, tag ->
ChoiceRow(
title = tag,
position = positionOf(index + 1, tags.size + 1),
selected = tag in filter.tags,
onClick = { viewModel.update { it.copy(tags = it.tags.toggle(tag)) } },
)
}
if (filter.tags.size > 1) {
Spacer(Modifier.height(8.dp))
GroupedRow(
title = stringResource(R.string.filter_match_all_tags),
summary = stringResource(
if (filter.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
),
position = Position.Alone,
trailing = {
Switch(
checked = filter.tagMatch == TagMatch.ALL,
onCheckedChange = { all ->
viewModel.update { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) }
},
)
},
onClick = {
viewModel.update { it.copy(tagMatch = if (it.tagMatch == TagMatch.ALL) TagMatch.ANY else TagMatch.ALL) }
},
)
}
// A rule the flat sections can't show is kept as it is: only the name changes here.
val flat = criteria
if (flat == null) {
Spacer(Modifier.height(16.dp))
GroupedRow(title = stringResource(R.string.filter_rules_not_editable), position = Position.Alone)
} else {
CriteriaSections(flat, lists, tagsInUse, viewModel, onChoosePriority = { choosingPriority = true })
}
if (filter.id > 0) {
@@ -184,13 +107,14 @@ fun FilterEditScreen(
Spacer(Modifier.height(24.dp))
}
if (choosingPriority && filter != null) {
val flat = criteria
if (choosingPriority && flat != null) {
OptionPicker(
title = stringResource(R.string.filter_section_priority),
options = Priority.entries,
selected = filter.minPriority,
selected = flat.minPriority,
label = { minPriorityLabel(it) },
onSelect = { priority -> viewModel.update { it.copy(minPriority = priority) } },
onSelect = { priority -> viewModel.updateCriteria { it.copy(minPriority = priority) } },
onDismiss = { choosingPriority = false },
)
}
@@ -212,6 +136,106 @@ fun FilterEditScreen(
}
}
/** The flat criteria: due windows, priority, lists and tags. */
@Composable
private fun CriteriaSections(
criteria: FilterCriteria,
lists: List<TaskList>,
tagsInUse: List<String>,
viewModel: FilterEditViewModel,
onChoosePriority: () -> Unit,
) {
GroupedSectionHeader(stringResource(R.string.filter_section_due))
val windows = DueWindow.entries
ChoiceRow(
title = stringResource(R.string.filter_any_due),
position = positionOf(0, windows.size + 1),
selected = criteria.due.isEmpty(),
onClick = { viewModel.updateCriteria { it.copy(due = emptySet()) } },
)
windows.forEachIndexed { index, window ->
ChoiceRow(
title = dueWindowLabel(window),
position = positionOf(index + 1, windows.size + 1),
selected = window in criteria.due,
onClick = { viewModel.updateCriteria { it.copy(due = it.due.toggle(window)) } },
)
}
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
GroupedRow(
title = minPriorityLabel(criteria.minPriority),
position = Position.Alone,
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
onClick = onChoosePriority,
)
if (lists.isNotEmpty()) {
GroupedSectionHeader(stringResource(R.string.filter_section_lists))
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
ChoiceRow(
title = stringResource(R.string.filter_any_list),
position = positionOf(0, lists.size + 1),
selected = criteria.anyList,
onClick = { viewModel.updateCriteria { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) } },
)
lists.forEachIndexed { index, list ->
ChoiceRow(
title = list.name,
summary = list.accountName.takeIf { showAccount },
position = positionOf(index + 1, lists.size + 1),
selected = list.id in criteria.listIds,
leading = { ListColorChip(list.color) },
onClick = { viewModel.updateCriteria { it.copy(listIds = it.listIds.toggle(list.id)) } },
)
}
}
// A tag no open task carries any more stays listed while the filter uses
// it, so it can still be unticked.
val tags = remember(tagsInUse, criteria.tags) {
(tagsInUse + criteria.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
}
if (tags.isNotEmpty()) {
GroupedSectionHeader(stringResource(R.string.filter_section_tags))
ChoiceRow(
title = stringResource(R.string.filter_any_tag),
position = positionOf(0, tags.size + 1),
selected = criteria.tags.isEmpty(),
onClick = { viewModel.updateCriteria { it.copy(tags = emptySet()) } },
)
tags.forEachIndexed { index, tag ->
ChoiceRow(
title = tag,
position = positionOf(index + 1, tags.size + 1),
selected = tag in criteria.tags,
onClick = { viewModel.updateCriteria { it.copy(tags = it.tags.toggle(tag)) } },
)
}
if (criteria.tags.size > 1) {
Spacer(Modifier.height(8.dp))
GroupedRow(
title = stringResource(R.string.filter_match_all_tags),
summary = stringResource(
if (criteria.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
),
position = Position.Alone,
trailing = {
Switch(
checked = criteria.tagMatch == TagMatch.ALL,
onCheckedChange = { all ->
viewModel.updateCriteria { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) }
},
)
},
onClick = {
viewModel.updateCriteria { it.copy(tagMatch = if (it.tagMatch == TagMatch.ALL) TagMatch.ANY else TagMatch.ALL) }
},
)
}
}
}
@Composable
private fun ChoiceRow(
title: String,
@@ -5,6 +5,7 @@ import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.TaskFilter
@@ -35,6 +36,11 @@ class FilterEditViewModel @Inject constructor(
/** `null` until [bind] has loaded the filter. An id of 0 is a new one. */
val draft: StateFlow<SavedFilter?> = _draft.asStateFlow()
private val _criteria = MutableStateFlow<FilterCriteria?>(null)
/** The draft in the flat form the editor shows; `null` while loading, or when its rule has none. */
val criteria: StateFlow<FilterCriteria?> = _criteria.asStateFlow()
val lists: StateFlow<List<TaskList>> = repository.taskLists()
.catch { emit(emptyList()) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
@@ -52,20 +58,31 @@ class FilterEditViewModel @Inject constructor(
if (bound) return
bound = true
if (filterId == null) {
_draft.value = SavedFilter(id = 0, name = "")
load(SavedFilter(id = 0, name = ""))
return
}
viewModelScope.launch {
val saved = settingsPrefs.savedFilter(filterId).first()
// Show it as it matches: lists deleted since drop out, as they do in the repository.
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
_draft.value = saved?.let { if (existing == null) it else it.withListsIn(existing) }
?: SavedFilter(id = 0, name = "")
load(saved?.let { if (existing == null) it else it.withListsIn(existing) } ?: SavedFilter(id = 0, name = ""))
}
}
fun update(transform: (SavedFilter) -> SavedFilter) {
_draft.value = _draft.value?.let(transform)
fun rename(name: String) {
_draft.value = _draft.value?.copy(name = name)
}
/** Changes the draft's flat criteria; a draft without a flat form keeps its rule as it is. */
fun updateCriteria(transform: (FilterCriteria) -> FilterCriteria) {
val next = _criteria.value?.let(transform) ?: return
_criteria.value = next
_draft.value = _draft.value?.copy(rule = next.toRule())
}
private fun load(filter: SavedFilter) {
_criteria.value = filter.criteria
_draft.value = filter
}
fun save(onSaved: (Long) -> Unit) {
@@ -16,6 +16,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskFiltering
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.UpcomingRange
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.agendula.domain.tagsInUse
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -26,6 +27,7 @@ import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.ZoneId
import javax.inject.Inject
import kotlin.time.Clock
@@ -146,10 +148,10 @@ class ListsViewModel @Inject constructor(
// Open smart lists drop completed tasks, but the Today ring needs the
// ones already ticked off to show "x of y done", so read them too.
repository.tasks(TaskFilter.Smart(SmartList.COMPLETED)),
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
settingsPrefs.settings.map { Triple(it.hiddenFromSmartLists, it.upcomingRange, it.weekStart) }.distinctUntilChanged(),
settingsPrefs.savedFilters,
) { lists, openTasks, completedTasks, (hidden, upcomingRange), filters ->
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters) as ListsUiState
) { lists, openTasks, completedTasks, (hidden, upcomingRange, weekStart), filters ->
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart ?: localeWeekStart()) as ListsUiState
}.recoveringFromProviderFailure { ListsUiState.Failure }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
@@ -160,6 +162,7 @@ class ListsViewModel @Inject constructor(
hidden: Set<Long>,
upcomingRange: UpcomingRange,
savedFilters: List<SavedFilter>,
weekStart: DayOfWeek,
): ListsUiState.Content {
val now = Clock.System.now()
val zone = ZoneId.systemDefault()
@@ -214,7 +217,7 @@ class ListsViewModel @Inject constructor(
}
// Same folding as the tags: a subtask counts only when its parent isn't in the filter too.
val filters = savedFilters.map { filter ->
val matching = openTasks.filter { filter.matches(it, todayStart, todayEnd) }
val matching = openTasks.filter { filter.matches(it, todayStart, todayEnd, weekStart) }
val ids = matching.mapTo(HashSet()) { it.taskId }
FilterOverview(filter, matching.count { !it.isSubtask || it.parentId !in ids })
}
@@ -482,7 +482,7 @@ private fun TaskListBody(
// In a mixed view (a smart list) the list colour bar + name disambiguate
// 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)
(filter is TaskFilter.Saved && state.savedFilter?.criteria?.listIds?.size != 1)
// Parents the user expanded to reveal their subtasks inline. Children are
// grouped from the same flat task set the list already holds.
var expandedParents by rememberSaveable { mutableStateOf(emptySet<Long>()) }
+1
View File
@@ -308,6 +308,7 @@
<string name="filter_delete_body">Only the filter goes. Its tasks stay where they are.</string>
<string name="filter_delete_confirm">Delete</string>
<string name="filter_missing">Filter deleted</string>
<string name="filter_rules_not_editable">This filter uses rules that can’t be edited here yet. You can still rename or delete it.</string>
<string name="new_task">New task</string>
<string name="lists_failure">Could not read your tasks.</string>
<string name="lists_empty">No task lists yet.</string>
@@ -7,6 +7,7 @@ import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.SavedFilter
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
@@ -55,22 +56,22 @@ class ForgetDeletedListsTest {
@Test
fun `a saved filter drops a deleted list, so a list given its id later is not in it`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.OWN)
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", listIds = setOf(1L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", criteria = FilterCriteria(listIds = setOf(1L))))
prefs.forgetDeletedLists(listOf(1L), StorageMode.OWN)
val filters = prefs.savedFilters.first().associate { it.name to it.listIds }
val filters = prefs.savedFilters.first().associate { it.name to it.criteria!!.listIds }
assertThat(filters).containsExactly("Both", setOf(2L), "Gone", emptySet<Long>())
}
@Test
fun `a read of the lists drops the gone ones from the saved filters`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.OWN)
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
prefs.forgetListsExcept(StorageMode.OWN, null, setOf(2L, 3L))
assertThat(prefs.savedFilters.first().single().listIds).containsExactly(2L)
assertThat(prefs.savedFilters.first().single().criteria!!.listIds).containsExactly(2L)
}
}
@@ -1,30 +1,67 @@
package de.jeanlucmakiola.agendula.data.prefs
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.domain.DueSpec
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.Rule
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.TagMatch
import org.junit.jupiter.api.Test
class SavedFilterCodecTest {
private val filter = SavedFilter(
id = 3,
name = "Work | today, 100%",
private val criteria = FilterCriteria(
due = setOf(DueWindow.TODAY, DueWindow.OVERDUE),
listIds = setOf(4L, 9L),
tags = setOf("a,b", "größe", "x|y"),
tags = setOf("a,b", "größe", "x|y", "f(x)"),
tagMatch = TagMatch.ALL,
minPriority = Priority.MEDIUM,
)
private val filter = SavedFilter(id = 3, name = "Work | today, 100% (v2|x)", criteria = criteria)
private fun SavedFilter.flat(): FilterCriteria = criteria!!
@Test
fun `a filter round-trips, separators and all`() {
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
assertThat(raw).startsWith("v2|3|")
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
}
@Test
fun `a nested rule round-trips`() {
val rule = Rule.All(
listOf(
Rule.Any(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next action"))),
Rule.Not(Rule.Any(listOf(Rule.HasTag("someday"), Rule.Due(DueSpec.Window(DueWindow.NO_DATE))))),
Rule.Not(Rule.Not(Rule.MinPriority(Priority.LOW))),
Rule.Any(
listOf(
Rule.Due(DueSpec.Today),
Rule.Due(DueSpec.ThisWeek),
Rule.Due(DueSpec.ThisMonth),
Rule.Due(DueSpec.NextDays(0)),
Rule.Due(DueSpec.NextDays(14)),
),
),
Rule.Any(emptyList()),
Rule.All(emptyList()),
),
)
val nested = SavedFilter(id = 5, name = "GTD", rule = rule)
val raw = SavedFilterCodec.upsert(null, nested, "OWN")
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(nested)
assertThat(nested.criteria).isNull()
}
@Test
fun `a filter of everything round-trips`() {
val all = SavedFilter(id = 1, name = "All")
assertThat(SavedFilterCodec.decode(SavedFilterCodec.upsert(null, all, "OWN"), "OWN")).containsExactly(all)
}
@Test
fun `upsert replaces by id and keeps the order`() {
val first = filter.copy(id = 1, name = "one")
@@ -34,31 +71,39 @@ class SavedFilterCodecTest {
assertThat(SavedFilterCodec.decode(raw, "OWN").map { it.name }).containsExactly("renamed", filter.name).inOrder()
}
@Test
fun `upsert replaces a flat line by id`() {
val raw = SavedFilterCodec.upsert(legacyLine(id = 3, refs = listOf("OWN:1")), filter.copy(name = "new"), "OWN")
assertThat(SavedFilterCodec.decode(raw, "OWN").map { it.name }).containsExactly("new")
}
@Test
fun `list ids belong to their store`() {
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single().flat()
assertThat(elsewhere.listIds).isEmpty()
assertThat(elsewhere.listsElsewhere).isTrue()
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listsElsewhere).isFalse()
assertThat(elsewhere.listsElsewhere).containsExactly("OWN:4", "OWN:9")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listsElsewhere).isEmpty()
}
@Test
fun `choosing any list in one store drops the other store's lists`() {
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = emptySet(), listsElsewhere = false), "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().anyList).isTrue()
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) }, "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().anyList).isTrue()
}
@Test
fun `unticking the last list here keeps the other store's lists`() {
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
assertThat(external.listsElsewhere).isTrue()
raw = SavedFilterCodec.upsert(raw, external.copy(listIds = emptySet()), "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().anyList).isFalse()
var external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = setOf(1L)) }, "EXTERNAL")
external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
assertThat(external.flat().listsElsewhere).isNotEmpty()
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = emptySet()) }, "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().flat().anyList).isFalse()
}
@Test
@@ -66,27 +111,84 @@ class SavedFilterCodecTest {
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
raw = SavedFilterCodec.upsert(raw, elsewhere.copy(name = "renamed"), "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
}
@Test
fun `editing in one store keeps the other store's lists`() {
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().listIds).containsExactly(1L)
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = setOf(1L)) }, "EXTERNAL")
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().flat().listIds).containsExactly(1L)
}
@Test
fun `remove drops only that filter`() {
fun `remove drops only that filter, in either format`() {
var raw = SavedFilterCodec.upsert(null, filter.copy(id = 1), "OWN")
raw = SavedFilterCodec.upsert(raw, filter, "OWN")
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 1), "OWN").map { it.id }).containsExactly(3L)
raw = SavedFilterCodec.upsert(raw, filter, "OWN") + "\n" + legacyLine(id = 7)
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 1), "OWN").map { it.id }).containsExactly(3L, 7L)
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 7), "OWN").map { it.id }).containsExactly(1L, 3L)
}
@Test
fun `broken lines are skipped`() {
val raw = "nonsense\n" + SavedFilterCodec.upsert(null, filter, "OWN") + "\n7|short\n8|bad%zz||||ANY|NONE"
val raw = "nonsense\n" + SavedFilterCodec.upsert(null, filter, "OWN") +
"\n7|short\n8|bad%zz||||ANY|NONE\nv2|9|x|and(\nv2|10|x|what(1)\nv2|11|x|and()trailing\nv2|12|x|range(next,-1)"
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
}
@Test
fun `a flat line reads as the same filter`() {
val raw = legacyLine(
id = 3,
name = "Work+%7C+today",
due = "OVERDUE,TODAY",
refs = listOf("OWN:4", "OWN:9", "EXTERNAL:2"),
tags = "a%2Cb,gr%C3%B6%C3%9Fe",
match = "ALL",
priority = "MEDIUM",
)
val own = SavedFilterCodec.decode(raw, "OWN").single()
assertThat(own.name).isEqualTo("Work | today")
assertThat(own.flat()).isEqualTo(
FilterCriteria(
due = setOf(DueWindow.OVERDUE, DueWindow.TODAY),
listIds = setOf(4L, 9L),
listsElsewhere = setOf("EXTERNAL:2"),
tags = setOf("a,b", "größe"),
tagMatch = TagMatch.ALL,
minPriority = Priority.MEDIUM,
),
)
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().flat().listIds).containsExactly(2L)
}
@Test
fun `dropping lists prunes them from rules and flat lines alike`() {
val nested = SavedFilter(
id = 5,
name = "n",
rule = Rule.Any(listOf(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(1L, 2L))))),
)
val raw = SavedFilterCodec.upsert(null, nested, "OWN") + "\n" + legacyLine(id = 6, refs = listOf("OWN:1", "OWN:3"))
val pruned = SavedFilterCodec.decode(SavedFilterCodec.withoutLists(raw, "OWN") { it == 1L }, "OWN")
assertThat(pruned[0].rule).isEqualTo(Rule.Any(listOf(Rule.Not(Rule.InList(setOf(2L))))))
assertThat(pruned[1].flat().listIds).containsExactly(3L)
assertThat(SavedFilterCodec.withoutLists(raw, "OWN") { it == 99L }).isEqualTo(raw)
}
private fun SavedFilter.edit(transform: (FilterCriteria) -> FilterCriteria) =
SavedFilter(id, name, transform(criteria!!))
}
/** A line as 1.4 and earlier wrote it. */
internal fun legacyLine(
id: Long,
name: String = "f",
due: String = "",
refs: List<String> = emptyList(),
tags: String = "",
match: String = "ANY",
priority: String = "NONE",
): String = listOf(id.toString(), name, due, refs.joinToString(","), tags, match, priority).joinToString("|")
@@ -102,7 +102,7 @@ class NewTaskDefaultsTest {
@Test
fun `a saved filter checks only its due windows`() {
val (start, end) = DayWindow.today(now, zone)
val filter = SavedFilter(id = 1L, name = "Soon", due = setOf(DueWindow.TODAY), listIds = setOf(9L))
val filter = SavedFilter(id = 1L, name = "Soon", criteria = FilterCriteria(due = setOf(DueWindow.TODAY), listIds = setOf(9L)))
val dates = newTaskDates(DefaultDueDate.TODAY, DefaultStartDate.NONE, localToday, localToday, now)
assertThat(dates.showsIn(null, filter, start, end)).isTrue()
val later = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, localToday, localToday, now)
@@ -64,6 +64,15 @@ class RuleTest {
assertThat(Rule.InList(emptySet(), setOf("EXTERNAL:1")).matches(testTask(listId = 1), day)).isFalse()
}
@Test
fun `a rule doesn't look at status, a saved filter keeps to open tasks`() {
val day = LocalDate.of(2026, 11, 26)
val done = testTask(status = TaskStatus.COMPLETED)
assertThat(Rule.Everything.matches(done, day)).isTrue()
assertThat(SavedFilter(1, "f").matches(done, clockOn(day))).isFalse()
assertThat(SavedFilter(1, "f", Rule.Not(Rule.Everything)).matches(testTask(), clockOn(day))).isFalse()
}
@Test
fun `due windows read as before`() {
val day = LocalDate.of(2026, 11, 26)
@@ -163,4 +172,55 @@ class RuleTest {
assertThat(Rule.Everything.withoutLists(gone)).isEqualTo(Rule.Everything)
assertThat(rule.withoutLists { false }).isEqualTo(rule)
}
@Test
fun `flat criteria round-trip through a rule`() {
val all = FilterCriteria(
due = setOf(DueWindow.TODAY, DueWindow.NO_DATE),
listIds = setOf(1L),
listsElsewhere = setOf("EXTERNAL:2"),
tags = setOf("x"),
tagMatch = TagMatch.ALL,
minPriority = Priority.LOW,
)
val samples = listOf(
FilterCriteria(),
all,
all.copy(tagMatch = TagMatch.ANY),
all.copy(tags = setOf("a", "b")),
all.copy(listIds = emptySet()),
all.copy(listsElsewhere = emptySet(), due = setOf(DueWindow.OVERDUE)),
)
for (criteria in samples) assertThat(FilterCriteria.of(criteria.toRule())).isEqualTo(criteria)
}
@Test
fun `a single criterion reads as flat too`() {
assertThat(FilterCriteria.of(Rule.InList(setOf(1L)))).isEqualTo(FilterCriteria(listIds = setOf(1L)))
assertThat(FilterCriteria.of(Rule.Due(DueSpec.Window(DueWindow.TODAY)))).isEqualTo(FilterCriteria(due = setOf(DueWindow.TODAY)))
assertThat(FilterCriteria.of(Rule.Any(listOf(Rule.HasTag("a"), Rule.HasTag("b")))))
.isEqualTo(FilterCriteria(tags = setOf("a", "b")))
}
@Test
fun `rules beyond the flat form have none`() {
val notFlat = listOf(
Rule.Not(Rule.HasTag("a")),
Rule.Due(DueSpec.ThisWeek),
Rule.Any(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)))),
Rule.All(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(2L)))),
Rule.All(listOf(Rule.Any(listOf(Rule.HasTag("a"))), Rule.All(listOf(Rule.HasTag("b"))))),
Rule.All(listOf(Rule.Any(emptyList()))),
Rule.InList(emptySet()),
Rule.All(listOf(Rule.All(listOf(Rule.Due(DueSpec.Window(DueWindow.TODAY)))))),
)
for (rule in notFlat) assertThat(FilterCriteria.of(rule)).isNull()
}
@Test
fun `a filter without a flat form presets nothing`() {
val filter = SavedFilter(1, "f", Rule.Not(Rule.InList(setOf(1L))))
assertThat(filter.newTaskPreset(LocalDate.of(2026, 11, 26))).isEqualTo(NewTaskPreset())
assertThat(filter.withListsIn(setOf(2L)).rule).isEqualTo(Rule.Everything)
}
}
@@ -19,6 +19,15 @@ class SavedFilterTest {
private val empty = SavedFilter(id = 1, name = "f")
private fun filterOf(
due: Set<DueWindow> = emptySet(),
listIds: Set<Long> = emptySet(),
listsElsewhere: Set<String> = emptySet(),
tags: Set<String> = emptySet(),
tagMatch: TagMatch = TagMatch.ANY,
minPriority: Priority = Priority.NONE,
) = SavedFilter(1, "f", FilterCriteria(due, listIds, listsElsewhere, tags, tagMatch, minPriority))
@Test
fun `an empty filter is every open task`() {
assertThat(empty.matches(testTask(due = null))).isTrue()
@@ -29,7 +38,7 @@ class SavedFilterTest {
@Test
fun `today and overdue together`() {
val filter = empty.copy(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE))
val filter = filterOf(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE))
assertThat(filter.matches(testTask(due = overdue))).isTrue()
assertThat(filter.matches(testTask(due = today))).isTrue()
assertThat(filter.matches(testTask(due = upcoming))).isFalse()
@@ -38,21 +47,21 @@ class SavedFilterTest {
@Test
fun `lists narrow by membership`() {
val filter = empty.copy(listIds = setOf(2L, 3L))
val filter = filterOf(listIds = setOf(2L, 3L))
assertThat(filter.matches(testTask(listId = 2))).isTrue()
assertThat(filter.matches(testTask(listId = 1))).isFalse()
}
@Test
fun `lists from another store match nothing here`() {
val filter = empty.copy(listsElsewhere = true)
val filter = filterOf(listsElsewhere = setOf("EXTERNAL:1"))
assertThat(filter.matches(testTask(listId = 1))).isFalse()
assertThat(filter.copy(listIds = setOf(1L)).matches(testTask(listId = 1))).isTrue()
assertThat(filterOf(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:1")).matches(testTask(listId = 1))).isTrue()
}
@Test
fun `priority is a floor`() {
val filter = empty.copy(minPriority = Priority.MEDIUM)
val filter = filterOf(minPriority = Priority.MEDIUM)
assertThat(filter.matches(testTask(priority = Priority.HIGH))).isTrue()
assertThat(filter.matches(testTask(priority = Priority.MEDIUM))).isTrue()
assertThat(filter.matches(testTask(priority = Priority.LOW))).isFalse()
@@ -61,8 +70,8 @@ class SavedFilterTest {
@Test
fun `tags match any or all`() {
val any = empty.copy(tags = setOf("work", "home"))
val all = any.copy(tagMatch = TagMatch.ALL)
val any = filterOf(tags = setOf("work", "home"))
val all = filterOf(tags = setOf("work", "home"), tagMatch = TagMatch.ALL)
val one = testTask(tags = listOf("work"))
val both = testTask(tags = listOf("home", "work", "x"))
assertThat(any.matches(one)).isTrue()
@@ -73,7 +82,7 @@ class SavedFilterTest {
@Test
fun `criteria combine with and`() {
val filter = empty.copy(due = setOf(DueWindow.TODAY), listIds = setOf(1L), tags = setOf("work"))
val filter = filterOf(due = setOf(DueWindow.TODAY), listIds = setOf(1L), tags = setOf("work"))
assertThat(filter.matches(testTask(listId = 1, due = today, tags = listOf("work")))).isTrue()
assertThat(filter.matches(testTask(listId = 2, due = today, tags = listOf("work")))).isFalse()
assertThat(filter.matches(testTask(listId = 1, due = today))).isFalse()
@@ -94,7 +103,7 @@ class SavedFilterTest {
@Test
fun `a new task preset lands in its filter`() {
val day = LocalDate.of(2026, 10, 10)
val filter = empty.copy(
val filter = filterOf(
due = setOf(DueWindow.UPCOMING),
tags = setOf("work", "home"),
tagMatch = TagMatch.ALL,
@@ -104,16 +113,17 @@ class SavedFilterTest {
assertThat(preset.dueDate).isEqualTo(day.plusDays(1))
assertThat(preset.tags).containsExactly("home", "work")
assertThat(preset.priority).isEqualTo(Priority.HIGH)
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.UPCOMING)).newTaskPreset(day).dueDate).isEqualTo(day)
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.NO_DATE)).newTaskPreset(day).dueDate).isNull()
assertThat(empty.copy(tags = setOf("b", "a")).newTaskPreset(day).tags).containsExactly("a")
assertThat(filterOf(due = setOf(DueWindow.TODAY, DueWindow.UPCOMING)).newTaskPreset(day).dueDate).isEqualTo(day)
assertThat(filterOf(due = setOf(DueWindow.TODAY, DueWindow.NO_DATE)).newTaskPreset(day).dueDate).isNull()
assertThat(filterOf(tags = setOf("b", "a")).newTaskPreset(day).tags).containsExactly("a")
}
@Test
fun `lists since deleted drop out`() {
val filter = empty.copy(listIds = setOf(1L, 5L))
assertThat(filter.withListsIn(setOf(1L, 2L)).listIds).containsExactly(1L)
assertThat(filter.withListsIn(setOf(2L)).anyList).isTrue()
assertThat(filter.copy(listsElsewhere = true).withListsIn(setOf(2L)).anyList).isFalse()
val filter = filterOf(listIds = setOf(1L, 5L))
assertThat(filter.withListsIn(setOf(1L, 2L)).criteria!!.listIds).containsExactly(1L)
assertThat(filter.withListsIn(setOf(2L)).criteria!!.anyList).isTrue()
val elsewhere = filterOf(listIds = setOf(1L, 5L), listsElsewhere = setOf("EXTERNAL:1"))
assertThat(elsewhere.withListsIn(setOf(2L)).criteria!!.anyList).isFalse()
}
}
@@ -118,9 +118,9 @@ class TaskGroupsTest {
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))
val oneList = SavedFilter(id = 1, name = "f", criteria = FilterCriteria(listIds = setOf(3L)))
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(1), oneList)).doesNotContain(TaskGrouping.LIST)
val overdueOnly = SavedFilter(id = 2, name = "g", due = setOf(DueWindow.OVERDUE))
val overdueOnly = SavedFilter(id = 2, name = "g", criteria = FilterCriteria(due = setOf(DueWindow.OVERDUE)))
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(2), overdueOnly)).doesNotContain(TaskGrouping.DAY)
assertThat(TaskGroups.offeredFor(TaskFilter.OfLists(setOf(1, 2)))).isEmpty()
}