Skip to content

Commit

Permalink
Fix cursor moves to next line when text is added via suggestion
Browse files Browse the repository at this point in the history
  • Loading branch information
MohamedRejeb committed Dec 26, 2024
1 parent 2503395 commit be770b8
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1271,6 +1271,29 @@ public class RichTextState internal constructor(
val activeRichSpan = getOrCreateRichSpanByTextIndex(previousIndex)

if (activeRichSpan != null) {
val isAndroidSuggestion =
activeRichSpan.isLastInParagraph &&
activeRichSpan.textRange.max == startTypeIndex &&
tempTextFieldValue.selection.max == startTypeIndex + typedCharsCount + 1

val typedText =
if (isAndroidSuggestion)
"$typedText "
else
typedText

if (isAndroidSuggestion) {
val beforeText =
tempTextFieldValue.text.substring(0, startTypeIndex + typedCharsCount)

val afterText =
tempTextFieldValue.text.substring(startTypeIndex + typedCharsCount)

tempTextFieldValue = tempTextFieldValue.copy(
text = "$beforeText $afterText",
)
}

if (startTypeIndex < activeRichSpan.textRange.min) {
val indexDiff = activeRichSpan.textRange.min - startTypeIndex
val beforeTypedText = tempTextFieldValue.text.substring(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1261,4 +1261,42 @@ class RichTextStateTest {
assertEquals("Hello\n\n", state.toText())
}

/**
* Test to mimic the behavior of the Android suggestion.
* Can only reproduced on real device.
*
* [420](https://github.com/MohamedRejeb/compose-rich-editor/issues/420)
*/
@Test
fun testMimicAndroidSuggestion() {
val richTextState = RichTextState()

richTextState.setHtml(
"""
<p>Hi </p>
<p>World! </p>
""".trimIndent()
)

richTextState.printParagraphs()

// Select the text
richTextState.selection = TextRange(3)

// Add text after selection
// What's happening is that the space added after "Kotlin" from the suggestion is being removed.
// It's been considered as the trailing space for the paragraph.
// Which will lead to the selection being at the start of the next paragraph.
// To fix this we need to add a space after the selection.
richTextState.onTextFieldValueChange(
TextFieldValue(
text = "Hi Kotlin World! ",
selection = TextRange(10)
)
)

assertEquals(TextRange(10), richTextState.selection)
assertEquals("Hi Kotlin World! ", richTextState.annotatedString.text)
}

}

0 comments on commit be770b8

Please sign in to comment.