package com.cottondb.android.ui.day.people import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.items import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import com.cottondb.android.day.people.PeopleState import com.cottondb.android.day.people.PersonCall import com.cottondb.android.day.people.PersonDetailModel import com.cottondb.android.day.people.PersonLinkedSectionItem import com.cottondb.android.day.people.PersonMoneyClaim import com.cottondb.android.day.people.PersonNote import com.cottondb.android.day.people.PersonSections import com.cottondb.android.day.people.PersonTodo import com.cottondb.android.day.people.documents import com.cottondb.android.day.people.events import com.cottondb.android.day.people.photos import com.cottondb.android.day.people.sectionItems 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 java.time.Clock import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale /** A local-only photo renderer. It must never call media.ensure. */ typealias PersonMediaRenderer = @Composable (key: String, description: String, modifier: Modifier) -> Unit /** The section identifiers and order shared by the person page and its full routes. */ enum class PersonSectionKind(val route: String, val label: String, val pageLimit: Int) { Todos("todos", "Todos", 4), Notes("notes", "Notes", 3), Events("events", "Events", 3), Photos("photos", "Photos", 6), Documents("documents", "Documents", 2), Money("money", "Money", 3), Linked("linked", "Also linked", 4), ; companion object { fun fromRoute(route: String): PersonSectionKind? = entries.firstOrNull { it.route == route } } } /** * The abbreviated, read-only sections shown below a person profile. A supplied * [media] may render a local file for a photo; this surface never asks for media. */ @Composable fun PersonSectionsPreview( personId: String, personName: String, sections: PersonSections, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, modifier: Modifier = Modifier, media: PersonMediaRenderer? = null, ) { Column(modifier, verticalArrangement = Arrangement.spacedBy(28.dp)) { PersonSectionKind.entries.forEach { section -> val rows = personRows(section, personId, sections) if (rows.isNotEmpty()) { PersonSectionHeading( label = section.label, shown = rows.size.coerceAtMost(section.pageLimit), total = rows.size, inset = false, onOpenAll = { onNavigate(Route.PeoplePersonSection(personId, section.route).path) }, ) PersonSectionPreviewRows( section = section, rows = rows.take(section.pageLimit), onNavigate = onNavigate, clock = clock, zoneId = zoneId, media = media, ) } } } } @Composable private fun PersonSectionPreviewRows( section: PersonSectionKind, rows: List, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, media: PersonMediaRenderer?, ) { if (section == PersonSectionKind.Photos && media != null) { Column( Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp), ) { rows.chunked(3).forEach { group -> Row( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp), ) { group.forEach { row -> val destination = row.destination Column( Modifier.weight(1f).then( if (destination == null) Modifier else Modifier.clickable( role = Role.Button, onClick = { onNavigate(destination.path) }, ) ).semantics { contentDescription = "Open ${row.title}" }, ) { row.mediaKey?.let { key -> media(key, row.title, Modifier.fillMaxWidth()) } row.title.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.ink) } } } } } } } else { Column { rows.forEach { row -> PersonSectionRowView(row, onNavigate, clock, zoneId, inset = false) } } } } /** * Route host for `/people/person/[id]/[section]`. It refreshes the same retained * person model and renders cached rows during a later read failure. */ @Composable fun PersonSectionRoute( model: PersonDetailModel, sectionRoute: String, dataRevision: Long, onBack: () -> Unit, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, modifier: Modifier = Modifier, media: PersonMediaRenderer? = null, ) { val state by model.state.collectAsState() val scope = rememberCoroutineScope() val cached = when (val shown = state) { is PeopleState.Data -> shown.read is PeopleState.Error -> shown.last PeopleState.Loading -> null } val refresh: () -> Unit = { scope.launch { model.refresh() } } LaunchedEffect(model, dataRevision) { model.refresh() } when { cached?.person != null -> Column(modifier.fillMaxSize()) { (state as? PeopleState.Error)?.let { error -> Row(Modifier.fillMaxWidth().padding(CottonMetrics.contentMargin)) { Text(error.message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError) Text("Try again", Modifier.clickable(role = Role.Button, onClick = refresh).padding(start = 12.dp), style = CottonTextStyles.preview, color = CottonPalette.accent) } } PersonSectionScreen( personId = model.personId, personName = requireNotNull(cached.person).fullName.orEmpty(), sectionRoute = sectionRoute, sections = cached.sections, onBack = onBack, onNavigate = onNavigate, clock = clock, zoneId = zoneId, modifier = Modifier.weight(1f), media = media, ) } state is PeopleState.Loading -> PersonSectionLoading(modifier) else -> PersonSectionFailure( message = (state as? PeopleState.Error)?.message ?: "This person could not be read.", onBack = onBack, onRetry = refresh, modifier = modifier, ) } } @Composable private fun PersonSectionLoading(modifier: Modifier) = Column( modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().padding(CottonMetrics.contentMargin), ) { Text("Loading this person…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) } @Composable private fun PersonSectionFailure(message: String, onBack: () -> Unit, onRetry: () -> Unit, modifier: Modifier) = Column( modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().padding(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(10.dp), ) { Text("This person could not be read", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Text(message, style = CottonTextStyles.body, color = CottonPalette.inkSecondary) Text("Try again", Modifier.clickable(role = Role.Button, onClick = onRetry).padding(vertical = 8.dp), style = CottonTextStyles.preview, color = CottonPalette.accent) Text("Back", Modifier.clickable(role = Role.Button, onClick = onBack).padding(vertical = 8.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } /** `/people/person/[id]/[section]`, rendered from the same single person read. */ @Composable fun PersonSectionScreen( personId: String, personName: String, sectionRoute: String, sections: PersonSections, onBack: () -> Unit, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, modifier: Modifier = Modifier, media: PersonMediaRenderer? = null, ) { val section = PersonSectionKind.fromRoute(sectionRoute) Column( modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding(), ) { Text( "Back", Modifier.padding(CottonMetrics.contentMargin) .clickable(role = Role.Button, onClick = onBack) .semantics { contentDescription = "Back" }, style = CottonTextStyles.preview, color = CottonPalette.inkSecondary, ) Text( section?.label ?: "Linked", Modifier.padding(horizontal = CottonMetrics.contentMargin), style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, ) Text( personName, Modifier.padding(horizontal = CottonMetrics.contentMargin, vertical = 4.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) if (section == null) { PersonSectionEmpty("There is nothing to show here.") } else { val rows = personRows(section, personId, sections) if (rows.isEmpty()) { PersonSectionEmpty(if (section == PersonSectionKind.Money) "Nothing is open between you." else "Nothing here yet.") } else { PersonSectionRows( section = section, rows = rows, onNavigate = onNavigate, clock = clock, zoneId = zoneId, media = media, modifier = Modifier.weight(1f), ) } } } } @Composable private fun PersonSectionHeading( label: String, shown: Int, total: Int, totalLabel: String = total.toString(), inset: Boolean = true, onOpenAll: () -> Unit, ) { Row( Modifier.fillMaxWidth().then(if (inset) Modifier.padding(horizontal = CottonMetrics.contentMargin) else Modifier), horizontalArrangement = Arrangement.SpaceBetween, ) { Text( label, style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, ) val hasMore = shown < total || totalLabel != total.toString() if (hasMore) { Text( "$shown / $totalLabel", Modifier.clickable(role = Role.Button, onClick = onOpenAll) .semantics { contentDescription = "Open all $label" }, style = CottonTextStyles.preview, color = CottonPalette.accent, ) } else { Text(totalLabel, style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } } } @Composable private fun PersonSectionRows( section: PersonSectionKind, rows: List, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, media: PersonMediaRenderer?, modifier: Modifier = Modifier, ) { if (section == PersonSectionKind.Photos && media != null) { LazyVerticalGrid( columns = GridCells.Fixed(3), modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(CottonMetrics.contentMargin), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { items(rows, key = { it.id }) { row -> val destination = row.destination Column( Modifier.then( if (destination == null) Modifier else Modifier.clickable( role = Role.Button, onClick = { onNavigate(destination.path) }, ) ).semantics { contentDescription = "Open ${row.title}" }, ) { row.mediaKey?.let { key -> media(key, row.title, Modifier.fillMaxWidth()) } if (row.title.isNotBlank()) { Text(row.title, style = CottonTextStyles.caption, color = CottonPalette.ink) } row.note?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } } return } LazyColumn(modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(vertical = 8.dp)) { items(rows, key = { it.id }) { row -> PersonSectionRowView(row, onNavigate, clock, zoneId) } } } @Composable private fun PersonSectionRowView( row: PersonSectionRow, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, inset: Boolean = true, ) { val action = row.destination?.let { destination -> Modifier.clickable(role = Role.Button, onClick = { onNavigate(destination.path) }) .semantics { contentDescription = "Open ${row.title}" } } ?: Modifier Column( Modifier.fillMaxWidth().then(action) .then(if (inset) Modifier.padding(horizontal = CottonMetrics.contentMargin) else Modifier) .padding(vertical = 12.dp), ) { Text(row.title, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) row.line?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } row.note?.let { Text(personDate(it, clock, zoneId), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } HorizontalDivider(Modifier.padding(top = 8.dp), color = CottonPalette.hairline) } } @Composable private fun PersonSectionEmpty(message: String) = Text( message, Modifier.padding(CottonMetrics.contentMargin), style = CottonTextStyles.body, color = CottonPalette.inkSecondary, ) private data class PersonSectionRow( val id: String, val title: String, val line: String? = null, val note: String? = null, val destination: Route? = null, val mediaKey: String? = null, ) private fun personRows(section: PersonSectionKind, personId: String, read: PersonSections): List = when (section) { PersonSectionKind.Todos -> read.todos.map { todo -> todo.row() } PersonSectionKind.Notes -> (read.notes.map { it.row() } + read.sectionItems(personId, setOf("note")).map { it.row() }) .sortedByDescending { it.note.orEmpty() } PersonSectionKind.Events -> read.events(personId).map { it.row() }.sortedByDescending { it.note.orEmpty() } PersonSectionKind.Photos -> read.photos(personId).map { it.row() }.sortedByDescending { it.note.orEmpty() } PersonSectionKind.Documents -> read.documents(personId).map { it.row() }.sortedByDescending { it.note.orEmpty() } PersonSectionKind.Money -> read.money.map { it.row() }.sortedBy { it.note.orEmpty() } PersonSectionKind.Linked -> read.links.mapNotNull { link -> val record = link.other(personId) ?: return@mapNotNull null if (record.kind in setOf("todo", "note", "event", "photo", "video", "document")) return@mapNotNull null PersonSectionRow( id = link.id, title = read.linkedFacts[link.id]?.title?.singleLine() ?: record.kind.label(), line = read.linkedFacts[link.id]?.container, note = read.linkedFacts[link.id]?.whenIso, destination = record.route(), ) }.sortedByDescending { it.note.orEmpty() } } private fun PersonTodo.row(): PersonSectionRow = PersonSectionRow( id = id, title = title?.singleLine().orEmpty().ifBlank { "Untitled" }, line = if (recurrenceId == null) null else "Repeats", note = dueAt ?: createdAt, destination = Route.TodosTodo(id), ) private fun PersonNote.row(): PersonSectionRow { val lines = body.orEmpty().lineParts() return PersonSectionRow( id = "person-note:$id", title = lines.first.ifBlank { "Note" }, line = lines.second, note = notedAt ?: createdAt, ) } private fun PersonLinkedSectionItem.row(): PersonSectionRow = PersonSectionRow( id = link.id, title = fact?.title?.singleLine().orEmpty().ifBlank { record.kind.label() }, line = when (record.kind) { "note" -> fact?.body?.lineParts()?.second ?: fact?.body?.lineParts()?.first "document" -> documentLine(fact?.docType, fact?.pageCount) else -> fact?.container }, note = fact?.whenIso, destination = record.route(), mediaKey = when (record.kind) { "photo" -> fact?.key "video" -> fact?.posterKey else -> null }, ) private fun PersonMoneyClaim.row(): PersonSectionRow = PersonSectionRow( id = transactionId, title = description?.singleLine().orEmpty().ifBlank { "Claim" }, line = if (settledMinor > 0) "Part paid" else null, note = dueDate, destination = Route.MoneyTransaction(transactionId), ) private fun PersonLinkedRecordRoute(kind: String, id: String): Route? = when (kind) { "person" -> Route.PeoplePerson(id) "thread" -> Route.MessagesThread(id) "email_thread" -> Route.EmailId(id) "todo" -> Route.TodosTodo(id) "note", "journal" -> Route.NotesNote(id) "thought" -> Route.ThoughtsThought(id) "memory" -> Route.Memory(id) "event" -> Route.CalendarEvent(id, date = null, at = null) "meeting" -> Route.MeetingsMeeting(id) "document" -> Route.DocumentsDocument(id) "page" -> Route.ReaderPage(id) "location" -> Route.LocationsLocation(id) "transaction" -> Route.MoneyTransaction(id) "goal" -> Route.GoalsGoal(id) "photo" -> Route.PhotosPhoto(id) "video" -> Route.VideosVideo(id) "album" -> Route.PhotosAlbum(id) "call" -> Route.CallsCall(id) "secret" -> Route.PasswordsSecret(id) else -> null } private fun com.cottondb.android.day.people.PersonLinkedRecord.route(): Route? = PersonLinkedRecordRoute(kind, id) private fun documentLine(type: String?, pages: Long?): String? = listOfNotNull( type?.singleLine(), pages?.takeIf { it > 0 }?.let { if (it == 1L) "1 page" else "$it pages" }, ).joinToString(" · ").ifBlank { null } private fun String.lineParts(): Pair { val lines = lineSequence().map(String::trim).filter(String::isNotBlank).toList() return lines.firstOrNull()?.take(60).orEmpty() to lines.drop(1).joinToString(" ").ifBlank { null } } private fun String.singleLine(): String = replace(Regex("\\s+"), " ").trim().take(160) private fun String.label(): String = replace('_', ' ').replaceFirstChar { it.titlecase(Locale.ROOT) } private fun personDate(value: String, clock: Clock, zoneId: ZoneId): String = runCatching { Instant.parse(value).atZone(zoneId).toLocalDate() }.recoverCatching { LocalDate.parse(value) }.map { date -> val pattern = if (date.year == LocalDate.now(clock.withZone(zoneId)).year) "d MMM" else "d MMM uuuu" date.format(DateTimeFormatter.ofPattern(pattern, Locale.getDefault())) }.getOrElse { value } /** The message archive strip is fed by [PersonDetailRead.thread], not a duplicate section decoder. */ @Composable fun PersonMessagesPreview( personId: String, personName: String, thread: com.cottondb.android.day.people.PersonThread?, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, modifier: Modifier = Modifier, avatar: (@Composable (personId: String, name: String, modifier: Modifier) -> Unit)? = null, ) { val lead = thread?.let { it.lastMessagePreview ?: it.contactDisplayName ?: it.contactPhoneE164 } ?: return PersonSectionHeading(label = "Messages", shown = 1, total = 1, inset = false) { onNavigate(Route.MessagesThread(thread.id).path) } Row( modifier.fillMaxWidth() .clickable(role = Role.Button, onClick = { onNavigate(Route.MessagesThread(thread.id).path) }) .semantics { contentDescription = "Open messages with ${thread.contactDisplayName ?: personName}" } .padding(vertical = 12.dp), ) { avatar?.invoke(personId, personName, Modifier.padding(end = 12.dp)) Column(Modifier.weight(1f)) { Text( thread.contactDisplayName ?: personName, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, ) Text(lead, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } thread.lastMessageAt?.let { Text(personDate(it, clock, zoneId), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } } } /** The capped person-call read is clearly a preview; its complete history has its own route. */ @Composable fun PersonCallsPreview( personId: String, calls: List, onNavigate: (String) -> Unit, clock: Clock, zoneId: ZoneId, modifier: Modifier = Modifier, ) { if (calls.isEmpty()) return Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { PersonSectionHeading( label = "Calls", shown = calls.size.coerceAtMost(3), total = calls.size, totalLabel = if (calls.size > 5) "${calls.size}+" else calls.size.toString(), inset = false, ) { onNavigate(Route.CallsHistory(personId).path) } calls.take(3).forEach { call -> val title = listOfNotNull(call.direction?.label(), call.outcome?.label()).joinToString(" · ") .ifBlank { "Call" } val line = listOfNotNull(call.durationS.takeIf { it > 0 }?.callDuration(), call.provider?.singleLine()) .joinToString(" · ").ifBlank { null } PersonSectionRowView( PersonSectionRow( id = call.id, title = title, line = line, note = call.startedAt, destination = Route.CallsCall(call.id), ), onNavigate = onNavigate, clock = clock, zoneId = zoneId, inset = false, ) } } } private fun Long.callDuration(): String = when { this < 60L -> "${this}s" this % 60L == 0L -> "${this / 60L}m" else -> "${this / 60L}m ${this % 60L}s" }