66 lines
2.4 KiB
React
66 lines
2.4 KiB
React
import { Fragment } from "react";
|
|
|
|
function inline(text, keyPrefix) {
|
|
const pattern = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g;
|
|
const nodes = [];
|
|
let last = 0;
|
|
let index = 0;
|
|
for (const match of text.matchAll(pattern)) {
|
|
if (match.index > last) nodes.push(text.slice(last, match.index));
|
|
const token = match[0];
|
|
const key = `${keyPrefix}-${index}`;
|
|
if (token.startsWith("**")) nodes.push(<strong key={key}>{token.slice(2, -2)}</strong>);
|
|
else if (token.startsWith("*")) nodes.push(<em key={key}>{token.slice(1, -1)}</em>);
|
|
else if (token.startsWith("`")) nodes.push(<code key={key}>{token.slice(1, -1)}</code>);
|
|
else {
|
|
const linked = token.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);
|
|
if (linked) {
|
|
nodes.push(<a key={key} href={linked[2]} rel="noreferrer">{linked[1]}</a>);
|
|
}
|
|
}
|
|
last = match.index + token.length;
|
|
index += 1;
|
|
}
|
|
if (last < text.length) nodes.push(text.slice(last));
|
|
return nodes;
|
|
}
|
|
|
|
export function MarkdownView({ text }) {
|
|
const lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
|
|
const blocks = [];
|
|
let list = null;
|
|
function closeList() {
|
|
if (!list) return;
|
|
const items = list.items.map((item, index) => <li key={`${list.key}-${index}`}>{inline(item, `${list.key}-${index}`)}</li>);
|
|
blocks.push(list.ordered ? <ol key={list.key}>{items}</ol> : <ul key={list.key}>{items}</ul>);
|
|
list = null;
|
|
}
|
|
lines.forEach((line, index) => {
|
|
const heading = line.match(/^(#{1,3})\s+(.*)$/);
|
|
const bullet = line.match(/^\s*[-*]\s+(.*)$/);
|
|
const numbered = line.match(/^\s*\d+\.\s+(.*)$/);
|
|
if (heading) {
|
|
closeList();
|
|
const Tag = heading[1].length === 1 ? "h3" : heading[1].length === 2 ? "h4" : "h5";
|
|
blocks.push(<Tag key={`h-${index}`}>{inline(heading[2], `h-${index}`)}</Tag>);
|
|
return;
|
|
}
|
|
if (bullet || numbered) {
|
|
if (!list || list.ordered !== Boolean(numbered)) {
|
|
closeList();
|
|
list = { key: `l-${index}`, ordered: Boolean(numbered), items: [] };
|
|
}
|
|
list.items.push((bullet || numbered)[1]);
|
|
return;
|
|
}
|
|
closeList();
|
|
if (!line.trim()) {
|
|
blocks.push(<Fragment key={`s-${index}`} />);
|
|
return;
|
|
}
|
|
blocks.push(<p key={`p-${index}`}>{inline(line, `p-${index}`)}</p>);
|
|
});
|
|
closeList();
|
|
return <div className="markdown">{blocks}</div>;
|
|
}
|