Last active
October 18, 2024 08:36
-
-
Save Maxim-Kolmogorov/0d8d15bb58b898aea3808a479dc10008 to your computer and use it in GitHub Desktop.
Phone mask for Android Jetpack Compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my.app.android | |
import androidx.compose.ui.text.AnnotatedString | |
import androidx.compose.ui.text.input.OffsetMapping | |
import androidx.compose.ui.text.input.TransformedText | |
import androidx.compose.ui.text.input.VisualTransformation | |
import kotlin.math.absoluteValue | |
class MaskVisualTransformation(private val mask: String): VisualTransformation { | |
private val specialSymbolsIndices = mask.indices.filter { mask[it] != '#' } | |
override fun filter(text: AnnotatedString): TransformedText { | |
var out = "" | |
var maskIndex = 0 | |
text.forEach { char -> | |
while (specialSymbolsIndices.contains(maskIndex)) { | |
out += mask[maskIndex] | |
maskIndex++ | |
} | |
out += char | |
maskIndex++ | |
} | |
return TransformedText(AnnotatedString(out), offsetTranslator()) | |
} | |
private fun offsetTranslator() = object: OffsetMapping { | |
override fun originalToTransformed(offset: Int): Int { | |
val offsetValue = offset.absoluteValue | |
if (offsetValue == 0) return 0 | |
var numberOfHashtags = 0 | |
val masked = mask.takeWhile { | |
if (it == '#') numberOfHashtags++ | |
numberOfHashtags < offsetValue | |
} | |
return masked.length + 1 | |
} | |
override fun transformedToOriginal(offset: Int): Int { | |
return mask.take(offset.absoluteValue).count { it == '#' } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment