diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt index e97a928a..530fd851 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt @@ -1168,7 +1168,7 @@ public class RichTextState internal constructor( */ private fun handleAddingCharacters() { val typedCharsCount = tempTextFieldValue.text.length - textFieldValue.text.length - var startTypeIndex = tempTextFieldValue.selection.max - typedCharsCount + var startTypeIndex = textFieldValue.selection.min val typedText = tempTextFieldValue.text.substring( startIndex = startTypeIndex, endIndex = startTypeIndex + typedCharsCount, diff --git a/richeditor-compose/src/commonTest/kotlin/com.mohamedrejeb.richeditor/model/RichTextStateTest.kt b/richeditor-compose/src/commonTest/kotlin/com.mohamedrejeb.richeditor/model/RichTextStateTest.kt index 06da1e2c..f75627df 100644 --- a/richeditor-compose/src/commonTest/kotlin/com.mohamedrejeb.richeditor/model/RichTextStateTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com.mohamedrejeb.richeditor/model/RichTextStateTest.kt @@ -613,4 +613,83 @@ class RichTextStateTest { assertEquals("Testing some text\nTesting some text", richTextState.toText()) } + @OptIn(ExperimentalRichTextApi::class) + @Test + fun testAddNewTextToFirstParagraphWithSelectionOnSecondParagraph() { + // https://github.com/MohamedRejeb/compose-rich-editor/issues/311 + val richTextState = RichTextState( + initialRichParagraphList = listOf( + RichParagraph( + key = 1, + ).also { + it.children.add( + RichSpan( + text = "G", + paragraph = it, + ), + ) + }, + RichParagraph( + key = 2, + ).also { + it.children.add( + RichSpan( + text = "b", + paragraph = it, + ), + ) + } + ) + ) + + richTextState.selection = TextRange(1) + richTextState.onTextFieldValueChange( + TextFieldValue( + text = "Good b", + selection = TextRange(5), + ) + ) + + assertEquals("Good\nb", richTextState.toText()) + } + + @OptIn(ExperimentalRichTextApi::class) + @Test + fun testTextCorrection() { + val richTextState = RichTextState( + initialRichParagraphList = listOf( + RichParagraph( + key = 1, + ).also { + it.children.add( + RichSpan( + text = "Hilo", + paragraph = it, + ), + ) + }, + RichParagraph( + key = 2, + ).also { + it.children.add( + RichSpan( + text = "b", + paragraph = it, + ), + ) + } + ) + ) + + richTextState.selection = TextRange(2) + richTextState.onTextFieldValueChange( + TextFieldValue( + text = "Hello b", + selection = TextRange(5), + ) + ) + + assertEquals("Hello\nb", richTextState.toText()) + } + } \ No newline at end of file