11package org.wordpress.aztec.watchers
22
33import android.text.Editable
4+ import android.text.Spanned
45import android.text.TextWatcher
56import org.wordpress.aztec.AztecText
67import org.wordpress.aztec.Constants
78import org.wordpress.aztec.spans.AztecFullWidthImageSpan
9+ import org.wordpress.aztec.spans.FullWidthImageProcessingMarker
810
911class FullWidthImageElementWatcher (val aztecText : AztecText ) : TextWatcher {
1012
@@ -30,18 +32,19 @@ class FullWidthImageElementWatcher(val aztecText: AztecText) : TextWatcher {
3032 }
3133
3234 private fun normalizeEditingAroundImageSpans (count : Int , start : Int ) {
33- if (! aztecText.isTextChangedListenerDisabled ()) {
35+ if (aztecText.text.getSpans( 0 , 0 , FullWidthImageProcessingMarker :: class .java).isEmpty ()) {
3436 val end = start + count
35- val line = aztecText.text.getSpans(end, end , AztecFullWidthImageSpan ::class .java).firstOrNull() ? :
36- aztecText.text.getSpans(start, start , AztecFullWidthImageSpan ::class .java).firstOrNull( )
37+ var lines = aztecText.text.getSpans(start, start , AztecFullWidthImageSpan ::class .java)
38+ lines + = aztecText.text.getSpans(end, end , AztecFullWidthImageSpan ::class .java)
3739
38- if (line != null ) {
39- val changedLineBeginning = aztecText.text.getSpanStart(line ) == end && end - 1 >= 0 &&
40+ lines.distinct().forEach {
41+ val changedLineBeginning = aztecText.text.getSpanStart(it ) == end && end - 1 >= 0 &&
4042 aztecText.text[end - 1 ] != Constants .NEWLINE
41- val changedLineEnd = aztecText.text.getSpanEnd(line ) == start &&
43+ val changedLineEnd = aztecText.text.getSpanEnd(it ) == start && start < aztecText.length() &&
4244 aztecText.text[start] != Constants .NEWLINE
4345
44- aztecText.disableTextChangedListener()
46+ val marker = FullWidthImageProcessingMarker ()
47+ aztecText.text.setSpan(marker, 0 , 0 , Spanned .SPAN_MARK_MARK )
4548
4649 if (changedLineBeginning) {
4750 // if characters added, insert a newline before the line
@@ -66,11 +69,11 @@ class FullWidthImageElementWatcher(val aztecText: AztecText) : TextWatcher {
6669 insertVisualNewline(start)
6770 } else {
6871 // if text deleted, remove the line
69- aztecText.text.delete(start - 2 , start)
72+ aztecText.text.delete(aztecText.text.getSpanStart(it) , start)
7073 }
7174 }
7275
73- aztecText.enableTextChangedListener( )
76+ aztecText.text.removeSpan(marker )
7477 }
7578 }
7679 }
0 commit comments