Open History to see the last commit
1import React, { type Ref } from "react";
2import {
3 findNodeHandle,
4 Platform,
5 processColor,
6 StyleSheet,
7 Text as RNText,
8 type ColorValue,
9 type TextInstance,
10 type TextProps,
11 type ViewStyle,
12} from "react-native";
13import { setMarkdownSelectionHandleColor } from "./T3MarkdownTextSelectionModule";
14import T3MarkdownTextRunNativeComponent from "./T3MarkdownTextRunNativeComponent";
15import T3MarkdownTextNativeComponent from "./T3MarkdownTextNativeComponent";
16import { flattenStyles } from "./util";
17
18const TextAncestorContext = React.createContext<[boolean, ViewStyle]>([
19 false,
20 StyleSheet.create({}),
21]);
22
23const textDefaults = {
24 allowFontScaling: true,
25 selectable: true,
26} satisfies TextProps;
27
28const useTextAncestorContext = () => React.useContext(TextAncestorContext);
29
30/**
31 * Event fired by `onSelectionChange`. `start`/`end` are 0-based UTF-16 indices
32 * into the rendered string. `start === end` means the selection was cleared.
33 */
34export type SelectionChangeEvent = {
35 nativeEvent: { target: number; start: number; end: number };
36};
37
38export type ContextMenuActionEvent = {
39 nativeEvent: { target: number; actionIdentifier: string };
40};
41
42/**
43 * `onTextLayout` is not offered: the native view reports plain line strings
44 * while the React Native Text fallback reports measured `TextLayoutLine`s.
45 */
46export type MarkdownTextPrimitiveProps = Omit<TextProps, "onTextLayout"> & {
47 nativeTextRef?: Ref<TextInstance>;
48 selectionHandleColor?: ColorValue;
49 uiTextView?: boolean;
50 contextMenuConfig?: string;
51 contextClipboardConfig?: string;
52 onContextMenuAction?: (event: ContextMenuActionEvent) => void;
53 /**
54 * Fired when the native text selection changes. Only fires on iOS when
55 * `uiTextView` is true. Note: fires on every selection-edge adjustment
56 * (e.g. dragging a selection handle), so consumers driving expensive work
57 * off this event should debounce.
58 */
59 onSelectionChange?: (event: SelectionChangeEvent) => void;
60};
61
62function MarkdownTextPrimitiveChild({
63 style,
64 children,
65 nativeTextRef: _nativeTextRef,
66 ...rest
67}: MarkdownTextPrimitiveProps) {
68 const [isAncestor, rootStyle] = useTextAncestorContext();
69
70 // Flatten the styles, and apply the root styles when needed
71 const flattenedStyle = React.useMemo(() => flattenStyles(rootStyle, style), [rootStyle, style]);
72 const contextValue = React.useMemo<[boolean, ViewStyle]>(
73 () => [true, flattenedStyle],
74 [flattenedStyle],
75 );
76 let childPosition = 0;
77 const nativeChildren = React.Children.toArray(children).map((child) => {
78 const position = childPosition;
79 childPosition += 1;
80
81 if (React.isValidElement(child)) {
82 return child;
83 }
84 if (typeof child !== "string" && typeof child !== "number") {
85 return null;
86 }
87
88 const text = child.toString();
89 return (
90 // @ts-expect-error The generated run props do not include inherited Text props.
91 <T3MarkdownTextRunNativeComponent
92 key={`text-${position}-${text.length}-${text}`}
93 style={flattenedStyle}
94 text={text}
95 {...rest}
96 />
97 );
98 });
99
100 if (!isAncestor) {
101 // Press handlers are delivered by the text runs; the container never sees them.
102 const { onPress: _onPress, onLongPress: _onLongPress, ...containerProps } = rest;
103 return (
104 <TextAncestorContext.Provider value={contextValue}>
105 <T3MarkdownTextNativeComponent
106 {...textDefaults}
107 {...containerProps}
108 style={[flattenedStyle]}
109 >
110 {nativeChildren}
111 </T3MarkdownTextNativeComponent>
112 </TextAncestorContext.Provider>
113 );
114 }
115
116 return <>{nativeChildren}</>;
117}
118
119function MarkdownTextPrimitiveInner({ nativeTextRef, ...props }: MarkdownTextPrimitiveProps) {
120 const [isAncestor] = useTextAncestorContext();
121
122 // Even if the uiTextView prop is set, we can still default to using
123 // normal selection (i.e. base RN text) if the text doesn't need to be
124 // selectable
125 if ((!props.selectable || !props.uiTextView) && !isAncestor) {
126 return <RNText ref={nativeTextRef} {...props} />;
127 }
128 return <MarkdownTextPrimitiveChild {...props} />;
129}
130
131function AndroidMarkdownText({
132 nativeTextRef,
133 selectionHandleColor,
134 onLayout,
135 contextClipboardConfig: _contextClipboardConfig,
136 ...props
137}: MarkdownTextPrimitiveProps) {
138 const textRef = React.useRef<TextInstance | null>(null);
139 React.useImperativeHandle<TextInstance | null, TextInstance | null>(
140 nativeTextRef,
141 () => textRef.current,
142 [],
143 );
144 const color = processColor(selectionHandleColor);
145 const applyHandleColor = React.useCallback(() => {
146 if (!textRef.current || typeof color !== "number") return;
147 const reactTag = findNodeHandle(textRef.current);
148 if (reactTag != null) setMarkdownSelectionHandleColor(reactTag, color);
149 }, [color]);
150
151 // RN's selectionColor only sets the highlight. Retint mounted handles when
152 // the theme changes, and after layout when the native view first exists.
153 React.useEffect(applyHandleColor, [applyHandleColor]);
154
155 return (
156 <RNText
157 ref={textRef}
158 {...props}
159 onLayout={(event) => {
160 applyHandleColor();
161 onLayout?.(event);
162 }}
163 />
164 );
165}
166
167export function MarkdownTextPrimitive({
168 selectionHandleColor,
169 ...props
170}: MarkdownTextPrimitiveProps) {
171 if (Platform.OS === "android" && selectionHandleColor !== undefined) {
172 return <AndroidMarkdownText {...props} selectionHandleColor={selectionHandleColor} />;
173 }
174 if (Platform.OS !== "ios") {
175 const { nativeTextRef, contextClipboardConfig: _contextClipboardConfig, ...textProps } = props;
176 return <RNText ref={nativeTextRef} {...textProps} />;
177 }
178 return <MarkdownTextPrimitiveInner {...props} />;
179}