Visual Transformation for any mask in Jetpack Compose TextField

When migrating from the existing View system to Jetpack Compose, we can find some little puzzles that we were used to solving easily before. One is to implement text masks for Jetpack Compose TextFields.

Date Visual Transformation

To create a date mask, we implement the filter method of the VisualTransformation interface. With the filter method, we change the visual output of the given text. In addition to the text, we return an implementation of the OffsetMapping interface. This implementation provides bidirectional offset mapping between original and transformed text. The composable will call it for converting offsets for various reasons, cursor drawing position, text selection by gesture, etc.

Visual Transformation for any mask

Depending on the mask it is not so easy to create the filtered text and the offset translator. Therefore, the goal here is to create a Visual Transformation implementation that accepts any type of mask.
We pass the mask when creating the object and following the same logic of DateVisualTransformation we implement the filter method for any mask.

Using the MaskVisualTransformation

Important: we can’t forget to limit the input length, the Visual Transformation doesn’t change the input value, only change its visual.

Brazilian number mask

Random mask

If you have any questions, suggestions, or improvements, feel free to contact me on LinkedIn.
Thank you!