Optimize partition search & loading indicator on search

This commit is contained in:
Hasinjato 2026-11-02 12:11:31 +03:00
parent 6b83955e05
commit f3b5ec4a91

View file

@ -37,8 +37,10 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
@ -91,8 +93,6 @@ fun MainScreenWithDrawer(
val scrollState = rememberScrollState()
val currentActivePath = Solfa.currentFile
var textInput = sharedScreenModel.searchTitle.collectAsState().value
val isSearchActive by sharedScreenModel.showSearchMenu.collectAsState()
val focusRequester = remember { FocusRequester() }
@ -387,6 +387,14 @@ fun MainScreenWithDrawer(
}
}
val solfaKeyboardState = remember { SolfaKeyboardState() }
val searchTitleFlow by sharedScreenModel.searchTitle.collectAsState()
var textInput by remember { mutableStateOf(TextFieldValue(searchTitleFlow, TextRange(searchTitleFlow.length))) }
LaunchedEffect(searchTitleFlow) {
if (searchTitleFlow != textInput.text) {
textInput = TextFieldValue(searchTitleFlow, TextRange(searchTitleFlow.length))
}
}
CompositionLocalProvider(LocalSolfaKeyboardState provides solfaKeyboardState) {
@ -437,7 +445,7 @@ fun MainScreenWithDrawer(
value = textInput,
onValueChange = { newValue ->
textInput = newValue
sharedScreenModel.updateSearchTxt(newValue)
sharedScreenModel.updateSearchTxt(newValue.text)
},
readOnly = isAndroid && isNumericKeyboard,
textStyle = LocalTextStyle.current.copy(
@ -459,7 +467,7 @@ fun MainScreenWithDrawer(
),
decorationBox = { innerTextField ->
TextFieldDefaults.DecorationBox(
value = textInput,
value = textInput.text,
innerTextField = innerTextField,
enabled = true,
singleLine = true,
@ -503,7 +511,7 @@ fun MainScreenWithDrawer(
IconButton(
onClick = {
textInput = ""
textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("")
},
modifier = Modifier.size(32.dp)
@ -1141,7 +1149,7 @@ fun MainScreenWithDrawer(
if (isSearchActive) {
sharedScreenModel.showSearchMenu(false)
sharedScreenModel.updateSearchTxt("")
textInput = ""
textInput = TextFieldValue("", TextRange.Zero)
} else {
sharedScreenModel.showSearchMenu(true)
scope.launch {
@ -1167,7 +1175,7 @@ fun MainScreenWithDrawer(
}
androidx.compose.animation.AnimatedVisibility(
visible = isSearchActive && textInput.isNotEmpty(),
visible = isSearchActive && textInput.text.isNotEmpty(),
enter = fadeIn() + expandVertically(),
exit = fadeOut() + shrinkVertically(),
modifier = Modifier
@ -1182,160 +1190,186 @@ fun MainScreenWithDrawer(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
modifier = Modifier.fillMaxHeight()
) {
val sortedSongs = remember(filteredSongs, textInput) {
val naturalComparator = Comparator<DrawerItem> { a, b ->
val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
val chunksA = a.title.lowercase().split(regex)
val chunksB = b.title.lowercase().split(regex)
var result = 0
val size = minOf(chunksA.size, chunksB.size)
for (i in 0 until size) {
val chunkA = chunksA[i]
val chunkB = chunksB[i]
val numA = chunkA.toLongOrNull()
val numB = chunkB.toLongOrNull()
result = if (numA != null && numB != null) {
numA.compareTo(numB)
} else {
chunkA.compareTo(chunkB)
}
if (result != 0) break
}
if (result == 0) chunksA.size.compareTo(chunksB.size) else result
}
var sortedSongs by remember { mutableStateOf(emptyList<DrawerItem>()) }
var isSearching by remember { mutableStateOf(true) }
if (textInput.isBlank()) {
filteredSongs.sortedWith(
compareBy<DrawerItem> { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
)
} else {
filteredSongs.sortedWith(
compareByDescending<DrawerItem> { item -> item.getSearchScore(textInput) }
.thenBy { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
)
LaunchedEffect(filteredSongs, textInput.text) {
isSearching = true
val query = textInput.text
val result = withContext(Dispatchers.Default) {
val naturalComparator = Comparator<DrawerItem> { a, b ->
val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
val chunksA = a.title.lowercase().split(regex)
val chunksB = b.title.lowercase().split(regex)
var result = 0
val size = minOf(chunksA.size, chunksB.size)
for (i in 0 until size) {
val chunkA = chunksA[i]
val chunkB = chunksB[i]
val numA = chunkA.toLongOrNull()
val numB = chunkB.toLongOrNull()
result = if (numA != null && numB != null) {
numA.compareTo(numB)
} else {
chunkA.compareTo(chunkB)
}
if (result != 0) break
}
if (result == 0) chunksA.size.compareTo(chunksB.size) else result
}
if (query.isBlank()) {
filteredSongs.sortedWith(
compareBy<DrawerItem> { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
)
} else {
filteredSongs.sortedWith(
compareByDescending<DrawerItem> { item -> item.getSearchScore(query) }
.thenBy { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
)
}
}
sortedSongs = result
isSearching = false
}
val searchListState = rememberLazyListState()
LaunchedEffect(textInput) {
LaunchedEffect(textInput.text) {
if (sortedSongs.isNotEmpty()) {
searchListState.scrollToItem(0)
}
}
LazyColumn(
state = searchListState,
modifier = Modifier.fillMaxSize()
) {
if (sortedSongs.isEmpty() && textInput.isNotEmpty()) {
item {
ListItem(
headlineContent = {
Text(
text = "Partition non trouvée pour \"$textInput\"",
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Medium,
fontSize = 14.sp
)
},
supportingContent = {
Text(
text = "Essayez un autre.",
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
},
leadingContent = {
Icon(
imageVector = Icons.Default.SearchOff,
contentDescription = "Not result search",
tint = MaterialTheme.colorScheme.error
)
}
)
}
}
itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item ->
val isFavorite = favoritePaths.contains(item)
val onPlaylist = item.path in lastPlaylistPaths
val dismissState = rememberSwipeToDismissBoxState(
confirmValueChange = { dismissValue ->
if (dismissValue == SwipeToDismissBoxValue.StartToEnd || dismissValue == SwipeToDismissBoxValue.EndToStart) {
sharedScreenModel.toFavorite(item.path)
sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset()
solfaScreenModel.loadFromFile(item.path)
sharedScreenModel.stopMidi()
sharedScreenModel.seekTo(0f)
sharedScreenModel.setTranspositionInterval(0)
false
} else {
false
}
}
)
SwipeToDismissBox(
state = dismissState,
backgroundContent = {
val color = if (isFavorite) Color.Gray else MaterialTheme.colorScheme.tertiary
val scale by animateFloatAsState(
targetValue = if (dismissState.progress > 0.1f) 1.2f else 0.8f,
label = "iconScale"
)
Box(
modifier = Modifier
.fillMaxSize()
.background(color)
.padding(horizontal = 20.dp),
contentAlignment = if (dismissState.dismissDirection == SwipeToDismissBoxValue.StartToEnd)
Alignment.CenterStart else Alignment.CenterEnd
) {
Icon(
imageVector = if (isFavorite) Icons.Default.FavoriteBorder else Icons.Default.Favorite,
contentDescription = "Favorite btn",
modifier = Modifier.scale(scale),
tint = MaterialTheme.colorScheme.onSecondary
)
}
}
) {
ListItem(
leadingContent = {
Icon(
imageVector = if (item.path.startsWith("assets://")) Icons.Default.ArrowDropDownCircle else Icons.Default.Folder,
contentDescription = "Part interne ou personnel",
modifier = Modifier.size(30.dp)
)
},
headlineContent = { Text(item.title) },
supportingContent = { Text(item.contentTitle, maxLines = 1) },
trailingContent = {
IconButton(
onClick = {
scope.launch {
sharedScreenModel.addSongToPlaylist(songTitle = item.title, path = item.path)
}
},
modifier = Modifier.size(35.dp)
) {
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(
state = searchListState,
modifier = Modifier.fillMaxSize()
) {
if (!isSearching && sortedSongs.isEmpty() && textInput.text.isNotEmpty()) {
item {
ListItem(
headlineContent = {
Text(
text = "Partition non trouvée pour \"${textInput.text}\"",
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Medium,
fontSize = 14.sp
)
},
supportingContent = {
Text(
text = "Essayez un autre.",
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
},
leadingContent = {
Icon(
imageVector = Icons.AutoMirrored.Default.PlaylistAdd,
contentDescription = if (onPlaylist) "Déjà dans la playlist" else "Btn add playlist",
tint = if (!onPlaylist) Color.LightGray else Color(
0xFFFFD700
)
imageVector = Icons.Default.SearchOff,
contentDescription = "Not result search",
tint = MaterialTheme.colorScheme.error
)
}
},
modifier = Modifier.clickable {
sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset()
solfaScreenModel.loadFromFile(item.path)
sharedScreenModel.loadNewSong(midiFile)
})
)
}
}
itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item ->
val isFavorite = favoritePaths.contains(item)
val onPlaylist = item.path in lastPlaylistPaths
val dismissState = rememberSwipeToDismissBoxState(
confirmValueChange = { dismissValue ->
if (dismissValue == SwipeToDismissBoxValue.StartToEnd || dismissValue == SwipeToDismissBoxValue.EndToStart) {
sharedScreenModel.toFavorite(item.path)
sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset()
solfaScreenModel.loadFromFile(item.path)
sharedScreenModel.stopMidi()
sharedScreenModel.seekTo(0f)
sharedScreenModel.setTranspositionInterval(0)
false
} else {
false
}
}
)
SwipeToDismissBox(
state = dismissState,
backgroundContent = {
val color = if (isFavorite) Color.Gray else MaterialTheme.colorScheme.tertiary
val scale by animateFloatAsState(
targetValue = if (dismissState.progress > 0.1f) 1.2f else 0.8f,
label = "iconScale"
)
Box(
modifier = Modifier
.fillMaxSize()
.background(color)
.padding(horizontal = 20.dp),
contentAlignment = if (dismissState.dismissDirection == SwipeToDismissBoxValue.StartToEnd)
Alignment.CenterStart else Alignment.CenterEnd
) {
Icon(
imageVector = if (isFavorite) Icons.Default.FavoriteBorder else Icons.Default.Favorite,
contentDescription = "Favorite btn",
modifier = Modifier.scale(scale),
tint = MaterialTheme.colorScheme.onSecondary
)
}
}
) {
ListItem(
leadingContent = {
Icon(
imageVector = if (item.path.startsWith("assets://")) Icons.Default.ArrowDropDownCircle else Icons.Default.Folder,
contentDescription = "Part interne ou personnel",
modifier = Modifier.size(30.dp)
)
},
headlineContent = { Text(item.title) },
supportingContent = { Text(item.contentTitle, maxLines = 1) },
trailingContent = {
IconButton(
onClick = {
scope.launch {
sharedScreenModel.addSongToPlaylist(songTitle = item.title, path = item.path)
}
},
modifier = Modifier.size(35.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.PlaylistAdd,
contentDescription = if (onPlaylist) "Déjà dans la playlist" else "Btn add playlist",
tint = if (!onPlaylist) Color.LightGray else Color(
0xFFFFD700
)
)
}
},
modifier = Modifier.clickable {
sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset()
solfaScreenModel.loadFromFile(item.path)
sharedScreenModel.loadNewSong(midiFile)
})
}
HorizontalDivider()
}
}
if (isSearching) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier.size(40.dp),
color = MaterialTheme.colorScheme.primary,
strokeWidth = 3.dp
)
}
HorizontalDivider()
}
}
}
@ -1353,21 +1387,23 @@ fun MainScreenWithDrawer(
keyboardHeightDp = with(density) { coordinates.size.height.toDp() }
},
onDigitClick = { digit ->
textInput += digit
sharedScreenModel.updateSearchTxt(textInput)
val newText = textInput.text + digit
textInput = TextFieldValue(newText, TextRange(newText.length))
sharedScreenModel.updateSearchTxt(newText)
},
onDeleteClick = {
if (textInput.isNotEmpty()) {
textInput = textInput.dropLast(1)
sharedScreenModel.updateSearchTxt(textInput)
if (textInput.text.isNotEmpty()) {
val newText = textInput.text.dropLast(1)
textInput = TextFieldValue(newText, TextRange(newText.length))
sharedScreenModel.updateSearchTxt(newText)
}
},
onClearClick = {
textInput = ""
textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("")
},
onPrefixClick = { prefix ->
val digits = textInput.trim()
val digits = textInput.text.trim()
val cleanPrefix = prefix.trim().lowercase()
if (digits.isNotEmpty() && digits.all { it.isDigit() }) {
@ -1380,16 +1416,16 @@ fun MainScreenWithDrawer(
}
}
if (matchingItem != null) {
textInput = ""
textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset()
solfaScreenModel.loadFromFile(matchingItem.path)
} else {
textInput = prefix
textInput = TextFieldValue(prefix, TextRange(prefix.length))
sharedScreenModel.updateSearchTxt(prefix)
}
} else {
textInput = prefix
textInput = TextFieldValue(prefix, TextRange(prefix.length))
sharedScreenModel.updateSearchTxt(prefix)
}
},