The editor supports trigger-driven token insertion (e.g., @mentions, #hashtags, /commands). A trigger is a character that activates a query session. When a user selects a suggestion, the typed text is replaced by an atomic token that behaves as a single unit (e.g., backspacing deletes the entire token).
Note: Trigger APIs are marked @ExperimentalRichTextApi and may change in future releases.
@OptIn(ExperimentalRichTextApi::class)
@Composable
fun MentionsSample() {
val state = rememberRichTextState()
LaunchedEffect(Unit) {
state.registerTrigger(
Trigger(
id = "mention",
char = '@',
style = { SpanStyle(color = Color(0xFF0969DA), fontWeight = FontWeight.Medium) },
)
)
}
Box {
OutlinedRichTextEditor(state = state)
TriggerSuggestions(
state = state,
triggerId = "mention",
suggestions = { query ->
users.filter { it.handle.contains(query, ignoreCase = true) }
},
onSelect = { user ->
RichSpanStyle.Token(
triggerId = "mention",
id = user.id,
label = user.handle, // must start with '@'
)
},
item = { user ->
Column {
Text(user.handle, fontWeight = FontWeight.Medium)
Text(user.name, style = MaterialTheme.typography.bodySmall)
}
},
)
}
}