@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package com.cottondb.android.ui.day.mood import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll 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.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField 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.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.cottondb.android.day.mood.MoodByline import com.cottondb.android.day.mood.MoodDraft import com.cottondb.android.day.mood.MoodEdit import com.cottondb.android.day.mood.MoodEmotion import com.cottondb.android.day.mood.MoodMoment import com.cottondb.android.day.mood.MoodMutation import com.cottondb.android.day.mood.MoodRead import com.cottondb.android.day.mood.MoodRepository 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 kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import java.time.Clock import java.time.Instant import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale /** The `/mood` timeline. `localDay` and `today` come from the core read unchanged. */ @Composable fun MoodScreen(repository: MoodRepository, clock: Clock, dataRevision: Long, onBack: () -> Unit) { val scope = rememberCoroutineScope() var read by remember(repository) { mutableStateOf(null) } var loading by remember(repository) { mutableStateOf(true) } var failure by remember(repository) { mutableStateOf(null) } var notice by remember { mutableStateOf(null) } var words by remember { mutableStateOf("") } var chosen by remember { mutableStateOf>(emptyList()) } var editing by remember { mutableStateOf(null) } var saving by remember { mutableStateOf(false) } suspend fun reload() { loading = read == null try { read = repository.read(clock.millis()) failure = null } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { failure = error.message ?: "Your moments could not be read." } finally { loading = false } } // A fold invalidation rereads the timeline only. It deliberately leaves an // unsent composer draft, selected chips, and a write failure notice alone. LaunchedEffect(repository, dataRevision) { reload() } MoodGround { Column(Modifier.fillMaxSize()) { MoodTopBar(onBack = onBack, onRefresh = { scope.launch { reload() } }) MoodComposer( words = words, chosen = chosen, enabled = !saving, onWords = { words = it }, onToggle = { emotion -> chosen = toggle(chosen, emotion) }, onSend = { val line = words.trim() if (!saving && (line.isNotEmpty() || chosen.isNotEmpty())) { val sentWords = words saving = true words = "" scope.launch { try { when (val result = repository.record(MoodDraft(chosen, clock.zone.id, line.ifBlank { null }))) { MoodMutation.Success -> { chosen = emptyList() reload() } is MoodMutation.Failure -> { if (words.isBlank()) words = sentWords notice = result.message } } } finally { saving = false } } } }, ) when { loading && read == null -> MoodLoading() read == null -> MoodUnreadable(failure ?: "Your moments could not be read.") { scope.launch { reload() } } else -> MoodTimeline( read = read!!, clock = clock, failure = failure, onRetry = { scope.launch { reload() } }, onEdit = { editing = it }, ) } } } editing?.let { moment -> MoodEditSheet( moment = moment, clock = clock, saving = saving, onDismiss = { if (!saving) editing = null }, onSave = { edit -> if (!saving) { saving = true scope.launch { try { when (val result = repository.update(moment.id, edit)) { MoodMutation.Success -> { editing = null; reload() } is MoodMutation.Failure -> notice = result.message } } finally { saving = false } } } }, onRemove = { if (!saving) { saving = true scope.launch { try { when (val result = repository.remove(moment.id)) { MoodMutation.Success -> { editing = null; reload() } is MoodMutation.Failure -> notice = result.message } } finally { saving = false } } } }, ) } notice?.let { message -> MoodNotice(message) { notice = null } } } @Composable private fun MoodGround(content: @Composable () -> Unit) = Box( Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().imePadding(), contentAlignment = Alignment.TopCenter, ) { content() } @Composable private fun MoodTopBar(onBack: () -> Unit, onRefresh: () -> Unit) = Row( Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { Text("Back", Modifier.clickable(role = Role.Button, onClick = onBack).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) Text("Mood", Modifier.weight(1f), style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, textAlign = TextAlign.Center) Text("Refresh", Modifier.clickable(role = Role.Button, onClick = onRefresh).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.accent) } @Composable private fun MoodComposer( words: String, chosen: List, enabled: Boolean, onWords: (String) -> Unit, onToggle: (MoodEmotion) -> Unit, onSend: () -> Unit, ) = Column(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(10.dp)) { Row(verticalAlignment = Alignment.Bottom) { OutlinedTextField( value = words, onValueChange = { if (it.length <= 1000) onWords(it) }, enabled = enabled, modifier = Modifier.weight(1f), placeholder = { Text("How are you going?") }, textStyle = CottonTextStyles.body, maxLines = 4, ) Text( "Save", Modifier.padding(start = 12.dp, bottom = 12.dp).clickable( enabled = enabled && (words.isNotBlank() || chosen.isNotEmpty()), role = Role.Button, onClick = onSend, ).semantics { contentDescription = "Record mood moment" }, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type), color = if (enabled && (words.isNotBlank() || chosen.isNotEmpty())) CottonPalette.accent else CottonPalette.inkTertiary, ) } Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { MoodEmotion.entries.forEach { emotion -> MoodChip(emotion, emotion in chosen, enabled) { onToggle(emotion) } } } } @Composable private fun MoodChip(emotion: MoodEmotion, selected: Boolean, enabled: Boolean, onClick: () -> Unit) = Text( emotion.wire, Modifier.shadow(if (selected) 3.dp else 0.dp, RoundedCornerShape(18.dp)) .background(if (selected) CottonPalette.groundElevated else CottonPalette.chipGround, RoundedCornerShape(18.dp)) .clickable(enabled = enabled, role = Role.Checkbox, onClick = onClick) .semantics { contentDescription = "${emotion.wire}, ${if (selected) "selected" else "not selected"}" } .padding(horizontal = 12.dp, vertical = 8.dp), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = if (selected) CottonPalette.ink else CottonPalette.inkSecondary, ) @Composable private fun MoodTimeline(read: MoodRead, clock: Clock, failure: String?, onRetry: () -> Unit, onEdit: (MoodMoment) -> Unit) = LazyColumn( Modifier.fillMaxSize(), contentPadding = PaddingValues(CottonMetrics.contentMargin, 22.dp, CottonMetrics.contentMargin, 36.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { failure?.let { message -> item { MoodRefreshNotice(message, onRetry) } } val grouped = read.moments.groupBy(MoodMoment::localDay).toSortedMap(compareByDescending { it }) if (grouped.isEmpty()) { item { MoodEmpty() } } else grouped.forEach { (day, moments) -> item { MoodDayHeading(dayHeading(day, read.today, clock), moments.size) } items(moments.sortedByDescending(::instantForSort), key = MoodMoment::id) { moment -> MoodSlip(moment, clock) { onEdit(moment) } } } } @Composable private fun MoodDayHeading(title: String, count: Int) = Row(Modifier.fillMaxWidth().padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) { Text(title, Modifier.weight(1f), style = CottonTextStyles.sectionLabel.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) if (count > 1) Text(count.toString(), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } @Composable private fun MoodSlip(moment: MoodMoment, clock: Clock, onClick: () -> Unit) = Column( Modifier.fillMaxWidth().shadow(2.dp, RoundedCornerShape(CottonMetrics.cardRadius)) .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)) .clickable(role = Role.Button, onClick = onClick) .semantics { contentDescription = moodMomentDescription(moment, clock) } .padding(18.dp), verticalArrangement = Arrangement.spacedBy(7.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.Top) { if (moment.emotions.isNotEmpty()) Text(moment.emotions.joinToString(" · ") { it.wire }, Modifier.weight(1f), style = CottonTextStyles.body, color = CottonPalette.ink) else Spacer(Modifier.weight(1f)) Text(houseTime(moment.at, clock), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } moment.line?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.body, color = CottonPalette.inkBody) } if (moment.emotionsBy == MoodByline.Assistant && moment.emotions.isNotEmpty()) { Text("named by the assistant", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } } @Composable private fun MoodEditSheet(moment: MoodMoment, clock: Clock, saving: Boolean, onDismiss: () -> Unit, onSave: (MoodEdit) -> Unit, onRemove: () -> Unit) { var line by remember(moment.id) { mutableStateOf(moment.line.orEmpty()) } var selected by remember(moment.id) { mutableStateOf(moment.emotions) } val valid = line.isNotBlank() || selected.isNotEmpty() ModalBottomSheet(onDismissRequest = onDismiss, containerColor = CottonPalette.ground) { Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { Text("This moment", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Text("${weekdayDate(moment.at, clock)} · ${houseTime(moment.at, clock)}", style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) OutlinedTextField(value = line, onValueChange = { if (it.length <= 1000) line = it }, enabled = !saving, modifier = Modifier.fillMaxWidth(), placeholder = { Text("What was it like?") }, minLines = 3, maxLines = 10) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { MoodEmotion.entries.chunked(3).forEach { row -> Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { row.forEach { emotion -> MoodChip(emotion, emotion in selected, !saving) { selected = toggle(selected, emotion) } } } } } if (moment.emotionsBy == MoodByline.Assistant && moment.emotions.isNotEmpty()) Text("The assistant named these. Saving makes them yours.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text("Remove", Modifier.clickable(enabled = !saving, role = Role.Button, onClick = onRemove).padding(8.dp), style = CottonTextStyles.body, color = CottonPalette.statusError) Spacer(Modifier.weight(1f)) Text("Save", Modifier.clickable(enabled = !saving && valid, role = Role.Button, onClick = { onSave(MoodEdit(selected, line.trim().ifBlank { null })) }).padding(8.dp), style = CottonTextStyles.body, color = if (!saving && valid) CottonPalette.accent else CottonPalette.inkTertiary) } } } } @Composable private fun MoodLoading() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Opening your moments…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) } @Composable private fun MoodUnreadable(message: String, onRetry: () -> Unit) = Column(Modifier.padding(28.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("Your moments could not be read.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink); Text("They are on this phone, and Cotton could not open them.", style = CottonTextStyles.body, color = CottonPalette.inkBody); Text("Try again", Modifier.clickable(role = Role.Button, onClick = onRetry).padding(vertical = 8.dp), style = CottonTextStyles.body, color = CottonPalette.accent); Text(message, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } @Composable private fun MoodRefreshNotice(message: String, onRetry: () -> Unit) = Row(Modifier.fillMaxWidth().background(CottonPalette.chipGround, RoundedCornerShape(CottonMetrics.cardRadius)).padding(12.dp), verticalAlignment = Alignment.CenterVertically) { Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 2, overflow = TextOverflow.Ellipsis); Text("Try again", Modifier.clickable(role = Role.Button, onClick = onRetry).padding(start = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.accent) } @Composable private fun MoodEmpty() = Column(Modifier.fillMaxWidth().padding(top = 36.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("No moments yet.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink); Text("Say how you are going, or tap a feeling.", style = CottonTextStyles.body, color = CottonPalette.inkBody, textAlign = TextAlign.Center) } @Composable private fun MoodNotice(message: String, onDismiss: () -> Unit) = ModalBottomSheet(onDismissRequest = onDismiss, containerColor = CottonPalette.ground) { Column(Modifier.fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { Text(message, style = CottonTextStyles.body, color = CottonPalette.ink); Text("OK", Modifier.clickable(role = Role.Button, onClick = onDismiss).padding(8.dp), style = CottonTextStyles.body, color = CottonPalette.accent) } } private fun toggle(chosen: List, emotion: MoodEmotion): List = MoodEmotion.entries.filter { candidate -> if (candidate == emotion) candidate !in chosen else candidate in chosen } private fun instantForSort(moment: MoodMoment): Long = runCatching { Instant.parse(moment.at).toEpochMilli() }.getOrDefault(Long.MIN_VALUE) private fun houseTime(at: String, clock: Clock): String = runCatching { Instant.parse(at).atZone(clock.zone).format(DateTimeFormatter.ofPattern("h:mm a", Locale.US)) }.getOrDefault("") private fun weekdayDate(at: String, clock: Clock): String = runCatching { Instant.parse(at).atZone(clock.zone).format(DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.US)) }.getOrDefault("") private fun dayHeading(day: String, today: String, clock: Clock): String = runCatching { when { day == today -> "Today" day == LocalDate.parse(today).minusDays(1).toString() -> "Yesterday" else -> { val parsed = LocalDate.parse(day) val pattern = if (parsed.year == LocalDate.now(clock).year) "EEEE d MMMM" else "EEEE d MMMM yyyy" parsed.format(DateTimeFormatter.ofPattern(pattern, Locale.US)) } } }.getOrDefault(day) private fun moodMomentDescription(moment: MoodMoment, clock: Clock): String = listOfNotNull(moment.emotions.takeIf { it.isNotEmpty() }?.joinToString { it.wire }, moment.line, houseTime(moment.at, clock)).joinToString(". ")