Skip to content

Commit

Permalink
Add filter logic to TextField
Browse files Browse the repository at this point in the history
  • Loading branch information
ksharma-xyz committed Nov 11, 2024
1 parent 6f0692a commit 3f824fd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.runtime.Composable
Expand Down Expand Up @@ -53,6 +54,8 @@ fun TextField(
textStyle: TextStyle? = null,
readOnly: Boolean = false,
imeAction: ImeAction = ImeAction.Default,
filter: (CharSequence) -> CharSequence = { it },
maxLength: Int = Int.MAX_VALUE,
onTextChange: (CharSequence) -> Unit = {},
) {
val interactionSource = remember { MutableInteractionSource() }
Expand All @@ -66,7 +69,11 @@ fun TextField(
)

LaunchedEffect(textFieldState.text) {
onTextChange(textFieldState.text)
val filteredText = filter(textFieldState.text).take(maxLength)
if (textFieldState.text != filteredText) {
textFieldState.setTextAndPlaceCursorAtEnd(filteredText.toString())
}
onTextChange(filteredText)
}

CompositionLocalProvider(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ fun SearchStopScreen(
val trimmedText by remember(textFieldText) { derivedStateOf { textFieldText.trim() } }

LaunchedEffect(trimmedText) {
snapshotFlow { trimmedText }.distinctUntilChanged().debounce(250).filter { it.isNotBlank() }
snapshotFlow { trimmedText }
.distinctUntilChanged()
.debounce(250)
.filter { it.isNotBlank() }
.mapLatest { text ->
Timber.d("Query - $text")
onEvent(SearchStopUiEvent.SearchTextChanged(text))
Expand Down Expand Up @@ -107,6 +110,10 @@ fun SearchStopScreen(
.padding(vertical = 12.dp)
.focusRequester(focusRequester)
.padding(horizontal = 16.dp),
maxLength = 30,
filter = { input ->
input.filter { it.isLetterOrDigit() || it.isWhitespace() }
},
) { value ->
Timber.d("value: $value")
textFieldText = value.toString()
Expand Down

0 comments on commit 3f824fd

Please sign in to comment.