Skip to content

Commit

Permalink
Update swap amount input behavior
Browse files Browse the repository at this point in the history
- When non focused show digits from the starting
- When became focused set the cursor to the end
  • Loading branch information
abdrasulov committed Mar 27, 2024
1 parent 2dba7eb commit 1d6614b
Showing 1 changed file with 25 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -782,43 +782,51 @@ private fun AmountInput(
value: BigDecimal?,
onValueChange: (BigDecimal?) -> Unit,
) {
var textFieldValue by rememberSaveable(value, stateSaver = TextFieldValue.Saver) {
val valueStr = value?.toPlainString()
val cursorPosition = valueStr?.length ?: 0

mutableStateOf(
TextFieldValue(
text = valueStr ?: "",
selection = TextRange(cursorPosition)
)
)
var amount by rememberSaveable {
mutableStateOf(value)
}

var textFieldValue by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue(text = amount?.toPlainString() ?: ""))
}

LaunchedEffect(value) {
if (value?.stripTrailingZeros() != amount?.stripTrailingZeros()) {
amount = value

textFieldValue = TextFieldValue(text = amount?.toPlainString() ?: "")
}
}

var setCursorToEnd by remember {
var setCursorToEndOnFocused by remember {
mutableStateOf(false)
}

BasicTextField(
modifier = Modifier
.fillMaxWidth()
.onFocusChanged {
setCursorToEnd = it.isFocused
setCursorToEndOnFocused = it.isFocused

if (!it.isFocused) {
textFieldValue = textFieldValue.copy(selection = TextRange.Zero)
}
},
value = textFieldValue,
onValueChange = { newValue ->
try {
val text = newValue.text
val amount = if (text.isBlank()) {
amount = if (text.isBlank()) {
null
} else {
text.toBigDecimal()
}

textFieldValue = if (setCursorToEnd) {
setCursorToEnd = false
newValue.copy(selection = TextRange(text.length))
if (!setCursorToEndOnFocused) {
textFieldValue = newValue
} else {
newValue
textFieldValue = newValue.copy(selection = TextRange(text.length))
setCursorToEndOnFocused = false
}

onValueChange.invoke(amount)
Expand Down

0 comments on commit 1d6614b

Please sign in to comment.