Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions .maestro/enrichedInput/flows/link_detection_events.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
appId: swmansion.enriched.example
---
# PR #869 - fix(android): events batching
# Link events must carry final values, never stale ones from the middle of an edit
- launchApp

- tapOn:
id: "toggle-screen-button"

- tapOn:
id: "editor-input"

- runFlow:
file: "../subflows/insert_link.yaml"
env:
LINK_TEXT: "foo supercalifragilistic baz"
LINK_URL: "https://swmansion.com"

- extendedWaitUntil:
notVisible:
id: "link-modal-submit-button"
timeout: 10000

# Leave a collapsed caret inside the link ("foo | baz"), then press Enter, which splits the link in two
- doubleTapOn:
id: "editor-input"
point: "50%, 50%"

- pressKey: Backspace

- pressKey: Enter

- tapOn:
id: "blur-button"

- tapOn:
id: "toggle-html-button"

- assertVisible:
id: "link-events-output"
text: "(?s).*\\| baz\\[\\d+,\\d+\\].*"

# The link from before the split (still containing the newline) must not be reported
- assertNotVisible:
id: "link-events-output"
text: "(?s).*foo\\s*\\n\\s*baz\\[0,\\d+\\].*"

# Toggling a code block off restores the link, toggling it on removes it again
- tapOn:
id: "clear-button"

- tapOn:
id: "focus-button"

- tapOn:
id: "toolbar-code-block"

- inputText: "Hello swmansion.com"

- tapOn:
id: "toolbar-code-block"

- tapOn:
id: "blur-button"

- assertVisible:
id: "link-events-output"
text: "(?s).*swmansion\\.com\\[\\d+,\\d+\\].*"

# Android only: iOS doesn't treat a caret at the link's end as inside it, so it sends no clear event here
- runFlow:
when:
platform: Android
commands:
- tapOn:
id: "focus-button"

- tapOn:
id: "toolbar-code-block"

- tapOn:
id: "blur-button"

- assertVisible:
id: "link-events-output"
text: "(?s).*swmansion\\.com\\[\\d+,\\d+\\] \\| \\[0,0\\].*"
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ class EnrichedTextInputView :
val customStyles: CustomStyles? = CustomStyles(this)
var isDuringTransaction: Boolean = false
var isRemovingMany: Boolean = false
private var eventsBatchDepth: Int = 0
val isBatchingEvents: Boolean
get() = eventsBatchDepth > 0
var scrollEnabled: Boolean = true
var allowFontScaling: Boolean = EnrichedConstants.ALLOW_FONT_SCALING_DEFAULT
set(value) {
Expand Down Expand Up @@ -125,6 +128,7 @@ class EnrichedTextInputView :

var linkRegex: Pattern? = Patterns.WEB_URL
var spanWatcher: EnrichedSpanWatcher? = null
var textWatcher: EnrichedTextWatcher? = null
var layoutManager: EnrichedTextInputViewLayoutManager = EnrichedTextInputViewLayoutManager(this)

var shouldEmitHtml: Boolean = false
Expand Down Expand Up @@ -239,8 +243,11 @@ class EnrichedTextInputView :
val spanWatcher = EnrichedSpanWatcher(this)
this.spanWatcher = spanWatcher

setEditableFactory(EnrichedEditableFactory(spanWatcher))
addTextChangedListener(EnrichedTextWatcher(this))
setEditableFactory(EnrichedEditableFactory(this, spanWatcher))

val textWatcher = EnrichedTextWatcher(this)
this.textWatcher = textWatcher
addTextChangedListener(textWatcher)

// Handle checkbox list item clicks
this.setCheckboxClickListener()
Expand Down Expand Up @@ -398,38 +405,40 @@ class EnrichedTextInputView :
}

fun handleTextPaste(item: ClipData.Item) {
val currentText = text as Spannable
val start = selectionStart.coerceAtLeast(0)
val end = selectionEnd.coerceAtLeast(0)
val lengthBefore = currentText.length

val pastedSpannable: Spannable =
when {
item.htmlText != null -> {
val parsed = parseText(item.htmlText)
(parsed as? Spannable) ?: return
}
batchEvents {
val currentText = text as Spannable
val start = selectionStart.coerceAtLeast(0)
val end = selectionEnd.coerceAtLeast(0)
val lengthBefore = currentText.length

val pastedSpannable: Spannable =
when {
item.htmlText != null -> {
val parsed = parseText(item.htmlText)
(parsed as? Spannable) ?: return@batchEvents
}

item.text != null -> {
SpannableString(item.text.toString())
}
item.text != null -> {
SpannableString(item.text.toString())
}

else -> {
return
else -> {
return@batchEvents
}
}
}

val finalText = currentText.mergeSpannables(start, end, pastedSpannable, htmlStyle)
setValue(finalText, false)
val finalText = currentText.mergeSpannables(start, end, pastedSpannable, htmlStyle)
setValue(finalText, false)

// replacement-safe: oldLength - removed + inserted
val insertedLength = finalText.length - (lengthBefore - (end - start))
val pasteEnd = (start + insertedLength).coerceIn(0, finalText.length)
setSelection(pasteEnd)
// replacement-safe: oldLength - removed + inserted
val insertedLength = finalText.length - (lengthBefore - (end - start))
val pasteEnd = (start + insertedLength).coerceIn(0, finalText.length)
setSelection(pasteEnd)

// Update links and mentions in the newly pasted range
val editable = text as? Editable ?: return
parametrizedStyles?.afterTextChanged(editable, start.coerceAtMost(pasteEnd), pasteEnd)
// Update links and mentions in the newly pasted range
val editable = text as? Editable ?: return@batchEvents
parametrizedStyles?.afterTextChanged(editable, start.coerceAtMost(pasteEnd), pasteEnd)
}
}

fun requestFocusProgrammatically() {
Expand Down Expand Up @@ -969,23 +978,27 @@ class EnrichedTextInputView :
}

fun verifyAndToggleStyle(name: String) {
val isValid = verifyStyle(name)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(name)
if (!isValid) return@batchEvents

val (rangeStart, rangeEnd) = getTargetRange(name)
val (rangeStart, rangeEnd) = getTargetRange(name)

runAsATransaction {
toggleStyle(name)
}
runAsATransaction {
toggleStyle(name)
}

parametrizedStyles?.onStyleToggled(name, rangeStart, rangeEnd)
parametrizedStyles?.onStyleToggled(name, rangeStart, rangeEnd)
}
}

