diff --git a/android/src/main/java/com/swmansion/enriched/EnrichedTextInputView.kt b/android/src/main/java/com/swmansion/enriched/EnrichedTextInputView.kt index da74919..ee3732b 100644 --- a/android/src/main/java/com/swmansion/enriched/EnrichedTextInputView.kt +++ b/android/src/main/java/com/swmansion/enriched/EnrichedTextInputView.kt @@ -59,6 +59,12 @@ class EnrichedTextInputView : AppCompatEditText { val mentionHandler: MentionHandler? = MentionHandler(this) var htmlStyle: HtmlStyle = HtmlStyle(this, null) + set(value) { + if (field != value) { + field = value + reapplyTextWithNewStyles() + } + } var spanWatcher: EnrichedSpanWatcher? = null var layoutManager: EnrichedTextInputViewLayoutManager = EnrichedTextInputViewLayoutManager(this) @@ -577,6 +583,27 @@ class EnrichedTextInputView : AppCompatEditText { } } + private fun reapplyTextWithNewStyles() { + val currentText = text + if (currentText != null && currentText.isNotEmpty()) { + runAsATransaction { + val currentHtml = EnrichedParser.toHtml(currentText as Spannable) + val newText = parseText(currentHtml) + + val currentSelectionStart = selectionStart + val currentSelectionEnd = selectionEnd + + setText(newText) + + val newLength = text?.length ?: 0 + val safeStart = currentSelectionStart.coerceIn(0, newLength) + val safeEnd = currentSelectionEnd.coerceIn(0, newLength) + setSelection(safeStart, safeEnd) + layoutManager.invalidateLayout() + } + } + } + override fun onAttachedToWindow() { super.onAttachedToWindow() diff --git a/example/src/App.tsx b/example/src/App.tsx index 9632cc0..f437a48 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -84,6 +84,8 @@ export default function App() { const [isImageModalOpen, setIsImageModalOpen] = useState(false); const [isValueModalOpen, setIsValueModalOpen] = useState(false); const [currentHtml, setCurrentHtml] = useState(''); + const [currentHtmlStyle, setCurrentHtmlStyle] = + useState(htmlStyle); const [selection, setSelection] = useState(); const [stylesState, setStylesState] = useState(DEFAULT_STYLE); @@ -273,6 +275,12 @@ export default function App() { closeChannelMentionPopup(); }; + const handleChangeHtmlStyle = () => { + setCurrentHtmlStyle((style) => + style === htmlStyle ? anotherHtmlStyle : htmlStyle + ); + }; + const handleFocusEvent = () => { console.log('Input focused'); }; @@ -304,7 +312,7 @@ export default function App() { ref={ref} mentionIndicators={['@', '#']} style={styles.editorInput} - htmlStyle={htmlStyle} + htmlStyle={currentHtmlStyle} placeholder="Type something here..." placeholderTextColor="rgb(0, 26, 114)" selectionColor="deepskyblue" @@ -336,6 +344,11 @@ export default function App() {