306 lines · 15.5 KB · KotlinRaw
package com.cottondb.android.ui.searchimport 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.heightimport androidx.compose.foundation.layout.imePaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.home.HomeToolimport com.cottondb.android.search.SEARCH_SECTION_COLLAPSEDimport com.cottondb.android.search.SearchHitimport com.cottondb.android.search.SearchReadimport com.cottondb.android.search.SearchSectionimport com.cottondb.android.search.SearchStateimport com.cottondb.android.search.groupsimport java.time.Clockimport java.time.Durationimport java.time.Instantimport java.time.ZoneIdimport java.time.format.DateTimeFormatterimport java.util.Localeprivate 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. */@Composablefun SearchScreen( state: SearchState, places: List<HomeTool>, 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, ) }}@Composableprivate 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") }}}@Composableprivate fun SearchResults( state: SearchState, places: List<HomeTool>, 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) }}@Composableprivate 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,)@Composableprivate 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) }}@Composableprivate fun SearchList( state: SearchState, matches: List<HomeTool>, 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, ) } } }}@Composableprivate 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)}@Composableprivate 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)}@Composableprivate 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())}@Composableprivate fun PlaceChips(matches: List<HomeTool>, 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, ) }}@Composableprivate 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)}@Composableprivate 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) }}@Composableprivate 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"}