Compare commits

..
Author SHA1 Message Date
makiolaj 080afe7aa3 Share one rule codec between saved filters and views (#59) 2026-11-27 11:45:54 +01:00
makiolaj e7b726ee82 Read and write view rules through the shared rule codec (#59) 2026-11-27 11:40:38 +01:00
makiolaj bb6e027011 Route tiles by type, one rule grammar for views and filters (#59) 2026-11-26 17:35:15 +01:00
makiolaj 1fc94757b0 Preview per block, provider-aware list refs in views (#59) 2026-11-26 17:28:21 +01:00
makiolaj 355daad87b Carry the view in the home state, drop view pruning for now (#59) 2026-11-26 17:23:10 +01:00
makiolaj 3f97683c6d Follow the rule renames in the view codec tests (#59) 2026-11-26 17:23:10 +01:00
makiolaj afab067884 Keep Home first, prune views with their lists and filters (#59) 2026-11-26 17:23:10 +01:00
makiolaj 6dec534528 Render home from the Home view's blocks (#59) 2026-11-26 17:23:10 +01:00
makiolaj b0bb853854 Store views and migrate to a Home view once (#59) 2026-11-26 17:23:10 +01:00
makiolaj ba9d984a42 Add the view and block model (#59) 2026-11-26 17:23:10 +01:00
makiolaj 5390cb8882 Read saved filters with one clock per load, week start from one place (#172) 2026-11-26 17:22:50 +01:00
makiolaj 1ad7ed6fe3 Address review: one clock per saved filter, locale-aware week start, editor state (#172) 2026-11-26 17:10:04 +01:00
makiolaj f745698b5b Migrate saved filters in place on their own key (#172) 2026-11-26 16:51:57 +01:00
makiolaj f9926a80b3 Require the week start for rules, read flat filters only in the migration (#172) 2026-11-26 16:45:12 +01:00
makiolaj bfbe7398d4 Keep nested rules intact when pruning lists, keep the old filters key (#172) 2026-11-26 16:32:44 +01:00
makiolaj 9dd8660571 Migrate stored filters to the rule format once (#172) 2026-11-26 16:23:50 +01:00
makiolaj ceaff3183c Base saved filters on the rule tree, stored in a v2 format (#172) 2026-11-26 16:23:50 +01:00
makiolaj 697e2e8554 Add filter rule tree with relative due ranges (#172) 2026-11-26 16:22:32 +01:00
38 changed files with 2559 additions and 438 deletions

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,8 @@ 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.prefs.ViewsMigration
import de.jeanlucmakiola.agendula.data.tasks.AndroidProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.ModeRoutingTasksDataSource
@@ -48,6 +50,7 @@ internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreference
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
name = "agendula_prefs",
corruptionHandler = replaceCorrupted(),
produceMigrations = { listOf(SavedFilterMigration, ViewsMigration) },
)
@Module
@@ -0,0 +1,117 @@
package de.jeanlucmakiola.agendula.data.prefs
import de.jeanlucmakiola.agendula.domain.DueSpec
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.Rule
import java.net.URLDecoder
import java.net.URLEncoder
/**
* The stored grammar of a [Rule], shared by saved filters ([SavedFilterCodec])
* and views ([ViewCodec]): nested calls `and(…)`, `or(…)`, `not(…)`,
* `list(OWN%3A3,…)`, `tag(…)`, `prio(HIGH)`, `due(TODAY)` and
* `range(week|month)` or `range(next,7)`. 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.
*
* Fixed once released, and part of both formats: a change here is a change to
* both, with a version bump and a data migration for each.
*/
internal object RuleCodec {
/** [rule] as text, [mode]'s list ids qualified by it. */
fun encode(rule: Rule, mode: String): String = when (rule) {
is Rule.AllOf -> "and(${rule.children.joinToString(",") { encode(it, mode) }})"
is Rule.AnyOf -> "or(${rule.children.joinToString(",") { encode(it, mode) }})"
is Rule.Not -> "not(${encode(rule.child, mode)})"
is Rule.InList -> {
val refs = rule.listIds.sorted().map { "$mode:$it" } + rule.elsewhere.sorted()
"list(${refs.joinToString(",") { encodeText(it) }})"
}
is Rule.HasTag -> "tag(${encodeText(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})"
}
}
/**
* The rule [text] holds, with [mode]'s list ids; throws on text that isn't
* the grammar. It prunes nothing: what [encode] wrote reads back equal.
*/
fun decode(text: String, mode: String): Rule = RuleParser(text, mode).parse()
/** Reads the grammar [encode] writes. */
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" -> listRule(list(::atom).map(::decodeText))
"tag" -> Rule.HasTag(decodeText(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
}
/** [mode]'s list ids; any other ref, one that names no id included, is kept as it is. */
private fun listRule(refs: List<String>): Rule.InList {
val here = HashSet<Long>()
val elsewhere = HashSet<String>()
refs.forEach { ref ->
ref.removePrefix("$mode:").takeIf { it != ref }?.toLongOrNull()?.let(here::add) ?: elsewhere.add(ref)
}
return Rule.InList(here, elsewhere)
}
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 encodeText(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
private fun decodeText(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
}
@@ -1,92 +1,132 @@
package de.jeanlucmakiola.agendula.data.prefs
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 in [RuleCodec]'s grammar and the name URL-encoded. Reading a line
* drops a top-level list condition left with no list, so the filter goes back
* to any list, as a flat filter did.
*
* 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), RuleCodec.encode(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 ref of this store naming no list is dropped, and a top-level list condition with
// none of its lists readable drops out, as a flat filter's did.
val rule = RuleCodec.decode(f[3], mode)
.mapLists { list -> list.copy(elsewhere = list.elsewhere.filterNotTo(HashSet()) { it.startsWith("$mode:") }) }
.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 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
@@ -31,6 +32,8 @@ import de.jeanlucmakiola.agendula.domain.asReminderLead
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.UpcomingRange
import de.jeanlucmakiola.agendula.domain.View
import de.jeanlucmakiola.agendula.domain.withHomeFirst
import de.jeanlucmakiola.agendula.domain.withinUpcoming
import de.jeanlucmakiola.floret.reminders.ReminderLead
import de.jeanlucmakiola.floret.reminders.ReminderOverride
@@ -38,12 +41,17 @@ import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
import de.jeanlucmakiola.floret.reminders.normalizeReminders
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
import kotlinx.coroutines.Dispatchers
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 kotlinx.coroutines.flow.flowOn
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 +168,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 +321,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 +341,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))
@@ -597,6 +622,18 @@ class SettingsPrefs @Inject constructor(
p[GROUPINGS] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key }
}
/**
* The views in order, with the list ids of the current store, Home first (see
* [withHomeFirst]). Lists are qualified by the store alone, as the saved
* filters' are, since both share one rule grammar.
*/
val views: Flow<List<View>> =
dataStore.data.map { p -> p[VIEWS] to p[STORAGE_MODE] }
.distinctUntilChanged()
.map { (raw, mode) -> ViewCodec.decode(raw, (storedMode(mode) ?: resolver.autoMode()).name).withHomeFirst() }
.distinctUntilChanged()
.flowOn(Dispatchers.Default)
suspend fun setDefaultEditFields(fields: Set<TaskFormField>) = dataStore.edit {
it[DEFAULT_EDIT_FIELDS] = fields.mapTo(mutableSetOf()) { field -> field.name }
}
@@ -638,8 +675,9 @@ 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")
val VIEWS = ViewsMigration.KEY
}
}
@@ -0,0 +1,224 @@
package de.jeanlucmakiola.agendula.data.prefs
import de.jeanlucmakiola.agendula.domain.Block
import de.jeanlucmakiola.agendula.domain.BlockOptions
import de.jeanlucmakiola.agendula.domain.BlockSource
import de.jeanlucmakiola.agendula.domain.BlockType
import de.jeanlucmakiola.agendula.domain.BlockWidth
import de.jeanlucmakiola.agendula.domain.Rule
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
import de.jeanlucmakiola.agendula.domain.TileColor
import de.jeanlucmakiola.agendula.domain.View
import de.jeanlucmakiola.agendula.domain.ViewIcon
import de.jeanlucmakiola.agendula.domain.normalized
import java.net.URLDecoder
import java.net.URLEncoder
/**
* Stored form of the views, in order. A `v1` line comes first, then each view
* as a `view|id|name|icon|quickAdd|scope` line followed by its blocks as
* `block|id|type|width|ignoreScope|source|options` lines.
*
* Rules (a scope, a `rules:` source) are written by [RuleCodec], so list
* ids are qualified by their store (`OWN:3`) here too. Sources read `smart:TODAY`,
* `list:OWN%3A3`, `tag:…`, `filter:4` or `rules:…`; options are `key=value`
* pairs joined by `;`. Text is URL-encoded and booleans are `1` / `0`.
*
* A later version that adds an option key or an enum value bumps [VERSION], so an
* older one reads none of its layout rather than a part of it. A writer has to
* keep the lines [decode] skips rather than encode only what it read, or a view
* from a newer version, or with a scope that doesn't parse, is lost.
*
* Fixed once released — don't change without a data migration.
*/
internal object ViewCodec {
const val VERSION = "v1"
/**
* The views in [raw], with only the list ids of [mode]'s store. Lines that
* don't read are skipped, and a stored layout of another version reads as none.
*/
fun decode(raw: String?, mode: String): List<View> {
val lines = raw.orEmpty().split('\n').filter { it.isNotBlank() }
if (lines.firstOrNull() != VERSION) return emptyList()
val views = mutableListOf<View>()
// A block line belongs to the view above it; those under an unreadable view go with it.
var current: View? = null
fun close() {
current?.let { views += it.copy(blocks = it.blocks.normalized()) }
current = null
}
lines.drop(1).forEach { line ->
val f = line.split('|')
when (f.firstOrNull()) {
"view" -> {
close()
current = runCatching { decodeView(f, mode) }.getOrNull()
}
"block" -> current?.let { view ->
runCatching { decodeBlock(f, mode) }.getOrNull()?.let { current = view.copy(blocks = view.blocks + it) }
}
}
}
close()
return views.distinctBy { it.id }
}
fun encode(views: List<View>, mode: String): String = buildList {
add(VERSION)
views.forEach { view ->
add(
listOf(
"view",
view.id.toString(),
encode(view.name),
view.icon.name,
flag(view.quickAdd),
view.scope?.let { RuleCodec.encode(it, mode) }.orEmpty(),
).joinToString("|"),
)
view.blocks.forEach { add(encodeBlock(it, mode)) }
}
}.joinToString("\n")
private fun decodeView(f: List<String>, mode: String): View? {
if (f.size != 6) return null
return View(
id = f[1].toLongOrNull() ?: return null,
name = decode(f[2]),
icon = enumOr(f[3], ViewIcon.HOME),
quickAdd = f[4] != "0",
scope = f[5].takeIf { it.isNotEmpty() }?.let { RuleCodec.decode(it, mode) },
blocks = emptyList(),
)
}
private fun encodeBlock(block: Block, mode: String): String = listOf(
"block",
block.id.toString(),
block.type.name,
block.width.name,
flag(block.ignoreScope),
block.source?.let { encodeSource(it, mode) }.orEmpty(),
encodeOptions(block.options),
).joinToString("|")
private fun decodeBlock(f: List<String>, mode: String): Block? {
if (f.size != 7) return null
val type = BlockType.valueOf(f[2])
return Block(
id = f[1].toLongOrNull() ?: return null,
type = type,
width = enumOr(f[3], type.widths.first()),
ignoreScope = f[4] == "1",
source = f[5].takeIf { it.isNotEmpty() }?.let { decodeSource(it, mode) },
options = decodeOptions(type, pairs(f[6])),
)
}
private fun encodeSource(source: BlockSource, mode: String): String = when (source) {
is BlockSource.Smart -> "smart:${source.smart.name}"
is BlockSource.List -> "list:${encode("$mode:${source.listId}")}"
is BlockSource.ListElsewhere -> "list:${encode(source.ref)}"
is BlockSource.Tag -> "tag:${encode(source.tag)}"
is BlockSource.Filter -> "filter:${source.filterId}"
is BlockSource.Rules -> "rules:${RuleCodec.encode(source.rule, mode)}"
}
/** The source [text] names; a list of another store stays as its stored ref. */
private fun decodeSource(text: String, mode: String): BlockSource {
val kind = text.substringBefore(':')
val value = text.substringAfter(':')
return when (kind) {
"smart" -> BlockSource.Smart(SmartList.valueOf(value))
"list" -> decode(value).let { ref ->
ref.removePrefix("$mode:").takeIf { it != ref }?.toLongOrNull()?.let(BlockSource::List)
?: BlockSource.ListElsewhere(ref)
}
"tag" -> BlockSource.Tag(decode(value))
"filter" -> BlockSource.Filter(value.toLong())
"rules" -> BlockSource.Rules(RuleCodec.decode(value, mode))
else -> throw IllegalArgumentException("Unknown source $kind")
}
}
private fun encodeOptions(options: BlockOptions): String = when (options) {
is BlockOptions.Progress -> listOf("wave" to flag(options.wave), "title" to options.title?.let(::encode))
is BlockOptions.CountTile -> listOf(
"title" to options.title?.let(::encode),
"color" to options.color?.name,
"icon" to options.icon?.name,
)
is BlockOptions.Preview -> listOf(
"count" to options.count.toString(),
"showAll" to flag(options.showAll),
"inlineDone" to flag(options.inlineDone),
)
is BlockOptions.TaskList -> listOf(
"sort" to options.sort?.name,
"completed" to flag(options.showCompleted),
"inlineDone" to flag(options.inlineDone),
)
is BlockOptions.Lists -> listOf(
"accounts" to options.accounts?.sorted()?.joinToString(",") { encode(it) },
"counts" to flag(options.counts),
)
is BlockOptions.SectionHeading -> listOf("text" to encode(options.text))
is BlockOptions.RecentlyCompleted -> listOf("count" to options.count.toString())
BlockOptions.Tags, BlockOptions.Filters, BlockOptions.WeekStrip -> emptyList()
}.mapNotNull { (key, value) -> value?.let { "$key=$it" } }.joinToString(";")
/** [type]'s options from [p]; a key missing or not reading keeps its default. */
private fun decodeOptions(type: BlockType, p: Map<String, String>): BlockOptions = when (type) {
BlockType.PROGRESS -> BlockOptions.Progress(
wave = p["wave"] != "0",
title = text(p["title"]),
)
BlockType.COUNT_TILE -> BlockOptions.CountTile(
title = text(p["title"]),
color = p["color"]?.let { enumOrNull<TileColor>(it) },
icon = p["icon"]?.let { enumOrNull<ViewIcon>(it) },
)
BlockType.PREVIEW -> BlockOptions.Preview(
count = previewCount(p["count"]),
showAll = p["showAll"] != "0",
inlineDone = p["inlineDone"] == "1",
)
BlockType.TASK_LIST -> BlockOptions.TaskList(
sort = p["sort"]?.let { enumOrNull<TaskSortOrder>(it) },
showCompleted = p["completed"] != "0",
inlineDone = p["inlineDone"] != "0",
)
BlockType.LISTS -> BlockOptions.Lists(
accounts = p["accounts"]?.split(',')?.mapTo(HashSet(), ::decode),
counts = p["counts"] != "0",
)
BlockType.TAGS -> BlockOptions.Tags
BlockType.FILTERS -> BlockOptions.Filters
BlockType.SECTION_HEADING -> BlockOptions.SectionHeading(p["text"]?.let(::decode).orEmpty())
BlockType.WEEK_STRIP -> BlockOptions.WeekStrip
BlockType.RECENTLY_COMPLETED -> BlockOptions.RecentlyCompleted(previewCount(p["count"]))
}
/** A stored title; empty reads as none, so the source's own name shows. */
private fun text(value: String?): String? = value?.let(::decode)?.takeIf { it.isNotBlank() }
private fun previewCount(value: String?): Int =
value?.toIntOrNull()?.takeIf { it in BlockOptions.PREVIEW_COUNTS } ?: BlockOptions.PREVIEW_COUNTS.first()
private fun pairs(text: String): Map<String, String> = text.split(';').filter { '=' in it }
.associate { it.substringBefore('=') to it.substringAfter('=') }
private fun flag(value: Boolean): String = if (value) "1" else "0"
private inline fun <reified E : Enum<E>> enumOrNull(name: String): E? =
enumValues<E>().firstOrNull { it.name == name }
private inline fun <reified E : Enum<E>> enumOr(name: String, default: E): E = enumOrNull<E>(name) ?: default
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
private fun decode(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
}
@@ -0,0 +1,25 @@
package de.jeanlucmakiola.agendula.data.prefs
import androidx.datastore.core.DataMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.agendula.domain.View
/**
* Stores the [View.home] layout once, when there are no views yet: on the
* upgrade from 1.4 and on a fresh install alike.
*/
internal object ViewsMigration : DataMigration<Preferences> {
val KEY = stringPreferencesKey("views")
// Home names no list, so the store its ids would be qualified by doesn't matter.
private const val ANY_STORE = "OWN"
override suspend fun shouldMigrate(currentData: Preferences): Boolean = currentData[KEY] == null
override suspend fun migrate(currentData: Preferences): Preferences =
currentData.toMutablePreferences().apply { this[KEY] = ViewCodec.encode(listOf(View.home()), ANY_STORE) }
override suspend fun cleanUp() = Unit
}
@@ -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,181 @@
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.
*
* That widening is a saved filter's; a view's scope uses [withoutListIds],
* where a list condition left without lists matches nothing at every level.
*/
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()
/** This rule without the lists [gone] names; a list condition left without lists matches nothing. */
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
@@ -0,0 +1,268 @@
package de.jeanlucmakiola.agendula.domain
/**
* A stored home layout: [blocks] in order, over the tasks [scope] admits (every
* task when `null`). Home is the first view.
*/
data class View(
val id: Long,
val name: String,
val icon: ViewIcon,
val scope: Rule?,
val blocks: List<Block>,
val quickAdd: Boolean = true,
) {
/** What is wrong with this view's blocks; empty when nothing is. */
val problems: List<LayoutProblem> get() = blocks.layoutProblems()
companion object {
const val HOME_ID = 1L
/**
* The Home view every install starts with: the blocks of the fixed home
* of 1.4, in its order. The name is empty so the UI shows its own,
* translated one until the user renames it.
*/
fun home(): View = View(
id = HOME_ID,
name = "",
icon = ViewIcon.HOME,
scope = null,
blocks = listOf(
Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY)),
Block(2, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.OVERDUE), BlockWidth.HALF),
Block(3, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF),
Block(4, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING)),
Block(5, BlockType.LISTS),
Block(6, BlockType.TAGS),
Block(7, BlockType.FILTERS),
),
)
}
}
/** One block of a [View]. [source] is set exactly when [type] takes one. */
data class Block(
val id: Long,
val type: BlockType,
val source: BlockSource? = null,
val width: BlockWidth = type.widths.first(),
val ignoreScope: Boolean = false,
val options: BlockOptions = BlockOptions.defaultFor(type),
) {
init {
require(options.type == type) { "Options ${options.type} on a $type block" }
}
}
/**
* These views with Home first: the stored one, or the default when it is missing,
* e.g. because its line didn't read.
*/
fun List<View>.withHomeFirst(): List<View> =
listOf(firstOrNull { it.id == View.HOME_ID } ?: View.home()) + filter { it.id != View.HOME_ID }
/** How much of a row a block takes: half-width blocks pack two to a row. */
enum class BlockWidth { HALF, FULL }
/** The kinds of block a view can hold. */
enum class BlockType(val widths: Set<BlockWidth>, val takesSource: Boolean) {
PROGRESS(setOf(BlockWidth.FULL, BlockWidth.HALF), takesSource = true),
COUNT_TILE(setOf(BlockWidth.HALF, BlockWidth.FULL), takesSource = true),
PREVIEW(setOf(BlockWidth.FULL), takesSource = true),
TASK_LIST(setOf(BlockWidth.FULL), takesSource = true),
LISTS(setOf(BlockWidth.FULL), takesSource = false),
TAGS(setOf(BlockWidth.FULL), takesSource = false),
FILTERS(setOf(BlockWidth.FULL), takesSource = false),
SECTION_HEADING(setOf(BlockWidth.FULL), takesSource = false),
WEEK_STRIP(setOf(BlockWidth.FULL), takesSource = false),
/** A preview of the completed tasks, latest first. */
RECENTLY_COMPLETED(setOf(BlockWidth.FULL), takesSource = false),
}
/** The tasks a block shows. */
sealed interface BlockSource {
data class Smart(val smart: SmartList) : BlockSource
data class List(val listId: Long) : BlockSource
/** A list of another task store, kept as stored ([ref], e.g. `OWN:3`) so it survives a switch; it shows nothing here. */
data class ListElsewhere(val ref: String) : BlockSource
data class Tag(val tag: String) : BlockSource
data class Filter(val filterId: Long) : BlockSource
data class Rules(val rule: Rule) : BlockSource
}
/** The settings of a block, one shape per [BlockType]. */
sealed interface BlockOptions {
val type: BlockType
/** [title] replaces the source's name when set. */
data class Progress(val wave: Boolean = true, val title: String? = null) : BlockOptions {
override val type get() = BlockType.PROGRESS
}
/** [color] and [icon] replace the source's own when set. */
data class CountTile(
val title: String? = null,
val color: TileColor? = null,
val icon: ViewIcon? = null,
) : BlockOptions {
override val type get() = BlockType.COUNT_TILE
}
data class Preview(
val count: Int = PREVIEW_COUNTS.first(),
val showAll: Boolean = true,
val inlineDone: Boolean = false,
) : BlockOptions {
init {
require(count in PREVIEW_COUNTS) { "Preview count $count" }
}
override val type get() = BlockType.PREVIEW
}
/** [sort] is the app's sort order when `null`. */
data class TaskList(
val sort: TaskSortOrder? = null,
val showCompleted: Boolean = true,
val inlineDone: Boolean = true,
) : BlockOptions {
override val type get() = BlockType.TASK_LIST
}
/** [accounts] limits the lists to those accounts; every account when `null`. */
data class Lists(val accounts: Set<String>? = null, val counts: Boolean = true) : BlockOptions {
init {
require(accounts == null || accounts.isNotEmpty()) { "No accounts; null means every one" }
}
override val type get() = BlockType.LISTS
}
data object Tags : BlockOptions {
override val type get() = BlockType.TAGS
}
data object Filters : BlockOptions {
override val type get() = BlockType.FILTERS
}
data class SectionHeading(val text: String = "") : BlockOptions {
override val type get() = BlockType.SECTION_HEADING
}
data object WeekStrip : BlockOptions {
override val type get() = BlockType.WEEK_STRIP
}
data class RecentlyCompleted(val count: Int = PREVIEW_COUNTS.first()) : BlockOptions {
init {
require(count in PREVIEW_COUNTS) { "Preview count $count" }
}
override val type get() = BlockType.RECENTLY_COMPLETED
}
companion object {
/** How many tasks a preview may show. */
val PREVIEW_COUNTS = listOf(3, 5, 10)
fun defaultFor(type: BlockType): BlockOptions = when (type) {
BlockType.PROGRESS -> Progress()
BlockType.COUNT_TILE -> CountTile()
BlockType.PREVIEW -> Preview()
BlockType.TASK_LIST -> TaskList()
BlockType.LISTS -> Lists()
BlockType.TAGS -> Tags
BlockType.FILTERS -> Filters
BlockType.SECTION_HEADING -> SectionHeading()
BlockType.WEEK_STRIP -> WeekStrip
BlockType.RECENTLY_COMPLETED -> RecentlyCompleted()
}
}
}
/** The tonal colour roles a count tile can take. */
enum class TileColor { PRIMARY, SECONDARY, TERTIARY, ERROR }
/** The curated icons a view (or a tile) can carry. Stored by name. */
enum class ViewIcon { HOME, WORK, PERSON, STAR, CALENDAR, LIST, FLAG, BOLT, HEART, SCHOOL, SHOPPING, FITNESS }
/** Where the app opens. */
sealed interface StartDestination {
data object LastUsed : StartDestination
data class View(val id: Long) : StartDestination
data class List(val id: Long) : StartDestination
data class Filter(val id: Long) : StartDestination
}
/** Something [layoutProblems] found wrong with a list of blocks. */
sealed interface LayoutProblem {
data class DuplicateId(val id: Long) : LayoutProblem
data class WidthNotAllowed(val blockId: Long) : LayoutProblem
data class SourceMismatch(val blockId: Long) : LayoutProblem
data object SeveralTaskLists : LayoutProblem
data object TaskListNotLast : LayoutProblem
}
/**
* What breaks the layout rules: ids repeat, a width the type doesn't allow, a
* source on a type that takes none or none where one is needed, and more than
* one task list or one that isn't the last block.
*/
fun List<Block>.layoutProblems(): List<LayoutProblem> {
val blocks = this
val taskLists = blocks.count { it.type == BlockType.TASK_LIST }
return buildList {
blocks.groupingBy { it.id }.eachCount().filterValues { it > 1 }.keys
.forEach { add(LayoutProblem.DuplicateId(it)) }
blocks.forEach { block ->
if (block.width !in block.type.widths) add(LayoutProblem.WidthNotAllowed(block.id))
if ((block.source != null) != block.type.takesSource) add(LayoutProblem.SourceMismatch(block.id))
}
if (taskLists > 1) add(LayoutProblem.SeveralTaskLists)
if (taskLists > 0 && blocks.last().type != BlockType.TASK_LIST) add(LayoutProblem.TaskListNotLast)
}
}
/**
* These blocks made to follow the layout rules: blocks with a wrong source and
* later blocks repeating an id dropped, widths a type doesn't allow made full, and only the
* first task list kept, moved to the end.
*/
fun List<Block>.normalized(): List<Block> {
val seen = HashSet<Long>()
val kept = filter { (it.source != null) == it.type.takesSource && seen.add(it.id) }
.map { if (it.width in it.type.widths) it else it.copy(width = BlockWidth.FULL) }
val taskList = kept.firstOrNull { it.type == BlockType.TASK_LIST }
return kept.filterNot { it.type == BlockType.TASK_LIST } + listOfNotNull(taskList)
}
/**
* The blocks laid out in rows: a full block alone, half blocks two by two. A half
* block followed by a full one, or by nothing, sits alone in its row.
*/
fun List<Block>.rows(): List<List<Block>> {
val rows = mutableListOf<List<Block>>()
var pending: Block? = null
for (block in this) {
val half = pending
when {
block.width == BlockWidth.FULL -> {
if (half != null) rows += listOf(half)
rows += listOf(block)
pending = null
}
half == null -> pending = block
else -> {
rows += listOf(half, block)
pending = null
}
}
}
pending?.let { rows += listOf(it) }
return rows
}
@@ -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()
@@ -82,7 +82,13 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.domain.Block
import de.jeanlucmakiola.agendula.domain.BlockOptions
import de.jeanlucmakiola.agendula.domain.BlockSource
import de.jeanlucmakiola.agendula.domain.BlockType
import de.jeanlucmakiola.agendula.domain.BlockWidth
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.rows
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
@@ -108,11 +114,13 @@ import java.time.LocalDate
import java.time.ZoneId
/**
* Home: a Today progress hero (wavy ring over tasks due today), an Overdue + All
* 2-up of tonal tiles, a live preview of the next upcoming tasks, then the user's
* lists grouped by account. Tapping a tile opens that smart list, an upcoming row
* opens that task, and the FAB starts a new task. The search action in the top bar
* slides open into a full-width field that filters every task by title.
* Home, laid out by the blocks of the active view. The Home view is a Today
* progress hero (wavy ring over tasks due today), an Overdue + All 2-up of tonal
* tiles, a live preview of the next upcoming tasks, then the user's lists grouped
* by account, tags and saved filters. Tapping a tile opens that smart list, an
* upcoming row opens that task, and the FAB starts a new task. The search action
* in the top bar slides open into a full-width field that filters every task by
* title.
*/
@Composable
fun ListsScreen(
@@ -275,7 +283,10 @@ private fun ListsContent(
bottomPadding: androidx.compose.ui.unit.Dp,
) {
// Lists get drag handles only while reordering, so the home screen stays calm.
var reordering by rememberSaveable { mutableStateOf(false) }
// Holds the id of the lists block being reordered.
var reordering by rememberSaveable { mutableStateOf<Long?>(null) }
val blocks = state.view.blocks
val rows = remember(blocks) { blocks.rows() }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(
@@ -283,150 +294,248 @@ private fun ListsContent(
bottom = bottomPadding,
),
) {
item {
TodayHero(
done = state.todayDone,
total = state.todayTotal,
onClick = { onOpenFilter(TaskFilter.Smart(SmartList.TODAY)) },
)
}
// Overdue + All sit below the Today hero as a quieter 2-up; Upcoming is no
// longer a count tile — it becomes the live preview further down.
item {
SmartPairRow(
counts = state.smartCounts.filter {
it.smart == SmartList.OVERDUE || it.smart == SmartList.ALL
},
onOpenFilter = onOpenFilter,
)
}
if (state.upcoming.isNotEmpty()) {
item { SectionHeader(stringResource(R.string.smart_upcoming)) }
item {
UpcomingPreview(
tasks = state.upcoming,
onOpenTask = onOpenTask,
onViewAll = { onOpenFilter(TaskFilter.Smart(SmartList.UPCOMING)) },
)
}
}
if (state.groups.isEmpty()) {
item { EmptyLists(onNewList = onNewList) }
} else {
item {
SectionHeader(
text = stringResource(R.string.lists_header),
action = {
IconButton(onClick = { reordering = !reordering }) {
Icon(
if (reordering) Icons.Rounded.Check else Icons.Rounded.SwapVert,
contentDescription = stringResource(
if (reordering) R.string.lists_reorder_done else R.string.lists_reorder,
),
)
}
ShapedActionButton(
shape = ActionShapes.AddList,
morphTo = ActionShapes.AddListPressed,
icon = Icons.Rounded.Add,
contentDescription = stringResource(R.string.list_add),
onClick = onNewList,
)
},
)
}
state.groups.forEach { group ->
item(key = "acct-${group.accountName}") { AccountHeader(group.accountName) }
if (reordering) {
item(key = "reorder-${group.accountName}") {
ReorderableColumn(
items = group.lists,
keyOf = { it.list.id },
onReorder = { ordered -> onReorder(ordered.map { it.list.id }) },
rowHeight = 72.dp,
) { overview, position, dragHandle, isDragging ->
GroupedRow(
title = overview.list.name,
position = position,
minHeight = 72.dp,
gapBelow = false,
container = if (isDragging) MaterialTheme.colorScheme.secondaryContainer else null,
leading = { ListColorChip(overview.list.color) },
trailing = {
Box(modifier = dragHandle.size(48.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Rounded.DragHandle,
contentDescription = stringResource(R.string.lists_reorder_handle),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
)
}
}
return@forEach
// TODO(#59): apply the view's scope once views other than Home can have one.
rows.forEach { row ->
val block = row.first()
if (block.type in TILES) {
// A full progress tile stands alone, as the Today hero always has; other tiles share a row.
if (block.type == BlockType.PROGRESS && block.width == BlockWidth.FULL) {
item { Tile(block, state, onOpenFilter, Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
} else {
item { HalfRow(row, state, onOpenFilter) }
}
itemsIndexed(group.lists, key = { _, o -> o.list.id }) { index, overview ->
return@forEach
}
when (block.type) {
BlockType.PREVIEW -> previewSection(block, state, onOpenFilter, onOpenTask)
BlockType.LISTS -> listsSection(
key = "${block.id}",
options = block.options as BlockOptions.Lists,
allGroups = state.groups,
reordering = reordering == block.id,
onToggleReorder = { reordering = if (reordering == block.id) null else block.id },
onOpenFilter = onOpenFilter,
onNewList = onNewList,
onReorder = onReorder,
)
BlockType.TAGS -> tagsSection("${block.id}", state.tags, onOpenFilter)
BlockType.FILTERS -> if (state.groups.isNotEmpty()) {
filtersSection("${block.id}", state.filters, onOpenFilter, onNewFilter)
}
// Rendered as tiles above.
BlockType.PROGRESS, BlockType.COUNT_TILE -> Unit
// TODO(#59): the rest of the catalog renders from phase 3 on.
BlockType.TASK_LIST,
BlockType.SECTION_HEADING,
BlockType.WEEK_STRIP,
BlockType.RECENTLY_COMPLETED,
-> Unit
}
}
}
}
private val TILES = setOf(BlockType.PROGRESS, BlockType.COUNT_TILE)
/** What a progress block shows: done of total for its source, or `null` for a source it can't show yet. */
private data class ProgressState(val done: Int, val total: Int, val filter: TaskFilter, val title: String?)
private fun progressFor(block: Block, state: ListsUiState.Content): ProgressState? {
val source = block.source as? BlockSource.Smart ?: return null
if (source.smart != SmartList.TODAY) return null
val title = (block.options as BlockOptions.Progress).title
return ProgressState(state.todayDone, state.todayTotal, TaskFilter.Smart(source.smart), title)
}
/** The smart count a count tile shows; `null` for a source it can't show yet. */
private fun countFor(block: Block, state: ListsUiState.Content): SmartCount? {
val source = block.source as? BlockSource.Smart ?: return null
return state.smartCounts.firstOrNull { it.smart == source.smart }
}
/** A row of tiles: two half blocks side by side, or one with an empty half beside it. */
@Composable
private fun HalfRow(row: List<Block>, state: ListsUiState.Content, onOpenFilter: (TaskFilter) -> Unit) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
row.forEach { Tile(it, state, onOpenFilter, Modifier.weight(1f)) }
if (row.size == 1 && row.single().width == BlockWidth.HALF) Spacer(Modifier.weight(1f))
}
}
/**
* A progress or count tile; an empty space for a source it can't show yet. A full
* progress tile spans the content width on its own, as the Today hero always has.
*/
@Composable
private fun Tile(
block: Block,
state: ListsUiState.Content,
onOpenFilter: (TaskFilter) -> Unit,
modifier: Modifier = Modifier,
) {
// TODO(#59): the wave switch, and a count tile's own title, colour and icon.
when (block.type) {
BlockType.PROGRESS -> progressFor(block, state)?.let { progress ->
TodayHero(progress, onClick = { onOpenFilter(progress.filter) }, modifier = modifier)
}
BlockType.COUNT_TILE -> countFor(block, state)?.let { count ->
SmartCard(count = count, modifier = modifier, onClick = { onOpenFilter(TaskFilter.Smart(count.smart)) })
}
else -> null
} ?: Spacer(modifier)
}
/** A preview of the source's next tasks, under its heading; nothing while there are none. */
private fun LazyListScope.previewSection(
block: Block,
state: ListsUiState.Content,
onOpenFilter: (TaskFilter) -> Unit,
onOpenTask: (Task) -> Unit,
) {
// TODO(#59): sources beyond the smart lists, and inline done.
val smart = (block.source as? BlockSource.Smart)?.smart ?: return
val options = block.options as BlockOptions.Preview
val tasks = state.previews[block.id].orEmpty()
if (tasks.isEmpty()) return
item { SectionHeader(stringResource(smartStyle(smart).labelRes)) }
item {
UpcomingPreview(
tasks = tasks,
onOpenTask = onOpenTask,
onViewAll = if (options.showAll) ({ onOpenFilter(TaskFilter.Smart(smart)) }) else null,
)
}
}
/** The user's lists by account, reorderable in place, or the way to make the first one. */
private fun LazyListScope.listsSection(
key: String,
options: BlockOptions.Lists,
allGroups: List<AccountGroup>,
reordering: Boolean,
onToggleReorder: () -> Unit,
onOpenFilter: (TaskFilter) -> Unit,
onNewList: () -> Unit,
onReorder: (List<Long>) -> Unit,
) {
if (allGroups.isEmpty()) {
item { EmptyLists(onNewList = onNewList) }
return
}
val groups = options.accounts?.let { accounts -> allGroups.filter { it.accountName in accounts } } ?: allGroups
if (groups.isEmpty()) return
item {
SectionHeader(
text = stringResource(R.string.lists_header),
action = {
IconButton(onClick = onToggleReorder) {
Icon(
if (reordering) Icons.Rounded.Check else Icons.Rounded.SwapVert,
contentDescription = stringResource(
if (reordering) R.string.lists_reorder_done else R.string.lists_reorder,
),
)
}
ShapedActionButton(
shape = ActionShapes.AddList,
morphTo = ActionShapes.AddListPressed,
icon = Icons.Rounded.Add,
contentDescription = stringResource(R.string.list_add),
onClick = onNewList,
)
},
)
}
groups.forEach { group ->
item(key = "$key-acct-${group.accountName}") { AccountHeader(group.accountName) }
if (reordering) {
item(key = "$key-reorder-${group.accountName}") {
ReorderableColumn(
items = group.lists,
keyOf = { it.list.id },
onReorder = { ordered -> onReorder(ordered.map { it.list.id }) },
rowHeight = 72.dp,
) { overview, position, dragHandle, isDragging ->
GroupedRow(
title = overview.list.name,
position = positionOf(index, group.lists.size),
position = position,
minHeight = 72.dp,
gapBelow = false,
container = if (isDragging) MaterialTheme.colorScheme.secondaryContainer else null,
leading = { ListColorChip(overview.list.color) },
trailing = {
if (overview.openCount > 0) {
Text(
overview.openCount.toString(),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
Box(modifier = dragHandle.size(48.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Rounded.DragHandle,
contentDescription = stringResource(R.string.lists_reorder_handle),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
onClick = { onOpenFilter(TaskFilter.OfList(overview.list.id)) },
)
}
}
return@forEach
}
if (state.tags.isNotEmpty()) {
item(key = "tags-header") { SectionHeader(stringResource(R.string.tags_header)) }
itemsIndexed(state.tags, key = { _, t -> "tag-${t.tag}" }) { index, overview ->
GroupedRow(
title = overview.tag,
position = positionOf(index, state.tags.size),
leading = {
Icon(
Icons.Rounded.Sell,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
trailing = {
itemsIndexed(group.lists, key = { _, o -> "$key-list-${o.list.id}" }) { index, overview ->
GroupedRow(
title = overview.list.name,
position = positionOf(index, group.lists.size),
minHeight = 72.dp,
leading = { ListColorChip(overview.list.color) },
trailing = {
if (options.counts && overview.openCount > 0) {
Text(
overview.openCount.toString(),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
onClick = { onOpenFilter(TaskFilter.Tagged(overview.tag)) },
)
}
}
},
onClick = { onOpenFilter(TaskFilter.OfList(overview.list.id)) },
)
}
}
}
if (state.groups.isNotEmpty()) {
filtersSection(state.filters, onOpenFilter, onNewFilter)
}
/** Each tag on an open task with its count; nothing while there are none. */
private fun LazyListScope.tagsSection(key: String, tags: List<TagOverview>, onOpenFilter: (TaskFilter) -> Unit) {
if (tags.isEmpty()) return
item(key = "$key-tags-header") { SectionHeader(stringResource(R.string.tags_header)) }
itemsIndexed(tags, key = { _, t -> "$key-tag-${t.tag}" }) { index, overview ->
GroupedRow(
title = overview.tag,
position = positionOf(index, tags.size),
leading = {
Icon(
Icons.Rounded.Sell,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
trailing = {
Text(
overview.openCount.toString(),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
onClick = { onOpenFilter(TaskFilter.Tagged(overview.tag)) },
)
}
}
/** The saved filters, or a single row offering the first one. */
private fun LazyListScope.filtersSection(
key: String,
filters: List<FilterOverview>,
onOpenFilter: (TaskFilter) -> Unit,
onNewFilter: () -> Unit,
) {
item(key = "filters-header") {
item(key = "$key-filters-header") {
SectionHeader(
text = stringResource(R.string.filters_header),
action = if (filters.isEmpty()) {
@@ -441,7 +550,7 @@ private fun LazyListScope.filtersSection(
)
}
if (filters.isEmpty()) {
item(key = "filters-empty") {
item(key = "$key-filters-empty") {
GroupedRow(
title = stringResource(R.string.filter_new_title),
summary = stringResource(R.string.filters_empty_hint),
@@ -452,7 +561,7 @@ private fun LazyListScope.filtersSection(
}
return
}
itemsIndexed(filters, key = { _, f -> "filter-${f.filter.id}" }) { index, overview ->
itemsIndexed(filters, key = { _, f -> "$key-filter-${f.filter.id}" }) { index, overview ->
GroupedRow(
title = overview.filter.name,
position = positionOf(index, filters.size),
@@ -634,7 +743,12 @@ private fun SearchResults(
*/
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun TodayHero(done: Int, total: Int, onClick: () -> Unit) {
private fun TodayHero(
progress: ProgressState,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val (done, total) = progress
val interaction = remember { MutableInteractionSource() }
val pressed by interaction.collectIsPressedAsState()
val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "todayCorner")
@@ -645,7 +759,7 @@ private fun TodayHero(done: Int, total: Int, onClick: () -> Unit) {
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
interactionSource = interaction,
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(140.dp),
modifier = modifier.height(140.dp),
) {
Row(
modifier = Modifier.fillMaxSize().padding(20.dp),
@@ -661,7 +775,7 @@ private fun TodayHero(done: Int, total: Int, onClick: () -> Unit) {
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(Icons.Rounded.Today, contentDescription = null, modifier = Modifier.size(20.dp))
Text(stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium)
Text(progress.title ?: stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium)
}
val headline = when {
total == 0 -> stringResource(R.string.home_today_empty)
@@ -692,30 +806,12 @@ private fun TodayHero(done: Int, total: Int, onClick: () -> Unit) {
}
}
/** Overdue + All as a 2-up row of the existing tonal tiles. */
@Composable
private fun SmartPairRow(counts: List<SmartCount>, onOpenFilter: (TaskFilter) -> Unit) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
counts.forEach { smart ->
SmartCard(
count = smart,
modifier = Modifier.weight(1f),
onClick = { onOpenFilter(TaskFilter.Smart(smart.smart)) },
)
}
if (counts.size == 1) Spacer(Modifier.weight(1f))
}
}
/** A grouped card previewing the next few upcoming tasks, with a "view all" tail. */
@Composable
private fun UpcomingPreview(
tasks: List<Task>,
onOpenTask: (Task) -> Unit,
onViewAll: () -> Unit,
onViewAll: (() -> Unit)?,
) {
Surface(
shape = RoundedCornerShape(22.dp),
@@ -726,24 +822,29 @@ private fun UpcomingPreview(
tasks.forEach { task ->
UpcomingRow(task = task, onClick = { onOpenTask(task) })
}
Surface(onClick = onViewAll, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
stringResource(R.string.home_upcoming_view_all),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.weight(1f))
Icon(
Icons.Rounded.ChevronRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
}
}
if (onViewAll != null) ViewAllRow(onViewAll)
}
}
}
@Composable
private fun ViewAllRow(onViewAll: () -> Unit) {
Surface(onClick = onViewAll, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
stringResource(R.string.home_upcoming_view_all),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.weight(1f))
Icon(
Icons.Rounded.ChevronRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
@@ -9,6 +9,10 @@ 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.BlockOptions
import de.jeanlucmakiola.agendula.domain.BlockSource
import de.jeanlucmakiola.agendula.domain.BlockType
import de.jeanlucmakiola.agendula.domain.RuleClock
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
@@ -16,6 +20,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskFiltering
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.UpcomingRange
import de.jeanlucmakiola.agendula.domain.View
import de.jeanlucmakiola.agendula.domain.tagsInUse
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -26,6 +31,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
@@ -93,18 +99,30 @@ sealed interface ListsUiState {
/** Completed vs. total tasks *due today* — drives the progress ring. */
val todayDone: Int,
val todayTotal: Int,
/** The next few open tasks (due tomorrow onward) for the inline preview. */
val upcoming: List<Task>,
/** What each preview block of [view] shows, by block id. */
val previews: Map<Long, List<Task>>,
/** Every task (open and completed) — the corpus the home search filters. */
val allTasks: List<Task>,
/** Each tag on an open task, alphabetically. */
val tags: List<TagOverview> = emptyList(),
/** The saved filters, oldest first. */
val filters: List<FilterOverview> = emptyList(),
/** The view these are laid out by. */
val view: View = View.home(),
) : ListsUiState
}
private const val UPCOMING_PREVIEW = 3
/**
* The tasks each preview block of this view shows, by block id: the first of
* [upcoming] for a preview of Upcoming. Other sources show nothing yet.
*/
internal fun View.previews(upcoming: Sequence<Task>): Map<Long, List<Task>> {
val counts = blocks
.filter { it.type == BlockType.PREVIEW && it.source == BlockSource.Smart(SmartList.UPCOMING) }
.associate { it.id to (it.options as BlockOptions.Preview).count }
val next = upcoming.take(counts.values.maxOrNull() ?: 0).toList()
return counts.mapValues { (_, count) -> next.take(count) }
}
/** The home overview: smart lists with live counts, then user lists by account. */
@HiltViewModel
@@ -146,10 +164,16 @@ 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,
// For now Home is always the view shown.
settingsPrefs.views.map { views -> views.first { it.id == View.HOME_ID } }.distinctUntilChanged(),
) { (hidden, range), weekStart, view -> Triple(hidden, range, weekStart) to view },
settingsPrefs.savedFilters,
) { lists, openTasks, completedTasks, (hidden, upcomingRange), filters ->
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters) as ListsUiState
) { lists, openTasks, completedTasks, (settings, view), filters ->
val (hidden, upcomingRange, weekStart) = settings
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart, view) as ListsUiState
}.recoveringFromProviderFailure { ListsUiState.Failure }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
@@ -160,6 +184,8 @@ class ListsViewModel @Inject constructor(
hidden: Set<Long>,
upcomingRange: UpcomingRange,
savedFilters: List<SavedFilter>,
weekStart: DayOfWeek,
view: View,
): ListsUiState.Content {
val now = Clock.System.now()
val zone = ZoneId.systemDefault()
@@ -191,9 +217,7 @@ class ListsViewModel @Inject constructor(
// Upcoming preview: the next handful of open tasks due tomorrow onward,
// already sorted by the repository's default ordering.
val upcoming = smartTopLevel
.filter { inSmart(it, SmartList.UPCOMING) }
.take(UPCOMING_PREVIEW)
val upcoming = smartTopLevel.asSequence().filter { inSmart(it, SmartList.UPCOMING) }
val openByList = topLevel.groupingBy { it.listId }.eachCount()
val groups = lists
.groupBy { it.accountName }
@@ -212,19 +236,24 @@ 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(
view = view,
smartCounts = smartCounts,
filters = filters,
groups = groups,
todayDone = completedToday,
todayTotal = todayTotal,
upcoming = upcoming,
previews = view.previews(upcoming),
allTasks = allTasks,
tags = tags,
)
@@ -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>()) }
+1
View File
@@ -308,6 +308,7 @@
<string name="filter_delete_body">Only the filter goes. Its tasks stay where they are.</string>
<string name="filter_delete_confirm">Delete</string>
<string name="filter_missing">Filter deleted</string>
<string name="filter_rules_not_editable">This filter uses rules that can’t be edited here yet. You can still rename or delete it.</string>
<string name="new_task">New task</string>
<string name="lists_failure">Could not read your tasks.</string>
<string name="lists_empty">No task lists yet.</string>
@@ -7,6 +7,7 @@ import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.SavedFilter
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
@@ -55,22 +56,22 @@ class ForgetDeletedListsTest {
@Test
fun `a saved filter drops a deleted list, so a list given its id later is not in it`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.OWN)
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", listIds = setOf(1L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", criteria = FilterCriteria(listIds = setOf(1L))))
prefs.forgetDeletedLists(listOf(1L), StorageMode.OWN)
val filters = prefs.savedFilters.first().associate { it.name to it.listIds }
val filters = prefs.savedFilters.first().associate { it.name to it.criteria!!.listIds }
assertThat(filters).containsExactly("Both", setOf(2L), "Gone", emptySet<Long>())
}
@Test
fun `a read of the lists drops the gone ones from the saved filters`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.OWN)
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
prefs.forgetListsExcept(StorageMode.OWN, null, setOf(2L, 3L))
assertThat(prefs.savedFilters.first().single().listIds).containsExactly(2L)
assertThat(prefs.savedFilters.first().single().criteria!!.listIds).containsExactly(2L)
}
}
@@ -1,30 +1,90 @@
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%",
@Test
fun `the stored line stays byte for byte, and its rule reads back through the rule codec`() {
val rule = Rule.AllOf(
listOf(
Rule.AnyOf(listOf(Rule.InList(setOf(4L, 2L), setOf("EXTERNAL:7")), Rule.HasTag("a b,c"))),
Rule.Not(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))),
Rule.MinPriority(Priority.HIGH),
Rule.Due(DueSpec.ThisWeek),
Rule.Due(DueSpec.NextDays(7)),
),
)
val text = "and(or(list(OWN%3A2,OWN%3A4,EXTERNAL%3A7),tag(a+b%2Cc)),not(due(NO_DATE)),prio(HIGH),range(week),range(next,7))"
assertThat(SavedFilterCodec.upsert(null, SavedFilter(3, "Work | x", rule), "OWN")).isEqualTo("v2|3|Work+%7C+x|$text")
assertThat(RuleCodec.encode(rule, "OWN")).isEqualTo(text)
assertThat(RuleCodec.decode(text, "OWN")).isEqualTo(rule)
// The rule codec prunes nothing; the saved filter drops an empty top-level list condition itself.
assertThat(RuleCodec.decode("list()", "OWN")).isEqualTo(Rule.InList(emptySet()))
assertThat(SavedFilterCodec.decode("v2|1|x|list()", "OWN").single().rule).isEqualTo(Rule.Everything)
// A ref of this store that names no id is kept as it is.
assertThat(RuleCodec.decode("list(OWN%3Aabc,OWN%3A3)", "OWN")).isEqualTo(Rule.InList(setOf(3L), setOf("OWN:abc")))
}
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 +97,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 +128,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 +147,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("|")
@@ -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)
}
}
@@ -0,0 +1,167 @@
package de.jeanlucmakiola.agendula.data.prefs
import androidx.datastore.preferences.core.preferencesOf
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.domain.Block
import de.jeanlucmakiola.agendula.domain.BlockOptions
import de.jeanlucmakiola.agendula.domain.BlockSource
import de.jeanlucmakiola.agendula.domain.BlockType
import de.jeanlucmakiola.agendula.domain.BlockWidth
import de.jeanlucmakiola.agendula.domain.DueSpec
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.Rule
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
import de.jeanlucmakiola.agendula.domain.TileColor
import de.jeanlucmakiola.agendula.domain.View
import de.jeanlucmakiola.agendula.domain.ViewIcon
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
class ViewCodecTest {
private val rule = Rule.AllOf(
listOf(
Rule.AnyOf(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next, action|(x)"))),
Rule.Not(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))),
Rule.MinPriority(Priority.HIGH),
Rule.Due(DueSpec.NextDays(7)),
),
)
private val everyBlock = listOf(
Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY), BlockWidth.HALF, options = BlockOptions.Progress(wave = false, title = "Mine | today; a=b")),
Block(2, BlockType.COUNT_TILE, BlockSource.List(9), BlockWidth.HALF, ignoreScope = true, options = BlockOptions.CountTile("Tile", TileColor.TERTIARY, ViewIcon.BOLT)),
Block(3, BlockType.COUNT_TILE, BlockSource.Tag("größe,x"), BlockWidth.FULL),
Block(4, BlockType.PREVIEW, BlockSource.Filter(12), options = BlockOptions.Preview(count = 10, showAll = false, inlineDone = true)),
Block(5, BlockType.LISTS, options = BlockOptions.Lists(accounts = setOf("me@example.org", "a,b;c"), counts = false)),
Block(6, BlockType.TAGS),
Block(7, BlockType.FILTERS),
Block(8, BlockType.SECTION_HEADING, options = BlockOptions.SectionHeading("Work = 100%")),
Block(9, BlockType.WEEK_STRIP, ignoreScope = true),
Block(10, BlockType.RECENTLY_COMPLETED, options = BlockOptions.RecentlyCompleted(5)),
Block(11, BlockType.TASK_LIST, BlockSource.Rules(rule), options = BlockOptions.TaskList(TaskSortOrder.PRIORITY, showCompleted = false, inlineDone = false)),
)
private val views = listOf(
View.home(),
View(id = 2, name = "Work | stuff\nmore", icon = ViewIcon.WORK, scope = rule, blocks = everyBlock, quickAdd = false),
View(id = 3, name = "Empty", icon = ViewIcon.STAR, scope = Rule.Everything, blocks = emptyList()),
)
@Test
fun `views round-trip with every block, source and option`() {
val raw = ViewCodec.encode(views, "OWN")
assertThat(raw.lines().first()).isEqualTo("v1")
assertThat(ViewCodec.decode(raw, "OWN")).isEqualTo(views)
}
@Test
fun `default options round-trip for every type`() {
val blocks = BlockType.entries.mapIndexed { i, type ->
Block(i + 1L, type, if (type.takesSource) BlockSource.Smart(SmartList.ALL) else null, type.widths.first())
}.let { it.filterNot { b -> b.type == BlockType.TASK_LIST } + it.single { b -> b.type == BlockType.TASK_LIST } }
val view = View(1, "x", ViewIcon.HOME, null, blocks)
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
}
@Test
fun `another store's lists read as theirs only, and survive a rewrite there`() {
val raw = ViewCodec.encode(views, "OWN")
val external = ViewCodec.decode(raw, "EXTERNAL")
assertThat(external[1].blocks.single { it.id == 2L }.source).isEqualTo(BlockSource.ListElsewhere("OWN:9"))
val scope = external[1].scope as Rule.AllOf
assertThat((scope.children[0] as Rule.AnyOf).children[0]).isEqualTo(Rule.InList(setOf(7L), setOf("OWN:2")))
assertThat(ViewCodec.decode(ViewCodec.encode(external, "EXTERNAL"), "OWN")).isEqualTo(views)
}
@Test
fun `an empty title reads as none`() {
val raw = "v1\nview|1|x|HOME|1|\nblock|1|PROGRESS|FULL|0|smart:TODAY|wave=1;title=\nblock|2|COUNT_TILE|HALF|0|smart:ALL|title=+"
val blocks = ViewCodec.decode(raw, "OWN").single().blocks
assertThat(blocks.map { it.options }).containsExactly(BlockOptions.Progress(), BlockOptions.CountTile()).inOrder()
}
@Test
fun `rules are stored in the saved filters' grammar`() {
val view = View(5, "x", ViewIcon.HOME, Rule.AllOf(listOf(Rule.HasTag("a b"), Rule.InList(setOf(3L)))), emptyList())
assertThat(ViewCodec.encode(listOf(view), "OWN").lines()[1]).isEqualTo("view|5|x|HOME|1|and(tag(a+b),list(OWN%3A3))")
}
@Test
fun `an account without a name and a list id that isn't one survive`() {
val view = View(1, "x", ViewIcon.HOME, null, listOf(Block(1, BlockType.LISTS, options = BlockOptions.Lists(accounts = setOf("")))))
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
val odd = ViewCodec.decode("v1\nview|1|x|HOME|1|\nblock|4|COUNT_TILE|HALF|0|list:OWN%3Aabc|", "OWN").single()
assertThat(odd.blocks.single().source).isEqualTo(BlockSource.ListElsewhere("OWN:abc"))
}
@Test
fun `a rule reads back exactly as written, with no saved-filter pruning`() {
val scopes = listOf(
Rule.InList(emptySet()),
Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.HasTag("x"))),
Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.InList(emptySet(), setOf("EXTERNAL:7")))),
Rule.InList(setOf(3L), setOf("OWN:abc")),
)
scopes.forEachIndexed { i, scope ->
val view = View(i + 1L, "x", ViewIcon.HOME, scope, listOf(Block(1, BlockType.TASK_LIST, BlockSource.Rules(scope))))
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
}
}
@Test
fun `nothing stored, or another version, reads as no views`() {
assertThat(ViewCodec.decode(null, "OWN")).isEmpty()
assertThat(ViewCodec.decode("", "OWN")).isEmpty()
assertThat(ViewCodec.decode("v2\nview|1|x|HOME|1|", "OWN")).isEmpty()
assertThat(ViewCodec.decode("view|1|x|HOME|1|", "OWN")).isEmpty()
}
@Test
fun `lines that don't read are skipped, with their blocks`() {
val raw = listOf(
"v1",
"view|1|Home|HOME|1|",
"block|1|TAGS|FULL|0||",
"block|2|NOPE|FULL|0||",
"block|3|PREVIEW|FULL|0|smart:NOPE|",
"block|4|PREVIEW|FULL|0|rules:and(|",
"block|x|FILTERS|FULL|0||",
"garbage",
"block|5|FILTERS|FULL|0||",
"view|x|Broken|HOME|1|",
"block|6|TAGS|FULL|0||",
"view|2|Odd|NOPE|0|and(",
"view|3|Fine|NOPE|0|",
"block|7|COUNT_TILE|WIDE|0|smart:ALL|count=x;color=PINK",
"block|8|PREVIEW|HALF|0|smart:UPCOMING|count=4;showAll=0",
"block|9|LISTS|FULL|0|smart:ALL|",
"view|1|Again|HOME|1|",
).joinToString("\n")
val decoded = ViewCodec.decode(raw, "OWN")
assertThat(decoded.map { it.id }).containsExactly(1L, 3L).inOrder()
assertThat(decoded[0].blocks.map { it.id }).containsExactly(1L, 5L).inOrder()
val fine = decoded[1]
assertThat(fine.icon).isEqualTo(ViewIcon.HOME)
assertThat(fine.quickAdd).isFalse()
// An unknown width or value falls back; a block with a source its type doesn't take drops out.
assertThat(fine.blocks).containsExactly(
Block(7, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF),
Block(8, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(showAll = false)),
).inOrder()
}
@Test
fun `the migration stores Home once, and only when there are no views`() = runBlocking {
assertThat(ViewsMigration.shouldMigrate(preferencesOf())).isTrue()
val migrated = ViewsMigration.migrate(preferencesOf())
assertThat(ViewCodec.decode(migrated[ViewsMigration.KEY], "OWN")).containsExactly(View.home())
assertThat(ViewsMigration.shouldMigrate(migrated)).isFalse()
assertThat(ViewsMigration.migrate(preferencesOf())).isEqualTo(migrated)
val stored = preferencesOf(ViewsMigration.KEY to ViewCodec.encode(views.drop(1), "OWN"))
assertThat(ViewsMigration.shouldMigrate(stored)).isFalse()
}
}
@@ -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()
}
@@ -0,0 +1,109 @@
package de.jeanlucmakiola.agendula.domain
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class ViewTest {
private fun half(id: Long) = Block(id, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF)
private fun full(id: Long) = Block(id, BlockType.TAGS)
private fun taskList(id: Long) = Block(id, BlockType.TASK_LIST, BlockSource.Smart(SmartList.TODAY))
@Test
fun `home is the 1_4 home in its order`() {
val home = View.home()
assertThat(home.scope).isNull()
assertThat(home.quickAdd).isTrue()
assertThat(home.problems).isEmpty()
assertThat(home.blocks.rows().map { row -> row.map { it.type to it.source } }).containsExactly(
listOf(BlockType.PROGRESS to BlockSource.Smart(SmartList.TODAY)),
listOf(
BlockType.COUNT_TILE to BlockSource.Smart(SmartList.OVERDUE),
BlockType.COUNT_TILE to BlockSource.Smart(SmartList.ALL),
),
listOf(BlockType.PREVIEW to BlockSource.Smart(SmartList.UPCOMING)),
listOf(BlockType.LISTS to null),
listOf(BlockType.TAGS to null),
listOf(BlockType.FILTERS to null),
).inOrder()
assertThat((home.blocks[3].options as BlockOptions.Preview)).isEqualTo(BlockOptions.Preview(count = 3, showAll = true))
}
@Test
fun `half blocks pack two to a row, a lone one sits alone`() {
val blocks = listOf(half(1), half(2), half(3), full(4), half(5), half(6), half(7))
assertThat(blocks.rows().map { row -> row.map { it.id } }).containsExactly(
listOf(1L, 2L),
listOf(3L),
listOf(4L),
listOf(5L, 6L),
listOf(7L),
).inOrder()
assertThat(emptyList<Block>().rows()).isEmpty()
}
@Test
fun `options must match the type`() {
assertThrows<IllegalArgumentException> { Block(1, BlockType.TAGS, options = BlockOptions.Filters) }
assertThrows<IllegalArgumentException> { BlockOptions.Preview(count = 4) }
BlockType.entries.forEach { assertThat(BlockOptions.defaultFor(it).type).isEqualTo(it) }
}
@Test
fun `layout problems name what breaks the rules`() {
val blocks = listOf(
taskList(1),
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), BlockWidth.HALF),
Block(2, BlockType.LISTS, BlockSource.Smart(SmartList.ALL)),
Block(4, BlockType.PROGRESS),
taskList(5),
full(6),
)
assertThat(blocks.layoutProblems()).containsExactly(
LayoutProblem.DuplicateId(2),
LayoutProblem.WidthNotAllowed(2),
LayoutProblem.SourceMismatch(2),
LayoutProblem.SourceMismatch(4),
LayoutProblem.SeveralTaskLists,
LayoutProblem.TaskListNotLast,
)
assertThat(listOf(half(1), half(2), taskList(3)).layoutProblems()).isEmpty()
}
@Test
fun `normalising fixes what layout problems find`() {
val blocks = listOf(
taskList(1),
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), BlockWidth.HALF),
Block(2, BlockType.TAGS),
Block(4, BlockType.PROGRESS),
taskList(5),
full(6),
)
val normalized = blocks.normalized()
assertThat(normalized.map { it.id }).containsExactly(2L, 6L, 1L).inOrder()
assertThat(normalized[0].width).isEqualTo(BlockWidth.FULL)
assertThat(normalized.layoutProblems()).isEmpty()
assertThat(View.home().blocks.normalized()).isEqualTo(View.home().blocks)
// A block dropped for its source doesn't take its id with it.
assertThat(listOf(Block(5, BlockType.LISTS, BlockSource.Smart(SmartList.ALL)), full(5)).normalized())
.containsExactly(full(5))
}
@Test
fun `a block takes its type's first width unless told`() {
assertThat(Block(1, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL)).width).isEqualTo(BlockWidth.HALF)
assertThat(Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY)).width).isEqualTo(BlockWidth.FULL)
assertThrows<IllegalArgumentException> { BlockOptions.Lists(accounts = emptySet()) }
}
@Test
fun `home comes first, the default standing in when it is missing`() {
val work = View(2, "Work", ViewIcon.WORK, null, emptyList())
val mine = View.home().copy(name = "Mine")
assertThat(listOf(work, mine).withHomeFirst()).containsExactly(mine, work).inOrder()
assertThat(listOf(work).withHomeFirst()).containsExactly(View.home(), work).inOrder()
assertThat(emptyList<View>().withHomeFirst()).containsExactly(View.home())
}
}
@@ -0,0 +1,35 @@
package de.jeanlucmakiola.agendula.ui.lists
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.domain.Block
import de.jeanlucmakiola.agendula.domain.BlockOptions
import de.jeanlucmakiola.agendula.domain.BlockSource
import de.jeanlucmakiola.agendula.domain.BlockType
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.View
import de.jeanlucmakiola.agendula.domain.testTask
import org.junit.jupiter.api.Test
class HomePreviewsTest {
private val upcoming = (1L..12L).map { testTask(id = it) }
@Test
fun `home previews the next three upcoming tasks, as 1_4 did`() {
assertThat(View.home().previews(upcoming.asSequence())).containsExactly(4L, upcoming.take(3))
}
@Test
fun `each Upcoming preview takes its own count, other sources show nothing yet`() {
val view = View.home().copy(
blocks = listOf(
Block(1, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 5)),
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 10)),
Block(3, BlockType.PREVIEW, BlockSource.Smart(SmartList.TODAY)),
),
)
assertThat(view.previews(upcoming.asSequence())).containsExactly(1L, upcoming.take(5), 2L, upcoming.take(10))
assertThat(view.previews(emptySequence())).containsExactly(1L, emptyList<Task>(), 2L, emptyList<Task>())
}
}