168 lines · 13.4 KB · KotlinRaw
package com.cottondb.android.ui.day.thoughtsimport 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.Rowimport 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.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport 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.unit.dpimport com.cottondb.android.day.thoughts.RoutedRecordimport com.cottondb.android.day.thoughts.Thoughtimport com.cottondb.android.day.thoughts.ThoughtMutationimport com.cottondb.android.day.thoughts.ThoughtReadimport com.cottondb.android.day.thoughts.ThoughtRepositoryimport 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 kotlinx.serialization.json.JsonElementimport java.time.Clockimport java.time.Durationimport java.time.Instant/** * One capture's ledger page. * * `audioUrl` is an object key, never a host path. A future Android playback * seam must first ask `read.mediaPath`, pass an existing local path to the * platform player, and only call `media.ensure` from that explicit detail * seam. This renderer neither fetches bytes nor draws a pretend audio player. * * Swift replaces a settled one-record capture with that record's screen. The * Android record destinations are not all hosted yet, so this bounded port * keeps the ledger page visible; root navigation can add that typed handover * when those destinations exist. */@Composablefun ThoughtDetailScreen(id: String, repository: ThoughtRepository, clock: Clock, dataRevision: Long, onBack: () -> Unit, onNavigate: (String) -> Unit) { val scope = rememberCoroutineScope() var read by remember(id, repository) { mutableStateOf<ThoughtRead?>(null) } var loading by remember(id, repository) { mutableStateOf(true) } var failure by remember(id, repository) { mutableStateOf<String?>(null) } var writing by remember { mutableStateOf(false) } var menu by remember { mutableStateOf(false) } var notice by remember { mutableStateOf<String?>(null) } suspend fun reload() { loading = read == null try { read = repository.read(); failure = null } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { failure = error.message ?: "Couldn't read this capture." } finally { loading = false } } LaunchedEffect(id, repository, dataRevision) { reload() } val thought = read?.thoughts?.firstOrNull { it.id == id } Box(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().imePadding()) { Column(Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin)) { Row(Modifier.fillMaxWidth().padding(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("Capture", Modifier.weight(1f), style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) if (thought != null) Text("More", Modifier.clickable(role = Role.Button, onClick = { menu = true }).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.ink) } when { loading -> ThoughtSkeleton() thought != null -> ThoughtPage(thought, read!!, clock, onNavigate) failure != null -> ThoughtUnreadable(failure!!) { scope.launch { reload() } } else -> ThoughtMissing() } } } if (menu && thought != null) AlertDialog( onDismissRequest = { menu = false }, title = { Text("Capture actions", fontFamily = CottonFonts.display) }, text = { if (thought.routeStatus == "pending") Text("Dismiss this capture", Modifier.fillMaxWidth().clickable(enabled = !writing, role = Role.Button) { if (!writing) { writing = true; menu = false scope.launch { try { when (val result = repository.dismiss(thought.id)) { ThoughtMutation.Success -> reload(); is ThoughtMutation.Failure -> notice = result.message } } finally { writing = false } } } }.padding(vertical = 12.dp), style = CottonTextStyles.body, color = CottonPalette.statusError) else Text("This capture has no further actions.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }, confirmButton = { TextButton(onClick = { menu = false }) { Text("Done") } }, ) notice?.let { message -> AlertDialog(onDismissRequest = { notice = null }, title = { Text("Couldn’t change capture", fontFamily = CottonFonts.display) }, text = { Text(message) }, confirmButton = { TextButton(onClick = { notice = null }) { Text("OK") } }) }}@Composable private fun ThoughtPage(thought: Thought, read: ThoughtRead, clock: Clock, onNavigate: (String) -> Unit) = Column(verticalArrangement = Arrangement.spacedBy(18.dp)) { Column( Modifier.fillMaxWidth().shadow(3.dp, RoundedCornerShape(CottonMetrics.cardRadius)).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(22.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { Text(if (thought.audioUrl.isNullOrBlank()) "THOUGHT" else "THOUGHT · SPOKEN", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary) Text(thought.rawText.orEmpty(), style = CottonTextStyles.body, color = CottonPalette.inkBody) Text("captured ${recordAge(thought.capturedAt, clock)}", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary) if (thought.routeStatus == "dismissed") Text("DROPPED", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.statusError) } ThoughtStoryLine(thought, read) val records = recordsOf(thought) if (records.size > 1) ThoughtBecame(records, read, onNavigate)}@Composable private fun ThoughtStoryLine(thought: Thought, read: ThoughtRead) = Column(Modifier.padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { Text(standing(thought, recordsOf(thought).size), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = if (thought.routeStatus == "pending") CottonPalette.statusError else CottonPalette.inkSecondary) proposalLine(thought)?.let { Text(it, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } thought.sweepNote?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) }}@Composable private fun ThoughtBecame(records: List<RoutedRecord>, read: ThoughtRead, onNavigate: (String) -> Unit) = Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text("What it became · ${records.size}", style = CottonTextStyles.sectionLabel.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Column(Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(horizontal = 18.dp)) { records.forEachIndexed { index, record -> if (index > 0) androidx.compose.material3.HorizontalDivider(color = CottonPalette.hairline) val fact = read.routedFacts[record.id] val personName = fact?.personId?.let { person -> read.people.firstOrNull { it.id == person }?.fullName } val title = if (record.kind == "person_note" && personName != null) "Note on $personName" else kindName(record.kind) Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = { recordPath(record, fact?.personId)?.let(onNavigate) }).semantics { contentDescription = "Open $title" }.padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(title, style = CottonTextStyles.body, color = CottonPalette.ink); fact?.dateIso?.let { Text(dateFact(record.kind, it), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } Text("Open", style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } } }}@Composable private fun ThoughtSkeleton() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { Box(Modifier.fillMaxWidth().padding(top = 36.dp).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(vertical = 110.dp)) }@Composable private fun ThoughtUnreadable(message: String, retry: () -> Unit) = Column(Modifier.padding(top = 40.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("Couldn't read this capture.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink); Text("It is on your database; this device could not read it just now.", style = CottonTextStyles.body, color = CottonPalette.inkBody); Text("Try again", Modifier.clickable(role = Role.Button, onClick = retry).padding(vertical = 8.dp), style = CottonTextStyles.body, color = CottonPalette.accent); Text(message, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) }@Composable private fun ThoughtMissing() = Column(Modifier.padding(top = 40.dp)) { Text("This capture isn't here any more.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink) }private fun recordsOf(thought: Thought): List<RoutedRecord> { if (thought.routedRecords.isNotEmpty()) return thought.routedRecords val routedKind = thought.routedKind val routedId = thought.routedId return if (routedKind != null && routedId != null) { listOf(RoutedRecord(routedKind, routedId)) } else { emptyList() }}private fun standing(thought: Thought, count: Int): String = when { thought.routeStatus == "dismissed" -> "Dismissed — it stays on the record, out of the way."; count > 1 -> "This one became $count records."; thought.routeStatus != "pending" && count == 0 -> "Stayed a thought — nothing was made of it, and nothing needs to be."; else -> "Still waiting to be filed." }private fun proposalLine(thought: Thought): String? = when (thought.routeReason) { "low_confidence" -> proposalKind(thought)?.let { "Could be a $it — file it yourself." } ?: "Cotton could not place this yet."; "no_match" -> "Cotton could not place this yet."; else -> null }private fun proposalKind(thought: Thought): String? = thought.routeProposal?.get("target")?.jsonObjectOrNull()?.get("kind")?.jsonStringOrNull() ?: thought.routeProposal?.get("records")?.jsonArrayOrNull()?.firstOrNull()?.jsonObjectOrNull()?.get("target")?.jsonObjectOrNull()?.get("kind")?.jsonStringOrNull()private fun JsonElement.jsonObjectOrNull() = this as? kotlinx.serialization.json.JsonObjectprivate fun JsonElement.jsonArrayOrNull() = this as? kotlinx.serialization.json.JsonArrayprivate fun JsonElement.jsonStringOrNull() = (this as? kotlinx.serialization.json.JsonPrimitive)?.takeIf { it.isString }?.contentprivate fun kindName(kind: String): String = when (kind) { "todo" -> "Todo"; "event" -> "Event"; "note" -> "Note"; "journal" -> "Journal"; "person_note" -> "Note"; "person" -> "Person"; "location" -> "Location"; "mood" -> "Mood"; "transaction" -> "Transaction"; else -> kind }private fun dateFact(kind: String, iso: String): String = when (kind) { "todo" -> "due $iso"; "event" -> "starts $iso"; "journal" -> "page for $iso"; "mood" -> "felt on $iso"; "transaction" -> "on $iso"; else -> iso }private fun recordPath(record: RoutedRecord, personId: String?): String? = when (record.kind) { "todo" -> "/todos/todo/${record.id}"; "event" -> "/calendar/event/${record.id}"; "note" -> "/notes/note/${record.id}"; "journal" -> "/journal"; "person_note" -> personId?.let { "/people/person/$it" }; "person" -> "/people/person/${record.id}"; "location" -> "/locations/location/${record.id}"; "mood" -> "/mood"; else -> null }private fun recordAge(iso: String?, clock: Clock): String { val instant = iso?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return ""; val minutes = Duration.between(instant, clock.instant()).toMinutes().coerceAtLeast(0); return when { minutes < 1 -> "just now"; minutes < 60 -> "${minutes}m ago"; minutes < 1440 -> "${minutes / 60}h ago"; else -> "${minutes / 1440}d ago" } }