Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MarkdownTextPrimitive.tsx

174 lines5.5 KB

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