Skip to content

Instantly share code, notes, and snippets.

@JakubNeukirch
Created October 29, 2024 16:22
Show Gist options
  • Save JakubNeukirch/30360280f2ada8ff0c400c19ae74692e to your computer and use it in GitHub Desktop.
Save JakubNeukirch/30360280f2ada8ff0c400c19ae74692e to your computer and use it in GitHub Desktop.
Voldemort ShuffleText animation in Kotlin Multiplatform
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
@Composable
fun ShuffleText(
text: String,
) {
val characters = remember(text) { text.toCharacterItems() }
LazyRow {
items(
characters,
key = { character -> character.key }
) { item ->
Text(
text = item.character.toString(),
modifier = Modifier.animateItem(
placementSpec = tween(
durationMillis = 600
),
)
)
}
}
}
private fun String.toCharacterItems(): List<CharacterItem> {
val chars = this.toCharArray()
val result = mutableListOf<CharacterItem>()
for (i in chars.indices) {
result.add(CharacterItem(chars[i], result.count { it.character.lowercase() == chars[i].lowercase() }))
}
return result
}
data class CharacterItem(
val character: Char,
val characterOccurrence: Int,
) {
val key: String get() = "${character.lowercase()}$characterOccurrence" //can't use just character as there might be duplicate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment