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
24 changes: 24 additions & 0 deletions .maestro/enrichedText/flows/image_press.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
appId: swmansion.enriched.example
---
# Validates that image press events are triggered correctly
- launchApp

- tapOn:
id: 'toggle-screen-button'

- tapOn:
id: 'toggle-enriched-text-screen-button'

- runFlow:
file: '../subflows/set_enriched_text_value.yaml'
env:
VALUE: '<html><img src="https://picsum.photos/id/1/200/200" width="200" height="200"/></html>'

- tapOn:
id: 'enriched-text'
point: '5%,50%'

- runFlow:
file: '../subflows/capture_or_assert_screenshot.yaml'
env:
SCREENSHOT_NAME: 'image_press'
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
143 changes: 143 additions & 0 deletions .playwright/tests/enrichedTextPress.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import { test, expect, type Page } from '@playwright/test';

test.setTimeout(90_000);

const IMAGE_ROUTE = '**/pw-e2e-ok.png';
const IMAGE_SRC = '/pw-e2e-ok.png';
const BROKEN_IMAGE_ROUTE = '**/pw-e2e-broken.png';
const BROKEN_IMAGE_SRC = '/pw-e2e-broken.png';
const PNG_BODY = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64'
);

const sel = {
root: '[data-testid="test-enriched-text-root"]',
htmlInput: '[data-testid="test-enriched-text-html-input"]',
Expand All @@ -11,8 +20,22 @@ const sel = {
displayInner: '[data-testid="test-enriched-text-display"] .et-view',
linkPressOutput: '[data-testid="test-enriched-text-link-press-output"]',
mentionPressOutput: '[data-testid="test-enriched-text-mention-press-output"]',
imagePressOutput: '[data-testid="test-enriched-text-image-press-output"]',
} as const;

const VISIBILITY_TIMEOUT_MS = 1_000;

test.beforeEach(async ({ page }) => {
await page.route(IMAGE_ROUTE, async (route) => {
await route.fulfill({
status: 200,
contentType: 'image/png',
body: PNG_BODY,
});
});
await page.route(BROKEN_IMAGE_ROUTE, (route) => route.abort());
});

async function gotoTestEnrichedText(page: Page): Promise<void> {
await page.goto('/test-enriched-text');
await page.waitForSelector(sel.displayInner);
Expand All @@ -35,6 +58,10 @@ function mentionPress(page: Page) {
return page.locator(sel.mentionPressOutput);
}

function imagePress(page: Page) {
return page.locator(sel.imagePressOutput);
}

test.describe('EnrichedText link press', () => {
test('pressing a link emits onLinkPress with the url', async ({ page }) => {
await gotoTestEnrichedText(page);
Expand Down Expand Up @@ -143,6 +170,102 @@ test.describe('EnrichedText mention press', () => {
});
});

test.describe('EnrichedText image press', () => {
test('pressing an image emits onImagePress with the image', async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
`<html><p>Look <img src="${IMAGE_SRC}" width="32" height="32" /> now.</p></html>`
);

await expect(imagePress(page)).toHaveText('null');

await page.locator(`${sel.displayInner} img`).click();

await expect
.poll(async () =>
JSON.parse((await imagePress(page).textContent()) || 'null')
)
.toEqual({ image: { uri: IMAGE_SRC, width: 32, height: 32 } });
});

test('pressing an image surrounded by styled text still emits onImagePress', async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
`<html><p>A <b>bold</b> <img src="${IMAGE_SRC}" width="120" height="60" /> here.</p></html>`
);

await page.locator(`${sel.displayInner} img`).click();

await expect
.poll(async () =>
JSON.parse((await imagePress(page).textContent()) || 'null')
)
.toEqual({ image: { uri: IMAGE_SRC, width: 120, height: 60 } });
});

test('pressing non-image text does not emit onImagePress', async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
`<html><p>Plain text with an <img src="${IMAGE_SRC}" width="32" height="32" />.</p></html>`
);

await page
.locator(`${sel.displayInner} p`)
.click({ position: { x: 2, y: 2 } });

await expect(imagePress(page)).toHaveText('null');
});

test('pressing an empty-src placeholder does not emit onImagePress', async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
'<html><p>Before <img src="" width="40" height="40" /> after.</p></html>'
);

await expect(page.locator(`${sel.displayInner} img`)).toBeVisible({
timeout: VISIBILITY_TIMEOUT_MS,
});

