feat(search): collapsible section headers + sorting + search improvements
- Collapsible sticky section headers with animated chevron - Full header row clickable to toggle collapse - SearchResultSorter, SearchSortOrder, pseudo-kind filtering - TextFieldValue cursor preservation, relay timeout improvements Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+34
-1
@@ -83,6 +83,24 @@ class AdvancedSearchBarState(
|
||||
private val _noteResults = MutableStateFlow<ImmutableList<Event>>(persistentListOf())
|
||||
val noteResults: StateFlow<ImmutableList<Event>> = _noteResults.asStateFlow()
|
||||
|
||||
// Sort orders
|
||||
private val _eventSortOrder = MutableStateFlow(SearchSortOrder.DEFAULT_EVENT)
|
||||
val eventSortOrder: StateFlow<SearchSortOrder> = _eventSortOrder.asStateFlow()
|
||||
|
||||
private val _peopleSortOrder = MutableStateFlow(SearchSortOrder.DEFAULT_PEOPLE)
|
||||
val peopleSortOrder: StateFlow<SearchSortOrder> = _peopleSortOrder.asStateFlow()
|
||||
|
||||
// Derived sorted results
|
||||
val sortedNoteResults: StateFlow<ImmutableList<Event>> =
|
||||
combine(_noteResults, _eventSortOrder, _rawText) { notes, order, text ->
|
||||
SearchResultSorter.sortEvents(notes, order, text).toImmutableList()
|
||||
}.stateIn(scope, SharingStarted.Eagerly, persistentListOf())
|
||||
|
||||
val sortedPeopleResults: StateFlow<ImmutableList<User>> =
|
||||
combine(_peopleResults, _peopleSortOrder) { people, order ->
|
||||
SearchResultSorter.sortPeople(people, order).toImmutableList()
|
||||
}.stateIn(scope, SharingStarted.Eagerly, persistentListOf())
|
||||
|
||||
private val activeSubIds = MutableStateFlow<Set<String>>(emptySet())
|
||||
val isSearching: StateFlow<Boolean> =
|
||||
activeSubIds
|
||||
@@ -112,6 +130,11 @@ class AdvancedSearchBarState(
|
||||
_query.value = _query.value.copy(kinds = kinds.toImmutableList())
|
||||
}
|
||||
|
||||
fun updatePseudoKinds(pseudoKinds: List<String>) {
|
||||
_changeSource = ChangeSource.FORM
|
||||
_query.value = _query.value.copy(pseudoKinds = pseudoKinds.toImmutableList())
|
||||
}
|
||||
|
||||
fun addAuthor(hexOrName: String) {
|
||||
_changeSource = ChangeSource.FORM
|
||||
val current = _query.value
|
||||
@@ -228,6 +251,14 @@ class AdvancedSearchBarState(
|
||||
_panelExpanded.value = !_panelExpanded.value
|
||||
}
|
||||
|
||||
fun updateEventSortOrder(order: SearchSortOrder) {
|
||||
_eventSortOrder.value = order
|
||||
}
|
||||
|
||||
fun updatePeopleSortOrder(order: SearchSortOrder) {
|
||||
_peopleSortOrder.value = order
|
||||
}
|
||||
|
||||
fun clearSearch() {
|
||||
_changeSource = ChangeSource.INIT
|
||||
_rawText.value = ""
|
||||
@@ -235,6 +266,8 @@ class AdvancedSearchBarState(
|
||||
_peopleResults.value = persistentListOf()
|
||||
_noteResults.value = persistentListOf()
|
||||
_relayStates.value = persistentListOf()
|
||||
_eventSortOrder.value = SearchSortOrder.DEFAULT_EVENT
|
||||
_peopleSortOrder.value = SearchSortOrder.DEFAULT_PEOPLE
|
||||
activeSubIds.value = emptySet()
|
||||
eventDeduplicator.clear()
|
||||
}
|
||||
@@ -275,7 +308,7 @@ class AdvancedSearchBarState(
|
||||
fun addNoteResults(events: List<Event>) {
|
||||
if (events.isNotEmpty()) {
|
||||
val current = _noteResults.value
|
||||
_noteResults.value = (current + events).sortedByDescending { it.createdAt }.toImmutableList()
|
||||
_noteResults.value = (current + events).toImmutableList()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-7
@@ -32,6 +32,22 @@ import com.vitorpamplona.quartz.nip72ModCommunities.definition.CommunityDefiniti
|
||||
import com.vitorpamplona.quartz.nip84Highlights.HighlightEvent
|
||||
import com.vitorpamplona.quartz.nip99Classifieds.ClassifiedsEvent
|
||||
|
||||
data class ContentPreset(
|
||||
val kinds: List<Int> = emptyList(),
|
||||
val pseudoKind: String? = null,
|
||||
) {
|
||||
/** Check if this preset is active given current query state. */
|
||||
fun isSelected(
|
||||
queryKinds: List<Int>,
|
||||
queryPseudoKinds: List<String>,
|
||||
): Boolean =
|
||||
if (pseudoKind != null) {
|
||||
pseudoKind in queryPseudoKinds
|
||||
} else {
|
||||
kinds.isNotEmpty() && queryKinds.containsAll(kinds)
|
||||
}
|
||||
}
|
||||
|
||||
object KindRegistry {
|
||||
val aliases: Map<String, List<Int>> =
|
||||
mapOf(
|
||||
@@ -49,14 +65,14 @@ object KindRegistry {
|
||||
|
||||
val pseudoKinds: Set<String> = setOf("reply", "media")
|
||||
|
||||
val presets: Map<String, List<Int>> =
|
||||
val presets: Map<String, ContentPreset> =
|
||||
mapOf(
|
||||
"Notes" to listOf(TextNoteEvent.KIND),
|
||||
"Articles" to listOf(LongTextNoteEvent.KIND),
|
||||
"Media" to listOf(TextNoteEvent.KIND),
|
||||
"Channels" to listOf(ChannelCreateEvent.KIND, ChannelMetadataEvent.KIND),
|
||||
"Communities" to listOf(CommunityDefinitionEvent.KIND),
|
||||
"Wiki" to listOf(WikiNoteEvent.KIND),
|
||||
"Notes" to ContentPreset(kinds = listOf(TextNoteEvent.KIND)),
|
||||
"Articles" to ContentPreset(kinds = listOf(LongTextNoteEvent.KIND)),
|
||||
"Media" to ContentPreset(pseudoKind = "media"),
|
||||
"Channels" to ContentPreset(kinds = listOf(ChannelCreateEvent.KIND, ChannelMetadataEvent.KIND)),
|
||||
"Communities" to ContentPreset(kinds = listOf(CommunityDefinitionEvent.KIND)),
|
||||
"Wiki" to ContentPreset(kinds = listOf(WikiNoteEvent.KIND)),
|
||||
)
|
||||
|
||||
fun resolve(alias: String): List<Int>? = aliases[alias.lowercase()]
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright (c) 2025 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.amethyst.commons.search
|
||||
|
||||
import com.vitorpamplona.amethyst.commons.model.User
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip23LongContent.LongTextNoteEvent
|
||||
import com.vitorpamplona.quartz.utils.currentTimeSeconds
|
||||
|
||||
object SearchResultSorter {
|
||||
fun sortEvents(
|
||||
events: List<Event>,
|
||||
order: SearchSortOrder,
|
||||
searchText: String,
|
||||
): List<Event> =
|
||||
when (order) {
|
||||
SearchSortOrder.NEWEST -> {
|
||||
events.sortedByDescending { it.createdAt }
|
||||
}
|
||||
|
||||
SearchSortOrder.OLDEST -> {
|
||||
events.sortedBy { it.createdAt }
|
||||
}
|
||||
|
||||
SearchSortOrder.RELEVANCE -> {
|
||||
if (searchText.isBlank()) {
|
||||
events.sortedByDescending { it.createdAt }
|
||||
} else {
|
||||
events.sortedByDescending { scoreEvent(it, searchText) }
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
events
|
||||
}
|
||||
}
|
||||
|
||||
fun sortPeople(
|
||||
people: List<User>,
|
||||
order: SearchSortOrder,
|
||||
): List<User> =
|
||||
when (order) {
|
||||
SearchSortOrder.NAME_AZ -> people.sortedBy { it.toBestDisplayName().lowercase() }
|
||||
SearchSortOrder.NAME_ZA -> people.sortedByDescending { it.toBestDisplayName().lowercase() }
|
||||
else -> people
|
||||
}
|
||||
|
||||
fun scoreEvent(
|
||||
event: Event,
|
||||
searchText: String,
|
||||
): Double {
|
||||
val query = searchText.trim().lowercase()
|
||||
if (query.isEmpty()) return event.createdAt.toDouble()
|
||||
|
||||
var score = 0.0
|
||||
val content = event.content.lowercase()
|
||||
val tokens = query.split("\\s+".toRegex())
|
||||
|
||||
// Exact phrase match in content
|
||||
if (content.contains(query)) {
|
||||
score += 10.0
|
||||
}
|
||||
|
||||
// Per-token scoring
|
||||
for (token in tokens) {
|
||||
if (token.isEmpty()) continue
|
||||
val wordBoundary = "\\b${Regex.escape(token)}\\b".toRegex()
|
||||
if (wordBoundary.containsMatchIn(content)) {
|
||||
score += 5.0
|
||||
} else if (content.contains(token)) {
|
||||
score += 2.0
|
||||
}
|
||||
}
|
||||
|
||||
// Article title boost
|
||||
if (event is LongTextNoteEvent) {
|
||||
val title = event.title()?.lowercase()
|
||||
if (title != null) {
|
||||
if (title.contains(query)) {
|
||||
score += 15.0
|
||||
}
|
||||
for (token in tokens) {
|
||||
if (token.isEmpty()) continue
|
||||
if (title.contains(token)) {
|
||||
score += 3.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recency tiebreaker (normalized 0..1)
|
||||
val now = currentTimeSeconds()
|
||||
val age = (now - event.createdAt).coerceAtLeast(1)
|
||||
val maxAge = 365L * 24 * 3600 // 1 year
|
||||
score += (1.0 - (age.toDouble() / maxAge).coerceIn(0.0, 1.0))
|
||||
|
||||
return score
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2025 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.amethyst.commons.search
|
||||
|
||||
enum class SearchSortOrder(
|
||||
val label: String,
|
||||
) {
|
||||
NEWEST("Newest"),
|
||||
OLDEST("Oldest"),
|
||||
RELEVANCE("Relevance"),
|
||||
NAME_AZ("A → Z"),
|
||||
NAME_ZA("Z → A"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
val EVENT_OPTIONS = listOf(NEWEST, OLDEST, RELEVANCE)
|
||||
val PEOPLE_OPTIONS = listOf(NAME_AZ, NAME_ZA)
|
||||
val DEFAULT_EVENT = NEWEST
|
||||
val DEFAULT_PEOPLE = NAME_AZ
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright (c) 2025 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.amethyst.commons.search
|
||||
|
||||
import com.vitorpamplona.amethyst.commons.model.Note
|
||||
import com.vitorpamplona.amethyst.commons.model.User
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata
|
||||
import com.vitorpamplona.quartz.nip23LongContent.LongTextNoteEvent
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class SearchResultSorterTest {
|
||||
private fun event(
|
||||
id: String,
|
||||
createdAt: Long,
|
||||
content: String = "",
|
||||
kind: Int = 1,
|
||||
) = Event(
|
||||
id = id,
|
||||
pubKey = "abc123def456abc123def456abc123def456abc123def456abc123def456abcd",
|
||||
createdAt = createdAt,
|
||||
kind = kind,
|
||||
tags = emptyArray(),
|
||||
content = content,
|
||||
sig = "sig",
|
||||
)
|
||||
|
||||
private fun article(
|
||||
id: String,
|
||||
createdAt: Long,
|
||||
content: String = "",
|
||||
title: String? = null,
|
||||
): LongTextNoteEvent {
|
||||
val tags =
|
||||
if (title != null) {
|
||||
arrayOf(arrayOf("title", title))
|
||||
} else {
|
||||
emptyArray()
|
||||
}
|
||||
return LongTextNoteEvent(
|
||||
id = id,
|
||||
pubKey = "abc123def456abc123def456abc123def456abc123def456abc123def456abcd",
|
||||
createdAt = createdAt,
|
||||
tags = tags,
|
||||
content = content,
|
||||
sig = "sig",
|
||||
)
|
||||
}
|
||||
|
||||
private fun user(
|
||||
hex: String,
|
||||
displayName: String,
|
||||
): User {
|
||||
val u = User(hex, Note("r1-$hex"), Note("r2-$hex"))
|
||||
val meta = UserMetadata().apply { this.displayName = displayName }
|
||||
val metaEvent =
|
||||
MetadataEvent(
|
||||
id = "meta-$hex",
|
||||
pubKey = hex,
|
||||
createdAt = 0L,
|
||||
tags = emptyArray(),
|
||||
content = "{}",
|
||||
sig = "sig",
|
||||
)
|
||||
u.updateUserInfo(meta, metaEvent)
|
||||
return u
|
||||
}
|
||||
|
||||
// --- Event sorting ---
|
||||
|
||||
@Test
|
||||
fun newestSortsDescending() {
|
||||
val events = listOf(event("a", 100), event("b", 300), event("c", 200))
|
||||
val sorted = SearchResultSorter.sortEvents(events, SearchSortOrder.NEWEST, "")
|
||||
assertEquals(listOf("b", "c", "a"), sorted.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oldestSortsAscending() {
|
||||
val events = listOf(event("a", 300), event("b", 100), event("c", 200))
|
||||
val sorted = SearchResultSorter.sortEvents(events, SearchSortOrder.OLDEST, "")
|
||||
assertEquals(listOf("b", "c", "a"), sorted.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relevanceEmptyQueryFallsBackToRecency() {
|
||||
val events = listOf(event("a", 100), event("b", 300), event("c", 200))
|
||||
val sorted = SearchResultSorter.sortEvents(events, SearchSortOrder.RELEVANCE, "")
|
||||
assertEquals(listOf("b", "c", "a"), sorted.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relevanceExactMatchBeatsPartial() {
|
||||
val exact = event("exact", 100, content = "bitcoin is great")
|
||||
val partial = event("partial", 100, content = "bit of something")
|
||||
val sorted = SearchResultSorter.sortEvents(listOf(partial, exact), SearchSortOrder.RELEVANCE, "bitcoin")
|
||||
assertEquals("exact", sorted.first().id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relevanceWordBoundaryBeatsSubstring() {
|
||||
val boundary = event("boundary", 100, content = "I love bitcoin and lightning")
|
||||
val substring = event("substr", 100, content = "bitcoinery is not a word")
|
||||
val sorted = SearchResultSorter.sortEvents(listOf(substring, boundary), SearchSortOrder.RELEVANCE, "bitcoin")
|
||||
assertEquals("boundary", sorted.first().id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relevanceArticleTitleBoost() {
|
||||
val withTitle = article("titled", 100, content = "some content", title = "Bitcoin Guide")
|
||||
val withoutTitle = event("notitle", 100, content = "bitcoin bitcoin bitcoin")
|
||||
val sorted = SearchResultSorter.sortEvents(listOf(withoutTitle, withTitle), SearchSortOrder.RELEVANCE, "bitcoin")
|
||||
assertEquals("titled", sorted.first().id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relevanceMultipleTokensAddUp() {
|
||||
val multi = event("multi", 100, content = "bitcoin and lightning network")
|
||||
val single = event("single", 100, content = "bitcoin only here")
|
||||
val sorted =
|
||||
SearchResultSorter.sortEvents(
|
||||
listOf(single, multi),
|
||||
SearchSortOrder.RELEVANCE,
|
||||
"bitcoin lightning",
|
||||
)
|
||||
assertEquals("multi", sorted.first().id)
|
||||
}
|
||||
|
||||
// --- People sorting ---
|
||||
|
||||
@Test
|
||||
fun nameAzSortsAlphabetically() {
|
||||
val people =
|
||||
listOf(
|
||||
user("cc00000000000000000000000000000000000000000000000000000000000000", "Charlie"),
|
||||
user("aa00000000000000000000000000000000000000000000000000000000000000", "Alice"),
|
||||
user("bb00000000000000000000000000000000000000000000000000000000000000", "Bob"),
|
||||
)
|
||||
val sorted = SearchResultSorter.sortPeople(people, SearchSortOrder.NAME_AZ)
|
||||
assertEquals(listOf("Alice", "Bob", "Charlie"), sorted.map { it.toBestDisplayName() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nameZaSortsReverseAlphabetically() {
|
||||
val people =
|
||||
listOf(
|
||||
user("aa00000000000000000000000000000000000000000000000000000000000000", "Alice"),
|
||||
user("cc00000000000000000000000000000000000000000000000000000000000000", "Charlie"),
|
||||
user("bb00000000000000000000000000000000000000000000000000000000000000", "Bob"),
|
||||
)
|
||||
val sorted = SearchResultSorter.sortPeople(people, SearchSortOrder.NAME_ZA)
|
||||
assertEquals(listOf("Charlie", "Bob", "Alice"), sorted.map { it.toBestDisplayName() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nameSortIsCaseInsensitive() {
|
||||
val people =
|
||||
listOf(
|
||||
user("aa00000000000000000000000000000000000000000000000000000000000000", "alice"),
|
||||
user("bb00000000000000000000000000000000000000000000000000000000000000", "Bob"),
|
||||
)
|
||||
val sorted = SearchResultSorter.sortPeople(people, SearchSortOrder.NAME_AZ)
|
||||
assertEquals("alice", sorted.first().toBestDisplayName())
|
||||
}
|
||||
|
||||
// --- Score function ---
|
||||
|
||||
@Test
|
||||
fun scoreExactPhraseHigherThanTokens() {
|
||||
val exactEvent = event("e", 100, content = "bitcoin lightning network")
|
||||
val tokenEvent = event("t", 100, content = "lightning and bitcoin elsewhere network")
|
||||
val exactScore = SearchResultSorter.scoreEvent(exactEvent, "bitcoin lightning")
|
||||
val tokenScore = SearchResultSorter.scoreEvent(tokenEvent, "bitcoin lightning")
|
||||
assertTrue(exactScore > tokenScore)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user