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

SourceText.tsx

53 lines2.0 KB

1import React, { type ComponentRef, type Ref } from "react";
2import { Platform, StyleSheet, Text, type TextProps, type TextStyle } from "react-native";
3import T3SourceTextRunNativeComponent from "./T3SourceTextRunNativeComponent";
4import T3SourceTextNativeComponent from "./T3SourceTextNativeComponent";
5import { flattenStyles } from "./util";
6​
7const TextAncestorContext = React.createContext<[boolean, TextStyle]>([false, {}]);
8​
9export type SourceTextProps = Omit<TextProps, "onTextLayout" | "onPress" | "onLongPress"> & {
10 nativeTextRef?: Ref<ComponentRef<typeof Text>>;
11 onSelectionChange?: (event: {
12 nativeEvent: { target: number; start: number; end: number };
13 }) => void;
14};
15​
16export function SourceText({ style, children, nativeTextRef, ...props }: SourceTextProps) {
17 const [isAncestor, rootStyle] = React.useContext(TextAncestorContext);
18 const flattenedStyle = React.useMemo(() => flattenStyles(rootStyle, style), [rootStyle, style]);
19 const contextValue = React.useMemo<[boolean, TextStyle]>(
20 () => [true, StyleSheet.flatten([rootStyle, style]) ?? {}],
21 [rootStyle, style],
22 );
23 if (Platform.OS !== "ios") {
24 const { onSelectionChange: _onSelectionChange, ...textProps } = props;
25 return (
26 <Text ref={nativeTextRef} style={style} {...textProps}>
27 {children}
28 </Text>
29 );
30 }
31 const runs = React.Children.toArray(children).map((child, index) => {
32 if (React.isValidElement(child)) return child;
33 if (typeof child !== "string" && typeof child !== "number") return null;
34 return (
35 <T3SourceTextRunNativeComponent
36 key={index}
37 style={flattenedStyle}
38 {...flattenedStyle}
39 text={String(child)}
40 />
41 );
42 });
43 if (isAncestor) {
44 return <TextAncestorContext.Provider value={contextValue}>{runs}</TextAncestorContext.Provider>;
45 }
46 return (
47 <TextAncestorContext.Provider value={contextValue}>
48 <T3SourceTextNativeComponent allowFontScaling selectable {...props} style={flattenedStyle}>
49 {runs}
50 </T3SourceTextNativeComponent>
51 </TextAncestorContext.Provider>
52 );