package com.cottondb.android.ui.search 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.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp 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.home.HomeTool import com.cottondb.android.search.SEARCH_SECTION_COLLAPSED import com.cottondb.android.search.SearchHit import com.cottondb.android.search.SearchRead import com.cottondb.android.search.SearchSection import com.cottondb.android.search.SearchState import com.cottondb.android.search.groups import java.time.Clock import java.time.Duration import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale private const val REST_HINT = "Search reaches every word Cotton has read — your notes and documents, the people you know, your messages, your money." private const val FAILED = "That search could not run." private const val FAILED_HINT = "Nothing is wrong with your records — try again." private const val NO_MATCH = "Nothing in your database matches that." private const val NO_MATCH_HINT = "Try a name, a word from inside a note, or a date." /** Stateless host for the retained [SearchState]. Places come from Home's one directory. */ @Composable fun SearchScreen( state: SearchState, places: List, onQueryChange: (String) -> Unit, onBack: () -> Unit, onClearRecents: () -> Unit, onOpenPlace: (String) -> Unit, onOpenHit: (SearchHit) -> Unit, onExpand: (SearchSection) -> Unit, clock: Clock, zoneId: ZoneId, onRetryRecents: () -> Unit = {}, takesFocus: Boolean = false, ) { Column( Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().imePadding(), ) { SearchPill(state.query, onQueryChange, onBack, takesFocus) state.recentsProblem?.let { message -> Row(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin)) { Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError) TextButton(onClick = onRetryRecents) { Text("Retry") } } } SearchResults( state = state, places = places, onQueryChange = onQueryChange, onClearRecents = onClearRecents, onOpenPlace = onOpenPlace, onOpenHit = onOpenHit, onExpand = onExpand, clock = clock, zoneId = zoneId, ) } } @Composable private fun SearchPill(query: String, onQueryChange: (String) -> Unit, onBack: () -> Unit, takesFocus: Boolean) { val focus = remember { FocusRequester() } LaunchedEffect(takesFocus) { if (takesFocus) focus.requestFocus() } Row( Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.settingsMargin, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { OutlinedTextField( value = query, onValueChange = onQueryChange, modifier = Modifier.weight(1f).focusRequester(focus).semantics { contentDescription = "Search everything" }, placeholder = { Text("Search everything", style = CottonTextStyles.preview) }, singleLine = true, textStyle = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), ) TextButton(onClick = onBack, modifier = Modifier.semantics { contentDescription = "Close search" }) { Text("Close") } } } @Composable private fun SearchResults( state: SearchState, places: List, onQueryChange: (String) -> Unit, onClearRecents: () -> Unit, onOpenPlace: (String) -> Unit, onOpenHit: (SearchHit) -> Unit, onExpand: (SearchSection) -> Unit, clock: Clock, zoneId: ZoneId, ) { val trimmed = state.query.trim() val matches = if (trimmed.isEmpty()) emptyList() else places.filter { it.name.contains(trimmed, ignoreCase = true) }.take(8) val read = state.read val hasRows = trimmed.isEmpty().not() && (matches.isNotEmpty() || read?.hits?.isNotEmpty() == true) when { trimmed.isEmpty() && state.recents.isEmpty() -> SearchHint(REST_HINT) trimmed.isNotEmpty() && !hasRows && !state.bites -> SearchHint(REST_HINT) trimmed.isNotEmpty() && !hasRows && state.failed -> SearchNotice(FAILED, FAILED_HINT, "search-failed") trimmed.isNotEmpty() && !hasRows && state.settled.isNotBlank() -> SearchNotice(NO_MATCH, NO_MATCH_HINT, "search-empty") else -> SearchList(state, matches, read, onQueryChange, onClearRecents, onOpenPlace, onOpenHit, onExpand, clock, zoneId) } } @Composable private fun SearchHint(copy: String) = Text( copy, Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 28.dp).semantics { contentDescription = "Search hint" }, style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary, ) @Composable private fun SearchNotice(first: String, second: String, tag: String) = Box( Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin).semantics { contentDescription = tag }, contentAlignment = Alignment.Center, ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text(first, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink) Text(second, Modifier.padding(top = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } @Composable private fun SearchList( state: SearchState, matches: List, read: SearchRead?, onQueryChange: (String) -> Unit, onClearRecents: () -> Unit, onOpenPlace: (String) -> Unit, onOpenHit: (SearchHit) -> Unit, onExpand: (SearchSection) -> Unit, clock: Clock, zoneId: ZoneId, ) = LazyColumn( Modifier.fillMaxSize().semantics { contentDescription = "Search list" }, contentPadding = PaddingValues(CottonMetrics.contentMargin, 10.dp, CottonMetrics.contentMargin, 24.dp), ) { if (state.query.trim().isEmpty()) { item("recent-heading") { RecentHeading(onClearRecents) } state.recents.forEach { recent -> item("recent-$recent") { RecentRow(recent) { onQueryChange(recent) } } } } else { if (matches.isNotEmpty()) item("place-chips") { PlaceChips(matches, onOpenPlace) } read?.groups()?.forEach { (section, hits) -> item("section-${section.wire}") { SectionHeading(section, maxOf(read.totals[section] ?: 0L, hits.size.toLong())) } val open = section in state.expanded val shown = if (open) hits else hits.take(SEARCH_SECTION_COLLAPSED) shown.forEach { hit -> item("hit-${hit.kind.wire}-${hit.id}") { SearchHitRow(hit, state.settled, clock, zoneId, onOpenHit) } } val total = maxOf(read.totals[section] ?: 0L, hits.size.toLong()) val remaining = total - shown.size if (!open && remaining > 0) item("more-${section.wire}") { Text( "see $remaining more", Modifier.clickable(role = Role.Button) { onExpand(section) }.padding(start = 6.dp, top = 2.dp, bottom = 12.dp) .semantics { contentDescription = "See all ${sectionLabel(section)}" }, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.hand), color = CottonPalette.ink, ) } } } } @Composable private fun RecentHeading(onClear: () -> Unit) = Row( Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Text("Recent", style = CottonTextStyles.sectionLabel.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Text("clear", Modifier.padding(start = 10.dp).clickable(role = Role.Button, onClick = onClear).semantics { contentDescription = "Clear recent searches" }, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } @Composable private fun RecentRow(query: String, onOpen: () -> Unit) = Row( Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onOpen).padding(vertical = 9.dp) .semantics { contentDescription = "Recent search $query" }, verticalAlignment = Alignment.CenterVertically, ) { RecentClock(Modifier.padding(end = 10.dp)) Text(query, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink, maxLines = 1, overflow = TextOverflow.Ellipsis) } @Composable private fun RecentClock(modifier: Modifier = Modifier) = androidx.compose.foundation.Canvas(modifier.width(14.dp).height(14.dp)) { val radius = size.minDimension * .38f drawCircle(CottonPalette.inkSecondary, radius, center, style = Stroke(width = 1.2.dp.toPx())) drawLine(CottonPalette.inkSecondary, center, Offset(center.x, center.y - radius * .56f), strokeWidth = 1.2.dp.toPx()) drawLine(CottonPalette.inkSecondary, center, Offset(center.x + radius * .5f, center.y), strokeWidth = 1.2.dp.toPx()) } @Composable private fun PlaceChips(matches: List, onOpen: (String) -> Unit) = Row( Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(bottom = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { matches.forEach { place -> Text( place.name, Modifier.height(34.dp).background(CottonPalette.groundElevated, RoundedCornerShape(4.dp)).clickable(role = Role.Button) { onOpen(place.path) } .padding(horizontal = 12.dp, vertical = 8.dp).semantics { contentDescription = "Open ${place.name}" }, style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink, ) } } @Composable private fun SectionHeading(section: SearchSection, total: Long) = Row( Modifier.fillMaxWidth().padding(top = 22.dp, bottom = 10.dp), verticalAlignment = Alignment.CenterVertically, ) { Text(sectionLabel(section), style = CottonTextStyles.sectionLabel.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Spacer(Modifier.width(8.dp)) Text(total.toString(), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } @Composable private fun SearchHitRow(hit: SearchHit, query: String, clock: Clock, zoneId: ZoneId, onOpen: (SearchHit) -> Unit) = Column( Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(4.dp)).clickable(role = Role.Button) { onOpen(hit) } .padding(12.dp).semantics { contentDescription = "Open ${hitTitle(hit)}" }, ) { MatchLine(hitTitle(hit), query, struck = hit.struck, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink) hit.snippet?.takeIf(String::isNotBlank)?.let { MatchLine(it, query, struck = hit.struck, style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary) } hitMeta(hit, clock, zoneId)?.let { Text(it, Modifier.padding(top = 4.dp), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } } @Composable private fun MatchLine(text: String, query: String, struck: Boolean, style: androidx.compose.ui.text.TextStyle, color: androidx.compose.ui.graphics.Color) { // Compose's text underline is intentionally applied to the matching run only. val range = text.indexOf(query, ignoreCase = true) if (range < 0 || query.isBlank()) { Text(text, style = style, color = color, textDecoration = if (struck) androidx.compose.ui.text.style.TextDecoration.LineThrough else null) return } val annotated = androidx.compose.ui.text.buildAnnotatedString { append(text.substring(0, range)) pushStyle(androidx.compose.ui.text.SpanStyle(color = CottonPalette.accent, textDecoration = androidx.compose.ui.text.style.TextDecoration.Underline)) append(text.substring(range, range + query.length)) pop() append(text.substring(range + query.length)) } Text(annotated, style = style, textDecoration = if (struck) androidx.compose.ui.text.style.TextDecoration.LineThrough else null) } private fun hitTitle(hit: SearchHit): String = hit.title?.takeIf(String::isNotBlank) ?: when (hit.kind.wire) { "note" -> if (hit.journal) "Journal" else "Untitled note" "meeting" -> "Meeting" "session" -> "Untitled session" "transaction" -> "Transaction" "mood" -> "Mood" else -> "Untitled" } internal fun searchHitMeta(hit: SearchHit, clock: Clock, zoneId: ZoneId): String? = when { hit.kind.wire == "document" && hit.page != null -> "Page ${hit.page}" else -> hit.whenAt?.let { searchRecordDateLabel(it, clock, zoneId) }?.takeIf(String::isNotBlank) } private fun hitMeta(hit: SearchHit, clock: Clock, zoneId: ZoneId) = searchHitMeta(hit, clock, zoneId) internal fun searchRecordDateLabel(iso: String, clock: Clock, zoneId: ZoneId): String = com.cottondb.android.format.RecordDates.label(iso, clock, zoneId) private fun sectionLabel(section: SearchSection): String = when (section) { SearchSection.Todo -> "Todos"; SearchSection.Event -> "Calendar"; SearchSection.Note -> "Notes"; SearchSection.Message -> "Messages"; SearchSection.Email -> "Email"; SearchSection.Person -> "People"; SearchSection.Location -> "Locations"; SearchSection.Document -> "Documents"; SearchSection.Transaction -> "Money"; SearchSection.Page -> "Reader"; SearchSection.Meeting -> "Meetings"; SearchSection.Memory -> "Memory"; SearchSection.Session -> "Code sessions"; SearchSection.Pull -> "Pull requests"; SearchSection.Issue -> "Issues"; SearchSection.Repository -> "Repositories"; SearchSection.Release -> "Releases"; SearchSection.Goal -> "Goals"; SearchSection.Thought -> "Thoughts"; SearchSection.Mood -> "Mood"; SearchSection.SessionMessage -> "Session messages"; SearchSection.Photo -> "Photos"; SearchSection.Video -> "Videos"; SearchSection.Call -> "Calls"; SearchSection.Secret -> "Passwords"; SearchSection.Decision -> "Decisions" }