310 lines · 19.2 KB · KotlinRaw
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)package com.cottondb.android.ui.day.moodimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.horizontalScrollimport 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.imePaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.OutlinedTextFieldimport 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.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.day.mood.MoodBylineimport com.cottondb.android.day.mood.MoodDraftimport com.cottondb.android.day.mood.MoodEditimport com.cottondb.android.day.mood.MoodEmotionimport com.cottondb.android.day.mood.MoodMomentimport com.cottondb.android.day.mood.MoodMutationimport com.cottondb.android.day.mood.MoodReadimport com.cottondb.android.day.mood.MoodRepositoryimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.launchimport java.time.Clockimport java.time.Instantimport java.time.LocalDateimport java.time.format.DateTimeFormatterimport java.util.Locale/** The `/mood` timeline. `localDay` and `today` come from the core read unchanged. */@Composablefun MoodScreen(repository: MoodRepository, clock: Clock, dataRevision: Long, onBack: () -> Unit) { val scope = rememberCoroutineScope() var read by remember(repository) { mutableStateOf<MoodRead?>(null) } var loading by remember(repository) { mutableStateOf(true) } var failure by remember(repository) { mutableStateOf<String?>(null) } var notice by remember { mutableStateOf<String?>(null) } var words by remember { mutableStateOf("") } var chosen by remember { mutableStateOf<List<MoodEmotion>>(emptyList()) } var editing by remember { mutableStateOf<MoodMoment?>(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<MoodEmotion>, 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<MoodEmotion>, emotion: MoodEmotion): List<MoodEmotion> = 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(". ")