package com.cottondb.android.ui.day.todos 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.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.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.cottondb.android.day.todos.CreateTodo import com.cottondb.android.day.todos.Todo import com.cottondb.android.day.todos.TodoDetail import com.cottondb.android.day.todos.TodoDueChange import com.cottondb.android.day.todos.TodoField import com.cottondb.android.day.todos.TodoListState import com.cottondb.android.day.todos.TodoMutationResult import com.cottondb.android.day.todos.TodoPatch import com.cottondb.android.day.todos.TodoPriority import com.cottondb.android.day.todos.TodoProject import com.cottondb.android.day.todos.TodoProjectLink import com.cottondb.android.day.todos.TodoRecurrenceUpdate import com.cottondb.android.day.todos.TodoRepository import com.cottondb.android.day.todos.TodoStatus import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.navigation.Route import kotlinx.coroutines.launch import java.time.LocalDate /** Day Todo route host. The caller owns the navigation stack and one repository per core session. */ @Composable fun TodoScreen( route: Route, repository: TodoRepository, timezone: String, today: LocalDate, onNavigate: (String) -> Unit, onBack: () -> Unit, dataRevision: Long = 0, ) { when (route) { is Route.Todos -> TodoListScreen(repository, TodoListKind.Open, null, route.new, timezone, today, onNavigate, onBack, dataRevision) is Route.TodosDone -> TodoListScreen(repository, TodoListKind.Done, route.project, false, timezone, today, onNavigate, onBack, dataRevision) is Route.TodosDropped -> TodoListScreen(repository, TodoListKind.Dropped, route.project, false, timezone, today, onNavigate, onBack, dataRevision) is Route.ProjectsTodos -> TodoListScreen(repository, TodoListKind.Open, route.slug, false, timezone, today, onNavigate, onBack, dataRevision) is Route.TodosTodo -> TodoDetailScreen(repository, route.id, timezone, today, onBack, dataRevision) else -> TodoRouteMismatch(route.template, onBack) } } internal enum class TodoListKind(val title: String) { Open("Todos"), Done("Done"), Dropped("Dropped") } @Composable private fun TodoListScreen( repository: TodoRepository, kind: TodoListKind, project: String?, startsNew: Boolean, timezone: String, today: LocalDate, onNavigate: (String) -> Unit, onBack: () -> Unit, dataRevision: Long = 0, ) { val state by repository.state.collectAsState() val busy by repository.isMutating.collectAsState() val scope = rememberCoroutineScope() var composer by remember(project, startsNew) { mutableStateOf(startsNew) } var notice by remember { mutableStateOf(null) } LaunchedEffect(repository, project, dataRevision) { repository.refresh(project) } val read = when (state) { is TodoListState.Data -> (state as TodoListState.Data).read; is TodoListState.Error -> (state as TodoListState.Error).last; TodoListState.Loading -> null } val rows = when (kind) { TodoListKind.Open -> read?.todos.orEmpty().filter { it.status == TodoStatus.Open } TodoListKind.Done -> read?.todos.orEmpty().filter { it.status == TodoStatus.Done } TodoListKind.Dropped -> read?.dropped.orEmpty() } PaperGround { Column(Modifier.fillMaxSize()) { TodoTopBar(kind.title, onBack, onRefresh = { scope.launch { repository.refresh(project) } }, onAdd = if (kind == TodoListKind.Open) ({ composer = true }) else null) if (project != null) { Text(read?.projectName ?: "This project's todos", modifier = Modifier.padding(horizontal = CottonMetrics.contentMargin), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } when { state is TodoListState.Loading && read == null -> TodoLoadingPaper() state is TodoListState.Error && read == null -> TodoFailure((state as TodoListState.Error).message) { scope.launch { repository.refresh(project) } } else -> LazyColumn( Modifier.weight(1f), contentPadding = PaddingValues(CottonMetrics.contentMargin, 20.dp, CottonMetrics.contentMargin, 104.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { if (state is TodoListState.Error) item { TodoNotice((state as TodoListState.Error).message) } if (rows.isEmpty()) item { TodoEmpty(kind, project, onAdd = { composer = true }) } items(rows, key = { it.id }) { todo -> TodoPaperRow(todo, timezone, onOpen = { onNavigate("/todos/todo/${todo.id}") }, onToggle = { checked -> scope.launch { when (val result = repository.update(todo.id, TodoPatch(status = if (checked) TodoStatus.Done else TodoStatus.Open))) { is TodoMutationResult.Failure -> notice = result.message is TodoMutationResult.CreatedButUnfiled -> notice = result.message TodoMutationResult.Success -> Unit } } }) } } } TodoBottomRail(kind, project, onNavigate) } } notice?.let { TodoNoticeDialog(it) { notice = null } } if (composer) TodoComposer( projectSlug = project, timezone = timezone, today = today, busy = busy, onDismiss = { composer = false }, onCreate = { title, dueAt -> scope.launch { when (val result = repository.create(CreateTodo(title = title, due = dueAt), project)) { TodoMutationResult.Success -> composer = false is TodoMutationResult.CreatedButUnfiled -> { composer = false; notice = result.message } is TodoMutationResult.Failure -> notice = result.message } } }, ) } @Composable private fun TodoDetailScreen(repository: TodoRepository, id: String, timezone: String, today: LocalDate, onBack: () -> Unit, dataRevision: Long) { val scope = rememberCoroutineScope() val busy by repository.isMutating.collectAsState() var loading by remember(id) { mutableStateOf(true) } var detail by remember(id) { mutableStateOf(null) } var failure by remember(id) { mutableStateOf(null) } var editingDue by remember { mutableStateOf(false) } var projectsOpen by remember { mutableStateOf(false) } var recurrenceOpen by remember { mutableStateOf(false) } var moreOpen by remember { mutableStateOf(false) } var notice by remember { mutableStateOf(null) } suspend fun load() { loading = true try { detail = repository.detail(id); failure = null } catch (error: Throwable) { if (error is kotlinx.coroutines.CancellationException) throw error; failure = error.message ?: "This todo could not be read." } loading = false } LaunchedEffect(repository, id, dataRevision) { load() } val todo = detail?.todo PaperGround { Column(Modifier.fillMaxSize()) { TodoTopBar("Todo", onBack, onRefresh = { scope.launch { load() } }, onAdd = null, onMore = { if (!busy) moreOpen = true }) when { loading -> TodoLoadingPaper() todo == null -> TodoFailure(failure ?: "This todo isn't here any more.") { scope.launch { load() } } else -> TodoDetailPaper( todo = todo, recurrence = detail!!.recurrence, timezone = timezone, busy = busy, onToggle = { checked -> scope.launch { mutateDetail(repository.update(todo.id, TodoPatch(status = if (checked) TodoStatus.Done else TodoStatus.Open)), ::load, { notice = it }) } }, onTitle = { title -> scope.launch { mutateDetail(repository.update(todo.id, TodoPatch(title = title)), ::load, { notice = it }) } }, onNotes = { text -> scope.launch { mutateDetail(repository.update(todo.id, TodoPatch(notes = if (text.trim().isEmpty()) TodoField.Clear else TodoField.Set(text))), ::load, { notice = it }) } }, onDue = { editingDue = true }, onProjects = { projectsOpen = true }, onRecurrence = { recurrenceOpen = true }, ) } } } if (editingDue && todo != null) DueSheet(storedTodoDue(todo.dueAt, timezone), timezone, today, onDismiss = { editingDue = false }) { due -> scope.launch { editingDue = false; mutateDetail(repository.update(todo.id, TodoPatch(due = if (due == null) TodoDueChange.Clear else TodoDueChange.Set(due))), ::load, { notice = it }) } } if (projectsOpen && todo != null && detail != null) ProjectPicker(detail!!.projects, detail!!.projectLinks, busy, onDismiss = { projectsOpen = false }) { project, linked -> scope.launch { val result = if (linked) repository.unlink(project.slug, todo.id) else repository.link(project.slug, todo.id); mutateDetail(result, ::load, { notice = it }) } } if (recurrenceOpen && todo != null) RecurrenceSheet(todo, detail?.recurrence, onDismiss = { recurrenceOpen = false }) { command -> scope.launch { recurrenceOpen = false val result = when (command) { RecurrenceCommand.Stop -> todo.recurrenceId?.let { repository.stopRecurrence(it, todo.id) } ?: TodoMutationResult.Failure("This todo does not repeat.") is RecurrenceCommand.Set -> { val dueAt = todo.dueAt if (dueAt == null) { notice = "A repeating todo needs a due date." return@launch } if (todo.recurrenceId == null) { repository.makeRecurring(todo.id, command.rrule, dueAt, timezone) } else { val rule = detail?.recurrence if (rule == null) { notice = "The repeat rule could not be read." return@launch } val previousRrule = rule.rrule ?: run { notice = "The previous repeat rule could not be read." return@launch } repository.updateRecurrence(TodoRecurrenceUpdate(rule.id, rule.title ?: todo.title.orEmpty(), rule.notes, rule.priority, command.rrule, dueAt, rule.paused, previousRrule, rule.dtstart ?: dueAt, rule.materializedUntil, timezone)) } } } mutateDetail(result, ::load, { notice = it }) } } if (moreOpen && todo != null) TodoMoreSheet(todo, onDismiss = { moreOpen = false }, onPriority = { scope.launch { moreOpen = false; mutateDetail(repository.update(todo.id, TodoPatch(priority = if (todo.priority > 0) TodoPriority.None else TodoPriority.High)), ::load, { notice = it }) } }, onDrop = { scope.launch { moreOpen = false when (val result = repository.update(todo.id, TodoPatch(status = TodoStatus.Dropped))) { TodoMutationResult.Success -> { load(); onBack() } is TodoMutationResult.CreatedButUnfiled -> { load(); notice = result.message } is TodoMutationResult.Failure -> notice = result.message } } }) notice?.let { TodoNoticeDialog(it) { notice = null } } } private suspend fun mutateDetail(result: TodoMutationResult, reload: suspend () -> Unit, report: (String) -> Unit) { when (result) { TodoMutationResult.Success -> reload() is TodoMutationResult.CreatedButUnfiled -> { reload(); report(result.message) } is TodoMutationResult.Failure -> report(result.message) } }