diff --git a/apps/android/src/ui/mermaid/mermaid-block.tsx b/apps/android/src/ui/mermaid/mermaid-block.tsx new file mode 100644 index 0000000..9dcbe62 --- /dev/null +++ b/apps/android/src/ui/mermaid/mermaid-block.tsx @@ -0,0 +1,198 @@ +import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { ActivityIndicator, Modal, Pressable, StyleSheet, Text, View, useWindowDimensions, type LayoutChangeEvent } from 'react-native' +import * as Clipboard from 'expo-clipboard' +import { Code, Maximize2, Shapes, X } from 'lucide-react-native' +import { SvgXml } from 'react-native-svg' +import { WebView } from 'react-native-webview' +import { SafeAreaView } from 'react-native-safe-area-context' +import { strings as t } from '../../locales/i18n' +import { CodeBlockView } from '../code-block' +import { IconCheckOutline, IconCopyOutline } from '../dsh-icons' +import { useTheme } from '../theme-context' +import { MAX_MERMAID_SOURCE_CHARS, mermaidThemeFor, useMermaidDiagram, type MermaidDiagram } from './mermaid-renderer' + +/** Streaming replies grow a fence chunk by chunk; render only once the source stops changing. */ +const SETTLE_MS = 700 +const COPY_RESET_MS = 2000 +const PLACEHOLDER_HEIGHT = 120 +const BODY_PADDING = 10 + +function useSettled(value: string): string { + const [settled, setSettled] = useState(value) + useEffect(() => { + if (value === settled) return + const timer = setTimeout(() => setSettled(value), SETTLE_MS) + return () => clearTimeout(timer) + }, [value, settled]) + return settled +} + +export const MermaidBlock = memo(function MermaidBlock({ code }: { code: string }) { + const { colors, scheme } = useTheme() + const source = (code || '').replace(/\n+$/u, '') + const settled = useSettled(source) + const streaming = settled !== source + const tooLarge = source.length > MAX_MERMAID_SOURCE_CHARS + const theme = useMemo(() => mermaidThemeFor(colors, scheme === 'dark'), [colors, scheme]) + const requested = !streaming && !tooLarge && source.trim() !== '' + const state = useMermaidDiagram(requested ? source : undefined, theme) + const [showSource, setShowSource] = useState(false) + const [viewer, setViewer] = useState(false) + const [copied, setCopied] = useState(false) + const [width, setWidth] = useState(0) + const copyTimer = useRef | null>(null) + + useEffect(() => () => { if (copyTimer.current) clearTimeout(copyTimer.current) }, []) + + const copy = useCallback(async () => { + try { + await Clipboard.setStringAsync(source) + setCopied(true) + if (copyTimer.current) clearTimeout(copyTimer.current) + copyTimer.current = setTimeout(() => setCopied(false), COPY_RESET_MS) + } catch { + // Clipboard can be unavailable; the source stays selectable in source view. + } + }, [source]) + + const onLayout = useCallback((event: LayoutChangeEvent) => { + setWidth(Math.max(0, event.nativeEvent.layout.width - BODY_PADDING * 2)) + }, []) + + // While streaming, while hidden behind the source toggle, and on failure the plain code block + // is the content; a failure adds a one-line note above it. + if (!requested || state?.status === 'error') { + const note = tooLarge ? t.diagram.tooLarge : !streaming && state?.status === 'error' ? t.diagram.failed : undefined + return + {note !== undefined && {note}} + + + } + if (showSource) { + return + + setShowSource(false)} hitSlop={6} style={styles.backToDiagram}> + + {t.diagram.showDiagram} + + + } + + const diagram = state?.status === 'ready' ? state.diagram : undefined + return ( + + + mermaid + + setShowSource(true)}> + + + + {copied ? : } + + {diagram !== undefined && setViewer(true)}> + + } + + + + {diagram === undefined + ? + + {t.diagram.rendering} + + : setViewer(true)} onLongPress={copy} delayLongPress={400}> + {diagram.inline !== undefined && width > 0 + ? + : diagram.inline !== undefined + ? + : + + {t.diagram.fullScreenOnly} + {t.diagram.tapToOpen} + } + } + + {diagram !== undefined && viewer && setViewer(false)} onCopy={copy} copied={copied} />} + + ) +}) + +function HeaderButton({ label, onPress, children }: { label: string; onPress: () => void; children: React.ReactNode }) { + return [styles.actionButton, { opacity: pressed ? 0.6 : 1 }]}> + {children} + +} + +function InlineDiagram({ diagram, xml, width }: { diagram: MermaidDiagram; xml: string; width: number }) { + // Shrink wide diagrams to the bubble; never enlarge small ones past their natural size. + const scale = Math.min(1, width / diagram.width) + return + + +} + +/** + * The untouched SVG is shown as an , which never runs scripts, so the page needs no + * JavaScript at all; the WebView's own pinch zoom handles scaling. Diagrams with HTML labels, + * which react-native-svg cannot draw, are always shown here. + */ +function DiagramViewer({ diagram, onClose, onCopy, copied }: { diagram: MermaidDiagram; onClose: () => void; onCopy: () => void; copied: boolean }) { + const { colors } = useTheme() + const { width } = useWindowDimensions() + const html = useMemo(() => viewerHtml(diagram, colors.background, width), [diagram, colors.background, width]) + return + + + + + + {t.diagram.label} + + {copied ? : } + + + undefined} + onShouldStartLoadWithRequest={request => request.url === 'about:blank'} /> + + +} + +function viewerHtml(diagram: MermaidDiagram, background: string, screenWidth: number): string { + const src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(diagram.svg)}` + // Start fitted to the screen; pinch zoom goes up to eight times that. + const fit = Math.min(1, (screenWidth - 24) / diagram.width) + const widthPx = Math.max(1, Math.round(diagram.width * fit)) + return ` + + + +` +} + +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' }, + body: { padding: BODY_PADDING }, + placeholder: { minHeight: PLACEHOLDER_HEIGHT, alignItems: 'center', justifyContent: 'center', gap: 8 }, + inline: { alignItems: 'center' }, + fullScreenCard: { minHeight: PLACEHOLDER_HEIGHT, borderRadius: 10, alignItems: 'center', justifyContent: 'center', gap: 6, padding: 12 }, + cardTitle: { fontWeight: '600' }, + note: { fontSize: 12, marginTop: 6 }, + backToDiagram: { flexDirection: 'row', alignItems: 'center', gap: 6, alignSelf: 'flex-start', paddingVertical: 4 }, + link: { fontSize: 13, fontWeight: '600' }, + viewer: { flex: 1 }, + viewerBar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 8, height: 52, borderBottomWidth: StyleSheet.hairlineWidth }, + viewerButton: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, + viewerTitle: { fontSize: 16, fontWeight: '600' }, +})