feat(composer): fold large pastes into text attachments (#11442)

This commit is contained in:
Chris Deeming authored and GitHub committed 2026-09-12 17:28:28 -07:00
1 parent 36caf200c2
commit 68c2277f50
77 files changed
+3278 -465

No files matched your search

@@ -8,6 +8,10 @@ android {
namespace 'expo.modules.t3composereditor'
compileSdk rootProject.ext.compileSdkVersion
testOptions {
unitTests.includeAndroidResources = true
}
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
@@ -17,4 +21,12 @@ android {
dependencies {
implementation project(':expo-modules-core')
implementation project(':t3tools-mobile-markdown-text')
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
}
tasks.withType(Test).configureEach {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(21)
}
}
@@ -116,6 +116,12 @@ class T3ComposerEditorModule : Module() {
Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean ->
view.setSpellCheck(spellCheck)
}
Prop("textPasteThresholdBytes") { view: T3ComposerEditorView, threshold: Int ->
view.setTextPasteThresholdBytes(threshold)
}
Prop("maxInputChars") { view: T3ComposerEditorView, maxInputChars: Int ->
view.setMaxInputChars(maxInputChars)
}
Events(
"onComposerChange",
@@ -125,6 +131,7 @@ class T3ComposerEditorModule : Module() {
"onComposerPasteImages",
"onComposerContextPress",
"onComposerPasteContext",
"onComposerPasteText",
"onComposerContentSizeChange",
)
@@ -1,7 +1,8 @@
package expo.modules.t3composereditor
import android.content.Context
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Color
import android.graphics.Canvas
import android.graphics.Paint
@@ -48,6 +49,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
private val onComposerPasteImages by EventDispatcher()
private val onComposerContextPress by EventDispatcher()
private val onComposerPasteContext by EventDispatcher()
private val onComposerPasteText by EventDispatcher()
private val onComposerContentSizeChange by EventDispatcher()
private var applyingNativeValue = false
private var desiredLineHeightPx = 0
@@ -86,7 +88,16 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
editor.pasteImagesListener = { uris ->
onComposerPasteImages(mapOf("uris" to uris))
}
editor.pasteContextListener = { payload -> onComposerPasteContext(payload) }
editor.pasteContextListener = { payload ->
nativeEventCount += 1
onComposerPasteContext(
payload + mapOf(
"value" to editor.text.toString(),
"eventCount" to nativeEventCount,
"selection" to currentSelectionPayload(),
)
)
}
val contextGestures =
GestureDetector(
context,
@@ -120,6 +131,17 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
contextGestures.onTouchEvent(event)
false
}
editor.pasteTextListener = { text, start, end ->
nativeEventCount += 1
onComposerPasteText(
mapOf(
"value" to editor.text.toString(),
"eventCount" to nativeEventCount,
"text" to text,
"selection" to currentSelectionPayload(start, end),
),
)
}
editor.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
onComposerFocus(emptyMap<String, Any>())
@@ -305,6 +327,14 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
updateInputFlags()
}
fun setTextPasteThresholdBytes(threshold: Int) {
editor.textPasteThresholdBytes = threshold
}
fun setMaxInputChars(maxInputChars: Int) {
editor.maxInputChars = maxInputChars
}
fun focusEditor() {
editor.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
@@ -365,10 +395,13 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
editor.highlightColor = defaultHighlightColor
}
private fun currentSelectionPayload(): Map<String, Int> =
private fun currentSelectionPayload(
start: Int = editor.selectionStart,
end: Int = editor.selectionEnd
): Map<String, Int> =
mapOf(
"start" to editor.selectionStart.coerceAtLeast(0),
"end" to editor.selectionEnd.coerceAtLeast(0),
"start" to minOf(start, end).coerceAtLeast(0),
"end" to maxOf(start, end).coerceAtLeast(0),
)
private fun emitSelectionChange(start: Int, end: Int) {
@@ -379,7 +412,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
onComposerSelectionChange(
mapOf(
"value" to editor.text.toString(),
"selection" to mapOf("start" to start, "end" to end),
"selection" to currentSelectionPayload(start, end),
"eventCount" to nativeEventCount,
),
)
@@ -544,11 +577,14 @@ private fun parseTokens(value: String): List<ComposerToken> = try {
emptyList()
}
private class SelectionAwareEditText(context: Context) : EditText(context) {
internal class SelectionAwareEditText(context: Context) : EditText(context) {
var readOnly = false
var selectionListener: ((Int, Int) -> Unit)? = null
var pasteImagesListener: ((List<String>) -> Unit)? = null
var pasteContextListener: ((Map<String, String>) -> Unit)? = null
var pasteTextListener: ((String, Int, Int) -> Unit)? = null
var textPasteThresholdBytes = 0
var maxInputChars = Int.MAX_VALUE
var clipboardFragment = ""
private fun deleteChip(backwards: Boolean): Boolean {
@@ -602,7 +638,6 @@ private class SelectionAwareEditText(context: Context) : EditText(context) {
super.deleteSurroundingTextInCodePoints(beforeLength, afterLength)
}
}
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
super.onSelectionChanged(selStart, selEnd)
selectionListener?.invoke(selStart, selEnd)
@@ -615,6 +650,10 @@ private class SelectionAwareEditText(context: Context) : EditText(context) {
}
val handled = when {
id == android.R.id.copy || id == android.R.id.cut -> copyContext(id == android.R.id.cut)
id == android.R.id.pasteAsPlainText -> {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
pasteInterceptedText(clipboard?.primaryClip, foldLargeText = false)
}
pasting -> pasteContextOrImages()
else -> false
}
@@ -636,6 +675,10 @@ private class SelectionAwareEditText(context: Context) : EditText(context) {
pasteContextListener?.invoke(payload)
return true
}
return pasteImagesOrInterceptedText()
}
private fun pasteImagesOrInterceptedText(): Boolean {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
val clip = clipboard?.primaryClip
val imageUris = buildList {
@@ -648,7 +691,48 @@ private class SelectionAwareEditText(context: Context) : EditText(context) {
}
}
}
if (imageUris.isNotEmpty()) pasteImagesListener?.invoke(imageUris)
return imageUris.isNotEmpty()
return when {
imageUris.isNotEmpty() -> {
pasteImagesListener?.invoke(imageUris)
true
}
else -> pasteInterceptedText(clip)
}
}
private fun pasteInterceptedText(clip: ClipData?, foldLargeText: Boolean = true): Boolean {
val text = if (textPasteThresholdBytes > 0) clip?.plainText() else null
if (text.isNullOrEmpty()) return false
val start = minOf(selectionStart, selectionEnd).coerceIn(0, length())
val end = maxOf(selectionStart, selectionEnd).coerceIn(start, length())
val exceedsInputLimit = length().toLong() - (end - start) + text.length > maxInputChars
val shouldFold = foldLargeText && (
text.length >= textPasteThresholdBytes ||
text.toByteArray(Charsets.UTF_8).size >= textPasteThresholdBytes
)
val shouldIntercept = exceedsInputLimit || shouldFold
if (shouldIntercept) {
pasteTextListener?.invoke(text, start, end)
}
// Let EditText perform ordinary pastes, retaining its native undo history.
return shouldIntercept
}
// coerceToText opens content: URIs synchronously. Leave URI-backed
// clipboard items to Android's normal paste path so the UI thread never
// reads an arbitrary provider just to measure a text paste.
private fun ClipData.plainText(): String? =
takeIf { itemCount > 0 }
?.getItemAt(0)
?.takeIf { it.uri == null }
?.coerceToText(context)
?.toString()
?.takeIf(String::isNotEmpty)
override fun onKeyShortcut(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_V && event.isCtrlPressed && event.isShiftPressed) {
return onTextContextMenuItem(android.R.id.pasteAsPlainText)
}
return super.onKeyShortcut(keyCode, event)
}
}
@@ -0,0 +1,123 @@
package expo.modules.t3composereditor
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.KeyEvent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [36], manifest = Config.NONE)
class ComposerPasteTest {
private val context = RuntimeEnvironment.getApplication()
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
private val editor = SelectionAwareEditText(context).apply {
textPasteThresholdBytes = 32 * 1024
maxInputChars = 120_000
}
private fun pasteAsText(): Boolean = editor.onKeyShortcut(
KeyEvent.KEYCODE_V,
KeyEvent(
0,
0,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_V,
0,
KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON
)
)
@Test
fun shortcutKeepsLargeTextInlineAndUndoable() {
val pasted = "x".repeat(32 * 1024)
clipboard.setPrimaryClip(ClipData.newPlainText("test", pasted))
editor.setText("before old after")
editor.setSelection(10, 7)
editor.pasteTextListener = { _, _, _ -> error("Inline paste must stay native") }
assertTrue(pasteAsText())
assertEquals("before $pasted after", editor.text.toString())
assertTrue(editor.onTextContextMenuItem(android.R.id.undo))
assertEquals("before old after", editor.text.toString())
}
@Test
fun shortcutInterceptsInputLimitOverflowWithoutChangingTheSelection() {
clipboard.setPrimaryClip(ClipData.newPlainText("test", "hello"))
editor.setText("x".repeat(119_999))
editor.setSelection(10, 7)
var intercepted: Triple<String, Int, Int>? = null
editor.pasteTextListener = { text, start, end -> intercepted = Triple(text, start, end) }
assertTrue(pasteAsText())
assertEquals(Triple("hello", 7, 10), intercepted)
assertEquals(119_999, editor.length())
assertEquals(10, editor.selectionStart)
assertEquals(7, editor.selectionEnd)
}
@Test
fun shortcutAllowsReplacementAtTheInputLimit() {
clipboard.setPrimaryClip(ClipData.newPlainText("test", "hello"))
editor.setText("x".repeat(120_000))
editor.setSelection(12, 7)
editor.pasteTextListener = { _, _, _ -> error("Replacement fits the input limit") }
assertTrue(pasteAsText())
assertEquals("hello", editor.text.substring(7, 12))
assertEquals(120_000, editor.length())
}
@Test
fun regularPasteStillFoldsAtTheUtf8Threshold() {
val pasted = "é".repeat(16 * 1024)
clipboard.setPrimaryClip(ClipData.newPlainText("test", pasted))
editor.setText("old")
editor.setSelection(0, 3)
var intercepted: String? = null
editor.pasteTextListener = { text, _, _ -> intercepted = text }
assertTrue(editor.onTextContextMenuItem(android.R.id.paste))
assertEquals(pasted, intercepted)
assertEquals("old", editor.text.toString())
}
@Test
fun shortcutPastesStructuredClipboardAsText() {
clipboard.setPrimaryClip(
ClipData.newHtmlText(
"test",
"plain text",
"<pre data-t3-context-fragment=\"x\">plain text</pre>"
)
)
editor.setSelection(0)
editor.pasteContextListener = { error("Paste as Text must not import structured context") }
assertTrue(pasteAsText())
assertEquals("plain text", editor.text.toString())
}
@Test
fun readOnlyShortcutDoesNotPasteOrEmitAnEvent() {
clipboard.setPrimaryClip(ClipData.newPlainText("test", "x".repeat(120_001)))
editor.setText("unchanged")
editor.setSelection(editor.length())
editor.readOnly = true
var intercepted: String? = null
editor.pasteTextListener = { text, _, _ -> intercepted = text }
assertFalse(pasteAsText())
assertEquals("unchanged", editor.text.toString())
assertNull(intercepted)
}
}
@@ -87,6 +87,12 @@ public class T3ComposerEditorModule: Module {
Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in
view.setSpellCheck(spellCheck)
}
Prop("textPasteThresholdBytes") { (view: T3ComposerEditorView, threshold: Int) in
view.setTextPasteThresholdBytes(threshold)
}
Prop("maxInputChars") { (view: T3ComposerEditorView, maxInputChars: Int) in
view.setMaxInputChars(maxInputChars)
}
Events(
"onComposerChange",
@@ -97,6 +103,7 @@ public class T3ComposerEditorModule: Module {
"onComposerPasteImages",
"onComposerContextPress",
"onComposerPasteContext",
"onComposerPasteText",
"onComposerContentSizeChange"
)
@@ -86,10 +86,14 @@ private final class ComposerTextView: UITextView {
var onPasteImages: (([String]) -> Void)?
var onPasteContext: (([String: String]) -> Void)?
var onPasteText: ((String, NSRange) -> Void)?
var clipboardFragment = ""
var onAttributedMutation: (() -> Void)?
var onSubmit: (() -> Void)?
var isReadOnly = false
var textPasteThresholdBytes = 0
var maxInputChars = Int.max
private var bypassTextPasteInterception = false
override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
@@ -101,6 +105,16 @@ private final class ComposerTextView: UITextView {
submit.discoverabilityTitle = "Send Message"
submit.wantsPriorityOverSystemBehavior = true
commands.append(submit)
if textPasteThresholdBytes > 0 {
let pasteAsText = UIKeyCommand(
input: "v",
modifierFlags: [.command, .shift],
action: #selector(pasteInline(_:))
)
pasteAsText.discoverabilityTitle = "Paste as Text"
pasteAsText.wantsPriorityOverSystemBehavior = true
commands.append(pasteAsText)
}
return commands
}
@@ -108,6 +122,15 @@ private final class ComposerTextView: UITextView {
onSubmit?()
}
@objc private func pasteInline(_ sender: UIKeyCommand) {
guard !isReadOnly else {
return
}
bypassTextPasteInterception = true
defer { bypassTextPasteInterception = false }
paste(sender)
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if isReadOnly && Self.readOnlyActions.contains(NSStringFromSelector(action)) {
return false
@@ -150,9 +173,28 @@ private final class ComposerTextView: UITextView {
return
}
}
if !bypassTextPasteInterception,
let text = pasteboard.string, shouldInterceptTextPaste(text) {
onPasteText?(text, selectedRange)
return
}
super.paste(sender)
}
private func shouldInterceptTextPaste(_ text: String) -> Bool {
guard textPasteThresholdBytes > 0, !text.isEmpty else { return false }
let pastedLength = (text as NSString).length
if pastedLength >= textPasteThresholdBytes || text.utf8.count >= textPasteThresholdBytes {
return true
}
// Chips occupy one display character but expand to their source in the
// submitted message. Measure that source, including the replaced selection.
let sourceLength = sourceOffset(forDisplayOffset: attributedText.length)
let selectedLength = sourceOffset(forDisplayOffset: NSMaxRange(selectedRange)) -
sourceOffset(forDisplayOffset: selectedRange.location)
return sourceLength - selectedLength + pastedLength > maxInputChars
}
override func deleteBackward() {
guard !isReadOnly else {
return
@@ -368,6 +410,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
let onComposerPasteImages = EventDispatcher()
let onComposerContextPress = EventDispatcher()
let onComposerPasteContext = EventDispatcher()
let onComposerPasteText = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
public required init(appContext: AppContext? = nil) {
@@ -387,7 +430,25 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
self?.onComposerPasteImages(["uris": urls])
}
textView.onPasteContext = { [weak self] context in
self?.onComposerPasteContext(context)
guard let self else { return }
let selection = self.sourceSelection()
self.nativeEventCount += 1
var payload: [String: Any] = context
payload["value"] = self.textView.serializedText()
payload["eventCount"] = self.nativeEventCount
payload["selection"] = ["start": selection.start, "end": selection.end]
self.onComposerPasteContext(payload)
}
textView.onPasteText = { [weak self] text, _ in
guard let self else { return }
let selection = self.sourceSelection()
self.nativeEventCount += 1
self.onComposerPasteText([
"value": self.textView.serializedText(),
"eventCount": self.nativeEventCount,
"text": text,
"selection": ["start": selection.start, "end": selection.end],
])
}
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
@@ -596,6 +657,14 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
textView.spellCheckingType = spellCheck ? .yes : .no
}
func setTextPasteThresholdBytes(_ threshold: Int) {
textView.textPasteThresholdBytes = threshold
}
func setMaxInputChars(_ maxInputChars: Int) {
textView.maxInputChars = maxInputChars
}
func focusEditor() {
textView.becomeFirstResponder()
}
@@ -33,6 +33,15 @@ using namespace facebook::react;
@end
@implementation T3ContextCopyTextView
// Read-only text still supports selecting the entire document after selecting a word.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(selectAll:)) {
return self.selectable && self.text.length > 0 && self.selectedRange.length < self.text.length;
}
return [super canPerformAction:action withSender:sender];
}
- (void)copy:(id)sender
{
NSRange selected = self.selectedRange;