/** * Markdown renderer utility for React Native * Converts markdown to plain text with proper formatting */ export class MarkdownRenderer { /** * Parse markdown and convert to plain text with formatting */ static parseMarkdown(text: string): string { if (!text) return ""; let result = text; // Handle line separators (---) first to avoid confusion with bullet points result = result.replace(/^---$/gm, "─────────"); // Handle headers result = result.replace(/^#{1,6}\s+(.+)$/gm, "$1"); // Handle bold text result = result.replace(/\*\*(.+?)\*\*/g, "$1"); result = result.replace(/__(.+?)__/g, "$1"); // Handle italic text result = result.replace(/\*(.+?)\*/g, "$1"); result = result.replace(/_(.+?)_/g, "$1"); // Handle inline code result = result.replace(/`([^`]+)`/g, "$1"); // Handle code blocks (preserve code content, remove formatting markers) result = result.replace(/```(?:[a-zA-Z0-9]*)?\n?([\s\S]*?)```/g, "\n$1\n"); // Handle bullet points (both - and *) result = result.replace(/^[\s]*[-*]\s+(.+)$/gm, "• $1"); // Handle numbered lists result = result.replace(/^[\s]*\d+\.\s+(.+)$/gm, "$1"); // Handle blockquotes result = result.replace(/^>\s+(.+)$/gm, "$1"); // Handle strikethrough result = result.replace(/~~(.+?)~~/g, "$1"); // Handle links (keep only the text) result = result.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1"); result = result.replace(/\[([^\]]+)\]\[[^\]]+\]/g, "$1"); // Handle emphasis combinations result = result.replace(/\*\*\*(.+?)\*\*\*/g, "$1"); // bold + italic result = result.replace(/___(.+?)___/g, "$1"); // bold + italic // Clean up extra whitespace result = result.replace(/\n\s*\n\s*\n/g, "\n\n"); // Multiple empty lines to double result = result.replace(/^\s+|\s+$/gm, ""); // Trim lines result = result.replace(/\n\n+/g, "\n\n"); // Multiple newlines to double return result.trim(); } /** * Check if text contains markdown formatting */ static isMarkdown(text: string): boolean { if (!text) return false; const markdownPatterns = [ /\*\*.*?\*\*/, // Bold /\*.*?\*/, // Italic /`.*?`/, // Inline code /^#{1,6}\s/, // Headers /^[-*]\s/, // Bullet points /^>\s/, // Blockquotes /~~.*?~~/, // Strikethrough /\[.*?\]\(.*?\)/, // Links /^---$/, // Line separators /```[\s\S]*?```/, // Code blocks ]; return markdownPatterns.some((pattern) => pattern.test(text)); } /** * Extract code blocks from markdown */ static extractCodeBlocks(text: string): string[] { if (!text) return []; const codeBlockRegex = /```(?:[\w-]+\n)?([\s\S]*?)```/g; const blocks: string[] = []; let match; while ((match = codeBlockRegex.exec(text)) !== null) { blocks.push(match[1]?.trim() || ""); } return blocks; } /** * Extract headers from markdown */ static extractHeaders(text: string): string[] { if (!text) return []; const headerRegex = /^#{1,6}\s+(.+)$/gm; const headers: string[] = []; let match; while ((match = headerRegex.exec(text)) !== null) { headers.push(match[1]?.trim() || ""); } return headers; } /** * Extract bullet points from markdown */ static extractBulletPoints(text: string): string[] { if (!text) return []; const bulletRegex = /^[\s]*[-*]\s+(.+)$/gm; const bullets: string[] = []; let match; while ((match = bulletRegex.exec(text)) !== null) { bullets.push(match[1]?.trim() || ""); } return bullets; } /** * Extract numbered list items from markdown */ static extractNumberedList(text: string): string[] { if (!text) return []; const numberedRegex = /^[\s]*\d+\.\s+(.+)$/gm; const items: string[] = []; let match; while ((match = numberedRegex.exec(text)) !== null) { items.push(match[1]?.trim() || ""); } return items; } /** * Extract blockquotes from markdown */ static extractBlockquotes(text: string): string[] { if (!text) return []; const blockquoteRegex = /^>\s+(.+)$/gm; const quotes: string[] = []; let match; while ((match = blockquoteRegex.exec(text)) !== null) { quotes.push(match[1]?.trim() || ""); } return quotes; } /** * Detect all copyable sections in markdown content * Returns sections for: code blocks, tables, lists, and paragraphs (header + text) */ static detectCopyableSections(markdown: string): Array<{ type: "code" | "table" | "list" | "paragraph"; content: string; startIndex: number; endIndex: number; heading?: string; }> { if (!markdown) return []; const sections: Array<{ type: "code" | "table" | "list" | "paragraph"; content: string; startIndex: number; endIndex: number; heading?: string; }> = []; // 1. Code blocks: ```...``` const codeBlockRegex = /```[\s\S]*?```/g; let match: RegExpExecArray | null; while ((match = codeBlockRegex.exec(markdown)) !== null) { sections.push({ type: "code", content: match[0], startIndex: match.index, endIndex: match.index + match[0].length, }); } // 2. Tables: lines with | separators (at least 2 rows with consistent structure) const tableRegex = /(\|.+\|[\r\n]+){2,}/g; while ((match = tableRegex.exec(markdown)) !== null) { // Skip if inside code block const inCodeBlock = sections.some( (s) => s.type === "code" && match!.index >= s.startIndex && match!.index < s.endIndex, ); if (!inCodeBlock) { sections.push({ type: "table", content: match[0], startIndex: match.index, endIndex: match.index + match[0].length, }); } } // 3. Bullet lists: consecutive lines starting with -, *, or + const bulletListRegex = /(^[\s]*[-*+]\s.+$[\r\n]*){2,}/gm; while ((match = bulletListRegex.exec(markdown)) !== null) { const inCodeBlock = sections.some( (s) => s.type === "code" && match!.index >= s.startIndex && match!.index < s.endIndex, ); if (!inCodeBlock) { sections.push({ type: "list", content: match[0], startIndex: match.index, endIndex: match.index + match[0].length, }); } } // 4. Numbered lists: consecutive lines starting with digits followed by period const numberedListRegex = /(^[\s]*\d+\.\s.+$[\r\n]*){2,}/gm; while ((match = numberedListRegex.exec(markdown)) !== null) { const inCodeBlock = sections.some( (s) => s.type === "code" && match!.index >= s.startIndex && match!.index < s.endIndex, ); if (!inCodeBlock) { sections.push({ type: "list", content: match[0], startIndex: match.index, endIndex: match.index + match[0].length, }); } } // 5. Paragraphs: heading (h1-h3) followed by text const paragraphRegex = /(^#{1,3}\s+(.+)$[\r\n]+)((?:^(?!#|\||[-*+]|\d+\.).+$[\r\n]*)+)/gm; while ((match = paragraphRegex.exec(markdown)) !== null) { const inCodeBlock = sections.some( (s) => s.type === "code" && match!.index >= s.startIndex && match!.index < s.endIndex, ); if (!inCodeBlock) { const headingMatch = match[2]; // Captured heading text sections.push({ type: "paragraph", content: match[0], heading: headingMatch, startIndex: match.index, endIndex: match.index + match[0].length, }); } } // Sort by position in document sections.sort((a, b) => a.startIndex - b.startIndex); return sections; } /** * Extract clean content from a copyable section * Removes markdown formatting for better clipboard experience */ static extractCleanContent(section: { type: string; content: string; heading?: string; }): string { if (!section || !section.content) return ""; switch (section.type) { case "code": // Remove ``` delimiters and language identifier return section.content.replace(/^```[\w]*\n?|```$/g, "").trim(); case "table": // Keep table format as-is (it's already clean) return section.content.trim(); case "list": // Keep list markers for readability return section.content.trim(); case "paragraph": // Remove heading markers but keep structure return section.content.replace(/^#{1,3}\s+/gm, "").trim(); default: return section.content.trim(); } } /** * Parse markdown into sections based on H1-H3 headings. * Each section includes the heading and all content below it until the next heading. * * @param markdown - The markdown text to parse * @returns Array of sections with heading, content, and level */ static parseIntoSections(markdown: string): Array<{ heading: string; content: string; level: 1 | 2 | 3; }> { if (!markdown) return []; const lines = markdown.split("\n"); const sections: Array<{ heading: string; content: string; level: 1 | 2 | 3; }> = []; let currentSection: { heading: string; content: string; level: 1 | 2 | 3; } | null = null; lines.forEach((line) => { // Check for H1-H3 headings const h1Match = line.match(/^#\s+(.+)$/); const h2Match = line.match(/^##\s+(.+)$/); const h3Match = line.match(/^###\s+(.+)$/); if (h1Match || h2Match || h3Match) { // Save previous section if (currentSection) { sections.push(currentSection); } // Start new section const heading = (h1Match || h2Match || h3Match)![1] || ""; const level = (h1Match ? 1 : h2Match ? 2 : 3) as 1 | 2 | 3; currentSection = { heading, content: line + "\n", // Include the heading in content level, }; } else if (currentSection) { // Add line to current section currentSection.content += line + "\n"; } }); // Add last section if (currentSection) { sections.push(currentSection); } return sections; } /** * Extract table content as plain text with pipe separators. * Used for copying table data to clipboard. * * @param tableNode - The markdown AST node representing a table * @returns Plain text representation of the table */ static extractTableContent(tableNode: any): string { if (!tableNode || !tableNode.children) return ""; // Helper function to recursively extract text from a node const extractText = (node: any): string => { if (!node) return ""; // If node has content property, return it if (node.content) return node.content; // If node has children, recursively extract from all children if (node.children && Array.isArray(node.children)) { return node.children.map((child: any) => extractText(child)).join(""); } return ""; }; let text = ""; tableNode.children.forEach((row: any) => { if (row.children) { const cells = row.children.map((cell: any) => { return extractText(cell).trim(); }); text += cells.join(" | ") + "\n"; } }); return text.trim(); } }