UNPKG

@churchapps/apphelper-markdown

Version:
50 lines (49 loc) 2.35 kB
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime"; import { marked } from "marked"; export function MarkdownPreviewLight({ value: markdownString = "", textAlign }) { const getTargetAndClasses = (extra) => { let result = ""; const classRegex = /\.[^( |\})]+/g; const matches = extra.match(classRegex); if (matches && matches.length > 0) { let classes = matches.join(" "); classes = classes.replaceAll(".", ""); result = " class=\"" + classes + "\""; } const targetRegex = /:target="([^"]+)"/g; let targets = targetRegex.exec(extra); if (targets) result += " " + targets[0].replace(":", ""); return result; }; // \[([^\]]+)\] - text // \(([^)]+)\) - url // \{([^\}]+)\} - target and classes // \[([^\]]+)\]\(([^)]+)\)\{([^\}]+)\} - full const getSpecialLinks = (markdownString) => { if (!markdownString) return ""; const regex = /\[([^\]]+)\]\(([^)]+)\)\{([^\}]+)\}/g; const convertedText = markdownString.replace(regex, (match, text, url, extra) => { if (!match) return text; let result = "<a href=\"" + url + "\""; result += getTargetAndClasses(extra); result += ">" + text + "</a>"; return result; }); return convertedText; }; if (markdownString === null || markdownString === undefined || !markdownString) return _jsx(_Fragment, {}); else { const convertedText = getSpecialLinks(markdownString || ""); let processedMarkdown = convertedText; processedMarkdown = convertedText.replace(/__(.*?)__/g, "<u>$1</u>"); //Replace `__underlined__` with `<u>underlined</u>` processedMarkdown = processedMarkdown.replace(/```([\s\S]+?)```/g, "<pre class='code-block'><code>$1</code></pre>"); //Convert block code ```code``` to <pre><code>code</code></pre> processedMarkdown = processedMarkdown.replace(/`([^`]+)`/g, "<code>$1</code>"); //Convert inline code `code` to <code>code</code> const html = marked.parse(processedMarkdown || ""); const style = (textAlign) ? { textAlign } : {}; return _jsx("div", { style: style, dangerouslySetInnerHTML: { __html: html } }); } }