diff --git a/apps/android/src/ui/code-block.tsx b/apps/android/src/ui/code-block.tsx new file mode 100644 index 0000000..9631293 --- /dev/null +++ b/apps/android/src/ui/code-block.tsx @@ -0,0 +1,184 @@ +import React, { memo, useCallback, useEffect, useRef, useState } from 'react' +import { + Pressable, + ScrollView, + StyleSheet, + Text, + View, + type StyleProp, + type ViewStyle, +} from 'react-native' +import * as Clipboard from 'expo-clipboard' +import { useTheme } from './theme-context' +import { IconWrapFill, IconNowrapFill, IconCopyOutline, IconCheckOutline } from './dsh-icons' + +export interface CodeBlockProps { + code: string + language?: string + style?: StyleProp +} + +const MONOSPACE_FONT = 'monospace' +const COPY_RESET_MS = 2000 + +export const CodeBlockView = memo(function CodeBlockView({ code, language, style }: CodeBlockProps) { + const { colors, density } = useTheme() + const isCompact = density === 'compact' + const [wrap, setWrap] = useState(false) + const [copied, setCopied] = useState(false) + const timeoutRef = useRef | null>(null) + + const cleanCode = (code || '').replace(/\n+$/u, '') + const label = (language || 'code').toLowerCase() + + useEffect(() => { + return () => { + if (timeoutRef.current) clearTimeout(timeoutRef.current) + } + }, []) + + const handleToggleWrap = useCallback(() => { + setWrap(prev => !prev) + }, []) + + const handleCopy = useCallback(async () => { + try { + await Clipboard.setStringAsync(cleanCode) + setCopied(true) + if (timeoutRef.current) clearTimeout(timeoutRef.current) + timeoutRef.current = setTimeout(() => setCopied(false), COPY_RESET_MS) + } catch { + // Ignore clipboard error on devices without permission + } + }, [cleanCode]) + + return ( + + + + {label} + + + [ + styles.actionButton, + { opacity: pressed ? 0.6 : 1 }, + ]} + > + {wrap ? ( + + ) : ( + + )} + + [ + styles.actionButton, + { opacity: pressed ? 0.6 : 1 }, + ]} + > + {copied ? ( + + ) : ( + + )} + + + + + {wrap ? ( + + + {cleanCode} + + + ) : ( + + + {cleanCode} + + + )} + + ) +}) + +const styles = StyleSheet.create({ + container: { + borderRadius: 12, + borderWidth: StyleSheet.hairlineWidth, + overflow: 'hidden', + marginVertical: 6, + alignSelf: 'stretch', + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingHorizontal: 10, + paddingVertical: 5, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + language: { + fontSize: 11, + fontWeight: '600', + letterSpacing: 0.3, + textTransform: 'uppercase', + }, + actions: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + }, + actionButton: { + width: 26, + height: 26, + borderRadius: 4, + alignItems: 'center', + justifyContent: 'center', + }, + scrollContent: { + minWidth: '100%', + }, + wrapBody: {}, + codeText: { + fontFamily: MONOSPACE_FONT, + includeFontPadding: false, + }, +})