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

MarkdownTextPrimitive.tsx

125 lines4.1 KB

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