612 lines · 24.0 KB · KotlinRaw
package com.cottondb.android.ui.day.peopleimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.grid.GridCellsimport androidx.compose.foundation.lazy.grid.LazyVerticalGridimport androidx.compose.foundation.lazy.grid.itemsimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport kotlinx.coroutines.launchimport com.cottondb.android.day.people.PeopleStateimport com.cottondb.android.day.people.PersonCallimport com.cottondb.android.day.people.PersonDetailModelimport com.cottondb.android.day.people.PersonLinkedSectionItemimport com.cottondb.android.day.people.PersonMoneyClaimimport com.cottondb.android.day.people.PersonNoteimport com.cottondb.android.day.people.PersonSectionsimport com.cottondb.android.day.people.PersonTodoimport com.cottondb.android.day.people.documentsimport com.cottondb.android.day.people.eventsimport com.cottondb.android.day.people.photosimport com.cottondb.android.day.people.sectionItemsimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.navigation.Routeimport java.time.Clockimport java.time.Instantimport java.time.LocalDateimport java.time.ZoneIdimport java.time.format.DateTimeFormatterimport 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. */@Composablefun 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, ) } } }}@Composableprivate fun PersonSectionPreviewRows( section: PersonSectionKind, rows: List<PersonSectionRow>, 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. */@Composablefun 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, ) }}@Composableprivate fun PersonSectionLoading(modifier: Modifier) = Column( modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().padding(CottonMetrics.contentMargin),) { Text("Loading this person…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }@Composableprivate 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. */@Composablefun 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), ) } } }}@Composableprivate 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) } }}@Composableprivate fun PersonSectionRows( section: PersonSectionKind, rows: List<PersonSectionRow>, 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) } }}@Composableprivate 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) }}@Composableprivate 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<PersonSectionRow> = 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<String, String?> { 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. */@Composablefun 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. */@Composablefun PersonCallsPreview( personId: String, calls: List<PersonCall>, 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"}