From 8abbe79ab65374ad7a97df828fd60a936b21f05c Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 27 Nov 2026 14:48:51 +0100 Subject: [PATCH] Edit layout: rearrange, resize, add and remove blocks, block settings, and the full block catalog (#59) The new blocks are count tiles with their own title, colour and icon, a half progress tile, previews and recently completed with check-off, the week strip and section headings. Tiles follow the compact density. --- .../agendula/ui/common/ActionShapes.kt | 9 + .../agendula/ui/lists/EditLayout.kt | 706 ++++++++++++ .../agendula/ui/lists/HomeBlocks.kt | 1007 +++++++++++++++++ .../agendula/ui/lists/ListsScreen.kt | 968 ++++------------ .../agendula/ui/lists/ListsViewModel.kt | 152 ++- .../agendula/ui/lists/LongPressToEdit.kt | 39 + .../agendula/ui/views/EditViewScreen.kt | 26 +- .../agendula/ui/views/ViewSession.kt | 15 + app/src/main/res/values/strings.xml | 83 ++ .../agendula/ui/lists/HomePreviewsTest.kt | 33 + 10 files changed, 2287 insertions(+), 751 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/EditLayout.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/HomeBlocks.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/LongPressToEdit.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ActionShapes.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ActionShapes.kt index 5707498..76668dd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ActionShapes.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ActionShapes.kt @@ -44,4 +44,13 @@ object ActionShapes { /** The overflow menu — a puffy cloud. */ val More: RoundedPolygon get() = MaterialShapes.Puffy + + /** Add a block to a view's layout — the same burst as the other "add" actions. */ + val AddBlock: RoundedPolygon get() = MaterialShapes.Sunny + + /** Switch a block between half and full width — a pill, wide like what it makes. */ + val ResizeBlock: RoundedPolygon get() = MaterialShapes.Pill + + /** Take a block out of a layout — a soft burst, apart from [Delete], since it can be undone. */ + val RemoveBlock: RoundedPolygon get() = MaterialShapes.SoftBurst } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/EditLayout.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/EditLayout.kt new file mode 100644 index 0000000..3e7a54e --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/EditLayout.kt @@ -0,0 +1,706 @@ +package de.jeanlucmakiola.agendula.ui.lists + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ListAlt +import androidx.compose.material.icons.automirrored.rounded.ShortText +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.Apps +import androidx.compose.material.icons.rounded.CalendarViewWeek +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Checklist +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material.icons.rounded.DragHandle +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.material.icons.rounded.History +import androidx.compose.material.icons.rounded.Palette +import androidx.compose.material.icons.rounded.Sell +import androidx.compose.material.icons.rounded.Sort +import androidx.compose.material.icons.rounded.SwapHoriz +import androidx.compose.material.icons.rounded.TaskAlt +import androidx.compose.material.icons.rounded.ViewAgenda +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBarDefaults +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.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.Block +import de.jeanlucmakiola.agendula.domain.BlockOptions +import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.BlockWidth +import de.jeanlucmakiola.agendula.domain.TaskSortOrder +import de.jeanlucmakiola.agendula.domain.TileColor +import de.jeanlucmakiola.agendula.domain.canAdd +import de.jeanlucmakiola.agendula.ui.common.ActionShapes +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.tasklist.sortLabel +import de.jeanlucmakiola.agendula.ui.views.ViewIconPicker +import de.jeanlucmakiola.agendula.ui.views.label +import de.jeanlucmakiola.agendula.ui.views.vector +import de.jeanlucmakiola.agendula.ui.views.viewName +import de.jeanlucmakiola.floret.components.ActionButton +import de.jeanlucmakiola.floret.components.ConnectedChoiceRow +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GridSpan +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionPicker +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.ReorderableGrid +import de.jeanlucmakiola.floret.components.SelectedCheck +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.identity.FloretDensity + +/** The top bar while a layout is edited: its title, *Add block* and ✓ Done. */ +@Composable +internal fun EditLayoutTopBar(onAdd: () -> Unit, onDone: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.surface) { + Row( + modifier = Modifier + .fillMaxWidth() + .windowInsetsPadding(TopAppBarDefaults.windowInsets) + .height(72.dp) + .padding(start = 24.dp, end = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.view_edit_layout), + style = MaterialTheme.typography.titleLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + ActionButton( + shape = ActionShapes.AddBlock, + morphTo = ActionShapes.AddListPressed, + icon = Icons.Rounded.Add, + contentDescription = stringResource(R.string.block_add), + onClick = onAdd, + size = 48.dp, + ) + Button(onClick = onDone, modifier = Modifier.padding(start = 8.dp)) { + Icon(Icons.Rounded.Check, contentDescription = null, modifier = Modifier.size(ButtonDefaults.IconSize)) + Spacer(Modifier.width(ButtonDefaults.IconSpacing)) + Text(stringResource(R.string.edit_layout_done)) + } + } + } +} + +/** + * The view's blocks to rearrange: dragged by their handle or after a long + * press, made half or full width, removed, or tapped for their settings. *Add + * block* closes the grid. The task list stays last and doesn't move. + */ +@Composable +internal fun EditLayoutContent( + state: ListsUiState.Content, + onMove: (List) -> Unit, + onResize: (Block, BlockWidth) -> Unit, + onRemove: (Block) -> Unit, + onOpenSettings: (Block) -> Unit, + onAdd: () -> Unit, + bottomPadding: Dp, +) { + val scroll = rememberScrollState() + // Blocks show what they hold, but nothing in them opens while the layout is edited. + val inert = BlockActions( + openFilter = { _, _ -> }, + openTask = {}, + toggleDone = {}, + chooseSource = {}, + newList = {}, + newFilter = {}, + reorderLists = {}, + scopeFor = { null }, + ) + Column(Modifier.fillMaxSize().verticalScroll(scroll).padding(top = 8.dp, bottom = bottomPadding)) { + ReorderableGrid( + items = state.view.blocks, + keyOf = { it.id }, + spanOf = { if (it.width == BlockWidth.HALF) GridSpan.Half else GridSpan.Full }, + onReorder = { blocks -> onMove(blocks.map { it.id }) }, + canDrag = { it.type != BlockType.TASK_LIST }, + scrollState = scroll, + moveEarlierLabel = stringResource(R.string.block_move_earlier), + moveLaterLabel = stringResource(R.string.block_move_later), + ) { block, column, dragHandle, dragging -> + EditBlockFrame( + block = block, + state = state, + actions = inert, + column = column, + dragHandle = dragHandle, + dragging = dragging, + onResize = { onResize(block, it) }, + onRemove = { onRemove(block) }, + onOpenSettings = { onOpenSettings(block) }, + ) + } + AddBlockTile(onAdd) + } +} + +/** + * One block in the edit grid with its controls: a tile carries them in its + * corner, a section on its title line. Tapping the block opens its settings. + */ +@Composable +private fun EditBlockFrame( + block: Block, + state: ListsUiState.Content, + actions: BlockActions, + column: Int, + dragHandle: Modifier, + dragging: Boolean, + onResize: (BlockWidth) -> Unit, + onRemove: () -> Unit, + onOpenSettings: () -> Unit, +) { + // A heading's own text shows as its content, under the name of its kind. + val heading = block.type == BlockType.SECTION_HEADING + val typeName = stringResource(block.type.label) + val title = if (heading) typeName else blockTitle(block, state).ifBlank { typeName } + val settingsLabel = stringResource(R.string.block_settings) + // A long press belongs to the grid, which starts a drag; letting go of one doesn't open the settings. + val tapTarget = Modifier + .clickable(onClickLabel = settingsLabel) { if (!dragging) onOpenSettings() } + .semantics { contentDescription = if (title == typeName) title else "$typeName, $title" } + val controls: @Composable () -> Unit = { + BlockControls(block, dragHandle, onResize, onRemove) + } + if (block.type in TILES) { + val inset = when { + block.width == BlockWidth.FULL -> Modifier.padding(horizontal = GroupedListInset) + column == 0 -> Modifier.padding(start = GroupedListInset) + else -> Modifier.padding(end = GroupedListInset) + } + Box(inset) { + Box(Modifier.clearAndSetSemantics {}) { Tile(block, state, actions, Modifier.fillMaxWidth()) } + Box(Modifier.matchParentSize().clip(RoundedCornerShape(22.dp)).then(tapTarget)) + Row(Modifier.align(Alignment.TopEnd).padding(4.dp)) { controls() } + } + return + } + Column { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 28.dp, end = 12.dp, top = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + controls() + } + Box { + Box(Modifier.clearAndSetSemantics {}) { + BlockBody(block, state, actions, editing = true, showHeader = heading) + } + Box(Modifier.matchParentSize().then(tapTarget)) + } + } +} + +/** A block's drag handle, its half/full switch where its type has both, and ✕. */ +@Composable +private fun BlockControls( + block: Block, + dragHandle: Modifier, + onResize: (BlockWidth) -> Unit, + onRemove: () -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (block.type != BlockType.TASK_LIST) { + Box( + modifier = dragHandle + .size(36.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHighest.copy(alpha = 0.7f)), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Rounded.DragHandle, + contentDescription = stringResource(R.string.block_drag), + modifier = Modifier.size(20.dp), + ) + } + } + if (block.type.widths.size > 1) { + val toFull = block.width == BlockWidth.HALF + ActionButton( + shape = ActionShapes.ResizeBlock, + icon = Icons.Rounded.SwapHoriz, + contentDescription = stringResource(if (toFull) R.string.block_make_full else R.string.block_make_half), + onClick = { onResize(if (toFull) BlockWidth.FULL else BlockWidth.HALF) }, + size = 36.dp, + iconSize = 20.dp, + ) + } + ActionButton( + shape = ActionShapes.RemoveBlock, + icon = Icons.Rounded.Close, + contentDescription = stringResource(R.string.block_remove), + onClick = onRemove, + size = 36.dp, + iconSize = 20.dp, + ) + } +} + +/** The dashed *Add block* tile that closes the edit grid. */ +@Composable +private fun AddBlockTile(onAdd: () -> Unit) { + val outline = MaterialTheme.colorScheme.outline + Surface( + onClick = onAdd, + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surface, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = GroupedListInset, vertical = 16.dp) + .drawBehind { + drawRoundRect( + color = outline, + cornerRadius = CornerRadius(22.dp.toPx()), + style = Stroke(width = 1.5.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(8.dp.toPx(), 6.dp.toPx()))), + ) + }, + ) { + Row( + modifier = Modifier.heightIn(min = FloretDensity.cardRowHeight), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.block_add), style = MaterialTheme.typography.labelLarge) + } + } +} + +/** A block kind's name. */ +internal val BlockType.label: Int + get() = when (this) { + BlockType.PROGRESS -> R.string.block_progress + BlockType.COUNT_TILE -> R.string.block_count + BlockType.PREVIEW -> R.string.block_preview + BlockType.RECENTLY_COMPLETED -> R.string.block_recent + BlockType.WEEK_STRIP -> R.string.block_week + BlockType.TASK_LIST -> R.string.block_task_list + BlockType.LISTS -> R.string.lists_header + BlockType.TAGS -> R.string.tags_header + BlockType.FILTERS -> R.string.filters_header + BlockType.SECTION_HEADING -> R.string.block_heading + } + +/** What a block kind shows, in a line. */ +private val BlockType.hint: Int + get() = when (this) { + BlockType.PROGRESS -> R.string.block_progress_hint + BlockType.COUNT_TILE -> R.string.block_count_hint + BlockType.PREVIEW -> R.string.block_preview_hint + BlockType.RECENTLY_COMPLETED -> R.string.block_recent_hint + BlockType.WEEK_STRIP -> R.string.block_week_hint + BlockType.TASK_LIST -> R.string.block_task_list_hint + BlockType.LISTS -> R.string.block_lists_hint + BlockType.TAGS -> R.string.block_tags_hint + BlockType.FILTERS -> R.string.block_filters_hint + BlockType.SECTION_HEADING -> R.string.block_heading_hint + } + +private val BlockType.icon: ImageVector + get() = when (this) { + BlockType.PROGRESS -> Icons.Rounded.TaskAlt + BlockType.COUNT_TILE -> Icons.Rounded.Apps + BlockType.PREVIEW -> Icons.Rounded.ViewAgenda + BlockType.RECENTLY_COMPLETED -> Icons.Rounded.History + BlockType.WEEK_STRIP -> Icons.Rounded.CalendarViewWeek + BlockType.TASK_LIST -> Icons.Rounded.Checklist + BlockType.LISTS -> Icons.AutoMirrored.Rounded.ListAlt + BlockType.TAGS -> Icons.Rounded.Sell + BlockType.FILTERS -> Icons.Rounded.FilterList + BlockType.SECTION_HEADING -> Icons.AutoMirrored.Rounded.ShortText + } + +/** The add picker's groups of block kinds, in order. */ +private val BlockGroups = listOf( + R.string.block_group_tasks to listOf( + BlockType.PROGRESS, + BlockType.COUNT_TILE, + BlockType.PREVIEW, + BlockType.RECENTLY_COMPLETED, + BlockType.WEEK_STRIP, + BlockType.TASK_LIST, + ), + R.string.block_group_browse to listOf(BlockType.LISTS, BlockType.TAGS, BlockType.FILTERS), + R.string.block_group_layout to listOf(BlockType.SECTION_HEADING), +) + +/** + * The block kinds to add, grouped; a second task list is offered but can't be + * picked. Picking one closes the picker. + */ +@Composable +internal fun AddBlockPicker(blocks: List, onPick: (BlockType) -> Unit, onDismiss: () -> Unit) { + FullScreenPicker(title = stringResource(R.string.block_add), onDismiss = onDismiss) { + BlockGroups.forEach { (header, types) -> + GroupedSectionHeader(stringResource(header)) + types.forEachIndexed { index, type -> + val addable = blocks.canAdd(type) + GroupedRow( + title = stringResource(type.label), + summary = stringResource(if (addable) type.hint else R.string.block_task_list_taken), + position = positionOf(index, types.size), + dimmed = !addable, + leading = { CategoryIcon(type.icon, ChipAccent.Primary) }, + onClick = if (addable) ({ onDismiss(); onPick(type) }) else null, + ) + } + } + Spacer(Modifier.height(16.dp)) + } +} + +/** + * A block's settings, full screen: its title (or a heading's text), its source, + * the options of its kind, *Ignore view scope* where the view has a scope, and + * remove. Changes are kept until Save; back leaves them. + */ +@Composable +internal fun BlockSettings( + block: Block, + state: ListsUiState.Content, + onChange: ((Block) -> Block) -> Unit, + onChooseSource: () -> Unit, + onSave: () -> Unit, + onRemove: () -> Unit, + onDismiss: () -> Unit, +) { + var choosing by rememberSaveable { mutableStateOf(null) } + fun options(transform: (BlockOptions) -> BlockOptions) = onChange { it.copy(options = transform(it.options)) } + FullScreenPicker( + title = stringResource(block.type.label), + onDismiss = onDismiss, + actions = { + Button(onClick = onSave, modifier = Modifier.padding(end = 12.dp)) { Text(stringResource(R.string.save)) } + }, + ) { + TitleSection(block, state, ::options) + + if (block.type.takesSource) { + GroupedSectionHeader(stringResource(R.string.block_section_tasks)) + GroupedRow( + title = stringResource(R.string.block_source), + summary = block.source?.let { sourceLabel(it, state) }?.takeIf { block.id !in state.goneSources } + ?: stringResource(R.string.view_source_gone), + position = Position.Alone, + leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = onChooseSource, + ) + } + + TypeOptions(block, state, ::options, onPick = { choosing = it }) + + if (state.view.scope != null) { + GroupedSectionHeader(stringResource(R.string.block_section_scope)) + GroupedSwitchRow( + title = stringResource(R.string.block_ignore_scope), + summary = stringResource(R.string.block_ignore_scope_hint, viewName(state.view.name, state.view.id)), + checked = block.ignoreScope, + onCheckedChange = { on -> onChange { it.copy(ignoreScope = on) } }, + position = Position.Alone, + ) + } + + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.block_remove), + position = Position.Alone, + contentColor = MaterialTheme.colorScheme.error, + leading = { Icon(Icons.Rounded.Delete, contentDescription = null) }, + onClick = onRemove, + ) + Spacer(Modifier.height(24.dp)) + } + + when (choosing) { + BlockPicker.COLOR -> (block.options as? BlockOptions.CountTile)?.let { tile -> + OptionPicker( + title = stringResource(R.string.block_color), + options = listOf(null) + TileColor.entries, + selected = tile.color, + label = { stringResource(it?.label ?: R.string.block_automatic) }, + leading = { color -> + val swatch = color?.let { tileColors(it).first } ?: MaterialTheme.colorScheme.surfaceContainerHighest + Box(Modifier.size(24.dp).clip(CircleShape).background(swatch)) + }, + onSelect = { color -> options { (it as BlockOptions.CountTile).copy(color = color) } }, + onDismiss = { choosing = null }, + ) + } + BlockPicker.ICON -> (block.options as? BlockOptions.CountTile)?.let { tile -> + ViewIconPicker( + current = tile.icon, + onSelect = { icon -> options { (it as BlockOptions.CountTile).copy(icon = icon) } }, + onDismiss = { choosing = null }, + automatic = true, + ) + } + BlockPicker.SORT -> (block.options as? BlockOptions.TaskList)?.let { list -> + OptionPicker( + title = stringResource(R.string.sort_title), + options = listOf(null) + TaskSortOrder.entries, + selected = list.sort, + label = { stringResource(it?.let(::sortLabel) ?: R.string.block_sort_default) }, + onSelect = { sort -> options { (it as BlockOptions.TaskList).copy(sort = sort) } }, + onDismiss = { choosing = null }, + ) + } + null -> Unit + } +} + +/** The pickers a block's settings open over themselves. */ +private enum class BlockPicker { COLOR, ICON, SORT } + +/** A block's own title, a heading's text; nothing for the kinds that keep a fixed one. */ +@Composable +private fun TitleSection(block: Block, state: ListsUiState.Content, options: ((BlockOptions) -> BlockOptions) -> Unit) { + val current = when (val o = block.options) { + is BlockOptions.Progress -> o.title + is BlockOptions.CountTile -> o.title + is BlockOptions.Preview -> o.title + is BlockOptions.RecentlyCompleted -> o.title + is BlockOptions.WeekStrip -> o.title + is BlockOptions.SectionHeading -> o.text + else -> return + } + val heading = block.type == BlockType.SECTION_HEADING + // An empty title shows the default one, which the field offers as its placeholder. + val fallback = if (heading) stringResource(R.string.block_heading_text_hint) else blockTitle(block.copy(options = BlockOptions.defaultFor(block.type)), state) + GroupedSectionHeader(stringResource(if (heading) R.string.block_heading_text else R.string.block_title)) + NameField( + name = current.orEmpty(), + placeholder = fallback, + autoFocus = heading && current.isNullOrEmpty(), + onNameChange = { text -> + val title = text.takeIf { it.isNotBlank() } + options { o -> + when (o) { + is BlockOptions.Progress -> o.copy(title = title) + is BlockOptions.CountTile -> o.copy(title = title) + is BlockOptions.Preview -> o.copy(title = title) + is BlockOptions.RecentlyCompleted -> o.copy(title = title) + is BlockOptions.WeekStrip -> o.copy(title = title) + is BlockOptions.SectionHeading -> o.copy(text = text) + else -> o + } + } + }, + onImeAction = {}, + ) +} + +/** The options of the block's kind. */ +@Composable +private fun TypeOptions( + block: Block, + state: ListsUiState.Content, + options: ((BlockOptions) -> BlockOptions) -> Unit, + onPick: (BlockPicker) -> Unit, +) { + when (val o = block.options) { + is BlockOptions.Progress -> { + GroupedSectionHeader(stringResource(R.string.block_section_options)) + GroupedSwitchRow( + title = stringResource(R.string.block_wave), + summary = stringResource(R.string.block_wave_hint), + checked = o.wave, + onCheckedChange = { on -> options { (it as BlockOptions.Progress).copy(wave = on) } }, + position = Position.Alone, + ) + } + is BlockOptions.CountTile -> { + GroupedSectionHeader(stringResource(R.string.block_section_look)) + GroupedRow( + title = stringResource(R.string.block_color), + summary = stringResource(o.color?.label ?: R.string.block_automatic), + position = Position.Top, + leading = { Icon(Icons.Rounded.Palette, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { onPick(BlockPicker.COLOR) }, + ) + GroupedRow( + title = stringResource(R.string.block_icon), + summary = o.icon?.let { stringResource(it.label) } ?: stringResource(R.string.block_automatic), + position = Position.Bottom, + leading = { Icon(o.icon?.vector ?: Icons.Rounded.Apps, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { onPick(BlockPicker.ICON) }, + ) + } + is BlockOptions.Preview -> { + HowMany(o.count) { count -> options { (it as BlockOptions.Preview).copy(count = count) } } + GroupedSectionHeader(stringResource(R.string.block_section_options)) + GroupedSwitchRow( + title = stringResource(R.string.block_show_all), + summary = stringResource(R.string.block_show_all_hint), + checked = o.showAll, + onCheckedChange = { on -> options { (it as BlockOptions.Preview).copy(showAll = on) } }, + position = Position.Top, + ) + GroupedSwitchRow( + title = stringResource(R.string.block_inline_done), + summary = stringResource(R.string.block_inline_done_hint), + checked = o.inlineDone, + onCheckedChange = { on -> options { (it as BlockOptions.Preview).copy(inlineDone = on) } }, + position = Position.Bottom, + ) + } + is BlockOptions.RecentlyCompleted -> + HowMany(o.count) { count -> options { (it as BlockOptions.RecentlyCompleted).copy(count = count) } } + is BlockOptions.TaskList -> { + GroupedSectionHeader(stringResource(R.string.block_section_options)) + GroupedRow( + title = stringResource(R.string.sort_title), + summary = stringResource(o.sort?.let(::sortLabel) ?: R.string.block_sort_default), + position = Position.Top, + leading = { Icon(Icons.Rounded.Sort, contentDescription = null) }, + trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) }, + onClick = { onPick(BlockPicker.SORT) }, + ) + GroupedSwitchRow( + title = stringResource(R.string.block_show_completed), + summary = stringResource(R.string.block_show_completed_hint), + checked = o.showCompleted, + onCheckedChange = { on -> options { (it as BlockOptions.TaskList).copy(showCompleted = on) } }, + position = Position.Middle, + ) + GroupedSwitchRow( + title = stringResource(R.string.block_inline_done), + summary = stringResource(R.string.block_inline_done_hint), + checked = o.inlineDone, + onCheckedChange = { on -> options { (it as BlockOptions.TaskList).copy(inlineDone = on) } }, + position = Position.Bottom, + ) + } + is BlockOptions.Lists -> ListsOptions(o, state, options) + is BlockOptions.SectionHeading, is BlockOptions.WeekStrip, BlockOptions.Tags, BlockOptions.Filters -> Unit + } +} + +/** How many tasks a preview shows, as an inline choice. */ +@Composable +private fun HowMany(count: Int, onSelect: (Int) -> Unit) { + GroupedSectionHeader(stringResource(R.string.block_how_many)) + ConnectedChoiceRow( + options = BlockOptions.PREVIEW_COUNTS, + selected = count, + label = { it.toString() }, + onSelect = onSelect, + ) +} + +/** Which accounts' lists the lists block shows, and whether with their open counts. */ +@Composable +private fun ListsOptions(o: BlockOptions.Lists, state: ListsUiState.Content, options: ((BlockOptions) -> BlockOptions) -> Unit) { + val accounts = state.lists.map { it.accountName }.distinct().sortedBy { it.lowercase() } + // An account no longer there stays listed while the block names it, so it can be unticked. + val shown = (accounts + o.accounts.orEmpty()).distinct() + if (shown.size > 1 || o.accounts != null) { + GroupedSectionHeader(stringResource(R.string.block_accounts)) + val total = shown.size + 1 + GroupedRow( + title = stringResource(R.string.block_accounts_all), + position = positionOf(0, total), + selected = o.accounts == null, + trailing = if (o.accounts == null) ({ SelectedCheck() }) else null, + onClick = { options { (it as BlockOptions.Lists).copy(accounts = null) } }, + ) + shown.forEachIndexed { index, account -> + val chosen = o.accounts?.contains(account) == true + GroupedRow( + title = account, + position = positionOf(index + 1, total), + selected = chosen, + trailing = if (chosen) ({ SelectedCheck() }) else null, + onClick = { + options { + val lists = it as BlockOptions.Lists + val now = lists.accounts.orEmpty().let { set -> if (account in set) set - account else set + account } + lists.copy(accounts = now.takeIf { set -> set.isNotEmpty() }) + } + }, + ) + } + } + GroupedSectionHeader(stringResource(R.string.block_section_options)) + GroupedSwitchRow( + title = stringResource(R.string.block_counts), + summary = stringResource(R.string.block_counts_hint), + checked = o.counts, + onCheckedChange = { on -> options { (it as BlockOptions.Lists).copy(counts = on) } }, + position = Position.Alone, + ) +} + +/** A tile colour's name. */ +private val TileColor.label: Int + get() = when (this) { + TileColor.PRIMARY -> R.string.block_color_primary + TileColor.SECONDARY -> R.string.block_color_secondary + TileColor.TERTIARY -> R.string.block_color_tertiary + TileColor.ERROR -> R.string.block_color_error + } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/HomeBlocks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/HomeBlocks.kt new file mode 100644 index 0000000..21f9519 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/HomeBlocks.kt @@ -0,0 +1,1007 @@ +package de.jeanlucmakiola.agendula.ui.lists + +import androidx.compose.animation.core.VisibilityThreshold +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.spring +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ListAlt +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.DragHandle +import androidx.compose.material.icons.rounded.ErrorOutline +import androidx.compose.material.icons.rounded.FilterAltOff +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Sell +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material.icons.rounded.Today +import androidx.compose.material.icons.rounded.Upcoming +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularWavyProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.WavyProgressIndicatorDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.Block +import de.jeanlucmakiola.agendula.domain.BlockOptions +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.BlockWidth +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.domain.TaskEnd +import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.TileColor +import de.jeanlucmakiola.agendula.domain.taskFilter +import de.jeanlucmakiola.agendula.ui.common.ActionShapes +import de.jeanlucmakiola.agendula.ui.common.ListColorChip +import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat +import de.jeanlucmakiola.agendula.ui.common.priorityAccent +import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel +import de.jeanlucmakiola.agendula.ui.views.vector +import de.jeanlucmakiola.floret.components.ActionButton +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.IconInfoCard +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.ReorderableColumn +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.identity.FloretDensity +import de.jeanlucmakiola.floret.identity.byDensity +import de.jeanlucmakiola.floret.identity.reducibleSpec +import de.jeanlucmakiola.floret.identity.rememberLoopingMotion +import de.jeanlucmakiola.floret.locale.currentLocale +import de.jeanlucmakiola.floret.locale.relativeTimeAgo +import de.jeanlucmakiola.floret.time.formatDateTimeCompact +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.TextStyle + +/** What the blocks of a view do when tapped. */ +internal class BlockActions( + /** Opens a task screen, within the scope of the view given, if any. */ + val openFilter: (TaskFilter, Long?) -> Unit, + val openTask: (Task) -> Unit, + /** Completes an open task, or reopens a completed one. */ + val toggleDone: (Task) -> Unit, + /** Offers another source for the block whose source is gone. */ + val chooseSource: (Long) -> Unit, + val newList: () -> Unit, + val newFilter: () -> Unit, + val reorderLists: (List) -> Unit, + /** The view a block opens its tasks within: none when it ignores the scope. */ + val scopeFor: (Block) -> Long?, +) + +/** The blocks drawn as tiles, side by side when half wide. */ +internal val TILES = setOf(BlockType.PROGRESS, BlockType.COUNT_TILE) + +/** + * The name a block goes by: its own title, else its source's name or its kind's. + * Empty for a section heading without text. + */ +@Composable +internal fun blockTitle(block: Block, state: ListsUiState.Content): String { + val source = block.source + return when (val options = block.options) { + is BlockOptions.Progress -> options.title ?: stringResource(R.string.smart_today) + is BlockOptions.CountTile -> options.title ?: source?.let { sourceLabel(it, state) }.orEmpty() + is BlockOptions.Preview -> options.title ?: source?.let { sourceLabel(it, state) }.orEmpty() + is BlockOptions.RecentlyCompleted -> options.title ?: stringResource(R.string.block_recent) + is BlockOptions.WeekStrip -> options.title ?: stringResource(R.string.block_week_title) + is BlockOptions.SectionHeading -> options.text + is BlockOptions.TaskList -> stringResource(R.string.block_task_list) + is BlockOptions.Lists -> stringResource(R.string.lists_header) + BlockOptions.Tags -> stringResource(R.string.tags_header) + BlockOptions.Filters -> stringResource(R.string.filters_header) + } +} + +/** The name a block's source goes by. */ +@Composable +internal 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.filterNames[source.filterId].orEmpty() + is BlockSource.Rules -> stringResource(R.string.block_source_rules) + is BlockSource.ListElsewhere -> "" +} + +/** Whether to mark [block] as reading past its view's scope. */ +internal fun ListsUiState.Content.marksIgnoredScope(block: Block): Boolean = view.scope != null && block.ignoreScope + +/** + * A full-width block's content, under its header unless [showHeader] is off (an + * edit frame shows the title itself). While [editing], a block that would show + * nothing says what it is instead, and taps go to the frame rather than in. + */ +@Composable +internal fun BlockBody( + block: Block, + state: ListsUiState.Content, + actions: BlockActions, + editing: Boolean, + showHeader: Boolean = true, + reorderingLists: Boolean = false, + onToggleReorderLists: () -> Unit = {}, +) { + if (block.id in state.goneSources) { + Notice( + text = stringResource(R.string.view_source_gone), + action = stringResource(R.string.view_choose_source), + onAction = { actions.chooseSource(block.id) }, + ) + return + } + val marked = state.marksIgnoredScope(block) + val open = { filter: TaskFilter -> actions.openFilter(filter, actions.scopeFor(block)) } + val header: @Composable (String) -> Unit = { title -> if (showHeader) SectionHeader(title, marked = marked) } + when (block.type) { + BlockType.PREVIEW -> { + val tasks = state.previews[block.id].orEmpty() + val filter = block.source?.taskFilter + val options = block.options as BlockOptions.Preview + if (tasks.isEmpty()) { + if (editing) BlockPlaceholder(stringResource(R.string.block_empty)) + return + } + header(blockTitle(block, state)) + TaskCard( + tasks = tasks, + onOpenTask = actions.openTask, + onToggle = if (options.inlineDone) actions.toggleDone else null, + onViewAll = if (options.showAll && filter != null) ({ open(filter) }) else null, + ) + } + BlockType.RECENTLY_COMPLETED -> { + val tasks = state.recent[block.id].orEmpty() + if (tasks.isEmpty()) { + if (editing) BlockPlaceholder(stringResource(R.string.block_recent_empty)) + return + } + header(blockTitle(block, state)) + TaskCard(tasks = tasks, onOpenTask = actions.openTask, onToggle = actions.toggleDone, onViewAll = null, completedTime = true) + } + BlockType.WEEK_STRIP -> state.weeks[block.id]?.let { week -> + header(blockTitle(block, state)) + WeekStrip(week, onOpenDay = { open(TaskFilter.DueOn(it)) }) + } + BlockType.SECTION_HEADING -> { + val text = (block.options as BlockOptions.SectionHeading).text + if (text.isNotBlank()) { + if (showHeader) SectionHeader(text) + } else if (editing) { + BlockPlaceholder(stringResource(R.string.block_heading_empty)) + } + } + BlockType.LISTS -> ListsBlock( + options = block.options as BlockOptions.Lists, + groups = state.sectionsFor(block).groups, + anyLists = state.lists.isNotEmpty(), + showHeader = showHeader, + marked = marked, + reordering = reorderingLists && !editing, + onToggleReorder = onToggleReorderLists, + onOpen = open, + onNewList = actions.newList, + onReorder = actions.reorderLists, + actionsShown = !editing, + ) + BlockType.TAGS -> { + val tags = state.sectionsFor(block).tags + if (tags.isEmpty()) { + if (editing) BlockPlaceholder(stringResource(R.string.block_empty)) + return + } + header(stringResource(R.string.tags_header)) + TagsBlock(tags, open) + } + BlockType.FILTERS -> if (state.lists.isNotEmpty()) { + FiltersBlock( + filters = state.sectionsFor(block).filters, + showHeader = showHeader, + marked = marked, + onOpen = open, + onNewFilter = actions.newFilter, + actionsShown = !editing, + ) + } else if (editing) { + BlockPlaceholder(stringResource(R.string.block_empty)) + } + BlockType.TASK_LIST -> if (editing) { + BlockPlaceholder( + stringResource(R.string.block_task_list_summary, block.source?.let { sourceLabel(it, state) }.orEmpty()), + ) + } + BlockType.PROGRESS, BlockType.COUNT_TILE -> Tile(block, state, actions, Modifier.fillMaxWidth().padding(horizontal = GroupedListInset)) + } +} + +/** + * A progress or count tile: a notice for a source since deleted, an empty space + * for one it can't show. A full progress tile is the Today hero; a half one, and + * any progress tile while compact, the smaller ring tile. + */ +@Composable +internal fun Tile(block: Block, state: ListsUiState.Content, actions: BlockActions, modifier: Modifier = Modifier) { + if (block.id in state.goneSources) { + GoneTile(onChoose = { actions.chooseSource(block.id) }, modifier = modifier) + return + } + val filter = block.source?.taskFilter + val open = { filter?.let { actions.openFilter(it, actions.scopeFor(block)) } ?: Unit } + val marked = state.marksIgnoredScope(block) + when (val options = block.options) { + is BlockOptions.Progress -> state.progress[block.id]?.takeIf { filter != null }?.let { progress -> + if (block.width == BlockWidth.HALF) { + ProgressTile(progress.done, progress.total, blockTitle(block, state), options.wave, marked, open, modifier) + } else { + TodayHero(progress.done, progress.total, options.title, options.wave, marked, open, modifier) + } + } + is BlockOptions.CountTile -> state.counts[block.id]?.takeIf { filter != null }?.let { count -> + CountCard(tileStyle(block, options, state), count, marked, modifier, open) + } + else -> null + } ?: Spacer(modifier.height(FloretDensity.tileHeight)) +} + +/** A notice standing in for something gone, with the way to fix it. */ +@Composable +internal 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) } + } +} + +/** What an empty block shows while the layout is edited, so it can still be found. */ +@Composable +private fun BlockPlaceholder(text: String) { + Surface( + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier.fillMaxWidth().padding(horizontal = GroupedListInset), + ) { + Text( + text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 20.dp), + ) + } +} + +/** 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 = FloretDensity.tileHeight), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(byDensity(8.dp, 4.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, + ) + } + } +} + +/** The small mark on a block that shows tasks outside its view's scope. */ +@Composable +private fun IgnoredScopeMark(tint: Color = MaterialTheme.colorScheme.onSurfaceVariant) { + val description = stringResource(R.string.block_ignores_scope) + Icon( + Icons.Rounded.FilterAltOff, + contentDescription = description, + tint = tint, + modifier = Modifier.size(16.dp), + ) +} + +/** The corner a tile rounds to, rounder while pressed. */ +@Composable +private fun pressCorner(interaction: MutableInteractionSource): Dp { + val pressed by interaction.collectIsPressedAsState() + val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, reducibleSpec(spring(visibilityThreshold = Dp.VisibilityThreshold)), label = "tileCorner") + return corner +} + +/** + * The day's momentum: a wavy progress ring over "x of y done" for tasks due today. + * Tapping opens the Today list. When nothing is due today it drops the ring and + * reads as a calm, finished state rather than an empty 0. The ring's wave moves + * when [wave] is on and motion isn't reduced. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun TodayHero( + done: Int, + total: Int, + title: String?, + wave: Boolean, + marked: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val interaction = remember { MutableInteractionSource() } + val left = total - done + Surface( + onClick = onClick, + shape = RoundedCornerShape(pressCorner(interaction)), + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + interactionSource = interaction, + modifier = modifier.height(byDensity(140.dp, 112.dp)), + ) { + Row( + modifier = Modifier.fillMaxSize().padding(byDensity(20.dp, 16.dp)), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(byDensity(6.dp, 2.dp)), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Icons.Rounded.Today, contentDescription = null, modifier = Modifier.size(20.dp)) + Text(title ?: stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium) + if (marked) IgnoredScopeMark(MaterialTheme.colorScheme.onPrimaryContainer) + } + val headline = when { + total == 0 -> stringResource(R.string.home_today_empty) + left == 0 -> stringResource(R.string.home_today_all_done) + else -> pluralStringResource(R.plurals.home_today_progress_count, total, done, total) + } + Text(headline, style = MaterialTheme.typography.headlineSmall) + if (total > 0 && left > 0) { + Text( + pluralStringResource(R.plurals.home_today_remaining_count, left, left), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f), + ) + } + } + if (total > 0) { + ProgressRing(done, total, wave, byDensity(84.dp, 72.dp), MaterialTheme.colorScheme.onPrimaryContainer) + } + } + } +} + +/** The progress block at half width: title and "x of y" beside a small ring, a tile's height. */ +@Composable +private fun ProgressTile( + done: Int, + total: Int, + title: String, + wave: Boolean, + marked: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val interaction = remember { MutableInteractionSource() } + Surface( + onClick = onClick, + shape = RoundedCornerShape(pressCorner(interaction)), + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + interactionSource = interaction, + modifier = modifier.height(FloretDensity.tileHeight), + ) { + Row( + modifier = Modifier.fillMaxSize().padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + title, + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (marked) IgnoredScopeMark(MaterialTheme.colorScheme.onPrimaryContainer) + } + Text( + if (total == 0) stringResource(R.string.home_today_empty) else stringResource(R.string.block_progress_short, done, total), + style = MaterialTheme.typography.titleLarge, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + if (total > 0) ProgressRing(done, total, wave, 48.dp, MaterialTheme.colorScheme.onPrimaryContainer) + } + } +} + +/** A wavy ring of [done] out of [total]; the wave is still unless [wave] is on and motion runs. */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun ProgressRing(done: Int, total: Int, wave: Boolean, size: Dp, color: Color) { + val wavelength = WavyProgressIndicatorDefaults.CircularWavelength + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(size)) { + CircularWavyProgressIndicator( + progress = { done.toFloat() / total }, + modifier = Modifier.fillMaxSize(), + color = color, + trackColor = color.copy(alpha = 0.22f), + wavelength = wavelength, + // A still wave when switched off, when motion is reduced or the system removed animations (#157). + waveSpeed = if (wave && rememberLoopingMotion()) wavelength else 0.dp, + ) + Text( + stringResource(R.string.progress_fraction_compact, done, total), + style = if (size >= 72.dp) MaterialTheme.typography.titleMedium else MaterialTheme.typography.labelMedium, + ) + } +} + +/** 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 tileStyle(block: Block, options: BlockOptions.CountTile, state: ListsUiState.Content): TileStyle { + val colors = MaterialTheme.colorScheme + val source = block.source + val label = blockTitle(block, state) + val auto = 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, is BlockSource.Rules -> TileStyle(Icons.Rounded.FilterList, label, colors.tertiaryContainer, colors.onTertiaryContainer) + else -> TileStyle(Icons.AutoMirrored.Rounded.ListAlt, label, colors.secondaryContainer, colors.onSecondaryContainer) + } + val (container, onContainer) = options.color?.let { tileColors(it) } ?: (auto.container to auto.onContainer) + return auto.copy(icon = options.icon?.vector ?: auto.icon, container = container, onContainer = onContainer) +} + +/** A tile colour's container and the colour on it. */ +@Composable +internal fun tileColors(color: TileColor): Pair { + val colors = MaterialTheme.colorScheme + return when (color) { + TileColor.PRIMARY -> colors.primaryContainer to colors.onPrimaryContainer + TileColor.SECONDARY -> colors.secondaryContainer to colors.onSecondaryContainer + TileColor.TERTIARY -> colors.tertiaryContainer to colors.onTertiaryContainer + TileColor.ERROR -> colors.errorContainer to colors.onErrorContainer + } +} + +/** + * Clean tonal tile. The expressive touch is subtle: rounded corners gently morph + * rounder on press (the same quiet shape behaviour as the lists), not a loud + * silhouette. Full width it lays out in a row: icon and name, count at the end. + */ +@Composable +private fun CountCard(style: TileStyle, count: Int, marked: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { + val interaction = remember { MutableInteractionSource() } + Surface( + onClick = onClick, + shape = RoundedCornerShape(pressCorner(interaction)), + color = style.container, + contentColor = style.onContainer, + interactionSource = interaction, + modifier = modifier.height(FloretDensity.tileHeight), + ) { + Column( + modifier = Modifier.fillMaxSize().padding(byDensity(16.dp, 12.dp)), + verticalArrangement = Arrangement.SpaceBetween, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(style.icon, contentDescription = null) + Spacer(Modifier.weight(1f)) + if (marked) IgnoredScopeMark(style.onContainer) + } + Column { + Text(count.toString(), style = byDensity(MaterialTheme.typography.headlineMedium, MaterialTheme.typography.headlineSmall)) + Text(style.label, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } +} + +/** + * A grouped card of a few tasks, with a "view all" tail when [onViewAll] is set. + * With [onToggle] each row leads with a checkbox that completes it, or reopens a + * completed one; [completedTime] says when each was completed instead of its due. + */ +@Composable +private fun TaskCard( + tasks: List, + onOpenTask: (Task) -> Unit, + onToggle: ((Task) -> Unit)?, + onViewAll: (() -> Unit)?, + completedTime: Boolean = false, +) { + Surface( + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier.fillMaxWidth().padding(horizontal = GroupedListInset), + ) { + Column { + tasks.forEach { task -> + UpcomingRow( + task = task, + onClick = { onOpenTask(task) }, + onToggle = onToggle?.let { toggle -> { toggle(task) } }, + completedTime = completedTime, + ) + } + if (onViewAll != null) ViewAllRow(onViewAll) + } + } +} + +@Composable +private fun ViewAllRow(onViewAll: () -> Unit) { + Surface(onClick = onViewAll, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.home_upcoming_view_all), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + ) + Spacer(Modifier.weight(1f)) + Icon( + Icons.Rounded.ChevronRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + ) + } + } +} + +/** + * One slim task row: list-colour avatar (or a checkbox, with [onToggle]), title, + * then a quiet meta line of the relative due date and (if set) a tinted priority + * flag — the same calm one-line treatment as the task list, minus the swipe + * machinery. A completed task is struck through; with [completedTime] the meta + * line says when it was completed. + */ +@Composable +internal fun UpcomingRow(task: Task, onClick: () -> Unit, onToggle: (() -> Unit)? = null, completedTime: Boolean = false) { + val dark = isSystemInDarkTheme() + val muted = MaterialTheme.colorScheme.onSurfaceVariant + val metaStyle = MaterialTheme.typography.bodySmall + Surface(onClick = onClick, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = byDensity(60.dp, 52.dp)) + .padding(start = if (onToggle != null) 4.dp else 16.dp, end = 16.dp) + .padding(vertical = FloretDensity.cardRowInset), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(if (onToggle != null) 4.dp else 12.dp), + ) { + if (onToggle != null) { + val description = stringResource(if (task.isCompleted) R.string.cd_reopen else R.string.cd_complete) + Checkbox( + checked = task.isCompleted, + onCheckedChange = { onToggle() }, + enabled = !task.isReadOnly, + modifier = Modifier.semantics { contentDescription = description }, + ) + } else { + ListColorChip(task.effectiveColor) + } + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + task.title, + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textDecoration = if (task.isCompleted) TextDecoration.LineThrough else null, + color = if (task.isCompleted) muted else MaterialTheme.colorScheme.onSurface, + ) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + val meta = if (completedTime) completedLabel(task) else upcomingDueLabel(task) + meta?.let { Text(it, style = metaStyle, color = muted) } + if (task.priority != Priority.NONE && !completedTime) { + if (meta != null) Text("·", style = metaStyle, color = muted) + Icon( + Icons.Rounded.Flag, + contentDescription = null, + tint = priorityAccent(task.priority, dark), + modifier = Modifier.size(13.dp), + ) + Text(priorityLabel(task.priority), style = metaStyle, color = muted) + } + } + } + } + } +} + +/** "Today" / "Tomorrow" for the near dates, else the compact date. */ +@Composable +private fun upcomingDueLabel(task: Task): String? { + val due = task.shownValue(TaskEnd.DUE) ?: return null + val zone = remember { ZoneId.systemDefault() } + val today = remember { LocalDate.now(zone) } + val dueDate = remember(task) { task.dateOf(TaskEnd.DUE, zone) } + return when (dueDate) { + today -> stringResource(R.string.home_due_today) + today.plusDays(1) -> stringResource(R.string.home_due_tomorrow) + else -> due.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), LocalUse24HourFormat.current) + } +} + +/** "Done 10 minutes ago", or nothing for a task without a completion time. */ +@Composable +private fun completedLabel(task: Task): String? { + val at = task.completedAt ?: return null + return stringResource(R.string.block_recent_done_at, relativeTimeAgo(at.toEpochMilliseconds())) +} + +/** + * The week holding today, a day per column with up to three dots for the open + * tasks due that day and today highlighted. Tapping a day opens its tasks. + */ +@Composable +private fun WeekStrip(week: WeekStripDays, onOpenDay: (LocalDate) -> Unit) { + val locale = currentLocale() + val dayFormat = de.jeanlucmakiola.agendula.ui.common.rememberDayFormat(long = true) + Surface( + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier.fillMaxWidth().padding(horizontal = GroupedListInset), + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(byDensity(8.dp, 4.dp)), + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + week.days.forEach { day -> + val isToday = day == week.today + val due = week.due[day] ?: 0 + val description = pluralStringResource(R.plurals.block_week_day, due, dayFormat.format(day, week.today), due) + Surface( + onClick = { onOpenDay(day) }, + shape = RoundedCornerShape(16.dp), + color = if (isToday) MaterialTheme.colorScheme.primary else Color.Transparent, + contentColor = if (isToday) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface, + modifier = Modifier + .weight(1f) + .semantics(mergeDescendants = true) { + contentDescription = description + selected = isToday + }, + ) { + Column( + modifier = Modifier.padding(vertical = byDensity(10.dp, 6.dp)), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + day.dayOfWeek.getDisplayName(TextStyle.NARROW, locale), + style = MaterialTheme.typography.labelSmall, + ) + Text(day.dayOfMonth.toString(), style = MaterialTheme.typography.titleMedium) + DueDots(due) + } + } + } + } + } +} + +/** Up to three dots, one per open task due; a fixed height so the days line up. */ +@Composable +private fun DueDots(count: Int) { + Row( + modifier = Modifier.height(6.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + repeat(count.coerceAtMost(3)) { + Surface(shape = CircleShape, color = androidx.compose.material3.LocalContentColor.current, modifier = Modifier.size(4.dp)) {} + } + } +} + +/** The user's lists by account, reorderable in place, or the way to make the first one. */ +@Composable +private fun ListsBlock( + options: BlockOptions.Lists, + groups: List, + anyLists: Boolean, + showHeader: Boolean, + marked: Boolean, + reordering: Boolean, + onToggleReorder: () -> Unit, + onOpen: (TaskFilter) -> Unit, + onNewList: () -> Unit, + onReorder: (List) -> Unit, + actionsShown: Boolean, +) { + if (!anyLists) { + EmptyLists(onNewList = onNewList) + return + } + val shown = options.accounts?.let { accounts -> groups.filter { it.accountName in accounts } } ?: groups + if (shown.isEmpty()) { + if (!actionsShown) BlockPlaceholder(stringResource(R.string.block_empty)) + return + } + Column { + if (showHeader) { + SectionHeader( + text = stringResource(R.string.lists_header), + marked = marked, + action = if (!actionsShown) { + null + } else { + { + ActionButton( + shape = ActionShapes.Reorder, + icon = if (reordering) Icons.Rounded.Check else Icons.Rounded.SwapVert, + contentDescription = stringResource( + if (reordering) R.string.lists_reorder_done else R.string.lists_reorder, + ), + onClick = onToggleReorder, + ) + ActionButton( + shape = ActionShapes.AddList, + morphTo = ActionShapes.AddListPressed, + icon = Icons.Rounded.Add, + contentDescription = stringResource(R.string.list_add), + onClick = onNewList, + ) + } + }, + ) + } + shown.forEach { group -> + AccountHeader(group.accountName) + if (reordering) { + ReorderableColumn( + items = group.lists, + keyOf = { it.list.id }, + onReorder = { ordered -> onReorder(ordered.map { it.list.id }) }, + rowHeight = FloretDensity.rowHeight, + ) { overview, position, dragHandle, isDragging -> + GroupedRow( + title = overview.list.name, + position = position, + gapBelow = false, + container = if (isDragging) MaterialTheme.colorScheme.secondaryContainer else null, + leading = { ListColorChip(overview.list.color) }, + trailing = { + Box(modifier = dragHandle.size(48.dp), contentAlignment = Alignment.Center) { + Icon( + Icons.Rounded.DragHandle, + contentDescription = stringResource(R.string.lists_reorder_handle), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + ) + } + } else { + group.lists.forEachIndexed { index, overview -> + GroupedRow( + title = overview.list.name, + position = positionOf(index, group.lists.size), + leading = { ListColorChip(overview.list.color) }, + trailing = { + if (options.counts && overview.openCount > 0) Count(overview.openCount) + }, + onClick = { onOpen(TaskFilter.OfList(overview.list.id)) }, + ) + } + } + } + } +} + +/** Each tag on an open task with its count. */ +@Composable +private fun TagsBlock(tags: List, onOpen: (TaskFilter) -> Unit) { + Column { + tags.forEachIndexed { index, overview -> + GroupedRow( + title = overview.tag, + position = positionOf(index, tags.size), + leading = { + Icon(Icons.Rounded.Sell, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + }, + trailing = { Count(overview.openCount) }, + onClick = { onOpen(TaskFilter.Tagged(overview.tag)) }, + ) + } + } +} + +/** The saved filters, or a single row offering the first one. */ +@Composable +private fun FiltersBlock( + filters: List, + showHeader: Boolean, + marked: Boolean, + onOpen: (TaskFilter) -> Unit, + onNewFilter: () -> Unit, + actionsShown: Boolean, +) { + Column { + if (showHeader) { + SectionHeader( + text = stringResource(R.string.filters_header), + marked = marked, + action = if (filters.isEmpty() || !actionsShown) { + null + } else { + { + ActionButton( + shape = ActionShapes.AddFilter, + morphTo = ActionShapes.AddListPressed, + icon = Icons.Rounded.Add, + contentDescription = stringResource(R.string.filter_new_title), + onClick = onNewFilter, + ) + } + }, + ) + } + if (filters.isEmpty()) { + GroupedRow( + title = stringResource(R.string.filter_new_title), + summary = stringResource(R.string.filters_empty_hint), + position = Position.Alone, + leading = { Icon(Icons.Rounded.Add, contentDescription = null) }, + onClick = onNewFilter, + ) + return@Column + } + filters.forEachIndexed { index, overview -> + GroupedRow( + title = overview.filter.name, + position = positionOf(index, filters.size), + leading = { + Icon(Icons.Rounded.FilterList, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + }, + trailing = { Count(overview.openCount) }, + onClick = { onOpen(TaskFilter.Saved(overview.filter.id)) }, + ) + } + } +} + +@Composable +private fun Count(count: Int) { + Text( + count.toString(), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** No lists at all — a fresh install, where nothing else on this screen works yet. */ +@Composable +private fun EmptyLists(onNewList: () -> Unit) { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text( + text = stringResource(R.string.lists_empty), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + FilledTonalButton(onClick = onNewList) { + Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.lists_empty_action)) + } + } +} + +/** A block's heading; [marked] when the block reads past its view's scope. */ +@Composable +internal fun SectionHeader(text: String, marked: Boolean = false, action: (@Composable () -> Unit)? = null) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding( + start = 28.dp, + end = if (action == null) 28.dp else 20.dp, + top = if (action == null) byDensity(16.dp, 12.dp) else 12.dp, + bottom = 4.dp, + ), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = text, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.weight(1f, fill = false), + ) + if (marked) { + Spacer(Modifier.width(6.dp)) + IgnoredScopeMark() + } + Spacer(Modifier.weight(1f)) + action?.invoke() + } +} + +@Composable +private fun AccountHeader(text: String) { + Text( + text = text, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp), + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index fe535ba..4efc0dc 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 @@ -1,69 +1,44 @@ package de.jeanlucmakiola.agendula.ui.lists -import de.jeanlucmakiola.floret.components.ReorderableColumn -import androidx.compose.material.icons.rounded.Check -import androidx.compose.material.icons.rounded.DragHandle -import androidx.compose.material.icons.rounded.FilterList -import androidx.compose.material.icons.rounded.Sell -import androidx.compose.material.icons.rounded.SwapVert import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.animateDpAsState -import androidx.compose.animation.core.VisibilityThreshold -import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.expandHorizontally import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkHorizontally -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.interaction.collectIsPressedAsState -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.union import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.windowInsetsPadding -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyListScope -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ListAlt import androidx.compose.material.icons.rounded.Add -import androidx.compose.material.icons.rounded.ChevronRight -import androidx.compose.material.icons.rounded.ErrorOutline -import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Dashboard +import androidx.compose.material.icons.rounded.MoreVert import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Settings -import androidx.compose.material.icons.rounded.Today -import androidx.compose.material.icons.rounded.Upcoming -import androidx.compose.material3.CircularWavyProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material.icons.rounded.Tune +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExtendedFloatingActionButton -import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults -import androidx.compose.material3.WavyProgressIndicatorDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -73,13 +48,10 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -87,52 +59,36 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.Block import de.jeanlucmakiola.agendula.domain.BlockOptions -import de.jeanlucmakiola.agendula.domain.BlockSource import de.jeanlucmakiola.agendula.domain.BlockType import de.jeanlucmakiola.agendula.domain.BlockWidth -import de.jeanlucmakiola.agendula.domain.TaskEnd -import de.jeanlucmakiola.agendula.domain.rows -import de.jeanlucmakiola.agendula.domain.Priority -import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task -import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.domain.TaskSearch import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.rows import de.jeanlucmakiola.agendula.domain.taskFilter +import de.jeanlucmakiola.agendula.ui.common.ActionShapes +import de.jeanlucmakiola.agendula.ui.common.SearchPill +import de.jeanlucmakiola.agendula.ui.common.SyncPullBox +import de.jeanlucmakiola.agendula.ui.tasklist.ClearCompletedDialog 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.clearableCompleted import de.jeanlucmakiola.agendula.ui.tasklist.rememberTaskRows import de.jeanlucmakiola.agendula.ui.tasklist.taskRows import de.jeanlucmakiola.agendula.ui.views.ScopeChipRow 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.ActionButton -import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.FloretDropdownMenu import de.jeanlucmakiola.floret.components.SnackChip import de.jeanlucmakiola.floret.components.SnackChipHeight import de.jeanlucmakiola.floret.components.SnackChipMargin -import kotlinx.coroutines.delay -import de.jeanlucmakiola.agendula.ui.common.ListColorChip -import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat -import de.jeanlucmakiola.agendula.ui.common.SearchPill -import de.jeanlucmakiola.agendula.ui.common.SyncPullBox -import de.jeanlucmakiola.agendula.ui.common.priorityAccent -import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel -import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.FloretDensity -import de.jeanlucmakiola.floret.identity.byDensity -import de.jeanlucmakiola.floret.identity.reducibleSpec -import de.jeanlucmakiola.floret.identity.rememberLoopingMotion import de.jeanlucmakiola.floret.identity.rememberReduceMotion -import de.jeanlucmakiola.floret.time.formatDateTimeCompact -import java.time.LocalDate -import java.time.ZoneId +import kotlinx.coroutines.delay /** * Home, laid out by the blocks of the active view, each read through the view's @@ -140,6 +96,9 @@ import java.time.ZoneId * 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. + * + * *Edit layout* in the ⋮ menu, or a long press on a block, turns the blocks into + * a grid to rearrange, resize, remove, add to and open the settings of. */ @Composable fun ListsScreen( @@ -164,6 +123,15 @@ fun ListsScreen( var listsAndFilters by rememberSaveable { mutableStateOf(false) } // The block whose deleted source is being replaced. var choosingSourceFor by rememberSaveable { mutableStateOf(null) } + // Adding a block: picking its kind, then its source for a kind that takes one. + var addingBlock by rememberSaveable { mutableStateOf(false) } + var addingType by rememberSaveable { mutableStateOf(null) } + // The source picker over an open block's settings. + var choosingDraftSource by rememberSaveable { mutableStateOf(false) } + var confirmClear by rememberSaveable { mutableStateOf(false) } + val editing by viewModel.editingLayout.collectAsStateWithLifecycle() + val removed by viewModel.removed.collectAsStateWithLifecycle() + val draft by viewModel.blockDraft.collectAsStateWithLifecycle() 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 — @@ -187,8 +155,10 @@ fun ListsScreen( viewModel.clearWriteFailure() } } - // System back closes search before leaving the screen. + // System back closes search, or leaves the layout editor, before leaving the screen. BackHandler(enabled = searchActive, onBack = closeSearch) + BackHandler(enabled = editing, onBack = viewModel::stopEditingLayout) + LaunchedEffect(editing) { if (editing) 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 } @@ -197,6 +167,7 @@ fun ListsScreen( 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. + // It also checks off the tasks of a preview or a recently completed block. val homeTaskModel: TaskListViewModel = hiltViewModel(key = "home-task-block") val blockModel: TaskListViewModel? = if (content != null && taskBlock != null && taskFilter != null) { val scopeViewId = scopeFor(taskBlock) @@ -210,27 +181,43 @@ fun ListsScreen( } val undo by homeTaskModel.undo.collectAsStateWithLifecycle() val viewSaveFailed by viewModel.viewSaveFailed.collectAsStateWithLifecycle() + val actions = BlockActions( + openFilter = onOpenFilter, + openTask = onOpenTask, + toggleDone = homeTaskModel::toggleComplete, + chooseSource = { choosingSourceFor = it }, + newList = { newList = true }, + newFilter = onNewFilter, + reorderLists = viewModel::reorderLists, + scopeFor = scopeFor, + ) 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 }, - onToggleSearch = { if (searchActive) closeSearch() else searchActive = true }, - onOpenSettings = onOpenSettings, - ) + if (editing) { + EditLayoutTopBar(onAdd = { addingBlock = true }, onDone = viewModel::stopEditingLayout) + } else { + 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, + onEditLayout = { content?.view?.id?.let(viewModel::editLayout) }, + onEditView = { content?.view?.id?.let(onEditView) }, + searchActive = searchActive, + query = query, + onQueryChange = { query = it }, + onToggleSearch = { if (searchActive) closeSearch() else searchActive = true }, + onOpenSettings = onOpenSettings, + ) + } }, floatingActionButton = { - // The FAB would otherwise float over the search results. - if (!searchActive) { + // The FAB would otherwise float over the search results, or the layout being edited. + if (!searchActive && !editing) { ExtendedFloatingActionButton( onClick = if (noLists) ({ newList = true }) else ({ onNewTask(content?.newTaskList, content?.newTaskTag) }), icon = { Icon(Icons.Rounded.Add, contentDescription = null) }, @@ -242,7 +229,7 @@ fun ListsScreen( }, ) { inner -> SyncPullBox( - available = syncAvailable && !searchActive, + available = syncAvailable && !searchActive && !editing, syncing = syncing, onSync = viewModel::syncAll, modifier = Modifier.fillMaxSize().padding(top = inner.calculateTopPadding()), @@ -250,22 +237,27 @@ fun ListsScreen( when (val s = state) { ListsUiState.Loading -> Unit // brief; avoids a flash before first emission ListsUiState.Failure -> - CenteredMessage(stringResource(R.string.lists_failure), PaddingValues(0.dp)) - is ListsUiState.Content -> { + CenteredMessage(stringResource(R.string.lists_failure)) + is ListsUiState.Content -> if (editing) { + EditLayoutContent( + state = s, + onMove = { ids -> viewModel.moveBlocks(s.view.id, ids) }, + onResize = { block, width -> viewModel.resizeBlock(s.view.id, block.id, width) }, + onRemove = { block -> viewModel.removeBlock(s.view.id, block) }, + onOpenSettings = { block -> viewModel.editBlock(s.view.id, block) }, + onAdd = { addingBlock = true }, + bottomPadding = inner.calculateBottomPadding() + SnackChipHeight + SnackChipMargin * 2, + ) + } else { ListsContent( state = s, - onOpenFilter = onOpenFilter, - scopeFor = scopeFor, - onOpenTask = onOpenTask, - onNewList = { newList = true }, - onNewFilter = onNewFilter, - onReorder = viewModel::reorderLists, - onChooseSource = { choosingSourceFor = it }, + actions = actions, onEditScope = { onEditView(s.view.id) }, + onEditLayout = viewModel::editShownLayout, + onClearCompleted = { confirmClear = true }, taskBlock = blockModel?.let { model -> taskBlock?.let { block -> TaskBlock(block, taskFilter!!, scopeFor(block), model) } }, - topPadding = 0.dp, bottomPadding = inner.calculateBottomPadding() + 96.dp, ) // While searching with a non-blank query, results cover the home @@ -299,19 +291,30 @@ fun ListsScreen( .height(SnackChipHeight), contentAlignment = Alignment.CenterStart, ) { - // One chip: a refused write, else the task block's undo. + // One chip: a refused write, else a removed block's undo, else the task block's undo. val failure = writeFailure val receipt = undo + val gone = removed SnackChip( - visible = failure != null || viewSaveFailed || receipt != null, + visible = failure != null || viewSaveFailed || gone != null || receipt != null, message = when { failure != null -> stringResource(listWriteFailureMessage(failure)) viewSaveFailed -> stringResource(R.string.view_save_failed) + gone != null -> stringResource(R.string.block_removed) receipt is UndoReceipt.Completed -> stringResource(R.string.task_completed) else -> stringResource(R.string.task_deleted) }, - actionLabel = if (failure == null && !viewSaveFailed && receipt != null) stringResource(R.string.undo) else null, - onAction = if (failure == null && !viewSaveFailed && receipt != null) homeTaskModel::undo else null, + actionLabel = if (failure == null && !viewSaveFailed && (gone != null || receipt != null)) { + stringResource(R.string.undo) + } else { + null + }, + onAction = when { + failure != null || viewSaveFailed -> null + gone != null -> viewModel::undoRemove + receipt != null -> homeTaskModel::undo + else -> null + }, ) } } @@ -348,6 +351,58 @@ fun ListsScreen( onDismiss = { choosingSourceFor = null }, ) } + + if (confirmClear) { + val blockState = homeTaskModel.state.collectAsStateWithLifecycle().value as? TaskListUiState.Content + ClearCompletedDialog( + count = blockState?.clearableCompleted()?.size ?: 0, + onConfirm = homeTaskModel::clearCompleted, + onDismiss = { confirmClear = false }, + ) + } + + if (content == null || !editing) return + if (addingBlock) { + AddBlockPicker( + blocks = content.view.blocks, + onPick = { type -> + if (type.takesSource) addingType = type else viewModel.addBlock(content.view.id, type, null) + }, + onDismiss = { addingBlock = false }, + ) + } + addingType?.let { type -> + SourcePicker( + title = stringResource(R.string.block_source_title), + state = content, + withSmartLists = true, + todayOnly = type == BlockType.PROGRESS, + onPick = { source -> viewModel.addBlock(content.view.id, type, source) }, + onDismiss = { addingType = null }, + ) + } + val open = draft?.takeIf { it.viewId == content.view.id } + if (open != null) { + BlockSettings( + block = open.block, + state = content, + onChange = viewModel::updateDraft, + onChooseSource = { choosingDraftSource = true }, + onSave = viewModel::saveDraft, + onRemove = { viewModel.removeBlock(content.view.id, open.block) }, + onDismiss = viewModel::closeDraft, + ) + if (choosingDraftSource) { + SourcePicker( + title = stringResource(R.string.block_source_title), + state = content, + withSmartLists = true, + todayOnly = open.block.type == BlockType.PROGRESS, + onPick = { source -> viewModel.updateDraft { it.copy(source = source) } }, + onDismiss = { choosingDraftSource = false }, + ) + } + } } /** @@ -369,40 +424,43 @@ 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 scopeViewId: Long?, val model: TaskListViewModel) +/** The view's blocks, row by row; a long press on one opens the layout editor. */ @Composable private fun ListsContent( state: ListsUiState.Content, - onOpenFilter: (TaskFilter, Long?) -> Unit, - scopeFor: (Block) -> Long?, - onOpenTask: (Task) -> Unit, - onNewList: () -> Unit, - onNewFilter: () -> Unit, - onReorder: (List) -> Unit, - onChooseSource: (Long) -> Unit, + actions: BlockActions, onEditScope: () -> Unit, + onEditLayout: () -> Unit, + onClearCompleted: () -> Unit, taskBlock: TaskBlock?, - topPadding: androidx.compose.ui.unit.Dp, - bottomPadding: androidx.compose.ui.unit.Dp, + bottomPadding: Dp, ) { // Lists get drag handles only while reordering, so the home screen stays calm. // Holds the id of the lists block being reordered. var reordering by rememberSaveable { mutableStateOf(null) } + val haptics = LocalHapticFeedback.current + val longPress = Modifier.onLongPressOver(haptics, onEditLayout) val blocks = state.view.blocks val rows = remember(blocks) { blocks.rows() } // 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 taskOptions = taskBlock?.block?.options as? BlockOptions.TaskList val taskRows = if (taskBlock != null && blockState != null) { - rememberTaskRows(blockState, taskBlock.filter, taskBlock.model, expansionKey = state.view.id) + rememberTaskRows( + blockState, + taskBlock.filter, + taskBlock.model, + onClearCompleted = onClearCompleted.takeIf { blockState.clearableCompleted().isNotEmpty() }, + expansionKey = state.view.id, + inlineDone = taskOptions?.inlineDone != false, + ) } else { null } LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues( - top = topPadding, - bottom = bottomPadding, - ), + contentPadding = PaddingValues(bottom = bottomPadding), ) { if (state.scopeListsGone) { item(key = "scope-gone") { @@ -415,405 +473,68 @@ private fun ListsContent( } rows.forEach { row -> val block = row.first() - if (block.id in state.goneSources && block.type !in TILES) { - 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) } + item(key = "row-${block.id}") { + // A full tile stands alone, as the Today hero always has; half ones share a row. + if (row.size == 1 && block.width == BlockWidth.FULL) { + val gap = if (block.type == BlockType.PROGRESS) 0.dp else FloretDensity.tileGap + Tile(block, state, actions, longPress.fillMaxWidth().padding(horizontal = 16.dp).padding(top = gap)) + } else { + HalfRow(row, state, actions, longPress) + } } return@forEach } - val open = { filter: TaskFilter -> onOpenFilter(filter, scopeFor(block)) } - val sections = state.sectionsFor(block) - when (block.type) { - BlockType.PREVIEW -> previewSection(block, state, open, onOpenTask) - BlockType.LISTS -> listsSection( - key = "${block.id}", - options = block.options as BlockOptions.Lists, - allGroups = sections.groups, - anyLists = state.lists.isNotEmpty(), - reordering = reordering == block.id, - onToggleReorder = { reordering = if (reordering == block.id) null else block.id }, - onOpenFilter = open, - onNewList = onNewList, - onReorder = onReorder, - ) - 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 (block.type == BlockType.TASK_LIST) { + if (block.id in state.goneSources) { + item(key = "${block.id}-gone") { BlockBody(block, state, actions, editing = false) } + } else 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, + onOpenTask = actions.openTask, 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.SECTION_HEADING, - BlockType.WEEK_STRIP, - BlockType.RECENTLY_COMPLETED, - -> Unit + return@forEach + } + item(key = "block-${block.id}") { + androidx.compose.foundation.layout.Column(longPress) { + BlockBody( + block = block, + state = state, + actions = actions, + editing = false, + reorderingLists = reordering == block.id, + onToggleReorderLists = { reordering = if (reordering == block.id) null else block.id }, + ) + } } } } } -private val TILES = setOf(BlockType.PROGRESS, BlockType.COUNT_TILE) - -/** 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, Long?) -> Unit, - scopeFor: (Block) -> Long?, - onChooseSource: (Long) -> Unit, -) { +private fun HalfRow(row: List, state: ListsUiState.Content, actions: BlockActions, longPress: Modifier) { Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = FloretDensity.tileGap), + horizontalArrangement = Arrangement.spacedBy(FloretDensity.tileGap), ) { - row.forEach { Tile(it, state, onOpenFilter, scopeFor, onChooseSource, Modifier.weight(1f)) } + row.forEach { Tile(it, state, actions, longPress.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, 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, 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 -> 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 -> 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, - state: ListsUiState.Content, - onOpenFilter: (TaskFilter) -> Unit, - onOpenTask: (Task) -> Unit, -) { - // 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(key = "${block.id}-header") { SectionHeader(sourceLabel(source, state)) } - item(key = "${block.id}-preview") { - UpcomingPreview( - tasks = tasks, - onOpenTask = onOpenTask, - 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.filterNames[source.filterId].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 (!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(key = "$key-header") { - SectionHeader( - text = stringResource(R.string.lists_header), - action = { - ActionButton( - shape = ActionShapes.Reorder, - icon = if (reordering) Icons.Rounded.Check else Icons.Rounded.SwapVert, - contentDescription = stringResource( - if (reordering) R.string.lists_reorder_done else R.string.lists_reorder, - ), - onClick = onToggleReorder, - ) - ActionButton( - shape = ActionShapes.AddList, - morphTo = ActionShapes.AddListPressed, - icon = Icons.Rounded.Add, - contentDescription = stringResource(R.string.list_add), - onClick = onNewList, - ) - }, - ) - } - groups.forEach { group -> - item(key = "$key-acct-${group.accountName}") { AccountHeader(group.accountName) } - if (reordering) { - item(key = "$key-reorder-${group.accountName}") { - ReorderableColumn( - items = group.lists, - keyOf = { it.list.id }, - onReorder = { ordered -> onReorder(ordered.map { it.list.id }) }, - rowHeight = FloretDensity.rowHeight, - ) { overview, position, dragHandle, isDragging -> - GroupedRow( - title = overview.list.name, - position = position, - gapBelow = false, - container = if (isDragging) MaterialTheme.colorScheme.secondaryContainer else null, - leading = { ListColorChip(overview.list.color) }, - trailing = { - Box(modifier = dragHandle.size(48.dp), contentAlignment = Alignment.Center) { - Icon( - Icons.Rounded.DragHandle, - contentDescription = stringResource(R.string.lists_reorder_handle), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - }, - ) - } - } - return@forEach - } - itemsIndexed(group.lists, key = { _, o -> "$key-list-${o.list.id}" }) { index, overview -> - GroupedRow( - title = overview.list.name, - position = positionOf(index, group.lists.size), - leading = { ListColorChip(overview.list.color) }, - trailing = { - if (options.counts && overview.openCount > 0) { - Text( - overview.openCount.toString(), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - }, - onClick = { onOpenFilter(TaskFilter.OfList(overview.list.id)) }, - ) - } - } -} - -/** Each tag on an open task with its count; nothing while there are none. */ -private fun LazyListScope.tagsSection(key: String, tags: List, onOpenFilter: (TaskFilter) -> Unit) { - if (tags.isEmpty()) return - item(key = "$key-tags-header") { SectionHeader(stringResource(R.string.tags_header)) } - itemsIndexed(tags, key = { _, t -> "$key-tag-${t.tag}" }) { index, overview -> - GroupedRow( - title = overview.tag, - position = positionOf(index, tags.size), - leading = { - Icon( - Icons.Rounded.Sell, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - trailing = { - Text( - overview.openCount.toString(), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - onClick = { onOpenFilter(TaskFilter.Tagged(overview.tag)) }, - ) - } -} - -/** The saved filters, or a single row offering the first one. */ -private fun LazyListScope.filtersSection( - key: String, - filters: List, - onOpenFilter: (TaskFilter) -> Unit, - onNewFilter: () -> Unit, -) { - item(key = "$key-filters-header") { - SectionHeader( - text = stringResource(R.string.filters_header), - action = if (filters.isEmpty()) { - null - } else { - { - ActionButton( - shape = ActionShapes.AddFilter, - morphTo = ActionShapes.AddListPressed, - icon = Icons.Rounded.Add, - contentDescription = stringResource(R.string.filter_new_title), - onClick = onNewFilter, - ) - } - }, - ) - } - if (filters.isEmpty()) { - item(key = "$key-filters-empty") { - GroupedRow( - title = stringResource(R.string.filter_new_title), - summary = stringResource(R.string.filters_empty_hint), - position = Position.Alone, - leading = { Icon(Icons.Rounded.Add, contentDescription = null) }, - onClick = onNewFilter, - ) - } - return - } - itemsIndexed(filters, key = { _, f -> "$key-filter-${f.filter.id}" }) { index, overview -> - GroupedRow( - title = overview.filter.name, - position = positionOf(index, filters.size), - leading = { - Icon( - Icons.Rounded.FilterList, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - trailing = { - Text( - overview.openCount.toString(), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - onClick = { onOpenFilter(TaskFilter.Saved(overview.filter.id)) }, - ) - } -} - -/** No lists at all — a fresh install, where nothing else on this screen works yet. */ -@Composable -private fun EmptyLists(onNewList: () -> Unit) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 32.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - Text( - text = stringResource(R.string.lists_empty), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - FilledTonalButton(onClick = onNewList) { - Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.lists_empty_action)) - } - } -} - -/** - * 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. + * The home top bar: the view switcher at the start, then search, settings and + * the ⋮ menu (*Edit layout*, *Edit view*) at the end. Tapping search unfurls a + * pill to its left (the field grows out from the icon's side, over the + * switcher) while the search icon stays put, so no action moves. */ @Composable private fun HomeTopBar( @@ -823,12 +544,15 @@ private fun HomeTopBar( onSwitchView: (Long) -> Unit, onListsAndFilters: () -> Unit, onManageViews: () -> Unit, + onEditLayout: () -> Unit, + onEditView: () -> Unit, searchActive: Boolean, query: String, onQueryChange: (String) -> Unit, onToggleSearch: () -> Unit, onOpenSettings: () -> Unit, ) { + var menuOpen by remember { mutableStateOf(false) } Surface(color = MaterialTheme.colorScheme.surface) { Row( modifier = Modifier @@ -869,6 +593,33 @@ private fun HomeTopBar( iconSize = 26.dp, spinIcon = true, ) + Box { + ActionButton( + shape = ActionShapes.More, + icon = Icons.Rounded.MoreVert, + contentDescription = stringResource(R.string.more_options), + onClick = { menuOpen = true }, + size = 48.dp, + ) + FloretDropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem( + text = { Text(stringResource(R.string.view_edit_layout)) }, + leadingIcon = { Icon(Icons.Rounded.Dashboard, contentDescription = null) }, + onClick = { + menuOpen = false + onEditLayout() + }, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.view_edit_title)) }, + leadingIcon = { Icon(Icons.Rounded.Tune, contentDescription = null) }, + onClick = { + menuOpen = false + onEditView() + }, + ) + } + } } } } @@ -974,271 +725,10 @@ private fun SearchResults( } } -/** - * The day's momentum: a wavy progress ring over "x of y done" for tasks due today. - * Tapping opens the Today list. When nothing is due today it drops the ring and - * reads as a calm, finished state rather than an empty 0. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -private fun TodayHero( - done: Int, - total: Int, - title: String?, - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - val interaction = remember { MutableInteractionSource() } - val pressed by interaction.collectIsPressedAsState() - val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, reducibleSpec(spring(visibilityThreshold = Dp.VisibilityThreshold)), label = "todayCorner") - val left = total - done - Surface( - onClick = onClick, - shape = RoundedCornerShape(corner), - color = MaterialTheme.colorScheme.primaryContainer, - contentColor = MaterialTheme.colorScheme.onPrimaryContainer, - interactionSource = interaction, - modifier = modifier.height(140.dp), - ) { - Row( - modifier = Modifier.fillMaxSize().padding(20.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Icon(Icons.Rounded.Today, contentDescription = null, modifier = Modifier.size(20.dp)) - Text(title ?: stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium) - } - val headline = when { - total == 0 -> stringResource(R.string.home_today_empty) - left == 0 -> stringResource(R.string.home_today_all_done) - else -> pluralStringResource(R.plurals.home_today_progress_count, total, done, total) - } - Text(headline, style = MaterialTheme.typography.headlineSmall) - if (total > 0 && left > 0) { - Text( - pluralStringResource(R.plurals.home_today_remaining_count, left, left), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f), - ) - } - } - if (total > 0) { - Box(contentAlignment = Alignment.Center, modifier = Modifier.size(84.dp)) { - CircularWavyProgressIndicator( - progress = { done.toFloat() / total }, - modifier = Modifier.fillMaxSize(), - color = MaterialTheme.colorScheme.onPrimaryContainer, - trackColor = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.22f), - wavelength = TodayWavelength, - // A still wave when motion is reduced or the system removed animations (#157). - waveSpeed = if (rememberLoopingMotion()) TodayWavelength else 0.dp, - ) - Text(stringResource(R.string.progress_fraction_compact, done, total), style = MaterialTheme.typography.titleMedium) - } - } - } - } -} - -private val TodayWavelength = WavyProgressIndicatorDefaults.CircularWavelength - -/** A grouped card previewing the next few upcoming tasks, with a "view all" tail. */ -@Composable -private fun UpcomingPreview( - tasks: List, - onOpenTask: (Task) -> Unit, - onViewAll: (() -> Unit)?, -) { - Surface( - shape = RoundedCornerShape(22.dp), - color = MaterialTheme.colorScheme.surfaceContainer, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), - ) { - Column { - tasks.forEach { task -> - UpcomingRow(task = task, onClick = { onOpenTask(task) }) - } - if (onViewAll != null) ViewAllRow(onViewAll) - } - } -} - -@Composable -private fun ViewAllRow(onViewAll: () -> Unit) { - Surface(onClick = onViewAll, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.home_upcoming_view_all), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary, - ) - Spacer(Modifier.weight(1f)) - Icon( - Icons.Rounded.ChevronRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary, - ) - } - } -} - -/** - * One slim upcoming row: list-colour avatar, title, then a quiet meta line of the - * relative due date and (if set) a tinted priority flag — the same calm one-line - * treatment as the task list, minus the swipe machinery. - */ -@Composable -private fun UpcomingRow(task: Task, onClick: () -> Unit) { - val dark = isSystemInDarkTheme() - val muted = MaterialTheme.colorScheme.onSurfaceVariant - val metaStyle = MaterialTheme.typography.bodySmall - Surface(onClick = onClick, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier.fillMaxWidth().heightIn(min = byDensity(60.dp, 52.dp)).padding(horizontal = 16.dp, vertical = FloretDensity.cardRowInset), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - ListColorChip(task.effectiveColor) - Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - task.title, - style = MaterialTheme.typography.bodyLarge, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - upcomingDueLabel(task)?.let { Text(it, style = metaStyle, color = muted) } - if (task.priority != Priority.NONE) { - Text("·", style = metaStyle, color = muted) - Icon( - Icons.Rounded.Flag, - contentDescription = null, - tint = priorityAccent(task.priority, dark), - modifier = Modifier.size(13.dp), - ) - Text(priorityLabel(task.priority), style = metaStyle, color = muted) - } - } - } - } - } -} - -/** "Today" / "Tomorrow" for the near dates, else the compact date. */ -@Composable -private fun upcomingDueLabel(task: Task): String? { - val due = task.shownValue(TaskEnd.DUE) ?: return null - val zone = remember { ZoneId.systemDefault() } - val today = remember { LocalDate.now(zone) } - val dueDate = remember(task) { task.dateOf(TaskEnd.DUE, zone) } - return when (dueDate) { - today -> stringResource(R.string.home_due_today) - today.plusDays(1) -> stringResource(R.string.home_due_tomorrow) - else -> due.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), LocalUse24HourFormat.current) - } -} - -/** 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 tileStyle(source: BlockSource, state: ListsUiState.Content): TileStyle { - val colors = MaterialTheme.colorScheme - 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) - } -} - -/** - * Clean tonal tile. The expressive touch is subtle: rounded corners gently morph - * rounder on press (the same quiet shape behaviour as the lists), not a loud - * silhouette. - */ -@Composable -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, reducibleSpec(spring(visibilityThreshold = Dp.VisibilityThreshold)), label = "smartCorner") - Surface( - onClick = onClick, - shape = RoundedCornerShape(corner), - color = style.container, - contentColor = style.onContainer, - interactionSource = interaction, - modifier = modifier.height(116.dp), - ) { - Column( - modifier = Modifier.fillMaxSize().padding(16.dp), - verticalArrangement = Arrangement.SpaceBetween, - ) { - Icon(style.icon, contentDescription = null) - Column { - Text(count.toString(), style = MaterialTheme.typography.headlineMedium) - Text(style.label, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - } -} - -@Composable -private fun SectionHeader(text: String, action: (@Composable () -> Unit)? = null) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding( - start = 28.dp, - end = if (action == null) 28.dp else 20.dp, - top = if (action == null) 16.dp else 12.dp, - bottom = 4.dp, - ), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - text = text, - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f), - ) - action?.invoke() - } -} - -@Composable -private fun AccountHeader(text: String) { - Text( - text = text, - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp), - ) -} - -@Composable -private fun CenteredMessage(text: String, inner: PaddingValues) { +private fun CenteredMessage(text: String) { Box( - modifier = Modifier.fillMaxSize().padding(inner).padding(32.dp), + modifier = Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center, ) { Text( 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 c54bfae..0436f3b 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 @@ -14,6 +14,16 @@ 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.dueCounts +import de.jeanlucmakiola.agendula.domain.recentlyCompleted +import de.jeanlucmakiola.agendula.domain.reordered +import de.jeanlucmakiola.agendula.domain.replaced +import de.jeanlucmakiola.agendula.domain.resized +import de.jeanlucmakiola.agendula.domain.restored +import de.jeanlucmakiola.agendula.domain.weekDays +import de.jeanlucmakiola.agendula.domain.withBlock +import de.jeanlucmakiola.agendula.domain.without import de.jeanlucmakiola.agendula.domain.RuleClock import de.jeanlucmakiola.agendula.domain.SavedFilter import de.jeanlucmakiola.agendula.domain.SmartList @@ -38,8 +48,11 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import java.time.LocalDate import java.time.ZoneId import javax.inject.Inject import kotlin.time.Clock @@ -101,6 +114,15 @@ 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) +/** A week strip's [days], which of them is [today], and how many open tasks are [due] on each. */ +data class WeekStripDays(val days: List, val today: LocalDate, val due: Map) + +/** A block just removed from view [viewId], from [index], until its undo lapses. */ +data class RemovedBlock(val viewId: Long, val block: Block, val index: Int) + +/** Block [block] of view [viewId] as its settings screen changes it, until saved. */ +data class BlockDraft(val viewId: Long, val block: Block) + /** What the lists, tags and filters blocks show, read through one scope. */ data class HomeSections( val groups: List, @@ -124,6 +146,10 @@ sealed interface ListsUiState { val counts: Map = emptyMap(), /** What each preview block shows, by block id. */ val previews: Map> = emptyMap(), + /** What each recently completed block shows, latest first, by block id. */ + val recent: Map> = emptyMap(), + /** Each week strip's days, by block id. */ + val weeks: 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. */ @@ -187,16 +213,32 @@ internal fun homeContent( val progress = HashMap() val counts = HashMap() val previews = HashMap>() + val recent = HashMap>() + val weeks = HashMap() val gone = HashSet() view.blocks.forEach { block -> + 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 inView(task: Task) = task.listId !in smartHidden && within.admits(task, clock) + when (block.type) { + BlockType.RECENTLY_COMPLETED -> { + val count = (block.options as BlockOptions.RecentlyCompleted).count + recent[block.id] = recentlyCompleted(completedTasks.filter(::inView), count) + return@forEach + } + BlockType.WEEK_STRIP -> { + val days = weekDays(clock.today, clock.weekStart) + weeks[block.id] = WeekStripDays(days, clock.today, dueCounts(openTasks.filter(::inView), days, clock.zone)) + return@forEach + } + else -> Unit + } 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)) { @@ -228,6 +270,8 @@ internal fun homeContent( progress = progress, counts = counts, previews = previews, + recent = recent, + weeks = weeks, goneSources = gone, scopeListsGone = scope.narrowedByGone, scopedSections = if (scope == AppliedScope.None) { @@ -368,18 +412,108 @@ class ListsViewModel @Inject constructor( val viewSaveFailed: StateFlow = _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 { - // Read and written in one go, so nothing changed since the picker opened is lost. + fun chooseSource(viewId: Long, blockId: Long, source: BlockSource) = + editBlocks(viewId) { blocks -> blocks.map { if (it.id == blockId) it.copy(source = source) else it } } + + /** + * Changes the blocks of view [viewId] by [transform], read and written in one + * go so nothing changed meanwhile is lost; says so when they can't be stored. + */ + private fun editBlocks(viewId: Long, transform: (List) -> List) = viewModelScope.launch { + if (!settingsPrefs.updateView(viewId) { it.copy(blocks = transform(it.blocks)) }) flagSaveFailed() + } + + private suspend fun flagSaveFailed() { + _viewSaveFailed.value = true + delay(4_000) + _viewSaveFailed.value = false + } + + /** Whether home shows the active view's blocks to rearrange. */ + val editingLayout: StateFlow = session.editingLayout + + fun editLayout(viewId: Long) = session.editLayout(viewId) + + /** Opens the layout of the view shown now; for a gesture that may outlive a switch of view. */ + fun editShownLayout() { + (state.value as? ListsUiState.Content)?.view?.id?.let(session::editLayout) + } + + fun stopEditingLayout() { + session.stopEditingLayout() + _blockDraft.value = null + } + + /** + * Adds a [type] block reading [source] to view [viewId], before its task list. + * A section heading opens its settings straight away, to be given its text. + */ + fun addBlock(viewId: Long, type: BlockType, source: BlockSource?) = viewModelScope.launch { + var added: Block? = null val written = settingsPrefs.updateView(viewId) { view -> - view.copy(blocks = view.blocks.map { if (it.id == blockId) it.copy(source = source) else it }) + val blocks = view.blocks.withBlock(type, source) + added = blocks.firstOrNull { block -> view.blocks.none { it.id == block.id } } + view.copy(blocks = blocks) } - if (!written) { - _viewSaveFailed.value = true + if (!written) return@launch flagSaveFailed() + val block = added + if (block != null && type == BlockType.SECTION_HEADING) _blockDraft.value = BlockDraft(viewId, block) + } + + /** Puts the blocks of view [viewId] in the order of [ids]. */ + fun moveBlocks(viewId: Long, ids: List) = editBlocks(viewId) { it.reordered(ids) } + + fun resizeBlock(viewId: Long, blockId: Long, width: BlockWidth) = editBlocks(viewId) { it.resized(blockId, width) } + + private val _removed = MutableStateFlow(null) + + /** The block just removed, while its removal can be undone. */ + val removed: StateFlow = _removed.asStateFlow() + private var removedTimer: Job? = null + + /** Removes [block] from view [viewId], with a moment to undo it. */ + fun removeBlock(viewId: Long, block: Block) { + val view = (state.value as? ListsUiState.Content)?.views?.firstOrNull { it.id == viewId } ?: return + val index = view.blocks.indexOfFirst { it.id == block.id }.takeIf { it >= 0 } ?: return + if (_blockDraft.value?.block?.id == block.id) _blockDraft.value = null + editBlocks(viewId) { it.without(block.id) } + _removed.value = RemovedBlock(viewId, block, index) + removedTimer?.cancel() + removedTimer = viewModelScope.launch { delay(4_000) - _viewSaveFailed.value = false + _removed.value = null } } + fun undoRemove() { + val removed = _removed.value ?: return + removedTimer?.cancel() + _removed.value = null + editBlocks(removed.viewId) { it.restored(removed.block, removed.index) } + } + + private val _blockDraft = MutableStateFlow(null) + + /** The block whose settings are open, as changed so far; `null` while none is. */ + val blockDraft: StateFlow = _blockDraft.asStateFlow() + + fun editBlock(viewId: Long, block: Block) { + _blockDraft.value = BlockDraft(viewId, block) + } + + fun updateDraft(transform: (Block) -> Block) = _blockDraft.update { it?.copy(block = transform(it.block)) } + + /** Stores the open block's settings over the block as it is stored now, and closes them. */ + fun saveDraft() { + val draft = _blockDraft.value ?: return + _blockDraft.value = null + editBlocks(draft.viewId) { it.replaced(draft.block) } + } + + fun closeDraft() { + _blockDraft.value = null + } + private val _writeFailure = MutableStateFlow(null) /** Set when a list write is refused; the screen shows it and clears it. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/LongPressToEdit.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/LongPressToEdit.kt new file mode 100644 index 0000000..ccc1316 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/LongPressToEdit.kt @@ -0,0 +1,39 @@ +package de.jeanlucmakiola.agendula.ui.lists + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.ui.Modifier +import androidx.compose.ui.hapticfeedback.HapticFeedback +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput + +/** + * Calls [onLongPress] when the finger rests on this element for a long press, + * whatever inside it takes taps: it watches before the content does, and once + * it fires the rest of the press is its own, so nothing inside clicks or + * scrolls. Moving past the touch slop first leaves the press to the content. + */ +internal fun Modifier.onLongPressOver(haptics: HapticFeedback, onLongPress: () -> Unit): Modifier = + pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + val slop = viewConfiguration.touchSlop + val ended = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) { + var over = false + while (!over) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } + over = change == null || !change.pressed || change.isConsumed || + (change.position - down.position).getDistance() > slop + } + true + } + if (ended != null) return@awaitEachGesture + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + onLongPress() + do { + val event = awaitPointerEvent(PointerEventPass.Initial) + event.changes.forEach { it.consume() } + } while (event.changes.any { it.pressed }) + } + } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt index f3f6f10..d69317b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt @@ -145,7 +145,7 @@ fun EditViewScreen( if (choosingIcon && view != null) { ViewIconPicker( current = view.icon, - onSelect = viewModel::setIcon, + onSelect = { icon -> icon?.let(viewModel::setIcon) }, onDismiss = { choosingIcon = false }, ) } @@ -170,11 +170,31 @@ fun EditViewScreen( /** 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. */ +/** + * The curated view icons in a full-screen grid; picking one closes it. With + * [automatic] a row on top picks none, for a tile that takes its source's icon. + */ @OptIn(ExperimentalLayoutApi::class) @Composable -private fun ViewIconPicker(current: ViewIcon, onSelect: (ViewIcon) -> Unit, onDismiss: () -> Unit) { +internal fun ViewIconPicker( + current: ViewIcon?, + onSelect: (ViewIcon?) -> Unit, + onDismiss: () -> Unit, + automatic: Boolean = false, +) { FullScreenPicker(title = stringResource(R.string.view_icon_title), onDismiss = onDismiss) { + if (automatic) { + Spacer(Modifier.height(8.dp)) + GroupedRow( + title = stringResource(R.string.block_automatic), + position = Position.Alone, + checked = current == null, + onClick = { + onSelect(null) + 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)) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt index d9fd2d6..8aa1b4e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt @@ -44,6 +44,21 @@ class ViewSession @Inject constructor( appScope.launch { prefs.setActiveView(viewId) } } + private val _editingLayout = MutableStateFlow(false) + + /** Home shows its blocks to rearrange, until [stopEditingLayout]. Held here so a rotation keeps it. */ + val editingLayout: StateFlow = _editingLayout.asStateFlow() + + /** Shows view [viewId] with its layout open for editing. */ + fun editLayout(viewId: Long) { + switchTo(viewId) + _editingLayout.value = true + } + + fun stopEditingLayout() { + _editingLayout.value = false + } + private val _startPush = MutableStateFlow(null) /** diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e19c27c..c81cc47 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1188,6 +1188,89 @@ History Grid Tree + + Edit layout + Done + Add block + Block settings + Drag to move + Move earlier + Move later + Make full width + Make half width + Remove block + Block removed + Tasks + Browse + Layout + Progress + Ring with how much is done + Count tile + One number, half or full width + Preview + The next 3, 5 or 10 tasks + Recently completed + What you finished, with undo + Week strip + This week with due dots + Task list + Every task, always at the bottom + This view has one already + Your lists by account + Every tag with counts + Your saved filters + Section heading + A title to group blocks + Show tasks from + Custom rules + Nothing to show right now + Nothing completed yet + No text yet + + Tasks from %1$s + Shows tasks outside this view + This week + + + %1$s, %2$d task due + %1$s, %2$d tasks due + + + Done %1$s + + %1$d of %2$d + Title + Text + Heading + Tasks + Source + Options + Look + View scope + How many + “View all” link + Opens the full list + Check off here + Tap the box to complete a task + Ignore view scope + + Also show tasks outside “%1$s” + Moving wave + The ring’s wave moves, unless motion is reduced + Colour + Icon + Automatic + Primary + Secondary + Tertiary + Alert + As set for the app + Completed tasks + In their own section at the end + Accounts + All accounts + Counts + Open tasks next to each list Start screen Last used view 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 6f420b3..25178ba 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 @@ -159,4 +159,37 @@ class HomePreviewsTest { assertThat(content(scoped(Rule.InList(setOf(1L, 2L)))).newTaskList).isNull() assertThat(content(scoped(Rule.Not(Rule.InList(setOf(9L))))).scopeListsGone).isFalse() } + + @Test + fun `recently completed shows the view's completed tasks, latest first, unless it ignores the scope`() { + fun done(id: Long, listId: Long, minutes: Long) = testTask( + id = id, + listId = listId, + status = TaskStatus.COMPLETED, + completedAt = startOfDay(today, zone) + kotlin.time.Duration.parse("${minutes}m"), + ) + val completed = listOf(done(30, 1, 10), done(31, 2, 30), done(32, 1, 20), done(33, 1, 5)) + val blocks = listOf( + Block(1, BlockType.RECENTLY_COMPLETED), + Block(2, BlockType.RECENTLY_COMPLETED, ignoreScope = true, options = BlockOptions.RecentlyCompleted(count = 5)), + ) + val state = homeContent( + scoped(Rule.InList(setOf(1L)), blocks), listOf(View.home()), listOf(work, home), + openTasks = emptyList(), completedTasks = completed, hidden = emptySet(), + savedFilters = emptyList(), clock = clock, upcomingEnd = null, + ) + assertThat(state.recent.getValue(1L).map { it.taskId }).containsExactly(32L, 30L, 33L).inOrder() + assertThat(state.recent.getValue(2L).map { it.taskId }).containsExactly(31L, 32L, 30L, 33L).inOrder() + } + + @Test + fun `the week strip counts the open tasks due on each day of the week, in the scope`() { + val view = scoped(Rule.InList(setOf(1L)), listOf(Block(1, BlockType.WEEK_STRIP))) + val week = content(view).weeks.getValue(1L) + assertThat(week.today).isEqualTo(today) + assertThat(week.days.first()).isEqualTo(LocalDate.of(2026, 11, 23)) + assertThat(week.days.last()).isEqualTo(LocalDate.of(2026, 11, 29)) + // Today's work task, then the even upcoming ones (list 1) due by Sunday. + assertThat(week.due).containsExactly(today, 1, today.plusDays(2), 1) + } }