Compare commits

..
14 changed files with 1294 additions and 259 deletions

No files matched your search

@@ -13,6 +13,7 @@ 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
@@ -49,7 +50,7 @@ internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreference
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
name = "agendula_prefs",
corruptionHandler = replaceCorrupted(),
produceMigrations = { listOf(SavedFilterMigration) },
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,6 +1,5 @@
package de.jeanlucmakiola.agendula.data.prefs
import de.jeanlucmakiola.agendula.domain.DueSpec
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.FilterCriteria
import de.jeanlucmakiola.agendula.domain.Priority
@@ -14,12 +13,10 @@ import java.net.URLDecoder
import java.net.URLEncoder
/**
* Stored form of the saved filters: one line per filter, `v2|id|name|rule`.
* The rule is written as nested calls: `and(…)`, `or(…)`, `not(…)`,
* `list(OWN%3A3,…)`, `tag(…)`, `prio(HIGH)`, `due(TODAY)` and
* `range(week|month)` or `range(next,7)`. Names, tags and list refs are
* URL-encoded, and list ids are qualified by the store they belong to
* (`OWN:3`), since each store numbers its lists on its own.
* 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]
@@ -95,15 +92,18 @@ internal object SavedFilterCodec {
private fun splitList(value: String): List<String> = value.split(',').filter { it.isNotEmpty() }
private fun encodeLine(filter: SavedFilter, mode: String): String =
listOf(V2, filter.id.toString(), encode(filter.name), encodeRule(filter.rule, mode)).joinToString("|")
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 top-level list condition with none of its lists readable drops out, as a flat filter's did.
val rule = RuleParser(f[3], mode).parse().withoutLists { false }
// 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)
}
@@ -129,80 +129,6 @@ internal object SavedFilterCodec {
return here.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet() to elsewhere.toSet()
}
private fun encodeRule(rule: Rule, mode: String): String = when (rule) {
is Rule.AllOf -> "and(${rule.children.joinToString(",") { encodeRule(it, mode) }})"
is Rule.AnyOf -> "or(${rule.children.joinToString(",") { encodeRule(it, mode) }})"
is Rule.Not -> "not(${encodeRule(rule.child, mode)})"
is Rule.InList -> {
val refs = rule.listIds.sorted().map { "$mode:$it" } + rule.elsewhere.sorted()
"list(${refs.joinToString(",") { encode(it) }})"
}
is Rule.HasTag -> "tag(${encode(rule.tag)})"
is Rule.MinPriority -> "prio(${rule.priority.name})"
is Rule.Due -> when (val spec = rule.spec) {
is DueSpec.Window -> "due(${spec.window.name})"
DueSpec.ThisWeek -> "range(week)"
DueSpec.ThisMonth -> "range(month)"
is DueSpec.NextDays -> "range(next,${spec.days})"
}
}
/** Reads what [encodeRule] writes; throws on anything else. */
private class RuleParser(private val text: String, private val mode: String) {
private var at = 0
fun parse(): Rule = rule().also { require(at == text.length) { "Trailing input at $at" } }
private fun rule(): Rule {
val name = atom()
expect('(')
val rule = when (name) {
"and" -> Rule.AllOf(list(::rule))
"or" -> Rule.AnyOf(list(::rule))
"not" -> Rule.Not(rule())
"list" -> splitRefs(list(::atom).map(::decode), mode).let { (here, elsewhere) -> Rule.InList(here, elsewhere) }
"tag" -> Rule.HasTag(decode(atom()))
"prio" -> Rule.MinPriority(Priority.valueOf(atom()))
"due" -> Rule.Due(DueSpec.Window(DueWindow.valueOf(atom())))
"range" -> Rule.Due(range(list(::atom)))
else -> throw IllegalArgumentException("Unknown rule $name")
}
expect(')')
return rule
}
private fun range(args: List<String>): DueSpec.Range = when {
args == listOf("week") -> DueSpec.ThisWeek
args == listOf("month") -> DueSpec.ThisMonth
args.size == 2 && args[0] == "next" -> DueSpec.NextDays(args[1].toInt())
else -> throw IllegalArgumentException("Unknown range $args")
}
/** Comma-separated [item]s up to the closing parenthesis, which stays unread. */
private fun <T> list(item: () -> T): List<T> {
if (peek() == ')') return emptyList()
val items = mutableListOf(item())
while (peek() == ',') {
at++
items += item()
}
return items
}
private fun atom(): String {
val start = at
while (at < text.length && text[at] !in "(),") at++
return text.substring(start, at)
}
private fun peek(): Char? = text.getOrNull(at)
private fun expect(c: Char) {
require(peek() == c) { "Expected $c at $at" }
at++
}
}
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
private fun decode(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
@@ -32,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
@@ -39,11 +41,13 @@ 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
@@ -618,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 }
}
@@ -661,6 +677,7 @@ class SettingsPrefs @Inject constructor(
val GROUPINGS = stringSetPreferencesKey("task_groupings")
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
}
@@ -136,6 +136,9 @@ fun DueSpec.matches(task: Task, clock: RuleClock): Boolean = when (this) {
* 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)
@@ -149,7 +152,8 @@ fun Rule.withoutLists(gone: (Long) -> Boolean): Rule {
private fun Rule.isEmptyList(): Boolean = this is Rule.InList && listIds.isEmpty() && elsewhere.isEmpty()
private fun Rule.withoutListIds(gone: (Long) -> Boolean): Rule = mapLists { list ->
/** 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) }
}
@@ -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
}
@@ -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,9 @@ 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
@@ -17,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
@@ -95,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
@@ -151,10 +167,13 @@ class ListsViewModel @Inject constructor(
combine(
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
settingsPrefs.firstDayOfWeek,
) { (hidden, range), weekStart -> Triple(hidden, range, weekStart) },
// 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, weekStart), filters ->
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart) 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)
@@ -166,6 +185,7 @@ class ListsViewModel @Inject constructor(
upcomingRange: UpcomingRange,
savedFilters: List<SavedFilter>,
weekStart: DayOfWeek,
view: View,
): ListsUiState.Content {
val now = Clock.System.now()
val zone = ZoneId.systemDefault()
@@ -197,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 }
@@ -229,12 +247,13 @@ class ListsViewModel @Inject constructor(
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,
)
@@ -14,6 +14,28 @@ import org.junit.jupiter.api.Test
class SavedFilterCodecTest {
@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),
@@ -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()
}
}
@@ -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>())
}
}