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.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType 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.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
@ -91,8 +93,6 @@ fun MainScreenWithDrawer(
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val currentActivePath = Solfa.currentFile val currentActivePath = Solfa.currentFile
var textInput = sharedScreenModel.searchTitle.collectAsState().value
val isSearchActive by sharedScreenModel.showSearchMenu.collectAsState() val isSearchActive by sharedScreenModel.showSearchMenu.collectAsState()
val focusRequester = remember { FocusRequester() } val focusRequester = remember { FocusRequester() }
@ -387,6 +387,14 @@ fun MainScreenWithDrawer(
} }
} }
val solfaKeyboardState = remember { SolfaKeyboardState() } 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) { CompositionLocalProvider(LocalSolfaKeyboardState provides solfaKeyboardState) {
@ -437,7 +445,7 @@ fun MainScreenWithDrawer(
value = textInput, value = textInput,
onValueChange = { newValue -> onValueChange = { newValue ->
textInput = newValue textInput = newValue
sharedScreenModel.updateSearchTxt(newValue) sharedScreenModel.updateSearchTxt(newValue.text)
}, },
readOnly = isAndroid && isNumericKeyboard, readOnly = isAndroid && isNumericKeyboard,
textStyle = LocalTextStyle.current.copy( textStyle = LocalTextStyle.current.copy(
@ -459,7 +467,7 @@ fun MainScreenWithDrawer(
), ),
decorationBox = { innerTextField -> decorationBox = { innerTextField ->
TextFieldDefaults.DecorationBox( TextFieldDefaults.DecorationBox(
value = textInput, value = textInput.text,
innerTextField = innerTextField, innerTextField = innerTextField,
enabled = true, enabled = true,
singleLine = true, singleLine = true,
@ -503,7 +511,7 @@ fun MainScreenWithDrawer(
IconButton( IconButton(
onClick = { onClick = {
textInput = "" textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("") sharedScreenModel.updateSearchTxt("")
}, },
modifier = Modifier.size(32.dp) modifier = Modifier.size(32.dp)
@ -1141,7 +1149,7 @@ fun MainScreenWithDrawer(
if (isSearchActive) { if (isSearchActive) {
sharedScreenModel.showSearchMenu(false) sharedScreenModel.showSearchMenu(false)
sharedScreenModel.updateSearchTxt("") sharedScreenModel.updateSearchTxt("")
textInput = "" textInput = TextFieldValue("", TextRange.Zero)
} else { } else {
sharedScreenModel.showSearchMenu(true) sharedScreenModel.showSearchMenu(true)
scope.launch { scope.launch {
@ -1167,7 +1175,7 @@ fun MainScreenWithDrawer(
} }
androidx.compose.animation.AnimatedVisibility( androidx.compose.animation.AnimatedVisibility(
visible = isSearchActive && textInput.isNotEmpty(), visible = isSearchActive && textInput.text.isNotEmpty(),
enter = fadeIn() + expandVertically(), enter = fadeIn() + expandVertically(),
exit = fadeOut() + shrinkVertically(), exit = fadeOut() + shrinkVertically(),
modifier = Modifier modifier = Modifier
@ -1182,160 +1190,186 @@ fun MainScreenWithDrawer(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
modifier = Modifier.fillMaxHeight() modifier = Modifier.fillMaxHeight()
) { ) {
val sortedSongs = remember(filteredSongs, textInput) { var sortedSongs by remember { mutableStateOf(emptyList<DrawerItem>()) }
val naturalComparator = Comparator<DrawerItem> { a, b -> var isSearching by remember { mutableStateOf(true) }
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 (textInput.isBlank()) { LaunchedEffect(filteredSongs, textInput.text) {
filteredSongs.sortedWith( isSearching = true
compareBy<DrawerItem> { item -> !item.path.startsWith("assets://") } val query = textInput.text
.thenComparing(naturalComparator) val result = withContext(Dispatchers.Default) {
) val naturalComparator = Comparator<DrawerItem> { a, b ->
} else { val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
filteredSongs.sortedWith( val chunksA = a.title.lowercase().split(regex)
compareByDescending<DrawerItem> { item -> item.getSearchScore(textInput) } val chunksB = b.title.lowercase().split(regex)
.thenBy { item -> !item.path.startsWith("assets://") } var result = 0
.thenComparing(naturalComparator) 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() val searchListState = rememberLazyListState()
LaunchedEffect(textInput) { LaunchedEffect(textInput.text) {
if (sortedSongs.isNotEmpty()) { if (sortedSongs.isNotEmpty()) {
searchListState.scrollToItem(0) searchListState.scrollToItem(0)
} }
} }
LazyColumn(
state = searchListState, Box(modifier = Modifier.fillMaxSize()) {
modifier = Modifier.fillMaxSize() LazyColumn(
) { state = searchListState,
if (sortedSongs.isEmpty() && textInput.isNotEmpty()) { modifier = Modifier.fillMaxSize()
item { ) {
ListItem( if (!isSearching && sortedSongs.isEmpty() && textInput.text.isNotEmpty()) {
headlineContent = { item {
Text( ListItem(
text = "Partition non trouvée pour \"$textInput\"", headlineContent = {
color = MaterialTheme.colorScheme.error, Text(
fontWeight = FontWeight.Medium, text = "Partition non trouvée pour \"${textInput.text}\"",
fontSize = 14.sp color = MaterialTheme.colorScheme.error,
) fontWeight = FontWeight.Medium,
}, fontSize = 14.sp
supportingContent = { )
Text( },
text = "Essayez un autre.", supportingContent = {
fontSize = 12.sp, Text(
color = MaterialTheme.colorScheme.onSurfaceVariant text = "Essayez un autre.",
) fontSize = 12.sp,
}, color = MaterialTheme.colorScheme.onSurfaceVariant
leadingContent = { )
Icon( },
imageVector = Icons.Default.SearchOff, leadingContent = {
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)
) {
Icon( Icon(
imageVector = Icons.AutoMirrored.Default.PlaylistAdd, imageVector = Icons.Default.SearchOff,
contentDescription = if (onPlaylist) "Déjà dans la playlist" else "Btn add playlist", contentDescription = "Not result search",
tint = if (!onPlaylist) Color.LightGray else Color( tint = MaterialTheme.colorScheme.error
0xFFFFD700
)
) )
} }
}, )
modifier = Modifier.clickable { }
sharedScreenModel.updateSearchTxt("") }
sharedScreenModel.reset() itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item ->
solfaScreenModel.loadFromFile(item.path) val isFavorite = favoritePaths.contains(item)
sharedScreenModel.loadNewSong(midiFile) 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() } keyboardHeightDp = with(density) { coordinates.size.height.toDp() }
}, },
onDigitClick = { digit -> onDigitClick = { digit ->
textInput += digit val newText = textInput.text + digit
sharedScreenModel.updateSearchTxt(textInput) textInput = TextFieldValue(newText, TextRange(newText.length))
sharedScreenModel.updateSearchTxt(newText)
}, },
onDeleteClick = { onDeleteClick = {
if (textInput.isNotEmpty()) { if (textInput.text.isNotEmpty()) {
textInput = textInput.dropLast(1) val newText = textInput.text.dropLast(1)
sharedScreenModel.updateSearchTxt(textInput) textInput = TextFieldValue(newText, TextRange(newText.length))
sharedScreenModel.updateSearchTxt(newText)
} }
}, },
onClearClick = { onClearClick = {
textInput = "" textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("") sharedScreenModel.updateSearchTxt("")
}, },
onPrefixClick = { prefix -> onPrefixClick = { prefix ->
val digits = textInput.trim() val digits = textInput.text.trim()
val cleanPrefix = prefix.trim().lowercase() val cleanPrefix = prefix.trim().lowercase()
if (digits.isNotEmpty() && digits.all { it.isDigit() }) { if (digits.isNotEmpty() && digits.all { it.isDigit() }) {
@ -1380,16 +1416,16 @@ fun MainScreenWithDrawer(
} }
} }
if (matchingItem != null) { if (matchingItem != null) {
textInput = "" textInput = TextFieldValue("", TextRange.Zero)
sharedScreenModel.updateSearchTxt("") sharedScreenModel.updateSearchTxt("")
sharedScreenModel.reset() sharedScreenModel.reset()
solfaScreenModel.loadFromFile(matchingItem.path) solfaScreenModel.loadFromFile(matchingItem.path)
} else { } else {
textInput = prefix textInput = TextFieldValue(prefix, TextRange(prefix.length))
sharedScreenModel.updateSearchTxt(prefix) sharedScreenModel.updateSearchTxt(prefix)
} }
} else { } else {
textInput = prefix textInput = TextFieldValue(prefix, TextRange(prefix.length))
sharedScreenModel.updateSearchTxt(prefix) sharedScreenModel.updateSearchTxt(prefix)
} }
}, },