(markdown: string)
| 54 | * // Returns: '<p><strong>bold</strong> and <em>italic</em></p>' |
| 55 | */ |
| 56 | export const markdownToHtmlBasic = (markdown: string): string => { |
| 57 | if (!markdown) { |
| 58 | return ''; |
| 59 | } |
| 60 | |
| 61 | const lines = markdown.split(/\r?\n/); |
| 62 | const htmlParts: string[] = []; |
| 63 | let listType: 'ul' | 'ol' | null = null; |
| 64 | let listItems: string[] = []; |
| 65 | let isInCodeBlock = false; |
| 66 | let codeBlockLines: string[] = []; |
| 67 | let hasRenderedBlock = false; |
| 68 | let pendingBlankLines = 0; |
| 69 | |
| 70 | const flushList = () => { |
| 71 | if (!listType || listItems.length === 0) { |
| 72 | listType = null; |
| 73 | listItems = []; |
| 74 | return; |
| 75 | } |
| 76 | |
| 77 | htmlParts.push(`<${listType}>${listItems.join('')}</${listType}>`); |
| 78 | hasRenderedBlock = true; |
| 79 | listType = null; |
| 80 | listItems = []; |
| 81 | }; |
| 82 | |
| 83 | const flushPendingEmptyParagraphs = () => { |
| 84 | if (!hasRenderedBlock || pendingBlankLines === 0) { |
| 85 | return; |
| 86 | } |
| 87 | |
| 88 | for (let i = 1; i < pendingBlankLines; i += 1) { |
| 89 | htmlParts.push('<p></p>'); |
| 90 | } |
| 91 | |
| 92 | pendingBlankLines = 0; |
| 93 | }; |
| 94 | |
| 95 | lines.forEach((line) => { |
| 96 | const trimmed = line.trim(); |
| 97 | |
| 98 | if (trimmed.startsWith('```')) { |
| 99 | if (isInCodeBlock) { |
| 100 | flushPendingEmptyParagraphs(); |
| 101 | const codeContent = escapeHtml(codeBlockLines.join('\n')); |
| 102 | htmlParts.push(`<pre><code>${codeContent}</code></pre>`); |
| 103 | codeBlockLines = []; |
| 104 | isInCodeBlock = false; |
| 105 | hasRenderedBlock = true; |
| 106 | } else { |
| 107 | flushList(); |
| 108 | flushPendingEmptyParagraphs(); |
| 109 | isInCodeBlock = true; |
| 110 | } |
| 111 | return; |
| 112 | } |
| 113 |
no test coverage detected