diff --git a/.playwright/tests/mentions.spec.ts b/.playwright/tests/mentions.spec.ts index 56e202b19..c59208cb4 100644 --- a/.playwright/tests/mentions.spec.ts +++ b/.playwright/tests/mentions.spec.ts @@ -22,6 +22,7 @@ const sel = { setChannelButton: '[data-testid="mention-set-channel-button"]', startUserButton: '[data-testid="mention-start-user-button"]', startChannelButton: '[data-testid="mention-start-channel-button"]', + removeInvalidToggle: '[data-testid="mention-remove-invalid-toggle"]', } as const; async function gotoMentionTest(page: Page): Promise { @@ -313,3 +314,294 @@ test("inserting a mention between text doesn't produce a double space", async ({ '

example Jane test

' ); }); + +// Inserts "Jane" plus the space setMention adds, then moves the caret +// `steps` characters left from the end: 1 is right after the mention, +// 3 is between "Ja" and "ne" +async function insertMentionAndMoveLeft( + page: Page, + steps: number +): Promise { + const editor = mentionEditor(page); + await editor.click(); + await editor.pressSequentially('@', { delay: 80 }); + await page.locator(sel.setUserButton).click(); + await expect + .poll(async () => + (await htmlOutput(page).textContent())?.includes(' { + await gotoMentionTest(page); + await insertMentionAndMoveLeft(page, 3); + await mentionEditor(page).press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

Jaxne

'); +}); + +test('removeInvalidMentionContent: typing inside a mention removes it', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertMentionAndMoveLeft(page, 3); + await mentionEditor(page).press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

'); +}); + +test('removeInvalidMentionContent: backspace inside a mention removes it', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertMentionAndMoveLeft(page, 3); + await mentionEditor(page).press('Backspace'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

'); +}); + +test('removeInvalidMentionContent: typing right after a mention keeps it', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertMentionAndMoveLeft(page, 1); + await mentionEditor(page).press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual( + '

Janex

' + ); +}); + +test('removeInvalidMentionContent: replacing everything keeps only the new text', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + const editor = mentionEditor(page); + await editor.click(); + await editor.pressSequentially('Hi @', { delay: 80 }); + await page.locator(sel.setUserButton).click(); + await editor.press('End'); + await editor.pressSequentially('and more', { delay: 40 }); + await editor.press('ControlOrMeta+a'); + await editor.press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

x

'); +}); + +test('removeInvalidMentionContent: replacing a selection around a mention keeps only the new text', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + const editor = mentionEditor(page); + await editor.click(); + await editor.pressSequentially('Hi @', { delay: 80 }); + await page.locator(sel.setUserButton).click(); + await editor.press('End'); + await editor.pressSequentially('end', { delay: 40 }); + // "Hi Jane end": select "i Jane e" + await editor.press('Home'); + await editor.press('ArrowRight'); + for (let i = 0; i < 8; i++) { + await editor.press('Shift+ArrowRight'); + } + await editor.press('Z'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

HZnd

'); +}); + +test('removeInvalidMentionContent: replacing exactly a mention keeps the new text', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + const editor = mentionEditor(page); + await editor.click(); + await editor.pressSequentially('Hi @', { delay: 80 }); + await page.locator(sel.setUserButton).click(); + await editor.press('End'); + await editor.pressSequentially('end', { delay: 40 }); + // "Hi Jane end": select "Jane" + await editor.press('Home'); + for (let i = 0; i < 3; i++) { + await editor.press('ArrowRight'); + } + for (let i = 0; i < 4; i++) { + await editor.press('Shift+ArrowRight'); + } + await editor.press('Z'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

Hi Z end

'); +}); + +const pasteCases = [ + { + name: 'a valid mention split by formatting is kept', + pasted: 'a @Jane z', + expected: 'a @Jane z', + }, + { + name: 'a mention that does not match its text is removed', + pasted: 'a @Jake z', + expected: 'a z', + }, +]; + +for (const { name, pasted, expected } of pasteCases) { + test(`removeInvalidMentionContent: pasting, ${name}`, async ({ page }) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + const editor = page.locator( + '[data-testid="mention-test-editor"] .ProseMirror' + ); + await editor.click(); + await editor.evaluate((el, html) => { + const data = new DataTransfer(); + data.setData('text/html', html); + el.dispatchEvent( + new ClipboardEvent('paste', { + clipboardData: data, + bubbles: true, + cancelable: true, + }) + ); + }, pasted); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${expected}

`); + }); +} + +const JANE = 'Jane'; + +// "Jane Jane " with both as mentions and the caret at the start +async function insertTwoMentions(page: Page): Promise { + const editor = mentionEditor(page); + await editor.click(); + for (let i = 1; i <= 2; i++) { + await editor.pressSequentially('@', { delay: 80 }); + await page.locator(sel.setUserButton).click(); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${`${JANE} `.repeat(i)}

`); + await editor.press('End'); + } + await editor.press('Home'); +} + +async function moveRight(page: Page, steps: number): Promise { + for (let i = 0; i < steps; i++) { + await mentionEditor(page).press('ArrowRight'); + } + // the editor picks up the new caret position asynchronously + await page.waitForTimeout(200); +} + +test('removeInvalidMentionContent: equal mentions that end up touching are kept', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertTwoMentions(page); + await moveRight(page, 4); + await mentionEditor(page).press('Delete'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${JANE.replace('>Jane<', '>JaneJane<')}

`); +}); + +test('removeInvalidMentionContent: editing one of two touching equal mentions keeps the other', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertTwoMentions(page); + await moveRight(page, 4); + await mentionEditor(page).press('Delete'); + await moveRight(page, 2); + await mentionEditor(page).press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${JANE}

`); +}); + +test('removeInvalidMentionContent: a space typed between touching equal mentions keeps both', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertTwoMentions(page); + await moveRight(page, 4); + await mentionEditor(page).press('Delete'); + await mentionEditor(page).press('Space'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${JANE} ${JANE}

`); +}); + +test('removeInvalidMentionContent: undo brings the removed mention back', async ({ + page, +}) => { + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertMentionAndMoveLeft(page, 3); + await page.waitForTimeout(700); + await mentionEditor(page).press('x'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual('

'); + await mentionEditor(page).press('ControlOrMeta+z'); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(`

${JANE}

`); +}); + +test('removeInvalidMentionContent: undo and redo restore touching equal mentions', async ({ + page, +}) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await gotoMentionTest(page); + await page.locator(sel.removeInvalidToggle).click(); + await insertTwoMentions(page); + await moveRight(page, 4); + await mentionEditor(page).press('Delete'); + const touching = `

${JANE.replace('>Jane<', '>JaneJane<')}

`; + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(touching); + // longer than the history's grouping delay + await page.waitForTimeout(700); + await moveRight(page, 2); + await mentionEditor(page).press('Backspace'); + const edited = `

${JANE}

`; + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(edited); + for (const [key, html] of [ + ['ControlOrMeta+z', touching], + ['ControlOrMeta+Shift+z', edited], + ] as const) { + await mentionEditor(page).press(key); + await expect + .poll(async () => await htmlOutput(page).textContent()) + .toEqual(html); + } + expect(errors).toEqual([]); +}); diff --git a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt index c3babc3d1..90a304bc6 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt @@ -14,6 +14,7 @@ import android.text.Editable import android.text.InputType import android.text.Spannable import android.text.SpannableString +import android.text.SpannableStringBuilder import android.util.AttributeSet import android.util.Log import android.util.Patterns @@ -477,9 +478,17 @@ class EnrichedTextInputView : item.htmlText != null -> { val parsed = parseText(item.htmlText) // Not parsed (e.g. external HTML with the normalizer off): fall back to the plain text item - (parsed as? Spannable) - ?: item.text?.let { SpannableString(it.toString()) } - ?: return + val pasted = + (parsed as? Spannable) + ?: item.text?.let { SpannableString(it.toString()) } + ?: return + if (parametrizedStyles?.removeInvalidMentionContent == true) { + // the watcher below keeps text that replaced a mention, so pasted + // mismatched mentions are removed before they are merged in + SpannableStringBuilder(pasted).also { parametrizedStyles?.removeInvalidMentions(it) } + } else { + pasted + } } item.text != null -> { @@ -544,7 +553,12 @@ class EnrichedTextInputView : if (value == null) return runAsATransaction { - val newText = if (shouldParseHtml) parseText(value) else value + var newText = if (shouldParseHtml) parseText(value) else value + // the text watcher doesn't run during the transaction, so mentions whose + // text doesn't match them are removed before the text is set + if (shouldParseHtml && parametrizedStyles?.removeInvalidMentionContent == true) { + newText = SpannableStringBuilder(newText).also { parametrizedStyles?.removeInvalidMentions(it) } + } setText(newText) applyLineSpacing() diff --git a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt index a0a9aa617..5a43e5c8c 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt @@ -179,6 +179,14 @@ class EnrichedTextInputViewManager : view?.parametrizedStyles?.mentionIndicators = indicatorsArray } + @ReactProp(name = "removeInvalidMentionContent", defaultBoolean = false) + override fun setRemoveInvalidMentionContent( + view: EnrichedTextInputView?, + removeInvalidMentionContent: Boolean, + ) { + view?.parametrizedStyles?.removeInvalidMentionContent = removeInvalidMentionContent + } + @ReactProp(name = "htmlStyle") override fun setHtmlStyle( view: EnrichedTextInputView?, diff --git a/android/src/main/java/com/swmansion/enriched/textinput/styles/ParametrizedStyles.kt b/android/src/main/java/com/swmansion/enriched/textinput/styles/ParametrizedStyles.kt index afeb2f46b..432941364 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/styles/ParametrizedStyles.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/styles/ParametrizedStyles.kt @@ -23,6 +23,7 @@ class ParametrizedStyles( private var isSettingLinkSpan = false var mentionIndicators: Array = emptyArray() + var removeInvalidMentionContent = false fun removeSpansForRange( spannable: Spannable, @@ -95,9 +96,43 @@ class ParametrizedStyles( ) { afterTextChangedManualLinks(startCursorPosition, endCursorPosition) afterTextChangedLinks(startCursorPosition, endCursorPosition) + // the deletion re-runs this watcher on the final text with fresh positions + if (removeInvalidMentionContent && removeInvalidMentions(s, startCursorPosition, endCursorPosition)) return detectActiveMention(s, startCursorPosition) } + // insertedStart and insertedEnd is the text the edit inserted, if any + fun removeInvalidMentions( + s: Editable, + insertedStart: Int = -1, + insertedEnd: Int = -1, + ): Boolean { + var removed = false + for (span in s.getSpans(0, s.length, EnrichedInputMentionSpan::class.java)) { + val start = s.getSpanStart(span) + val end = s.getSpanEnd(span) + // the nested watcher pass may have removed it already + if (start == -1) continue + // a mention at the start of a paragraph style can cover the paragraph's + // zero width space, which isn't part of its text + val currentText = s.subSequence(start, end).toString().replace(EnrichedConstants.ZWS_STRING, "") + if (currentText == span.getText()) continue + + s.removeSpan(span) + // replacing exactly the mention's text leaves the span over the new + // text; the mention is already gone, so the new text stays + if (start >= insertedStart && end <= insertedEnd) continue + + // keep the paragraph's zero width space, or the paragraph style would be + // removed with it + var deleteStart = start + while (deleteStart < end && s[deleteStart] == EnrichedConstants.ZWS) deleteStart++ + s.delete(deleteStart, end) + removed = true + } + return removed + } + // Re-runs in-progress mention detection on a pure caret move (no text change), fun afterSelectionChangedMentions( start: Int, diff --git a/apps/example-web/src/testScreens/TestMentions.tsx b/apps/example-web/src/testScreens/TestMentions.tsx index 7cf6dd199..89d792d25 100644 --- a/apps/example-web/src/testScreens/TestMentions.tsx +++ b/apps/example-web/src/testScreens/TestMentions.tsx @@ -16,6 +16,8 @@ export function TestMentions() { const [detectedText, setDetectedText] = useState(''); const [detectedIndicator, setDetectedIndicator] = useState(''); const [lastEndEvent, setLastEndEvent] = useState(''); + const [removeInvalidMentionContent, setRemoveInvalidMentionContent] = + useState(false); const preventDefault = (e: React.MouseEvent) => { e.preventDefault(); @@ -31,6 +33,7 @@ export function TestMentions() { style={editorStyle} htmlStyle={WEB_DEFAULT_HTML_STYLE} mentionIndicators={['@', '#']} + removeInvalidMentionContent={removeInvalidMentionContent} onStartMention={(indicator) => { setEventType('start'); setEventIndicator(indicator); @@ -112,6 +115,13 @@ export function TestMentions() { Start mention (channel) + ); } diff --git a/apps/example/src/screens/DevScreen.tsx b/apps/example/src/screens/DevScreen.tsx index 0b50b274c..b66bcef32 100644 --- a/apps/example/src/screens/DevScreen.tsx +++ b/apps/example/src/screens/DevScreen.tsx @@ -23,6 +23,8 @@ interface DevScreenProps { export function DevScreen({ onSwitch }: DevScreenProps) { const editor = useEditorState(); const [textNodes, setTextNodes] = useState>([]); + const [removeInvalidMentionContent, setRemoveInvalidMentionContent] = + useState(false); const handlePushTextNode = async () => { const currentText = await editor.ref.current?.getHTML(); @@ -44,6 +46,7 @@ export function DevScreen({ onSwitch }: DevScreenProps) { +