diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index b856b76..1c7cdbd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -94,6 +94,19 @@ import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.taskFilter +import de.jeanlucmakiola.agendula.ui.tasklist.EmptyState +import de.jeanlucmakiola.agendula.ui.tasklist.TaskListUiState +import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel +import de.jeanlucmakiola.agendula.ui.tasklist.UndoReceipt +import de.jeanlucmakiola.agendula.ui.tasklist.rememberTaskRows +import de.jeanlucmakiola.agendula.ui.tasklist.taskRows +import de.jeanlucmakiola.agendula.ui.views.ScopeInputChip +import de.jeanlucmakiola.agendula.ui.views.ViewSwitcher +import de.jeanlucmakiola.agendula.ui.views.viewName +import de.jeanlucmakiola.floret.components.IconInfoCard +import androidx.compose.material3.TextButton import de.jeanlucmakiola.agendula.ui.common.ActionShapes import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position @@ -114,20 +127,20 @@ import java.time.LocalDate import java.time.ZoneId /** - * Home, laid out by the blocks of the active view. The Home view is a Today - * progress hero (wavy ring over tasks due today), an Overdue + All 2-up of tonal - * tiles, a live preview of the next upcoming tasks, then the user's lists grouped - * by account, tags and saved filters. Tapping a tile opens that smart list, an - * upcoming row opens that task, and the FAB starts a new task. The search action - * in the top bar slides open into a full-width field that filters every task by - * title. + * Home, laid out by the blocks of the active view, each read through the view's + * scope. The view's name in the top bar switches views and opens the lists and + * filters; a tile opens its list within the scope, a preview row its task, and + * the FAB starts a new task. The search action slides open into a field that + * searches the tasks in the view, with a chip to search every task instead. */ @Composable fun ListsScreen( - onOpenFilter: (TaskFilter) -> Unit, + onOpenFilter: (TaskFilter, Long?) -> Unit, onOpenTask: (Task) -> Unit, onNewTask: () -> Unit, onOpenSettings: () -> Unit, + onManageViews: () -> Unit, + onEditView: (Long) -> Unit, modifier: Modifier = Modifier, onNewFilter: () -> Unit = {}, viewModel: ListsViewModel = hiltViewModel(), @@ -137,7 +150,12 @@ fun ListsScreen( val syncing by viewModel.syncing.collectAsStateWithLifecycle() var query by rememberSaveable { mutableStateOf("") } var searchActive by rememberSaveable { mutableStateOf(false) } + // A search in a scoped view starts within the scope; the chip's ✕ widens it. + var searchEverything by rememberSaveable { mutableStateOf(false) } var newList by rememberSaveable { mutableStateOf(false) } + var listsAndFilters by rememberSaveable { mutableStateOf(false) } + // The block whose deleted source is being replaced. + var choosingSourceFor by rememberSaveable { mutableStateOf(null) } val destinations by viewModel.destinations.collectAsStateWithLifecycle() // ⚠️ Asked when the sheet opens, not when the screen is built. The answer is // an OPTIONS against each account's home set, and an account added since — @@ -147,10 +165,12 @@ fun ListsScreen( val closeSearch = { query = "" searchActive = false + searchEverything = false } + val content = state as? ListsUiState.Content // With no lists there is nowhere to put a task, so the primary action becomes // making one — otherwise a fresh install's FAB opens a form that cannot save. - val noLists = (state as? ListsUiState.Content)?.groups?.isEmpty() == true + val noLists = content?.lists?.isEmpty() == true // The sheet closes on save, so a refused write has to report itself here. val writeFailure by viewModel.writeFailure.collectAsStateWithLifecycle() LaunchedEffect(writeFailure) { @@ -162,10 +182,30 @@ fun ListsScreen( // System back closes search before leaving the screen. BackHandler(enabled = searchActive, onBack = closeSearch) + // The view's task list block, when it has one: it runs on the task screen's own model. + val taskBlock = content?.view?.blocks?.lastOrNull { it.type == BlockType.TASK_LIST && it.id !in content.goneSources } + val taskFilter = taskBlock?.source?.taskFilter + val blockModel: TaskListViewModel? = if (content != null && taskBlock != null && taskFilter != null) { + val model: TaskListViewModel = hiltViewModel(key = "view-${content.view.id}-block-${taskBlock.id}") + val scopeViewId = content.view.id.takeIf { content.view.scope != null && !taskBlock.ignoreScope } + val withCompleted = (taskBlock.options as BlockOptions.TaskList).showCompleted + LaunchedEffect(taskFilter, scopeViewId, withCompleted) { model.bind(taskFilter, scopeViewId, withCompleted) } + model + } else { + null + } + val undo = blockModel?.undo?.collectAsStateWithLifecycle()?.value + Scaffold( modifier = modifier, topBar = { HomeTopBar( + viewTitle = content?.view?.let { viewName(it.name, it.id) }, + views = content?.views.orEmpty(), + activeViewId = content?.view?.id, + onSwitchView = viewModel::switchView, + onListsAndFilters = { listsAndFilters = true }, + onManageViews = onManageViews, searchActive = searchActive, query = query, onQueryChange = { query = it }, @@ -197,13 +237,21 @@ fun ListsScreen( ListsUiState.Failure -> CenteredMessage(stringResource(R.string.lists_failure), PaddingValues(0.dp)) is ListsUiState.Content -> { + // Blocks open what they show within the view's scope, unless they ignore it. + val scopeFor = { block: Block -> s.view.id.takeIf { s.view.scope != null && !block.ignoreScope } } ListsContent( state = s, onOpenFilter = onOpenFilter, + scopeFor = scopeFor, onOpenTask = onOpenTask, onNewList = { newList = true }, onNewFilter = onNewFilter, onReorder = viewModel::reorderLists, + onChooseSource = { choosingSourceFor = it }, + onEditScope = { onEditView(s.view.id) }, + taskBlock = blockModel?.let { model -> + taskBlock?.let { block -> TaskBlock(block, taskFilter!!, model) } + }, topPadding = 0.dp, bottomPadding = inner.calculateBottomPadding() + 96.dp, ) @@ -211,9 +259,12 @@ fun ListsScreen( // content; an empty query leaves the home content visible behind // the open field. if (searchActive) { + val scoped = s.view.scope != null && !searchEverything SearchResults( query = query, - allTasks = s.allTasks, + allTasks = if (scoped) s.scopedTasks else s.allTasks, + scope = if (scoped) s.view else null, + onDropScope = { searchEverything = true }, onOpenTask = { taskId -> closeSearch() onOpenTask(taskId) @@ -235,12 +286,23 @@ fun ListsScreen( .height(SnackChipHeight), contentAlignment = Alignment.CenterStart, ) { - SnackChip( - visible = writeFailure != null, - message = stringResource( - listWriteFailureMessage(writeFailure ?: ListWriteFailure.SAVE), - ), - ) + if (undo != null && blockModel != null) { + SnackChip( + visible = true, + message = stringResource( + if (undo is UndoReceipt.Completed) R.string.task_completed else R.string.task_deleted, + ), + actionLabel = stringResource(R.string.undo), + onAction = blockModel::undo, + ) + } else { + SnackChip( + visible = writeFailure != null, + message = stringResource( + listWriteFailureMessage(writeFailure ?: ListWriteFailure.SAVE), + ), + ) + } } } } @@ -253,6 +315,27 @@ fun ListsScreen( destinations = destinations, ) } + + if (listsAndFilters && content != null) { + SourcePicker( + title = stringResource(R.string.view_lists_and_filters), + state = content, + withSmartLists = false, + onPick = { source -> source.taskFilter?.let { onOpenFilter(it, null) } }, + onDismiss = { listsAndFilters = false }, + ) + } + + val choosingBlock = choosingSourceFor?.let { id -> content?.view?.blocks?.firstOrNull { it.id == id } } + if (choosingBlock != null && content != null) { + SourcePicker( + title = stringResource(R.string.view_choose_source), + state = content, + withSmartLists = true, + onPick = { source -> viewModel.chooseSource(content.view, choosingBlock.id, source) }, + onDismiss = { choosingSourceFor = null }, + ) + } } /** @@ -271,14 +354,21 @@ internal fun listWriteFailureMessage(failure: ListWriteFailure): Int = when (fai ListWriteFailure.ACCOUNT_HOME -> R.string.list_delete_failed_account_home } +/** 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) + @Composable private fun ListsContent( state: ListsUiState.Content, - onOpenFilter: (TaskFilter) -> Unit, + onOpenFilter: (TaskFilter, Long?) -> Unit, + scopeFor: (Block) -> Long?, onOpenTask: (Task) -> Unit, onNewList: () -> Unit, onNewFilter: () -> Unit, onReorder: (List) -> Unit, + onChooseSource: (Long) -> Unit, + onEditScope: () -> Unit, + taskBlock: TaskBlock?, topPadding: androidx.compose.ui.unit.Dp, bottomPadding: androidx.compose.ui.unit.Dp, ) { @@ -287,6 +377,12 @@ private fun ListsContent( var reordering by rememberSaveable { mutableStateOf(null) } val blocks = state.view.blocks val rows = remember(blocks) { blocks.rows() } + val blockState = taskBlock?.model?.state?.collectAsStateWithLifecycle()?.value as? TaskListUiState.Content + val taskRows = if (taskBlock != null && blockState != null) { + rememberTaskRows(blockState, taskBlock.filter, taskBlock.model) + } else { + null + } LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues( @@ -294,38 +390,70 @@ private fun ListsContent( bottom = bottomPadding, ), ) { - // TODO(#59): apply the view's scope once views other than Home can have one. + if (state.scopeListsGone) { + item(key = "scope-gone") { + Notice( + text = stringResource(R.string.view_scope_list_gone), + action = stringResource(R.string.view_edit_scope), + onAction = onEditScope, + ) + } + } rows.forEach { row -> val block = row.first() - if (block.type in TILES) { - // A full progress tile stands alone, as the Today hero always has; other tiles share a row. - if (block.type == BlockType.PROGRESS && block.width == BlockWidth.FULL) { - item { Tile(block, state, onOpenFilter, Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } - } else { - item { HalfRow(row, state, onOpenFilter) } + if (block.id in state.goneSources && row.size == 1) { + item(key = "${block.id}-gone") { + Notice( + text = stringResource(R.string.view_source_gone), + action = stringResource(R.string.view_choose_source), + onAction = { onChooseSource(block.id) }, + ) } return@forEach } + if (block.type in TILES) { + // A full progress tile stands alone, as the Today hero always has; other tiles share a row. + if (block.type == BlockType.PROGRESS && block.width == BlockWidth.FULL) { + item { Tile(block, state, onOpenFilter, scopeFor, onChooseSource, Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } + } else { + item { HalfRow(row, state, onOpenFilter, scopeFor, onChooseSource) } + } + return@forEach + } + val open = { filter: TaskFilter -> onOpenFilter(filter, scopeFor(block)) } + val sections = state.sectionsFor(block) when (block.type) { - BlockType.PREVIEW -> previewSection(block, state, onOpenFilter, onOpenTask) + BlockType.PREVIEW -> previewSection(block, state, open, onOpenTask) BlockType.LISTS -> listsSection( key = "${block.id}", options = block.options as BlockOptions.Lists, - allGroups = state.groups, + allGroups = sections.groups, + anyLists = state.lists.isNotEmpty(), reordering = reordering == block.id, onToggleReorder = { reordering = if (reordering == block.id) null else block.id }, - onOpenFilter = onOpenFilter, + onOpenFilter = open, onNewList = onNewList, onReorder = onReorder, ) - BlockType.TAGS -> tagsSection("${block.id}", state.tags, onOpenFilter) - BlockType.FILTERS -> if (state.groups.isNotEmpty()) { - filtersSection("${block.id}", state.filters, onOpenFilter, onNewFilter) + BlockType.TAGS -> tagsSection("${block.id}", sections.tags, open) + BlockType.FILTERS -> if (state.lists.isNotEmpty()) { + filtersSection("${block.id}", sections.filters, open, onNewFilter) + } + BlockType.TASK_LIST -> if (taskBlock?.block?.id == block.id && taskRows != null && blockState != null) { + if (blockState.tasks.isEmpty()) { + item(key = "${block.id}-empty") { EmptyState(stringResource(R.string.task_list_empty)) } + } + taskRows( + rows = taskRows, + onOpenTask = onOpenTask, + onRequestDelete = taskBlock.model::requestDelete, + viewModel = taskBlock.model, + keyPrefix = "${block.id}-", + ) } // Rendered as tiles above. BlockType.PROGRESS, BlockType.COUNT_TILE -> Unit // TODO(#59): the rest of the catalog renders from phase 3 on. - BlockType.TASK_LIST, BlockType.SECTION_HEADING, BlockType.WEEK_STRIP, BlockType.RECENTLY_COMPLETED, @@ -337,57 +465,104 @@ private fun ListsContent( private val TILES = setOf(BlockType.PROGRESS, BlockType.COUNT_TILE) -/** What a progress block shows: done of total for its source, or `null` for a source it can't show yet. */ -private data class ProgressState(val done: Int, val total: Int, val filter: TaskFilter, val title: String?) - -private fun progressFor(block: Block, state: ListsUiState.Content): ProgressState? { - val source = block.source as? BlockSource.Smart ?: return null - if (source.smart != SmartList.TODAY) return null - val title = (block.options as BlockOptions.Progress).title - return ProgressState(state.todayDone, state.todayTotal, TaskFilter.Smart(source.smart), title) -} - -/** The smart count a count tile shows; `null` for a source it can't show yet. */ -private fun countFor(block: Block, state: ListsUiState.Content): SmartCount? { - val source = block.source as? BlockSource.Smart ?: return null - return state.smartCounts.firstOrNull { it.smart == source.smart } +/** A notice standing in for something gone, with the way to fix it. */ +@Composable +private fun Notice(text: String, action: String, onAction: () -> Unit, modifier: Modifier = Modifier) { + IconInfoCard( + icon = Icons.Rounded.ErrorOutline, + iconContentDescription = null, + modifier = modifier.padding(horizontal = 16.dp).padding(top = 8.dp), + ) { + Text(text, style = MaterialTheme.typography.bodyMedium) + TextButton(onClick = onAction, contentPadding = PaddingValues(0.dp)) { Text(action) } + } } /** A row of tiles: two half blocks side by side, or one with an empty half beside it. */ @Composable -private fun HalfRow(row: List, state: ListsUiState.Content, onOpenFilter: (TaskFilter) -> Unit) { +private fun HalfRow( + row: List, + state: ListsUiState.Content, + onOpenFilter: (TaskFilter, Long?) -> Unit, + scopeFor: (Block) -> Long?, + onChooseSource: (Long) -> Unit, +) { Row( modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - row.forEach { Tile(it, state, onOpenFilter, Modifier.weight(1f)) } + row.forEach { Tile(it, state, onOpenFilter, scopeFor, onChooseSource, Modifier.weight(1f)) } if (row.size == 1 && row.single().width == BlockWidth.HALF) Spacer(Modifier.weight(1f)) } } /** - * A progress or count tile; an empty space for a source it can't show yet. A full - * progress tile spans the content width on its own, as the Today hero always has. + * A progress or count tile; an empty space for a source it can't show yet, and + * a notice for one since deleted. A full progress tile spans the content width + * on its own, as the Today hero always has. */ @Composable private fun Tile( block: Block, state: ListsUiState.Content, - onOpenFilter: (TaskFilter) -> Unit, + onOpenFilter: (TaskFilter, Long?) -> Unit, + scopeFor: (Block) -> Long?, + onChooseSource: (Long) -> Unit, modifier: Modifier = Modifier, ) { + if (block.id in state.goneSources) { + GoneTile(onChoose = { onChooseSource(block.id) }, modifier = modifier) + return + } + val source = block.source + val filter = source?.taskFilter // TODO(#59): the wave switch, and a count tile's own title, colour and icon. when (block.type) { - BlockType.PROGRESS -> progressFor(block, state)?.let { progress -> - TodayHero(progress, onClick = { onOpenFilter(progress.filter) }, modifier = modifier) + BlockType.PROGRESS -> state.progress[block.id]?.takeIf { filter != null }?.let { progress -> + TodayHero( + done = progress.done, + total = progress.total, + title = (block.options as BlockOptions.Progress).title, + onClick = { onOpenFilter(filter!!, scopeFor(block)) }, + modifier = modifier, + ) } - BlockType.COUNT_TILE -> countFor(block, state)?.let { count -> - SmartCard(count = count, modifier = modifier, onClick = { onOpenFilter(TaskFilter.Smart(count.smart)) }) + BlockType.COUNT_TILE -> state.counts[block.id]?.takeIf { filter != null }?.let { count -> + CountCard( + style = tileStyle(source!!, state), + count = count, + modifier = modifier, + onClick = { onOpenFilter(filter!!, scopeFor(block)) }, + ) } else -> null } ?: Spacer(modifier) } +/** A tile whose source was deleted: says so, and offers another. */ +@Composable +private fun GoneTile(onChoose: () -> Unit, modifier: Modifier = Modifier) { + Surface( + onClick = onChoose, + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = modifier.heightIn(min = 116.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Icons.Rounded.ErrorOutline, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + Text(stringResource(R.string.view_source_gone), style = MaterialTheme.typography.bodyMedium) + Text( + stringResource(R.string.view_choose_source), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + ) + } + } +} + /** A preview of the source's next tasks, under its heading; nothing while there are none. */ private fun LazyListScope.previewSection( block: Block, @@ -395,39 +570,51 @@ private fun LazyListScope.previewSection( onOpenFilter: (TaskFilter) -> Unit, onOpenTask: (Task) -> Unit, ) { - // TODO(#59): sources beyond the smart lists, and inline done. - val smart = (block.source as? BlockSource.Smart)?.smart ?: return + // TODO(#59): inline done. + val source = block.source ?: return + val filter = source.taskFilter ?: return val options = block.options as BlockOptions.Preview val tasks = state.previews[block.id].orEmpty() if (tasks.isEmpty()) return - item { SectionHeader(stringResource(smartStyle(smart).labelRes)) } - item { + item(key = "${block.id}-header") { SectionHeader(sourceLabel(source, state)) } + item(key = "${block.id}-preview") { UpcomingPreview( tasks = tasks, onOpenTask = onOpenTask, - onViewAll = if (options.showAll) ({ onOpenFilter(TaskFilter.Smart(smart)) }) else null, + onViewAll = if (options.showAll) ({ onOpenFilter(filter) }) else null, ) } } +/** The name a block's source goes by. */ +@Composable +private fun sourceLabel(source: BlockSource, state: ListsUiState.Content): String = when (source) { + is BlockSource.Smart -> stringResource(smartListLabel(source.smart)) + is BlockSource.List -> state.lists.firstOrNull { it.id == source.listId }?.name.orEmpty() + is BlockSource.Tag -> source.tag + is BlockSource.Filter -> state.unscopedSections.filters.firstOrNull { it.filter.id == source.filterId }?.filter?.name.orEmpty() + is BlockSource.ListElsewhere, is BlockSource.Rules -> "" +} + /** The user's lists by account, reorderable in place, or the way to make the first one. */ private fun LazyListScope.listsSection( key: String, options: BlockOptions.Lists, allGroups: List, + anyLists: Boolean, reordering: Boolean, onToggleReorder: () -> Unit, onOpenFilter: (TaskFilter) -> Unit, onNewList: () -> Unit, onReorder: (List) -> Unit, ) { - if (allGroups.isEmpty()) { - item { EmptyLists(onNewList = onNewList) } + if (!anyLists) { + item(key = "$key-empty") { EmptyLists(onNewList = onNewList) } return } val groups = options.accounts?.let { accounts -> allGroups.filter { it.accountName in accounts } } ?: allGroups if (groups.isEmpty()) return - item { + item(key = "$key-header") { SectionHeader( text = stringResource(R.string.lists_header), action = { @@ -607,14 +794,19 @@ private fun EmptyLists(onNewList: () -> Unit) { } /** - * The home top bar. There is no title — the launcher icon already says which app - * this is. Settings is pinned at the right; the search action sits just left of it - * and stays put. Tapping search unfurls a pill to its left (the field grows out - * from the icon's side) while the search icon remains as the bar's fixed trailing - * icon, so neither action moves. + * The home top bar: the view switcher at the start, settings pinned at the end + * and the search action just left of it. Tapping search unfurls a pill to its + * left (the field grows out from the icon's side, over the switcher) while the + * search icon remains the bar's fixed trailing icon, so neither action moves. */ @Composable private fun HomeTopBar( + viewTitle: String?, + views: List, + activeViewId: Long?, + onSwitchView: (Long) -> Unit, + onListsAndFilters: () -> Unit, + onManageViews: () -> Unit, searchActive: Boolean, query: String, onQueryChange: (String) -> Unit, @@ -630,6 +822,17 @@ private fun HomeTopBar( .padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { + if (!searchActive && viewTitle != null) { + ViewSwitcher( + title = viewTitle, + views = views, + activeViewId = activeViewId, + onSwitchView = onSwitchView, + onListsAndFilters = onListsAndFilters, + onManageViews = onManageViews, + modifier = Modifier.weight(1f, fill = false), + ) + } // Search occupies the flexible space left of settings. Pulled into its // own composable so AnimatedVisibility resolves to the plain overload — // a RowScope receiver in here would make that call ambiguous. @@ -697,13 +900,16 @@ private fun SearchSlot( /** * Search results overlaying the home content: tasks whose title matches the query, - * across every list (completed included), open ones first. A blank query renders - * nothing so the home content shows through behind the open field. + * across [allTasks] (completed included), open ones first. Within a view's + * [scope] a chip says so, and its ✕ ([onDropScope]) searches every task. A blank + * query renders nothing so the home content shows through behind the open field. */ @Composable private fun SearchResults( query: String, allTasks: List, + scope: View?, + onDropScope: () -> Unit, onOpenTask: (Task) -> Unit, modifier: Modifier = Modifier, ) { @@ -714,24 +920,32 @@ private fun SearchResults( .sortedWith(compareBy({ it.isCompleted }, { it.title.lowercase() })) } Surface(modifier = modifier, color = MaterialTheme.colorScheme.surface) { - if (results.isEmpty()) { - Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) { - Text( - text = stringResource(R.string.home_search_empty, query.trim()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + // The last result scrolls clear of the navigation bar and the keyboard. + LazyColumn(modifier = Modifier.fillMaxSize()) { + if (scope != null) { + item(key = "scope") { + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 8.dp)) { + ScopeInputChip(name = viewName(scope.name, scope.id), icon = scope.icon, onDrop = onDropScope) + } + } } - } else { - // The last result scrolls clear of the navigation bar and the keyboard. - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(results, key = { it.occurrenceKey }) { task -> - UpcomingRow(task = task, onClick = { onOpenTask(task) }) - } - item(key = "bottom-inset") { - Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars.union(WindowInsets.ime))) + if (results.isEmpty()) { + item(key = "empty") { + Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.TopCenter) { + Text( + text = stringResource(R.string.home_search_empty, query.trim()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } + items(results, key = { it.occurrenceKey }) { task -> + UpcomingRow(task = task, onClick = { onOpenTask(task) }) + } + item(key = "bottom-inset") { + Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars.union(WindowInsets.ime))) + } } } } @@ -744,11 +958,12 @@ private fun SearchResults( @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable private fun TodayHero( - progress: ProgressState, + done: Int, + total: Int, + title: String?, onClick: () -> Unit, modifier: Modifier = Modifier, ) { - val (done, total) = progress val interaction = remember { MutableInteractionSource() } val pressed by interaction.collectIsPressedAsState() val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "todayCorner") @@ -775,7 +990,7 @@ private fun TodayHero( horizontalArrangement = Arrangement.spacedBy(8.dp), ) { Icon(Icons.Rounded.Today, contentDescription = null, modifier = Modifier.size(20.dp)) - Text(progress.title ?: stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium) + Text(title ?: stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium) } val headline = when { total == 0 -> stringResource(R.string.home_today_empty) @@ -908,16 +1123,23 @@ private fun upcomingDueLabel(task: Task): String? { } } -private data class SmartStyle(val icon: ImageVector, val labelRes: Int, val container: Color, val onContainer: Color) +/** How a count tile looks: its icon, name and tonal colours. */ +private data class TileStyle(val icon: ImageVector, val label: String, val container: Color, val onContainer: Color) @Composable -private fun smartStyle(smart: SmartList): SmartStyle { +private fun tileStyle(source: BlockSource, state: ListsUiState.Content): TileStyle { val colors = MaterialTheme.colorScheme - return when (smart) { - SmartList.TODAY -> SmartStyle(Icons.Rounded.Today, R.string.smart_today, colors.primaryContainer, colors.onPrimaryContainer) - SmartList.OVERDUE -> SmartStyle(Icons.Rounded.ErrorOutline, R.string.smart_overdue, colors.errorContainer, colors.onErrorContainer) - SmartList.UPCOMING -> SmartStyle(Icons.Rounded.Upcoming, R.string.smart_upcoming, colors.tertiaryContainer, colors.onTertiaryContainer) - else -> SmartStyle(Icons.AutoMirrored.Rounded.ListAlt, R.string.smart_all, colors.secondaryContainer, colors.onSecondaryContainer) + val label = sourceLabel(source, state) + return when (source) { + is BlockSource.Smart -> when (source.smart) { + SmartList.TODAY -> TileStyle(Icons.Rounded.Today, label, colors.primaryContainer, colors.onPrimaryContainer) + SmartList.OVERDUE -> TileStyle(Icons.Rounded.ErrorOutline, label, colors.errorContainer, colors.onErrorContainer) + SmartList.UPCOMING -> TileStyle(Icons.Rounded.Upcoming, label, colors.tertiaryContainer, colors.onTertiaryContainer) + else -> TileStyle(Icons.AutoMirrored.Rounded.ListAlt, label, colors.secondaryContainer, colors.onSecondaryContainer) + } + is BlockSource.Tag -> TileStyle(Icons.Rounded.Sell, label, colors.tertiaryContainer, colors.onTertiaryContainer) + is BlockSource.Filter -> TileStyle(Icons.Rounded.FilterList, label, colors.tertiaryContainer, colors.onTertiaryContainer) + else -> TileStyle(Icons.AutoMirrored.Rounded.ListAlt, label, colors.secondaryContainer, colors.onSecondaryContainer) } } @@ -927,8 +1149,7 @@ private fun smartStyle(smart: SmartList): SmartStyle { * silhouette. */ @Composable -private fun SmartCard(count: SmartCount, modifier: Modifier = Modifier, onClick: () -> Unit) { - val style = smartStyle(count.smart) +private fun CountCard(style: TileStyle, count: Int, modifier: Modifier = Modifier, onClick: () -> Unit) { val interaction = remember { MutableInteractionSource() } val pressed by interaction.collectIsPressedAsState() val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "smartCorner") @@ -946,8 +1167,8 @@ private fun SmartCard(count: SmartCount, modifier: Modifier = Modifier, onClick: ) { Icon(style.icon, contentDescription = null) Column { - Text(count.count.toString(), style = MaterialTheme.typography.headlineMedium) - Text(stringResource(style.labelRes), style = MaterialTheme.typography.labelLarge) + Text(count.toString(), style = MaterialTheme.typography.headlineMedium) + Text(style.label, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt index 170d551..12592ee 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt @@ -9,19 +9,26 @@ import de.jeanlucmakiola.agendula.data.sync.RemoteLists import de.jeanlucmakiola.agendula.data.tasks.TasksRepository import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure import de.jeanlucmakiola.floret.time.DayWindow +import de.jeanlucmakiola.agendula.domain.AppliedScope +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.RuleClock import de.jeanlucmakiola.agendula.domain.SavedFilter import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.SourceContext import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter -import de.jeanlucmakiola.agendula.domain.TaskFiltering import de.jeanlucmakiola.agendula.domain.TaskList -import de.jeanlucmakiola.agendula.domain.UpcomingRange import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.appliedScope +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.tagsInUse +import de.jeanlucmakiola.agendula.ui.views.ViewSession import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -31,10 +38,10 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch -import java.time.DayOfWeek import java.time.ZoneId import javax.inject.Inject import kotlin.time.Clock +import kotlin.time.Instant /** * What a list write failed at. The screens turn this into wording; the view @@ -86,51 +93,178 @@ internal fun RemoteLists.Outcome.asFailure(local: ListWriteFailure): ListWriteFa data class ListOverview(val list: TaskList, val openCount: Int) data class AccountGroup(val accountName: String, val lists: List) -data class SmartCount(val smart: SmartList, val count: Int) data class TagOverview(val tag: String, val openCount: Int) data class FilterOverview(val filter: SavedFilter, val openCount: Int) +/** Done of total for a progress block. */ +data class BlockProgress(val done: Int, val total: Int) + +/** What the lists, tags and filters blocks show, read through one scope. */ +data class HomeSections( + val groups: List, + /** Each tag on an open task, alphabetically. */ + val tags: List, + /** The saved filters, oldest first. */ + val filters: List, +) + sealed interface ListsUiState { data object Loading : ListsUiState data object Failure : ListsUiState data class Content( - val smartCounts: List, - val groups: List, - /** Completed vs. total tasks *due today* — drives the progress ring. */ - val todayDone: Int, - val todayTotal: Int, - /** What each preview block of [view] shows, by block id. */ - val previews: Map>, - /** Every task (open and completed) — the corpus the home search filters. */ - val allTasks: List, - /** Each tag on an open task, alphabetically. */ - val tags: List = emptyList(), - /** The saved filters, oldest first. */ - val filters: List = emptyList(), /** The view these are laid out by. */ - val view: View = View.home(), - ) : ListsUiState + val view: View, + /** Every view, for the switcher, Home first. */ + val views: List = listOf(view), + /** Each progress block's done of total, by block id; missing for a source it can't show. */ + val progress: Map = emptyMap(), + /** Each count tile's count, by block id. */ + val counts: Map = emptyMap(), + /** What each preview block shows, by block id. */ + val previews: Map> = emptyMap(), + /** The blocks whose list or saved filter was deleted. */ + val goneSources: Set = emptySet(), + /** The view's scope names a list since deleted, so that part of it matches nothing. */ + val scopeListsGone: Boolean = false, + /** The lists, tags and filters blocks within the view's scope. */ + val sections: HomeSections = HomeSections(emptyList(), emptyList(), emptyList()), + /** The same for every task: a block that ignores the scope, and the lists and filters picker. */ + val unscopedSections: HomeSections = sections, + /** Every list, whatever the scope: whether there are any, and the names sources show. */ + val lists: List = emptyList(), + /** Every task (open and completed) — the corpus the home search filters. */ + val allTasks: List = emptyList(), + /** [allTasks] within the view's scope, where a search in a scoped view starts. */ + val scopedTasks: List = allTasks, + ) : ListsUiState { + fun sectionsFor(block: Block): HomeSections = if (block.ignoreScope) unscopedSections else sections + } } /** - * The tasks each preview block of this view shows, by block id: the first of - * [upcoming] for a preview of Upcoming. Other sources show nothing yet. + * Home laid out by [view] over these tasks: each block reads its source through + * the view's scope, unless it ignores it. A block whose list or filter is gone + * shows nothing but says so; a scope list since deleted matches nothing. */ -internal fun View.previews(upcoming: Sequence): Map> { - val counts = blocks - .filter { it.type == BlockType.PREVIEW && it.source == BlockSource.Smart(SmartList.UPCOMING) } - .associate { it.id to (it.options as BlockOptions.Preview).count } - val next = upcoming.take(counts.values.maxOrNull() ?: 0).toList() - return counts.mapValues { (_, count) -> next.take(count) } +internal fun homeContent( + view: View, + views: List, + lists: List, + openTasks: List, + completedTasks: List, + hidden: Set, + savedFilters: List, + clock: RuleClock, + upcomingEnd: Instant?, +): ListsUiState.Content { + val listIds = lists.mapTo(HashSet()) { it.id } + // Lists deleted since drop out, as they do when the filter is opened. + val filters = savedFilters.map { it.withListsIn(listIds) } + val context = SourceContext(clock, upcomingEnd, filters.associateBy { it.id }) + val scope = view.appliedScope(listIds) + // Count only top-level tasks: a subtask is represented by its parent (and + // its progress chip), and an open subtask under a *completed* parent must + // 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 progress = HashMap() + val counts = HashMap() + val previews = HashMap>() + val gone = HashSet() + view.blocks.forEach { block -> + val source = block.source ?: return@forEach + if (source.isGone(listIds, filterIds)) { + gone += block.id + return@forEach + } + val within = scope.forBlock(block) + // The smart lists leave out the hidden lists, but not one the scope names. + val smartHidden = within.hiddenFromSmart(hidden) + fun shows(task: Task) = source.counts(task, context, smartHidden) && within.admits(task, clock) + when (block.type) { + BlockType.PROGRESS -> if (source == BlockSource.Smart(SmartList.TODAY)) { + // Today's completed rows against all of its rows. + 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.PREVIEW -> { + val count = (block.options as BlockOptions.Preview).count + previews[block.id] = topLevel.asSequence().filter(::shows).take(count).toList() + } + else -> Unit + } + } + + val allTasks = openTasks + completedTasks + val sections = homeSections(lists, openTasks, allTasks, filters, scope, clock) + return ListsUiState.Content( + view = view, + views = views, + progress = progress, + counts = counts, + previews = previews, + goneSources = gone, + scopeListsGone = scope.goneLists.isNotEmpty(), + sections = sections, + unscopedSections = if (scope == AppliedScope.None) { + sections + } else { + homeSections(lists, openTasks, allTasks, filters, AppliedScope.None, clock) + }, + lists = lists, + allTasks = allTasks, + scopedTasks = if (scope == AppliedScope.None) allTasks else allTasks.filter { scope.admits(it, clock) }, + ) } -/** The home overview: smart lists with live counts, then user lists by account. */ +/** + * The lists, tags and filters within [scope], each with its open count. A scope + * that keeps tasks to some lists shows only those. + */ +private fun homeSections( + lists: List, + openTasks: List, + allTasks: List, + filters: List, + scope: AppliedScope, + clock: RuleClock, +): HomeSections { + val open = if (scope == AppliedScope.None) openTasks else openTasks.filter { scope.admits(it, clock) } + val openByList = open.filter { !it.isSubtask }.groupingBy { it.listId }.eachCount() + val shown = scope.lists?.let { ids -> lists.filter { it.id in ids } } ?: lists + val groups = shown + .groupBy { it.accountName } + .map { (account, accountLists) -> + AccountGroup(account, accountLists.map { ListOverview(it, openByList[it.id] ?: 0) }) + } + .sortedBy { it.accountName.lowercase() } + // Counts the open rows the tag's own screen shows: a subtask folds under a + // parent carrying the same tag, and stands on its own otherwise. + val all = if (scope == AppliedScope.None) allTasks else allTasks.filter { scope.admits(it, clock) } + val tags = tagsInUse(open).map { tag -> + val tagged = all.filter { tag in it.tags } + val ids = tagged.mapTo(HashSet()) { it.taskId } + TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) }) + } + // Same folding as the tags: a subtask counts only when its parent isn't in the filter too. + val overviews = filters.map { filter -> + val matching = open.filter { filter.matches(it, clock) } + val ids = matching.mapTo(HashSet()) { it.taskId } + FilterOverview(filter, matching.count { !it.isSubtask || it.parentId !in ids }) + } + return HomeSections(groups, tags, overviews) +} + +/** The home overview: the active view's blocks with live counts. */ @HiltViewModel class ListsViewModel @Inject constructor( private val repository: TasksRepository, private val remoteLists: RemoteLists, private val manualSync: ManualSync, - settingsPrefs: SettingsPrefs, + private val settingsPrefs: SettingsPrefs, + private val session: ViewSession, ) : ViewModel() { /** Pull to sync (#73); off without an account. */ @@ -157,6 +291,11 @@ class ListsViewModel @Inject constructor( accounts.map { ListDestination(it.id, it.displayName) } } + /** The views, and the one shown: the last used one, Home when it is gone. Nothing while a launch picks it. */ + private val shownView = combine(settingsPrefs.views, session.activeViewId, session.starting) { views, active, starting -> + if (starting) null else (views.firstOrNull { it.id == active } ?: views.first()) to views + }.distinctUntilChanged() + val state: StateFlow = combine( repository.taskLists(), @@ -167,96 +306,36 @@ class ListsViewModel @Inject constructor( combine( settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(), settingsPrefs.firstDayOfWeek, - // For now Home is always the view shown. - settingsPrefs.views.map { views -> views.first { it.id == View.HOME_ID } }.distinctUntilChanged(), - ) { (hidden, range), weekStart, view -> Triple(hidden, range, weekStart) to view }, - settingsPrefs.savedFilters, - ) { lists, openTasks, completedTasks, (settings, view), filters -> - val (hidden, upcomingRange, weekStart) = settings - buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart, view) as ListsUiState + settingsPrefs.savedFilters, + ::Triple, + ), + shownView, + ) { lists, openTasks, completedTasks, (settings, weekStart, filters), shown -> + val (view, views) = shown ?: return@combine ListsUiState.Loading + val (hidden, upcomingRange) = settings + val now = Clock.System.now() + val zone = ZoneId.systemDefault() + val (todayStart, todayEnd) = DayWindow.today(now, zone) + homeContent( + view = view, + views = views, + lists = lists, + openTasks = openTasks, + completedTasks = completedTasks, + hidden = hidden, + savedFilters = filters, + clock = RuleClock(todayStart, todayEnd, zone, weekStart), + upcomingEnd = upcomingRange.end(now, zone), + ) }.recoveringFromProviderFailure { ListsUiState.Failure } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading) - private fun buildContent( - lists: List, - openTasks: List, - completedTasks: List, - hidden: Set, - upcomingRange: UpcomingRange, - savedFilters: List, - weekStart: DayOfWeek, - view: View, - ): ListsUiState.Content { - val now = Clock.System.now() - val zone = ZoneId.systemDefault() - val (todayStart, todayEnd) = DayWindow.today(now, zone) - // Count only top-level tasks: a subtask is represented by its parent (and - // its progress chip), and an open subtask under a *completed* parent must - // not read as an open item here. Mirrors the task list collapsing subtasks. - val topLevel = openTasks.filter { !it.isSubtask } - // The smart counts leave out the hidden lists; each list's own count does not. - val smartTopLevel = topLevel.filter { it.listId !in hidden } - val upcomingEnd = upcomingRange.end(now, zone) - fun inSmart(task: Task, smart: SmartList) = - TaskFiltering.matches(task, TaskFilter.Smart(smart), todayStart, todayEnd, upcomingEnd = upcomingEnd) - fun count(smart: SmartList) = smartTopLevel.count { inSmart(it, smart) } + fun switchView(viewId: Long) = session.switchTo(viewId) - val smartCounts = listOf( - SmartCount(SmartList.TODAY, count(SmartList.TODAY)), - SmartCount(SmartList.OVERDUE, count(SmartList.OVERDUE)), - SmartCount(SmartList.UPCOMING, count(SmartList.UPCOMING)), - SmartCount(SmartList.ALL, smartTopLevel.size), - ) - - // Today ring: the completed rows of the Today list against all of its rows. - val openToday = count(SmartList.TODAY) - val completedToday = completedTasks.count { - !it.isSubtask && it.listId !in hidden && TaskFiltering.isToday(it, todayStart, todayEnd) - } - val todayTotal = openToday + completedToday - - // Upcoming preview: the next handful of open tasks due tomorrow onward, - // already sorted by the repository's default ordering. - val upcoming = smartTopLevel.asSequence().filter { inSmart(it, SmartList.UPCOMING) } - val openByList = topLevel.groupingBy { it.listId }.eachCount() - val groups = lists - .groupBy { it.accountName } - .map { (account, accountLists) -> - AccountGroup( - accountName = account, - lists = accountLists.map { ListOverview(it, openByList[it.id] ?: 0) }, - ) - } - .sortedBy { it.accountName.lowercase() } - // Counts the open rows the tag's own screen shows: a subtask folds under a - // parent carrying the same tag, and stands on its own otherwise. - val allTasks = openTasks + completedTasks - val tags = tagsInUse(openTasks).map { tag -> - val tagged = allTasks.filter { tag in it.tags } - val ids = tagged.mapTo(HashSet()) { it.taskId } - TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) }) - } - val clock = RuleClock(todayStart, todayEnd, zone, weekStart) - // Lists deleted since drop out, as they do when the filter is opened. - val listIds = lists.mapTo(HashSet()) { it.id } - // Same folding as the tags: a subtask counts only when its parent isn't in the filter too. - val filters = savedFilters.map { saved -> - val filter = saved.withListsIn(listIds) - val matching = openTasks.filter { filter.matches(it, clock) } - val ids = matching.mapTo(HashSet()) { it.taskId } - FilterOverview(saved, matching.count { !it.isSubtask || it.parentId !in ids }) - } - return ListsUiState.Content( - view = view, - smartCounts = smartCounts, - filters = filters, - groups = groups, - todayDone = completedToday, - todayTotal = todayTotal, - previews = view.previews(upcoming), - allTasks = allTasks, - tags = tags, - ) + /** Points the block [blockId] of [view], whose source is gone, at [source] instead. */ + fun chooseSource(view: View, blockId: Long, source: BlockSource) = viewModelScope.launch { + val blocks = view.blocks.map { if (it.id == blockId) it.copy(source = source) else it } + settingsPrefs.saveView(view.copy(blocks = blocks)) } private val _writeFailure = MutableStateFlow(null) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt new file mode 100644 index 0000000..aa90339 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt @@ -0,0 +1,113 @@ +package de.jeanlucmakiola.agendula.ui.lists + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +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.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.SmartList +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.positionOf + +/** + * A full-screen pick of what a block or screen shows: the lists by account, the + * saved filters and the tags, each with its open count, led by the smart lists + * when [withSmartLists]. *Lists & filters…* in the view menu opens it to push the + * picked one's screen; a block whose source is gone, to choose another. + */ +@Composable +internal fun SourcePicker( + title: String, + state: ListsUiState.Content, + withSmartLists: Boolean, + onPick: (BlockSource) -> Unit, + onDismiss: () -> Unit, +) { + val sections = state.unscopedSections + val pick = { source: BlockSource -> + onDismiss() + onPick(source) + } + FullScreenPicker(title = title, onDismiss = onDismiss) { + if (withSmartLists) { + GroupedSectionHeader(stringResource(R.string.view_source_smart)) + SmartList.entries.forEachIndexed { index, smart -> + GroupedRow( + title = stringResource(smartListLabel(smart)), + position = positionOf(index, SmartList.entries.size), + leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) }, + onClick = { pick(BlockSource.Smart(smart)) }, + ) + } + } + sections.groups.forEach { group -> + GroupedSectionHeader(group.accountName) + group.lists.forEachIndexed { index, overview -> + GroupedRow( + title = overview.list.name, + position = positionOf(index, group.lists.size), + leading = { ListColorChip(overview.list.color) }, + trailing = { Count(overview.openCount) }, + onClick = { pick(BlockSource.List(overview.list.id)) }, + ) + } + } + if (sections.filters.isNotEmpty()) { + GroupedSectionHeader(stringResource(R.string.filters_header)) + sections.filters.forEachIndexed { index, overview -> + GroupedRow( + title = overview.filter.name, + position = positionOf(index, sections.filters.size), + leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) }, + trailing = { Count(overview.openCount) }, + onClick = { pick(BlockSource.Filter(overview.filter.id)) }, + ) + } + } + if (sections.tags.isNotEmpty()) { + GroupedSectionHeader(stringResource(R.string.tags_header)) + sections.tags.forEachIndexed { index, overview -> + GroupedRow( + title = overview.tag, + position = positionOf(index, sections.tags.size), + leading = { Icon(Icons.Rounded.Sell, contentDescription = null) }, + trailing = { Count(overview.openCount) }, + onClick = { pick(BlockSource.Tag(overview.tag)) }, + ) + } + } + Spacer(Modifier.height(16.dp)) + } +} + +@Composable +private fun Count(count: Int) { + Text( + count.toString(), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** The name of a smart list. */ +internal fun smartListLabel(smart: SmartList): Int = when (smart) { + SmartList.TODAY -> R.string.smart_today + SmartList.OVERDUE -> R.string.smart_overdue + SmartList.UPCOMING -> R.string.smart_upcoming + SmartList.NO_DATE -> R.string.smart_no_date + SmartList.COMPLETED -> R.string.smart_completed + SmartList.ALL -> R.string.smart_all +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt index 557b21e..f1bdafa 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt @@ -36,6 +36,10 @@ import de.jeanlucmakiola.agendula.ui.lists.ListsScreen import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen import de.jeanlucmakiola.agendula.ui.tasklist.TaskListScreen import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel +import de.jeanlucmakiola.agendula.ui.views.EditViewScreen +import de.jeanlucmakiola.agendula.ui.views.EditViewViewModel +import de.jeanlucmakiola.agendula.ui.views.ManageViewsScreen +import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.floret.identity.predictiveBackExit /** @@ -99,6 +103,8 @@ fun AgendulaNavHost( launchSingleTop = true } is NavRequest.Import -> nav.navigate(Dest.Import.build(navRequest.uri)) + // The view itself was switched to as the request arrived; this only uncovers home. + is NavRequest.OpenView -> nav.popBackStack(Dest.LISTS, inclusive = false) } val returnHome = (navRequest as? NavRequest.NewTask)?.returnHome == true || (navRequest as? NavRequest.OpenTask)?.returnHome == true @@ -123,11 +129,34 @@ fun AgendulaNavHost( composable(Dest.LISTS) { ReadableWidth { ListsScreen( - onOpenFilter = { filter -> nav.navigate(Dest.TaskList.build(filter)) }, + onOpenFilter = { filter, scopeViewId -> nav.navigate(Dest.TaskList.build(filter, scopeViewId)) }, onOpenTask = { task -> nav.navigate(task.detailRoute()) }, onNewTask = { nav.navigate(Dest.TaskEdit.buildNew()) }, onNewFilter = { nav.navigate(Dest.FilterEdit.build()) }, onOpenSettings = { nav.navigate(Dest.SETTINGS) }, + onManageViews = { nav.navigate(Dest.MANAGE_VIEWS) }, + onEditView = { id -> nav.navigate(Dest.EditView.build(id)) }, + ) + } + } + + composable(Dest.MANAGE_VIEWS) { + ReadableWidth { + ManageViewsScreen( + onBack = { nav.popBackStack() }, + onEditView = { id -> nav.navigate(Dest.EditView.build(id)) }, + ) + } + } + + composable(Dest.EditView.route, arguments = Dest.EditView.arguments) { entry -> + val viewId = entry.arguments?.getLong(Dest.EditView.ARG_VIEW_ID) ?: View.HOME_ID + val vm: EditViewViewModel = hiltViewModel() + LaunchedEffect(viewId) { vm.bind(viewId) } + ReadableWidth { + EditViewScreen( + viewModel = vm, + onBack = { nav.popBackStack() }, ) } } @@ -159,8 +188,9 @@ fun AgendulaNavHost( tag = args?.getString(Dest.TaskList.ARG_TAG), filterId = args?.getLong(Dest.TaskList.ARG_FILTER_ID) ?: Dest.NO_ID, ) + val scopeViewId = args?.getLong(Dest.TaskList.ARG_VIEW)?.takeIf { it != Dest.NO_ID } val vm: TaskListViewModel = hiltViewModel() - LaunchedEffect(filter) { vm.bind(filter) } + LaunchedEffect(filter, scopeViewId) { vm.bind(filter, scopeViewId) } val taskList: @Composable (onOpenTask: (Task) -> Unit, detailShown: Boolean) -> Unit = { onOpenTask, detailShown -> TaskListScreen( @@ -178,6 +208,8 @@ fun AgendulaNavHost( ) }, onEditFilter = { id -> nav.navigate(Dest.FilterEdit.build(id)) }, + // The new view shows on home, so the screen it was pinned from goes. + onPinned = { nav.popBackStack(Dest.LISTS, inclusive = false) }, onBack = { nav.popBackStack() }, backClosesSearch = !detailShown, ) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt index 50ed7ce..35da591 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt @@ -51,6 +51,9 @@ sealed interface NavRequest { /** One saved filter — a widget header. */ data class OpenFilter(val filterId: Long) : NavRequest + /** One view — its launcher shortcut. The view is switched to as the request is made. */ + data class OpenView(val viewId: Long) : NavRequest + /** An `.ics` another app handed over. */ data class Import(val uri: Uri) : NavRequest } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt new file mode 100644 index 0000000..9a8bd37 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt @@ -0,0 +1,198 @@ +package de.jeanlucmakiola.agendula.ui.views + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.material.icons.rounded.PostAdd +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.saveable.rememberSaveable +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.selected +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.View +import de.jeanlucmakiola.agendula.domain.ViewIcon +import de.jeanlucmakiola.agendula.domain.deletable +import de.jeanlucmakiola.agendula.ui.common.NameField +import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon +import de.jeanlucmakiola.agendula.ui.settings.ChipAccent +import de.jeanlucmakiola.agendula.ui.settings.SettingsHint +import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +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). + */ +@Composable +fun EditViewScreen( + viewModel: EditViewViewModel, + onBack: () -> Unit, +) { + val draft by viewModel.draft.collectAsStateWithLifecycle() + val listNames by viewModel.listNames.collectAsStateWithLifecycle() + val view = draft + val isNew = view?.id == 0L + var choosingIcon by rememberSaveable { mutableStateOf(false) } + var confirmDelete by rememberSaveable { mutableStateOf(false) } + val save = { viewModel.save(onBack) } + + CollapsingScaffold( + title = stringResource(if (isNew) R.string.view_new_title else R.string.view_edit_title), + onBack = onBack, + largeTopBar = false, + actions = { + Button( + onClick = save, + enabled = view != null && (view.id == View.HOME_ID || view.name.isNotBlank()), + modifier = Modifier.padding(end = 12.dp), + ) { Text(stringResource(R.string.save)) } + }, + ) { + if (view == null) return@CollapsingScaffold + + // Home keeps its translated name until it is given one of its own. + NameField( + name = view.name, + placeholder = if (view.id == View.HOME_ID) stringResource(R.string.view_home) else stringResource(R.string.view_name_hint), + autoFocus = isNew, + onNameChange = viewModel::rename, + onImeAction = save, + ) + + GroupedSectionHeader(stringResource(R.string.view_section_icon)) + GroupedRow( + title = stringResource(view.icon.label), + position = Position.Alone, + leading = { CategoryIcon(view.icon.vector, ChipAccent.Primary) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { choosingIcon = true }, + ) + + GroupedSectionHeader(stringResource(R.string.view_section_scope)) + GroupedRow( + title = scopeSummary(view.scope, listNames), + 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) }, + ) + SettingsHint(stringResource(R.string.view_scope_blocks_hint)) + + GroupedSectionHeader(stringResource(R.string.view_section_layout)) + GroupedRow( + title = stringResource(R.string.view_quick_add), + summary = stringResource(R.string.view_quick_add_hint), + position = Position.Alone, + leading = { Icon(Icons.Rounded.PostAdd, contentDescription = null) }, + trailing = { Switch(checked = view.quickAdd, onCheckedChange = viewModel::setQuickAdd) }, + onClick = { viewModel.setQuickAdd(!view.quickAdd) }, + ) + + if (view.deletable && !isNew) { + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.view_delete), + position = Position.Alone, + contentColor = MaterialTheme.colorScheme.error, + leading = { Icon(Icons.Rounded.Delete, contentDescription = null) }, + onClick = { confirmDelete = true }, + ) + } + Spacer(Modifier.height(24.dp)) + } + + if (choosingIcon && view != null) { + ViewIconPicker( + current = view.icon, + onSelect = viewModel::setIcon, + onDismiss = { choosingIcon = false }, + ) + } + + if (confirmDelete && view != null) { + AlertDialog( + onDismissRequest = { confirmDelete = false }, + title = { Text(stringResource(R.string.view_delete_title, viewName(view.name, view.id))) }, + text = { Text(stringResource(R.string.view_delete_body)) }, + confirmButton = { + TextButton(onClick = { confirmDelete = false; viewModel.delete(onBack) }) { + Text(stringResource(R.string.delete)) + } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }) { Text(stringResource(R.string.dialog_cancel)) } + }, + ) + } +} + +/** How many icons lead the picker as suggestions. */ +private const val SUGGESTED_ICONS = 10 + +/** The curated view icons in a full-screen grid; picking one closes it. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun ViewIconPicker(current: ViewIcon, onSelect: (ViewIcon) -> Unit, onDismiss: () -> Unit) { + FullScreenPicker(title = stringResource(R.string.view_icon_title), onDismiss = onDismiss) { + val (suggested, more) = ViewIcon.entries.withIndex().partition { it.index < SUGGESTED_ICONS } + listOf(R.string.view_icon_suggested to suggested, R.string.view_icon_more to more).forEach { (header, icons) -> + GroupedSectionHeader(stringResource(header)) + FlowRow( + modifier = Modifier.fillMaxWidth().padding(horizontal = GroupedListInset), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + icons.forEach { (_, icon) -> + val chosen = icon == current + Surface( + onClick = { + onSelect(icon) + onDismiss() + }, + shape = if (chosen) CircleShape else RoundedCornerShape(16.dp), + color = if (chosen) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh, + contentColor = if (chosen) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(56.dp).semantics { selected = chosen }, + ) { + Box(contentAlignment = Alignment.Center) { + Icon(icon.vector, contentDescription = stringResource(icon.label)) + } + } + } + } + } + Spacer(Modifier.height(16.dp)) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ManageViewsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ManageViewsScreen.kt new file mode 100644 index 0000000..4dbe2a6 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ManageViewsScreen.kt @@ -0,0 +1,135 @@ +package de.jeanlucmakiola.agendula.ui.views + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.DragHandle +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +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 androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.ui.settings.ChipAccent +import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon +import de.jeanlucmakiola.agendula.ui.settings.SettingsHint +import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.ReorderableColumn + +private val ViewRowHeight = 88.dp + +/** + * The views in the order the view menu lists them: Home first, the others + * dragged into place by their handle. A row opens the view's settings; the add + * action starts a new view. + */ +@Composable +fun ManageViewsScreen( + onBack: () -> Unit, + onEditView: (Long) -> Unit, + viewModel: ManageViewsViewModel = hiltViewModel(), +) { + val views by viewModel.views.collectAsStateWithLifecycle() + val listNames by viewModel.listNames.collectAsStateWithLifecycle() + val home = views.firstOrNull() ?: return + val others = views.drop(1) + + CollapsingScaffold( + title = stringResource(R.string.view_manage), + onBack = onBack, + largeTopBar = false, + actions = { + IconButton(onClick = { onEditView(0) }) { + Icon(Icons.Rounded.Add, contentDescription = stringResource(R.string.view_add)) + } + }, + ) { + ViewRow( + view = home, + listNames = listNames, + position = if (others.isEmpty()) Position.Alone else Position.Top, + handle = null, + dragging = false, + onClick = { onEditView(home.id) }, + ) + // Home heads the run, so the others continue it rather than start their own. + ReorderableColumn( + items = others, + keyOf = { it.id }, + onReorder = { ordered -> viewModel.reorder(listOf(home.id) + ordered.map { it.id }) }, + rowHeight = ViewRowHeight, + ) { view, position, dragHandle, isDragging -> + ViewRow( + view = view, + listNames = listNames, + position = when (position) { + Position.Top, Position.Middle -> Position.Middle + Position.Bottom, Position.Alone -> Position.Bottom + }, + handle = { DragHandle(dragHandle) }, + dragging = isDragging, + gapBelow = false, + onClick = { onEditView(view.id) }, + ) + } + SettingsHint(stringResource(R.string.view_manage_hint)) + } +} + +@Composable +private fun ViewRow( + view: View, + listNames: Map, + position: Position, + handle: (@Composable () -> Unit)?, + dragging: Boolean, + onClick: () -> Unit, + gapBelow: Boolean = true, +) { + val blocks = pluralStringResource(R.plurals.view_blocks, view.blocks.size, view.blocks.size) + GroupedRow( + title = viewName(view.name, view.id), + summary = stringResource(R.string.view_summary, scopeSummary(view.scope, listNames), blocks), + position = position, + minHeight = ViewRowHeight, + gapBelow = gapBelow, + container = if (dragging) MaterialTheme.colorScheme.secondaryContainer else null, + leading = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // Home has no handle: it stays first. + if (handle != null) handle() else Spacer(Modifier.size(40.dp)) + CategoryIcon(view.icon.vector, ChipAccent.Primary) + Spacer(Modifier.width(4.dp)) + } + }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = onClick, + ) +} + +@Composable +private fun DragHandle(modifier: Modifier) { + Box(modifier = modifier.size(40.dp), contentAlignment = Alignment.Center) { + Icon( + Icons.Rounded.DragHandle, + contentDescription = stringResource(R.string.view_reorder_handle), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ScopeSummary.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ScopeSummary.kt new file mode 100644 index 0000000..33a71c4 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ScopeSummary.kt @@ -0,0 +1,55 @@ +package de.jeanlucmakiola.agendula.ui.views + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.DueSpec +import de.jeanlucmakiola.agendula.domain.DueWindow +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.ui.filters.minPriorityLabel + +/** + * A view's scope in a line: "Everything" without one, else its conditions, as in + * "List Work and tag next". [lists] names the lists by id; one missing from it + * reads as deleted. + */ +@Composable +fun scopeSummary(scope: Rule?, lists: Map): String = + if (scope == null || scope == Rule.Everything) stringResource(R.string.view_scope_everything) else ruleSummary(scope, lists) + +@Composable +private fun ruleSummary(rule: Rule, lists: Map): String = when (rule) { + is Rule.AllOf -> joined(rule.children, lists, R.string.view_scope_and, R.string.view_scope_everything) + is Rule.AnyOf -> joined(rule.children, lists, R.string.view_scope_or, R.string.view_scope_nothing) + is Rule.Not -> stringResource(R.string.view_scope_not, ruleSummary(rule.child, lists)) + is Rule.InList -> { + val deleted = stringResource(R.string.view_scope_list_deleted) + val names = rule.listIds.map { lists[it] ?: deleted }.sorted() + + List(rule.elsewhere.size) { stringResource(R.string.view_scope_list_elsewhere) } + if (names.isEmpty()) stringResource(R.string.view_scope_nothing) else stringResource(R.string.view_scope_list, names.joinToString(", ")) + } + is Rule.HasTag -> stringResource(R.string.view_scope_tag, rule.tag) + is Rule.MinPriority -> minPriorityLabel(rule.priority) + is Rule.Due -> when (val spec = rule.spec) { + is DueSpec.Window -> stringResource( + when (spec.window) { + DueWindow.OVERDUE -> R.string.view_scope_due_overdue + DueWindow.TODAY -> R.string.view_scope_due_today + DueWindow.UPCOMING -> R.string.view_scope_due_upcoming + DueWindow.NO_DATE -> R.string.view_scope_due_none + }, + ) + DueSpec.ThisWeek -> stringResource(R.string.view_scope_due_week) + DueSpec.ThisMonth -> stringResource(R.string.view_scope_due_month) + is DueSpec.NextDays -> pluralStringResource(R.plurals.view_scope_due_next_days, spec.days, spec.days) + } +} + +@Composable +private fun joined(children: List, lists: Map, join: Int, empty: Int): String { + if (children.isEmpty()) return stringResource(empty) + var text = ruleSummary(children.first(), lists) + children.drop(1).forEach { text = stringResource(join, text, ruleSummary(it, lists)) } + return text +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSwitcher.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSwitcher.kt new file mode 100644 index 0000000..52925b9 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSwitcher.kt @@ -0,0 +1,125 @@ +package de.jeanlucmakiola.agendula.ui.views + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Dashboard +import androidx.compose.material.icons.rounded.ExpandMore +import androidx.compose.material.icons.rounded.Checklist +import androidx.compose.material3.DropdownMenuGroup +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.DropdownMenuPopup +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.MenuDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +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.graphics.Color +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.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.View + +/** + * The view's name in the home top bar, which opens the view menu: every view, + * the shown one checked, then *Lists & filters…* and *Manage views*. There is + * no drawer and no swiping between views (#59). + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun ViewSwitcher( + title: String, + views: List, + activeViewId: Long?, + onSwitchView: (Long) -> Unit, + onListsAndFilters: () -> Unit, + onManageViews: () -> Unit, + modifier: Modifier = Modifier, +) { + var open by remember { mutableStateOf(false) } + val switcherLabel = stringResource(R.string.view_switch) + Box(modifier) { + Surface( + onClick = { open = true }, + shape = CircleShape, + color = if (open) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent, + modifier = Modifier.semantics { role = Role.DropdownList }, + ) { + Row( + modifier = Modifier.heightIn(min = 48.dp).padding(start = 12.dp, end = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + title, + style = MaterialTheme.typography.titleLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + Icon(Icons.Rounded.ExpandMore, contentDescription = switcherLabel) + } + } + DropdownMenuPopup(expanded = open, onDismissRequest = { open = false }) { + DropdownMenuGroup(shapes = MenuDefaults.groupShape(0, 2)) { + views.forEachIndexed { index, view -> + val selected = view.id == activeViewId + DropdownMenuItem( + selected = selected, + onClick = { + open = false + onSwitchView(view.id) + }, + text = { Text(viewName(view.name, view.id)) }, + shapes = MenuDefaults.itemShape(index, views.size), + leadingIcon = { Icon(view.icon.vector, contentDescription = null) }, + selectedLeadingIcon = { Icon(view.icon.vector, contentDescription = null) }, + trailingContent = if (selected) { + { Icon(Icons.Rounded.Check, contentDescription = null) } + } else { + null + }, + ) + } + } + Spacer(Modifier.height(MenuDefaults.GroupSpacing)) + DropdownMenuGroup(shapes = MenuDefaults.groupShape(1, 2)) { + DropdownMenuItem( + onClick = { + open = false + onListsAndFilters() + }, + text = { Text(stringResource(R.string.view_lists_and_filters_menu)) }, + shape = MenuDefaults.leadingItemShape, + leadingIcon = { Icon(Icons.Rounded.Checklist, contentDescription = null) }, + ) + DropdownMenuItem( + onClick = { + open = false + onManageViews() + }, + text = { Text(stringResource(R.string.view_manage)) }, + shape = MenuDefaults.trailingItemShape, + leadingIcon = { Icon(Icons.Rounded.Dashboard, contentDescription = null) }, + ) + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt new file mode 100644 index 0000000..02e21a8 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt @@ -0,0 +1,113 @@ +package de.jeanlucmakiola.agendula.ui.views + +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.View +import de.jeanlucmakiola.agendula.domain.ViewIcon +import de.jeanlucmakiola.agendula.domain.newView +import de.jeanlucmakiola.agendula.domain.reordered +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 + +/** The names of the lists by id, for scope summaries; empty while they can't be read. */ +private fun TasksRepository.listNames() = taskLists() + .map { lists -> lists.associate { it.id to it.name } } + .catch { emit(emptyMap()) } + +/** The views in order, to reorder them and open one. */ +@HiltViewModel +class ManageViewsViewModel @Inject constructor( + private val settingsPrefs: SettingsPrefs, + repository: TasksRepository, +) : ViewModel() { + + val views: StateFlow> = settingsPrefs.views + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + + val listNames: StateFlow> = repository.listNames() + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) + + /** Puts the views in the order of [ids]; Home stays first. */ + fun reorder(ids: List) = viewModelScope.launch { + settingsPrefs.reorderViews(views.value.reordered(ids).map { it.id }) + } +} + +/** + * One view's name, icon and quick-add switch until saved; [bind] with an id of 0 + * starts a new view. Its scope shows read-only here for now. + */ +@HiltViewModel +class EditViewViewModel @Inject constructor( + private val settingsPrefs: SettingsPrefs, + private val session: ViewSession, + repository: TasksRepository, +) : ViewModel() { + + private val _draft = MutableStateFlow(null) + + /** `null` until [bind] has loaded the view. An id of 0 is a new one. */ + val draft: StateFlow = _draft.asStateFlow() + + val listNames: StateFlow> = repository.listNames() + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) + + private var bound = false + private var saving = false + + fun bind(viewId: Long) { + if (bound) return + bound = true + if (viewId <= 0) { + _draft.value = newView(0, "") + return + } + viewModelScope.launch { + _draft.value = settingsPrefs.views.first().firstOrNull { it.id == viewId } ?: newView(0, "") + } + } + + fun rename(name: String) = _draft.update { it?.copy(name = name) } + + fun setIcon(icon: ViewIcon) = _draft.update { it?.copy(icon = icon) } + + fun setQuickAdd(on: Boolean) = _draft.update { it?.copy(quickAdd = on) } + + /** + * 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. + */ + fun save(onSaved: () -> Unit) { + val draft = _draft.value ?: return + if (saving || (draft.id != View.HOME_ID && draft.name.isBlank())) return + saving = true + viewModelScope.launch { + val stored = settingsPrefs.views.first().firstOrNull { it.id == draft.id } + val view = stored?.copy(name = draft.name.trim(), icon = draft.icon, quickAdd = draft.quickAdd) + ?: draft.copy(id = 0, name = draft.name.trim()) + val id = settingsPrefs.saveView(view) + if (stored == null) session.switchTo(id) + onSaved() + } + } + + fun delete(onDeleted: () -> Unit) { + val id = _draft.value?.id?.takeIf { it > 0 && it != View.HOME_ID } ?: return + viewModelScope.launch { + settingsPrefs.deleteView(id) + onDeleted() + } + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/lists/HomePreviewsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/lists/HomePreviewsTest.kt index 27ad9f7..e11eb60 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/lists/HomePreviewsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/lists/HomePreviewsTest.kt @@ -5,31 +5,139 @@ import de.jeanlucmakiola.agendula.domain.Block import de.jeanlucmakiola.agendula.domain.BlockOptions import de.jeanlucmakiola.agendula.domain.BlockSource import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.BlockWidth +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.RuleClock +import de.jeanlucmakiola.agendula.domain.SavedFilter import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.domain.TaskList +import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.ViewIcon +import de.jeanlucmakiola.agendula.domain.allDayInstantOf +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 +/** Home as the active view lays it out, through its scope (#59). */ class HomePreviewsTest { - private val upcoming = (1L..12L).map { testTask(id = it) } + private val zone = ZoneId.systemDefault() + private val today = LocalDate.of(2026, 11, 26) + private val clock = RuleClock(startOfDay(today, zone), startOfDay(today.plusDays(1), zone), zone, DayOfWeek.MONDAY) + + private fun list(id: Long, name: String) = + TaskList(id, name, 0, "Local", "local", isSynced = false, isVisible = true, owner = null) + + private val work = list(1, "Work") + private val home = list(2, "Home") + private fun dueOn(day: LocalDate) = allDayInstantOf(day) + + private val upcoming = (1L..12L).map { testTask(id = it, listId = if (it % 2 == 0L) 1 else 2, due = dueOn(today.plusDays(it))) } + private val todayWork = testTask(id = 20, listId = 1, due = dueOn(today), isAllDay = true, tags = listOf("x")) + private val todayHome = testTask(id = 21, listId = 2, due = dueOn(today), isAllDay = true) + private val doneToday = testTask( + id = 22, + listId = 1, + status = TaskStatus.COMPLETED, + completedAt = startOfDay(today, zone), + ) + + private fun content( + view: View, + open: List = upcoming.map { it.copy(isAllDay = true) } + todayWork + todayHome, + lists: List = listOf(work, home), + hidden: Set = emptySet(), + filters: List = emptyList(), + ) = homeContent(view, listOf(view), lists, open, listOf(doneToday), hidden, filters, clock, upcomingEnd = null) + + private fun scoped(scope: Rule?, blocks: List = View.home().blocks) = + View(2, "Work", ViewIcon.WORK, scope, blocks) @Test fun `home previews the next three upcoming tasks, as 1_4 did`() { - assertThat(View.home().previews(upcoming.asSequence())).containsExactly(4L, upcoming.take(3)) + val state = content(View.home()) + val expected = upcoming.take(3).map { it.taskId } + assertThat(state.previews.getValue(4L).map { it.taskId }).isEqualTo(expected) + assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 1, total = 3)) + assertThat(state.counts.getValue(3L)).isEqualTo(14) + assertThat(state.counts.getValue(2L)).isEqualTo(0) + assertThat(state.goneSources).isEmpty() + assertThat(state.scopedTasks).isSameInstanceAs(state.allTasks) } @Test - fun `each Upcoming preview takes its own count, other sources show nothing yet`() { + fun `each preview takes its own count and source`() { val view = View.home().copy( blocks = listOf( Block(1, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 5)), Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 10)), - Block(3, BlockType.PREVIEW, BlockSource.Smart(SmartList.TODAY)), + Block(3, BlockType.PREVIEW, BlockSource.Tag("x")), ), ) - assertThat(view.previews(upcoming.asSequence())).containsExactly(1L, upcoming.take(5), 2L, upcoming.take(10)) - assertThat(view.previews(emptySequence())).containsExactly(1L, emptyList(), 2L, emptyList()) + val state = content(view) + assertThat(state.previews.getValue(1L)).hasSize(5) + assertThat(state.previews.getValue(2L)).hasSize(10) + assertThat(state.previews.getValue(3L).map { it.taskId }).containsExactly(20L) + } + + @Test + fun `every block reads its source through the scope`() { + val state = content(scoped(Rule.InList(setOf(1L)))) + assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 1, total = 2)) + assertThat(state.counts.getValue(3L)).isEqualTo(7) + assertThat(state.previews.getValue(4L).map { it.listId }.toSet()).containsExactly(1L) + // The lists block shows the lists the scope keeps tasks to, with scoped counts. + assertThat(state.sections.groups.flatMap { g -> g.lists.map { it.list.id to it.openCount } }) + .containsExactly(1L to 7) + assertThat(state.sections.tags.map { it.tag to it.openCount }).containsExactly("x" to 1) + assertThat(state.unscopedSections.groups.flatMap { g -> g.lists.map { it.list.id } }).containsExactly(1L, 2L) + assertThat(state.scopedTasks.map { it.listId }.toSet()).containsExactly(1L) + assertThat(state.allTasks.map { it.listId }.toSet()).containsExactly(1L, 2L) + } + + @Test + fun `a block that ignores the scope counts everything`() { + val blocks = View.home().blocks.map { if (it.id == 3L) it.copy(ignoreScope = true) else it } + val state = content(scoped(Rule.InList(setOf(1L)), blocks)) + assertThat(state.counts.getValue(3L)).isEqualTo(14) + assertThat(state.sectionsFor(blocks.single { it.id == 3L })).isEqualTo(state.unscopedSections) + } + + @Test + fun `a list named in the scope counts in the smart lists though hidden`() { + val hidden = setOf(1L) + assertThat(content(View.home(), hidden = hidden).counts.getValue(3L)).isEqualTo(7) + assertThat(content(scoped(Rule.InList(setOf(1L))), hidden = hidden).counts.getValue(3L)).isEqualTo(7) + assertThat(content(scoped(Rule.HasTag("x")), hidden = hidden).counts.getValue(3L)).isEqualTo(0) + } + + @Test + fun `a block whose list or filter is deleted says so, and shows nothing`() { + val blocks = listOf( + Block(1, BlockType.COUNT_TILE, BlockSource.List(9), BlockWidth.HALF), + Block(2, BlockType.PREVIEW, BlockSource.Filter(4)), + Block(3, BlockType.COUNT_TILE, BlockSource.List(1), BlockWidth.HALF), + Block(4, BlockType.TASK_LIST, BlockSource.Filter(5)), + ) + val state = content(scoped(null, blocks), filters = listOf(SavedFilter(5, "f", Rule.HasTag("x")))) + assertThat(state.goneSources).containsExactly(1L, 2L) + assertThat(state.counts.keys).containsExactly(3L) + assertThat(state.previews).isEmpty() + } + + @Test + fun `a scope list since deleted matches nothing and raises the notice`() { + val state = content(scoped(Rule.InList(setOf(9L)))) + assertThat(state.scopeListsGone).isTrue() + assertThat(state.counts.getValue(3L)).isEqualTo(0) + assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 0, total = 0)) + assertThat(state.sections.groups).isEmpty() + assertThat(state.scopedTasks).isEmpty() + assertThat(content(scoped(Rule.InList(setOf(1L)))).scopeListsGone).isFalse() } }