Skip to content

Instantly share code, notes, and snippets.

@daniatitienei
Created August 20, 2022 14:09
Show Gist options
  • Save daniatitienei/de7e91ac310211e6c28487a8289c1c9a to your computer and use it in GitHub Desktop.
Save daniatitienei/de7e91ac310211e6c28487a8289c1c9a to your computer and use it in GitHub Desktop.
class CardNumberVisualTransformation : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
val trimmed = if (text.length >= 16) text.text.substring(0..15) else text.text
var out = ""
for (i in trimmed.indices) {
out += trimmed[i]
if (i % 4 == 3 && i != 15) out += " "
}
val creditCardOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 3) return offset
if (offset <= 7) return offset + 1
if (offset <= 11) return offset + 2
if (offset <= 16) return offset + 3
return 19
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= 4) return offset
if (offset <= 9) return offset - 1
if (offset <= 14) return offset - 2
if (offset <= 19) return offset - 3
return 16
}
}
return TransformedText(AnnotatedString(out), creditCardOffsetTranslator)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment