Skip to content

Commit

Permalink
Merge pull request #243 from MohamedRejeb/1.x
Browse files Browse the repository at this point in the history
Support replacing selected text
  • Loading branch information
MohamedRejeb authored Apr 8, 2024
2 parents 3299d50 + a647f50 commit 0fdb42c
Showing 1 changed file with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ class RichTextState internal constructor(
/**
* Add a link to the text field.
* The link is going to be added after the current selection.
*
* @param text the text of the link.
* @param url the URL of the link.
*/
fun addLink(
text: String,
Expand Down Expand Up @@ -307,6 +310,8 @@ class RichTextState internal constructor(

/**
* Add a link to the selected text.
*
* @param url the URL of the link.
*/
fun addLinkToSelection(
url: String,
Expand All @@ -327,6 +332,8 @@ class RichTextState internal constructor(

/**
* Update the link of the selected text.
*
* @param url the new URL of the link.
*/
fun updateLink(
url: String,
Expand Down Expand Up @@ -363,6 +370,41 @@ class RichTextState internal constructor(
return getLinkRichSpan(richSpan)
}

/**
* Replaces the currently selected text with the provided text.
*
* @param text The new text to be inserted
*/
fun replaceSelectedText(text: String) {
removeSelectedText()
addTextAfterSelection(text = text)
}

private fun addTextAfterSelection(
text: String
) {
addText(
text = text,
index = selection.min
)
}

private fun addText(
text: String,
index: Int,
) {
val beforeText = textFieldValue.text.substring(0, index)
val afterText = textFieldValue.text.substring(selection.max)
val newText = "$beforeText$text$afterText"

onTextFieldValueChange(
newTextFieldValue = textFieldValue.copy(
text = newText,
selection = TextRange(index + text.length),
)
)
}

@Deprecated(
message = "Use toggleCodeSpan instead",
replaceWith = ReplaceWith("toggleCodeSpan()"),
Expand Down Expand Up @@ -1228,6 +1270,36 @@ class RichTextState internal constructor(
}
}

/**
* Removes the selected text from the current text input.
*
* This method removes the text specified by the `selection` from the current text input.
*
* @see removeTextRange
*/
private fun removeSelectedText() {
removeTextRange(selection)
}

/**x
* Removes the specified text range from the current text.
*
* @param textRange the range of text to be removed
*/
private fun removeTextRange(
textRange: TextRange
) {
onTextFieldValueChange(
newTextFieldValue = textFieldValue.copy(
text = textFieldValue.text.removeRange(
startIndex = selection.min,
endIndex = selection.max,
),
selection = TextRange(textRange.min),
)
)
}

/**
* Handles adding or removing the style in [toAddSpanStyle] and [toRemoveSpanStyle] from the selected text.
*/
Expand Down

0 comments on commit 0fdb42c

Please sign in to comment.