Cotton code
240 lines · 13.1 KB · KotlinRaw
package com.cottondb.android.ui.day.todosimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.runtime.collectAsStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.day.todos.CreateTodoimport com.cottondb.android.day.todos.Todoimport com.cottondb.android.day.todos.TodoDetailimport com.cottondb.android.day.todos.TodoDueChangeimport com.cottondb.android.day.todos.TodoFieldimport com.cottondb.android.day.todos.TodoListStateimport com.cottondb.android.day.todos.TodoMutationResultimport com.cottondb.android.day.todos.TodoPatchimport com.cottondb.android.day.todos.TodoPriorityimport com.cottondb.android.day.todos.TodoProjectimport com.cottondb.android.day.todos.TodoProjectLinkimport com.cottondb.android.day.todos.TodoRecurrenceUpdateimport com.cottondb.android.day.todos.TodoRepositoryimport com.cottondb.android.day.todos.TodoStatusimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.navigation.Routeimport kotlinx.coroutines.launchimport java.time.LocalDate/** Day Todo route host. The caller owns the navigation stack and one repository per core session. */@Composablefun 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") }@Composableprivate 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<String?>(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            }        } },    )}@Composableprivate 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<TodoDetail?>(null) }    var failure by remember(id) { mutableStateOf<String?>(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<String?>(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)    }}