await page.locator(`${sel.displayInner} img`).click();

await expect(imagePress(page)).toHaveText('null');
});

test('pressing a broken-URL placeholder does emit onImagePress', async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
`<html><p>Before <img src="${BROKEN_IMAGE_SRC}" width="40" height="40" /> after.</p></html>`
);

await expect(page.locator(`${sel.displayInner} img`)).toBeVisible({
timeout: VISIBILITY_TIMEOUT_MS,
});

await page.locator(`${sel.displayInner} img`).click();

await expect
.poll(async () =>
JSON.parse((await imagePress(page).textContent()) || 'null')
)
.toEqual({ image: { uri: BROKEN_IMAGE_SRC, width: 40, height: 40 } });
});
});

test.describe('EnrichedText press inside lists', () => {
const listCases = [
{
Expand Down Expand Up @@ -206,5 +329,25 @@ test.describe('EnrichedText press inside lists', () => {
attributes: { id: '1' },
});
});

test(`pressing an image inside a ${c.name} emits onImagePress`, async ({
page,
}) => {
await gotoTestEnrichedText(page);
await setEnrichedTextValue(
page,
`<html>${c.open}<li><p>See <img src="${IMAGE_SRC}" width="28" height="28" /> tiny</p></li><li><p>Other item</p></li>${c.close}</html>`
);

await expect(imagePress(page)).toHaveText('null');

await page.locator(`${sel.displayInner} li img`).click();

await expect
.poll(async () =>
JSON.parse((await imagePress(page).textContent()) || 'null')
)
.toEqual({ image: { uri: IMAGE_SRC, width: 28, height: 28 } });
});
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.facebook.react.uimanager.ViewManagerDelegate
import com.facebook.react.viewmanagers.EnrichedTextViewManagerDelegate
import com.facebook.react.viewmanagers.EnrichedTextViewManagerInterface
import com.facebook.yoga.YogaMeasureMode
import com.swmansion.enriched.text.events.OnImagePressEvent
import com.swmansion.enriched.text.events.OnLinkPressEvent
import com.swmansion.enriched.text.events.OnMentionPressEvent

Expand All @@ -29,6 +30,7 @@ class EnrichedTextViewManager :
val map = mutableMapOf<String, Any>()
map.put(OnLinkPressEvent.EVENT_NAME, mapOf("registrationName" to OnLinkPressEvent.EVENT_NAME))
map.put(OnMentionPressEvent.EVENT_NAME, mapOf("registrationName" to OnMentionPressEvent.EVENT_NAME))
map.put(OnImagePressEvent.EVENT_NAME, mapOf("registrationName" to OnImagePressEvent.EVENT_NAME))
return map
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.swmansion.enriched.text.events

import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.events.Event

class OnImagePressEvent(
surfaceId: Int,
viewId: Int,
private val uri: String,
private val width: Double,
private val height: Double,
) : Event<OnImagePressEvent>(surfaceId, viewId) {
override fun getEventName(): String = EVENT_NAME

override fun getEventData(): WritableMap? {
val eventData: WritableMap = Arguments.createMap()
val imageMap = Arguments.createMap()
imageMap.putString("uri", uri)
imageMap.putDouble("width", width)
imageMap.putDouble("height", height)
eventData.putMap("image", imageMap)
return eventData
}

companion object {
const val EVENT_NAME: String = "onImagePress"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ package com.swmansion.enriched.text.spans
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import android.view.View
import com.facebook.react.bridge.ReactContext
import com.facebook.react.uimanager.UIManagerHelper
import com.swmansion.enriched.R
import com.swmansion.enriched.common.AsyncDrawable
import com.swmansion.enriched.common.ResourceManager
import com.swmansion.enriched.common.spans.EnrichedImageSpan
import com.swmansion.enriched.text.EnrichedTextStyle
import com.swmansion.enriched.text.events.OnImagePressEvent
import com.swmansion.enriched.text.spans.interfaces.EnrichedTextClickableSpan
import com.swmansion.enriched.text.spans.interfaces.EnrichedTextSpan

class EnrichedTextImageSpan(
Expand All @@ -16,11 +21,28 @@ class EnrichedTextImageSpan(
width: Int,
height: Int,
) : EnrichedImageSpan(drawable, source, width, height),
EnrichedTextSpan {
EnrichedTextSpan,
EnrichedTextClickableSpan {
override val dependsOnHtmlStyle = false
override var isPressed = false

override fun rebuildWithStyle(style: EnrichedTextStyle) = this

override fun onClick(view: View) {
val context = view.context as? ReactContext ?: return
val surfaceId = UIManagerHelper.getSurfaceId(context)
val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(context, view.id)
dispatcher?.dispatchEvent(
OnImagePressEvent(
surfaceId,
view.id,
source ?: "",
getWidth().toDouble(),
getHeight().toDouble(),
),
)
}

// We use a callback to trigger a layout rebuild because ForceRedrawSpan/SpanWatcher
// (used in EnrichedImageSpan) doesn’t work in EnrichedTextView with SpannedString.
fun observeAsyncDrawableLoaded(onLoaded: () -> Unit) {
Expand Down
6 changes: 6 additions & 0 deletions apps/example-web/src/components/TextRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type BlurEvent,
type EnrichedTextInstance,
type FocusEvent,
type OnImagePressEvent,
type OnLinkPressEvent,
type OnMentionPressEvent,
} from 'react-native-enriched-html';
Expand Down Expand Up @@ -33,6 +34,10 @@ export function TextRenderer({ htmlValue }: TextRendererProps) {
console.log('[EnrichedText] mention press event', e);
};

const handleImagePress = (e: OnImagePressEvent) => {
console.log('[EnrichedText] image press event', e);
};

return (
<div className="container enriched-text-container">
<h1 className="app-title">Enriched Text</h1>
Expand All @@ -44,6 +49,7 @@ export function TextRenderer({ htmlValue }: TextRendererProps) {
onBlur={handleTextBlur}
onLinkPress={handleLinkPress}
onMentionPress={handleMentionPress}
onImagePress={handleImagePress}
>
{htmlValue}
</EnrichedText>
Expand Down
7 changes: 7 additions & 0 deletions apps/example-web/src/testScreens/TestEnrichedText.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState, type ChangeEvent } from 'react';
import {
EnrichedText,
type OnImagePressEvent,
type OnLinkPressEvent,
type OnMentionPressEvent,
} from 'react-native-enriched-html';
Expand All @@ -12,6 +13,8 @@ const INITIAL_VALUE = '<html><p></p></html>';
export function TestEnrichedText() {
const [htmlInput, setHtmlInput] = useState(INITIAL_VALUE);
const [value, setValue] = useState(INITIAL_VALUE);
const [lastImagePress, setLastImagePress] =
useState<OnImagePressEvent | null>(null);
const [lastLinkPress, setLastLinkPress] = useState<OnLinkPressEvent | null>(
null
);
Expand All @@ -30,6 +33,7 @@ export function TestEnrichedText() {
htmlStyle={WEB_DEFAULT_HTML_STYLE}
onLinkPress={setLastLinkPress}
onMentionPress={setLastMentionPress}
onImagePress={setLastImagePress}
>
{value}
</EnrichedText>
Expand Down Expand Up @@ -65,6 +69,9 @@ export function TestEnrichedText() {

<pre data-testid="test-enriched-text-value-output">{value}</pre>

<pre data-testid="test-enriched-text-image-press-output">
{JSON.stringify(lastImagePress)}
</pre>
<pre data-testid="test-enriched-text-link-press-output">
{JSON.stringify(lastLinkPress)}
</pre>
Expand Down
9 changes: 9 additions & 0 deletions apps/example/src/components/TextRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
EnrichedText,
type OnLinkPressEvent,
type OnMentionPressEvent,
type OnImagePressEvent,
} from 'react-native-enriched-html';
import { enrichedTextHtmlStyle } from '../constants/editorConfig';

Expand All @@ -22,6 +23,13 @@ export const TextRenderer = ({ nodes }: TextRendererProps) => {
);
};

const handleImagePress = (e: OnImagePressEvent) => {
Alert.alert(
'Image Pressed',
`You pressed the image: ${JSON.stringify(e.image)}`
);
};

if (nodes.length === 0) {
return null;
}
Expand All @@ -35,6 +43,7 @@ export const TextRenderer = ({ nodes }: TextRendererProps) => {
htmlStyle={enrichedTextHtmlStyle}
onLinkPress={handleLinkPress}
onMentionPress={handleMentionPress}
onImagePress={handleImagePress}
>
{node}
</EnrichedText>
Expand Down
Loading
Loading