Skip to content

Commit 39bf99b

Browse files
authored
Merge pull request #978 from wordpress-mobile/fix/add-block-when-no-blocks-present
Fix issue when adding image when no blocks are present
2 parents 412af29 + 67e2eac commit 39bf99b

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

aztec/src/main/kotlin/org/wordpress/aztec/formatting/LineBlockFormatter.kt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,6 @@ class LineBlockFormatter(editor: AztecText) : AztecFormatter(editor) {
182182
}
183183
} else {
184184
ssb.append("\n")
185-
186185
val ssbLength = ssb.length
187186
editableText.getSpans(position, position + ssbLength, IAztecBlockSpan::class.java).filter {
188187
it !is AztecMediaSpan && editableText.getSpanStart(it) == position
@@ -232,13 +231,20 @@ class LineBlockFormatter(editor: AztecText) : AztecFormatter(editor) {
232231
}
233232

234233
private fun getEndOfBlock(): Int {
234+
if (selectionStart == 0 && selectionEnd == 0) {
235+
return 0
236+
}
235237
var position = 0
236238
editableText.getSpans(selectionStart, selectionEnd, IAztecBlockSpan::class.java).forEach {
237239
val spanEnd = editableText.getSpanEnd(it)
238240
if (spanEnd > position) {
239241
position = spanEnd
240242
}
241243
}
244+
if (position <= 0 && selectionEnd != 0) {
245+
// If the text contains "\n" return that as the position, else set the position to the end of the text
246+
position = editableText.indexOf("\n", selectionEnd).takeIf { it >= 0 } ?: editableText.length
247+
}
242248
return position
243249
}
244250
}

aztec/src/test/kotlin/org/wordpress/aztec/ImageBlockTest.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,30 @@ class ImageBlockTest {
137137

138138
Assert.assertEquals("<h1>Headline 1</h1><hr /><h2>Headline 2</h2>", editText.toHtml())
139139
}
140+
141+
@Test
142+
@Throws(Exception::class)
143+
fun addImageAtTheEndWhenNoBlocksPresent() {
144+
editText.fromHtml("Test 1<br>test 2<br>test 3")
145+
146+
editText.setSelection(editText.editableText.indexOf("3"))
147+
val attributes = AztecAttributes()
148+
attributes.setValue("id", "1234")
149+
editText.insertImage(null, attributes)
150+
151+
Assert.assertEquals("Test 1<br>test 2<br>test 3<img id=\"1234\" />", editText.toHtml())
152+
}
153+
154+
@Test
155+
@Throws(Exception::class)
156+
fun addImageInTheMiddleWhenNoBlocksPresent() {
157+
editText.fromHtml("Test 1<br>test 2<br>test 3")
158+
159+
editText.setSelection(editText.editableText.indexOf("2"))
160+
val attributes = AztecAttributes()
161+
attributes.setValue("id", "1234")
162+
editText.insertImage(null, attributes)
163+
164+
Assert.assertEquals("Test 1<br>test 2<img id=\"1234\" /><br>test 3", editText.toHtml())
165+
}
140166
}

0 commit comments

Comments
 (0)