|
| 1 | +import { marked } from 'marked'; |
| 2 | +import { getComponentType } from './get-component-type.js'; |
| 3 | +import { jsx2js } from './jsx2js.js'; |
| 4 | + |
| 5 | +// Extract import statements from the Markdown |
| 6 | +const extractImports = (markdown) => { |
| 7 | + const importRegex = /^import\s+.+from\s+.+;$/gm; |
| 8 | + const imports = []; |
| 9 | + const cleanedMarkdown = markdown.replace(importRegex, (match) => { |
| 10 | + imports.push(match.trim()); |
| 11 | + return ''; // Remove the import statement from the Markdown |
| 12 | + }); |
| 13 | + return { imports, cleanedMarkdown }; |
| 14 | +}; |
| 15 | + |
| 16 | +// Parse Markdown using marked |
| 17 | +const parseMarkdown = (markdown) => marked.lexer(markdown); |
| 18 | + |
| 19 | +// Transform tokens into a function |
| 20 | +const transformToFunction = (tokens) => { |
| 21 | + const transformToken = (token) => { |
| 22 | + if (token.type === 'text') return JSON.stringify(token.text); |
| 23 | + |
| 24 | + if (token.type === 'paragraph') { |
| 25 | + const childNodes = token.tokens.map(transformToken).join(', '); |
| 26 | + return `tag('p', {}, ${childNodes})`; |
| 27 | + } |
| 28 | + |
| 29 | + if (token.type === 'heading') { |
| 30 | + const childNodes = token.tokens.map(transformToken).join(', '); |
| 31 | + return `tag('h${token.depth}', {}, [${childNodes}])`; |
| 32 | + } |
| 33 | + |
| 34 | + if (token.type === 'html') { |
| 35 | + const component = token.raw.trim(); |
| 36 | + const type = getComponentType(component); |
| 37 | + switch (type) { |
| 38 | + case 'jsx': |
| 39 | + return `${jsx2js(component)}`; |
| 40 | + case 'html': |
| 41 | + return `HTMLWrapper("${component}")`; |
| 42 | + default: |
| 43 | + return null; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return 'null'; |
| 48 | + }; |
| 49 | + |
| 50 | + const body = tokens.map(transformToken).join(',\n'); |
| 51 | + return body.replaceAll(',\n', ';\n'); |
| 52 | +}; |
| 53 | + |
| 54 | +// Sample Markdown |
| 55 | +const markdown = ` |
| 56 | +import Button from './Button.js'; |
| 57 | +
|
| 58 | +# Hello World |
| 59 | +
|
| 60 | +This is a paragraph with <Button data="hello"/> |
| 61 | +
|
| 62 | +<p> Hello </p> |
| 63 | +`; |
| 64 | + |
| 65 | +// Extract imports and clean Markdown |
| 66 | +const { imports, cleanedMarkdown } = extractImports(markdown); |
| 67 | + |
| 68 | +// Parse and transform |
| 69 | +const tokens = parseMarkdown(cleanedMarkdown); |
| 70 | +const jsFunction = transformToFunction(tokens); |
| 71 | + |
| 72 | +// Combine imports and the transformed function |
| 73 | +const finalOutput = [...imports, jsFunction].join('\n\n'); |
| 74 | + |
| 75 | +console.log(finalOutput); |
0 commit comments