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

SourceText.tsx

58 lines2.3 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(
32 (
33 child,
34 index,
35 ) => /* oxlint-disable react/no-array-index-key -- Native text runs are stateless positions within the supplied text. */ {
36 if (React.isValidElement(child)) return child;
37 if (typeof child !== "string" && typeof child !== "number") return null;
38 return (
39 <T3SourceTextRunNativeComponent
40 key={index}
41 style={flattenedStyle}
42 {...flattenedStyle}
43 text={String(child)}
44 />
45 );
46 } /* oxlint-enable react/no-array-index-key */,
47 );
48 if (isAncestor) {
49 return <TextAncestorContext.Provider value={contextValue}>{runs}</TextAncestorContext.Provider>;
50 }
51 return (
52 <TextAncestorContext.Provider value={contextValue}>
53 <T3SourceTextNativeComponent allowFontScaling selectable {...props} style={flattenedStyle}>
54 {runs}
55 </T3SourceTextNativeComponent>
56 </TextAncestorContext.Provider>
57 );