-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCodeHighlighter.tsx
More file actions
107 lines (98 loc) · 2.43 KB
/
CodeHighlighter.tsx
File metadata and controls
107 lines (98 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import React, { type FunctionComponent, type ReactNode, useMemo } from "react";
import {
ScrollView,
type ScrollViewProps,
type StyleProp,
StyleSheet,
Text,
type TextStyle,
View,
type ViewStyle,
} from "react-native";
import SyntaxHighlighter, {
type SyntaxHighlighterProps,
} from "react-syntax-highlighter";
import { trimNewlines } from "trim-newlines";
import {
getRNStylesFromHljsStyle,
type HighlighterStyleSheet,
type ReactStyle,
} from "./../utils/styles";
export interface CodeHighlighterProps extends SyntaxHighlighterProps {
hljsStyle: ReactStyle;
textStyle?: StyleProp<TextStyle>;
scrollViewProps?: ScrollViewProps;
children: string | string[];
/**
* @deprecated Use scrollViewProps.contentContainerStyle instead
*/
containerStyle?: StyleProp<ViewStyle>;
}
const CodeHighlighter: FunctionComponent<CodeHighlighterProps> = ({
children,
textStyle,
hljsStyle,
scrollViewProps,
containerStyle,
...rest
}) => {
const stylesheet: HighlighterStyleSheet = useMemo(
() => getRNStylesFromHljsStyle(hljsStyle),
[hljsStyle],
);
const getStylesForNode = (node: rendererNode): TextStyle[] => {
const classes: string[] = node.properties?.className ?? [];
return classes
.map((c: string) => stylesheet[c])
.filter((c) => !!c) as TextStyle[];
};
const renderNode = (nodes: rendererNode[], keyPrefix = "row") =>
nodes.reduce<ReactNode[]>((acc, node, index) => {
const keyPrefixWithIndex = `${keyPrefix}_${index}`;
if (node.children) {
const styles = StyleSheet.flatten([
textStyle,
{ color: stylesheet.hljs?.color },
getStylesForNode(node),
]);
acc.push(
<Text style={styles} key={keyPrefixWithIndex}>
{renderNode(node.children, `${keyPrefixWithIndex}_child`)}
</Text>,
);
}
if (node.value) {
acc.push(trimNewlines(String(node.value)));
}
return acc;
}, []);
const renderer = (props: rendererProps) => {
const { rows } = props;
return (
<ScrollView
{...scrollViewProps}
horizontal
contentContainerStyle={[
stylesheet.hljs,
scrollViewProps?.contentContainerStyle,
containerStyle,
]}
>
<View onStartShouldSetResponder={() => true}>{renderNode(rows)}</View>
</ScrollView>
);
};
return (
<SyntaxHighlighter
{...rest}
renderer={renderer}
CodeTag={View}
PreTag={View}
style={{}}
testID="react-native-code-highlighter"
>
{children}
</SyntaxHighlighter>
);
};
export default CodeHighlighter;