|
| 1 | + |
| 2 | +import React, { useState } from 'react'; |
| 3 | +import { |
| 4 | + LayoutChangeEvent, |
| 5 | + Pressable, |
| 6 | + StyleSheet, |
| 7 | + Text, |
| 8 | + View, |
| 9 | + useColorScheme, |
| 10 | +} from 'react-native'; |
| 11 | +import Animated, { |
| 12 | + useAnimatedStyle, |
| 13 | + useSharedValue, |
| 14 | + withTiming, |
| 15 | +} from 'react-native-reanimated'; |
| 16 | +import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; |
| 17 | +import { ghcolors, tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism'; |
| 18 | + |
| 19 | +interface CodeSnippetProps { |
| 20 | + code: string; |
| 21 | +} |
| 22 | + |
| 23 | +export default function CodeSnippet({ code }: CodeSnippetProps): JSX.Element { |
| 24 | + const colorScheme = useColorScheme(); |
| 25 | + const backgroundColor = colorScheme === 'dark' ? '#333' : '#f5f5f5'; |
| 26 | + const color = colorScheme === 'dark' ? '#fff' : '#222'; |
| 27 | + const syntaxStyle = colorScheme === 'dark' ? tomorrow : ghcolors; |
| 28 | + |
| 29 | + const [isExpanded, setIsExpanded] = useState(false); |
| 30 | + const height = useSharedValue(0); |
| 31 | + const contentHeight = useSharedValue(0); |
| 32 | + |
| 33 | + const animatedStyle = useAnimatedStyle(() => ({ |
| 34 | + height: height.value, |
| 35 | + })); |
| 36 | + |
| 37 | + const toggle = () => { |
| 38 | + height.value = withTiming(isExpanded ? 0 : contentHeight.value, { |
| 39 | + duration: 300, |
| 40 | + }); |
| 41 | + setIsExpanded(!isExpanded); |
| 42 | + }; |
| 43 | + |
| 44 | + const onLayout = (event: LayoutChangeEvent) => { |
| 45 | + contentHeight.value = event.nativeEvent.layout.height; |
| 46 | + }; |
| 47 | + |
| 48 | + return ( |
| 49 | + <View style={[styles.container, { backgroundColor }]}> |
| 50 | + <Pressable onPress={toggle} style={styles.header}> |
| 51 | + <Text style={[styles.headerText, { color }]}> |
| 52 | + {isExpanded ? 'Hide Code' : 'Show Code'} |
| 53 | + </Text> |
| 54 | + </Pressable> |
| 55 | + <Animated.View style={animatedStyle}> |
| 56 | + <View onLayout={onLayout} style={styles.codeContainer}> |
| 57 | + <SyntaxHighlighter language='jsx' style={syntaxStyle}> |
| 58 | + {code} |
| 59 | + </SyntaxHighlighter> |
| 60 | + </View> |
| 61 | + </Animated.View> |
| 62 | + </View> |
| 63 | + ); |
| 64 | +} |
| 65 | + |
| 66 | +const styles = StyleSheet.create({ |
| 67 | + container: { |
| 68 | + marginVertical: 10, |
| 69 | + borderRadius: 5, |
| 70 | + overflow: 'hidden', |
| 71 | + }, |
| 72 | + header: { |
| 73 | + padding: 10, |
| 74 | + }, |
| 75 | + headerText: { |
| 76 | + fontWeight: 'bold', |
| 77 | + }, |
| 78 | + codeContainer: { |
| 79 | + position: 'absolute', |
| 80 | + top: 0, |
| 81 | + left: 0, |
| 82 | + right: 0, |
| 83 | + }, |
| 84 | +}); |
0 commit comments