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

MarkdownTextPrimitive.tsx

124 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 onContextMenuAction?: (event: ContextMenuActionEvent) => void;
40 /**
41 * Fired when the native text selection changes. Only fires on iOS when
42 * `uiTextView` is true. Note: fires on every selection-edge adjustment
43 * (e.g. dragging a selection handle), so consumers driving expensive work
44 * off this event should debounce.
45 */
46 onSelectionChange?: (event: SelectionChangeEvent) => void;
47};
48​
49function MarkdownTextPrimitiveChild({
50 style,
51 children,
52 nativeTextRef: _nativeTextRef,
53 ...rest
54}: MarkdownTextPrimitiveProps) {
55 const [isAncestor, rootStyle] = useTextAncestorContext();
56​
57 // Flatten the styles, and apply the root styles when needed
58 const flattenedStyle = React.useMemo(() => flattenStyles(rootStyle, style), [rootStyle, style]);
59 const contextValue = React.useMemo<[boolean, ViewStyle]>(
60 () => [true, flattenedStyle],
61 [flattenedStyle],
62 );
63 let childPosition = 0;
64 const nativeChildren = React.Children.toArray(children).map((child) => {
65 const position = childPosition;
66 childPosition += 1;
67​
68 if (React.isValidElement(child)) {
69 return child;
70 }
71 if (typeof child !== "string" && typeof child !== "number") {
72 return null;
73 }
74​
75 const text = child.toString();
76 return (
77 // @ts-expect-error The generated run props do not include inherited Text props.
78 <T3MarkdownTextRunNativeComponent
79 key={`text-${position}-${text.length}-${text}`}
80 style={flattenedStyle}
81 text={text}
82 {...rest}
83 />
84 );
85 });
86​
87 if (!isAncestor) {
88 // Press handlers are delivered by the text runs; the container never sees them.
89 const { onPress: _onPress, onLongPress: _onLongPress, ...containerProps } = rest;
90 return (
91 <TextAncestorContext.Provider value={contextValue}>
92 <T3MarkdownTextNativeComponent
93 {...textDefaults}
94 {...containerProps}
95 style={[flattenedStyle]}
96 >
97 {nativeChildren}
98 </T3MarkdownTextNativeComponent>
99 </TextAncestorContext.Provider>
100 );
101 }
102​
103 return <>{nativeChildren}</>;
105​
106function MarkdownTextPrimitiveInner({ nativeTextRef, ...props }: MarkdownTextPrimitiveProps) {
107 const [isAncestor] = useTextAncestorContext();
108​
109 // Even if the uiTextView prop is set, we can still default to using
110 // normal selection (i.e. base RN text) if the text doesn't need to be
111 // selectable
112 if ((!props.selectable || !props.uiTextView) && !isAncestor) {
113 return <RNText ref={nativeTextRef} {...props} />;
114 }
115 return <MarkdownTextPrimitiveChild {...props} />;
117​
118export function MarkdownTextPrimitive(props: MarkdownTextPrimitiveProps) {
119 if (Platform.OS !== "ios") {
120 const { nativeTextRef, ...textProps } = props;
121 return <RNText ref={nativeTextRef} {...textProps} />;
122 }
123 return <MarkdownTextPrimitiveInner {...props} />;