package com.cottondb.android.ui.day.notes import androidx.activity.compose.BackHandler 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.foundation.shape.RoundedCornerShape import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState 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.notes.EditorState import com.cottondb.android.day.notes.JournalPage import com.cottondb.android.day.notes.JournalState import com.cottondb.android.day.notes.NoteEditorModel import com.cottondb.android.day.notes.NoteFace import com.cottondb.android.day.notes.NoteMutation import com.cottondb.android.day.notes.NotesJournalRepository import com.cottondb.android.day.notes.NotesState import com.cottondb.android.design.CottonFonts 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 com.cottondb.android.ui.day.todos.PaperGround import com.cottondb.android.ui.day.todos.TodoFailure import com.cottondb.android.ui.day.todos.TodoLoadingPaper import com.cottondb.android.ui.day.todos.TodoNotice import com.cottondb.android.ui.day.todos.TodoTopBar import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.time.LocalDate private 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. */ @Composable fun 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) } @Composable private 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}") } } } } } } } @Composable private 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) } @Composable private 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) } } @Composable private 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, ) } } } @Composable private fun NoteSheetScreen( editor: NoteEditorModel, writerScope: CoroutineScope, title: String, isJournal: Boolean, suppliedJournalId: String? = null, onBack: () -> Unit, afterSave: suspend () -> Unit, earlierPages: List = 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) } }, ) } } } } @Composable private fun NoteEditorPaper( journal: Boolean, title: String, body: String, readOnly: Boolean, error: String?, onTitle: (String) -> Unit, onBody: (String) -> Unit, onSave: () -> Unit, earlierPages: List, 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) } } }