Elffuss BraidHub

kikocis/continue public

5fda066adb4e · 6.2 KiBRawPermalink
1import { Text } from "ink";
2import React from "react";
3
4import {
5 highlightCode,
6 detectLanguage,
7 SyntaxHighlighterTheme,
8 defaultTheme,
9} from "./SyntaxHighlighter.js";
10
11interface MarkdownRendererProps {
12 content: string | null | undefined;
13 theme?: SyntaxHighlighterTheme;
14}
15
16interface MarkdownPattern {
17 regex: RegExp;
18 render: (content: string, key: string) => React.ReactNode;
19}
20
21const MarkdownRenderer: React.FC<MarkdownRendererProps> = React.memo(
22 ({ content, theme = defaultTheme }) => {
23 const patterns: MarkdownPattern[] = [
24 {
25 regex: /```(?:(\w+)\n)?([\s\S]*?)```/g,
26 render: (_content, _key) => {
27 // content here is the captured group, but we need to parse the full match
28 return null; // This will be handled separately
29 },
30 },
31 {
32 regex: /^(#{1,6})\s+(.+)$/gm,
33 render: (content, key) => (
34 <Text key={key} bold>
35 {content}
36 </Text>
37 ),
38 },
39 {
40 regex: /\*\*(.+?)\*\*/g,
41 render: (content, key) => (
42 <Text key={key} bold>
43 {content}
44 </Text>
45 ),
46 },
47 {
48 regex: /\*([^\s*][^*]*[^\s*]|[^\s*])\*/g,
49 render: (content, key) => (
50 <Text key={key} italic>
51 {content}
52 </Text>
53 ),
54 },
55 {
56 regex: /_([^_]+)_/g,
57 render: (content, key) => (
58 <Text key={key} italic>
59 {content}
60 </Text>
61 ),
62 },
63 {
64 regex: /~~([^~]+)~~/g,
65 render: (content, key) => (
66 <Text key={key} strikethrough>
67 {content}
68 </Text>
69 ),
70 },
71 {
72 regex: /`([^`\n]+)`/g,
73 render: (content, key) => (
74 <Text key={key} color="magentaBright">
75 {content}
76 </Text>
77 ),
78 },
79 ];
80
81 const renderMarkdown = (text: string | null | undefined) => {
82 const parts: React.ReactNode[] = [];
83
84 // Handle null/undefined text
85 if (!text) {
86 return parts;
87 }
88
89 let currentIndex = 0;
90
91 // First, handle code blocks separately
92 const codeBlockRegex = /```(?:(\w+)\n)?([\s\S]*?)```/g;
93 const codeBlocks: Array<{
94 index: number;
95 length: number;
96 language: string;
97 code: string;
98 }> = [];
99
100 let codeMatch;
101 while ((codeMatch = codeBlockRegex.exec(text)) !== null) {
102 const language = codeMatch[1] || detectLanguage(codeMatch[2]);
103 codeBlocks.push({
104 index: codeMatch.index,
105 length: codeMatch[0].length,
106 language,
107 code: codeMatch[2].trim(),
108 });
109 }
110
111 // Find all matches for other patterns (excluding code blocks)
112 const allMatches: Array<{
113 index: number;
114 length: number;
115 content: string;
116 render: (content: string, key: string) => React.ReactNode;
117 }> = [];
118
119 patterns.slice(1).forEach((pattern) => {
120 // Skip the first pattern (code blocks)
121 let match: RegExpExecArray | null;
122 const regex = new RegExp(pattern.regex.source, pattern.regex.flags);
123
124 while ((match = regex.exec(text)) !== null) {
125 // Skip if this match is inside a code block
126 const isInCodeBlock = codeBlocks.some(
127 (block) =>
128 match!.index >= block.index &&
129 match!.index < block.index + block.length,
130 );
131
132 if (!isInCodeBlock) {
133 allMatches.push({
134 index: match.index,
135 length: match[0].length,
136 content: match[2] || match[1], // Use second capture group for headings, first for others
137 render: pattern.render,
138 });
139 }
140 }
141 });
142
143 // Combine code blocks and other matches
144 const combinedMatches: Array<{
145 index: number;
146 length: number;
147 type: "code" | "other";
148 content?: string;
149 render?: (content: string, key: string) => React.ReactNode;
150 language?: string;
151 code?: string;
152 }> = [
153 ...codeBlocks.map((block) => ({
154 index: block.index,
155 length: block.length,
156 type: "code" as const,
157 language: block.language,
158 code: block.code,
159 })),
160 ...allMatches.map((match) => ({
161 index: match.index,
162 length: match.length,
163 type: "other" as const,
164 content: match.content,
165 render: match.render,
166 })),
167 ];
168
169 // Sort matches by index to process them in order
170 combinedMatches.sort((a, b) => a.index - b.index);
171
172 // Process matches, avoiding overlaps
173 const processedMatches: typeof combinedMatches = [];
174 for (const match of combinedMatches) {
175 const overlaps = processedMatches.some(
176 (processed) =>
177 (match.index >= processed.index &&
178 match.index < processed.index + processed.length) ||
179 (processed.index >= match.index &&
180 processed.index < match.index + match.length),
181 );
182
183 if (!overlaps) {
184 processedMatches.push(match);
185 }
186 }
187
188 // Render the text with formatting
189 processedMatches.forEach((match, idx) => {
190 // Add text before this match
191 if (match.index > currentIndex) {
192 parts.push(text.slice(currentIndex, match.index));
193 }
194
195 // Add the formatted match
196 if (match.type === "code") {
197 const highlightedCode = highlightCode(
198 match.code!,
199 match.language!,
200 theme,
201 );
202 parts.push(
203 <Text key={`code-${idx}-${match.index}`}>{highlightedCode}</Text>,
204 );
205 } else {
206 parts.push(
207 match.render!(match.content!, `format-${idx}-${match.index}`),
208 );
209 }
210
211 currentIndex = match.index + match.length;
212 });
213
214 // Add remaining text
215 if (currentIndex < text.length) {
216 parts.push(text.slice(currentIndex));
217 }
218
219 return parts;
220 };
221
222 return <Text>{renderMarkdown(content)}</Text>;
223 },
224);
225
226MarkdownRenderer.displayName = "MarkdownRenderer";
227
228export { MarkdownRenderer };
229export type { SyntaxHighlighterTheme };
230export { defaultTheme };