Fixes a white space after a new line

This commit is contained in:
Vitor Pamplona 2024-05-20 15:15:06 -04:00
parent beb901120e
commit 24f7991116
2 changed files with 12 additions and 3 deletions

View File

@ -118,4 +118,13 @@ class TextFieldValueExtensionTest {
assertEquals("a http://a.b b", next.text)
assertEquals(TextRange(13, 13), next.selection)
}
@Test
fun testInsertAfterNewLine() {
val current = TextFieldValue("ab\n\n", selection = TextRange(4, 4))
val next = current.insertUrlAtCursor("https://i.nostr.build/zdMW4.jpg")
assertEquals("ab\n\nhttps://i.nostr.build/zdMW4.jpg", next.text)
assertEquals(TextRange(35, 35), next.selection)
}
}

View File

@ -24,15 +24,15 @@ import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
fun TextFieldValue.insertUrlAtCursor(url: String): TextFieldValue {
var toInsert = url
if (selection.start > 0 && text[selection.start - 1] != ' ') {
var toInsert = url.trim()
if (selection.start > 0 && text[selection.start - 1] != ' ' && text[selection.start - 1] != '\n') {
toInsert = " $toInsert"
}
// takes the position before adding an empty char after the url
val endOfUrlIndex = selection.start + toInsert.length
if (selection.end < text.length && text[selection.end] != ' ') {
if (selection.end < text.length && text[selection.end] != ' ' && text[selection.end] != '\n') {
toInsert = "$toInsert "
}