Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5390cb8882 | ||
|
|
1ad7ed6fe3 | ||
|
|
f745698b5b | ||
|
|
f9926a80b3 | ||
|
|
bfbe7398d4 | ||
|
|
9dd8660571 | ||
|
|
ceaff3183c | ||
|
|
697e2e8554 |
No files matched your search
@@ -4,6 +4,7 @@ import android.app.Application
|
||||
import androidx.hilt.work.HiltWorkerFactory
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import androidx.work.Configuration
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import dagger.hilt.EntryPoint
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
@@ -97,9 +98,11 @@ class AgendulaApp : Application(), Configuration.Provider {
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
refreshNotificationChannels()
|
||||
// Language or dark mode changed: the widget's strings and list colours follow.
|
||||
// Language or dark mode changed: week starts, the widget's strings and list colours follow.
|
||||
runCatching {
|
||||
EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java).taskWidgetUpdater().requestRefresh()
|
||||
val entryPoint = EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java)
|
||||
entryPoint.settingsPrefs().onLocaleChanged()
|
||||
entryPoint.taskWidgetUpdater().requestRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,5 +131,6 @@ class AgendulaApp : Application(), Configuration.Provider {
|
||||
fun reminderRefresher(): ReminderRefresher
|
||||
fun providerSnapshotSource(): ProviderSnapshotSource
|
||||
fun autoBackupScheduler(): AutoBackupScheduler
|
||||
fun settingsPrefs(): SettingsPrefs
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.agendula.ui.common.localeFirstDayOfWeek
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
@@ -104,7 +103,7 @@ class MainActivity : ComponentActivity() {
|
||||
val darkTheme = ui.settings.themeMode.isDark(isSystemInDarkTheme())
|
||||
val context = LocalContext.current
|
||||
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
|
||||
val firstDayOfWeek = ui.settings.weekStart ?: localeFirstDayOfWeek()
|
||||
val firstDayOfWeek = ui.settings.effectiveWeekStart
|
||||
AgendulaTheme(
|
||||
darkTheme = darkTheme,
|
||||
dynamicColor = ui.settings.dynamicColor,
|
||||
|
||||
@@ -12,6 +12,7 @@ import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SavedFilterMigration
|
||||
import de.jeanlucmakiola.agendula.data.tasks.AndroidProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ModeRoutingTasksDataSource
|
||||
@@ -48,6 +49,7 @@ internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreference
|
||||
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "agendula_prefs",
|
||||
corruptionHandler = replaceCorrupted(),
|
||||
produceMigrations = { listOf(SavedFilterMigration) },
|
||||
)
|
||||
|
||||
@Module
|
||||
|
||||
@@ -1,92 +1,206 @@
|
||||
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.flatten
|
||||
import de.jeanlucmakiola.agendula.domain.mapLists
|
||||
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(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`. They are still read, and [migrate]
|
||||
* rewrites them once.
|
||||
*
|
||||
* 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() }
|
||||
|
||||
/** [raw] with [filter] replacing the line of the same id, or appended. */
|
||||
/**
|
||||
* [raw] with [filter] replacing the line of the same id, or appended. Other
|
||||
* stores' lists the stored line no longer has, e.g. pruned while the filter
|
||||
* was being edited, stay gone.
|
||||
*/
|
||||
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 stored = existing.getOrNull(index)?.let { runCatching { decodeLine(it, mode) }.getOrNull() }
|
||||
val kept = stored?.rule?.elsewhereRefs()?.let { refs ->
|
||||
filter.copy(rule = filter.rule.mapLists { it.copy(elsewhere = it.elsewhere intersect refs) }.withoutLists { false })
|
||||
}
|
||||
val line = encodeLine(filter, mode, foreign)
|
||||
val line = encodeLine(kept ?: 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 (see [Rule.withoutLists]).
|
||||
*/
|
||||
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("|")
|
||||
// Most filters hold none of this store's lists; only those need reading.
|
||||
if ("$mode:" !in line && encode("$mode:") !in line) return@joinToString line
|
||||
val filter = runCatching { decodeLine(line, mode) }.getOrNull() ?: return@joinToString line
|
||||
val pruned = filter.copy(rule = filter.rule.withoutLists(gone))
|
||||
if (pruned == filter) line else encodeLine(pruned, mode)
|
||||
}
|
||||
|
||||
fun remove(raw: String?, id: Long): String = lines(raw).filterNot { idOf(it) == id }.joinToString("\n")
|
||||
|
||||
/** Whether [raw] still holds lines of the flat format. */
|
||||
fun needsMigration(raw: String?): Boolean = lines(raw).any { !isV2(it) }
|
||||
|
||||
/**
|
||||
* [raw] with every flat line rewritten as a rule, lists of every store kept
|
||||
* as they are. Lines that never read as a filter are dropped.
|
||||
*/
|
||||
fun migrate(raw: String?): String = lines(raw).mapNotNull { line ->
|
||||
if (isV2(line)) return@mapNotNull line
|
||||
// No store owns NO_STORE, so every list stays a qualified ref and comes back out unchanged.
|
||||
runCatching { decodeFlatLine(line, NO_STORE) }.getOrNull()?.let { encodeLine(it, NO_STORE) }
|
||||
}.joinToString("\n")
|
||||
|
||||
private const val NO_STORE = "\u0000"
|
||||
|
||||
private fun lines(raw: String?): List<String> = raw.orEmpty().split('\n').filter { it.isNotBlank() }
|
||||
|
||||
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 Rule.elsewhereRefs(): Set<String> =
|
||||
flatten().filterIsInstance<Rule.InList>().flatMapTo(HashSet()) { it.elsewhere }
|
||||
|
||||
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 top-level 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 }
|
||||
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.AllOf -> "and(${rule.children.joinToString(",") { encodeRule(it, mode) }})"
|
||||
is Rule.AnyOf -> "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.spec) {
|
||||
is DueSpec.Window -> "due(${spec.window.name})"
|
||||
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.AllOf(list(::rule))
|
||||
"or" -> Rule.AnyOf(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("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())
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataMigration
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
|
||||
/** Rewrites the saved filters of 1.4 and earlier as rules, in place and once (see [SavedFilterCodec.migrate]). */
|
||||
internal object SavedFilterMigration : DataMigration<Preferences> {
|
||||
|
||||
val KEY = stringPreferencesKey("saved_filters")
|
||||
|
||||
override suspend fun shouldMigrate(currentData: Preferences): Boolean =
|
||||
SavedFilterCodec.needsMigration(currentData[KEY])
|
||||
|
||||
override suspend fun migrate(currentData: Preferences): Preferences =
|
||||
currentData.toMutablePreferences().apply { this[KEY] = SavedFilterCodec.migrate(this[KEY]) }
|
||||
|
||||
override suspend fun cleanUp() = Unit
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import de.jeanlucmakiola.agendula.domain.DefaultDueDate
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.NewTaskDates
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import de.jeanlucmakiola.agendula.domain.newTaskDates
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
@@ -39,11 +40,14 @@ import de.jeanlucmakiola.floret.reminders.applyReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.normalizeReminders
|
||||
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import java.time.DayOfWeek
|
||||
import java.time.ZoneId
|
||||
import java.time.LocalDate
|
||||
import java.util.Locale
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -160,6 +164,9 @@ data class Settings(
|
||||
/** How far ahead the Upcoming smart list reaches. */
|
||||
val upcomingRange: UpcomingRange = UpcomingRange.ALL,
|
||||
) {
|
||||
/** The first day of the week, the locale's when none is set. */
|
||||
val effectiveWeekStart: DayOfWeek get() = weekStart ?: localeWeekStart()
|
||||
|
||||
/** Whether a save rings the reminders it puts in the past (#106). */
|
||||
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
|
||||
|
||||
@@ -310,7 +317,7 @@ class SettingsPrefs @Inject constructor(
|
||||
?: TimeFormatPref.AUTO,
|
||||
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
|
||||
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
|
||||
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
|
||||
weekStart = storedWeekStart(p),
|
||||
pushEnabled = p[PUSH_ENABLED] ?: true,
|
||||
hiddenFromSmartLists = scope.let { mode ->
|
||||
p[SMART_LIST_HIDDEN].orEmpty()
|
||||
@@ -330,6 +337,20 @@ class SettingsPrefs @Inject constructor(
|
||||
)
|
||||
}.distinctUntilChanged() // Other stores write this DataStore too.
|
||||
|
||||
private val locale = MutableStateFlow(Locale.getDefault())
|
||||
|
||||
private fun storedWeekStart(p: Preferences): DayOfWeek? = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() }
|
||||
|
||||
/** Call when the device language changes: a week start left on automatic follows it. */
|
||||
fun onLocaleChanged() {
|
||||
locale.value = Locale.getDefault()
|
||||
}
|
||||
|
||||
/** The first day of the week: the setting, or the current locale's when none is set. */
|
||||
val firstDayOfWeek: Flow<DayOfWeek> =
|
||||
combine(dataStore.data.map { storedWeekStart(it) }.distinctUntilChanged(), locale) { set, locale -> set ?: localeWeekStart(locale) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
/** 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, claimedScope(p))
|
||||
@@ -638,7 +659,7 @@ class SettingsPrefs @Inject constructor(
|
||||
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_FILTERS = SavedFilterMigration.KEY
|
||||
val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ 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.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.readsWeekStart
|
||||
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -37,6 +39,7 @@ import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
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
|
||||
@@ -85,11 +88,15 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
// A deleted filter shows nothing rather than failing the screen or widget on it.
|
||||
is TaskFilter.Saved -> settingsPrefs.savedFilter(filter.id)
|
||||
.flatMapLatest { saved ->
|
||||
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)
|
||||
if (saved == null) return@flatMapLatest flowOf(FilteredTasks(emptyList()))
|
||||
// Only a rule with weeks in it reloads when the week start moves; others never read it.
|
||||
val weekStarts = if (saved.rule.readsWeekStart) settingsPrefs.firstDayOfWeek else flowOf(DayOfWeek.MONDAY)
|
||||
weekStarts.flatMapLatest { weekStart ->
|
||||
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, weekStart), current)
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> observing { FilteredTasks(loadTasks(filter)) }
|
||||
@@ -113,7 +120,8 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null): List<Task> {
|
||||
/** [weekStart] is where [saved]'s weeks begin. */
|
||||
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null, weekStart: DayOfWeek = DayOfWeek.MONDAY): 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
|
||||
@@ -127,7 +135,9 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
is TaskFilter.Tagged -> TaskQuery(includeCompleted = true)
|
||||
is TaskFilter.Saved -> TaskQuery(includeCompleted = true)
|
||||
}
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), zone)
|
||||
val clock = saved?.let { RuleClock(todayStart, todayEnd, zone, weekStart) }
|
||||
val all = SeriesCollapse.visible(dataSource.tasks(query))
|
||||
// (done, total) of direct children per parent, over the unfiltered set.
|
||||
val progress: Map<Long, Pair<Int, Int>> = all
|
||||
@@ -137,7 +147,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, ruleClock = clock) }
|
||||
.map { task ->
|
||||
progress[task.taskId]?.let { (done, total) ->
|
||||
task.copy(subtaskDone = done, subtaskTotal = total)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
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.AllOf] of the criteria that narrow. */
|
||||
fun toRule(): Rule = Rule.AllOf(
|
||||
buildList {
|
||||
if (due.isNotEmpty()) add(Rule.AnyOf(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.AllOf(each) else Rule.AnyOf(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.AllOf) rule.children else listOf(rule)
|
||||
var criteria = FilterCriteria()
|
||||
val seen = mutableSetOf<Kind>()
|
||||
fun claim(kind: Kind): Boolean = seen.add(kind)
|
||||
for (part in parts) {
|
||||
criteria = when {
|
||||
part is Rule.Due && part.spec is DueSpec.Window -> {
|
||||
if (!claim(Kind.DUE)) return null
|
||||
criteria.copy(due = setOf(part.spec.window))
|
||||
}
|
||||
part is Rule.InList -> {
|
||||
if (!claim(Kind.LISTS) || part.listIds.isEmpty() && part.elsewhere.isEmpty()) return null
|
||||
criteria.copy(listIds = part.listIds, listsElsewhere = part.elsewhere)
|
||||
}
|
||||
part is Rule.MinPriority -> {
|
||||
if (!claim(Kind.PRIORITY)) return null
|
||||
criteria.copy(minPriority = part.priority)
|
||||
}
|
||||
// Tags straight under the top read as all of them.
|
||||
part is Rule.HasTag -> {
|
||||
if (Kind.TAG_GROUP in seen) return null
|
||||
seen += Kind.TAGS
|
||||
criteria.copy(tags = criteria.tags + part.tag, tagMatch = TagMatch.ALL)
|
||||
}
|
||||
else -> {
|
||||
val group = groupOf(part) ?: return null
|
||||
val windows = group.mapNotNull { ((it as? Rule.Due)?.spec as? DueSpec.Window)?.window }
|
||||
val tags = group.mapNotNull { (it as? Rule.HasTag)?.tag }
|
||||
when {
|
||||
part is Rule.AnyOf && windows.size == group.size -> {
|
||||
if (!claim(Kind.DUE)) return null
|
||||
criteria.copy(due = windows.toSet())
|
||||
}
|
||||
tags.size == group.size -> {
|
||||
if (!claim(Kind.TAGS) || !claim(Kind.TAG_GROUP)) return null
|
||||
criteria.copy(tags = tags.toSet(), tagMatch = if (part is Rule.AllOf) TagMatch.ALL else TagMatch.ANY)
|
||||
}
|
||||
else -> return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return criteria
|
||||
}
|
||||
|
||||
private enum class Kind { DUE, LISTS, PRIORITY, TAGS, TAG_GROUP }
|
||||
|
||||
/** The children of a non-empty [Rule.AllOf] or [Rule.AnyOf]; `null` for anything else. */
|
||||
private fun groupOf(rule: Rule): List<Rule>? = when (rule) {
|
||||
is Rule.AllOf -> rule.children
|
||||
is Rule.AnyOf -> rule.children
|
||||
else -> null
|
||||
}?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
@@ -70,8 +70,8 @@ fun newTaskDates(
|
||||
|
||||
/**
|
||||
* Whether an open task with these dates shows in [smartList], Upcoming reaching
|
||||
* up to [upcomingEnd], or passes [savedFilter]'s due windows; with neither it
|
||||
* shows anywhere.
|
||||
* up to [upcomingEnd], or passes [savedFilter]'s due conditions read with
|
||||
* [ruleClock]; with neither it shows anywhere, as does a saved filter without a clock.
|
||||
*/
|
||||
fun NewTaskDates.showsIn(
|
||||
smartList: SmartList?,
|
||||
@@ -79,10 +79,11 @@ fun NewTaskDates.showsIn(
|
||||
todayStart: Instant,
|
||||
todayEnd: Instant,
|
||||
upcomingEnd: Instant? = null,
|
||||
ruleClock: RuleClock? = null,
|
||||
): Boolean {
|
||||
val probe = openTaskDated(start, due, isAllDay)
|
||||
return when {
|
||||
savedFilter != null -> savedFilter.due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in savedFilter.due
|
||||
savedFilter != null -> ruleClock == null || savedFilter.admitsDueOf(probe, ruleClock)
|
||||
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd, upcomingEnd = upcomingEnd)
|
||||
else -> true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.temporal.TemporalAdjusters
|
||||
import java.time.temporal.WeekFields
|
||||
import java.util.Locale
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A condition on a task, nestable with [AllOf], [AnyOf] and [Not]. An empty [AllOf]
|
||||
* passes every task, an empty [AnyOf] none. Whether a task is open or done is not
|
||||
* a rule: the view a rule is used in decides that.
|
||||
*/
|
||||
sealed interface Rule {
|
||||
data class AllOf(val children: List<Rule>) : Rule
|
||||
data class AnyOf(val children: List<Rule>) : Rule
|
||||
data class Not(val child: Rule) : Rule
|
||||
|
||||
/**
|
||||
* In one of [listIds], this store's lists. [elsewhere] holds the lists of
|
||||
* other task stores as stored, so saving here keeps them; they never match
|
||||
* a task here, so with no [listIds] this matches nothing.
|
||||
*/
|
||||
data class InList(val listIds: Set<Long>, val elsewhere: Set<String> = emptySet()) : Rule
|
||||
|
||||
/** Carries [tag], compared exactly. */
|
||||
data class HasTag(val tag: String) : Rule
|
||||
|
||||
/** At [priority] or higher. */
|
||||
data class MinPriority(val priority: Priority) : Rule
|
||||
|
||||
data class Due(val spec: DueSpec) : Rule
|
||||
|
||||
companion object {
|
||||
/** The rule every task passes. */
|
||||
val Everything: Rule = AllOf(emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When a task is due: one of the [DueWindow]s, or a range of days around today.
|
||||
* Due today is [DueWindow.TODAY]; there is no range for it.
|
||||
*/
|
||||
sealed interface DueSpec {
|
||||
data class Window(val window: DueWindow) : DueSpec
|
||||
|
||||
/** Due on a day in a range relative to today; an undated task is in none. */
|
||||
sealed interface Range : DueSpec {
|
||||
/** The first day of the range and the day after its last, when today is [today]. */
|
||||
fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate>
|
||||
}
|
||||
|
||||
/** The calendar week holding today, starting on [weekStart]. */
|
||||
data object ThisWeek : Range {
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate> {
|
||||
val first = today.with(TemporalAdjusters.previousOrSame(weekStart))
|
||||
return first to first.plusWeeks(1)
|
||||
}
|
||||
}
|
||||
|
||||
/** The calendar month holding today. */
|
||||
data object ThisMonth : Range {
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate> {
|
||||
val first = today.withDayOfMonth(1)
|
||||
return first to first.plusMonths(1)
|
||||
}
|
||||
}
|
||||
|
||||
/** Today and the [days] after it, the way [UpcomingRange] reaches ahead. */
|
||||
data class NextDays(val days: Int) : Range {
|
||||
init {
|
||||
require(days >= 0) { "days must not be negative: $days" }
|
||||
}
|
||||
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek) = today to today.plusDays(days + 1L)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The day rules are read against: local today from [todayStart] to [todayEnd]
|
||||
* (see [DayWindow]) in [zone], with weeks starting on [weekStart].
|
||||
*/
|
||||
data class RuleClock(
|
||||
val todayStart: Instant,
|
||||
val todayEnd: Instant,
|
||||
val zone: ZoneId,
|
||||
val weekStart: DayOfWeek,
|
||||
) {
|
||||
val today: LocalDate by lazy(LazyThreadSafetyMode.PUBLICATION) { todayStart.calendarDate(allDay = false, zone = zone) }
|
||||
}
|
||||
|
||||
/** The first day of the week in [locale]; what an unset week start means. */
|
||||
fun localeWeekStart(locale: Locale = Locale.getDefault()): DayOfWeek = WeekFields.of(locale).firstDayOfWeek
|
||||
|
||||
/** Whether [task] passes this rule, whatever its status. */
|
||||
fun Rule.matches(task: Task, clock: RuleClock): Boolean = when (this) {
|
||||
is Rule.AllOf -> children.all { it.matches(task, clock) }
|
||||
is Rule.AnyOf -> children.any { it.matches(task, clock) }
|
||||
is Rule.Not -> !child.matches(task, clock)
|
||||
is Rule.InList -> task.listId in listIds
|
||||
is Rule.HasTag -> tag in task.tags
|
||||
is Rule.MinPriority -> task.priority >= priority
|
||||
is Rule.Due -> spec.matches(task, clock)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [task]'s due date alone settles this rule: `true` or `false` when it
|
||||
* does, `null` when the rule's other conditions decide.
|
||||
*/
|
||||
fun Rule.dueVerdict(task: Task, clock: RuleClock): Boolean? = when (this) {
|
||||
is Rule.Due -> spec.matches(task, clock)
|
||||
is Rule.Not -> child.dueVerdict(task, clock)?.not()
|
||||
is Rule.AllOf -> children.map { it.dueVerdict(task, clock) }.let { v ->
|
||||
if (false in v) false else if (null in v) null else true
|
||||
}
|
||||
is Rule.AnyOf -> children.map { it.dueVerdict(task, clock) }.let { v ->
|
||||
if (true in v) true else if (null in v) null else false
|
||||
}
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority -> null
|
||||
}
|
||||
|
||||
/** Whether [task]'s due falls in this spec. */
|
||||
fun DueSpec.matches(task: Task, clock: RuleClock): Boolean = when (this) {
|
||||
is DueSpec.Window -> dueWindowOf(task, clock.todayStart, clock.todayEnd, clock.zone) == window
|
||||
is DueSpec.Range -> {
|
||||
val (first, afterLast) = days(clock.today, clock.weekStart)
|
||||
val due = task.wallClock(TaskEnd.DUE, clock.zone)
|
||||
due != null && due >= startOfDay(first, clock.zone) && due < startOfDay(afterLast, clock.zone)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This rule without the lists [gone] names, e.g. lists since deleted. A list
|
||||
* condition left without lists matches nothing, as it did with them gone, so a
|
||||
* nested rule reads the same. Only at the top, where a flat filter keeps its
|
||||
* criteria, does it drop out instead, so the filter goes back to any list.
|
||||
*/
|
||||
fun Rule.withoutLists(gone: (Long) -> Boolean): Rule {
|
||||
val pruned = withoutListIds(gone)
|
||||
return when {
|
||||
pruned.isEmptyList() -> Rule.Everything
|
||||
pruned is Rule.AllOf -> pruned.children.filterNot { it.isEmptyList() }
|
||||
.let { if (it.size == pruned.children.size) pruned else Rule.AllOf(it) }
|
||||
else -> pruned
|
||||
}
|
||||
}
|
||||
|
||||
private fun Rule.isEmptyList(): Boolean = this is Rule.InList && listIds.isEmpty() && elsewhere.isEmpty()
|
||||
|
||||
private fun Rule.withoutListIds(gone: (Long) -> Boolean): Rule = mapLists { list ->
|
||||
list.listIds.filterNotTo(HashSet(), gone).let { if (it.size == list.listIds.size) list else list.copy(listIds = it) }
|
||||
}
|
||||
|
||||
/** This rule with each list condition replaced by [transform]; the same instance when nothing changed. */
|
||||
fun Rule.mapLists(transform: (Rule.InList) -> Rule.InList): Rule = when (this) {
|
||||
is Rule.InList -> transform(this)
|
||||
is Rule.AllOf -> children.map { it.mapLists(transform) }.let { if (it == children) this else Rule.AllOf(it) }
|
||||
is Rule.AnyOf -> children.map { it.mapLists(transform) }.let { if (it == children) this else Rule.AnyOf(it) }
|
||||
is Rule.Not -> child.mapLists(transform).let { if (it == child) this else Rule.Not(it) }
|
||||
is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this
|
||||
}
|
||||
|
||||
/** Every condition in this rule, itself included. */
|
||||
fun Rule.flatten(): Sequence<Rule> = sequence {
|
||||
yield(this@flatten)
|
||||
when (this@flatten) {
|
||||
is Rule.AllOf -> children.forEach { yieldAll(it.flatten()) }
|
||||
is Rule.AnyOf -> children.forEach { yieldAll(it.flatten()) }
|
||||
is Rule.Not -> yieldAll(child.flatten())
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this rule depends on where the week starts. */
|
||||
val Rule.readsWeekStart: Boolean get() = flatten().any { it is Rule.Due && it.spec is DueSpec.ThisWeek }
|
||||
@@ -10,42 +10,28 @@ 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())
|
||||
|
||||
/** 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)
|
||||
/** [rule] in the flat form the filter editor shows; `null` when it has none. */
|
||||
val criteria: FilterCriteria? by lazy(LazyThreadSafetyMode.PUBLICATION) { FilterCriteria.of(rule) }
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
/**
|
||||
* This filter without the list ids missing from [existing], e.g. lists since
|
||||
* deleted. A read finding no list at all proves nothing, so it keeps them.
|
||||
*/
|
||||
fun withListsIn(existing: Set<Long>): SavedFilter =
|
||||
if (existing.isEmpty()) this else copy(rule = rule.withoutLists { it !in existing })
|
||||
|
||||
fun matches(task: Task, clock: RuleClock): Boolean = !task.isClosed && rule.matches(task, clock)
|
||||
|
||||
/** Whether an open task dated like [probe] can pass this filter, going by its due conditions only. */
|
||||
fun admitsDueOf(probe: Task, clock: RuleClock): Boolean = rule.dueVerdict(probe, clock) != false
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,8 +78,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 +89,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,
|
||||
)
|
||||
}
|
||||
@@ -35,6 +35,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.
|
||||
* [ruleClock] reads [saved]'s rule; a saved filter without either matches nothing.
|
||||
*/
|
||||
fun matches(
|
||||
task: Task,
|
||||
@@ -43,13 +44,15 @@ object TaskFiltering {
|
||||
todayEnd: Instant,
|
||||
saved: SavedFilter? = null,
|
||||
upcomingEnd: Instant? = null,
|
||||
ruleClock: RuleClock? = null,
|
||||
): 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 -> ruleClock != null &&
|
||||
saved?.takeIf { it.id == filter.id }?.matches(task, ruleClock) == true
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -22,10 +22,14 @@ enum class UpcomingRange {
|
||||
fun end(now: Instant, zone: ZoneId = ZoneId.systemDefault()): Instant? {
|
||||
val today = now.calendarDate(allDay = false, zone = zone)
|
||||
val last = lastDay(today) ?: return null
|
||||
return Instant.fromEpochMilliseconds(last.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
return startOfDay(last.plusDays(1), zone)
|
||||
}
|
||||
}
|
||||
|
||||
/** Local midnight starting [date] in [zone]. */
|
||||
fun startOfDay(date: LocalDate, zone: ZoneId = ZoneId.systemDefault()): Instant =
|
||||
Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
|
||||
/** Whether [task] is due before [end]; an undated task never is. */
|
||||
fun dueBefore(task: Task, end: Instant, zone: ZoneId = ZoneId.systemDefault()): Boolean =
|
||||
task.wallClock(TaskEnd.DUE, zone)?.let { it < end } ?: false
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.WeekFields
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
@@ -14,12 +14,9 @@ import java.util.Locale
|
||||
val LocalUse24HourFormat = staticCompositionLocalOf { true }
|
||||
|
||||
/** The resolved first day of the week, provided at the app root from the week-start setting. */
|
||||
val LocalFirstDayOfWeek = staticCompositionLocalOf { WeekFields.of(Locale.getDefault()).firstDayOfWeek }
|
||||
val LocalFirstDayOfWeek = staticCompositionLocalOf { localeWeekStart() }
|
||||
|
||||
/** A minute-of-day as a clock time: "14:00" or "2:00 PM". */
|
||||
fun formatMinuteOfDay(minuteOfDay: Int, is24Hour: Boolean, locale: Locale = Locale.getDefault()): String =
|
||||
LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)
|
||||
.format(DateTimeFormatter.ofPattern(if (is24Hour) "HH:mm" else "h:mm a", locale))
|
||||
|
||||
/** The locale's first day of the week, for a week start left on automatic. */
|
||||
fun localeFirstDayOfWeek(locale: Locale = Locale.getDefault()): DayOfWeek = WeekFields.of(locale).firstDayOfWeek
|
||||
@@ -32,6 +32,7 @@ import de.jeanlucmakiola.agendula.domain.populatedFields
|
||||
import de.jeanlucmakiola.agendula.domain.htmlToPlainText
|
||||
import de.jeanlucmakiola.agendula.domain.looksLikeHtml
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.dueWindows
|
||||
import de.jeanlucmakiola.agendula.domain.showsIn
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
@@ -245,9 +246,10 @@ class TaskEditViewModel @Inject constructor(
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val upcomingEnd = settings.upcomingRange.end(now, zone)
|
||||
val ruleClock = RuleClock(todayStart, todayEnd, zone, settingsPrefs.firstDayOfWeek.first())
|
||||
val presetDue = preset?.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
|
||||
val dates = settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) {
|
||||
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd)
|
||||
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd, ruleClock)
|
||||
}
|
||||
// A read-only or vanished default — or a widget's preset list, if it was
|
||||
// since deleted or turned read-only — would give the task a list it
|
||||
|
||||
@@ -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,7 +57,8 @@ fun FilterEditScreen(
|
||||
val draft by viewModel.draft.collectAsStateWithLifecycle()
|
||||
val lists by viewModel.lists.collectAsStateWithLifecycle()
|
||||
val tagsInUse by viewModel.tags.collectAsStateWithLifecycle()
|
||||
val filter = draft
|
||||
val filter = draft?.filter
|
||||
val criteria = draft?.criteria
|
||||
var choosingPriority by rememberSaveable { mutableStateOf(false) }
|
||||
var confirmDelete by rememberSaveable { mutableStateOf(false) }
|
||||
val save = { viewModel.save(onSaved) }
|
||||
@@ -77,98 +81,16 @@ 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.
|
||||
if (criteria == null) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(title = stringResource(R.string.filter_rules_not_editable), position = Position.Alone)
|
||||
} else {
|
||||
CriteriaSections(criteria, lists, tagsInUse, viewModel, onChoosePriority = { choosingPriority = true })
|
||||
}
|
||||
|
||||
if (filter.id > 0) {
|
||||
@@ -184,13 +106,13 @@ fun FilterEditScreen(
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (choosingPriority && filter != null) {
|
||||
if (choosingPriority && criteria != null) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_section_priority),
|
||||
options = Priority.entries,
|
||||
selected = filter.minPriority,
|
||||
selected = criteria.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 +134,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
|
||||
@@ -19,6 +20,7 @@ import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -30,10 +32,18 @@ class FilterEditViewModel @Inject constructor(
|
||||
private val repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _draft = MutableStateFlow<SavedFilter?>(null)
|
||||
/**
|
||||
* The filter being edited and its [criteria], kept apart so a choice the
|
||||
* rule can't hold, like all tags with none picked, survives while editing.
|
||||
* [criteria] is `null` when the rule has no flat form; [filter] then keeps
|
||||
* its rule as loaded.
|
||||
*/
|
||||
data class Draft(val filter: SavedFilter, val criteria: FilterCriteria?)
|
||||
|
||||
private val _draft = MutableStateFlow<Draft?>(null)
|
||||
|
||||
/** `null` until [bind] has loaded the filter. An id of 0 is a new one. */
|
||||
val draft: StateFlow<SavedFilter?> = _draft.asStateFlow()
|
||||
val draft: StateFlow<Draft?> = _draft.asStateFlow()
|
||||
|
||||
val lists: StateFlow<List<TaskList>> = repository.taskLists()
|
||||
.catch { emit(emptyList()) }
|
||||
@@ -52,28 +62,42 @@ 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.update { it?.copy(filter = it.filter.copy(name = name)) }
|
||||
}
|
||||
|
||||
/** Changes the criteria, and the rule with them; a filter without a flat form is left as it is. */
|
||||
fun updateCriteria(transform: (FilterCriteria) -> FilterCriteria) {
|
||||
_draft.update { draft ->
|
||||
val criteria = draft?.criteria?.let(transform) ?: return@update draft
|
||||
Draft(draft.filter.copy(rule = criteria.toRule()), criteria)
|
||||
}
|
||||
}
|
||||
|
||||
private fun load(filter: SavedFilter) {
|
||||
_draft.value = Draft(filter, filter.criteria)
|
||||
}
|
||||
|
||||
fun save(onSaved: (Long) -> Unit) {
|
||||
val filter = _draft.value ?: return
|
||||
val filter = _draft.value?.filter ?: return
|
||||
if (filter.name.isBlank() || saving) return
|
||||
saving = true
|
||||
viewModelScope.launch {
|
||||
val id = settingsPrefs.saveFilter(filter.copy(name = filter.name.trim()))
|
||||
// Lists deleted while this was open don't come back with it.
|
||||
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
|
||||
val current = if (existing == null) filter else filter.withListsIn(existing)
|
||||
val id = settingsPrefs.saveFilter(current.copy(name = filter.name.trim()))
|
||||
// A widget showing this filter doesn't watch the prefs.
|
||||
widgetUpdater.requestRefresh()
|
||||
onSaved(id)
|
||||
@@ -81,7 +105,7 @@ class FilterEditViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
fun delete(onDeleted: () -> Unit) {
|
||||
val id = _draft.value?.id?.takeIf { it > 0 } ?: return
|
||||
val id = _draft.value?.filter?.id?.takeIf { it > 0 } ?: return
|
||||
viewModelScope.launch {
|
||||
settingsPrefs.deleteFilter(id)
|
||||
widgetUpdater.requestRefresh()
|
||||
|
||||
@@ -9,6 +9,7 @@ import de.jeanlucmakiola.agendula.data.sync.RemoteLists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
@@ -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,13 @@ 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(),
|
||||
combine(
|
||||
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
|
||||
settingsPrefs.firstDayOfWeek,
|
||||
) { (hidden, range), weekStart -> Triple(hidden, range, weekStart) },
|
||||
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) as ListsUiState
|
||||
}.recoveringFromProviderFailure { ListsUiState.Failure }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
|
||||
|
||||
@@ -160,6 +165,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()
|
||||
@@ -212,11 +218,15 @@ class ListsViewModel @Inject constructor(
|
||||
val ids = tagged.mapTo(HashSet()) { it.taskId }
|
||||
TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) })
|
||||
}
|
||||
val clock = RuleClock(todayStart, todayEnd, zone, weekStart)
|
||||
// Lists deleted since drop out, as they do when the filter is opened.
|
||||
val listIds = lists.mapTo(HashSet()) { it.id }
|
||||
// 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 filters = savedFilters.map { saved ->
|
||||
val filter = saved.withListsIn(listIds)
|
||||
val matching = openTasks.filter { filter.matches(it, clock) }
|
||||
val ids = matching.mapTo(HashSet()) { it.taskId }
|
||||
FilterOverview(filter, matching.count { !it.isSubtask || it.parentId !in ids })
|
||||
FilterOverview(saved, matching.count { !it.isSubtask || it.parentId !in ids })
|
||||
}
|
||||
return ListsUiState.Content(
|
||||
smartCounts = smartCounts,
|
||||
|
||||
@@ -23,7 +23,7 @@ import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay
|
||||
import de.jeanlucmakiola.agendula.ui.common.localeFirstDayOfWeek
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
@@ -162,7 +162,7 @@ internal fun AppearanceScreen(
|
||||
if (day == null) {
|
||||
stringResource(
|
||||
R.string.settings_week_start_auto_summary,
|
||||
localeFirstDayOfWeek(locale).getDisplayName(TextStyle.FULL, locale),
|
||||
localeWeekStart(locale).getDisplayName(TextStyle.FULL, locale),
|
||||
)
|
||||
} else {
|
||||
null
|
||||
|
||||
@@ -30,6 +30,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderLead
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
@@ -111,6 +112,7 @@ class SettingsViewModel @Inject constructor(
|
||||
private val taskNotifier: TaskNotifier,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val widgetUpdater: TaskWidgetUpdater,
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
@@ -265,7 +267,11 @@ class SettingsViewModel @Inject constructor(
|
||||
prefs.setTimeFormat(pref)
|
||||
refreshShownReminders()
|
||||
}
|
||||
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch { prefs.setWeekStart(day) }
|
||||
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch {
|
||||
prefs.setWeekStart(day)
|
||||
// A widget on a saved filter reads weeks from it, and doesn't watch the prefs.
|
||||
widgetUpdater.requestRefresh()
|
||||
}
|
||||
fun setSnoozeMinutes(minutes: Int) = viewModelScope.launch {
|
||||
prefs.setSnoozeMinutes(minutes)
|
||||
refreshShownReminders()
|
||||
|
||||
@@ -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>()) }
|
||||
|
||||
@@ -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,68 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.preferences.core.preferencesOf
|
||||
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 kotlinx.coroutines.runBlocking
|
||||
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.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next action"))),
|
||||
Rule.Not(Rule.AnyOf(listOf(Rule.HasTag("someday"), Rule.Due(DueSpec.Window(DueWindow.NO_DATE))))),
|
||||
Rule.Not(Rule.Not(Rule.MinPriority(Priority.LOW))),
|
||||
Rule.AnyOf(
|
||||
listOf(
|
||||
Rule.Due(DueSpec.ThisWeek),
|
||||
Rule.Due(DueSpec.ThisMonth),
|
||||
Rule.Due(DueSpec.NextDays(0)),
|
||||
Rule.Due(DueSpec.NextDays(14)),
|
||||
),
|
||||
),
|
||||
Rule.AnyOf(emptyList()),
|
||||
Rule.AllOf(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")
|
||||
@@ -37,28 +75,30 @@ class SavedFilterCodecTest {
|
||||
@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,15 +106,16 @@ 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
|
||||
@@ -84,9 +125,133 @@ class SavedFilterCodecTest {
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 1), "OWN").map { it.id }).containsExactly(3L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `saving keeps no other store's list pruned meanwhile`() {
|
||||
val both = SavedFilter(1, "f", FilterCriteria(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:5", "EXTERNAL:6")))
|
||||
var raw = SavedFilterCodec.upsert(null, both, "OWN")
|
||||
val loaded = SavedFilterCodec.decode(raw, "OWN").single()
|
||||
raw = SavedFilterCodec.withoutLists(raw, "EXTERNAL") { it == 5L }
|
||||
raw = SavedFilterCodec.upsert(raw, loaded.copy(name = "renamed"), "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().criteria!!.listsElsewhere).containsExactly("EXTERNAL:6")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flat and v2 lines are told apart per line`() {
|
||||
val raw = legacyLine(id = 7, refs = listOf("OWN:2")) + "\n" + SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").map { it.id }).containsExactly(7L, 3L).inOrder()
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").first().criteria!!.listIds).containsExactly(2L)
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 7), "OWN").map { it.id }).containsExactly(3L)
|
||||
val renamed = SavedFilterCodec.upsert(raw, SavedFilter(7, "renamed", FilterCriteria(listIds = setOf(2L))), "OWN")
|
||||
assertThat(renamed.lines().first()).startsWith("v2|7|renamed|")
|
||||
}
|
||||
|
||||
@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 migrated = SavedFilterCodec.migrate(raw)
|
||||
val own = SavedFilterCodec.decode(migrated, "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(migrated, "EXTERNAL").single().flat().listIds).containsExactly(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `migration rewrites flat lines once and reads the same`() {
|
||||
val raw = listOf(
|
||||
legacyLine(id = 1, due = "UPCOMING", refs = listOf("OWN:1", "EXTERNAL:5"), tags = "x", match = "ANY"),
|
||||
SavedFilterCodec.upsert(null, filter, "OWN"),
|
||||
"garbage",
|
||||
legacyLine(id = 2, refs = listOf("OWN:nope")),
|
||||
).joinToString("\n")
|
||||
assertThat(SavedFilterCodec.needsMigration(raw)).isTrue()
|
||||
val migrated = SavedFilterCodec.migrate(raw)
|
||||
assertThat(SavedFilterCodec.needsMigration(migrated)).isFalse()
|
||||
for (mode in listOf("OWN", "EXTERNAL")) {
|
||||
assertThat(SavedFilterCodec.decode(migrated, mode)).isEqualTo(SavedFilterCodec.decode(raw, mode))
|
||||
}
|
||||
assertThat(migrated.lines()).hasSize(3)
|
||||
assertThat(migrated.lines().all { it.startsWith("v2|") }).isTrue()
|
||||
assertThat(SavedFilterCodec.migrate(migrated)).isEqualTo(migrated)
|
||||
val upcomingX = FilterCriteria(due = setOf(DueWindow.UPCOMING), tags = setOf("x"))
|
||||
assertThat(SavedFilterCodec.decode(migrated, "OWN").map { it.criteria }).containsExactly(
|
||||
upcomingX.copy(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:5")),
|
||||
criteria,
|
||||
FilterCriteria(),
|
||||
).inOrder()
|
||||
assertThat(SavedFilterCodec.decode(migrated, "EXTERNAL").map { it.criteria }).containsExactly(
|
||||
upcomingX.copy(listIds = setOf(5L), listsElsewhere = setOf("OWN:1")),
|
||||
criteria.copy(listIds = emptySet(), listsElsewhere = setOf("OWN:4", "OWN:9")),
|
||||
FilterCriteria(listsElsewhere = setOf("OWN:nope")),
|
||||
).inOrder()
|
||||
// An unreadable list of this store reads as no list condition, as it did before.
|
||||
assertThat(SavedFilterCodec.decode(migrated, "OWN").single { it.id == 2L }.rule).isEqualTo(Rule.Everything)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the datastore migration rewrites the key in place and is idempotent`() = runBlocking<Unit> {
|
||||
val raw = legacyLine(id = 1, refs = listOf("OWN:1")) + "\n" + SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val prefs = preferencesOf(SavedFilterMigration.KEY to raw)
|
||||
assertThat(SavedFilterMigration.shouldMigrate(prefs)).isTrue()
|
||||
val once = SavedFilterMigration.migrate(prefs)
|
||||
assertThat(once[SavedFilterMigration.KEY]!!.lines().all { it.startsWith("v2|") }).isTrue()
|
||||
assertThat(once.asMap().keys).containsExactly(SavedFilterMigration.KEY)
|
||||
assertThat(SavedFilterMigration.shouldMigrate(once)).isFalse()
|
||||
val twice = SavedFilterMigration.migrate(once)
|
||||
assertThat(twice).isEqualTo(once)
|
||||
assertThat(SavedFilterCodec.decode(twice[SavedFilterMigration.KEY], "OWN"))
|
||||
.isEqualTo(SavedFilterCodec.decode(raw, "OWN"))
|
||||
assertThat(SavedFilterMigration.shouldMigrate(preferencesOf())).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dropping lists prunes them from every filter`() {
|
||||
val nested = SavedFilter(
|
||||
id = 5,
|
||||
name = "n",
|
||||
rule = Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(1L, 2L))))),
|
||||
)
|
||||
val raw = SavedFilterCodec.upsert(null, nested, "OWN") + "\n" + SavedFilterCodec.migrate(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.AnyOf(listOf(Rule.InList(emptySet()), 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("|")
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import com.google.common.truth.Truth.assertWithMessage
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.dueWindowOf
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Every flat filter, migrated to a rule, keeps the tasks the 1.4 filter kept, in every store. */
|
||||
class SavedFilterMigrationEquivalenceTest {
|
||||
|
||||
private val dayMs = 86_400_000L
|
||||
private val todayStart = Instant.fromEpochMilliseconds(1000 * dayMs)
|
||||
private val todayEnd = Instant.fromEpochMilliseconds(1001 * dayMs)
|
||||
private val clock = RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), DayOfWeek.MONDAY)
|
||||
|
||||
/** The 1.4 filter as its codec read it for one store, and its `matches`. */
|
||||
private data class Legacy(
|
||||
val due: Set<DueWindow>,
|
||||
val listIds: Set<Long>,
|
||||
val listsElsewhere: Boolean,
|
||||
val tags: Set<String>,
|
||||
val tagMatch: TagMatch,
|
||||
val minPriority: Priority,
|
||||
) {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun read(refs: List<String>, mode: String, due: Set<DueWindow>, tags: Set<String>, match: TagMatch, priority: Priority) =
|
||||
Legacy(
|
||||
due = due,
|
||||
listIds = refs.filter { it.startsWith("$mode:") }.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet(),
|
||||
listsElsewhere = refs.any { !it.startsWith("$mode:") },
|
||||
tags = tags,
|
||||
tagMatch = match,
|
||||
minPriority = priority,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val tasks: List<Task> = buildList {
|
||||
val dues = listOf(
|
||||
null,
|
||||
Instant.fromEpochMilliseconds(999 * dayMs),
|
||||
Instant.fromEpochMilliseconds(1000 * dayMs + 1),
|
||||
Instant.fromEpochMilliseconds(1003 * dayMs),
|
||||
)
|
||||
val tagSets = listOf(emptyList(), listOf("a"), listOf("b"), listOf("a", "b"), listOf("A"), listOf("c"))
|
||||
for (listId in 1L..3L) for (due in dues) for (tags in tagSets) for (priority in Priority.entries) {
|
||||
for (status in listOf(TaskStatus.NEEDS_ACTION, TaskStatus.COMPLETED)) {
|
||||
add(testTask(listId = listId, due = due, tags = tags, priority = priority, status = status))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every flat filter matches the same tasks after migration`() {
|
||||
val dueSets = (0 until 16).map { bits -> DueWindow.entries.filterIndexed { i, _ -> bits and (1 shl i) != 0 }.toSet() }
|
||||
val refSets = listOf(
|
||||
emptyList(),
|
||||
listOf("OWN:1"),
|
||||
listOf("OWN:1", "OWN:2"),
|
||||
listOf("EXTERNAL:3"),
|
||||
listOf("OWN:2", "EXTERNAL:1"),
|
||||
listOf("OWN:x"),
|
||||
)
|
||||
val tagChoices = listOf(
|
||||
emptySet<String>() to TagMatch.ANY,
|
||||
emptySet<String>() to TagMatch.ALL,
|
||||
setOf("a") to TagMatch.ANY,
|
||||
setOf("a") to TagMatch.ALL,
|
||||
setOf("a", "b") to TagMatch.ANY,
|
||||
setOf("a", "b") to TagMatch.ALL,
|
||||
)
|
||||
var id = 0L
|
||||
var checked = 0
|
||||
val mismatches = mutableListOf<String>()
|
||||
for (due in dueSets) for (refs in refSets) for ((tags, match) in tagChoices) for (priority in Priority.entries) {
|
||||
id++
|
||||
val line = legacyLine(
|
||||
id = id,
|
||||
due = due.joinToString(",") { it.name },
|
||||
refs = refs,
|
||||
tags = tags.joinToString(","),
|
||||
match = match.name,
|
||||
priority = priority.name,
|
||||
)
|
||||
val migrated = SavedFilterCodec.migrate(line)
|
||||
for (mode in listOf("OWN", "EXTERNAL")) {
|
||||
val legacy = Legacy.read(refs, mode, due, tags, match, priority)
|
||||
val now = SavedFilterCodec.decode(migrated, mode).single()
|
||||
for (task in tasks) {
|
||||
if (now.matches(task, clock) != legacy.matches(task, todayStart, todayEnd)) {
|
||||
mismatches += "$line in $mode: $task"
|
||||
}
|
||||
checked++
|
||||
}
|
||||
}
|
||||
}
|
||||
assertWithMessage("mismatches").that(mismatches.take(5)).isEmpty()
|
||||
assertWithMessage("checked").that(checked).isGreaterThan(1_000_000)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import java.time.ZoneId
|
||||
@@ -102,11 +103,12 @@ 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 clock = RuleClock(start, end, zone, DayOfWeek.MONDAY)
|
||||
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()
|
||||
assertThat(dates.showsIn(null, filter, start, end, ruleClock = clock)).isTrue()
|
||||
val later = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, localToday, localToday, now)
|
||||
assertThat(later.showsIn(null, filter, start, end)).isFalse()
|
||||
assertThat(later.showsIn(null, filter, start, end, ruleClock = clock)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
class RuleTest {
|
||||
|
||||
private val zone = ZoneId.of("Europe/Berlin")
|
||||
|
||||
private fun clockOn(day: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY, zone: ZoneId = this.zone) =
|
||||
RuleClock(startOfDay(day, zone), startOfDay(day.plusDays(1), zone), zone, weekStart)
|
||||
|
||||
private fun dueOn(day: LocalDate) = testTask(due = allDayInstantOf(day), isAllDay = true)
|
||||
|
||||
private fun dueAt(day: LocalDate, time: LocalTime, zone: ZoneId = this.zone) =
|
||||
testTask(due = Instant.fromEpochMilliseconds(day.atTime(time).atZone(zone).toInstant().toEpochMilli()))
|
||||
|
||||
private fun Rule.matches(task: Task, day: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY) =
|
||||
matches(task, clockOn(day, weekStart))
|
||||
|
||||
private fun DueSpec.Range.daysIn(today: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY): List<LocalDate> =
|
||||
(-40L..40L).map { today.plusDays(it) }.filter { Rule.Due(this).matches(dueOn(it), today, weekStart) }
|
||||
|
||||
@Test
|
||||
fun `groups combine their children`() {
|
||||
val work = Rule.HasTag("work")
|
||||
val high = Rule.MinPriority(Priority.HIGH)
|
||||
val task = testTask(tags = listOf("work"), priority = Priority.LOW)
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
assertThat(Rule.AllOf(listOf(work, high)).matches(task, day)).isFalse()
|
||||
assertThat(Rule.AnyOf(listOf(work, high)).matches(task, day)).isTrue()
|
||||
assertThat(Rule.Not(work).matches(task, day)).isFalse()
|
||||
assertThat(Rule.Not(high).matches(task, day)).isTrue()
|
||||
assertThat(Rule.AllOf(emptyList()).matches(task, day)).isTrue()
|
||||
assertThat(Rule.AnyOf(emptyList()).matches(task, day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `next actions are a list or a tag`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(7L)), Rule.HasTag("next"))),
|
||||
Rule.Not(Rule.AnyOf(listOf(Rule.HasTag("someday"), Rule.InList(setOf(9L))))),
|
||||
),
|
||||
)
|
||||
assertThat(rule.matches(testTask(listId = 7), day)).isTrue()
|
||||
assertThat(rule.matches(testTask(listId = 1, tags = listOf("next")), day)).isTrue()
|
||||
assertThat(rule.matches(testTask(listId = 1), day)).isFalse()
|
||||
assertThat(rule.matches(testTask(listId = 7, tags = listOf("someday")), day)).isFalse()
|
||||
assertThat(rule.matches(testTask(listId = 9, tags = listOf("next")), day)).isFalse()
|
||||
assertThat(Rule.Not(Rule.Not(Rule.InList(setOf(7L)))).matches(testTask(listId = 7), day)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags compare exactly and other stores' lists never match here`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
assertThat(Rule.HasTag("work").matches(testTask(tags = listOf("Work")), day)).isFalse()
|
||||
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)
|
||||
fun window(w: DueWindow) = Rule.Due(DueSpec.Window(w))
|
||||
assertThat(window(DueWindow.TODAY).matches(dueAt(day, LocalTime.of(23, 59)), day)).isTrue()
|
||||
assertThat(window(DueWindow.OVERDUE).matches(dueOn(day.minusDays(1)), day)).isTrue()
|
||||
assertThat(window(DueWindow.UPCOMING).matches(dueOn(day.plusDays(1)), day)).isTrue()
|
||||
assertThat(window(DueWindow.NO_DATE).matches(testTask(), day)).isTrue()
|
||||
assertThat(window(DueWindow.NO_DATE).matches(dueOn(day), day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the next zero days are today, timed or not`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val today = Rule.Due(DueSpec.NextDays(0))
|
||||
assertThat(DueSpec.NextDays(0).daysIn(day)).containsExactly(day)
|
||||
assertThat(today.matches(dueAt(day, LocalTime.MIDNIGHT), day)).isTrue()
|
||||
assertThat(today.matches(dueAt(day, LocalTime.of(23, 59)), day)).isTrue()
|
||||
assertThat(today.matches(dueAt(day.plusDays(1), LocalTime.MIDNIGHT), day)).isFalse()
|
||||
assertThat(today.matches(testTask(), day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this week starts on the week start`() {
|
||||
// A Thursday.
|
||||
val thursday = LocalDate.of(2026, 11, 26)
|
||||
val monday = LocalDate.of(2026, 11, 23)
|
||||
val sunday = LocalDate.of(2026, 11, 22)
|
||||
val saturday = LocalDate.of(2026, 11, 21)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.MONDAY)).isEqualTo((0L..6L).map { monday.plusDays(it) })
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.SUNDAY)).isEqualTo((0L..6L).map { sunday.plusDays(it) })
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.SATURDAY)).isEqualTo((0L..6L).map { saturday.plusDays(it) })
|
||||
// On the week start itself, and on the last day of the week.
|
||||
assertThat(DueSpec.ThisWeek.daysIn(monday, DayOfWeek.MONDAY).first()).isEqualTo(monday)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(sunday, DayOfWeek.MONDAY).first()).isEqualTo(LocalDate.of(2026, 11, 16))
|
||||
assertThat(DueSpec.ThisWeek.daysIn(sunday, DayOfWeek.SUNDAY).first()).isEqualTo(sunday)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this week crosses the year`() {
|
||||
val newYear = LocalDate.of(2027, 1, 1)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(newYear, DayOfWeek.MONDAY))
|
||||
.isEqualTo((0L..6L).map { LocalDate.of(2026, 12, 28).plusDays(it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this month is the calendar month`() {
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2026, 12, 31)))
|
||||
.isEqualTo((1..31).map { LocalDate.of(2026, 12, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2027, 1, 1)))
|
||||
.isEqualTo((1..31).map { LocalDate.of(2027, 1, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2028, 2, 29)))
|
||||
.isEqualTo((1..29).map { LocalDate.of(2028, 2, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2027, 2, 15)))
|
||||
.isEqualTo((1..28).map { LocalDate.of(2027, 2, it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `next days run from today and reach as far as upcoming does`() {
|
||||
val day = LocalDate.of(2026, 12, 29)
|
||||
assertThat(DueSpec.NextDays(0).daysIn(day)).containsExactly(day)
|
||||
assertThat(DueSpec.NextDays(7).daysIn(day)).isEqualTo((0L..7L).map { day.plusDays(it) })
|
||||
val now = Instant.fromEpochMilliseconds(day.atTime(12, 0).atZone(zone).toInstant().toEpochMilli())
|
||||
assertThat(DueSpec.NextDays(7).days(day, DayOfWeek.MONDAY).second)
|
||||
.isEqualTo(UpcomingRange.WEEK.lastDay(day)!!.plusDays(1))
|
||||
assertThat(startOfDay(DueSpec.NextDays(7).days(day, DayOfWeek.MONDAY).second, zone))
|
||||
.isEqualTo(UpcomingRange.WEEK.end(now, zone))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an all-day due is read as its date west of utc`() {
|
||||
val west = ZoneId.of("America/New_York")
|
||||
val day = LocalDate.of(2026, 11, 30)
|
||||
val clock = clockOn(day, zone = west)
|
||||
assertThat(Rule.Due(DueSpec.NextDays(0)).matches(dueOn(day), clock)).isTrue()
|
||||
assertThat(Rule.Due(DueSpec.ThisMonth).matches(dueOn(LocalDate.of(2026, 12, 1)), clock)).isFalse()
|
||||
assertThat(Rule.Due(DueSpec.ThisMonth).matches(dueAt(day, LocalTime.of(23, 30), west), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a top-level list condition losing its lists drops out`() {
|
||||
val gone: (Long) -> Boolean = { it == 1L }
|
||||
assertThat(Rule.InList(setOf(1L, 2L)).withoutLists(gone)).isEqualTo(Rule.InList(setOf(2L)))
|
||||
assertThat(Rule.InList(setOf(1L)).withoutLists(gone)).isEqualTo(Rule.Everything)
|
||||
assertThat(Rule.InList(setOf(1L), setOf("EXTERNAL:1")).withoutLists(gone))
|
||||
.isEqualTo(Rule.InList(emptySet(), setOf("EXTERNAL:1")))
|
||||
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))).withoutLists(gone))
|
||||
.isEqualTo(Rule.AllOf(listOf(Rule.HasTag("a"))))
|
||||
assertThat(Rule.Everything.withoutLists(gone)).isEqualTo(Rule.Everything)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a nested list condition losing its lists still matches the same tasks`() {
|
||||
val gone: (Long) -> Boolean = { it == 1L }
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val rules = listOf(
|
||||
Rule.Not(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))),
|
||||
Rule.AnyOf(listOf(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))), Rule.HasTag("b"))),
|
||||
Rule.AnyOf(listOf(Rule.Not(Rule.InList(setOf(1L))), Rule.HasTag("x"))),
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.Not(Rule.InList(setOf(1L, 2L))))),
|
||||
)
|
||||
val tasks = listOf(2L, 3L).flatMap { list ->
|
||||
listOf(emptyList(), listOf("a"), listOf("b"), listOf("x")).map { testTask(listId = list, tags = it) }
|
||||
}
|
||||
for (rule in rules) {
|
||||
val pruned = rule.withoutLists(gone)
|
||||
assertThat(pruned).isNotEqualTo(rule)
|
||||
for (task in tasks) assertThat(pruned.matches(task, day)).isEqualTo(rule.matches(task, day))
|
||||
}
|
||||
assertThat(rules[0].withoutLists(gone))
|
||||
.isEqualTo(Rule.Not(Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.HasTag("x")))))
|
||||
assertThat(rules[0].withoutLists { false }).isEqualTo(rules[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only a week range reads the week start`() {
|
||||
assertThat(Rule.AllOf(listOf(Rule.Not(Rule.Due(DueSpec.ThisWeek)))).readsWeekStart).isTrue()
|
||||
assertThat(Rule.AllOf(listOf(Rule.Due(DueSpec.ThisMonth), Rule.Due(DueSpec.NextDays(7)))).readsWeekStart).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a saved filter is read with its clock`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val filter = SavedFilter(1, "f", Rule.Due(DueSpec.ThisWeek))
|
||||
val clock = clockOn(day)
|
||||
fun matches(task: Task, ruleClock: RuleClock?) =
|
||||
TaskFiltering.matches(task, TaskFilter.Saved(1), clock.todayStart, clock.todayEnd, filter, ruleClock = ruleClock)
|
||||
assertThat(matches(dueOn(day), clock)).isTrue()
|
||||
assertThat(matches(dueOn(day.plusDays(7)), clock)).isFalse()
|
||||
assertThat(matches(dueOn(day), null)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the due date settles a rule only where nothing else decides`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val clock = clockOn(day)
|
||||
val thisWeek = Rule.Due(DueSpec.ThisWeek)
|
||||
val inWeek = dueOn(day)
|
||||
val later = dueOn(day.plusDays(30))
|
||||
val rule = Rule.AllOf(listOf(thisWeek, Rule.Not(Rule.MinPriority(Priority.HIGH))))
|
||||
assertThat(rule.dueVerdict(inWeek, clock)).isNull()
|
||||
assertThat(rule.dueVerdict(later, clock)).isFalse()
|
||||
assertThat(Rule.AnyOf(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(inWeek, clock)).isTrue()
|
||||
assertThat(Rule.AnyOf(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(later, clock)).isNull()
|
||||
assertThat(Rule.Not(thisWeek).dueVerdict(later, clock)).isTrue()
|
||||
assertThat(Rule.Everything.dueVerdict(later, clock)).isTrue()
|
||||
val filter = SavedFilter(1, "f", rule)
|
||||
assertThat(filter.admitsDueOf(inWeek, clock)).isTrue()
|
||||
assertThat(filter.admitsDueOf(later, clock)).isFalse()
|
||||
}
|
||||
|
||||
@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.AnyOf(listOf(Rule.HasTag("a"), Rule.HasTag("b")))))
|
||||
.isEqualTo(FilterCriteria(tags = setOf("a", "b")))
|
||||
assertThat(FilterCriteria.of(Rule.AllOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b")))))
|
||||
.isEqualTo(FilterCriteria(listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ALL))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rules beyond the flat form have none`() {
|
||||
val notFlat = listOf(
|
||||
Rule.Not(Rule.HasTag("a")),
|
||||
Rule.Due(DueSpec.ThisWeek),
|
||||
Rule.AnyOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)))),
|
||||
Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(2L)))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("a"))), Rule.AllOf(listOf(Rule.HasTag("b"))))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(emptyList()))),
|
||||
Rule.InList(emptySet()),
|
||||
Rule.AllOf(listOf(Rule.AllOf(listOf(Rule.Due(DueSpec.Window(DueWindow.TODAY)))))),
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.AnyOf(listOf(Rule.HasTag("b"))))),
|
||||
)
|
||||
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.Not(Rule.InList(emptySet())))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
@@ -15,10 +16,19 @@ class SavedFilterTest {
|
||||
private val today = Instant.fromEpochMilliseconds(1000 * dayMs + 1)
|
||||
private val upcoming = Instant.fromEpochMilliseconds(1002 * dayMs)
|
||||
|
||||
private fun SavedFilter.matches(task: Task) = matches(task, todayStart, todayEnd)
|
||||
private fun SavedFilter.matches(task: Task) = matches(task, RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), DayOfWeek.MONDAY))
|
||||
|
||||
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 +39,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 +48,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 +71,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 +83,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 +104,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 +114,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()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user