Custom rules are offered for every block that takes a source: for a deleted source straight into the block, and when adding a block or in a block's settings through the editor's result, so settings keep their Save.
This commit is contained in:
commit
5910c1fca3
25 files changed
+2864
-210
No files matched your search
+16
-3
@@ -24,6 +24,19 @@ 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*. 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*. Any block
|
||||
that shows tasks can show *Custom rules* instead of a list or filter, 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
|
||||
@@ -33,12 +46,12 @@ All notable changes to this project are documented here. The format follows
|
||||
stay still. The system setting does the same whatever the switch says (#157).
|
||||
- Edit layout, from a view's ⋮ menu, from Edit view, or by long-pressing a
|
||||
block: drag blocks into a new order, make tiles half or full width, remove a
|
||||
block (with undo) and add new ones. Tapping a block opens its settings: its
|
||||
block (with undo) and add new ones; ✓ keeps the changes, ✕ undoes them all. Tapping a block opens its settings: its
|
||||
title, what it shows, its own options, and whether it ignores the view's
|
||||
scope, which a small mark on the block then shows (#59).
|
||||
- New blocks: count tiles of any list, tag, filter or smart list with their
|
||||
own title, colour and icon; progress of any of those, also half width; previews of 3, 5 or
|
||||
10 tasks that can be checked off in place; recently completed, unchecked to
|
||||
own title, colour and icon; progress of any of those, also half width;
|
||||
previews of 3, 5 or 10 tasks that can be checked off in place; recently completed, unchecked to
|
||||
undo; a week strip with a dot per task due, opening a day's tasks; and
|
||||
section headings. Tiles follow the compact density too (#59).
|
||||
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
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.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.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]. */
|
||||
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<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
onChange: ((Rule) -> Rule) -> Unit,
|
||||
) {
|
||||
var picking by remember { mutableStateOf<Picking?>(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<Long, String>,
|
||||
onChange: ((Rule) -> Rule) -> Unit,
|
||||
onPick: (Picking) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val match = group.groupMatch ?: Match.ALL
|
||||
val children = group.groupChildren
|
||||
val nested = path.isNotEmpty()
|
||||
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)) {
|
||||
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) } },
|
||||
)
|
||||
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),
|
||||
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, 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)) } },
|
||||
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,
|
||||
position: Position,
|
||||
listNames: Map<Long, String>,
|
||||
onField: () -> Unit,
|
||||
onValue: () -> Unit,
|
||||
onToggleNot: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
val field = condition.field ?: return
|
||||
GroupedRow(
|
||||
title = conditionValue(condition.positive, listNames),
|
||||
position = position,
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the condition at [index] sits in its run of conditions, which read as one connected list. */
|
||||
private fun conditionPosition(children: List<Rule>, 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
|
||||
* 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<Long, String>): 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 -> ""
|
||||
}
|
||||
@@ -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 && filter.name.isEmpty(),
|
||||
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,12 @@ 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) {
|
||||
TemplateChooser(
|
||||
lists = lists,
|
||||
title = stringResource(R.string.filter_new_title),
|
||||
onStart = viewModel::startFrom,
|
||||
onDismiss = onBack,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -133,149 +110,3 @@ fun FilterEditScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The flat criteria: due windows, priority, lists and tags. */
|
||||
@Composable
|
||||
private fun CriteriaSections(
|
||||
criteria: FilterCriteria,
|
||||
lists: List<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
viewModel: FilterEditViewModel,
|
||||
onChoosePriority: () -> Unit,
|
||||
) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_due))
|
||||
val windows = DueWindow.entries
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_due),
|
||||
position = positionOf(0, windows.size + 1),
|
||||
selected = criteria.due.isEmpty(),
|
||||
onClick = { viewModel.updateCriteria { it.copy(due = emptySet()) } },
|
||||
)
|
||||
windows.forEachIndexed { index, window ->
|
||||
ChoiceRow(
|
||||
title = dueWindowLabel(window),
|
||||
position = positionOf(index + 1, windows.size + 1),
|
||||
selected = window in criteria.due,
|
||||
onClick = { viewModel.updateCriteria { it.copy(due = it.due.toggle(window)) } },
|
||||
)
|
||||
}
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
|
||||
GroupedRow(
|
||||
title = minPriorityLabel(criteria.minPriority),
|
||||
position = Position.Alone,
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = onChoosePriority,
|
||||
)
|
||||
|
||||
if (lists.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_lists))
|
||||
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_list),
|
||||
position = positionOf(0, lists.size + 1),
|
||||
selected = criteria.anyList,
|
||||
onClick = { viewModel.updateCriteria { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) } },
|
||||
)
|
||||
lists.forEachIndexed { index, list ->
|
||||
ChoiceRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index + 1, lists.size + 1),
|
||||
selected = list.id in criteria.listIds,
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { viewModel.updateCriteria { it.copy(listIds = it.listIds.toggle(list.id)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// A tag no open task carries any more stays listed while the filter uses
|
||||
// it, so it can still be unticked.
|
||||
val tags = remember(tagsInUse, criteria.tags) {
|
||||
(tagsInUse + criteria.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
|
||||
}
|
||||
if (tags.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_tags))
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_tag),
|
||||
position = positionOf(0, tags.size + 1),
|
||||
selected = criteria.tags.isEmpty(),
|
||||
onClick = { viewModel.updateCriteria { it.copy(tags = emptySet()) } },
|
||||
)
|
||||
tags.forEachIndexed { index, tag ->
|
||||
ChoiceRow(
|
||||
title = tag,
|
||||
position = positionOf(index + 1, tags.size + 1),
|
||||
selected = tag in criteria.tags,
|
||||
onClick = { viewModel.updateCriteria { it.copy(tags = it.tags.toggle(tag)) } },
|
||||
)
|
||||
}
|
||||
if (criteria.tags.size > 1) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_match_all_tags),
|
||||
summary = stringResource(
|
||||
if (criteria.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
|
||||
),
|
||||
position = Position.Alone,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = criteria.tagMatch == TagMatch.ALL,
|
||||
onCheckedChange = { all ->
|
||||
viewModel.updateCriteria { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) }
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.updateCriteria { it.copy(tagMatch = if (it.tagMatch == TagMatch.ALL) TagMatch.ANY else TagMatch.ALL) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChoiceRow(
|
||||
title: String,
|
||||
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 <T> Set<T>.toggle(item: T): Set<T> = 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
|
||||
},
|
||||
)
|
||||
@@ -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<Draft?>(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,39 @@ 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) {
|
||||
_draft.update { draft ->
|
||||
val criteria = draft?.criteria?.let(transform) ?: return@update draft
|
||||
Draft(draft.filter.copy(rule = criteria.toRule()), criteria)
|
||||
/** 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; *Next actions*
|
||||
* with [nextList]. An unnamed filter takes the template's [name].
|
||||
*/
|
||||
fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) {
|
||||
// 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 = 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, 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 {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
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.tagsInUse
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
/**
|
||||
* 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?, 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 them; nothing in the advanced editor. */
|
||||
fun editSimple(transform: (SimpleRule) -> SimpleRule): RuleDraft {
|
||||
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 copy(rule = transform(rule))
|
||||
|
||||
/** 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. 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. */
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/** [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(nextList, tags)
|
||||
}
|
||||
|
||||
/** 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. *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(nextList: Long?, tags: List<String>): SimpleRule {
|
||||
fun tag(name: String) = tags.firstOrNull { it.equals(name, ignoreCase = true) } ?: name
|
||||
return when (this) {
|
||||
NEXT_ACTIONS -> SimpleRule(
|
||||
match = Match.ANY,
|
||||
listIds = setOfNotNull(nextList),
|
||||
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_ACTION_TAG = "nextAction"
|
||||
const val WAITING_TAG = "waiting"
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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) {
|
||||
TemplateChooser(
|
||||
lists = lists,
|
||||
title = title,
|
||||
onStart = viewModel::startFrom,
|
||||
onDismiss = onBack,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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<State?>(null)
|
||||
|
||||
/** `null` until [bind] has loaded the rule. */
|
||||
val state: StateFlow<State?> = _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<Boolean> = _saveFailed.asStateFlow()
|
||||
|
||||
val lists: StateFlow<List<TaskList>> = repository.taskLists()
|
||||
.catch { emit(emptyList()) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
/** Every tag on an open task. */
|
||||
val tags: StateFlow<List<String>> = 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; *Next actions* with
|
||||
* [nextList]. [name] goes to an unnamed *Save as filter*.
|
||||
*/
|
||||
fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) {
|
||||
// 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 = 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) }
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
// 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 -> {
|
||||
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 var savedFilterId: Long? = null
|
||||
|
||||
/** 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
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<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
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<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
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, shown = !form.anyList) { 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(), listsNegated = false) } },
|
||||
)
|
||||
lists.forEachIndexed { index, list ->
|
||||
ChoiceRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index + 1, lists.size + 1),
|
||||
selected = list.id in 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)
|
||||
}
|
||||
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 + 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 + 2),
|
||||
selected = tag in form.tags,
|
||||
onClick = { onChange { it.copy(tags = it.tags.toggle(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(
|
||||
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, 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))
|
||||
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(), dueNegated = false) } },
|
||||
)
|
||||
(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, [shown] while the
|
||||
* section picks something; "any" can't be turned round.
|
||||
*/
|
||||
@Composable
|
||||
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(
|
||||
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 = 240.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 <T> Set<T>.toggle(item: T): Set<T> = 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
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,402 @@
|
||||
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.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.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
|
||||
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.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
|
||||
|
||||
/**
|
||||
* 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<TaskList>,
|
||||
selected: Set<Long>,
|
||||
onDone: (Set<Long>) -> 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: one in use, or another one typed in. */
|
||||
@Composable
|
||||
internal fun TagPicker(tags: List<String>, selected: String?, onSelect: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
val options = remember(tags, selected) {
|
||||
(tags + listOfNotNull(selected)).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
|
||||
}
|
||||
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) },
|
||||
)
|
||||
}
|
||||
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, in the
|
||||
* spelling of one of [known] that differs only in case.
|
||||
*/
|
||||
@Composable
|
||||
internal fun OtherTagRow(position: Position, known: List<String>, 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 { 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
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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. *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 TemplateChooser(
|
||||
title: String,
|
||||
lists: List<TaskList>,
|
||||
onStart: (template: FilterTemplate?, nextList: Long?, name: String?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var askingList by rememberSaveable { mutableStateOf(false) }
|
||||
if (askingList) {
|
||||
val name = stringResource(templateName(FilterTemplate.NEXT_ACTIONS))
|
||||
NextListPicker(
|
||||
lists = lists,
|
||||
onPick = { onStart(FilterTemplate.NEXT_ACTIONS, it, name) },
|
||||
onDismiss = { askingList = false },
|
||||
)
|
||||
return
|
||||
}
|
||||
val names = FilterTemplate.entries.associateWith { stringResource(templateName(it)) }
|
||||
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 = { onStart(null, null, 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 = {
|
||||
if (template == FilterTemplate.NEXT_ACTIONS) askingList = true else onStart(template, null, names[template])
|
||||
},
|
||||
)
|
||||
}
|
||||
GroupedHint(stringResource(R.string.filter_templates_note), verticalPadding = 8.dp)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** Which list holds the next actions; [onPick] gets `null` when skipped, for the tag alone. */
|
||||
@Composable
|
||||
private fun NextListPicker(lists: List<TaskList>, 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))
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
/** 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<Int, Int, ImageVector> = 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
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
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<Int>
|
||||
|
||||
/** 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<Rule>
|
||||
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>): 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
|
||||
}
|
||||
|
||||
/** 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<DueSpec> = 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<Int> = 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<Priority> = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH)
|
||||
@@ -0,0 +1,202 @@
|
||||
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<DueSpec> = emptySet(),
|
||||
val dueNegated: Boolean = false,
|
||||
val listIds: Set<Long> = emptySet(),
|
||||
val listsElsewhere: Set<String> = emptySet(),
|
||||
val listsNegated: Boolean = false,
|
||||
val tags: Set<String> = 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))
|
||||
|
||||
/** 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))
|
||||
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<DueSpec>, 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<String>, 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<Rule>, 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<Piece>, 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
|
||||
@@ -83,6 +83,7 @@ import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.agendula.ui.common.priorityAccent
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel
|
||||
import de.jeanlucmakiola.agendula.ui.views.scopeSummary
|
||||
import de.jeanlucmakiola.agendula.ui.views.vector
|
||||
import de.jeanlucmakiola.floret.components.ActionButton
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
@@ -150,7 +151,7 @@ internal fun sourceLabel(source: BlockSource, state: ListsUiState.Content): Stri
|
||||
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.block_source_rules)
|
||||
is BlockSource.Rules -> scopeSummary(source.rule, state.lists.associate { it.id to it.name })
|
||||
is BlockSource.ListElsewhere -> ""
|
||||
}
|
||||
|
||||
|
||||
@@ -61,9 +61,11 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockOptions
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.BlockWidth
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSearch
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
@@ -112,6 +114,10 @@ fun ListsScreen(
|
||||
onEditView: (Long) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onNewFilter: () -> Unit = {},
|
||||
onEditBlockRules: (viewId: Long, blockId: Long) -> Unit = { _, _ -> },
|
||||
onEditRules: (initial: Rule?) -> Unit = {},
|
||||
rulesResult: BlockSource? = null,
|
||||
onRulesResultTaken: () -> Unit = {},
|
||||
viewModel: ListsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
@@ -361,6 +367,8 @@ fun ListsScreen(
|
||||
withCompletedList = choosingBlock.type != BlockType.PROGRESS,
|
||||
onPick = { source -> viewModel.chooseSource(content.view.id, choosingBlock.id, source) },
|
||||
onDismiss = { choosingSourceFor = null },
|
||||
// Every block that takes a source can show custom rules.
|
||||
onCustomRules = { onEditBlockRules(content.view.id, choosingBlock.id) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -390,6 +398,12 @@ fun ListsScreen(
|
||||
}
|
||||
|
||||
if (content == null || !editing) return
|
||||
// Custom rules come back from their editor for the block being added, or the settings open.
|
||||
LaunchedEffect(rulesResult) {
|
||||
val source = rulesResult ?: return@LaunchedEffect
|
||||
viewModel.takeRulesResult(source)
|
||||
onRulesResultTaken()
|
||||
}
|
||||
if (addingBlock) {
|
||||
AddBlockPicker(
|
||||
blocks = content.view.blocks,
|
||||
@@ -407,6 +421,10 @@ fun ListsScreen(
|
||||
withCompletedList = type != BlockType.PROGRESS,
|
||||
onPick = { source -> viewModel.addBlock(content.view.id, type, source) },
|
||||
onDismiss = { addingType = null },
|
||||
onCustomRules = {
|
||||
viewModel.awaitRulesFor(RulesRequest.Add(content.view.id, type))
|
||||
onEditRules(null)
|
||||
},
|
||||
)
|
||||
}
|
||||
val open = draft?.takeIf { it.viewId == content.view.id }
|
||||
@@ -432,6 +450,10 @@ fun ListsScreen(
|
||||
withCompletedList = open.block.type != BlockType.PROGRESS,
|
||||
onPick = { source -> viewModel.updateDraft { it.copy(source = source) } },
|
||||
onDismiss = { choosingDraftSource = false },
|
||||
onCustomRules = {
|
||||
viewModel.awaitRulesFor(RulesRequest.Draft)
|
||||
onEditRules((open.block.source as? BlockSource.Rules)?.rule)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +125,15 @@ data class RemovedBlock(val viewId: Long, val block: Block, val index: Int)
|
||||
/** The blocks of view [viewId] when its layout editing began, which a discard restores. */
|
||||
data class LayoutAtStart(val viewId: Long, val blocks: List<Block>)
|
||||
|
||||
/** What custom rules coming back from their editor are for. */
|
||||
sealed interface RulesRequest {
|
||||
/** A new [type] block of view [viewId]. */
|
||||
data class Add(val viewId: Long, val type: BlockType) : RulesRequest
|
||||
|
||||
/** The source of the block whose settings are open. */
|
||||
data object Draft : RulesRequest
|
||||
}
|
||||
|
||||
/** Block [block] of view [viewId] as its settings screen changes it, until saved. */
|
||||
data class BlockDraft(val viewId: Long, val block: Block)
|
||||
|
||||
@@ -551,6 +560,23 @@ class ListsViewModel @Inject constructor(
|
||||
_blockDraft.value = null
|
||||
}
|
||||
|
||||
private var rulesRequest: RulesRequest? = null
|
||||
|
||||
/** Notes what the custom rules the editor is opened for will go to. */
|
||||
fun awaitRulesFor(request: RulesRequest) {
|
||||
rulesRequest = request
|
||||
}
|
||||
|
||||
/** Puts [source], back from the rule editor, where [awaitRulesFor] said. */
|
||||
fun takeRulesResult(source: BlockSource) {
|
||||
when (val request = rulesRequest) {
|
||||
is RulesRequest.Add -> addBlock(request.viewId, request.type, source)
|
||||
RulesRequest.Draft -> updateDraft { it.copy(source = source) }
|
||||
null -> Unit
|
||||
}
|
||||
rulesRequest = null
|
||||
}
|
||||
|
||||
private val _writeFailure = MutableStateFlow<ListWriteFailure?>(null)
|
||||
|
||||
/** Set when a list write is refused; the screen shows it and clears it. */
|
||||
|
||||
@@ -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,14 +21,16 @@ 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], Completed among them unless not [withCompletedList].
|
||||
* *Lists & filters…* in the view menu opens it to push the
|
||||
* picked one's screen; a block whose source is gone, to choose another.
|
||||
* *Lists & filters…* in the view menu opens it to push the 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(
|
||||
@@ -37,6 +40,7 @@ internal fun SourcePicker(
|
||||
onPick: (BlockSource) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
withCompletedList: Boolean = true,
|
||||
onCustomRules: (() -> Unit)? = null,
|
||||
) {
|
||||
val sections = state.unscopedSections
|
||||
val pick = { source: BlockSource ->
|
||||
@@ -44,6 +48,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 (withCompletedList) SmartList.entries else SmartList.entries - SmartList.COMPLETED
|
||||
|
||||
@@ -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
|
||||
@@ -31,6 +32,10 @@ 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 de.jeanlucmakiola.agendula.ui.imports.ImportScreen
|
||||
import de.jeanlucmakiola.agendula.ui.lists.ListsScreen
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen
|
||||
@@ -136,7 +141,9 @@ fun AgendulaNavHost(
|
||||
popEnterTransition = { EnterTransition.None },
|
||||
popExitTransition = { overlayExit },
|
||||
) {
|
||||
composable(Dest.LISTS) {
|
||||
composable(Dest.LISTS) { entry ->
|
||||
// Custom rules handed back by the rule editor, for a block being added or set up.
|
||||
val rulesResult by entry.savedStateHandle.getStateFlow<String?>(RuleEditResult.KEY, null).collectAsStateWithLifecycle()
|
||||
ReadableWidth {
|
||||
ListsScreen(
|
||||
onOpenFilter = { filter, scopeViewId -> nav.navigate(Dest.TaskList.build(filter, scopeViewId)) },
|
||||
@@ -157,6 +164,10 @@ 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)) },
|
||||
onEditRules = { initial -> nav.navigate(Dest.RuleEdit.forResult(RulePurpose.SOURCE, initial)) },
|
||||
rulesResult = rulesResult?.let(RuleEditResult::decode)?.source,
|
||||
onRulesResultTaken = { entry.savedStateHandle.remove<String>(RuleEditResult.KEY) },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -174,9 +185,19 @@ 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<String?>(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<String>(RuleEditResult.KEY)
|
||||
}
|
||||
ReadableWidth {
|
||||
EditViewScreen(
|
||||
viewModel = vm,
|
||||
onEditScope = { scope -> nav.navigate(Dest.RuleEdit.forResult(RulePurpose.SCOPE, scope)) },
|
||||
onBack = { nav.popBackStack() },
|
||||
// Home shows the view with its layout open, under whatever led here.
|
||||
onEditLayout = { nav.popBackStack(Dest.LISTS, inclusive = false) },
|
||||
@@ -184,6 +205,32 @@ fun AgendulaNavHost(
|
||||
}
|
||||
}
|
||||
|
||||
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() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composable(Dest.Settings.route, arguments = Dest.Settings.arguments) { entry ->
|
||||
ReadableWidth {
|
||||
SettingsScreen(
|
||||
@@ -342,7 +389,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())
|
||||
|
||||
@@ -6,6 +6,9 @@ import de.jeanlucmakiola.agendula.data.prefs.RuleCodec
|
||||
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].
|
||||
@@ -147,6 +150,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"
|
||||
|
||||
@@ -38,6 +38,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
|
||||
@@ -55,12 +56,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,
|
||||
onEditLayout: () -> Unit = {},
|
||||
) {
|
||||
@@ -119,6 +121,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))
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@ 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
|
||||
import de.jeanlucmakiola.agendula.ui.filters.admitsEverything
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
@@ -94,9 +96,12 @@ class EditViewViewModel @Inject constructor(
|
||||
|
||||
fun setQuickAdd(on: Boolean) = _draft.update { it?.copy(quickAdd = on) }
|
||||
|
||||
/** 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 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 +114,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) {
|
||||
|
||||
@@ -312,7 +312,79 @@
|
||||
<string name="filter_delete_body">Only the filter goes. Its tasks stay where they are.</string>
|
||||
<string name="filter_delete_confirm">Delete</string>
|
||||
<string name="filter_missing">Filter deleted</string>
|
||||
<string name="filter_rules_not_editable">This filter uses rules that can’t be edited here yet. You can still rename or delete it.</string>
|
||||
<string name="filter_match_title">Show tasks that match</string>
|
||||
<string name="filter_match_all">All rules</string>
|
||||
<string name="filter_match_any">Any rule</string>
|
||||
<string name="filter_op_is">is</string>
|
||||
<string name="filter_op_is_not">is not</string>
|
||||
<string name="filter_op_at_least">at least</string>
|
||||
<string name="filter_op_below">below</string>
|
||||
<string name="filter_due_this_week">This week</string>
|
||||
<string name="filter_due_this_month">This month</string>
|
||||
<plurals name="filter_due_next_days">
|
||||
<item quantity="one">Next %d day</item>
|
||||
<item quantity="other">Next %d days</item>
|
||||
</plurals>
|
||||
<string name="filter_due_next_days_any">Next days…</string>
|
||||
<string name="filter_next_days_off">Off</string>
|
||||
<string name="filter_next_days_title">Within the next days</string>
|
||||
<string name="filter_next_days_amount">Enter a number of days</string>
|
||||
<string name="filter_advanced">Advanced editor</string>
|
||||
<string name="filter_advanced_hint">Nested groups with all / any / not</string>
|
||||
<string name="filter_advanced_note">Rules the simple editor can’t show, like nested groups or “not” on a group, always open here.</string>
|
||||
<string name="filter_simple">Simple editor</string>
|
||||
<string name="filter_simple_hint">Lists, tags, due date and priority</string>
|
||||
<string name="filter_simple_unavailable">These rules need the advanced editor</string>
|
||||
<string name="filter_group_all">All of</string>
|
||||
<string name="filter_group_any">Any of</string>
|
||||
<string name="filter_group_not">Not</string>
|
||||
<string name="filter_group_all_hint">every rule must match</string>
|
||||
<string name="filter_group_any_hint">one is enough</string>
|
||||
<string name="filter_group_not_all_hint">leaves out tasks matching every rule</string>
|
||||
<string name="filter_group_not_any_hint">leaves out tasks matching any rule</string>
|
||||
<string name="filter_group_empty_all">No rules yet: every task matches.</string>
|
||||
<string name="filter_group_empty_any">No rules yet: no task matches.</string>
|
||||
<string name="filter_group_menu">Group options</string>
|
||||
<string name="filter_group_negate">Negate group (not)</string>
|
||||
<string name="filter_group_negate_off">Remove “not”</string>
|
||||
<string name="filter_group_delete">Delete group</string>
|
||||
<string name="filter_add_rule">Rule</string>
|
||||
<string name="filter_add_group">Group</string>
|
||||
<string name="filter_rule_remove">Remove rule</string>
|
||||
<string name="filter_field_title">Rule on</string>
|
||||
<string name="filter_field_list">List</string>
|
||||
<string name="filter_field_tag">Tag</string>
|
||||
<string name="filter_field_priority">Priority</string>
|
||||
<string name="filter_field_due">Due</string>
|
||||
<string name="filter_value_no_list">No list</string>
|
||||
<string name="filter_lists_none">No lists yet.</string>
|
||||
<string name="filter_tags_none">No open task has a tag yet.</string>
|
||||
<string name="filter_tag_other">Other tag…</string>
|
||||
<string name="filter_tag_other_hint">Tag</string>
|
||||
<string name="filter_template_empty">Start empty</string>
|
||||
<string name="filter_template_empty_hint">Pick every rule yourself</string>
|
||||
<string name="filter_templates_header">Templates</string>
|
||||
<string name="filter_templates_note">A template fills in the rules and a name. You can change everything afterwards.</string>
|
||||
<string name="filter_template_gtd">Next actions (GTD)</string>
|
||||
<string name="filter_template_gtd_hint">A list of your choice, or tag nextAction</string>
|
||||
<string name="filter_template_gtd_name">Next actions</string>
|
||||
<string name="filter_template_gtd_list_title">Next actions list</string>
|
||||
<string name="filter_template_gtd_list_hint">Which list holds your next actions? Tasks tagged nextAction show too. Skip to go by the tag alone.</string>
|
||||
<string name="filter_template_gtd_skip">Skip</string>
|
||||
<string name="filter_template_week">This week</string>
|
||||
<string name="filter_template_week_hint">Due this week, overdue included</string>
|
||||
<string name="filter_template_month">This month</string>
|
||||
<string name="filter_template_month_hint">Due this month</string>
|
||||
<string name="filter_template_high">High priority</string>
|
||||
<string name="filter_template_high_hint">Priority high, any list</string>
|
||||
<string name="filter_template_waiting">Waiting for</string>
|
||||
<string name="filter_template_waiting_hint">Tag waiting</string>
|
||||
<string name="filter_template_no_date">No date</string>
|
||||
<string name="filter_template_no_date_hint">Open tasks without a due date</string>
|
||||
<string name="rule_scope_title">Edit scope</string>
|
||||
<string name="rule_source_title">Custom rules</string>
|
||||
<string name="rule_save_as_filter">Save as filter</string>
|
||||
<string name="rule_save_as_filter_hint">Keep these rules as a filter, and show the filter here</string>
|
||||
<string name="new_task">New task</string>
|
||||
<string name="lists_failure">Could not read your tasks.</string>
|
||||
<string name="lists_empty">No task lists yet.</string>
|
||||
@@ -1130,6 +1202,9 @@
|
||||
<string name="view_source_gone">This block’s list or filter was deleted.</string>
|
||||
<string name="view_choose_source">Choose source</string>
|
||||
<string name="view_source_smart">Smart lists</string>
|
||||
<string name="view_source_custom">Custom rules…</string>
|
||||
<string name="view_source_custom_hint">Lists, tags, due dates and priority</string>
|
||||
<string name="view_source_custom_label">Custom rules</string>
|
||||
<string name="view_scope_list_gone">A list in this view’s scope was deleted. That part of the scope now matches nothing.</string>
|
||||
<string name="view_edit_scope">Edit scope</string>
|
||||
<!-- A view's scope in one line, built from these pieces -->
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
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 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 `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) }
|
||||
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 tags = listOf("Waiting", "nextaction")
|
||||
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"))))),
|
||||
)
|
||||
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 `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")))
|
||||
}
|
||||
|
||||
@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))))
|
||||
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()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
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 de.jeanlucmakiola.agendula.domain.testTask
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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 `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) }
|
||||
val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isTrue()
|
||||
vm.startFrom(FilterTemplate.NO_DATE)
|
||||
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))
|
||||
}
|
||||
|
||||
@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 `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")))
|
||||
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<TaskList>) : TasksRepository by unsupported() {
|
||||
var tasks: List<Task> = emptyList()
|
||||
override fun taskLists() = flowOf(lists)
|
||||
override fun tasks(filter: TaskFilter): Flow<List<Task>> = flowOf(tasks)
|
||||
}
|
||||
|
||||
private class MemoryDataStore : DataStore<Preferences> {
|
||||
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 <reified T> unsupported(): T =
|
||||
Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ ->
|
||||
throw UnsupportedOperationException("Unexpected call: ${method.name}")
|
||||
} as T
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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<Unit>()
|
||||
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.AllOf(listOf(Rule.AllOf(emptyList()))))
|
||||
assertThat(vm.draft.value!!.scope).isNull()
|
||||
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<TaskList>())
|
||||
}
|
||||
|
||||
private class MemoryDataStore : DataStore<Preferences> {
|
||||
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 <reified T> unsupported(): T =
|
||||
Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ ->
|
||||
throw UnsupportedOperationException("Unexpected call: ${method.name}")
|
||||
} as T
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user