From e1a81682ac6beca6133746d6b7169af0f6ae563b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:37:41 +0100 Subject: [PATCH 01/16] Simple filter form with all/any and is/is not, read back from the rule tree (#172) --- .../agendula/ui/filters/SimpleRule.kt | 195 ++++++++++++++++++ .../agendula/ui/filters/SimpleRuleTest.kt | 162 +++++++++++++++ 2 files changed, 357 insertions(+) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRuleTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt new file mode 100644 index 0000000..ea4497d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt @@ -0,0 +1,195 @@ +package de.jeanlucmakiola.agendula.ui.filters + +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.TagMatch + +/** How the conditions of a group combine: every one ([ALL]) or at least one ([ANY]). */ +enum class Match { ALL, ANY } + +/** + * A rule as the simple editor shows it: up to four criteria joined by [match], + * each of which can be turned round with *is not*. An empty criterion doesn't + * narrow: no [due] means any due date, no lists any list, no [tags] any tag, + * [Priority.NONE] any priority. + * + * [toRule] writes, in this order, the criteria that narrow: + * - due: `or(due…)` over [due], under `not(…)` when [dueNegated]; + * - lists: `list(…)`, under `not(…)` when [listsNegated]; + * - priority: `prio(…)`; + * - tags: `or(tag…)`, or `and(tag…)` for [TagMatch.ALL], under `not(…)` when [tagsNegated]; + * + * all inside `and(…)` for [Match.ALL] or `or(…)` for [Match.ANY]. A form that + * narrows by nothing is every task, whatever [match] says. + * + * [of] reads those rules back unchanged, plus a few shapes that mean the same + * (see [of]); anything else needs the advanced editor. + */ +data class SimpleRule( + val match: Match = Match.ALL, + val due: Set = emptySet(), + val dueNegated: Boolean = false, + val listIds: Set = emptySet(), + val listsElsewhere: Set = emptySet(), + val listsNegated: Boolean = false, + val tags: Set = emptySet(), + val tagMatch: TagMatch = TagMatch.ANY, + val tagsNegated: Boolean = false, + val minPriority: Priority = Priority.NONE, +) { + /** Whether the form narrows by list at all. */ + val anyList: Boolean get() = listIds.isEmpty() && listsElsewhere.isEmpty() + + /** The "next N days" range among [due], if one is picked. */ + val nextDays: DueSpec.NextDays? get() = due.firstNotNullOfOrNull { it as? DueSpec.NextDays } + + /** [due] with [spec] added, or taken out when it is there. A second "next N days" replaces the first. */ + fun toggleDue(spec: DueSpec): SimpleRule = when { + spec in due -> copy(due = due - spec) + spec is DueSpec.NextDays -> copy(due = due.filterNot { it is DueSpec.NextDays }.toSet() + spec) + else -> copy(due = due + spec) + } + + /** [due] with the "next N days" range set to [spec], or dropped for `null`. */ + fun withNextDays(spec: DueSpec.NextDays?): SimpleRule = + copy(due = due.filterNot { it is DueSpec.NextDays }.toSet() + listOfNotNull(spec)) + + fun toRule(): Rule { + val parts = buildList { + if (due.isNotEmpty()) add(Rule.AnyOf(due.sortedBy(::dueRank).map(Rule::Due)).negatedIf(dueNegated)) + if (!anyList) add(Rule.InList(listIds, listsElsewhere).negatedIf(listsNegated)) + 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)).negatedIf(tagsNegated)) + } + } + return if (match == Match.ANY && parts.isNotEmpty()) Rule.AnyOf(parts) else Rule.AllOf(parts) + } + + companion object { + /** + * [rule] as the simple form, or `null` when it has none. The form reads: + * - what [toRule] writes, so `of(form.toRule()) == form` for any form that + * narrows, and `of(rule)!!.toRule() == rule` for any rule [toRule] wrote; + * - a lone criterion in place of the `and(…)`, as a pinned list's scope is; + * - each criterion in any order, and as its bare condition (`tag(a)` for + * `or(tag(a))`, `due(TODAY)` for `or(due(TODAY))`); + * - several bare tags straight in the top group, read with its own + * all/any, and several bare due conditions in an `or(…)` top group. + * + * Those read back written the canonical way, meaning the same. Not readable: + * a criterion given twice in other ways, a negated priority, a `not(not(…))`, + * an empty or doubled-up due/tag group, two "next N days", a list condition + * naming no list, nested groups beyond these, and an empty `or()`, which + * matches nothing. + */ + fun of(rule: Rule): SimpleRule? { + val (match, parts) = when (rule) { + is Rule.AllOf -> Match.ALL to rule.children + is Rule.AnyOf -> if (rule.children.isEmpty()) return null else Match.ANY to rule.children + else -> Match.ALL to listOf(rule) + } + val pieces = parts.map { piece(it) ?: return null }.groupBy { it::class } + var form = SimpleRule(match = match) + for ((_, kind) in pieces) { + val merged = if (kind.size == 1) kind.single() else merge(kind, match) ?: return null + form = when (merged) { + is Piece.Due -> { + if (merged.specs.count { it is DueSpec.NextDays } > 1) return null + form.copy(due = merged.specs, dueNegated = merged.negated) + } + is Piece.Lists -> form.copy( + listIds = merged.list.listIds, + listsElsewhere = merged.list.elsewhere, + listsNegated = merged.negated, + ) + is Piece.Prio -> form.copy(minPriority = merged.priority) + is Piece.Tags -> form.copy( + tags = merged.tags, + tagMatch = merged.match ?: TagMatch.ANY, + tagsNegated = merged.negated, + ) + } + } + return form + } + + /** One criterion of the top group; [bare] when it was a lone condition, not a group of them. */ + private sealed interface Piece { + val negated: Boolean + val bare: Boolean + + data class Due(val specs: Set, override val negated: Boolean, override val bare: Boolean) : Piece + data class Lists(val list: Rule.InList, override val negated: Boolean) : Piece { + override val bare get() = true + } + data class Prio(val priority: Priority) : Piece { + override val negated get() = false + override val bare get() = true + } + + /** [match] is `null` for a bare tag, which reads either way. */ + data class Tags(val tags: Set, val match: TagMatch?, override val negated: Boolean, override val bare: Boolean) : Piece + } + + private fun piece(part: Rule): Piece? { + val negated = part is Rule.Not + val inner = if (part is Rule.Not) part.child else part + return when (inner) { + is Rule.Due -> Piece.Due(setOf(inner.spec), negated, bare = true) + is Rule.InList -> if (inner.listIds.isEmpty() && inner.elsewhere.isEmpty()) null else Piece.Lists(inner, negated) + is Rule.MinPriority -> if (negated || inner.priority == Priority.NONE) null else Piece.Prio(inner.priority) + is Rule.HasTag -> Piece.Tags(setOf(inner.tag), null, negated, bare = true) + is Rule.AnyOf -> group(inner.children, TagMatch.ANY, negated, dueAllowed = true) + is Rule.AllOf -> group(inner.children, TagMatch.ALL, negated, dueAllowed = false) + is Rule.Not -> null + } + } + + /** A group of due conditions (an `or` only) or of tags; `null` for anything else, or a repeat. */ + private fun group(children: List, match: TagMatch, negated: Boolean, dueAllowed: Boolean): Piece? { + if (children.isEmpty()) return null + val specs = children.mapNotNull { (it as? Rule.Due)?.spec } + val tags = children.mapNotNull { (it as? Rule.HasTag)?.tag } + return when { + dueAllowed && specs.size == children.size && specs.toSet().size == specs.size -> + Piece.Due(specs.toSet(), negated, bare = false) + tags.size == children.size && tags.toSet().size == tags.size -> + Piece.Tags(tags.toSet(), match, negated, bare = false) + else -> null + } + } + + /** Bare tags joined by the top group, or bare due conditions under an `or(…)` top. */ + private fun merge(pieces: List, top: Match): Piece? { + if (pieces.any { it.negated || !it.bare }) return null + return when (val first = pieces.first()) { + is Piece.Tags -> { + val tags = pieces.flatMap { (it as Piece.Tags).tags } + if (tags.toSet().size != tags.size) return null + Piece.Tags(tags.toSet(), if (top == Match.ALL) TagMatch.ALL else TagMatch.ANY, negated = false, bare = false) + } + is Piece.Due -> { + if (top != Match.ANY) return null + val specs = pieces.flatMap { (it as Piece.Due).specs } + if (specs.toSet().size != specs.size) return null + first.copy(specs = specs.toSet(), bare = false) + } + is Piece.Lists, is Piece.Prio -> null + } + } + + /** The order [toRule] writes due conditions in: the windows as listed, then the ranges. */ + internal fun dueRank(spec: DueSpec): Int = when (spec) { + is DueSpec.Window -> spec.window.ordinal + DueSpec.ThisWeek -> DueWindow.entries.size + DueSpec.ThisMonth -> DueWindow.entries.size + 1 + is DueSpec.NextDays -> DueWindow.entries.size + 2 + } + } +} + +private fun Rule.negatedIf(negated: Boolean): Rule = if (negated) Rule.Not(this) else this diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRuleTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRuleTest.kt new file mode 100644 index 0000000..c9969c5 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRuleTest.kt @@ -0,0 +1,162 @@ +package de.jeanlucmakiola.agendula.ui.filters + +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.RuleClock +import de.jeanlucmakiola.agendula.domain.TagMatch +import de.jeanlucmakiola.agendula.domain.allDayInstantOf +import de.jeanlucmakiola.agendula.domain.matches +import de.jeanlucmakiola.agendula.domain.startOfDay +import de.jeanlucmakiola.agendula.domain.testTask +import org.junit.jupiter.api.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.ZoneId + +class SimpleRuleTest { + + private val today = window(DueWindow.TODAY) + private val overdue = window(DueWindow.OVERDUE) + private val noDate = window(DueWindow.NO_DATE) + + private val forms = listOf( + SimpleRule(listIds = setOf(1L)), + SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("nextAction")), + SimpleRule(due = setOf(overdue, DueSpec.ThisWeek), dueNegated = true), + SimpleRule(due = setOf(DueSpec.NextDays(7), noDate, today)), + SimpleRule(listIds = setOf(1L, 2L), listsElsewhere = setOf("EXTERNAL:3"), listsNegated = true), + SimpleRule(listsElsewhere = setOf("EXTERNAL:3")), + SimpleRule(tags = setOf("a", "b"), tagMatch = TagMatch.ALL, tagsNegated = true), + SimpleRule(tags = setOf("a"), tagMatch = TagMatch.ALL), + SimpleRule(tags = setOf("a")), + SimpleRule(minPriority = Priority.MEDIUM), + SimpleRule( + match = Match.ANY, + due = setOf(DueSpec.ThisMonth), + listIds = setOf(4L), + tags = setOf("x", "y"), + tagsNegated = true, + minPriority = Priority.HIGH, + ), + ) + + @Test + fun `every form that narrows reads back from its rule unchanged`() { + for (form in forms) assertThat(SimpleRule.of(form.toRule())).isEqualTo(form) + } + + @Test + fun `every rule the form writes is written again unchanged`() { + for (rule in forms.map { it.toRule() }) assertThat(SimpleRule.of(rule)!!.toRule()).isEqualTo(rule) + } + + @Test + fun `a form that narrows by nothing is every task, whatever its match`() { + assertThat(SimpleRule().toRule()).isEqualTo(Rule.Everything) + assertThat(SimpleRule(match = Match.ANY).toRule()).isEqualTo(Rule.Everything) + assertThat(SimpleRule.of(Rule.Everything)).isEqualTo(SimpleRule()) + } + + @Test + fun `filters made by the flat editor keep their rule`() { + val criteria = listOf( + FilterCriteria(), + FilterCriteria(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE)), + FilterCriteria(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:2"), minPriority = Priority.LOW), + FilterCriteria(tags = setOf("b", "a"), tagMatch = TagMatch.ALL), + FilterCriteria(due = setOf(DueWindow.NO_DATE), tags = setOf("x"), minPriority = Priority.HIGH, listIds = setOf(5L)), + ) + for (flat in criteria) { + val rule = flat.toRule() + assertThat(SimpleRule.of(rule)!!.toRule()).isEqualTo(rule) + } + } + + @Test + fun `the GTD case is any of list Next and tag nextAction, also as built in the advanced editor`() { + val form = SimpleRule(match = Match.ANY, listIds = setOf(7L), tags = setOf("nextAction")) + assertThat(form.toRule()).isEqualTo( + Rule.AnyOf(listOf(Rule.InList(setOf(7L)), Rule.AnyOf(listOf(Rule.HasTag("nextAction"))))), + ) + assertThat(SimpleRule.of(Rule.AnyOf(listOf(Rule.HasTag("nextAction"), Rule.InList(setOf(7L)))))).isEqualTo(form) + } + + @Test + fun `a lone criterion reads as all rules`() { + assertThat(SimpleRule.of(Rule.InList(setOf(3L)))).isEqualTo(SimpleRule(listIds = setOf(3L))) + assertThat(SimpleRule.of(Rule.Not(Rule.HasTag("someday")))) + .isEqualTo(SimpleRule(tags = setOf("someday"), tagsNegated = true)) + assertThat(SimpleRule.of(Rule.Due(DueSpec.ThisWeek))).isEqualTo(SimpleRule(due = setOf(DueSpec.ThisWeek))) + } + + @Test + fun `bare tags take the top group's all or any, bare due conditions only an any`() { + val tags = listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b")) + assertThat(SimpleRule.of(Rule.AllOf(tags))) + .isEqualTo(SimpleRule(listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ALL)) + assertThat(SimpleRule.of(Rule.AnyOf(tags))) + .isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ANY)) + val dues = listOf(Rule.Due(today), Rule.Due(DueSpec.ThisMonth)) + assertThat(SimpleRule.of(Rule.AnyOf(dues))).isEqualTo(SimpleRule(match = Match.ANY, due = setOf(today, DueSpec.ThisMonth))) + assertThat(SimpleRule.of(Rule.AllOf(dues))).isNull() + } + + @Test + fun `shapes read differently from how they are written mean the same`() { + val zone = ZoneId.of("Europe/Berlin") + val day = LocalDate.of(2026, 11, 26) + val clock = RuleClock(startOfDay(day, zone), startOfDay(day.plusDays(1), zone), zone, DayOfWeek.MONDAY) + val tasks = listOf( + testTask(listId = 1, tags = listOf("a")), + testTask(listId = 2, tags = listOf("a", "b")), + testTask(listId = 1, due = allDayInstantOf(day), isAllDay = true), + testTask(listId = 3, tags = listOf("b"), due = allDayInstantOf(day.plusDays(9)), isAllDay = true), + testTask(listId = 3, priority = Priority.HIGH), + ) + val rules = listOf( + Rule.AllOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b"))), + Rule.AnyOf(listOf(Rule.HasTag("b"), Rule.Due(today), Rule.MinPriority(Priority.HIGH), Rule.Due(DueSpec.NextDays(3)))), + Rule.AllOf(listOf(Rule.Not(Rule.InList(setOf(3L))), Rule.HasTag("a"))), + Rule.Not(Rule.AnyOf(listOf(Rule.Due(today)))), + ) + for (rule in rules) { + val written = SimpleRule.of(rule)!!.toRule() + for (task in tasks) assertThat(written.matches(task, clock)).isEqualTo(rule.matches(task, clock)) + } + } + + @Test + fun `shapes the form can't show need the advanced editor`() { + val notSimple = listOf( + Rule.AnyOf(emptyList()), + Rule.Not(Rule.Not(Rule.HasTag("a"))), + Rule.Not(Rule.MinPriority(Priority.HIGH)), + Rule.MinPriority(Priority.NONE), + Rule.InList(emptySet()), + Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(2L)))), + Rule.AllOf(listOf(Rule.HasTag("a"), Rule.AnyOf(listOf(Rule.HasTag("b"))))), + Rule.AllOf(listOf(Rule.Not(Rule.HasTag("a")), Rule.HasTag("b"))), + Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(today), Rule.HasTag("a"))))), + Rule.AllOf(listOf(Rule.AllOf(listOf(Rule.Due(today))))), + Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.NextDays(3)), Rule.Due(DueSpec.NextDays(7)))))), + Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("a"), Rule.HasTag("a"))))), + Rule.AllOf(listOf(Rule.AllOf(emptyList()))), + Rule.Not(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a")))), + ) + for (rule in notSimple) assertThat(SimpleRule.of(rule)).isNull() + } + + @Test + fun `a second next N days replaces the first`() { + val form = SimpleRule().toggleDue(DueSpec.NextDays(3)).toggleDue(today).toggleDue(DueSpec.NextDays(7)) + assertThat(form.due).containsExactly(today, DueSpec.NextDays(7)) + assertThat(form.withNextDays(null).due).containsExactly(today) + assertThat(form.toggleDue(today).due).containsExactly(DueSpec.NextDays(7)) + } + + private fun window(window: DueWindow) = DueSpec.Window(window) +} From 2499ceb1c78c2939395ec311bd995d18c16bef1d Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:37:41 +0100 Subject: [PATCH 02/16] Rule drafts, path edits for nested groups and filter templates (#172, #154) --- .../agendula/ui/filters/RuleDraft.kt | 81 ++++++++++ .../agendula/ui/filters/RuleEditResult.kt | 55 +++++++ .../agendula/ui/filters/RuleTree.kt | 134 +++++++++++++++++ .../agendula/ui/filters/RuleDraftTest.kt | 142 ++++++++++++++++++ 4 files changed, 412 insertions(+) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditResult.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt new file mode 100644 index 0000000..49617d7 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt @@ -0,0 +1,81 @@ +package de.jeanlucmakiola.agendula.ui.filters + +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.TaskList + +/** + * A rule being edited: [rule] is what saves, and [simple] the simple editor's + * form of it while that editor shows, `null` in the advanced one. The form is + * kept apart so a choice the rule can't hold, like *any rule* with nothing + * picked, survives while editing. + */ +data class RuleDraft(val rule: Rule, val simple: SimpleRule?) { + + val advanced: Boolean get() = simple == null + + /** Whether the simple editor can show the rule as it is now. */ + val canSimplify: Boolean get() = simple != null || SimpleRule.of(rule) != null + + /** Changes the simple form, and the rule with it; nothing in the advanced editor. */ + fun editSimple(transform: (SimpleRule) -> SimpleRule): RuleDraft { + val form = simple?.let(transform) ?: return this + return RuleDraft(form.toRule(), form) + } + + /** Changes the rule in the advanced editor; nothing in the simple one. */ + fun editAdvanced(transform: (Rule) -> Rule): RuleDraft = if (simple != null) this else RuleDraft(transform(rule), null) + + /** Over to the advanced editor, which can show any rule. */ + fun toAdvanced(): RuleDraft = RuleDraft(rule.forAdvanced(), null) + + /** Over to the simple editor, when it can show the rule; the rule stays as it is. */ + fun toSimple(): RuleDraft = if (simple != null) this else SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: this + + companion object { + /** [rule] in the simple editor when it can show it, else in the advanced one. */ + fun of(rule: Rule): RuleDraft = SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: RuleDraft(rule.forAdvanced(), null) + + fun of(form: SimpleRule): RuleDraft = RuleDraft(form.toRule(), form) + } +} + +/** The rules a new filter can start from (#154); the user changes them as they like. */ +enum class FilterTemplate { + NEXT_ACTIONS, + THIS_WEEK, + THIS_MONTH, + HIGH_PRIORITY, + WAITING_FOR, + NO_DATE, + ; + + /** + * The template's rules. Lists and tags are matched by name, ignoring case, + * to [lists] and [tags] (the ones in use); a tag not in use yet is taken as + * written, a list that doesn't exist is left out. + */ + fun form(lists: List, tags: List): SimpleRule { + fun tag(name: String) = tags.firstOrNull { it.equals(name, ignoreCase = true) } ?: name + return when (this) { + NEXT_ACTIONS -> SimpleRule( + match = Match.ANY, + listIds = lists.filter { it.name.trim().equals(NEXT_LIST, ignoreCase = true) }.mapTo(HashSet()) { it.id }, + tags = setOf(tag(NEXT_ACTION_TAG)), + ) + THIS_WEEK -> SimpleRule(due = setOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.ThisWeek)) + THIS_MONTH -> SimpleRule(due = setOf(DueSpec.ThisMonth)) + HIGH_PRIORITY -> SimpleRule(minPriority = Priority.HIGH) + WAITING_FOR -> SimpleRule(tags = setOf(tag(WAITING_TAG))) + NO_DATE -> SimpleRule(due = setOf(DueSpec.Window(DueWindow.NO_DATE))) + } + } + + private companion object { + const val NEXT_LIST = "Next" + const val NEXT_ACTION_TAG = "nextAction" + const val WAITING_TAG = "waiting" + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditResult.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditResult.kt new file mode 100644 index 0000000..86b8e64 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditResult.kt @@ -0,0 +1,55 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import de.jeanlucmakiola.agendula.data.prefs.RuleCodec +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.Rule + +/** What the bare rule editor is for, which names it and decides whether it offers *Save as filter*. */ +enum class RulePurpose { + /** A view's scope. */ + SCOPE, + + /** What a block shows: *Custom rules*, which can be saved as a filter. */ + SOURCE, +} + +/** + * What the rule editor hands back to the screen that opened it for a result: + * the rules, or the filter they were saved as. + */ +sealed interface RuleEditResult { + data class Rules(val rule: Rule) : RuleEditResult + data class Filter(val filterId: Long) : RuleEditResult + + /** This result as a block's source. */ + val source: BlockSource + get() = when (this) { + is Rules -> BlockSource.Rules(rule) + is Filter -> BlockSource.Filter(filterId) + } + + fun encode(): String = when (this) { + is Rules -> "rules:${RuleText.encode(rule)}" + is Filter -> "filter:$filterId" + } + + companion object { + /** The key the result is put under in the opener's saved state. */ + const val KEY = "ruleEditResult" + + fun decode(text: String): RuleEditResult? = when { + text.startsWith("rules:") -> RuleText.decode(text.removePrefix("rules:"))?.let(::Rules) + text.startsWith("filter:") -> text.removePrefix("filter:").toLongOrNull()?.let(::Filter) + else -> null + } + } +} + +/** A rule as text, to hand between screens. Lists keep their ids, those of other stores their refs. */ +internal object RuleText { + private const val MODE = "here" + + fun encode(rule: Rule): String = RuleCodec.encode(rule, MODE) + + fun decode(text: String): Rule? = runCatching { RuleCodec.decode(text, MODE) }.getOrNull() +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt new file mode 100644 index 0000000..2c90b93 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt @@ -0,0 +1,134 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import de.jeanlucmakiola.agendula.domain.DueSpec +import de.jeanlucmakiola.agendula.domain.DueWindow +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.Rule + +/** + * The advanced editor's view of a [Rule]: groups ([Rule.AllOf], [Rule.AnyOf], + * either under a [Rule.Not]) holding conditions ([Rule.InList], [Rule.HasTag], + * [Rule.MinPriority], [Rule.Due], each maybe under a [Rule.Not]) and further + * groups. A path names a node by the child index at each group on the way down. + */ +typealias RulePath = List + +/** What a condition checks. */ +enum class RuleField { LIST, TAG, PRIORITY, DUE } + +/** Whether this is a group, negated or not. */ +val Rule.isGroup: Boolean + get() = when (this) { + is Rule.AllOf, is Rule.AnyOf -> true + is Rule.Not -> child is Rule.AllOf || child is Rule.AnyOf + else -> false + } + +/** Whether this group or condition is under a [Rule.Not]. */ +val Rule.negated: Boolean get() = this is Rule.Not + +/** The group or condition itself, without its [Rule.Not]. */ +val Rule.positive: Rule get() = if (this is Rule.Not) child else this + +/** A group's kind; `null` for a condition. */ +val Rule.groupMatch: Match? + get() = when (positive) { + is Rule.AllOf -> Match.ALL + is Rule.AnyOf -> Match.ANY + else -> null + } + +/** A group's children; empty for a condition. */ +val Rule.groupChildren: List + get() = when (val group = positive) { + is Rule.AllOf -> group.children + is Rule.AnyOf -> group.children + else -> emptyList() + } + +/** What a condition checks; `null` for a group. */ +val Rule.field: RuleField? + get() = when (positive) { + is Rule.InList -> RuleField.LIST + is Rule.HasTag -> RuleField.TAG + is Rule.MinPriority -> RuleField.PRIORITY + is Rule.Due -> RuleField.DUE + else -> null + } + +/** This rule under a [Rule.Not], or out of it. */ +fun Rule.toggleNot(): Rule = if (this is Rule.Not) child else Rule.Not(this) + +/** [positive] replaced by [transform]'s result, keeping the [Rule.Not]. */ +fun Rule.mapPositive(transform: (Rule) -> Rule): Rule = + if (this is Rule.Not) Rule.Not(transform(child)) else transform(this) + +/** This group as a group of [match], with the same children and negation. */ +fun Rule.withGroupMatch(match: Match): Rule = mapPositive { group -> + val children = group.groupChildren + if (match == Match.ALL) Rule.AllOf(children) else Rule.AnyOf(children) +} + +private fun Rule.withGroupChildren(children: List): Rule = mapPositive { group -> + if (group is Rule.AnyOf) Rule.AnyOf(children) else Rule.AllOf(children) +} + +/** The node at [path]; `null` when there is none. */ +fun Rule.at(path: RulePath): Rule? = + if (path.isEmpty()) this else groupChildren.getOrNull(path.first())?.at(path.drop(1)) + +/** This rule with the node at [path] replaced by [transform]'s result; unchanged when there is none. */ +fun Rule.updateAt(path: RulePath, transform: (Rule) -> Rule): Rule { + if (path.isEmpty()) return transform(this) + val children = groupChildren + val index = path.first() + if (index !in children.indices) return this + return withGroupChildren(children.toMutableList().also { it[index] = it[index].updateAt(path.drop(1), transform) }) +} + +/** This rule without the node at [path]; the root can't be removed. */ +fun Rule.removeAt(path: RulePath): Rule { + if (path.isEmpty()) return this + return updateAt(path.dropLast(1)) { group -> + val children = group.groupChildren + val index = path.last() + if (index in children.indices) group.withGroupChildren(children.filterIndexed { i, _ -> i != index }) else group + } +} + +/** This rule with [child] added last to the group at [path]. */ +fun Rule.addTo(path: RulePath, child: Rule): Rule = updateAt(path) { group -> + if (group.isGroup) group.withGroupChildren(group.groupChildren + child) else group +} + +/** A new, empty group for under [parent]: of the other kind, since one of the same adds nothing. */ +fun newGroupUnder(parent: Rule): Rule = if (parent.groupMatch == Match.ANY) Rule.AllOf(emptyList()) else Rule.AnyOf(emptyList()) + +/** + * This rule as the advanced editor shows it: a group at the root (a lone + * condition goes into an all-of group) and no `not(not(…))`, which reads as + * what it holds. Both mean the same as before. + */ +fun Rule.forAdvanced(): Rule { + val tidy = withoutDoubleNegation() + return if (tidy.isGroup) tidy else Rule.AllOf(listOf(tidy)) +} + +private fun Rule.withoutDoubleNegation(): Rule = when (this) { + is Rule.Not -> if (child is Rule.Not) child.child.withoutDoubleNegation() else Rule.Not(child.withoutDoubleNegation()) + is Rule.AllOf -> Rule.AllOf(children.map { it.withoutDoubleNegation() }) + is Rule.AnyOf -> Rule.AnyOf(children.map { it.withoutDoubleNegation() }) + is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this +} + +/** The values a due condition offers, besides "next N days". */ +val DUE_CHOICES: List = DueWindow.entries.map(DueSpec::Window) + listOf(DueSpec.ThisWeek, DueSpec.ThisMonth) + +/** The "next N days" ranges offered before a custom one. */ +val NEXT_DAYS_PRESETS: List = listOf(3, 7, 14, 30) + +/** The longest "next N days" range that can be entered. */ +const val NEXT_DAYS_MAX = 365 + +/** The priorities a condition can ask for at least. */ +val PRIORITY_CHOICES: List = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt new file mode 100644 index 0000000..c015238 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt @@ -0,0 +1,142 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import com.google.common.truth.Truth.assertThat +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.TaskList +import org.junit.jupiter.api.Test + +class RuleDraftTest { + + private val work = Rule.InList(setOf(1L)) + private val focus = Rule.HasTag("focus") + private val high = Rule.MinPriority(Priority.HIGH) + private val nested = Rule.AllOf(listOf(work, Rule.AnyOf(listOf(focus, high)), Rule.Not(Rule.HasTag("someday")))) + + @Test + fun `a rule the simple form can show opens there, any other in the advanced editor`() { + assertThat(RuleDraft.of(work).simple).isEqualTo(SimpleRule(listIds = setOf(1L))) + val advanced = RuleDraft.of(nested) + assertThat(advanced.advanced).isTrue() + assertThat(advanced.rule).isEqualTo(nested) + } + + @Test + fun `the advanced editor gets a group at the root and no double negation`() { + assertThat(Rule.Not(Rule.Not(work)).forAdvanced()).isEqualTo(Rule.AllOf(listOf(work))) + assertThat(Rule.Not(Rule.AnyOf(listOf(Rule.Not(Rule.Not(focus))))).forAdvanced()) + .isEqualTo(Rule.Not(Rule.AnyOf(listOf(focus)))) + assertThat(nested.forAdvanced()).isEqualTo(nested) + } + + @Test + fun `simple to advanced always, back only while the simple form can show the rule`() { + val simple = RuleDraft.of(SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("focus"))) + val advanced = simple.toAdvanced() + assertThat(advanced.advanced).isTrue() + assertThat(advanced.rule).isEqualTo(simple.rule) + assertThat(advanced.toSimple()).isEqualTo(simple) + + val grown = advanced.editAdvanced { it.addTo(emptyList(), Rule.AllOf(listOf(high, focus))) } + assertThat(grown.canSimplify).isFalse() + assertThat(grown.toSimple()).isEqualTo(grown) + assertThat(grown.editAdvanced { it.removeAt(listOf(2)) }.toSimple().simple).isEqualTo(simple.simple) + } + + @Test + fun `each editor's changes only apply in it`() { + val simple = RuleDraft.of(SimpleRule()) + assertThat(simple.editAdvanced { Rule.Everything.toggleNot() }).isEqualTo(simple) + val advanced = simple.toAdvanced() + assertThat(advanced.editSimple { it.copy(minPriority = Priority.LOW) }).isEqualTo(advanced) + } + + @Test + fun `the simple form keeps a choice its rule can't hold`() { + val any = RuleDraft.of(SimpleRule()).editSimple { it.copy(match = Match.ANY) } + assertThat(any.simple!!.match).isEqualTo(Match.ANY) + assertThat(any.rule).isEqualTo(Rule.Everything) + val picked = any.editSimple { it.copy(listIds = setOf(1L), tags = setOf("a")) } + assertThat(picked.rule).isEqualTo(Rule.AnyOf(listOf(work, Rule.AnyOf(listOf(Rule.HasTag("a")))))) + } + + @Test + fun `conditions and groups are added, changed and removed by path`() { + var rule: Rule = Rule.AllOf(emptyList()) + rule = rule.addTo(emptyList(), work) + rule = rule.addTo(emptyList(), newGroupUnder(rule)) + assertThat(rule.at(listOf(1))).isEqualTo(Rule.AnyOf(emptyList())) + rule = rule.addTo(listOf(1), focus).addTo(listOf(1), high) + rule = rule.addTo(emptyList(), Rule.Not(Rule.HasTag("someday"))) + assertThat(rule).isEqualTo(nested) + + assertThat(rule.updateAt(listOf(1, 0), Rule::toggleNot).at(listOf(1, 0))).isEqualTo(Rule.Not(focus)) + assertThat(rule.updateAt(listOf(2), Rule::toggleNot).at(listOf(2))).isEqualTo(Rule.HasTag("someday")) + assertThat(rule.updateAt(listOf(1)) { it.withGroupMatch(Match.ALL) }.at(listOf(1))).isEqualTo(Rule.AllOf(listOf(focus, high))) + assertThat(rule.removeAt(listOf(1, 0)).at(listOf(1))).isEqualTo(Rule.AnyOf(listOf(high))) + assertThat(rule.removeAt(emptyList())).isEqualTo(rule) + assertThat(rule.removeAt(listOf(9))).isEqualTo(rule) + assertThat(rule.updateAt(listOf(0, 3)) { Rule.Everything }).isEqualTo(rule) + } + + @Test + fun `a negated group keeps its negation through changes inside it`() { + var rule: Rule = Rule.AllOf(listOf(Rule.Not(Rule.AnyOf(listOf(focus))))) + rule = rule.addTo(listOf(0), high) + assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AnyOf(listOf(focus, high)))) + assertThat(rule.at(listOf(0, 1))).isEqualTo(high) + rule = rule.updateAt(listOf(0)) { it.withGroupMatch(Match.ALL) } + assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AllOf(listOf(focus, high)))) + rule = rule.removeAt(listOf(0, 0)) + assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AllOf(listOf(high)))) + assertThat(rule.at(listOf(0))!!.isGroup).isTrue() + assertThat(rule.at(listOf(0, 0))!!.field).isEqualTo(RuleField.PRIORITY) + } + + @Test + fun `a new group is of the other kind than its parent`() { + assertThat(newGroupUnder(Rule.AllOf(emptyList()))).isEqualTo(Rule.AnyOf(emptyList())) + assertThat(newGroupUnder(Rule.Not(Rule.AnyOf(emptyList())))).isEqualTo(Rule.AllOf(emptyList())) + } + + @Test + fun `templates fill in the rules they name`() { + val lists = listOf(list(1, "Inbox"), list(2, " next "), list(3, "Work")) + val tags = listOf("Waiting", "nextaction") + fun rule(template: FilterTemplate) = template.form(lists, tags).toRule() + + assertThat(rule(FilterTemplate.NEXT_ACTIONS)).isEqualTo( + Rule.AnyOf(listOf(Rule.InList(setOf(2L)), Rule.AnyOf(listOf(Rule.HasTag("nextaction"))))), + ) + assertThat(rule(FilterTemplate.THIS_WEEK)).isEqualTo( + Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.Window(DueWindow.OVERDUE)), Rule.Due(DueSpec.ThisWeek))))), + ) + assertThat(rule(FilterTemplate.THIS_MONTH)).isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.ThisMonth)))))) + assertThat(rule(FilterTemplate.HIGH_PRIORITY)).isEqualTo(Rule.AllOf(listOf(high))) + assertThat(rule(FilterTemplate.WAITING_FOR)).isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("Waiting")))))) + assertThat(rule(FilterTemplate.NO_DATE)) + .isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))))))) + // Every template opens in the simple editor. + for (template in FilterTemplate.entries) assertThat(RuleDraft.of(rule(template)).simple).isNotNull() + } + + @Test + fun `without a Next list or tags in use the GTD template still asks for the tag`() { + assertThat(FilterTemplate.NEXT_ACTIONS.form(emptyList(), emptyList())) + .isEqualTo(SimpleRule(match = Match.ANY, tags = setOf("nextAction"))) + } + + @Test + fun `a result survives the trip between screens`() { + val rule = Rule.AllOf(listOf(Rule.InList(setOf(3L), setOf("EXTERNAL:9")), Rule.Not(Rule.HasTag("a,b(c)")), Rule.Due(DueSpec.NextDays(5)))) + for (result in listOf(RuleEditResult.Rules(rule), RuleEditResult.Filter(12))) { + assertThat(RuleEditResult.decode(result.encode())).isEqualTo(result) + } + assertThat(RuleEditResult.decode("rules:nope(")).isNull() + assertThat(RuleEditResult.decode("other")).isNull() + } + + private fun list(id: Long, name: String) = TaskList(id, name, 0, "Local", "local", isSynced = false, isVisible = true, owner = null) +} From 668a71744553018ba8df199fcecfb444cc76ee23 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:37:41 +0100 Subject: [PATCH 03/16] Filter editor gets simple and advanced modes and starts new filters from templates (#172, #154) --- .../agendula/ui/filters/AdvancedEditor.kt | 362 ++++++++++++++++++ .../agendula/ui/filters/FilterEditScreen.kt | 194 +--------- .../ui/filters/FilterEditViewModel.kt | 31 +- .../agendula/ui/filters/RuleEditor.kt | 305 +++++++++++++++ .../agendula/ui/filters/RulePickers.kt | 294 ++++++++++++++ app/src/main/res/values/strings.xml | 71 +++- 6 files changed, 1061 insertions(+), 196 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt new file mode 100644 index 0000000..c57590a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt @@ -0,0 +1,362 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.ArrowDropDown +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material.icons.rounded.DoNotDisturbOn +import androidx.compose.material.icons.rounded.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.identity.FloretDensity + +/** A picker the advanced editor has open, for the node at [path]. */ +private sealed interface Picking { + val path: RulePath + + /** [adding] puts a new condition into the group at [path] rather than changing the one there. */ + data class Field(override val path: RulePath, val adding: Boolean) : Picking + data class Value(override val path: RulePath, val field: RuleField, val adding: Boolean) : Picking +} + +/** + * The advanced editor: the rule as nested groups, each *all of* or *any of*, + * maybe negated, holding conditions and further groups. [rule] is a group at the + * root (see [forAdvanced]); [onChange] gets each change to it. + */ +@Composable +internal fun AdvancedEditor( + rule: Rule, + lists: List, + tagsInUse: List, + onChange: ((Rule) -> Rule) -> Unit, +) { + var picking by remember { mutableStateOf(null) } + val listNames = remember(lists) { lists.associate { it.id to it.name } } + + GroupCard( + group = rule, + path = emptyList(), + listNames = listNames, + onChange = onChange, + onPick = { picking = it }, + modifier = Modifier.padding(horizontal = GroupedListInset), + ) + GroupedHint(stringResource(R.string.filter_advanced_note), style = MaterialTheme.typography.bodySmall, verticalPadding = 8.dp) + + when (val open = picking) { + null -> Unit + is Picking.Field -> FieldPicker( + selected = if (open.adding) null else rule.at(open.path)?.field, + onSelect = { field -> picking = Picking.Value(open.path, field, open.adding) }, + onDismiss = { if (picking == open) picking = null }, + ) + is Picking.Value -> { + val current = if (open.adding) null else rule.at(open.path)?.positive?.takeIf { it.field == open.field } + val done = { condition: Rule -> + onChange { root -> + if (open.adding) { + root.addTo(open.path, condition) + } else { + root.updateAt(open.path) { old -> if (old.negated) Rule.Not(condition) else condition } + } + } + } + val dismiss = { picking = null } + when (open.field) { + RuleField.LIST -> { + val list = current as? Rule.InList + ListsPicker( + lists = lists, + selected = list?.listIds.orEmpty(), + onDone = { ids -> done(Rule.InList(ids, list?.elsewhere.orEmpty())) }, + onDismiss = dismiss, + ) + } + RuleField.TAG -> TagPicker( + tags = tagsInUse, + selected = (current as? Rule.HasTag)?.tag, + onSelect = { done(Rule.HasTag(it)) }, + onDismiss = dismiss, + ) + RuleField.PRIORITY -> PriorityPicker( + selected = (current as? Rule.MinPriority)?.priority, + onSelect = { done(Rule.MinPriority(it)) }, + onDismiss = dismiss, + ) + RuleField.DUE -> DuePicker( + selected = (current as? Rule.Due)?.spec, + onSelect = { done(Rule.Due(it)) }, + onDismiss = dismiss, + ) + } + } + } +} + +/** One group: its kind and negation, its children, and the buttons that add to it. */ +@Composable +private fun GroupCard( + group: Rule, + path: RulePath, + listNames: Map, + onChange: ((Rule) -> Rule) -> Unit, + onPick: (Picking) -> Unit, + modifier: Modifier = Modifier, +) { + val match = group.groupMatch ?: Match.ALL + val children = group.groupChildren + val nested = path.isNotEmpty() + Surface( + shape = RoundedCornerShape(24.dp), + color = if (path.size % 2 == 0) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + modifier = modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + GroupHeader( + match = match, + negated = group.negated, + deletable = nested, + onToggleMatch = { + val other = if (match == Match.ALL) Match.ANY else Match.ALL + onChange { it.updateAt(path) { g -> g.withGroupMatch(other) } } + }, + onToggleNot = { onChange { it.updateAt(path, Rule::toggleNot) } }, + onDelete = { onChange { it.removeAt(path) } }, + ) + if (children.isEmpty()) { + GroupedHint( + stringResource(if (match == Match.ALL) R.string.filter_group_empty_all else R.string.filter_group_empty_any), + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(horizontal = 4.dp), + ) + } + children.forEachIndexed { index, child -> + val childPath = path + index + if (child.isGroup) { + GroupCard( + group = child, + path = childPath, + listNames = listNames, + onChange = onChange, + onPick = onPick, + modifier = Modifier.padding(horizontal = 8.dp), + ) + } else { + ConditionRow( + condition = child, + listNames = listNames, + onField = { onPick(Picking.Field(childPath, adding = false)) }, + onValue = { child.field?.let { onPick(Picking.Value(childPath, it, adding = false)) } }, + onToggleNot = { onChange { it.updateAt(childPath, Rule::toggleNot) } }, + onRemove = { onChange { it.removeAt(childPath) } }, + ) + } + } + Row(Modifier.padding(horizontal = 8.dp)) { + TextButton(onClick = { onPick(Picking.Field(path, adding = true)) }) { + Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.filter_add_rule)) + } + TextButton(onClick = { onChange { it.addTo(path, newGroupUnder(group)) } }) { + Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.filter_add_group)) + } + } + } + } +} + +/** A group's kind, which a tap switches, its negation, and its ⋮ menu. */ +@Composable +private fun GroupHeader( + match: Match, + negated: Boolean, + deletable: Boolean, + onToggleMatch: () -> Unit, + onToggleNot: () -> Unit, + onDelete: () -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (negated) { + InlineChip(text = stringResource(R.string.filter_group_not), onClick = onToggleNot, toggles = false) + } + InlineChip( + text = stringResource(if (match == Match.ALL) R.string.filter_group_all else R.string.filter_group_any), + onClick = onToggleMatch, + ) + Text( + stringResource( + when { + negated && match == Match.ALL -> R.string.filter_group_not_all_hint + negated -> R.string.filter_group_not_any_hint + match == Match.ALL -> R.string.filter_group_all_hint + else -> R.string.filter_group_any_hint + }, + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + var menuOpen by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { menuOpen = true }) { + Icon(Icons.Rounded.MoreVert, contentDescription = stringResource(R.string.filter_group_menu)) + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem( + text = { Text(stringResource(if (negated) R.string.filter_group_negate_off else R.string.filter_group_negate)) }, + leadingIcon = { Icon(Icons.Rounded.DoNotDisturbOn, contentDescription = null) }, + onClick = { + menuOpen = false + onToggleNot() + }, + ) + if (deletable) { + DropdownMenuItem( + text = { Text(stringResource(R.string.filter_group_delete)) }, + leadingIcon = { Icon(Icons.Rounded.Delete, contentDescription = null) }, + onClick = { + menuOpen = false + onDelete() + }, + ) + } + } + } + } +} + +/** + * One condition: what it checks, which a tap changes, its operator, which a tap + * turns round, and its value, which a tap on the row changes; ✕ removes it. + */ +@Composable +private fun ConditionRow( + condition: Rule, + listNames: Map, + onField: () -> Unit, + onValue: () -> Unit, + onToggleNot: () -> Unit, + onRemove: () -> Unit, +) { + val field = condition.field ?: return + GroupedRow( + title = conditionValue(condition.positive, listNames), + position = Position.Alone, + minHeight = FloretDensity.nestedRowHeight, + leading = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + InlineChip(text = fieldLabel(field), onClick = onField, quiet = true) + InlineChip(text = operatorLabel(field, condition.negated), onClick = onToggleNot, toggles = false) + } + }, + trailing = { + IconButton(onClick = onRemove) { + Icon(Icons.Rounded.Close, contentDescription = stringResource(R.string.filter_rule_remove)) + } + }, + onClick = onValue, + ) +} + +/** + * A small pill inside a row, tapped in place: a group's kind, a condition's field + * or operator. [toggles] marks one that switches between two values, which reads + * as a switch to accessibility; [quiet] draws it without a container. + */ +@Composable +private fun InlineChip(text: String, onClick: () -> Unit, toggles: Boolean = true, quiet: Boolean = false) { + Surface( + onClick = onClick, + shape = CircleShape, + color = if (quiet) MaterialTheme.colorScheme.surfaceContainerHighest else MaterialTheme.colorScheme.secondaryContainer, + contentColor = if (quiet) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.semantics { + role = Role.Button + if (toggles) stateDescription = text + }, + ) { + Row( + modifier = Modifier.heightIn(min = 32.dp).padding(start = 12.dp, end = if (toggles) 4.dp else 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text, style = MaterialTheme.typography.labelLarge, maxLines = 1) + if (toggles) Icon(Icons.Rounded.ArrowDropDown, contentDescription = null) + } + } +} + +@Composable +private fun operatorLabel(field: RuleField, negated: Boolean): String = stringResource( + when { + field == RuleField.PRIORITY -> if (negated) R.string.filter_op_below else R.string.filter_op_at_least + negated -> R.string.filter_op_is_not + else -> R.string.filter_op_is + }, +) + +/** What a condition compares against, as in "Work, Home", "focus", "High" or "Next 7 days". */ +@Composable +private fun conditionValue(condition: Rule, listNames: Map): String = when (condition) { + is Rule.InList -> { + val deleted = stringResource(R.string.view_scope_list_deleted) + val elsewhere = stringResource(R.string.view_scope_list_elsewhere) + val names = condition.listIds.map { listNames[it] ?: deleted }.sorted() + List(condition.elsewhere.size) { elsewhere } + if (names.isEmpty()) stringResource(R.string.filter_value_no_list) else names.joinToString(", ") + } + is Rule.HasTag -> condition.tag + is Rule.MinPriority -> priorityName(condition.priority) + is Rule.Due -> dueLabel(condition.spec) + else -> "" +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt index c4658a4..15a91bf 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt @@ -4,19 +4,16 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Delete import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier @@ -24,27 +21,16 @@ import androidx.compose.ui.res.stringResource 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 import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.GroupedSectionHeader -import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck -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. A filter - * whose rule has no flat form can only be renamed or deleted here. + * Creates or edits a [SavedFilter]: a name, then its rules in the simple or the + * advanced editor (see [RuleEditorSections]). A new filter starts by picking a + * template, or none. */ @Composable fun FilterEditScreen( @@ -58,8 +44,6 @@ fun FilterEditScreen( val lists by viewModel.lists.collectAsStateWithLifecycle() val tagsInUse by viewModel.tags.collectAsStateWithLifecycle() 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) } @@ -75,23 +59,18 @@ fun FilterEditScreen( ) { Text(stringResource(R.string.save)) } }, ) { - if (filter == null) return@CollapsingScaffold + val current = draft ?: return@CollapsingScaffold + val filter = current.filter NameField( name = filter.name, placeholder = stringResource(R.string.filter_name_hint), - autoFocus = isNew, + autoFocus = isNew && !current.choosingTemplate, onNameChange = viewModel::rename, onImeAction = save, ) - // 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 }) - } + RuleEditorSections(current.rules, lists, tagsInUse, onChange = viewModel::updateRules) if (filter.id > 0) { Spacer(Modifier.height(24.dp)) @@ -106,14 +85,11 @@ fun FilterEditScreen( Spacer(Modifier.height(24.dp)) } - if (choosingPriority && criteria != null) { - OptionPicker( - title = stringResource(R.string.filter_section_priority), - options = Priority.entries, - selected = criteria.minPriority, - label = { minPriorityLabel(it) }, - onSelect = { priority -> viewModel.updateCriteria { it.copy(minPriority = priority) } }, - onDismiss = { choosingPriority = false }, + if (draft?.choosingTemplate == true) { + TemplatePicker( + title = stringResource(R.string.filter_new_title), + onPick = { viewModel.startFrom(it, lists, tagsInUse) }, + onDismiss = onBack, ) } @@ -133,149 +109,3 @@ fun FilterEditScreen( ) } } - -/** The flat criteria: due windows, priority, lists and tags. */ -@Composable -private fun CriteriaSections( - criteria: FilterCriteria, - lists: List, - tagsInUse: List, - 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, - position: Position, - selected: Boolean, - onClick: () -> Unit, - summary: String? = null, - leading: @Composable (() -> Unit)? = null, -) { - GroupedRow( - title = title, - summary = summary, - position = position, - selected = selected, - leading = leading, - trailing = if (selected) { - { SelectedCheck() } - } else { - null - }, - onClick = onClick, - ) -} - -private fun Set.toggle(item: T): Set = if (item in this) this - item else this + item - -@Composable -private fun dueWindowLabel(window: DueWindow): String = stringResource( - when (window) { - DueWindow.OVERDUE -> R.string.smart_overdue - DueWindow.TODAY -> R.string.smart_today - DueWindow.UPCOMING -> R.string.smart_upcoming - DueWindow.NO_DATE -> R.string.smart_no_date - }, -) - -@Composable -internal fun minPriorityLabel(priority: Priority): String = stringResource( - when (priority) { - Priority.NONE -> R.string.filter_priority_any - Priority.LOW -> R.string.filter_priority_low - Priority.MEDIUM -> R.string.filter_priority_medium - Priority.HIGH -> R.string.filter_priority_high - }, -) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt index 62c6b98..e1a3110 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt @@ -5,7 +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.Rule import de.jeanlucmakiola.agendula.domain.SavedFilter import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.TaskFilter @@ -33,12 +33,10 @@ class FilterEditViewModel @Inject constructor( ) : ViewModel() { /** - * 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. + * The filter being edited, by name; its rule is [rules]' and goes into it on + * save. A new filter starts [choosingTemplate]. */ - data class Draft(val filter: SavedFilter, val criteria: FilterCriteria?) + data class Draft(val filter: SavedFilter, val rules: RuleDraft, val choosingTemplate: Boolean = false) private val _draft = MutableStateFlow(null) @@ -62,7 +60,7 @@ class FilterEditViewModel @Inject constructor( if (bound) return bound = true if (filterId == null) { - load(SavedFilter(id = 0, name = "")) + _draft.value = Draft(SavedFilter(id = 0, name = ""), RuleDraft.of(Rule.Everything), choosingTemplate = true) return } viewModelScope.launch { @@ -77,20 +75,27 @@ class FilterEditViewModel @Inject constructor( _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) { + /** Changes the rules being edited. */ + fun updateRules(transform: (RuleDraft) -> RuleDraft) { + _draft.update { it?.copy(rules = transform(it.rules)) } + } + + /** Starts the new filter from [template]'s rules, or from none. */ + fun startFrom(template: FilterTemplate?, lists: List, tags: List) { _draft.update { draft -> - val criteria = draft?.criteria?.let(transform) ?: return@update draft - Draft(draft.filter.copy(rule = criteria.toRule()), criteria) + draft?.copy( + rules = template?.let { RuleDraft.of(it.form(lists, tags)) } ?: draft.rules, + choosingTemplate = false, + ) } } private fun load(filter: SavedFilter) { - _draft.value = Draft(filter, filter.criteria) + _draft.value = Draft(filter, RuleDraft.of(filter.rule)) } fun save(onSaved: (Long) -> Unit) { - val filter = _draft.value?.filter ?: return + val filter = _draft.value?.let { it.filter.copy(rule = it.rules.rule) } ?: return if (filter.name.isBlank() || saving) return saving = true viewModelScope.launch { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt new file mode 100644 index 0000000..c86a051 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt @@ -0,0 +1,305 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ListAlt +import androidx.compose.material.icons.rounded.AccountTree +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Tune +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.DueSpec +import de.jeanlucmakiola.agendula.domain.DueWindow +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.TagMatch +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.ui.common.ListColorChip +import de.jeanlucmakiola.floret.components.ConnectedChoiceRow +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionPicker +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf + +/** + * The rules of a filter, scope or block: the simple editor, or the advanced one + * for a rule it can't show, with a row to switch between them. [onChange] gets + * each change to apply to the draft. + */ +@Composable +internal fun RuleEditorSections( + draft: RuleDraft, + lists: List, + tagsInUse: List, + onChange: ((RuleDraft) -> RuleDraft) -> Unit, +) { + val simple = draft.simple + if (simple != null) { + SimpleSections(simple, lists, tagsInUse, onChange = { transform -> onChange { it.editSimple(transform) } }) + Spacer(Modifier.height(16.dp)) + GroupedRow( + title = stringResource(R.string.filter_advanced), + summary = stringResource(R.string.filter_advanced_hint), + position = Position.Alone, + leading = { Icon(Icons.Rounded.AccountTree, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { onChange { it.toAdvanced() } }, + ) + } else { + AdvancedEditor(draft.rule, lists, tagsInUse, onChange = { transform -> onChange { it.editAdvanced(transform) } }) + Spacer(Modifier.height(16.dp)) + val canSimplify = draft.canSimplify + GroupedRow( + title = stringResource(R.string.filter_simple), + summary = stringResource(if (canSimplify) R.string.filter_simple_hint else R.string.filter_simple_unavailable), + position = Position.Alone, + dimmed = !canSimplify, + leading = { Icon(Icons.Rounded.Tune, contentDescription = null) }, + trailing = if (canSimplify) { + { Icon(Icons.Rounded.ChevronRight, contentDescription = null) } + } else { + null + }, + onClick = if (canSimplify) ({ onChange { it.toSimple() } }) else null, + ) + } +} + +/** + * The simple editor: *all / any* on top, then lists, tags, due and priority, + * each turned round by *is / is not* where that reads. 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. + */ +@Composable +private fun SimpleSections( + form: SimpleRule, + lists: List, + tagsInUse: List, + onChange: ((SimpleRule) -> SimpleRule) -> Unit, +) { + var choosingPriority by rememberSaveable { mutableStateOf(false) } + var choosingDays by rememberSaveable { mutableStateOf(false) } + + GroupedSectionHeader(stringResource(R.string.filter_match_title)) + ConnectedChoiceRow( + options = Match.entries, + selected = form.match, + label = { stringResource(if (it == Match.ALL) R.string.filter_match_all else R.string.filter_match_any) }, + onSelect = { match -> onChange { it.copy(match = match) } }, + ) + + if (lists.isNotEmpty()) { + NegatableHeader(stringResource(R.string.filter_section_lists), form.listsNegated) { negated -> + onChange { it.copy(listsNegated = negated) } + } + val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1 + ChoiceRow( + title = stringResource(R.string.filter_any_list), + position = positionOf(0, lists.size + 1), + selected = form.anyList, + leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) }, + onClick = { onChange { 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 form.listIds, + leading = { ListColorChip(list.color) }, + onClick = { onChange { it.copy(listIds = it.listIds.toggle(list.id)) } }, + ) + } + } + + // A tag no open task carries any more stays listed while the form uses it, so it can still be unticked. + val tags = remember(tagsInUse, form.tags) { + (tagsInUse + form.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER) + } + if (tags.isNotEmpty()) { + NegatableHeader(stringResource(R.string.filter_section_tags), form.tagsNegated) { negated -> + onChange { it.copy(tagsNegated = negated) } + } + ChoiceRow( + title = stringResource(R.string.filter_any_tag), + position = positionOf(0, tags.size + 1), + selected = form.tags.isEmpty(), + onClick = { onChange { it.copy(tags = emptySet()) } }, + ) + tags.forEachIndexed { index, tag -> + ChoiceRow( + title = tag, + position = positionOf(index + 1, tags.size + 1), + selected = tag in form.tags, + onClick = { onChange { it.copy(tags = it.tags.toggle(tag)) } }, + ) + } + if (form.tags.size > 1) { + Spacer(Modifier.height(8.dp)) + GroupedSwitchRow( + title = stringResource(R.string.filter_match_all_tags), + summary = stringResource( + if (form.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off, + ), + checked = form.tagMatch == TagMatch.ALL, + onCheckedChange = { all -> onChange { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) } }, + position = Position.Alone, + ) + } + } + + NegatableHeader(stringResource(R.string.filter_section_due), form.dueNegated) { negated -> + onChange { it.copy(dueNegated = negated) } + } + val windows = listOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.Window(DueWindow.TODAY), DueSpec.Window(DueWindow.UPCOMING)) + val ranges = listOf(DueSpec.ThisWeek, DueSpec.ThisMonth) + val rows = 1 + windows.size + ranges.size + 2 + ChoiceRow( + title = stringResource(R.string.filter_any_due), + position = positionOf(0, rows), + selected = form.due.isEmpty(), + onClick = { onChange { it.copy(due = emptySet()) } }, + ) + (windows + ranges).forEachIndexed { index, spec -> + ChoiceRow( + title = dueLabel(spec), + position = positionOf(index + 1, rows), + selected = spec in form.due, + onClick = { onChange { it.toggleDue(spec) } }, + ) + } + val nextDays = form.nextDays + GroupedRow( + title = nextDays?.let { dueLabel(it) } ?: stringResource(R.string.filter_due_next_days_any), + position = positionOf(rows - 2, rows), + selected = nextDays != null, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { choosingDays = true }, + ) + val noDate = DueSpec.Window(DueWindow.NO_DATE) + ChoiceRow( + title = dueLabel(noDate), + position = positionOf(rows - 1, rows), + selected = noDate in form.due, + onClick = { onChange { it.toggleDue(noDate) } }, + ) + + GroupedSectionHeader(stringResource(R.string.filter_section_priority)) + GroupedRow( + title = minPriorityLabel(form.minPriority), + position = Position.Alone, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { choosingPriority = true }, + ) + + if (choosingPriority) { + OptionPicker( + title = stringResource(R.string.filter_section_priority), + options = Priority.entries, + selected = form.minPriority, + label = { minPriorityLabel(it) }, + onSelect = { priority -> onChange { it.copy(minPriority = priority) } }, + onDismiss = { choosingPriority = false }, + ) + } + if (choosingDays) { + NextDaysPicker( + selected = nextDays?.days, + withNone = true, + onSelect = { days -> onChange { it.withNextDays(days?.let(DueSpec::NextDays)) } }, + onDismiss = { choosingDays = false }, + ) + } +} + +/** A section header with an *is / is not* switch at its end. */ +@Composable +private fun NegatableHeader(title: String, negated: Boolean, onNegate: (Boolean) -> Unit) { + Row(verticalAlignment = Alignment.Bottom) { + GroupedSectionHeader(title, Modifier.weight(1f)) + ConnectedChoiceRow( + options = listOf(false, true), + selected = negated, + label = { stringResource(if (it) R.string.filter_op_is_not else R.string.filter_op_is) }, + onSelect = onNegate, + modifier = Modifier.width(NEGATE_WIDTH).padding(bottom = 4.dp), + ) + } +} + +/** Room for the *is / is not* pair, its inset included. */ +private val NEGATE_WIDTH = 200.dp + +@Composable +internal fun ChoiceRow( + title: String, + position: Position, + selected: Boolean, + onClick: () -> Unit, + summary: String? = null, + leading: @Composable (() -> Unit)? = null, +) { + GroupedRow( + title = title, + summary = summary, + position = position, + checked = selected, + leading = leading, + onClick = onClick, + ) +} + +internal fun Set.toggle(item: T): Set = if (item in this) this - item else this + item + +/** A due condition's value, as in "Overdue" or "Next 7 days". */ +@Composable +internal fun dueLabel(spec: DueSpec): String = when (spec) { + is DueSpec.Window -> stringResource( + when (spec.window) { + DueWindow.OVERDUE -> R.string.smart_overdue + DueWindow.TODAY -> R.string.smart_today + DueWindow.UPCOMING -> R.string.smart_upcoming + DueWindow.NO_DATE -> R.string.smart_no_date + }, + ) + DueSpec.ThisWeek -> stringResource(R.string.filter_due_this_week) + DueSpec.ThisMonth -> stringResource(R.string.filter_due_this_month) + is DueSpec.NextDays -> pluralStringResource(R.plurals.filter_due_next_days, spec.days, spec.days) +} + +@Composable +internal fun minPriorityLabel(priority: Priority): String = stringResource( + when (priority) { + Priority.NONE -> R.string.filter_priority_any + Priority.LOW -> R.string.filter_priority_low + Priority.MEDIUM -> R.string.filter_priority_medium + Priority.HIGH -> R.string.filter_priority_high + }, +) + +@Composable +internal fun priorityName(priority: Priority): String = stringResource( + when (priority) { + Priority.NONE -> R.string.priority_none + Priority.LOW -> R.string.priority_low + Priority.MEDIUM -> R.string.priority_medium + Priority.HIGH -> R.string.priority_high + }, +) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt new file mode 100644 index 0000000..1245464 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt @@ -0,0 +1,294 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ListAlt +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.Bolt +import androidx.compose.material.icons.rounded.CalendarMonth +import androidx.compose.material.icons.rounded.CalendarViewWeek +import androidx.compose.material.icons.rounded.Event +import androidx.compose.material.icons.rounded.EventBusy +import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Schedule +import androidx.compose.material.icons.rounded.Sell +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.DueSpec +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.ui.common.ListColorChip +import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon +import de.jeanlucmakiola.agendula.ui.settings.ChipAccent +import de.jeanlucmakiola.floret.components.CustomAmountEditor +import de.jeanlucmakiola.floret.components.CustomExpandRow +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.OptionPicker +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf + +/** + * The "next N days" ranges: the presets, then a custom number. [withNone] leads + * with a row that drops the range, for the simple editor, where it is optional. + */ +@Composable +internal fun NextDaysPicker( + selected: Int?, + withNone: Boolean, + onSelect: (Int?) -> Unit, + onDismiss: () -> Unit, +) { + FullScreenPicker(title = stringResource(R.string.filter_next_days_title), onDismiss = onDismiss) { + val pick = { days: Int? -> + onSelect(days) + onDismiss() + } + if (withNone) { + GroupedRow( + title = stringResource(R.string.filter_next_days_off), + position = Position.Alone, + checked = selected == null, + onClick = { pick(null) }, + ) + Spacer(Modifier.height(16.dp)) + } + NextDaysRows(selected, onPick = pick, first = 0, count = NEXT_DAYS_PRESETS.size + 1) + } +} + +/** + * The preset "next N days" rows and the custom one, at [first] of a run of + * [count] rows; [onPick] gets the number of days. + */ +@Composable +private fun NextDaysRows(selected: Int?, onPick: (Int) -> Unit, first: Int, count: Int) { + NEXT_DAYS_PRESETS.forEachIndexed { index, days -> + GroupedRow( + title = dueLabel(DueSpec.NextDays(days)), + position = positionOf(first + index, count), + checked = selected == days, + onClick = { onPick(days) }, + ) + } + val custom = selected != null && selected !in NEXT_DAYS_PRESETS + var expanded by rememberSaveable { mutableStateOf(false) } + var amountText by rememberSaveable { mutableStateOf(selected?.takeIf { custom }?.toString().orEmpty()) } + val value = amountText.toIntOrNull()?.takeIf { it in 1..NEXT_DAYS_MAX } + CustomExpandRow( + title = if (custom) { + stringResource(R.string.reminder_custom_with_value, dueLabel(DueSpec.NextDays(selected!!))) + } else { + stringResource(R.string.reminder_custom) + }, + position = positionOf(first + NEXT_DAYS_PRESETS.size, count), + expanded = expanded, + onExpandedChange = { expanded = it }, + checked = custom, + ) { + CustomAmountEditor( + amountText = amountText, + onAmountChange = { amountText = it }, + preview = value?.let { pluralStringResource(R.plurals.filter_due_next_days, it, it) } + ?: stringResource(R.string.filter_next_days_amount), + setLabel = stringResource(R.string.reminder_custom_set), + confirmEnabled = value != null, + onConfirm = { value?.let(onPick) }, + placeholder = "7", + ) + } +} + +/** A due condition's value: a window, this week or month, or the next N days. */ +@Composable +internal fun DuePicker(selected: DueSpec?, onSelect: (DueSpec) -> Unit, onDismiss: () -> Unit) { + FullScreenPicker(title = stringResource(R.string.filter_field_due), onDismiss = onDismiss) { + val pick = { spec: DueSpec -> + onSelect(spec) + onDismiss() + } + DUE_CHOICES.forEachIndexed { index, spec -> + GroupedRow( + title = dueLabel(spec), + position = positionOf(index, DUE_CHOICES.size), + checked = spec == selected, + onClick = { pick(spec) }, + ) + } + GroupedSectionHeader(stringResource(R.string.filter_next_days_title)) + NextDaysRows( + selected = (selected as? DueSpec.NextDays)?.days, + onPick = { pick(DueSpec.NextDays(it)) }, + first = 0, + count = NEXT_DAYS_PRESETS.size + 1, + ) + Spacer(Modifier.height(16.dp)) + } +} + +/** What a new or changed condition checks. */ +@Composable +internal fun FieldPicker(selected: RuleField?, onSelect: (RuleField) -> Unit, onDismiss: () -> Unit) { + OptionPicker( + title = stringResource(R.string.filter_field_title), + options = RuleField.entries, + selected = selected, + label = { fieldLabel(it!!) }, + leading = { Icon(fieldIcon(it!!), contentDescription = null) }, + onSelect = { it?.let(onSelect) }, + onDismiss = onDismiss, + ) +} + +/** + * The lists a list condition names, ticked on and off; [onDone] takes them, and + * only while there is one. + */ +@Composable +internal fun ListsPicker( + lists: List, + selected: Set, + onDone: (Set) -> Unit, + onDismiss: () -> Unit, +) { + var picked by remember { mutableStateOf(selected) } + FullScreenPicker( + title = stringResource(R.string.filter_section_lists), + onDismiss = onDismiss, + actions = { + TextButton( + onClick = { + onDone(picked) + onDismiss() + }, + enabled = picked.isNotEmpty(), + modifier = Modifier.padding(end = 8.dp), + ) { Text(stringResource(R.string.picker_done)) } + }, + ) { + if (lists.isEmpty()) { + GroupedHint(stringResource(R.string.filter_lists_none)) + return@FullScreenPicker + } + val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1 + lists.forEachIndexed { index, list -> + ChoiceRow( + title = list.name, + summary = list.accountName.takeIf { showAccount }, + position = positionOf(index, lists.size), + selected = list.id in picked, + leading = { ListColorChip(list.color) }, + onClick = { picked = picked.toggle(list.id) }, + ) + } + Spacer(Modifier.height(16.dp)) + } +} + +/** The tag a tag condition names, from the ones in use. */ +@Composable +internal fun TagPicker(tags: List, selected: String?, onSelect: (String) -> Unit, onDismiss: () -> Unit) { + val options = remember(tags, selected) { + (tags + listOfNotNull(selected)).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER) + } + if (options.isEmpty()) { + FullScreenPicker(title = stringResource(R.string.filter_section_tags), onDismiss = onDismiss) { + GroupedHint(stringResource(R.string.filter_tags_none)) + } + return + } + OptionPicker( + title = stringResource(R.string.filter_section_tags), + options = options, + selected = selected, + label = { it.orEmpty() }, + onSelect = { it?.let(onSelect) }, + onDismiss = onDismiss, + ) +} + +/** The priority a priority condition asks for at least. */ +@Composable +internal fun PriorityPicker(selected: Priority?, onSelect: (Priority) -> Unit, onDismiss: () -> Unit) { + OptionPicker( + title = stringResource(R.string.filter_section_priority), + options = PRIORITY_CHOICES, + selected = selected, + label = { priorityName(it!!) }, + onSelect = { it?.let(onSelect) }, + onDismiss = onDismiss, + ) +} + +/** + * Where new rules start: empty, or one of the [FilterTemplate]s. [onPick] gets + * `null` for empty; [onDismiss] leaves without starting. + */ +@Composable +internal fun TemplatePicker(title: String, onPick: (FilterTemplate?) -> Unit, onDismiss: () -> Unit) { + FullScreenPicker(title = title, onDismiss = onDismiss) { + GroupedRow( + title = stringResource(R.string.filter_template_empty), + summary = stringResource(R.string.filter_template_empty_hint), + position = Position.Alone, + leading = { CategoryIcon(Icons.Rounded.Add, ChipAccent.Primary) }, + onClick = { onPick(null) }, + ) + GroupedSectionHeader(stringResource(R.string.filter_templates_header)) + FilterTemplate.entries.forEachIndexed { index, template -> + val (name, hint, icon) = templateLabels(template) + GroupedRow( + title = stringResource(name), + summary = stringResource(hint), + position = positionOf(index, FilterTemplate.entries.size), + leading = { CategoryIcon(icon, ChipAccent.Primary) }, + onClick = { onPick(template) }, + ) + } + GroupedHint(stringResource(R.string.filter_templates_note), verticalPadding = 8.dp) + Spacer(Modifier.height(16.dp)) + } +} + +private fun templateLabels(template: FilterTemplate): Triple = when (template) { + FilterTemplate.NEXT_ACTIONS -> Triple(R.string.filter_template_gtd, R.string.filter_template_gtd_hint, Icons.Rounded.Bolt) + FilterTemplate.THIS_WEEK -> Triple(R.string.filter_template_week, R.string.filter_template_week_hint, Icons.Rounded.CalendarViewWeek) + FilterTemplate.THIS_MONTH -> Triple(R.string.filter_template_month, R.string.filter_template_month_hint, Icons.Rounded.CalendarMonth) + FilterTemplate.HIGH_PRIORITY -> Triple(R.string.filter_template_high, R.string.filter_template_high_hint, Icons.Rounded.Flag) + FilterTemplate.WAITING_FOR -> Triple(R.string.filter_template_waiting, R.string.filter_template_waiting_hint, Icons.Rounded.Schedule) + FilterTemplate.NO_DATE -> Triple(R.string.filter_template_no_date, R.string.filter_template_no_date_hint, Icons.Rounded.EventBusy) +} + +@Composable +internal fun fieldLabel(field: RuleField): String = stringResource( + when (field) { + RuleField.LIST -> R.string.filter_field_list + RuleField.TAG -> R.string.filter_field_tag + RuleField.PRIORITY -> R.string.filter_field_priority + RuleField.DUE -> R.string.filter_field_due + }, +) + +internal fun fieldIcon(field: RuleField): ImageVector = when (field) { + RuleField.LIST -> Icons.AutoMirrored.Rounded.ListAlt + RuleField.TAG -> Icons.Rounded.Sell + RuleField.PRIORITY -> Icons.Rounded.Flag + RuleField.DUE -> Icons.Rounded.Event +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d19146f..b51008f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -308,7 +308,73 @@ Only the filter goes. Its tasks stay where they are. Delete Filter deleted - This filter uses rules that can’t be edited here yet. You can still rename or delete it. + Show tasks that match + All rules + Any rule + is + is not + at least + below + This week + This month + + Next %d day + Next %d days + + Next days… + Off + Within the next days + Enter a number of days + Advanced editor + Nested groups with all / any / not + Rules the simple editor can’t show, like nested groups or “not” on a group, always open here. + Simple editor + Lists, tags, due date and priority + These rules need the advanced editor + All of + Any of + Not + every rule must match + one is enough + leaves out tasks matching every rule + leaves out tasks matching any rule + No rules yet: every task matches. + No rules yet: no task matches. + Group options + Negate group (not) + Remove “not” + Delete group + Rule + Group + Remove rule + Rule on + List + Tag + Priority + Due + No list + No lists yet. + No open task has a tag yet. + Start empty + Pick every rule yourself + Templates + A template only fills in the rules. You can change everything afterwards. + Next actions (GTD) + List “Next” or tag nextAction + This week + Due this week, overdue included + This month + Due this month + High priority + Priority high, any list + Waiting for + Tag waiting + No date + Open tasks without a due date + Edit scope + Custom rules + Save as filter + Keep these rules as a filter, and show the filter here New task Could not read your tasks. No task lists yet. @@ -1126,6 +1192,9 @@ This block’s list or filter was deleted. Choose source Smart lists + Custom rules… + Lists, tags, due dates and priority + Custom rules A list in this view’s scope was deleted. That part of the scope now matches nothing. Edit scope From f0a6e318f175b6de9b2510d99fb15e3548add5b1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:37:42 +0100 Subject: [PATCH 04/16] Edit a view's scope and a block's custom rules in the rule editor (#59, #172) --- .../agendula/ui/filters/RuleEditScreen.kt | 100 ++++++++++ .../agendula/ui/filters/RuleEditViewModel.kt | 158 +++++++++++++++ .../agendula/ui/lists/ListsScreen.kt | 5 +- .../agendula/ui/lists/SourcePicker.kt | 18 +- .../agendula/ui/navigation/AgendulaNavHost.kt | 44 ++++- .../agendula/ui/navigation/Destinations.kt | 45 +++++ .../agendula/ui/views/EditViewScreen.kt | 8 +- .../agendula/ui/views/ViewsViewModels.kt | 10 +- .../ui/filters/RuleEditViewModelTest.kt | 184 ++++++++++++++++++ .../agendula/ui/views/EditViewScopeTest.kt | 106 ++++++++++ 10 files changed, 670 insertions(+), 8 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt new file mode 100644 index 0000000..3b0524f --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt @@ -0,0 +1,100 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.ui.common.NameField +import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionalFormSection +import de.jeanlucmakiola.floret.components.Position + +/** + * Edits a bare rule, no filter around it: a view's scope or a block's custom + * rules ([purpose]). Custom rules can be saved as a filter too, named here. + * [onDone] gets what to hand back to the opener (see [RuleEditViewModel.save]). + */ +@Composable +fun RuleEditScreen( + viewModel: RuleEditViewModel, + purpose: RulePurpose, + onDone: (RuleEditResult?) -> Unit, + onBack: () -> Unit, +) { + val state by viewModel.state.collectAsStateWithLifecycle() + val lists by viewModel.lists.collectAsStateWithLifecycle() + val tagsInUse by viewModel.tags.collectAsStateWithLifecycle() + val saveFailed by viewModel.saveFailed.collectAsStateWithLifecycle() + val save = { viewModel.save(onDone) } + val title = stringResource(if (purpose == RulePurpose.SCOPE) R.string.rule_scope_title else R.string.rule_source_title) + + CollapsingScaffold( + title = title, + onBack = onBack, + largeTopBar = false, + actions = { + Button( + onClick = save, + enabled = state?.canSave == true, + modifier = Modifier.padding(end = 12.dp), + ) { Text(stringResource(R.string.save)) } + }, + ) { + val current = state ?: return@CollapsingScaffold + if (saveFailed) { + Text( + stringResource(R.string.view_save_failed), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = GroupedListInset).padding(bottom = 8.dp), + ) + } + + RuleEditorSections(current.rules, lists, tagsInUse, onChange = viewModel::updateRules) + + if (purpose == RulePurpose.SOURCE) { + Spacer(Modifier.height(24.dp)) + GroupedSwitchRow( + title = stringResource(R.string.rule_save_as_filter), + checked = current.saveAsFilter, + onCheckedChange = viewModel::setSaveAsFilter, + position = Position.Alone, + summary = stringResource(R.string.rule_save_as_filter_hint), + leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) }, + ) + OptionalFormSection(visible = current.saveAsFilter) { + Spacer(Modifier.height(8.dp)) + NameField( + name = current.filterName, + placeholder = stringResource(R.string.filter_name_hint), + autoFocus = current.saveAsFilter, + onNameChange = viewModel::renameFilter, + onImeAction = save, + ) + } + } + Spacer(Modifier.height(24.dp)) + } + + if (state?.choosingTemplate == true) { + TemplatePicker( + title = title, + onPick = { viewModel.startFrom(it, lists, tagsInUse) }, + onDismiss = onBack, + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt new file mode 100644 index 0000000..66ba51e --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt @@ -0,0 +1,158 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.lifecycle.ViewModel +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.BlockSource +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.SavedFilter +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.tagsInUse +import de.jeanlucmakiola.agendula.domain.withoutListIds +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +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 + +/** + * Holds a bare rule being edited, a view's scope or a block's custom rules, until + * it's saved to its [Target]. Call [bind] first. + */ +@HiltViewModel +class RuleEditViewModel @Inject constructor( + private val settingsPrefs: SettingsPrefs, + private val repository: TasksRepository, +) : ViewModel() { + + /** Where the rule goes on save. */ + sealed interface Target { + /** The source of the stored block [blockId] of view [viewId]. */ + data class Block(val viewId: Long, val blockId: Long) : Target + + /** Back to the screen that opened the editor, as a [RuleEditResult]. */ + data class Result(val initial: Rule?) : Target + } + + /** + * The rule being edited. [saveAsFilter] stores it as a filter named + * [filterName] too, and hands back that filter; only for a block's source. + */ + data class State( + val rules: RuleDraft, + val choosingTemplate: Boolean = false, + val saveAsFilter: Boolean = false, + val filterName: String = "", + ) { + val canSave: Boolean get() = !saveAsFilter || filterName.isNotBlank() + } + + private val _state = MutableStateFlow(null) + + /** `null` until [bind] has loaded the rule. */ + val state: StateFlow = _state.asStateFlow() + + private val _saveFailed = MutableStateFlow(false) + + /** Set when the block couldn't be written: the views are another version's, or it is gone. */ + val saveFailed: StateFlow = _saveFailed.asStateFlow() + + val lists: StateFlow> = repository.taskLists() + .catch { emit(emptyList()) } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + + /** Every tag on an open task. */ + val tags: StateFlow> = repository.tasks(TaskFilter.Smart(SmartList.ALL)) + .map { tagsInUse(it) } + .catch { emit(emptyList()) } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + + private var target: Target? = null + private var saving = false + + /** + * Loads the rule [target] holds. New custom rules ([RulePurpose.SOURCE] + * without any yet) start from the templates. Lists deleted since drop out, + * so a condition left without lists shows as matching nothing, as it does. + */ + fun bind(target: Target, purpose: RulePurpose) { + if (this.target != null) return + this.target = target + viewModelScope.launch { + val stored = when (target) { + is Target.Result -> target.initial + is Target.Block -> settingsPrefs.views.first().firstOrNull { it.id == target.viewId } + ?.blocks?.firstOrNull { it.id == target.blockId } + ?.let { (it.source as? BlockSource.Rules)?.rule } + } + val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull().orEmpty() + val rule = stored?.let { if (existing.isEmpty()) it else it.withoutListIds { id -> id !in existing } } + _state.value = State( + rules = RuleDraft.of(rule ?: Rule.Everything), + choosingTemplate = rule == null && purpose == RulePurpose.SOURCE, + ) + } + } + + fun updateRules(transform: (RuleDraft) -> RuleDraft) { + _state.update { it?.copy(rules = transform(it.rules)) } + } + + /** Starts from [template]'s rules, or from none. */ + fun startFrom(template: FilterTemplate?, lists: List, tags: List) { + _state.update { state -> + state?.copy( + rules = template?.let { RuleDraft.of(it.form(lists, tags)) } ?: state.rules, + choosingTemplate = false, + ) + } + } + + fun setSaveAsFilter(on: Boolean) = _state.update { it?.copy(saveAsFilter = on) } + + fun renameFilter(name: String) = _state.update { it?.copy(filterName = name) } + + /** + * Saves the rule, as a filter too when asked: into the block, or handed to + * [onDone] as a result. [onDone] gets `null` for a block, which is written + * here; a block that can't be written gets no filter either. + */ + fun save(onDone: (RuleEditResult?) -> Unit) { + val state = _state.value ?: return + val target = target ?: return + if (saving || !state.canSave) return + saving = true + viewModelScope.launch { + val rules = RuleEditResult.Rules(state.rules.rule) + suspend fun asFilter() = RuleEditResult.Filter(settingsPrefs.saveFilter(SavedFilter(0, state.filterName.trim(), rules.rule))) + when (target) { + is Target.Result -> onDone(if (state.saveAsFilter) asFilter() else rules) + is Target.Block -> { + var written = writeSource(target, rules.source) + if (written && state.saveAsFilter) written = writeSource(target, asFilter().source) + if (written) { + onDone(null) + } else { + saving = false + _saveFailed.value = true + } + } + } + } + } + + private suspend fun writeSource(target: Target.Block, source: BlockSource): Boolean = + settingsPrefs.updateView(target.viewId) { view -> + view.copy(blocks = view.blocks.map { if (it.id == target.blockId) it.copy(source = source) else it }) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index fe535ba..4c4ad48 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -151,6 +151,7 @@ fun ListsScreen( onEditView: (Long) -> Unit, modifier: Modifier = Modifier, onNewFilter: () -> Unit = {}, + onEditBlockRules: (viewId: Long, blockId: Long) -> Unit = { _, _ -> }, viewModel: ListsViewModel = hiltViewModel(), ) { val state by viewModel.state.collectAsStateWithLifecycle() @@ -346,6 +347,7 @@ fun ListsScreen( todayOnly = choosingBlock.type == BlockType.PROGRESS, onPick = { source -> viewModel.chooseSource(content.view.id, choosingBlock.id, source) }, onDismiss = { choosingSourceFor = null }, + onCustomRules = if (choosingBlock.type == BlockType.PROGRESS) null else ({ onEditBlockRules(content.view.id, choosingBlock.id) }), ) } } @@ -607,7 +609,8 @@ private fun sourceLabel(source: BlockSource, state: ListsUiState.Content): Strin is BlockSource.List -> state.lists.firstOrNull { it.id == source.listId }?.name.orEmpty() is BlockSource.Tag -> source.tag is BlockSource.Filter -> state.filterNames[source.filterId].orEmpty() - is BlockSource.ListElsewhere, is BlockSource.Rules -> "" + is BlockSource.Rules -> stringResource(R.string.view_source_custom_label) + is BlockSource.ListElsewhere -> "" } /** The user's lists by account, reorderable in place, or the way to make the first one. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt index 48a99d3..db3164f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt @@ -6,6 +6,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ListAlt import androidx.compose.material.icons.rounded.FilterList import androidx.compose.material.icons.rounded.Sell +import androidx.compose.material.icons.rounded.Tune import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -20,13 +21,15 @@ import de.jeanlucmakiola.agendula.ui.common.ListColorChip import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf /** * A full-screen pick of what a block or screen shows: the lists by account, the * saved filters and the tags, each with its open count, led by the smart lists * when [withSmartLists]. *Lists & filters…* in the view menu opens it to push the - * picked one's screen; a block whose source is gone, to choose another. + * picked one's screen; a block whose source is gone, to choose another. With + * [onCustomRules] it leads with *Custom rules…*, which opens the rule editor. */ @Composable internal fun SourcePicker( @@ -36,6 +39,7 @@ internal fun SourcePicker( onPick: (BlockSource) -> Unit, onDismiss: () -> Unit, todayOnly: Boolean = false, + onCustomRules: (() -> Unit)? = null, ) { val sections = state.unscopedSections val pick = { source: BlockSource -> @@ -43,6 +47,18 @@ internal fun SourcePicker( onPick(source) } FullScreenPicker(title = title, onDismiss = onDismiss) { + if (onCustomRules != null) { + GroupedRow( + title = stringResource(R.string.view_source_custom), + summary = stringResource(R.string.view_source_custom_hint), + position = Position.Alone, + leading = { Icon(Icons.Rounded.Tune, contentDescription = null) }, + onClick = { + onDismiss() + onCustomRules() + }, + ) + } if (withSmartLists) { GroupedSectionHeader(stringResource(R.string.view_source_smart)) val smarts = if (todayOnly) listOf(SmartList.TODAY) else SmartList.entries diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt index 0ed6132..40dabbd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt @@ -31,6 +31,11 @@ import de.jeanlucmakiola.agendula.ui.edit.TaskEditScreen import de.jeanlucmakiola.agendula.ui.edit.TaskEditViewModel import de.jeanlucmakiola.agendula.ui.filters.FilterEditScreen import de.jeanlucmakiola.agendula.ui.filters.FilterEditViewModel +import de.jeanlucmakiola.agendula.ui.filters.RuleEditResult +import de.jeanlucmakiola.agendula.ui.filters.RuleEditScreen +import de.jeanlucmakiola.agendula.ui.filters.RuleEditViewModel +import de.jeanlucmakiola.agendula.ui.filters.RulePurpose +import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.ui.imports.ImportScreen import de.jeanlucmakiola.agendula.ui.lists.ListsScreen import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen @@ -146,6 +151,7 @@ fun AgendulaNavHost( onOpenSettings = { nav.navigate(Dest.SETTINGS) }, onManageViews = { nav.navigate(Dest.MANAGE_VIEWS) }, onEditView = { id -> nav.navigate(Dest.EditView.build(id)) }, + onEditBlockRules = { viewId, blockId -> nav.navigate(Dest.RuleEdit.forBlock(viewId, blockId)) }, ) } } @@ -163,9 +169,45 @@ fun AgendulaNavHost( val viewId = entry.arguments?.getLong(Dest.EditView.ARG_VIEW_ID) ?: View.HOME_ID val vm: EditViewViewModel = hiltViewModel() LaunchedEffect(viewId) { vm.bind(viewId) } + // The scope edited in the rule editor, handed back once the view has loaded. + val scopeResult by entry.savedStateHandle.getStateFlow(RuleEditResult.KEY, null).collectAsStateWithLifecycle() + val loaded by vm.draft.collectAsStateWithLifecycle() + LaunchedEffect(scopeResult, loaded != null) { + val result = scopeResult ?: return@LaunchedEffect + if (loaded == null) return@LaunchedEffect + (RuleEditResult.decode(result) as? RuleEditResult.Rules)?.let { vm.setScope(it.rule) } + entry.savedStateHandle.remove(RuleEditResult.KEY) + } ReadableWidth { EditViewScreen( viewModel = vm, + onEditScope = { scope -> nav.navigate(Dest.RuleEdit.forResult(RulePurpose.SCOPE, scope)) }, + onBack = { nav.popBackStack() }, + ) + } + } + + composable(Dest.RuleEdit.route, arguments = Dest.RuleEdit.arguments) { entry -> + val args = entry.arguments + val purpose = Dest.RuleEdit.purposeOf(args?.getString(Dest.RuleEdit.ARG_PURPOSE)) + val target = Dest.RuleEdit.targetOf( + viewId = args?.getLong(Dest.RuleEdit.ARG_VIEW_ID) ?: Dest.NO_ID, + blockId = args?.getLong(Dest.RuleEdit.ARG_BLOCK_ID) ?: Dest.NO_ID, + rule = args?.getString(Dest.RuleEdit.ARG_RULE), + ) + val vm: RuleEditViewModel = hiltViewModel() + LaunchedEffect(target) { vm.bind(target, purpose) } + ReadableWidth { + RuleEditScreen( + viewModel = vm, + purpose = purpose, + onDone = { result -> + // Only while this editor is still the screen shown; the user may have left it. + if (nav.currentBackStackEntry?.id == entry.id) { + if (result != null) nav.previousBackStackEntry?.savedStateHandle?.set(RuleEditResult.KEY, result.encode()) + nav.popBackStack() + } + }, onBack = { nav.popBackStack() }, ) } @@ -320,7 +362,7 @@ fun AgendulaNavHost( } /** Routes holding a draft that leaving would lose. */ -private val FORMS = setOf(Dest.TaskEdit.route, Dest.FilterEdit.route, Dest.EditView.route) +private val FORMS = setOf(Dest.TaskEdit.route, Dest.FilterEdit.route, Dest.EditView.route, Dest.RuleEdit.route) /** A task's detail route, pinned to its occurrence when it is one of a series. */ private fun Task.detailRoute(): String = Dest.TaskDetail.build(taskId, occurrenceStart?.toEpochMilliseconds()) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt index 3ab3d11..e933e7e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt @@ -2,8 +2,12 @@ package de.jeanlucmakiola.agendula.ui.navigation import androidx.navigation.NavType import androidx.navigation.navArgument +import de.jeanlucmakiola.agendula.domain.Rule import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.ui.filters.RuleEditResult +import de.jeanlucmakiola.agendula.ui.filters.RuleEditViewModel +import de.jeanlucmakiola.agendula.ui.filters.RulePurpose /** * String-based route table for the app's [androidx.navigation.NavHost]. @@ -118,6 +122,47 @@ object Dest { if (filterId == null) "filterEdit" else "filterEdit?$ARG_FILTER_ID=$filterId" } + /** + * Edits a bare rule ([RuleEditScreen][de.jeanlucmakiola.agendula.ui.filters.RuleEditScreen]): + * the source of a stored block, written in place ([forBlock]), or a rule handed + * back to the opener under [RuleEditResult.KEY] in its saved state ([forResult]). + */ + object RuleEdit { + const val ARG_PURPOSE = "purpose" + const val ARG_VIEW_ID = "viewId" + const val ARG_BLOCK_ID = "blockId" + const val ARG_RULE = "rule" + const val route = "ruleEdit?$ARG_PURPOSE={$ARG_PURPOSE}&$ARG_VIEW_ID={$ARG_VIEW_ID}" + + "&$ARG_BLOCK_ID={$ARG_BLOCK_ID}&$ARG_RULE={$ARG_RULE}" + + val arguments = listOf( + navArgument(ARG_PURPOSE) { type = NavType.StringType; defaultValue = RulePurpose.SOURCE.name }, + navArgument(ARG_VIEW_ID) { type = NavType.LongType; defaultValue = NO_ID }, + navArgument(ARG_BLOCK_ID) { type = NavType.LongType; defaultValue = NO_ID }, + navArgument(ARG_RULE) { type = NavType.StringType; nullable = true; defaultValue = null }, + ) + + /** Custom rules for block [blockId] of the stored view [viewId], saved into it. */ + fun forBlock(viewId: Long, blockId: Long): String = + "ruleEdit?$ARG_PURPOSE=${RulePurpose.SOURCE.name}&$ARG_VIEW_ID=$viewId&$ARG_BLOCK_ID=$blockId" + + /** [initial], or none, edited for [purpose] and handed back as a [RuleEditResult]. */ + fun forResult(purpose: RulePurpose, initial: Rule?): String { + val base = "ruleEdit?$ARG_PURPOSE=${purpose.name}" + return if (initial == null) base else "$base&$ARG_RULE=${android.net.Uri.encode(RuleEditResult.Rules(initial).encode())}" + } + + /** Where the editor opened with [viewId], [blockId] and [rule] saves to. */ + fun targetOf(viewId: Long, blockId: Long, rule: String?): RuleEditViewModel.Target = + if (viewId != NO_ID && blockId != NO_ID) { + RuleEditViewModel.Target.Block(viewId, blockId) + } else { + RuleEditViewModel.Target.Result((rule?.let(RuleEditResult::decode) as? RuleEditResult.Rules)?.rule) + } + + fun purposeOf(name: String?): RulePurpose = RulePurpose.entries.firstOrNull { it.name == name } ?: RulePurpose.SOURCE + } + /** A single task's detail; `occ` (epoch millis) picks one occurrence of a series. */ object TaskDetail { const val ARG_TASK_ID = "taskId" diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt index f3f6f10..c67a934 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt @@ -36,6 +36,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.Rule import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.ViewIcon import de.jeanlucmakiola.agendula.domain.deletable @@ -53,12 +54,13 @@ import de.jeanlucmakiola.floret.components.Position /** * A view's settings: its name, icon and scope, the quick-add switch, and delete - * for any view but Home. The scope only shows here for now; editing it comes - * with the filter editor (#59 phase 3). + * for any view but Home. The scope opens in the rule editor ([onEditScope]), and + * comes back through [EditViewViewModel.setScope]. */ @Composable fun EditViewScreen( viewModel: EditViewViewModel, + onEditScope: (Rule?) -> Unit, onBack: () -> Unit, ) { val draft by viewModel.draft.collectAsStateWithLifecycle() @@ -116,6 +118,8 @@ fun EditViewScreen( summary = stringResource(if (view.scope == null) R.string.view_scope_none_hint else R.string.view_scope_hint), position = Position.Alone, leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { onEditScope(view.scope) }, ) SettingsHint(stringResource(R.string.view_scope_blocks_hint)) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt index a826611..a8b62b8 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt @@ -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.Rule import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.ViewIcon import de.jeanlucmakiola.agendula.domain.newView @@ -94,9 +95,12 @@ class EditViewViewModel @Inject constructor( fun setQuickAdd(on: Boolean) = _draft.update { it?.copy(quickAdd = on) } + /** Sets the scope; one that admits every task is none. */ + fun setScope(scope: Rule?) = _draft.update { it?.copy(scope = scope?.takeIf { s -> s != Rule.Everything }) } + /** - * Stores the name, icon and quick-add switch over the view as it is stored - * now, so a block changed meanwhile stays changed. A new view is shown next. + * Stores the name, icon, scope and quick-add switch over the view as it is + * stored now, so a block changed meanwhile stays changed. A new view is shown next. */ fun save(onSaved: () -> Unit) { val draft = _draft.value ?: return @@ -109,7 +113,7 @@ class EditViewViewModel @Inject constructor( onSaved() return@launch } - val view = stored?.copy(name = draft.name.trim(), icon = draft.icon, quickAdd = draft.quickAdd) + val view = stored?.copy(name = draft.name.trim(), icon = draft.icon, scope = draft.scope, quickAdd = draft.quickAdd) ?: draft.copy(name = draft.name.trim()) val id = settingsPrefs.saveView(view) if (id == null) { diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt new file mode 100644 index 0000000..015966a --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt @@ -0,0 +1,184 @@ +package de.jeanlucmakiola.agendula.ui.filters + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs +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.data.tasks.TasksRepository +import de.jeanlucmakiola.agendula.domain.Block +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.newView +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.lang.reflect.Proxy + +@OptIn(ExperimentalCoroutinesApi::class) +class RuleEditViewModelTest { + + private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders)) + private val repository = FakeRepository(listOf(list(1), list(2))) + + @BeforeEach fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterEach fun tearDown() = Dispatchers.resetMain() + + /** A view holding a tile on [source] as block 2, as stored. */ + private fun storedView(source: BlockSource): Long = runBlocking { + prefs.setStorageMode(StorageMode.OWN) + val view = newView(0, "V").let { v -> + v.copy(blocks = v.blocks.map { if (it.id == 2L) it.copy(source = source) else it }) + } + prefs.saveView(view)!! + } + + private fun block(viewId: Long): Block = runBlocking { prefs.views.first().first { it.id == viewId }.blocks.first { it.id == 2L } } + + /** An editor bound to [target], once it has loaded; the views are read off the main thread. */ + private fun editor(target: RuleEditViewModel.Target, purpose: RulePurpose) = + RuleEditViewModel(prefs, repository).apply { + bind(target, purpose) + runBlocking { state.first { it != null } } + } + + @Test + fun `a scope comes back as rules and offers no templates`() { + val scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("work"))) + val vm = editor(RuleEditViewModel.Target.Result(scope), RulePurpose.SCOPE) + assertThat(vm.state.value!!.choosingTemplate).isFalse() + assertThat(vm.state.value!!.rules.rule).isEqualTo(scope) + + vm.updateRules { draft -> draft.editSimple { it.copy(minPriority = Priority.HIGH) } } + var result: RuleEditResult? = null + vm.save { result = it } + assertThat(result).isEqualTo( + RuleEditResult.Rules( + Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.MinPriority(Priority.HIGH), Rule.AnyOf(listOf(Rule.HasTag("work"))))), + ), + ) + } + + @Test + fun `a list deleted since drops out, so its condition shows as matching nothing`() { + val scope = Rule.InList(setOf(9L)) + val vm = editor(RuleEditViewModel.Target.Result(scope), RulePurpose.SCOPE) + val draft = vm.state.value!!.rules + assertThat(draft.advanced).isTrue() + assertThat(draft.rule).isEqualTo(Rule.AllOf(listOf(Rule.InList(emptySet())))) + } + + @Test + fun `new custom rules start from a template and are written into the block`() { + val viewId = storedView(BlockSource.Smart(SmartList.OVERDUE)) + val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE) + assertThat(vm.state.value!!.choosingTemplate).isTrue() + + vm.startFrom(FilterTemplate.HIGH_PRIORITY, emptyList(), emptyList()) + assertThat(vm.state.value!!.choosingTemplate).isFalse() + var done = false + vm.save { done = it == null } + assertThat(done).isTrue() + assertThat(block(viewId).source).isEqualTo(BlockSource.Rules(Rule.AllOf(listOf(Rule.MinPriority(Priority.HIGH))))) + } + + @Test + fun `a block's custom rules open as stored`() { + val rule = Rule.AnyOf(listOf(Rule.InList(setOf(2L)), Rule.HasTag("next"))) + val viewId = storedView(BlockSource.Rules(rule)) + val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE) + assertThat(vm.state.value!!.choosingTemplate).isFalse() + assertThat(vm.state.value!!.rules.rule).isEqualTo(rule) + } + + @Test + fun `saved as a filter, the block shows the new filter`() { + val viewId = storedView(BlockSource.Smart(SmartList.ALL)) + val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE) + vm.startFrom(null, emptyList(), emptyList()) + vm.setSaveAsFilter(true) + assertThat(vm.state.value!!.canSave).isFalse() + vm.renameFilter(" Mine ") + vm.save { } + + val filter = runBlocking { prefs.savedFilters.first().single() } + assertThat(filter.name).isEqualTo("Mine") + assertThat(filter.rule).isEqualTo(Rule.Everything) + assertThat(block(viewId).source).isEqualTo(BlockSource.Filter(filter.id)) + } + + @Test + fun `a block that is gone gets no filter and says so`() { + runBlocking { prefs.setStorageMode(StorageMode.OWN) } + val vm = editor(RuleEditViewModel.Target.Block(42, 2), RulePurpose.SOURCE) + vm.startFrom(null, emptyList(), emptyList()) + vm.setSaveAsFilter(true) + vm.renameFilter("Mine") + var done = false + vm.save { done = true } + assertThat(done).isFalse() + assertThat(vm.saveFailed.value).isTrue() + assertThat(runBlocking { prefs.savedFilters.first() }).isEmpty() + } + + @Test + fun `custom rules opened for a result hand back the filter they were saved as`() { + runBlocking { prefs.setStorageMode(StorageMode.OWN) } + val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) + assertThat(vm.state.value!!.choosingTemplate).isTrue() + vm.startFrom(FilterTemplate.NO_DATE, emptyList(), emptyList()) + vm.setSaveAsFilter(true) + vm.renameFilter("Undated") + var result: RuleEditResult? = null + vm.save { result = it } + val filter = runBlocking { prefs.savedFilters.first().single() } + assertThat(result).isEqualTo(RuleEditResult.Filter(filter.id)) + } + + private class FakeRepository(private val lists: List) : TasksRepository by unsupported() { + override fun taskLists() = flowOf(lists) + override fun tasks(filter: TaskFilter): Flow> = flowOf(emptyList()) + } + + private class MemoryDataStore : DataStore { + override val data = MutableStateFlow(emptyPreferences()) + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) = + transform(data.value).also { data.value = it } + } + + private object NoProviders : ProviderEnvironment { + override fun packageDeclaring(authority: String): String? = null + override fun isGranted(permission: String) = false + override fun appLabel(packageName: String): String? = null + } + + private companion object { + fun list(id: Long) = TaskList(id, "L$id", 0, "Local", "local", isSynced = false, isVisible = true, owner = null) + + /** Fails any call the test does not expect. */ + inline fun unsupported(): T = + Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ -> + throw UnsupportedOperationException("Unexpected call: ${method.name}") + } as T + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt new file mode 100644 index 0000000..83d986f --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt @@ -0,0 +1,106 @@ +package de.jeanlucmakiola.agendula.ui.views + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs +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.data.tasks.TasksRepository +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.newView +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.lang.reflect.Proxy + +/** The scope edited in the rule editor is stored with the view (#59, #172). */ +@OptIn(ExperimentalCoroutinesApi::class) +class EditViewScopeTest { + + private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders)) + private val repository = FakeRepository() + + @BeforeEach fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterEach fun tearDown() = Dispatchers.resetMain() + + private fun editing(viewId: Long) = EditViewViewModel(prefs, ViewSession(prefs, repository, CoroutineScope(Dispatchers.Unconfined)), repository) + .apply { + bind(viewId) + runBlocking { draft.first { it != null } } + } + + /** Saves, and waits for the write, which reads the views off the main thread. */ + private fun EditViewViewModel.saveNow() = runBlocking { + val saved = CompletableDeferred() + save { saved.complete(Unit) } + withTimeout(5_000) { saved.await() } + } + + private fun stored(id: Long) = runBlocking { prefs.views.first().first { it.id == id } } + + @Test + fun `a scope set here is saved with the view`() { + val id = runBlocking { + prefs.setStorageMode(StorageMode.OWN) + prefs.saveView(newView(0, "Work"))!! + } + val scope = Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("next"))) + val vm = editing(id) + vm.setScope(scope) + vm.saveNow() + assertThat(stored(id).scope).isEqualTo(scope) + } + + @Test + fun `a scope that admits every task is none`() { + val id = runBlocking { + prefs.setStorageMode(StorageMode.OWN) + prefs.saveView(newView(0, "Work").copy(scope = Rule.HasTag("x")))!! + } + val vm = editing(id) + vm.setScope(Rule.Everything) + assertThat(vm.draft.value!!.scope).isNull() + vm.saveNow() + assertThat(stored(id).scope).isNull() + } + + private class FakeRepository : TasksRepository by unsupported() { + override fun taskLists() = flowOf(emptyList()) + } + + private class MemoryDataStore : DataStore { + override val data = MutableStateFlow(emptyPreferences()) + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) = + transform(data.value).also { data.value = it } + } + + private object NoProviders : ProviderEnvironment { + override fun packageDeclaring(authority: String): String? = null + override fun isGranted(permission: String) = false + override fun appLabel(packageName: String): String? = null + } + + private companion object { + inline fun unsupported(): T = + Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ -> + throw UnsupportedOperationException("Unexpected call: ${method.name}") + } as T + } +} From 6c468e6b38163052f8e3d67cc8a829545d3a77b9 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:37:42 +0100 Subject: [PATCH 05/16] Changelog for the filter editor and scope editing (#172, #154, #59) --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 175c493..114750b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,18 @@ All notable changes to this project are documented here. The format follows last used view, another view, a list or a saved filter. A list or filter opens over Home, so back leads there (#141). - Every view is also a launcher shortcut (#59). +- The filter editor matches *all rules* or *any rule*, and each of lists, + tags and due date can be turned round with *is / is not*, so "list Next or + tag nextAction" is one filter now. Due dates gain *This week*, *This month* + and *Next N days*. An *Advanced editor* builds nested groups of *all of* / + *any of*, each of which can be negated; a filter the simple editor can't + show opens there (#172). +- A new filter can start from a template: *Next actions (GTD)*, *This week*, + *This month*, *High priority*, *Waiting for* or *No date*. A template only + fills in the rules (#154). +- A view's scope is edited in the same editor, from *Edit view*. A block whose + list or filter was deleted can show *Custom rules* instead, which can be + saved as a filter (#59, #172). - A compact density under Settings → Appearance: shorter rows in the lists, the task lists and settings, so more fits on the screen. - A "Reduce motion" switch under Settings → Appearance takes the movement out From 7f3807c8fdc9454e0158fd7decbe2e844aadd334 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:46:32 +0100 Subject: [PATCH 06/16] Tiles and previews show custom rules; only they offer them as a source (#59, #172) --- .../agendula/ui/lists/ListsScreen.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 4c4ad48..cab8856 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -347,11 +347,15 @@ fun ListsScreen( todayOnly = choosingBlock.type == BlockType.PROGRESS, onPick = { source -> viewModel.chooseSource(content.view.id, choosingBlock.id, source) }, onDismiss = { choosingSourceFor = null }, - onCustomRules = if (choosingBlock.type == BlockType.PROGRESS) null else ({ onEditBlockRules(content.view.id, choosingBlock.id) }), + // Only a tile and a preview can show custom rules so far. + onCustomRules = if (choosingBlock.type in CUSTOM_RULE_BLOCKS) ({ onEditBlockRules(content.view.id, choosingBlock.id) }) else null, ) } } +/** The blocks that can show a [BlockSource.Rules] source. */ +private val CUSTOM_RULE_BLOCKS = setOf(BlockType.COUNT_TILE, BlockType.PREVIEW) + /** * Wording for a refused list write. * @@ -543,12 +547,13 @@ private fun Tile( modifier = modifier, ) } - BlockType.COUNT_TILE -> state.counts[block.id]?.takeIf { filter != null }?.let { count -> + // Custom rules have no screen of their own to open, so their tile only counts. + BlockType.COUNT_TILE -> state.counts[block.id]?.takeIf { filter != null || source is BlockSource.Rules }?.let { count -> CountCard( style = tileStyle(source!!, state), count = count, modifier = modifier, - onClick = { onOpenFilter(filter!!, scopeFor(block)) }, + onClick = { filter?.let { onOpenFilter(it, scopeFor(block)) } }, ) } else -> null @@ -588,7 +593,8 @@ private fun LazyListScope.previewSection( ) { // TODO(#59): inline done. val source = block.source ?: return - val filter = source.taskFilter ?: return + val filter = source.taskFilter + if (filter == null && source !is BlockSource.Rules) return val options = block.options as BlockOptions.Preview val tasks = state.previews[block.id].orEmpty() if (tasks.isEmpty()) return @@ -597,7 +603,7 @@ private fun LazyListScope.previewSection( UpcomingPreview( tasks = tasks, onOpenTask = onOpenTask, - onViewAll = if (options.showAll) ({ onOpenFilter(filter) }) else null, + onViewAll = if (options.showAll && filter != null) ({ onOpenFilter(filter) }) else null, ) } } From 8b17ba9d747b26b10ff68926c8bd66f514a77296 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:46:32 +0100 Subject: [PATCH 07/16] Templates match the lists and tags as read; rule saves drop deleted lists and reuse their filter on retry (#172, #154) --- .../agendula/ui/filters/FilterEditScreen.kt | 2 +- .../ui/filters/FilterEditViewModel.kt | 14 +++++----- .../agendula/ui/filters/RuleDraft.kt | 12 +++++++++ .../agendula/ui/filters/RuleEditScreen.kt | 2 +- .../agendula/ui/filters/RuleEditViewModel.kt | 26 +++++++++++------- .../ui/filters/RuleEditViewModelTest.kt | 27 +++++++++++++++---- 6 files changed, 60 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt index 15a91bf..e948166 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt @@ -88,7 +88,7 @@ fun FilterEditScreen( if (draft?.choosingTemplate == true) { TemplatePicker( title = stringResource(R.string.filter_new_title), - onPick = { viewModel.startFrom(it, lists, tagsInUse) }, + onPick = viewModel::startFrom, onDismiss = onBack, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt index e1a3110..f6c4106 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt @@ -80,13 +80,13 @@ class FilterEditViewModel @Inject constructor( _draft.update { it?.copy(rules = transform(it.rules)) } } - /** Starts the new filter from [template]'s rules, or from none. */ - fun startFrom(template: FilterTemplate?, lists: List, tags: List) { - _draft.update { draft -> - draft?.copy( - rules = template?.let { RuleDraft.of(it.form(lists, tags)) } ?: draft.rules, - choosingTemplate = false, - ) + /** Starts the new filter from [template]'s rules, or from none; its lists and tags are matched once they are read. */ + fun startFrom(template: FilterTemplate?) { + viewModelScope.launch { + val form = template?.let { repository.templateForm(it) } + _draft.update { draft -> + draft?.copy(rules = form?.let(RuleDraft::of) ?: draft.rules, choosingTemplate = false) + } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt index 49617d7..e23d580 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt @@ -1,10 +1,15 @@ package de.jeanlucmakiola.agendula.ui.filters +import de.jeanlucmakiola.agendula.data.tasks.TasksRepository 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.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.tagsInUse +import kotlinx.coroutines.flow.first /** * A rule being edited: [rule] is what saves, and [simple] the simple editor's @@ -42,6 +47,13 @@ data class RuleDraft(val rule: Rule, val simple: SimpleRule?) { } } +/** [template]'s form against the lists and tags in use as read now; ones that can't be read count as none. */ +internal suspend fun TasksRepository.templateForm(template: FilterTemplate): SimpleRule { + val lists = runCatching { taskLists().first() }.getOrDefault(emptyList()) + val tags = runCatching { tagsInUse(tasks(TaskFilter.Smart(SmartList.ALL)).first()) }.getOrDefault(emptyList()) + return template.form(lists, tags) +} + /** The rules a new filter can start from (#154); the user changes them as they like. */ enum class FilterTemplate { NEXT_ACTIONS, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt index 3b0524f..6923052 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt @@ -93,7 +93,7 @@ fun RuleEditScreen( if (state?.choosingTemplate == true) { TemplatePicker( title = title, - onPick = { viewModel.startFrom(it, lists, tagsInUse) }, + onPick = viewModel::startFrom, onDismiss = onBack, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt index 66ba51e..8f6b678 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt @@ -108,13 +108,13 @@ class RuleEditViewModel @Inject constructor( _state.update { it?.copy(rules = transform(it.rules)) } } - /** Starts from [template]'s rules, or from none. */ - fun startFrom(template: FilterTemplate?, lists: List, tags: List) { - _state.update { state -> - state?.copy( - rules = template?.let { RuleDraft.of(it.form(lists, tags)) } ?: state.rules, - choosingTemplate = false, - ) + /** Starts from [template]'s rules, or from none; its lists and tags are matched once they are read. */ + fun startFrom(template: FilterTemplate?) { + viewModelScope.launch { + val form = template?.let { repository.templateForm(it) } + _state.update { state -> + state?.copy(rules = form?.let(RuleDraft::of) ?: state.rules, choosingTemplate = false) + } } } @@ -133,8 +133,14 @@ class RuleEditViewModel @Inject constructor( if (saving || !state.canSave) return saving = true viewModelScope.launch { - val rules = RuleEditResult.Rules(state.rules.rule) - suspend fun asFilter() = RuleEditResult.Filter(settingsPrefs.saveFilter(SavedFilter(0, state.filterName.trim(), rules.rule))) + // Lists deleted while this was open don't come back with it. + val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull().orEmpty() + val rule = state.rules.rule.let { if (existing.isEmpty()) it else it.withoutListIds { id -> id !in existing } } + val rules = RuleEditResult.Rules(rule) + // A retry after a failed block write updates the filter made by the first try. + suspend fun asFilter() = RuleEditResult.Filter( + settingsPrefs.saveFilter(SavedFilter(savedFilterId ?: 0, state.filterName.trim(), rule)).also { savedFilterId = it }, + ) when (target) { is Target.Result -> onDone(if (state.saveAsFilter) asFilter() else rules) is Target.Block -> { @@ -151,6 +157,8 @@ class RuleEditViewModel @Inject constructor( } } + private var savedFilterId: Long? = null + private suspend fun writeSource(target: Target.Block, source: BlockSource): Boolean = settingsPrefs.updateView(target.viewId) { view -> view.copy(blocks = view.blocks.map { if (it.id == target.blockId) it.copy(source = source) else it }) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt index 015966a..e6f92c4 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt @@ -94,7 +94,7 @@ class RuleEditViewModelTest { val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE) assertThat(vm.state.value!!.choosingTemplate).isTrue() - vm.startFrom(FilterTemplate.HIGH_PRIORITY, emptyList(), emptyList()) + vm.startFrom(FilterTemplate.HIGH_PRIORITY) assertThat(vm.state.value!!.choosingTemplate).isFalse() var done = false vm.save { done = it == null } @@ -115,7 +115,7 @@ class RuleEditViewModelTest { fun `saved as a filter, the block shows the new filter`() { val viewId = storedView(BlockSource.Smart(SmartList.ALL)) val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE) - vm.startFrom(null, emptyList(), emptyList()) + vm.startFrom(null) vm.setSaveAsFilter(true) assertThat(vm.state.value!!.canSave).isFalse() vm.renameFilter(" Mine ") @@ -131,7 +131,7 @@ class RuleEditViewModelTest { fun `a block that is gone gets no filter and says so`() { runBlocking { prefs.setStorageMode(StorageMode.OWN) } val vm = editor(RuleEditViewModel.Target.Block(42, 2), RulePurpose.SOURCE) - vm.startFrom(null, emptyList(), emptyList()) + vm.startFrom(null) vm.setSaveAsFilter(true) vm.renameFilter("Mine") var done = false @@ -146,7 +146,7 @@ class RuleEditViewModelTest { runBlocking { prefs.setStorageMode(StorageMode.OWN) } val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) assertThat(vm.state.value!!.choosingTemplate).isTrue() - vm.startFrom(FilterTemplate.NO_DATE, emptyList(), emptyList()) + vm.startFrom(FilterTemplate.NO_DATE) vm.setSaveAsFilter(true) vm.renameFilter("Undated") var result: RuleEditResult? = null @@ -155,7 +155,24 @@ class RuleEditViewModelTest { assertThat(result).isEqualTo(RuleEditResult.Filter(filter.id)) } - private class FakeRepository(private val lists: List) : TasksRepository by unsupported() { + @Test + fun `lists deleted while the editor was open don't come back with the rules`() { + val vm = editor(RuleEditViewModel.Target.Result(Rule.InList(setOf(1L, 2L))), RulePurpose.SCOPE) + repository.lists = listOf(list(1)) + var result: RuleEditResult? = null + vm.save { result = it } + assertThat(result).isEqualTo(RuleEditResult.Rules(Rule.InList(setOf(1L)))) + } + + @Test + fun `a template matches the lists and tags as read, not as shown so far`() { + repository.lists = listOf(list(1), TaskList(5, "Next", 0, "Local", "local", isSynced = false, isVisible = true, owner = null)) + val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) + vm.startFrom(FilterTemplate.NEXT_ACTIONS) + assertThat(vm.state.value!!.rules.simple!!.listIds).containsExactly(5L) + } + + private class FakeRepository(var lists: List) : TasksRepository by unsupported() { override fun taskLists() = flowOf(lists) override fun tasks(filter: TaskFilter): Flow> = flowOf(emptyList()) } From 17821cff4e3ade3d497b91e179a6c3c03b8300f4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:46:32 +0100 Subject: [PATCH 08/16] A scope that admits every task by its shape is stored as none (#59, #172) --- .../agendula/ui/filters/RuleTree.kt | 20 +++++++++++++++++++ .../agendula/ui/views/ViewsViewModels.kt | 5 +++-- .../agendula/ui/filters/RuleDraftTest.kt | 14 +++++++++++++ .../agendula/ui/views/EditViewScopeTest.kt | 2 ++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt index 2c90b93..5c817ca 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleTree.kt @@ -121,6 +121,26 @@ private fun Rule.withoutDoubleNegation(): Rule = when (this) { is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this } +/** Whether every task passes this rule by its shape alone, as an empty all-of group does. */ +val Rule.admitsEverything: Boolean + get() = when (this) { + is Rule.AllOf -> children.all { it.admitsEverything } + is Rule.AnyOf -> children.any { it.admitsEverything } + is Rule.Not -> child.matchesNothing + is Rule.MinPriority -> priority == Priority.NONE + is Rule.InList, is Rule.HasTag, is Rule.Due -> false + } + +/** Whether no task passes this rule by its shape alone, as an empty any-of group or a list condition naming no list. */ +val Rule.matchesNothing: Boolean + get() = when (this) { + is Rule.AllOf -> children.any { it.matchesNothing } + is Rule.AnyOf -> children.all { it.matchesNothing } + is Rule.Not -> child.admitsEverything + is Rule.InList -> listIds.isEmpty() && elsewhere.isEmpty() + is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> false + } + /** The values a due condition offers, besides "next N days". */ val DUE_CHOICES: List = DueWindow.entries.map(DueSpec::Window) + listOf(DueSpec.ThisWeek, DueSpec.ThisMonth) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt index a8b62b8..776d31d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt @@ -9,6 +9,7 @@ import de.jeanlucmakiola.agendula.domain.Rule import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.ViewIcon import de.jeanlucmakiola.agendula.domain.newView +import de.jeanlucmakiola.agendula.ui.filters.admitsEverything import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -95,8 +96,8 @@ class EditViewViewModel @Inject constructor( fun setQuickAdd(on: Boolean) = _draft.update { it?.copy(quickAdd = on) } - /** Sets the scope; one that admits every task is none. */ - fun setScope(scope: Rule?) = _draft.update { it?.copy(scope = scope?.takeIf { s -> s != Rule.Everything }) } + /** Sets the scope; one that admits every task, however it is written, is none. */ + fun setScope(scope: Rule?) = _draft.update { it?.copy(scope = scope?.takeUnless { s -> s.admitsEverything }) } /** * Stores the name, icon, scope and quick-add switch over the view as it is diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt index c015238..2ca1292 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt @@ -128,6 +128,20 @@ class RuleDraftTest { .isEqualTo(SimpleRule(match = Match.ANY, tags = setOf("nextAction"))) } + @Test + fun `a rule that admits every task by its shape is told apart from one that narrows`() { + val empty = Rule.AllOf(emptyList()) + val nothing = Rule.AnyOf(emptyList()) + assertThat(Rule.AllOf(listOf(empty)).admitsEverything).isTrue() + assertThat(Rule.AllOf(listOf(Rule.Not(nothing))).admitsEverything).isTrue() + assertThat(Rule.Not(Rule.InList(emptySet())).admitsEverything).isTrue() + assertThat(Rule.MinPriority(Priority.NONE).admitsEverything).isTrue() + assertThat(Rule.AnyOf(listOf(work, empty)).admitsEverything).isTrue() + assertThat(Rule.AllOf(listOf(work, empty)).admitsEverything).isFalse() + assertThat(Rule.Not(Rule.InList(emptySet(), setOf("EXTERNAL:1"))).admitsEverything).isFalse() + assertThat(nothing.admitsEverything).isFalse() + } + @Test fun `a result survives the trip between screens`() { val rule = Rule.AllOf(listOf(Rule.InList(setOf(3L), setOf("EXTERNAL:9")), Rule.Not(Rule.HasTag("a,b(c)")), Rule.Due(DueSpec.NextDays(5)))) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt index 83d986f..5eb4d32 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/views/EditViewScopeTest.kt @@ -75,6 +75,8 @@ class EditViewScopeTest { prefs.saveView(newView(0, "Work").copy(scope = Rule.HasTag("x")))!! } val vm = editing(id) + vm.setScope(Rule.AllOf(listOf(Rule.AllOf(emptyList())))) + assertThat(vm.draft.value!!.scope).isNull() vm.setScope(Rule.Everything) assertThat(vm.draft.value!!.scope).isNull() vm.saveNow() From 5f6ddfaf55c25ea88d4455d2a177c87eb0867b8b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:46:32 +0100 Subject: [PATCH 09/16] Advanced editor groups sit on grouped surfaces with connected condition rows (#172) --- .../agendula/ui/filters/AdvancedEditor.kt | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt index c57590a..0f49884 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/AdvancedEditor.kt @@ -1,18 +1,17 @@ package de.jeanlucmakiola.agendula.ui.filters -import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.ArrowDropDown @@ -48,7 +47,9 @@ import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSurface import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.FloretDensity /** A picker the advanced editor has open, for the node at [path]. */ @@ -148,13 +149,12 @@ private fun GroupCard( val match = group.groupMatch ?: Match.ALL val children = group.groupChildren val nested = path.isNotEmpty() - Surface( - shape = RoundedCornerShape(24.dp), - color = if (path.size % 2 == 0) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.surface, - border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - modifier = modifier.fillMaxWidth(), + GroupedSurface( + position = Position.Alone, + color = if (path.size % 2 == 0) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.surfaceContainer, + modifier = modifier, ) { - Column(Modifier.padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Column(Modifier.padding(vertical = 8.dp)) { GroupHeader( match = match, negated = group.negated, @@ -166,6 +166,7 @@ private fun GroupCard( onToggleNot = { onChange { it.updateAt(path, Rule::toggleNot) } }, onDelete = { onChange { it.removeAt(path) } }, ) + Spacer(Modifier.height(4.dp)) if (children.isEmpty()) { GroupedHint( stringResource(if (match == Match.ALL) R.string.filter_group_empty_all else R.string.filter_group_empty_any), @@ -182,11 +183,12 @@ private fun GroupCard( listNames = listNames, onChange = onChange, onPick = onPick, - modifier = Modifier.padding(horizontal = 8.dp), + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), ) } else { ConditionRow( condition = child, + position = conditionPosition(children, index), listNames = listNames, onField = { onPick(Picking.Field(childPath, adding = false)) }, onValue = { child.field?.let { onPick(Picking.Value(childPath, it, adding = false)) } }, @@ -284,6 +286,7 @@ private fun GroupHeader( @Composable private fun ConditionRow( condition: Rule, + position: Position, listNames: Map, onField: () -> Unit, onValue: () -> Unit, @@ -293,7 +296,7 @@ private fun ConditionRow( val field = condition.field ?: return GroupedRow( title = conditionValue(condition.positive, listNames), - position = Position.Alone, + position = position, minHeight = FloretDensity.nestedRowHeight, leading = { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { @@ -310,6 +313,15 @@ private fun ConditionRow( ) } +/** Where the condition at [index] sits in its run of conditions, which read as one connected list. */ +private fun conditionPosition(children: List, index: Int): Position { + var first = index + while (first > 0 && !children[first - 1].isGroup) first-- + var last = index + while (last < children.lastIndex && !children[last + 1].isGroup) last++ + return positionOf(index - first, last - first + 1) +} + /** * A small pill inside a row, tapped in place: a group's kind, a condition's field * or operator. [toggles] marks one that switches between two values, which reads From d6ea0091f8b3f79f0d19e9168bb83d0e022f468a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:46:44 +0100 Subject: [PATCH 10/16] Changelog: custom rules are for tiles and previews (#59, #172) --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 114750b..6b62054 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,9 +33,9 @@ All notable changes to this project are documented here. The format follows - A new filter can start from a template: *Next actions (GTD)*, *This week*, *This month*, *High priority*, *Waiting for* or *No date*. A template only fills in the rules (#154). -- A view's scope is edited in the same editor, from *Edit view*. A block whose - list or filter was deleted can show *Custom rules* instead, which can be - saved as a filter (#59, #172). +- A view's scope is edited in the same editor, from *Edit view*. A tile or + preview whose list or filter was deleted can show *Custom rules* instead, + which can be saved as a filter (#59, #172). - A compact density under Settings → Appearance: shorter rows in the lists, the task lists and settings, so more fits on the screen. - A "Reduce motion" switch under Settings → Appearance takes the movement out From 879ae7e24419b3dcfc64d70be59ad1700813faff Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:58:19 +0100 Subject: [PATCH 11/16] Custom-rules tiles and previews are named by their rules and lead back to the source picker (#59, #172) --- .../agendula/ui/lists/ListsScreen.kt | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index cab8856..8707d47 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -105,6 +105,7 @@ import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel import de.jeanlucmakiola.agendula.ui.tasklist.UndoReceipt import de.jeanlucmakiola.agendula.ui.tasklist.rememberTaskRows import de.jeanlucmakiola.agendula.ui.tasklist.taskRows +import de.jeanlucmakiola.agendula.ui.views.scopeSummary import de.jeanlucmakiola.agendula.ui.views.ScopeChipRow import de.jeanlucmakiola.agendula.ui.views.ViewSwitcher import de.jeanlucmakiola.agendula.ui.views.viewName @@ -443,7 +444,7 @@ private fun ListsContent( val open = { filter: TaskFilter -> onOpenFilter(filter, scopeFor(block)) } val sections = state.sectionsFor(block) when (block.type) { - BlockType.PREVIEW -> previewSection(block, state, open, onOpenTask) + BlockType.PREVIEW -> previewSection(block, state, open, onOpenTask, onChooseSource) BlockType.LISTS -> listsSection( key = "${block.id}", options = block.options as BlockOptions.Lists, @@ -553,7 +554,8 @@ private fun Tile( style = tileStyle(source!!, state), count = count, modifier = modifier, - onClick = { filter?.let { onOpenFilter(it, scopeFor(block)) } }, + // Tapped, custom rules open the source picker, which edits or replaces them. + onClick = { if (filter != null) onOpenFilter(filter, scopeFor(block)) else onChooseSource(block.id) }, ) } else -> null @@ -590,6 +592,7 @@ private fun LazyListScope.previewSection( state: ListsUiState.Content, onOpenFilter: (TaskFilter) -> Unit, onOpenTask: (Task) -> Unit, + onChooseSource: (Long) -> Unit, ) { // TODO(#59): inline done. val source = block.source ?: return @@ -603,7 +606,12 @@ private fun LazyListScope.previewSection( UpcomingPreview( tasks = tasks, onOpenTask = onOpenTask, - onViewAll = if (options.showAll && filter != null) ({ onOpenFilter(filter) }) else null, + // Custom rules have no screen to show all of; theirs leads to the source picker instead. + onViewAll = when { + !options.showAll -> null + filter != null -> ({ onOpenFilter(filter) }) + else -> ({ onChooseSource(block.id) }) + }, ) } } @@ -615,7 +623,7 @@ private fun sourceLabel(source: BlockSource, state: ListsUiState.Content): Strin is BlockSource.List -> state.lists.firstOrNull { it.id == source.listId }?.name.orEmpty() is BlockSource.Tag -> source.tag is BlockSource.Filter -> state.filterNames[source.filterId].orEmpty() - is BlockSource.Rules -> stringResource(R.string.view_source_custom_label) + is BlockSource.Rules -> scopeSummary(source.rule, state.lists.associate { it.id to it.name }) is BlockSource.ListElsewhere -> "" } From 4aaa1b3a111d097e8fe8684d5222e8037e8705fc Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:58:19 +0100 Subject: [PATCH 12/16] First template pick wins, and a block gone meanwhile isn't reported saved (#172, #154) --- .../ui/filters/FilterEditViewModel.kt | 10 ++++++---- .../agendula/ui/filters/RuleEditViewModel.kt | 19 +++++++++++++------ .../ui/filters/RuleEditViewModelTest.kt | 19 +++++++++++++++++++ 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt index f6c4106..f153fef 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt @@ -82,11 +82,13 @@ class FilterEditViewModel @Inject constructor( /** Starts the new filter from [template]'s rules, or from none; its lists and tags are matched once they are read. */ fun startFrom(template: FilterTemplate?) { + // The picker closes on the first pick; a later tap while the lists are read is ignored. + if (_draft.value?.choosingTemplate != true) return + _draft.update { it?.copy(choosingTemplate = false) } + if (template == null) return viewModelScope.launch { - val form = template?.let { repository.templateForm(it) } - _draft.update { draft -> - draft?.copy(rules = form?.let(RuleDraft::of) ?: draft.rules, choosingTemplate = false) - } + val form = repository.templateForm(template) + _draft.update { it?.copy(rules = RuleDraft.of(form)) } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt index 8f6b678..85442e2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt @@ -110,11 +110,13 @@ class RuleEditViewModel @Inject constructor( /** Starts from [template]'s rules, or from none; its lists and tags are matched once they are read. */ fun startFrom(template: FilterTemplate?) { + // The picker closes on the first pick; a later tap while the lists are read is ignored. + if (_state.value?.choosingTemplate != true) return + _state.update { it?.copy(choosingTemplate = false) } + if (template == null) return viewModelScope.launch { - val form = template?.let { repository.templateForm(it) } - _state.update { state -> - state?.copy(rules = form?.let(RuleDraft::of) ?: state.rules, choosingTemplate = false) - } + val form = repository.templateForm(template) + _state.update { it?.copy(rules = RuleDraft.of(form)) } } } @@ -159,8 +161,13 @@ class RuleEditViewModel @Inject constructor( private var savedFilterId: Long? = null - private suspend fun writeSource(target: Target.Block, source: BlockSource): Boolean = - settingsPrefs.updateView(target.viewId) { view -> + /** Points the block at [source]; false when it can't be written or is gone. */ + private suspend fun writeSource(target: Target.Block, source: BlockSource): Boolean { + var found = false + val written = settingsPrefs.updateView(target.viewId) { view -> + found = view.blocks.any { it.id == target.blockId } view.copy(blocks = view.blocks.map { if (it.id == target.blockId) it.copy(source = source) else it }) } + return written && found + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt index e6f92c4..9c10cd6 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt @@ -141,6 +141,25 @@ class RuleEditViewModelTest { assertThat(runBlocking { prefs.savedFilters.first() }).isEmpty() } + @Test + fun `a block removed from its view meanwhile isn't reported saved`() { + val viewId = storedView(BlockSource.Smart(SmartList.ALL)) + val vm = editor(RuleEditViewModel.Target.Block(viewId, 99), RulePurpose.SOURCE) + vm.startFrom(null) + var done = false + vm.save { done = true } + assertThat(done).isFalse() + assertThat(vm.saveFailed.value).isTrue() + } + + @Test + fun `a second template tap while the first is read is ignored`() { + val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) + vm.startFrom(null) + vm.startFrom(FilterTemplate.HIGH_PRIORITY) + assertThat(vm.state.value!!.rules.rule).isEqualTo(Rule.Everything) + } + @Test fun `custom rules opened for a result hand back the filter they were saved as`() { runBlocking { prefs.setStorageMode(StorageMode.OWN) } From 02f842016f283c69190f424e3df06a35e772bf82 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:58:19 +0100 Subject: [PATCH 13/16] is / is not only on sections that pick something; the simple form survives a look at the advanced editor (#172) --- .../agendula/ui/filters/RuleDraft.kt | 23 +++++++++++------ .../agendula/ui/filters/RuleEditor.kt | 25 ++++++++++++------- .../agendula/ui/filters/SimpleRule.kt | 7 ++++++ .../agendula/ui/filters/RuleDraftTest.kt | 17 +++++++++++++ 4 files changed, 55 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt index e23d580..72f7169 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt @@ -17,27 +17,34 @@ import kotlinx.coroutines.flow.first * kept apart so a choice the rule can't hold, like *any rule* with nothing * picked, survives while editing. */ -data class RuleDraft(val rule: Rule, val simple: SimpleRule?) { +data class RuleDraft(val rule: Rule, val simple: SimpleRule?, private val left: SimpleRule? = null) { val advanced: Boolean get() = simple == null /** Whether the simple editor can show the rule as it is now. */ val canSimplify: Boolean get() = simple != null || SimpleRule.of(rule) != null - /** Changes the simple form, and the rule with it; nothing in the advanced editor. */ + /** Changes the simple form, and the rule with them; nothing in the advanced editor. */ fun editSimple(transform: (SimpleRule) -> SimpleRule): RuleDraft { - val form = simple?.let(transform) ?: return this + val form = simple?.let(transform)?.tidy() ?: return this return RuleDraft(form.toRule(), form) } /** Changes the rule in the advanced editor; nothing in the simple one. */ - fun editAdvanced(transform: (Rule) -> Rule): RuleDraft = if (simple != null) this else RuleDraft(transform(rule), null) + fun editAdvanced(transform: (Rule) -> Rule): RuleDraft = if (simple != null) this else copy(rule = transform(rule)) - /** Over to the advanced editor, which can show any rule. */ - fun toAdvanced(): RuleDraft = RuleDraft(rule.forAdvanced(), null) + /** Over to the advanced editor, which can show any rule; the simple form is kept for the way back. */ + fun toAdvanced(): RuleDraft = RuleDraft(rule.forAdvanced(), null, simple) - /** Over to the simple editor, when it can show the rule; the rule stays as it is. */ - fun toSimple(): RuleDraft = if (simple != null) this else SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: this + /** + * Over to the simple editor, when it can show the rule; the rule stays as it + * is. Unchanged since leaving it, the form comes back as it was left. + */ + fun toSimple(): RuleDraft = when { + simple != null -> this + left != null && left.toRule() == rule -> RuleDraft(rule, left) + else -> SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: this + } companion object { /** [rule] in the simple editor when it can show it, else in the advanced one. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt index c86a051..32b2235 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt @@ -106,7 +106,7 @@ private fun SimpleSections( ) if (lists.isNotEmpty()) { - NegatableHeader(stringResource(R.string.filter_section_lists), form.listsNegated) { negated -> + NegatableHeader(stringResource(R.string.filter_section_lists), form.listsNegated, shown = !form.anyList) { negated -> onChange { it.copy(listsNegated = negated) } } val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1 @@ -115,7 +115,7 @@ private fun SimpleSections( position = positionOf(0, lists.size + 1), selected = form.anyList, leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) }, - onClick = { onChange { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) } }, + onClick = { onChange { it.copy(listIds = emptySet(), listsElsewhere = emptySet(), listsNegated = false) } }, ) lists.forEachIndexed { index, list -> ChoiceRow( @@ -134,14 +134,14 @@ private fun SimpleSections( (tagsInUse + form.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER) } if (tags.isNotEmpty()) { - NegatableHeader(stringResource(R.string.filter_section_tags), form.tagsNegated) { negated -> + NegatableHeader(stringResource(R.string.filter_section_tags), form.tagsNegated, shown = form.tags.isNotEmpty()) { negated -> onChange { it.copy(tagsNegated = negated) } } ChoiceRow( title = stringResource(R.string.filter_any_tag), position = positionOf(0, tags.size + 1), selected = form.tags.isEmpty(), - onClick = { onChange { it.copy(tags = emptySet()) } }, + onClick = { onChange { it.copy(tags = emptySet(), tagsNegated = false) } }, ) tags.forEachIndexed { index, tag -> ChoiceRow( @@ -165,7 +165,7 @@ private fun SimpleSections( } } - NegatableHeader(stringResource(R.string.filter_section_due), form.dueNegated) { negated -> + NegatableHeader(stringResource(R.string.filter_section_due), form.dueNegated, shown = form.due.isNotEmpty()) { negated -> onChange { it.copy(dueNegated = negated) } } val windows = listOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.Window(DueWindow.TODAY), DueSpec.Window(DueWindow.UPCOMING)) @@ -175,7 +175,7 @@ private fun SimpleSections( title = stringResource(R.string.filter_any_due), position = positionOf(0, rows), selected = form.due.isEmpty(), - onClick = { onChange { it.copy(due = emptySet()) } }, + onClick = { onChange { it.copy(due = emptySet(), dueNegated = false) } }, ) (windows + ranges).forEachIndexed { index, spec -> ChoiceRow( @@ -229,9 +229,16 @@ private fun SimpleSections( } } -/** A section header with an *is / is not* switch at its end. */ +/** + * A section header with an *is / is not* switch at its end, [shown] while the + * section picks something; "any" can't be turned round. + */ @Composable -private fun NegatableHeader(title: String, negated: Boolean, onNegate: (Boolean) -> Unit) { +private fun NegatableHeader(title: String, negated: Boolean, shown: Boolean, onNegate: (Boolean) -> Unit) { + if (!shown) { + GroupedSectionHeader(title) + return + } Row(verticalAlignment = Alignment.Bottom) { GroupedSectionHeader(title, Modifier.weight(1f)) ConnectedChoiceRow( @@ -245,7 +252,7 @@ private fun NegatableHeader(title: String, negated: Boolean, onNegate: (Boolean) } /** Room for the *is / is not* pair, its inset included. */ -private val NEGATE_WIDTH = 200.dp +private val NEGATE_WIDTH = 240.dp @Composable internal fun ChoiceRow( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt index ea4497d..782686d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/SimpleRule.kt @@ -56,6 +56,13 @@ data class SimpleRule( fun withNextDays(spec: DueSpec.NextDays?): SimpleRule = copy(due = due.filterNot { it is DueSpec.NextDays }.toSet() + listOfNotNull(spec)) + /** This form with *is not* dropped from the sections that pick nothing, where it can't apply. */ + fun tidy(): SimpleRule = copy( + dueNegated = dueNegated && due.isNotEmpty(), + listsNegated = listsNegated && !anyList, + tagsNegated = tagsNegated && tags.isNotEmpty(), + ) + fun toRule(): Rule { val parts = buildList { if (due.isNotEmpty()) add(Rule.AnyOf(due.sortedBy(::dueRank).map(Rule::Due)).negatedIf(dueNegated)) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt index 2ca1292..d0cc62a 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt @@ -53,6 +53,23 @@ class RuleDraftTest { assertThat(advanced.editSimple { it.copy(minPriority = Priority.LOW) }).isEqualTo(advanced) } + @Test + fun `a look at the advanced editor brings the simple form back as it was left`() { + val any = RuleDraft.of(SimpleRule()).editSimple { it.copy(match = Match.ANY) } + assertThat(any.toAdvanced().toSimple().simple!!.match).isEqualTo(Match.ANY) + val changed = any.toAdvanced().editAdvanced { it.addTo(emptyList(), work) } + assertThat(changed.toSimple().simple).isEqualTo(SimpleRule(listIds = setOf(1L))) + } + + @Test + fun `is not drops out of a section once nothing in it is picked`() { + val draft = RuleDraft.of(SimpleRule(tags = setOf("a"), tagsNegated = true)) + .editSimple { it.copy(tags = emptySet()) } + assertThat(draft.simple!!.tagsNegated).isFalse() + assertThat(draft.editSimple { it.copy(tags = setOf("b")) }.rule) + .isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("b")))))) + } + @Test fun `the simple form keeps a choice its rule can't hold`() { val any = RuleDraft.of(SimpleRule()).editSimple { it.copy(match = Match.ANY) } From 34657f90ff6cbd6db992243f607aae621149093e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:58:19 +0100 Subject: [PATCH 14/16] Tag conditions can name a tag no task carries yet (#172) --- .../agendula/ui/filters/RulePickers.kt | 65 +++++++++++++++---- .../agendula/ui/navigation/AgendulaNavHost.kt | 2 +- app/src/main/res/values/strings.xml | 2 + 3 files changed, 55 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt index 1245464..daa5959 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.agendula.ui.filters +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding @@ -23,10 +24,13 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.DueSpec @@ -39,8 +43,11 @@ import de.jeanlucmakiola.floret.components.CustomAmountEditor import de.jeanlucmakiola.floret.components.CustomExpandRow import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSurface +import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf @@ -202,26 +209,58 @@ internal fun ListsPicker( } } -/** The tag a tag condition names, from the ones in use. */ +/** The tag a tag condition names: one in use, or another one typed in. */ @Composable internal fun TagPicker(tags: List, selected: String?, onSelect: (String) -> Unit, onDismiss: () -> Unit) { val options = remember(tags, selected) { (tags + listOfNotNull(selected)).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER) } - if (options.isEmpty()) { - FullScreenPicker(title = stringResource(R.string.filter_section_tags), onDismiss = onDismiss) { - GroupedHint(stringResource(R.string.filter_tags_none)) + val pick = { tag: String -> + onSelect(tag) + onDismiss() + } + FullScreenPicker(title = stringResource(R.string.filter_section_tags), onDismiss = onDismiss) { + if (options.isEmpty()) GroupedHint(stringResource(R.string.filter_tags_none)) + val count = options.size + 1 + options.forEachIndexed { index, tag -> + GroupedRow( + title = tag, + position = positionOf(index, count), + checked = tag == selected, + onClick = { pick(tag) }, + ) } - return + var expanded by rememberSaveable { mutableStateOf(options.isEmpty()) } + var typed by rememberSaveable { mutableStateOf("") } + CustomExpandRow( + title = stringResource(R.string.filter_tag_other), + position = positionOf(options.size, count), + expanded = expanded, + onExpandedChange = { expanded = it }, + ) { + GroupedSurface(position = Position.Bottom, modifier = Modifier.padding(horizontal = GroupedListInset)) { + Row( + modifier = Modifier.padding(start = 16.dp, end = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InlineTextField( + value = typed, + onValueChange = { typed = it }, + placeholder = stringResource(R.string.filter_tag_other_hint), + capitalization = KeyboardCapitalization.None, + imeAction = ImeAction.Done, + onImeAction = { typed.trim().takeIf { it.isNotEmpty() }?.let(pick) }, + modifier = Modifier.weight(1f).padding(vertical = 12.dp), + ) + TextButton( + onClick = { pick(typed.trim()) }, + enabled = typed.isNotBlank(), + ) { Text(stringResource(R.string.reminder_custom_set)) } + } + } + } + Spacer(Modifier.height(16.dp)) } - OptionPicker( - title = stringResource(R.string.filter_section_tags), - options = options, - selected = selected, - label = { it.orEmpty() }, - onSelect = { it?.let(onSelect) }, - onDismiss = onDismiss, - ) } /** The priority a priority condition asks for at least. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt index 40dabbd..9d40dc7 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt @@ -18,6 +18,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.ui.Modifier import androidx.compose.ui.unit.IntOffset import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.domain.smartListNamed import de.jeanlucmakiola.agendula.domain.Task import kotlin.time.Instant @@ -35,7 +36,6 @@ import de.jeanlucmakiola.agendula.ui.filters.RuleEditResult import de.jeanlucmakiola.agendula.ui.filters.RuleEditScreen import de.jeanlucmakiola.agendula.ui.filters.RuleEditViewModel import de.jeanlucmakiola.agendula.ui.filters.RulePurpose -import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.ui.imports.ImportScreen import de.jeanlucmakiola.agendula.ui.lists.ListsScreen import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b51008f..b3df0b7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -355,6 +355,8 @@ No list No lists yet. No open task has a tag yet. + Other tag… + Tag Start empty Pick every rule yourself Templates From a1c43d5bb276ab9606277b16f0e47cca57ce9aff Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 15:12:13 +0100 Subject: [PATCH 15/16] =?UTF-8?q?Templates=20name=20an=20unnamed=20filter?= =?UTF-8?q?=20and=20Next=20actions=20asks=20for=20its=20list;=20the=20simp?= =?UTF-8?q?le=20editor's=20tags=20get=20Other=20tag=E2=80=A6=20(#154,=20#1?= =?UTF-8?q?72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 5 +- .../agendula/ui/filters/FilterEditScreen.kt | 5 +- .../ui/filters/FilterEditViewModel.kt | 18 ++- .../agendula/ui/filters/RuleDraft.kt | 19 ++- .../agendula/ui/filters/RuleEditScreen.kt | 5 +- .../agendula/ui/filters/RuleEditViewModel.kt | 18 ++- .../agendula/ui/filters/RuleEditor.kt | 7 +- .../agendula/ui/filters/RulePickers.kt | 128 +++++++++++++----- app/src/main/res/values/strings.xml | 7 +- .../agendula/ui/filters/RuleDraftTest.kt | 9 +- .../ui/filters/RuleEditViewModelTest.kt | 17 ++- 11 files changed, 164 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b62054..3b5a444 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,8 +31,9 @@ All notable changes to this project are documented here. The format follows *any of*, each of which can be negated; a filter the simple editor can't show opens there (#172). - A new filter can start from a template: *Next actions (GTD)*, *This week*, - *This month*, *High priority*, *Waiting for* or *No date*. A template only - fills in the rules (#154). + *This month*, *High priority*, *Waiting for* or *No date*. It fills in the + rules and, if the filter has none yet, its name; *Next actions* asks which + list holds them. A tag no task carries yet can be typed in (#154, #172). - A view's scope is edited in the same editor, from *Edit view*. A tile or preview whose list or filter was deleted can show *Custom rules* instead, which can be saved as a filter (#59, #172). diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt index e948166..a0e096e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt @@ -86,9 +86,10 @@ fun FilterEditScreen( } if (draft?.choosingTemplate == true) { - TemplatePicker( + TemplateChooser( + lists = lists, title = stringResource(R.string.filter_new_title), - onPick = viewModel::startFrom, + onStart = viewModel::startFrom, onDismiss = onBack, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt index f153fef..9487bdb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt @@ -80,14 +80,22 @@ class FilterEditViewModel @Inject constructor( _draft.update { it?.copy(rules = transform(it.rules)) } } - /** Starts the new filter from [template]'s rules, or from none; its lists and tags are matched once they are read. */ - fun startFrom(template: FilterTemplate?) { - // The picker closes on the first pick; a later tap while the lists are read is ignored. + /** + * Starts the new filter from [template]'s rules, or from none; *Next actions* + * with [nextList]. An unnamed filter takes the template's [name]. + */ + fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) { + // The picker closes on the first pick; a later tap while the tags are read is ignored. if (_draft.value?.choosingTemplate != true) return - _draft.update { it?.copy(choosingTemplate = false) } + _draft.update { draft -> + draft?.copy( + filter = if (name != null && draft.filter.name.isBlank()) draft.filter.copy(name = name) else draft.filter, + choosingTemplate = false, + ) + } if (template == null) return viewModelScope.launch { - val form = repository.templateForm(template) + val form = repository.templateForm(template, nextList) _draft.update { it?.copy(rules = RuleDraft.of(form)) } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt index 72f7169..454dd8b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraft.kt @@ -7,7 +7,6 @@ import de.jeanlucmakiola.agendula.domain.Priority import de.jeanlucmakiola.agendula.domain.Rule import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.TaskFilter -import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.tagsInUse import kotlinx.coroutines.flow.first @@ -54,11 +53,10 @@ data class RuleDraft(val rule: Rule, val simple: SimpleRule?, private val left: } } -/** [template]'s form against the lists and tags in use as read now; ones that can't be read count as none. */ -internal suspend fun TasksRepository.templateForm(template: FilterTemplate): SimpleRule { - val lists = runCatching { taskLists().first() }.getOrDefault(emptyList()) +/** [template]'s form against the tags in use as read now (none when they can't be), [nextList] for *Next actions*. */ +internal suspend fun TasksRepository.templateForm(template: FilterTemplate, nextList: Long?): SimpleRule { val tags = runCatching { tagsInUse(tasks(TaskFilter.Smart(SmartList.ALL)).first()) }.getOrDefault(emptyList()) - return template.form(lists, tags) + return template.form(nextList, tags) } /** The rules a new filter can start from (#154); the user changes them as they like. */ @@ -72,16 +70,16 @@ enum class FilterTemplate { ; /** - * The template's rules. Lists and tags are matched by name, ignoring case, - * to [lists] and [tags] (the ones in use); a tag not in use yet is taken as - * written, a list that doesn't exist is left out. + * The template's rules. *Next actions* is [nextList] or the next-action tag, + * the tag alone without a list. Tags are matched by name, ignoring case, to + * [tags] (the ones in use); one not in use yet is taken as written. */ - fun form(lists: List, tags: List): SimpleRule { + fun form(nextList: Long?, tags: List): SimpleRule { fun tag(name: String) = tags.firstOrNull { it.equals(name, ignoreCase = true) } ?: name return when (this) { NEXT_ACTIONS -> SimpleRule( match = Match.ANY, - listIds = lists.filter { it.name.trim().equals(NEXT_LIST, ignoreCase = true) }.mapTo(HashSet()) { it.id }, + listIds = setOfNotNull(nextList), tags = setOf(tag(NEXT_ACTION_TAG)), ) THIS_WEEK -> SimpleRule(due = setOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.ThisWeek)) @@ -93,7 +91,6 @@ enum class FilterTemplate { } private companion object { - const val NEXT_LIST = "Next" const val NEXT_ACTION_TAG = "nextAction" const val WAITING_TAG = "waiting" } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt index 6923052..fa93fdb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditScreen.kt @@ -91,9 +91,10 @@ fun RuleEditScreen( } if (state?.choosingTemplate == true) { - TemplatePicker( + TemplateChooser( + lists = lists, title = title, - onPick = viewModel::startFrom, + onStart = viewModel::startFrom, onDismiss = onBack, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt index 85442e2..df2e40b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt @@ -108,14 +108,22 @@ class RuleEditViewModel @Inject constructor( _state.update { it?.copy(rules = transform(it.rules)) } } - /** Starts from [template]'s rules, or from none; its lists and tags are matched once they are read. */ - fun startFrom(template: FilterTemplate?) { - // The picker closes on the first pick; a later tap while the lists are read is ignored. + /** + * Starts from [template]'s rules, or from none; *Next actions* with + * [nextList]. [name] goes to an unnamed *Save as filter*. + */ + fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) { + // The picker closes on the first pick; a later tap while the tags are read is ignored. if (_state.value?.choosingTemplate != true) return - _state.update { it?.copy(choosingTemplate = false) } + _state.update { state -> + state?.copy( + filterName = if (name != null && state.filterName.isBlank()) name else state.filterName, + choosingTemplate = false, + ) + } if (template == null) return viewModelScope.launch { - val form = repository.templateForm(template) + val form = repository.templateForm(template, nextList) _state.update { it?.copy(rules = RuleDraft.of(form)) } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt index 32b2235..c60d017 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt @@ -133,24 +133,25 @@ private fun SimpleSections( val tags = remember(tagsInUse, form.tags) { (tagsInUse + form.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER) } - if (tags.isNotEmpty()) { + run { NegatableHeader(stringResource(R.string.filter_section_tags), form.tagsNegated, shown = form.tags.isNotEmpty()) { negated -> onChange { it.copy(tagsNegated = negated) } } ChoiceRow( title = stringResource(R.string.filter_any_tag), - position = positionOf(0, tags.size + 1), + position = positionOf(0, tags.size + 2), selected = form.tags.isEmpty(), onClick = { onChange { it.copy(tags = emptySet(), tagsNegated = false) } }, ) tags.forEachIndexed { index, tag -> ChoiceRow( title = tag, - position = positionOf(index + 1, tags.size + 1), + position = positionOf(index + 1, tags.size + 2), selected = tag in form.tags, onClick = { onChange { it.copy(tags = it.tags.toggle(tag)) } }, ) } + OtherTagRow(position = positionOf(tags.size + 1, tags.size + 2), onAdd = { tag -> onChange { it.copy(tags = it.tags + tag) } }) if (form.tags.size > 1) { Spacer(Modifier.height(8.dp)) GroupedSwitchRow( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt index daa5959..8208a08 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt @@ -230,36 +230,51 @@ internal fun TagPicker(tags: List, selected: String?, onSelect: (String) onClick = { pick(tag) }, ) } - var expanded by rememberSaveable { mutableStateOf(options.isEmpty()) } - var typed by rememberSaveable { mutableStateOf("") } - CustomExpandRow( - title = stringResource(R.string.filter_tag_other), - position = positionOf(options.size, count), - expanded = expanded, - onExpandedChange = { expanded = it }, - ) { - GroupedSurface(position = Position.Bottom, modifier = Modifier.padding(horizontal = GroupedListInset)) { - Row( - modifier = Modifier.padding(start = 16.dp, end = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - InlineTextField( - value = typed, - onValueChange = { typed = it }, - placeholder = stringResource(R.string.filter_tag_other_hint), - capitalization = KeyboardCapitalization.None, - imeAction = ImeAction.Done, - onImeAction = { typed.trim().takeIf { it.isNotEmpty() }?.let(pick) }, - modifier = Modifier.weight(1f).padding(vertical = 12.dp), - ) - TextButton( - onClick = { pick(typed.trim()) }, - enabled = typed.isNotBlank(), - ) { Text(stringResource(R.string.reminder_custom_set)) } + OtherTagRow(position = positionOf(options.size, count), startExpanded = options.isEmpty(), onAdd = pick) + Spacer(Modifier.height(16.dp)) + } +} + +/** + * The "Other tag…" row closing a run of tag rows: it opens a field for a tag no + * open task carries yet, and [onAdd] gets the tag typed, trimmed. + */ +@Composable +internal fun OtherTagRow(position: Position, onAdd: (String) -> Unit, startExpanded: Boolean = false) { + var expanded by rememberSaveable { mutableStateOf(startExpanded) } + var typed by rememberSaveable { mutableStateOf("") } + val add = { + typed.trim().takeIf { it.isNotEmpty() }?.let { + onAdd(it) + typed = "" + expanded = false + } + } + CustomExpandRow( + title = stringResource(R.string.filter_tag_other), + position = position, + expanded = expanded, + onExpandedChange = { expanded = it }, + ) { + GroupedSurface(position = Position.Bottom, modifier = Modifier.padding(horizontal = GroupedListInset)) { + Row( + modifier = Modifier.padding(start = 16.dp, end = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InlineTextField( + value = typed, + onValueChange = { typed = it }, + placeholder = stringResource(R.string.filter_tag_other_hint), + capitalization = KeyboardCapitalization.None, + imeAction = ImeAction.Done, + onImeAction = { add() }, + modifier = Modifier.weight(1f).padding(vertical = 12.dp), + ) + TextButton(onClick = { add() }, enabled = typed.isNotBlank()) { + Text(stringResource(R.string.reminder_custom_set)) } } } - Spacer(Modifier.height(16.dp)) } } @@ -277,18 +292,36 @@ internal fun PriorityPicker(selected: Priority?, onSelect: (Priority) -> Unit, o } /** - * Where new rules start: empty, or one of the [FilterTemplate]s. [onPick] gets - * `null` for empty; [onDismiss] leaves without starting. + * Where new rules start: empty, or one of the [FilterTemplate]s. *Next actions* + * first asks which of [lists] holds them, which can be skipped. [onStart] gets + * the template (`null` for empty), that list, and the template's name for an + * unnamed filter; [onDismiss] leaves without starting. */ @Composable -internal fun TemplatePicker(title: String, onPick: (FilterTemplate?) -> Unit, onDismiss: () -> Unit) { +internal fun TemplateChooser( + title: String, + lists: List, + onStart: (template: FilterTemplate?, nextList: Long?, name: String?) -> Unit, + onDismiss: () -> Unit, +) { + var askingList by rememberSaveable { mutableStateOf(false) } + if (askingList) { + val name = stringResource(templateLabels(FilterTemplate.NEXT_ACTIONS).first) + NextListPicker( + lists = lists, + onPick = { onStart(FilterTemplate.NEXT_ACTIONS, it, name) }, + onDismiss = { askingList = false }, + ) + return + } + val names = FilterTemplate.entries.associateWith { stringResource(templateLabels(it).first) } FullScreenPicker(title = title, onDismiss = onDismiss) { GroupedRow( title = stringResource(R.string.filter_template_empty), summary = stringResource(R.string.filter_template_empty_hint), position = Position.Alone, leading = { CategoryIcon(Icons.Rounded.Add, ChipAccent.Primary) }, - onClick = { onPick(null) }, + onClick = { onStart(null, null, null) }, ) GroupedSectionHeader(stringResource(R.string.filter_templates_header)) FilterTemplate.entries.forEachIndexed { index, template -> @@ -298,7 +331,9 @@ internal fun TemplatePicker(title: String, onPick: (FilterTemplate?) -> Unit, on summary = stringResource(hint), position = positionOf(index, FilterTemplate.entries.size), leading = { CategoryIcon(icon, ChipAccent.Primary) }, - onClick = { onPick(template) }, + onClick = { + if (template == FilterTemplate.NEXT_ACTIONS) askingList = true else onStart(template, null, names[template]) + }, ) } GroupedHint(stringResource(R.string.filter_templates_note), verticalPadding = 8.dp) @@ -306,6 +341,35 @@ internal fun TemplatePicker(title: String, onPick: (FilterTemplate?) -> Unit, on } } +/** Which list holds the next actions; [onPick] gets `null` when skipped, for the tag alone. */ +@Composable +private fun NextListPicker(lists: List, onPick: (Long?) -> Unit, onDismiss: () -> Unit) { + FullScreenPicker( + title = stringResource(R.string.filter_template_gtd_list_title), + onDismiss = onDismiss, + actions = { + TextButton(onClick = { onPick(null) }, modifier = Modifier.padding(end = 8.dp)) { + Text(stringResource(R.string.filter_template_gtd_skip)) + } + }, + ) { + GroupedHint(stringResource(R.string.filter_template_gtd_list_hint)) + Spacer(Modifier.height(8.dp)) + if (lists.isEmpty()) GroupedHint(stringResource(R.string.filter_lists_none)) + val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1 + lists.forEachIndexed { index, list -> + GroupedRow( + title = list.name, + summary = list.accountName.takeIf { showAccount }, + position = positionOf(index, lists.size), + leading = { ListColorChip(list.color) }, + onClick = { onPick(list.id) }, + ) + } + Spacer(Modifier.height(16.dp)) + } +} + private fun templateLabels(template: FilterTemplate): Triple = when (template) { FilterTemplate.NEXT_ACTIONS -> Triple(R.string.filter_template_gtd, R.string.filter_template_gtd_hint, Icons.Rounded.Bolt) FilterTemplate.THIS_WEEK -> Triple(R.string.filter_template_week, R.string.filter_template_week_hint, Icons.Rounded.CalendarViewWeek) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b3df0b7..973112c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -360,9 +360,12 @@ Start empty Pick every rule yourself Templates - A template only fills in the rules. You can change everything afterwards. + A template fills in the rules and a name. You can change everything afterwards. Next actions (GTD) - List “Next” or tag nextAction + A list of your choice, or tag nextAction + Next actions list + Which list holds your next actions? Tasks tagged nextAction show too. Skip to go by the tag alone. + Skip This week Due this week, overdue included This month diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt index d0cc62a..561a971 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleDraftTest.kt @@ -5,7 +5,6 @@ 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.TaskList import org.junit.jupiter.api.Test class RuleDraftTest { @@ -120,9 +119,8 @@ class RuleDraftTest { @Test fun `templates fill in the rules they name`() { - val lists = listOf(list(1, "Inbox"), list(2, " next "), list(3, "Work")) val tags = listOf("Waiting", "nextaction") - fun rule(template: FilterTemplate) = template.form(lists, tags).toRule() + fun rule(template: FilterTemplate) = template.form(nextList = 2L, tags = tags).toRule() assertThat(rule(FilterTemplate.NEXT_ACTIONS)).isEqualTo( Rule.AnyOf(listOf(Rule.InList(setOf(2L)), Rule.AnyOf(listOf(Rule.HasTag("nextaction"))))), @@ -140,8 +138,8 @@ class RuleDraftTest { } @Test - fun `without a Next list or tags in use the GTD template still asks for the tag`() { - assertThat(FilterTemplate.NEXT_ACTIONS.form(emptyList(), emptyList())) + fun `with the list skipped and no tags in use the GTD template still asks for the tag`() { + assertThat(FilterTemplate.NEXT_ACTIONS.form(nextList = null, tags = emptyList())) .isEqualTo(SimpleRule(match = Match.ANY, tags = setOf("nextAction"))) } @@ -169,5 +167,4 @@ class RuleDraftTest { assertThat(RuleEditResult.decode("other")).isNull() } - private fun list(id: Long, name: String) = TaskList(id, name, 0, "Local", "local", isSynced = false, isVisible = true, owner = null) } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt index 9c10cd6..d33b8ec 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt @@ -184,11 +184,20 @@ class RuleEditViewModelTest { } @Test - fun `a template matches the lists and tags as read, not as shown so far`() { - repository.lists = listOf(list(1), TaskList(5, "Next", 0, "Local", "local", isSynced = false, isVisible = true, owner = null)) + fun `the GTD template takes the list picked for it and names an unnamed filter`() { val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) - vm.startFrom(FilterTemplate.NEXT_ACTIONS) - assertThat(vm.state.value!!.rules.simple!!.listIds).containsExactly(5L) + vm.startFrom(FilterTemplate.NEXT_ACTIONS, nextList = 2L, name = "Next actions") + assertThat(vm.state.value!!.rules.simple) + .isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(2L), tags = setOf("nextAction"))) + assertThat(vm.state.value!!.filterName).isEqualTo("Next actions") + } + + @Test + fun `a template's name doesn't replace one already typed`() { + val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) + vm.renameFilter("Mine") + vm.startFrom(FilterTemplate.NO_DATE, name = "No date") + assertThat(vm.state.value!!.filterName).isEqualTo("Mine") } private class FakeRepository(var lists: List) : TasksRepository by unsupported() { From 28d80cb986624479ad6917f43de192dca2599abb Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 15:22:47 +0100 Subject: [PATCH 16/16] Template rules and name land together, typed tags take the spelling in use, GTD filters are named Next actions (#154, #172) --- .../agendula/ui/filters/FilterEditScreen.kt | 2 +- .../ui/filters/FilterEditViewModel.kt | 24 ++++++++++--------- .../agendula/ui/filters/RuleEditViewModel.kt | 24 ++++++++++--------- .../agendula/ui/filters/RuleEditor.kt | 2 +- .../agendula/ui/filters/RulePickers.kt | 21 +++++++++------- app/src/main/res/values/strings.xml | 1 + .../ui/filters/RuleEditViewModelTest.kt | 9 ++++--- 7 files changed, 48 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt index a0e096e..ce5e043 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditScreen.kt @@ -65,7 +65,7 @@ fun FilterEditScreen( NameField( name = filter.name, placeholder = stringResource(R.string.filter_name_hint), - autoFocus = isNew && !current.choosingTemplate, + autoFocus = isNew && !current.choosingTemplate && filter.name.isEmpty(), onNameChange = viewModel::rename, onImeAction = save, ) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt index 9487bdb..fd6502f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/FilterEditViewModel.kt @@ -85,21 +85,23 @@ class FilterEditViewModel @Inject constructor( * with [nextList]. An unnamed filter takes the template's [name]. */ fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) { - // The picker closes on the first pick; a later tap while the tags are read is ignored. - if (_draft.value?.choosingTemplate != true) return - _draft.update { draft -> - draft?.copy( - filter = if (name != null && draft.filter.name.isBlank()) draft.filter.copy(name = name) else draft.filter, - choosingTemplate = false, - ) - } - if (template == null) return + // The first pick wins; the picker stays up, and the editor untouched, until its rules are read. + if (_draft.value?.choosingTemplate != true || starting) return + starting = true viewModelScope.launch { - val form = repository.templateForm(template, nextList) - _draft.update { it?.copy(rules = RuleDraft.of(form)) } + val form = template?.let { repository.templateForm(it, nextList) } + _draft.update { draft -> + draft?.copy( + filter = if (name != null && draft.filter.name.isBlank()) draft.filter.copy(name = name) else draft.filter, + rules = form?.let(RuleDraft::of) ?: draft.rules, + choosingTemplate = false, + ) + } } } + private var starting = false + private fun load(filter: SavedFilter) { _draft.value = Draft(filter, RuleDraft.of(filter.rule)) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt index df2e40b..e73fb36 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModel.kt @@ -113,21 +113,23 @@ class RuleEditViewModel @Inject constructor( * [nextList]. [name] goes to an unnamed *Save as filter*. */ fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) { - // The picker closes on the first pick; a later tap while the tags are read is ignored. - if (_state.value?.choosingTemplate != true) return - _state.update { state -> - state?.copy( - filterName = if (name != null && state.filterName.isBlank()) name else state.filterName, - choosingTemplate = false, - ) - } - if (template == null) return + // The first pick wins; the picker stays up, and the editor untouched, until its rules are read. + if (_state.value?.choosingTemplate != true || starting) return + starting = true viewModelScope.launch { - val form = repository.templateForm(template, nextList) - _state.update { it?.copy(rules = RuleDraft.of(form)) } + val form = template?.let { repository.templateForm(it, nextList) } + _state.update { state -> + state?.copy( + rules = form?.let(RuleDraft::of) ?: state.rules, + filterName = if (name != null && state.filterName.isBlank()) name else state.filterName, + choosingTemplate = false, + ) + } } } + private var starting = false + fun setSaveAsFilter(on: Boolean) = _state.update { it?.copy(saveAsFilter = on) } fun renameFilter(name: String) = _state.update { it?.copy(filterName = name) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt index c60d017..3be6e89 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditor.kt @@ -151,7 +151,7 @@ private fun SimpleSections( onClick = { onChange { it.copy(tags = it.tags.toggle(tag)) } }, ) } - OtherTagRow(position = positionOf(tags.size + 1, tags.size + 2), onAdd = { tag -> onChange { it.copy(tags = it.tags + tag) } }) + OtherTagRow(position = positionOf(tags.size + 1, tags.size + 2), known = tags, onAdd = { tag -> onChange { it.copy(tags = it.tags + tag) } }) if (form.tags.size > 1) { Spacer(Modifier.height(8.dp)) GroupedSwitchRow( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt index 8208a08..fcb1c0b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/filters/RulePickers.kt @@ -230,22 +230,24 @@ internal fun TagPicker(tags: List, selected: String?, onSelect: (String) onClick = { pick(tag) }, ) } - OtherTagRow(position = positionOf(options.size, count), startExpanded = options.isEmpty(), onAdd = pick) + OtherTagRow(position = positionOf(options.size, count), known = options, startExpanded = options.isEmpty(), onAdd = pick) Spacer(Modifier.height(16.dp)) } } /** * The "Other tag…" row closing a run of tag rows: it opens a field for a tag no - * open task carries yet, and [onAdd] gets the tag typed, trimmed. + * open task carries yet, and [onAdd] gets the tag typed, trimmed, in the + * spelling of one of [known] that differs only in case. */ @Composable -internal fun OtherTagRow(position: Position, onAdd: (String) -> Unit, startExpanded: Boolean = false) { +internal fun OtherTagRow(position: Position, known: List, onAdd: (String) -> Unit, startExpanded: Boolean = false) { var expanded by rememberSaveable { mutableStateOf(startExpanded) } var typed by rememberSaveable { mutableStateOf("") } val add = { - typed.trim().takeIf { it.isNotEmpty() }?.let { - onAdd(it) + typed.trim().takeIf { it.isNotEmpty() }?.let { tag -> + // Tags match exactly, so one differing only in case takes the spelling in use. + onAdd(known.firstOrNull { it.equals(tag, ignoreCase = true) } ?: tag) typed = "" expanded = false } @@ -306,7 +308,7 @@ internal fun TemplateChooser( ) { var askingList by rememberSaveable { mutableStateOf(false) } if (askingList) { - val name = stringResource(templateLabels(FilterTemplate.NEXT_ACTIONS).first) + val name = stringResource(templateName(FilterTemplate.NEXT_ACTIONS)) NextListPicker( lists = lists, onPick = { onStart(FilterTemplate.NEXT_ACTIONS, it, name) }, @@ -314,7 +316,7 @@ internal fun TemplateChooser( ) return } - val names = FilterTemplate.entries.associateWith { stringResource(templateLabels(it).first) } + val names = FilterTemplate.entries.associateWith { stringResource(templateName(it)) } FullScreenPicker(title = title, onDismiss = onDismiss) { GroupedRow( title = stringResource(R.string.filter_template_empty), @@ -355,7 +357,6 @@ private fun NextListPicker(lists: List, onPick: (Long?) -> Unit, onDis ) { GroupedHint(stringResource(R.string.filter_template_gtd_list_hint)) Spacer(Modifier.height(8.dp)) - if (lists.isEmpty()) GroupedHint(stringResource(R.string.filter_lists_none)) val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1 lists.forEachIndexed { index, list -> GroupedRow( @@ -370,6 +371,10 @@ private fun NextListPicker(lists: List, onPick: (Long?) -> Unit, onDis } } +/** The name a filter made from [template] starts with. */ +private fun templateName(template: FilterTemplate): Int = + if (template == FilterTemplate.NEXT_ACTIONS) R.string.filter_template_gtd_name else templateLabels(template).first + private fun templateLabels(template: FilterTemplate): Triple = when (template) { FilterTemplate.NEXT_ACTIONS -> Triple(R.string.filter_template_gtd, R.string.filter_template_gtd_hint, Icons.Rounded.Bolt) FilterTemplate.THIS_WEEK -> Triple(R.string.filter_template_week, R.string.filter_template_week_hint, Icons.Rounded.CalendarViewWeek) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 973112c..f1c7dac 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -363,6 +363,7 @@ A template fills in the rules and a name. You can change everything afterwards. Next actions (GTD) A list of your choice, or tag nextAction + Next actions Next actions list Which list holds your next actions? Tasks tagged nextAction show too. Skip to go by the tag alone. Skip diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt index d33b8ec..27a65c8 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/filters/RuleEditViewModelTest.kt @@ -19,6 +19,7 @@ import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.newView +import de.jeanlucmakiola.agendula.domain.testTask import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow @@ -184,11 +185,12 @@ class RuleEditViewModelTest { } @Test - fun `the GTD template takes the list picked for it and names an unnamed filter`() { + fun `the GTD template takes the list picked for it, the tag as spelt in use, and names an unnamed filter`() { + repository.tasks = listOf(testTask(tags = listOf("NEXTACTION"))) val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE) vm.startFrom(FilterTemplate.NEXT_ACTIONS, nextList = 2L, name = "Next actions") assertThat(vm.state.value!!.rules.simple) - .isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(2L), tags = setOf("nextAction"))) + .isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(2L), tags = setOf("NEXTACTION"))) assertThat(vm.state.value!!.filterName).isEqualTo("Next actions") } @@ -201,8 +203,9 @@ class RuleEditViewModelTest { } private class FakeRepository(var lists: List) : TasksRepository by unsupported() { + var tasks: List = emptyList() override fun taskLists() = flowOf(lists) - override fun tasks(filter: TaskFilter): Flow> = flowOf(emptyList()) + override fun tasks(filter: TaskFilter): Flow> = flowOf(tasks) } private class MemoryDataStore : DataStore {