fun toggleCheckboxListItem(checked: Boolean) {
val isValid = verifyStyle(EnrichedSpans.CHECKBOX_LIST)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.CHECKBOX_LIST)
if (!isValid) return@batchEvents

listStyles?.toggleCheckboxListStyle(checked)
listStyles?.toggleCheckboxListStyle(checked)
}
}

fun addLink(
Expand All @@ -994,10 +1007,12 @@ class EnrichedTextInputView :
text: String,
url: String,
) {
val isValid = verifyStyle(EnrichedSpans.LINK)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.LINK)
if (!isValid) return@batchEvents

parametrizedStyles?.setLinkSpan(getActualIndex(start), getActualIndex(end), text, url)
parametrizedStyles?.setLinkSpan(getActualIndex(start), getActualIndex(end), text, url)
}
}

fun removeLink(
Expand All @@ -1012,29 +1027,35 @@ class EnrichedTextInputView :
width: Float,
height: Float,
) {
val isValid = verifyStyle(EnrichedSpans.IMAGE)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.IMAGE)
if (!isValid) return@batchEvents

parametrizedStyles?.setImageSpan(src, width, height)
layoutManager.invalidateLayout()
parametrizedStyles?.setImageSpan(src, width, height)
layoutManager.invalidateLayout()
}
}

fun startMention(indicator: String) {
val isValid = verifyStyle(EnrichedSpans.MENTION)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.MENTION)
if (!isValid) return@batchEvents

parametrizedStyles?.startMention(indicator)
parametrizedStyles?.startMention(indicator)
}
}

fun addMention(
indicator: String,
text: String,
attributes: Map<String, String>,
) {
val isValid = verifyStyle(EnrichedSpans.MENTION)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.MENTION)
if (!isValid) return@batchEvents

parametrizedStyles?.setMentionSpan(text, indicator, attributes)
parametrizedStyles?.setMentionSpan(text, indicator, attributes)
}
}

fun setTextAlignment(alignment: String) {
Expand All @@ -1045,13 +1066,15 @@ class EnrichedTextInputView :
}

fun setStyle(styleJSON: String) {
val isValid = verifyStyle(EnrichedSpans.CUSTOM_STYLE)
if (!isValid) return
batchEvents {
val isValid = verifyStyle(EnrichedSpans.CUSTOM_STYLE)
if (!isValid) return@batchEvents

runAsATransaction {
customStyles?.setStyle(styleJSON)
runAsATransaction {
customStyles?.setStyle(styleJSON)
}
layoutManager.invalidateLayout()
}
layoutManager.invalidateLayout()
}

fun requestHTML(requestId: Int) {
Expand All @@ -1072,12 +1095,36 @@ class EnrichedTextInputView :
// Eg. removing conflicting styles -> changing text -> applying spans
// In such scenario we want to prevent from handling side effects (eg. onTextChanged)
fun runAsATransaction(block: () -> Unit) {
batchEvents {
Comment thread
szydlovsky marked this conversation as resolved.
Resolved
try {
isDuringTransaction = true
block()
} finally {
isDuringTransaction = false
}
}
}

// Events are emitted once all changes are done, so they never carry intermediate state
fun batchEvents(block: () -> Unit) {
eventsBatchDepth++
try {
isDuringTransaction = true
block()
} finally {
isDuringTransaction = false
eventsBatchDepth--
}

if (eventsBatchDepth == 0) emitBatchedEvents()
}

private fun emitBatchedEvents() {
val spannable = text ?: return

textWatcher?.emitPendingEvent(spannable)
// Spans could have changed after the last validation, so links and mentions are detected again
selection?.validateParametrizedStyles()
spanState?.emitStateChangeEvent()
Comment thread
szydlovsky marked this conversation as resolved.
Resolved
spanWatcher?.emitPendingEvent(spannable)
}

private fun forceScrollToSelection() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,35 @@ package com.swmansion.enriched.textinput.utils
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import com.swmansion.enriched.textinput.EnrichedTextInputView
import com.swmansion.enriched.textinput.watchers.EnrichedSpanWatcher

class EnrichedEditableFactory(
private val view: EnrichedTextInputView,
private val watcher: EnrichedSpanWatcher,
) : Editable.Factory() {
override fun newEditable(source: CharSequence): Editable {
val s = source as? SpannableStringBuilder ?: SpannableStringBuilder(source)
val s = source as? EnrichedEditable ?: EnrichedEditable(view, source)
s.removeSpan(watcher)
s.setSpan(watcher, 0, s.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
return s
}
}

class EnrichedEditable(
private val view: EnrichedTextInputView,
source: CharSequence,
) : SpannableStringBuilder(source) {
// Every edit goes through here, hence the nested events batching.
override fun replace(
start: Int,
end: Int,
tb: CharSequence,
tbstart: Int,
tbend: Int,
): SpannableStringBuilder {
var result: SpannableStringBuilder = this
view.batchEvents { result = super.replace(start, end, tb, tbstart, tbend) }
return result
}
}
Loading