Enriched Text Input
@@ -271,6 +276,7 @@ function App() {
scrollEnabled
autoCapitalize="sentences"
style={enrichedInputStyle}
+ onScroll={handleScroll}
onFocus={handleFocus}
onBlur={handleBlur}
onKeyPress={handleKeyPress}
diff --git a/apps/example-web/src/RouteSelector.tsx b/apps/example-web/src/RouteSelector.tsx
index d280fb214..cfa78f6dd 100644
--- a/apps/example-web/src/RouteSelector.tsx
+++ b/apps/example-web/src/RouteSelector.tsx
@@ -8,6 +8,7 @@ import { TestEnrichedText } from './testScreens/TestEnrichedText';
import { TestEllipsize } from './testScreens/TestEllipsize';
import { TestRenderCycle } from './testScreens/TestRenderCycle';
import { useEffect, useState } from 'react';
+import { TestScroll } from './testScreens/TestScroll';
export default function RouteSelector() {
const [path, setPath] = useState(window.location.pathname);
@@ -55,5 +56,9 @@ export default function RouteSelector() {
return
;
}
+ if (path === '/test-scroll') {
+ return
;
+ }
+
return
;
}
diff --git a/apps/example-web/src/testScreens/TestScroll.tsx b/apps/example-web/src/testScreens/TestScroll.tsx
new file mode 100644
index 000000000..440a457e7
--- /dev/null
+++ b/apps/example-web/src/testScreens/TestScroll.tsx
@@ -0,0 +1,28 @@
+import { EnrichedTextInput } from 'react-native-enriched-html';
+import { useState } from 'react';
+
+const LONG_HTML = '
Test
'.repeat(150);
+
+export function TestScroll() {
+ const [offset, setOffset] = useState(0);
+ return (
+
+
+ {
+ setOffset(e.nativeEvent.contentOffset.y);
+ }}
+ />
+
+
{offset}
+
+ );
+}
+
+const styles = {
+ editor: {
+ height: 150,
+ },
+};
diff --git a/apps/example/android/app/src/main/java/swmansion/enriched/example/MainActivity.kt b/apps/example/android/app/src/main/java/swmansion/enriched/example/MainActivity.kt
index e234b0c52..dc02c2048 100644
--- a/apps/example/android/app/src/main/java/swmansion/enriched/example/MainActivity.kt
+++ b/apps/example/android/app/src/main/java/swmansion/enriched/example/MainActivity.kt
@@ -1,5 +1,6 @@
package swmansion.enriched.example
+import android.os.Bundle
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
@@ -18,5 +19,14 @@ class MainActivity : ReactActivity() {
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
- DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
+ object : DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) {
+ // Forwards Maestro launch arguments (intent extras) to the JS app as initial props
+ override fun getLaunchOptions(): Bundle =
+ Bundle().apply {
+ putBoolean(
+ "showScrollOffset",
+ intent?.getBooleanExtra("showScrollOffset", false) ?: false,
+ )
+ }
+ }
}
diff --git a/apps/example/ios/EnrichedTextInputExample/SceneDelegate.swift b/apps/example/ios/EnrichedTextInputExample/SceneDelegate.swift
index 8fa5a897c..0fd49314b 100644
--- a/apps/example/ios/EnrichedTextInputExample/SceneDelegate.swift
+++ b/apps/example/ios/EnrichedTextInputExample/SceneDelegate.swift
@@ -29,9 +29,21 @@ class SceneDelegate: RCTDefaultReactNativeFactoryDelegate, UIWindowSceneDelegate
reactNativeFactory?.devMenuConfiguration = devMenuConfiguration
#endif
+ // Forwards Maestro launch arguments to the JS app as initial props.
+ // Maestro passes them as plain `key value` process arguments (no leading `-`),
+ // so they don't end up in UserDefaults.
+ let arguments = ProcessInfo.processInfo.arguments
+ let showScrollOffset = zip(arguments, arguments.dropFirst()).contains {
+ $0 == "showScrollOffset" && $1 == "true"
+ }
+ let initialProperties: [AnyHashable: Any] = [
+ "showScrollOffset": showScrollOffset
+ ]
+
reactNativeFactory?.startReactNative(
withModuleName: "EnrichedTextInputExample",
in: window,
+ initialProperties: initialProperties,
connectionOptions: connectionOptions
)
diff --git a/apps/example/src/App.tsx b/apps/example/src/App.tsx
index 6c2d54105..eba1aac92 100644
--- a/apps/example/src/App.tsx
+++ b/apps/example/src/App.tsx
@@ -5,12 +5,18 @@ import { EnrichedTextScreen } from './screens/EnrichedTextScreen';
type Screen = 'dev' | 'test' | 'enrichedText';
-export default function App() {
+interface AppProps {
+ // Passed by Maestro as a launch argument, see MainActivity and SceneDelegate
+ showScrollOffset?: boolean;
+}
+
+export default function App({ showScrollOffset = false }: AppProps) {
const [screen, setScreen] = useState
('dev');
if (screen === 'test') {
return (
setScreen('dev')}
onSwitchEnrichedText={() => setScreen('enrichedText')}
/>
diff --git a/apps/example/src/components/ModalShell.tsx b/apps/example/src/components/ModalShell.tsx
index 748b44827..1bb1537da 100644
--- a/apps/example/src/components/ModalShell.tsx
+++ b/apps/example/src/components/ModalShell.tsx
@@ -1,10 +1,5 @@
import { type FC, type ReactNode } from 'react';
-import {
- KeyboardAvoidingView,
- Modal,
- Platform,
- StyleSheet,
-} from 'react-native';
+import { KeyboardAvoidingView, Modal, StyleSheet } from 'react-native';
interface ModalShellProps {
isOpen: boolean;
@@ -21,7 +16,7 @@ export const ModalShell: FC = ({
{children}
diff --git a/apps/example/src/hooks/useEditorState.ts b/apps/example/src/hooks/useEditorState.ts
index fee933ef0..5a6452844 100644
--- a/apps/example/src/hooks/useEditorState.ts
+++ b/apps/example/src/hooks/useEditorState.ts
@@ -10,6 +10,7 @@ import {
type OnKeyPressEvent,
type OnPasteImagesEvent,
type OnSubmitEditing,
+ type OnScrollEvent,
} from 'react-native-enriched-html';
import { useRef, useState } from 'react';
import { type MentionItem } from '../components/MentionPopup';
@@ -163,6 +164,10 @@ export function useEditorState() {
console.log('Key pressed:', e.key);
};
+ const handleScroll = (e: OnScrollEvent) => {
+ console.log('Scroll event:', e.contentOffset);
+ };
+
const handleLinkDetected = (state: CurrentLinkState) => {
console.log(state);
setCurrentLink(state);
@@ -271,6 +276,7 @@ export function useEditorState() {
handleSelectionChangeEvent,
handleKeyPress,
handleFocusEvent,
+ handleScroll,
handleBlurEvent,
handlePasteImagesEvent,
handleStartMention,
diff --git a/apps/example/src/screens/DevScreen.tsx b/apps/example/src/screens/DevScreen.tsx
index d5b4ba3f1..0b50b274c 100644
--- a/apps/example/src/screens/DevScreen.tsx
+++ b/apps/example/src/screens/DevScreen.tsx
@@ -62,6 +62,7 @@ export function DevScreen({ onSwitch }: DevScreenProps) {
onEndMention={editor.handleEndMention}
onFocus={editor.handleFocusEvent}
onBlur={editor.handleBlurEvent}
+ onScroll={(e) => editor.handleScroll(e.nativeEvent)}
onChangeSelection={(e) =>
editor.handleSelectionChangeEvent(e.nativeEvent)
}
diff --git a/apps/example/src/screens/TestScreen.tsx b/apps/example/src/screens/TestScreen.tsx
index 85266b36b..a50b13fa1 100644
--- a/apps/example/src/screens/TestScreen.tsx
+++ b/apps/example/src/screens/TestScreen.tsx
@@ -1,5 +1,5 @@
-import { useState } from 'react';
-import { View, StyleSheet, ScrollView } from 'react-native';
+import { useEffect, useRef, useState } from 'react';
+import { View, StyleSheet, ScrollView, Text } from 'react-native';
import { EnrichedTextInput } from 'react-native-enriched-html';
import { Button } from '../components/Button';
import { Toolbar } from '../components/Toolbar';
@@ -17,18 +17,26 @@ import {
} from '../constants/editorConfig';
interface TestScreenProps {
+ showScrollOffset: boolean;
onSwitch: () => void;
onSwitchEnrichedText: () => void;
}
export function TestScreen({
+ showScrollOffset,
onSwitch,
onSwitchEnrichedText,
}: TestScreenProps) {
const editor = useEditorState();
const [sizeMode, setSizeMode] = useState<'base' | 'max'>('base');
+ // The displayed offset is committed to state only once scrolling settles,
+ // so the screen doesn't re-render on every scroll event.
+ const [scrollOffset, setScrollOffset] = useState(0);
+ const scrollSettleTimeout = useRef>(undefined);
const keyboardHeight = useKeyboardHeight();
+ useEffect(() => () => clearTimeout(scrollSettleTimeout.current), []);
+
return (
{
+ editor.handleScroll(e.nativeEvent);
+ if (showScrollOffset) {
+ const offsetY = e.nativeEvent.contentOffset.y;
+ clearTimeout(scrollSettleTimeout.current);
+ scrollSettleTimeout.current = setTimeout(
+ () => setScrollOffset(offsetY),
+ 100
+ );
+ }
+ }}
onChangeSelection={(e) =>
editor.handleSelectionChangeEvent(e.nativeEvent)
}
@@ -111,6 +130,14 @@ export function TestScreen({
onSelectImage={editor.openImageModal}
layout="grid"
/>
+ {showScrollOffset && (
+
+ Scroll offset: {scrollOffset.toFixed(2)}
+
+ )}
@@ -223,4 +250,13 @@ const styles = StyleSheet.create({
editorInputMax: {
maxHeight: 400,
},
+ scrollOffsetOutput: {
+ width: '100%',
+ backgroundColor: 'gainsboro',
+ padding: 8,
+ color: 'rgb(0, 26, 114)',
+ fontFamily: 'Nunito-Regular',
+ fontSize: 16,
+ textAlign: 'center',
+ },
});
diff --git a/docs/docs/api-reference/enriched-text-input.md b/docs/docs/api-reference/enriched-text-input.md
index f3b12adc0..a2802ab41 100644
--- a/docs/docs/api-reference/enriched-text-input.md
+++ b/docs/docs/api-reference/enriched-text-input.md
@@ -519,6 +519,27 @@ interface OnSubmitEditing {
| -------------------------------------------------------- | ----------------- |
| `(event: NativeSyntheticEvent) => void` | Android, iOS, Web |
+### `onScroll` {#onscroll}
+
+Called when the input's content is scrolled, either by the user or
+programmatically.
+
+```ts
+interface OnScrollEvent {
+ contentOffset: {
+ x: number;
+ y: number;
+ };
+}
+```
+
+- `contentOffset` is the current scroll position of the input's content, in
+ points
+
+| Type | Platforms |
+| ------------------------------------------------------ | ----------------- |
+| `(event: NativeSyntheticEvent) => void` | Android, iOS, Web |
+
### `onPasteImages` {#onpasteimages}
Called when the user pastes one or more images or GIFs into the input. See
diff --git a/ios/EnrichedTextInputView.mm b/ios/EnrichedTextInputView.mm
index d47b3478f..ac24d7e47 100644
--- a/ios/EnrichedTextInputView.mm
+++ b/ios/EnrichedTextInputView.mm
@@ -57,6 +57,8 @@ @implementation EnrichedTextInputView {
UIColor *_placeholderColor;
BOOL _emitFocusBlur;
BOOL _emitTextChange;
+ BOOL _emitScroll;
+ CGPoint _lastEmittedContentOffset;
NSMutableDictionary *_attachmentViews;
NSArray *_contextMenuItems;
NSString *_submitBehavior;
@@ -141,6 +143,7 @@ - (void)setDefaults {
preserveTypingAttributesOnNextEmptyCheck = NO;
_emitFocusBlur = YES;
_emitTextChange = NO;
+ _emitScroll = NO;
dotReplacementRange = nullptr;
defaultTypingAttributes =
@@ -851,6 +854,9 @@ - (void)updateProps:(Props::Shared const &)props
// isOnChangeTextSet
_emitTextChange = newViewProps.isOnChangeTextSet;
+ // isOnScrollSet
+ _emitScroll = newViewProps.isOnScrollSet;
+
// contextMenuItems
bool contextMenuChanged = newViewProps.contextMenuItems.size() !=
oldViewProps.contextMenuItems.size();
@@ -1532,6 +1538,24 @@ - (void)emitOnKeyPressEvent:(NSString *)key {
emitter->onInputKeyPress({.key = [key toCppString]});
}
}
+- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
+ if (!_emitScroll) {
+ return;
+ }
+ if (CGPointEqualToPoint(scrollView.contentOffset,
+ _lastEmittedContentOffset)) {
+ return;
+ }
+ _lastEmittedContentOffset = scrollView.contentOffset;
+
+ auto emitter = [self getEventEmitter];
+ if (emitter != nullptr) {
+ emitter->onInputScroll({.contentOffset = {
+ .x = scrollView.contentOffset.x,
+ .y = scrollView.contentOffset.y,
+ }});
+ }
+}
// MARK: - Styles manipulation
diff --git a/ios/enrichedInputTextView/EnrichedInputTextView.mm b/ios/enrichedInputTextView/EnrichedInputTextView.mm
index 4dcba8bc4..c363608f9 100644
--- a/ios/enrichedInputTextView/EnrichedInputTextView.mm
+++ b/ios/enrichedInputTextView/EnrichedInputTextView.mm
@@ -7,13 +7,22 @@
#import "utils/TextListsUtils.h"
#import
-@implementation EnrichedInputTextView
+@implementation EnrichedInputTextView {
+ CGSize _lastLayoutSize;
+}
- (void)layoutSubviews {
[super layoutSubviews];
// UITextView resets contentSize during its own layout pass (triggered when
// the frame is set on first mount). Re-schedule a relayout so our explicit
// contentSize is applied after UITextView finishes its internal layout.
+ // layoutSubviews also runs on every scroll (only bounds.origin changes), so
+ // relayout only when the size changed to avoid a relayout <-> scroll loop.
+ if (CGSizeEqualToSize(self.bounds.size, _lastLayoutSize)) {
+ return;
+ }
+ _lastLayoutSize = self.bounds.size;
+
EnrichedTextInputView *input = (EnrichedTextInputView *)_input;
if (input != nil) {
[input scheduleRelayoutIfNeeded];
diff --git a/src/index.native.tsx b/src/index.native.tsx
index 8f7473c7a..23a2a073e 100644
--- a/src/index.native.tsx
+++ b/src/index.native.tsx
@@ -10,6 +10,7 @@ export type {
OnMentionDetected,
OnChangeSelectionEvent,
OnKeyPressEvent,
+ OnScrollEvent,
OnPasteImagesEvent,
OnSubmitEditing,
HtmlStyle,
diff --git a/src/index.tsx b/src/index.tsx
index e6b4e654a..2203afb39 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -11,6 +11,7 @@ export type {
OnMentionDetected,
OnChangeSelectionEvent,
OnKeyPressEvent,
+ OnScrollEvent,
OnPasteImagesEvent,
OnSubmitEditing,
HtmlStyle,
diff --git a/src/native/EnrichedTextInput.tsx b/src/native/EnrichedTextInput.tsx
index 67817c1c9..91a854f19 100644
--- a/src/native/EnrichedTextInput.tsx
+++ b/src/native/EnrichedTextInput.tsx
@@ -90,6 +90,7 @@ export const EnrichedTextInput = ({
onChangeSelection,
onKeyPress,
onSubmitEditing,
+ onScroll,
returnKeyType,
returnKeyLabel,
submitBehavior,
@@ -391,8 +392,10 @@ export const EnrichedTextInput = ({
onInputBlur={onBlur}
onChangeText={onChangeText}
onChangeHtml={onChangeHtml}
+ onInputScroll={onScroll}
isOnChangeHtmlSet={onChangeHtml !== undefined}
isOnChangeTextSet={onChangeText !== undefined}
+ isOnScrollSet={onScroll !== undefined}
onChangeState={onChangeState}
onLinkDetected={handleLinkDetected}
onMentionDetected={handleMentionDetected}
diff --git a/src/spec/EnrichedTextInputNativeComponent.ts b/src/spec/EnrichedTextInputNativeComponent.ts
index 0f90daaf9..eee357761 100644
--- a/src/spec/EnrichedTextInputNativeComponent.ts
+++ b/src/spec/EnrichedTextInputNativeComponent.ts
@@ -318,6 +318,13 @@ type Heading = {
bold?: boolean;
};
+export interface OnScrollEvent {
+ contentOffset: {
+ x: CodegenTypes.Float;
+ y: CodegenTypes.Float;
+ };
+}
+
export interface HtmlStyleInternal {
h1?: Heading;
h2?: Heading;
@@ -402,6 +409,7 @@ export interface NativeProps extends ViewProps {
onChangeSelection?: CodegenTypes.DirectEventHandler;
onRequestHtmlResult?: CodegenTypes.DirectEventHandler;
onInputKeyPress?: CodegenTypes.DirectEventHandler;
+ onInputScroll?: CodegenTypes.DirectEventHandler;
onPasteImages?: CodegenTypes.DirectEventHandler;
onContextMenuItemPress?: CodegenTypes.DirectEventHandler;
onSubmitEditing?: CodegenTypes.BubblingEventHandler;
@@ -419,6 +427,8 @@ export interface NativeProps extends ViewProps {
isOnChangeHtmlSet: boolean;
// Used for onChangeText event performance optimization
isOnChangeTextSet: boolean;
+ // Used for onScroll event performance optimization
+ isOnScrollSet: boolean;
// Experimental
androidExperimentalSynchronousEvents: boolean;
diff --git a/src/types.ts b/src/types.ts
index 78fe4db25..89fbf161a 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -434,10 +434,18 @@ export interface OnSubmitEditing {
text: string;
}
+export interface OnScrollEvent {
+ contentOffset: {
+ x: number;
+ y: number;
+ };
+}
+
// Component types
export type FocusEvent = NativeSyntheticEvent;
export type BlurEvent = NativeSyntheticEvent;
+export type ScrollEvent = NativeSyntheticEvent;
/**
* Imperative handle exposed via `ref` on ``.
@@ -807,6 +815,9 @@ export interface EnrichedTextInputProps extends Omit {
*/
onPasteImages?: (e: NativeSyntheticEvent) => void;
+ /** Called when the inputs content is scrolled by the user or programmatically. */
+ onScroll?: (e: ScrollEvent) => void;
+
/**
* Additional items to inject into the native text-selection context menu
* (the popover that appears when the user long-presses selected text).
diff --git a/src/web/EnrichedTextInput.tsx b/src/web/EnrichedTextInput.tsx
index 9f186965e..14e155c88 100644
--- a/src/web/EnrichedTextInput.tsx
+++ b/src/web/EnrichedTextInput.tsx
@@ -117,6 +117,7 @@ export const EnrichedTextInput = ({
onLinkDetected,
onLinkPress,
onSubmitEditing,
+ onScroll,
returnKeyType,
submitBehavior,
onPasteImages,
@@ -168,7 +169,6 @@ export const EnrichedTextInput = ({
const textShortcutsRef = useStableRef(textShortcuts);
const editorInstanceRef = useRef(null);
-
const handleKeyDown = (doc: Node, event: KeyboardEvent): boolean => {
onKeyPressRef.current?.(adaptWebToNativeEvent(event, { key: event.key }));
if (event.key !== 'Enter') {
@@ -189,6 +189,15 @@ export const EnrichedTextInput = ({
return false;
};
+ const handleScroll = (event: React.UIEvent) => {
+ const element = event.currentTarget;
+ onScroll?.(
+ adaptWebToNativeEvent(event, {
+ contentOffset: { x: element.scrollLeft, y: element.scrollTop },
+ })
+ );
+ };
+
const { handleLinkPress, handleLinkMouseDown } = useLinkPress(
() => onLinkPressRef.current
);
@@ -506,6 +515,7 @@ export const EnrichedTextInput = ({
}
style={finalStyle}
data-placeholder={placeholder}
+ onScroll={handleScroll}
/>
>
);