Cotton code
302 lines · 14.3 KB · KotlinRaw
package com.cottondb.android.ui.day.notesimport androidx.activity.compose.BackHandlerimport 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.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.day.notes.EditorStateimport com.cottondb.android.day.notes.JournalPageimport com.cottondb.android.day.notes.JournalStateimport com.cottondb.android.day.notes.NoteEditorModelimport com.cottondb.android.day.notes.NoteFaceimport com.cottondb.android.day.notes.NoteMutationimport com.cottondb.android.day.notes.NotesJournalRepositoryimport com.cottondb.android.day.notes.NotesStateimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.navigation.Routeimport com.cottondb.android.ui.day.todos.PaperGroundimport com.cottondb.android.ui.day.todos.TodoFailureimport com.cottondb.android.ui.day.todos.TodoLoadingPaperimport com.cottondb.android.ui.day.todos.TodoNoticeimport com.cottondb.android.ui.day.todos.TodoTopBarimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.time.LocalDateprivate val NotePaperShape = RoundedCornerShape(CottonMetrics.cardRadius)/** * Route host for the Notes list, one note sheet, and the owner's day journal. * `today` and `nowMs` come from the device host so journal routing and streak * reads use one explicit clock rather than a hidden UTC date. */@Composablefun NotesJournalScreen(    route: Route,    repository: NotesJournalRepository,    today: LocalDate,    nowMs: Long,    timezone: String,    writerScope: CoroutineScope,    editorFor: (key: String, journalDate: String?, id: String?) -> NoteEditorModel,    dataRevision: Long = 0,    onNavigate: (String) -> Unit,    onBack: () -> Unit,    onReplace: (String) -> Unit = onNavigate,) {    when (route) {        Route.Notes -> NotesListScreen(repository, dataRevision, onNavigate, onBack)        is Route.NotesNote -> NoteSheetScreen(            editor = editorFor("note:${route.id}", null, route.id.takeUnless { it == "new" }),            writerScope = writerScope, title = "Note", isJournal = false, onBack = onBack, afterSave = {},        )        Route.Journal, Route.NotesJournalToday -> JournalDayScreen(repository, today, nowMs, timezone, dataRevision, writerScope, editorFor, onNavigate, onBack)        is Route.JournalDate -> {            val day = journalOpening(route.date, today)            if (day == null) {                LaunchedEffect(route) { onReplace("/journal") }            } else {                JournalDayScreen(repository, day, nowMs, timezone, dataRevision, writerScope, editorFor, onNavigate, onBack)            }        }        else -> PaperGround { TodoFailure("${route.template} is not a Notes route.", onBack) }    }}/** A route can name only an actual day at or before [today]. */internal fun journalOpening(requested: String, today: LocalDate): LocalDate? =    runCatching { LocalDate.parse(requested) }.getOrNull()?.takeIf { it.toString() == requested && !it.isAfter(today) }@Composableprivate fun NotesListScreen(repository: NotesJournalRepository, dataRevision: Long, onNavigate: (String) -> Unit, onBack: () -> Unit) {    val state by repository.notes.collectAsState()    val scope = rememberCoroutineScope()    val read = when (state) {        is NotesState.Data -> (state as NotesState.Data).read        is NotesState.Error -> (state as NotesState.Error).last        NotesState.Loading -> null    }    LaunchedEffect(repository, dataRevision) { repository.refreshNotes() }    PaperGround {        Column(Modifier.fillMaxSize()) {            TodoTopBar("Notes", onBack, { scope.launch { repository.refreshNotes() } }, { onNavigate("/notes/note/new") })            when {                state is NotesState.Loading && read == null -> TodoLoadingPaper()                state is NotesState.Error && read == null -> TodoFailure((state as NotesState.Error).message) { scope.launch { repository.refreshNotes() } }                else -> LazyColumn(                    Modifier.weight(1f),                    contentPadding = PaddingValues(CottonMetrics.contentMargin, 12.dp, CottonMetrics.contentMargin, 40.dp),                    verticalArrangement = Arrangement.spacedBy(12.dp),                ) {                    if (state is NotesState.Error) item { TodoNotice((state as NotesState.Error).message) }                    if (read!!.notes.isEmpty()) item { NotesEmpty { onNavigate("/notes/note/new") } }                    items(read.notes, key = NoteFace::id) { note ->                        NoteCard(note) { onNavigate("/notes/note/${note.id}") }                    }                }            }        }    }}@Composableprivate fun NotesEmpty(onCreate: () -> Unit) = Column(    Modifier.fillMaxWidth().padding(top = 56.dp), horizontalAlignment = Alignment.CenterHorizontally,) {    Text("No notes yet.", style = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink)    Text("Everything you write saves as you go.", Modifier.padding(top = 10.dp).clickable(onClick = onCreate), style = CottonTextStyles.caption, color = CottonPalette.accent)}@Composableprivate fun NoteCard(note: NoteFace, onOpen: () -> Unit) = Column(    Modifier.fillMaxWidth().background(CottonPalette.groundElevated, NotePaperShape).clickable(onClick = onOpen).padding(18.dp),) {    Text(note.title?.takeIf(String::isNotBlank) ?: "Untitled", style = CottonTextStyles.editorTitle.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink, maxLines = 2, overflow = TextOverflow.Ellipsis)    note.body?.takeIf(String::isNotBlank)?.let { Text(it, Modifier.padding(top = 7.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary, maxLines = 3, overflow = TextOverflow.Ellipsis) }    note.updatedAt?.let { Text(it.take(10), Modifier.padding(top = 12.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) }}@Composableprivate fun JournalDayScreen(    repository: NotesJournalRepository,    day: LocalDate,    nowMs: Long,    timezone: String,    dataRevision: Long,    writerScope: CoroutineScope,    editorFor: (key: String, journalDate: String?, id: String?) -> NoteEditorModel,    onNavigate: (String) -> Unit,    onBack: () -> Unit,) {    val state by repository.journal.collectAsState()    val scope = rememberCoroutineScope()    val read = when (state) {        is JournalState.Data -> (state as JournalState.Data).read        is JournalState.Error -> (state as JournalState.Error).last        JournalState.Loading -> null    }    LaunchedEffect(repository, nowMs, timezone, dataRevision) { repository.refreshJournal(nowMs, timezone) }    when {        state is JournalState.Loading && read == null -> PaperGround { TodoLoadingPaper() }        state is JournalState.Error && read == null -> PaperGround { TodoFailure((state as JournalState.Error).message) { scope.launch { repository.refreshJournal(nowMs, timezone) } } }        else -> {            val existing = read!!.pages.firstOrNull { it.journalDate == day.toString() }            val editor = editorFor("journal:$day", day.toString(), existing?.id)            NoteSheetScreen(                editor = editor,                writerScope = writerScope,                title = day.toString(),                isJournal = true,                suppliedJournalId = existing?.id,                onBack = onBack,                afterSave = { repository.refreshJournal(nowMs, timezone) },                earlierPages = read.pages.filter { (it.journalDate ?: "") < day.toString() },                onOpenDay = { onNavigate("/journal/$it") },                banner = (state as? JournalState.Error)?.message,            )        }    }}@Composableprivate fun NoteSheetScreen(    editor: NoteEditorModel,    writerScope: CoroutineScope,    title: String,    isJournal: Boolean,    suppliedJournalId: String? = null,    onBack: () -> Unit,    afterSave: suspend () -> Unit,    earlierPages: List<JournalPage> = emptyList(),    onOpenDay: (String) -> Unit = {},    banner: String? = null,) {    val state by editor.state.collectAsState()    val draft by editor.draft.collectAsState()    val scope = rememberCoroutineScope()    LaunchedEffect(editor, suppliedJournalId) {        if (isJournal && suppliedJournalId != null) editor.adoptJournalPage(suppliedJournalId) else editor.load()    }    val record = (state as? EditorState.Editing)?.record    val refusal = when (state) {        is EditorState.Error -> (state as EditorState.Error).message        is EditorState.Editing -> (state as EditorState.Editing).error        else -> null    }    val readOnly = record?.managedBy != null    val projectJournal = isJournal && record?.projectId != null    val latestReadOnly by rememberUpdatedState(readOnly)    DisposableEffect(editor, writerScope) {        onDispose {            if (!latestReadOnly) editor.flushPending(writerScope)        }    }    fun leave() {        scope.launch {            if (readOnly) {                onBack()            } else if (editor.flushPending(writerScope)?.await() !is NoteMutation.Failure) {                afterSave()                onBack()            }        }    }    BackHandler(onBack = ::leave)    PaperGround {        Column(Modifier.fillMaxSize()) {            TodoTopBar(title, ::leave, { scope.launch { editor.load() } }, null)            when (state) {                EditorState.Resolving -> TodoLoadingPaper()                is EditorState.Gone -> TodoFailure("This note isn't here any more.", onBack)                is EditorState.Error -> TodoFailure((state as EditorState.Error).message) { scope.launch { editor.load() } }                is EditorState.Editing -> NoteEditorPaper(                    journal = isJournal,                    title = draft.title,                    body = draft.body,                    readOnly = readOnly,                    error = refusal ?: banner,                    onTitle = { next -> editor.setDraft(next, draft.body, scope, writerScope) },                    onBody = { next -> editor.setDraft(draft.title, next, scope, writerScope) },                    onSave = {                        scope.launch {                            when (val result = editor.flushPending(writerScope)?.await()) {                                is NoteMutation.Failure -> Unit                                else -> afterSave()                            }                        }                    },                    earlierPages = if (projectJournal) emptyList() else earlierPages,                    onOpenDay = { day ->                        scope.launch {                            if (editor.flushPending(writerScope)?.await() !is NoteMutation.Failure) onOpenDay(day)                        }                    },                )            }        }    }}@Composableprivate fun NoteEditorPaper(    journal: Boolean,    title: String,    body: String,    readOnly: Boolean,    error: String?,    onTitle: (String) -> Unit,    onBody: (String) -> Unit,    onSave: () -> Unit,    earlierPages: List<JournalPage>,    onOpenDay: (String) -> Unit,) = LazyColumn(    Modifier.fillMaxSize(), contentPadding = PaddingValues(CottonMetrics.contentMargin, 10.dp, CottonMetrics.contentMargin, 40.dp), verticalArrangement = Arrangement.spacedBy(16.dp),) {    error?.let { item { TodoNotice(it) } }    item {        Column(Modifier.fillMaxWidth().background(CottonPalette.groundElevated, NotePaperShape).padding(20.dp)) {            if (!journal) OutlinedTextField(title, onTitle, Modifier.fillMaxWidth(), label = { Text("Title") }, readOnly = readOnly, textStyle = CottonTextStyles.editorTitle.copy(fontFamily = CottonFonts.serif))            OutlinedTextField(body, onBody, Modifier.fillMaxWidth().padding(top = if (journal) 0.dp else 14.dp), label = { Text(if (journal) "Write about this day" else "Note") }, readOnly = readOnly, minLines = 10, textStyle = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif))            if (!readOnly) Text("Save", Modifier.padding(top = 14.dp).clickable(onClick = onSave), style = CottonTextStyles.preview, color = CottonPalette.accent)        }    }    if (earlierPages.isNotEmpty()) item { Text("Earlier days", style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink) }    items(earlierPages, key = JournalPage::id) { page ->        Row(Modifier.fillMaxWidth().background(CottonPalette.groundElevated, NotePaperShape).clickable { page.journalDate?.let(onOpenDay) }.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {            Column(Modifier.weight(1f)) {                Text(page.journalDate.orEmpty(), style = CottonTextStyles.preview, color = CottonPalette.ink)                Text(page.body, Modifier.padding(top = 4.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 2, overflow = TextOverflow.Ellipsis)            }            Spacer(Modifier.width(10.dp)); Text("›", style = CottonTextStyles.body, color = CottonPalette.inkSecondary)        }    }}