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.
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
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}
useHtmlNormalizer
>
{node}
Expand Down
6 changes: 6 additions & 0 deletions apps/example/src/screens/EnrichedTextScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { View, StyleSheet, ScrollView, Text } from 'react-native';
import {
EnrichedText,
type EnrichedTextProps,
type OnImagePressEvent,
type OnLinkPressEvent,
type OnMentionPressEvent,
} from 'react-native-enriched-html';
Expand Down Expand Up @@ -37,6 +38,10 @@ export function EnrichedTextScreen({ onSwitch }: EnrichedTextScreenProps) {
);
};

const handleImagePress = (e: OnImagePressEvent) => {
setHtml(`You pressed the image: ${JSON.stringify(e.image)}`);
};

return (
<>
<ScrollView
Expand Down Expand Up @@ -116,6 +121,7 @@ export function EnrichedTextScreen({ onSwitch }: EnrichedTextScreenProps) {
ellipsizeMode={ellipsizeMode}
onLinkPress={handleLinkPress}
onMentionPress={handleMentionPress}
onImagePress={handleImagePress}
useHtmlNormalizer
>
{html}
Expand Down
21 changes: 21 additions & 0 deletions docs/TEXT_API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ interface OnMentionPressEvent {
| -------------------------------------- | ------------- | ------------ |
| `(event: OnMentionPressEvent) => void` | - | iOS, Android |

### `onImagePress`

Called when the user presses an inline image. Receives an `OnImagePressEvent` with the image uri and dimensions.

```ts
interface OnImagePressEvent {
image: {
uri: string;
width: number;
height: number;
};
}
```

| Type | Default Value | Platform |
| ------------------------------------ | ------------- | ------------ |
| `(event: OnImagePressEvent) => void` | - | iOS, Android |

> [!NOTE]
> No visual feedback is applied on press.

## EnrichedTextHtmlStyle type

Extends [`HtmlStyle`](API_REFERENCE.md#htmlstyle-type) with additional press-state styling for interactive elements. All properties from `HtmlStyle` are supported except `a` and `mention`, which are replaced by the extended versions below.
Expand Down
1 change: 1 addition & 0 deletions ios/EnrichedTextView.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ NS_ASSUME_NONNULL_BEGIN
- (CGSize)measureSize:(CGFloat)maxWidth;
- (void)emitOnLinkPressEvent:(NSString *)url;
- (void)emitOnMentionPressEvent:(MentionParams *)mention;
- (void)emitOnImagePressEvent:(MediaAttachment *)attachment;
@end

NS_ASSUME_NONNULL_END
Expand Down
15 changes: 15 additions & 0 deletions ios/EnrichedTextView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,21 @@ - (void)emitOnMentionPressEvent:(MentionParams *)mention {
}
}

- (void)emitOnImagePressEvent:(MediaAttachment *)attachment {
if (!attachment)
return;
auto emitter = [self getEventEmitter];
if (emitter != nullptr) {
emitter->onImagePress(
{.image = {
.uri =
attachment.uri ? [attachment.uri toCppString] : std::string{},
.width = attachment.width,
.height = attachment.height,
}});
}
}

// MARK: - Media attachments delegate

- (void)mediaAttachmentDidUpdate:(MediaAttachment *)attachment {
Expand Down
20 changes: 18 additions & 2 deletions ios/utils/EnrichedTextTouchHandler.mm
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#import "EnrichedTextTouchHandler.h"
#import "ColorExtension.h"
#import "EnrichedTextView.h"
#import "ImageAttachment.h"
#import "LinkData.h"
#import "MentionParams.h"
#import "MentionStyleProps.h"
Expand Down Expand Up @@ -78,8 +79,10 @@ - (id)findClickableAt:(NSUInteger)idx
if (idx == NSNotFound || idx >= self.view.textView.textStorage.length)
return nil;

NSArray *keys =
@[ @"EnrichedManualLink", @"EnrichedAutomaticLink", @"EnrichedMention" ];
NSArray *keys = @[
@"EnrichedManualLink", @"EnrichedAutomaticLink", @"EnrichedMention",
@"EnrichedImage"
];
for (NSString *k in keys) {
id val = [self.view.textView.textStorage attribute:k
atIndex:idx
Expand All @@ -93,6 +96,10 @@ - (id)findClickableAt:(NSUInteger)idx
}

- (void)updateVisualsPressed:(BOOL)pressed {
if ([_activeAttrKey isEqualToString:@"EnrichedImage"]) {
return;
}

if (pressed) {
UIColor *color = nil;
UIColor *bgColor = nil;
Expand Down Expand Up @@ -141,6 +148,15 @@ - (void)dispatchEvent {
[self.view emitOnLinkPressEvent:((LinkData *)_activeValue).url];
} else if ([_activeAttrKey isEqualToString:@"EnrichedMention"]) {
[self.view emitOnMentionPressEvent:(MentionParams *)_activeValue];
} else if ([_activeAttrKey isEqualToString:@"EnrichedImage"]) {
NSRange attachmentRange = _activeRange;
ImageAttachment *attachment =
[self.view.textView.textStorage attribute:NSAttachmentAttributeName
atIndex:attachmentRange.location
effectiveRange:NULL];
if ([attachment isKindOfClass:[ImageAttachment class]]) {
[self.view emitOnImagePressEvent:attachment];
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ export type {
EnrichedTextHtmlStyle,
OnMentionPressEvent,
OnLinkPressEvent,
OnImagePressEvent,
} from './types';
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ export type {
EnrichedTextHtmlStyle,
OnMentionPressEvent,
OnLinkPressEvent,
OnImagePressEvent,
} from './types';
10 changes: 10 additions & 0 deletions src/native/EnrichedText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import EnrichedTextNativeComponent, {
type NativeProps,
type OnLinkPressEvent,
type OnMentionPressEventInternal,
type OnImagePressEvent,
} from '../spec/EnrichedTextNativeComponent';
import { nullthrows } from '../utils/nullthrows';
import { normalizeEnrichedTextHtmlStyle } from '../utils/normalizeHtmlStyle';
Expand All @@ -37,6 +38,7 @@ export const EnrichedText = ({
allowFontScaling = true,
onLinkPress: _onLinkPress,
onMentionPress: _onMentionPress,
onImagePress: _onImagePress,
...rest
}: EnrichedTextProps) => {
const nativeRef = useRef<ComponentType | null>(null);
Expand Down Expand Up @@ -66,6 +68,13 @@ export const EnrichedText = ({
[_onMentionPress]
);

const onImagePress: DirectEventHandler<OnImagePressEvent> = useCallback(
(e) => {
_onImagePress?.(e.nativeEvent);
},
[_onImagePress]
);

useImperativeHandle(ref, () => ({
measureInWindow: (callback: MeasureInWindowOnSuccessCallback) => {
nullthrows(nativeRef.current).measureInWindow(callback);
Expand Down Expand Up @@ -109,6 +118,7 @@ export const EnrichedText = ({
allowFontScaling={allowFontScaling}
onLinkPress={onLinkPress}
onMentionPress={onMentionPress}
onImagePress={onImagePress}
{...rest}
/>
);
Expand Down
9 changes: 9 additions & 0 deletions src/spec/EnrichedTextNativeComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ export interface OnMentionPressEvent {
attributes: Record<string, string>;
}

export interface OnImagePressEvent {
image: {
uri: string;
width: Float;
height: Float;
};
}

export interface NativeProps extends ViewProps {
// Custom props
text: string;
Expand All @@ -95,6 +103,7 @@ export interface NativeProps extends ViewProps {
// Events
onLinkPress?: DirectEventHandler<OnLinkPressEvent>;
onMentionPress?: DirectEventHandler<OnMentionPressEventInternal>;
onImagePress?: DirectEventHandler<OnImagePressEvent>;

// Style related props - used for generating proper setters in component's manager
// These should not be passed as regular props
Expand Down
11 changes: 11 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,9 @@ export interface EnrichedTextProps extends ViewProps {

/** Called when the user taps a mention node inside the rendered content. */
onMentionPress?: (event: OnMentionPressEvent) => void;

/** Called when the user taps an inline image inside the rendered content. */
onImagePress?: (event: OnImagePressEvent) => void;
}

export interface EnrichedTextMentionStyleProperties extends MentionStyleProperties {
Expand Down Expand Up @@ -864,3 +867,11 @@ export interface OnMentionPressEvent {
indicator: string;
attributes: Record<string, string>;
}

export interface OnImagePressEvent {
image: {
uri: string;
width: number;
height: number;
};
}
Loading