M3 TextField
has a placeholder
parameter where it shows a text when it's focused and empty. But I want to show a placeholder or a hint always as the user is typing. Something similar to search suggestions but more like Github Copilot suggestions which suggest text as you type.
Visually I achieved what I want but currently, when the cursor is moved it's not moving logically I suspect OffsetMapping
is responsible for that but I can't fix it. The problem is when you try to move the cursor it moves but sometimes jumps to the end of the green text instead of moving smoothly.
class MyMaskTransformation(
private val suggestion: String
) : VisualTransformation {
private var suffix: String = ""
override fun filter(text: AnnotatedString): TransformedText {
suffix = if (suggestion.length > text.length)
suggestion.takeLast(suggestion.length - text.length)
else ""
return TransformedText(
offsetMapping = offsetMapping,
text = buildAnnotatedString {
withStyle(SpanStyle(Color.Unspecified)) {
append(text)
}
withStyle(SpanStyle(Color.Gray)) {
append(suffix)
}
}
)
}
private val offsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset < suggestion.length || suggestion.isEmpty()) return offset
return suggestion.length - suffix.length
}
override fun transformedToOriginal(offset: Int): Int {
offset.toString().log()
if (offset == 0) return 0
if (suggestion.length - suffix.length in 1 until offset)
return suggestion.length - suffix.length
return offset
}
}
}