Home's task block, counts and notices follow the view (#59)

The undo chip outlives a view switch and the last view's rows don't flash
under the next, a list's search looks through the whole list, tag and
filter tiles count subtasks like their sections, a new task takes the
scope's tag, and only a gone list that narrowed the scope raises a notice.
This commit is contained in:
makiolaj committed 2026-11-27 13:59:25 +01:00
1 parent 1a2c41cc08
commit 02a09d0e31
6 files changed
+114 -28

No files matched your search

@@ -6,6 +6,21 @@ import kotlin.time.Instant
fun Rule.namedListIds(): Set<Long> =
flatten().filterIsInstance<Rule.InList>().flatMapTo(HashSet()) { it.listIds.asIterable() }
/** The lists this rule names outside any [Rule.Not]: the ones that narrow it. */
fun Rule.limitingListIds(): Set<Long> = when (this) {
is Rule.InList -> listIds
is Rule.AllOf -> children.flatMapTo(HashSet()) { it.limitingListIds() }
is Rule.AnyOf -> children.flatMapTo(HashSet()) { it.limitingListIds() }
is Rule.Not, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> emptySet()
}
/** A tag every task passing this rule carries: one at the top, alone or among all-of conditions. */
fun Rule.requiredTag(): String? = when (this) {
is Rule.HasTag -> tag
is Rule.AllOf -> children.firstNotNullOfOrNull { (it as? Rule.HasTag)?.tag }
else -> null
}
/**
* The lists a task has to be in to pass this rule, or `null` when a task of any
* list can. Read from list conditions joined by [Rule.AllOf] and [Rule.AnyOf]; a
@@ -30,6 +45,11 @@ data class AppliedScope(
val rule: Rule?,
val goneLists: Set<Long> = emptySet(),
val namedLists: Set<Long> = emptySet(),
/**
* Whether a gone list narrowed the scope, so that part now matches nothing.
* One under a [Rule.Not] widens it instead, which needs no notice.
*/
val narrowedByGone: Boolean = false,
) {
fun admits(task: Task, clock: RuleClock): Boolean = rule == null || rule.matches(task, clock)
@@ -53,7 +73,7 @@ fun View.appliedScope(exist: Set<Long>): AppliedScope {
val named = scope.namedListIds()
val gone = if (exist.isEmpty()) emptySet() else named - exist
val rule = if (gone.isEmpty()) scope else scope.withoutListIds { it in gone }
return AppliedScope(rule, gone, named - gone)
return AppliedScope(rule, gone, named - gone, narrowedByGone = gone.any { it in scope.limitingListIds() })
}
/** The scope [block] reads its tasks through: none when it ignores the view's. */
@@ -137,7 +137,7 @@ import java.time.ZoneId
fun ListsScreen(
onOpenFilter: (TaskFilter, Long?) -> Unit,
onOpenTask: (Task) -> Unit,
onNewTask: (Long?) -> Unit,
onNewTask: (listId: Long?, tag: String?) -> Unit,
onOpenSettings: () -> Unit,
onManageViews: () -> Unit,
onEditView: (Long) -> Unit,
@@ -187,19 +187,21 @@ fun ListsScreen(
val taskFilter = taskBlock?.source?.taskFilter
// Blocks open what they show within the view's scope, unless they ignore it.
val scopeFor = { block: Block -> content?.view?.takeIf { it.scope != null && !block.ignoreScope }?.id }
// One model, rebound as the view changes, rather than one kept per view visited. Held
// whatever the view, so an undo offered in one view stays offered after switching away.
val homeTaskModel: TaskListViewModel = hiltViewModel(key = "home-task-block")
val blockModel: TaskListViewModel? = if (content != null && taskBlock != null && taskFilter != null) {
// One model, rebound as the view changes, rather than one kept per view visited.
val model: TaskListViewModel = hiltViewModel(key = "home-task-block")
val scopeViewId = scopeFor(taskBlock)
val options = taskBlock.options as BlockOptions.TaskList
LaunchedEffect(taskFilter, scopeViewId, options) {
model.bind(taskFilter, scopeViewId, withCompleted = options.showCompleted, sort = options.sort)
homeTaskModel.bind(taskFilter, scopeViewId, withCompleted = options.showCompleted, sort = options.sort)
}
model
homeTaskModel
} else {
null
}
val undo = blockModel?.undo?.collectAsStateWithLifecycle()?.value
val undo by homeTaskModel.undo.collectAsStateWithLifecycle()
val viewSaveFailed by viewModel.viewSaveFailed.collectAsStateWithLifecycle()
Scaffold(
modifier = modifier,
@@ -222,7 +224,7 @@ fun ListsScreen(
// The FAB would otherwise float over the search results.
if (!searchActive) {
ExtendedFloatingActionButton(
onClick = if (noLists) ({ newList = true }) else ({ onNewTask(content?.newTaskList) }),
onClick = if (noLists) ({ newList = true }) else ({ onNewTask(content?.newTaskList, content?.newTaskTag) }),
icon = { Icon(Icons.Rounded.Add, contentDescription = null) },
text = {
Text(stringResource(if (noLists) R.string.list_add else R.string.new_task))
@@ -253,7 +255,7 @@ fun ListsScreen(
onChooseSource = { choosingSourceFor = it },
onEditScope = { onEditView(s.view.id) },
taskBlock = blockModel?.let { model ->
taskBlock?.let { block -> TaskBlock(block, taskFilter!!, model) }
taskBlock?.let { block -> TaskBlock(block, taskFilter!!, scopeFor(block), model) }
},
topPadding = 0.dp,
bottomPadding = inner.calculateBottomPadding() + 96.dp,
@@ -289,17 +291,19 @@ fun ListsScreen(
.height(SnackChipHeight),
contentAlignment = Alignment.CenterStart,
) {
// One chip: a refused list write, else the task block's undo.
// One chip: a refused write, else the task block's undo.
val failure = writeFailure
val receipt = undo
SnackChip(
visible = failure != null || undo != null,
visible = failure != null || viewSaveFailed || receipt != null,
message = when {
failure != null -> stringResource(listWriteFailureMessage(failure))
undo is UndoReceipt.Completed -> stringResource(R.string.task_completed)
viewSaveFailed -> stringResource(R.string.view_save_failed)
receipt is UndoReceipt.Completed -> stringResource(R.string.task_completed)
else -> stringResource(R.string.task_deleted)
},
actionLabel = if (failure == null && undo != null) stringResource(R.string.undo) else null,
onAction = if (failure == null && undo != null) blockModel?.let { it::undo } else null,
actionLabel = if (failure == null && !viewSaveFailed && receipt != null) stringResource(R.string.undo) else null,
onAction = if (failure == null && !viewSaveFailed && receipt != null) homeTaskModel::undo else null,
)
}
}
@@ -355,7 +359,7 @@ internal fun listWriteFailureMessage(failure: ListWriteFailure): Int = when (fai
}
/** A view's task list block and the task screen model behind it. */
private class TaskBlock(val block: Block, val filter: TaskFilter, val model: TaskListViewModel)
private class TaskBlock(val block: Block, val filter: TaskFilter, val scopeViewId: Long?, val model: TaskListViewModel)
@Composable
private fun ListsContent(
@@ -377,7 +381,9 @@ private fun ListsContent(
var reordering by rememberSaveable { mutableStateOf<Long?>(null) }
val blocks = state.view.blocks
val rows = remember(blocks) { blocks.rows() }
val blockState = taskBlock?.model?.state?.collectAsStateWithLifecycle()?.value as? TaskListUiState.Content
// The shared model still holds the last view's rows until it is rebound: show none until then.
val blockState = (taskBlock?.model?.state?.collectAsStateWithLifecycle()?.value as? TaskListUiState.Content)
?.takeIf { it.filter == taskBlock.filter && it.scope?.viewId == taskBlock.scopeViewId }
val taskRows = if (taskBlock != null && blockState != null) {
rememberTaskRows(blockState, taskBlock.filter, taskBlock.model, expansionKey = state.view.id)
} else {
@@ -27,6 +27,7 @@ import de.jeanlucmakiola.agendula.domain.contains
import de.jeanlucmakiola.agendula.domain.counts
import de.jeanlucmakiola.agendula.domain.forBlock
import de.jeanlucmakiola.agendula.domain.isGone
import de.jeanlucmakiola.agendula.domain.requiredTag
import de.jeanlucmakiola.agendula.domain.tagsInUse
import de.jeanlucmakiola.agendula.ui.views.ViewSession
import kotlinx.coroutines.flow.MutableStateFlow
@@ -35,9 +36,9 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.time.ZoneId
import javax.inject.Inject
@@ -144,6 +145,8 @@ sealed interface ListsUiState {
private val scopedCorpus: Lazy<List<Task>> = lazyOf(allTasks),
/** The list a new task goes to, so it shows in the view: the scope's one list, if it keeps tasks to one. */
val newTaskList: Long? = null,
/** A tag the scope requires, which a new task gets so it stays in the view. */
val newTaskTag: String? = null,
) : ListsUiState {
val sections: HomeSections get() = scopedSections.value
val unscopedSections: HomeSections get() = everySection.value
@@ -179,6 +182,7 @@ internal fun homeContent(
// not read as an open item here. Mirrors the task list collapsing subtasks.
val topLevel = openTasks.filter { !it.isSubtask } + completedTasks.filter { !it.isSubtask }
val filterIds = filters.mapTo(HashSet()) { it.id }
val allOpenAndDone = openTasks + completedTasks
val progress = HashMap<Long, BlockProgress>()
val counts = HashMap<Long, Int>()
@@ -200,7 +204,14 @@ internal fun homeContent(
val inToday = topLevel.filter { source.contains(it, context, smartHidden) && within.admits(it, clock) }
progress[block.id] = BlockProgress(inToday.count { it.isClosed }, inToday.size)
}
BlockType.COUNT_TILE -> counts[block.id] = topLevel.count(::shows)
BlockType.COUNT_TILE -> counts[block.id] = if (source is BlockSource.Smart) {
topLevel.count(::shows)
} else {
// As the tags and filters count them: a subtask counts unless its parent does.
val shown = allOpenAndDone.filter(::shows)
val ids = shown.mapTo(HashSet()) { it.taskId }
shown.count { !it.isSubtask || it.parentId !in ids }
}
BlockType.PREVIEW -> {
val count = (block.options as BlockOptions.Preview).count
previews[block.id] = topLevel.asSequence().filter(::shows).take(count).toList()
@@ -218,7 +229,7 @@ internal fun homeContent(
counts = counts,
previews = previews,
goneSources = gone,
scopeListsGone = scope.goneLists.isNotEmpty(),
scopeListsGone = scope.narrowedByGone,
scopedSections = if (scope == AppliedScope.None) {
every
} else {
@@ -234,6 +245,7 @@ internal fun homeContent(
lazy(LazyThreadSafetyMode.PUBLICATION) { allTasks.filter { scope.admits(it, clock) } }
},
newTaskList = scope.lists?.singleOrNull()?.takeIf { it in listIds },
newTaskTag = scope.rule?.requiredTag(),
)
}
@@ -350,12 +362,22 @@ class ListsViewModel @Inject constructor(
fun switchView(viewId: Long) = session.switchTo(viewId)
private val _viewSaveFailed = MutableStateFlow(false)
/** Set for a moment when a view couldn't be stored: the views are another version's. */
val viewSaveFailed: StateFlow<Boolean> = _viewSaveFailed.asStateFlow()
/** Points the block [blockId] of view [viewId], whose source is gone, at [source] instead. */
fun chooseSource(viewId: Long, blockId: Long, source: BlockSource) = viewModelScope.launch {
// The view as stored now, so nothing changed since the picker opened is lost.
val view = settingsPrefs.views.first().firstOrNull { it.id == viewId } ?: return@launch
val blocks = view.blocks.map { if (it.id == blockId) it.copy(source = source) else it }
settingsPrefs.saveView(view.copy(blocks = blocks))
// Read and written in one go, so nothing changed since the picker opened is lost.
val written = settingsPrefs.updateView(viewId) { view ->
view.copy(blocks = view.blocks.map { if (it.id == blockId) it.copy(source = source) else it })
}
if (!written) {
_viewSaveFailed.value = true
delay(4_000)
_viewSaveFailed.value = false
}
}
private val _writeFailure = MutableStateFlow<ListWriteFailure?>(null)
@@ -263,7 +263,7 @@ class TaskListViewModel @Inject constructor(
listOrder = lists.map { it.id },
todayStart = window.first,
todayEnd = window.second,
scope = view?.let { ScopeChip(it.id, it.name, it.icon, applied?.goneLists?.isNotEmpty() == true) },
scope = view?.let { ScopeChip(it.id, it.name, it.icon, applied?.narrowedByGone == true) },
scopeLists = applied?.lists,
appliedScope = applied,
)
@@ -280,9 +280,9 @@ class TaskListViewModel @Inject constructor(
?: settings
val (inView, hiddenByRange) = shownBy.viewOf(f, st.tasks, now)
val clock = RuleClock(st.todayStart, st.todayEnd, ZoneId.systemDefault(), settings.effectiveWeekStart)
val visible = inView.filter {
it.occurrenceKey !in pending && (scope == null || scope.admits(it, clock)) &&
(b.withCompleted != false || !it.isCompleted)
val present = inView.filter { it.occurrenceKey !in pending }
val visible = present.filter {
(scope == null || scope.admits(it, clock)) && (b.withCompleted != false || !it.isCompleted)
}
val available = tagsInUse(visible) - setOfNotNull((f as? TaskFilter.Tagged)?.tag)
// A tag that vanished can no longer be unticked, so it is dropped
@@ -297,7 +297,8 @@ class TaskListViewModel @Inject constructor(
.sortedWith((b.sort ?: settings.sortOrder).comparator()),
availableTags = available,
selectedTags = selected,
searchable = if (f is TaskFilter.OfList) visible else emptyList(),
// The whole list, not just its scoped rows: search mustn't offer to add a task it already has.
searchable = if (f is TaskFilter.OfList) present else emptyList(),
showAddSubtaskRow = settings.showAddSubtaskRow,
bottomAddBar = settings.bottomAddBar,
sortOrder = b.sort ?: settings.sortOrder,
@@ -168,4 +168,22 @@ class ViewScopeTest {
.isEqualTo(StartPlan(View.HOME_ID))
assertThat(DefaultStartDestination).isEqualTo(StartDestination.View(View.HOME_ID))
}
@Test
fun `only a gone list that narrowed the scope raises the notice`() {
assertThat(view(Rule.InList(setOf(1L))).appliedScope(setOf(2L)).narrowedByGone).isTrue()
val excluded = view(Rule.Not(Rule.InList(setOf(1L)))).appliedScope(setOf(2L))
assertThat(excluded.goneLists).containsExactly(1L)
assertThat(excluded.narrowedByGone).isFalse()
assertThat(excluded.admits(testTask(listId = 2), clock)).isTrue()
}
@Test
fun `a scope's required tag is one at its top`() {
assertThat(Rule.HasTag("x").requiredTag()).isEqualTo("x")
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("y"))).requiredTag()).isEqualTo("y")
assertThat(Rule.AnyOf(listOf(Rule.HasTag("x"), Rule.HasTag("y"))).requiredTag()).isNull()
assertThat(Rule.Not(Rule.HasTag("x")).requiredTag()).isNull()
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(2L))))).limitingListIds()).containsExactly(1L)
}
}
@@ -140,4 +140,23 @@ class HomePreviewsTest {
assertThat(state.scopedTasks).isEmpty()
assertThat(content(scoped(Rule.InList(setOf(1L)))).scopeListsGone).isFalse()
}
@Test
fun `a tag tile counts a subtask whose parent doesn't carry the tag`() {
val parent = testTask(id = 30, listId = 1)
val sub = testTask(id = 31, listId = 1, parentId = 30, tags = listOf("y"))
val view = scoped(null, listOf(Block(1, BlockType.COUNT_TILE, BlockSource.Tag("y"), BlockWidth.HALF)))
val state = content(view, open = listOf(parent, sub))
assertThat(state.counts.getValue(1L)).isEqualTo(1)
assertThat(state.counts.getValue(1L)).isEqualTo(state.sections.tags.single { it.tag == "y" }.openCount)
}
@Test
fun `a new task in a scoped view takes its one list and required tag`() {
val state = content(scoped(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))))
assertThat(state.newTaskList).isEqualTo(1L)
assertThat(state.newTaskTag).isEqualTo("x")
assertThat(content(scoped(Rule.InList(setOf(1L, 2L)))).newTaskList).isNull()
assertThat(content(scoped(Rule.Not(Rule.InList(setOf(9L))))).scopeListsGone).isFalse()
}
}