initial commit
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
hljs.registerLanguage('javascript', javascript)
|
||||
hljs.registerLanguage('json', json)
|
||||
|
||||
const CODE_LANGUAGES = ['sql', 'javascript', 'typescript', 'java', 'python', 'json', 'html', 'css', 'bash', 'shell', 'vue', 'xml', 'yaml', 'markdown']
|
||||
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
sh: 'bash',
|
||||
shell: 'bash',
|
||||
zsh: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
text: 'plaintext',
|
||||
}
|
||||
const CODE_FENCE_PATTERN = /```[\s\S]*?```/
|
||||
const CODE_FENCE_LINE_PATTERN = /^```/gm
|
||||
const SQL_KEYWORDS = /\b(select|insert|update|delete|create|alter|drop|from|where|join|group by|order by|limit)\b/i
|
||||
const CODE_STRUCTURE_PATTERN = /[{};<>]|\b(function|const|let|var|public|private|class|interface|return|import|export|try|catch|async|await)\b/
|
||||
|
||||
function escapeCodeHtml(code: string): string {
|
||||
return code
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function escapeAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
function normalizeLanguage(language = ''): string {
|
||||
const normalized = language.trim().toLowerCase()
|
||||
return LANGUAGE_ALIASES[normalized] || normalized || 'plaintext'
|
||||
}
|
||||
|
||||
function getDisplayLanguage(language: string): string {
|
||||
return language === 'plaintext' ? 'text' : language
|
||||
}
|
||||
|
||||
function detectCodeLanguage(content: string): string {
|
||||
const normalized = content.trim().toLowerCase()
|
||||
|
||||
if (SQL_KEYWORDS.test(normalized)) return 'sql'
|
||||
if (/^\s*[{[]/.test(content) && /[}\]]\s*$/.test(content)) return 'json'
|
||||
if (/<[a-z][\s\S]*?>/i.test(content)) return 'html'
|
||||
if (/\b(interface|type|implements|readonly|enum)\b/.test(normalized)) return 'typescript'
|
||||
if (/\b(system\.out\.println|public static void main|new \w+\()/i.test(content)) return 'java'
|
||||
if (/\b(def |import |from .+ import |print\()/i.test(content)) return 'python'
|
||||
if (/\b(const|let|var|function|=>|console\.log)\b/.test(normalized)) return 'javascript'
|
||||
if (/\b(selectors?|padding|margin|color|background|display|flex)\s*:/i.test(content)) return 'css'
|
||||
if (/^(npm|pnpm|yarn|git|curl|docker|cd|ls|dir)\b/im.test(content)) return 'bash'
|
||||
|
||||
return 'plaintext'
|
||||
}
|
||||
|
||||
function shouldRenderAsCode(content: string): boolean {
|
||||
const trimmed = content.trim()
|
||||
if (!trimmed || CODE_FENCE_PATTERN.test(trimmed)) return false
|
||||
|
||||
const lines = trimmed.split(/\r?\n/).filter((line) => line.trim())
|
||||
if (lines.length >= 2 && (SQL_KEYWORDS.test(trimmed) || CODE_STRUCTURE_PATTERN.test(trimmed))) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (lines.length === 1) {
|
||||
return /^(select|insert|update|delete)\b/i.test(trimmed) || /^[{[]/.test(trimmed)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function normalizeMarkdownContent(content: string): string {
|
||||
if (!shouldRenderAsCode(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
const language = detectCodeLanguage(content)
|
||||
if (CODE_LANGUAGES.includes(language) || language === 'plaintext') {
|
||||
return `\n\n\`\`\`${language}\n${content.trim()}\n\`\`\`\n\n`
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
function closeUnclosedCodeFence(content: string): string {
|
||||
const fenceCount = content.match(CODE_FENCE_LINE_PATTERN)?.length || 0
|
||||
return fenceCount % 2 === 1 ? `${content}\n\`\`\`` : content
|
||||
}
|
||||
|
||||
const markdown: MarkdownIt = new MarkdownIt({
|
||||
html: false,
|
||||
linkify: true,
|
||||
breaks: true,
|
||||
typographer: true,
|
||||
highlight(code: string, language: string): string {
|
||||
const normalizedLanguage = normalizeLanguage(language)
|
||||
const languageLabel = hljs.getLanguage(normalizedLanguage) ? normalizedLanguage : 'plaintext'
|
||||
const displayLanguage = getDisplayLanguage(languageLabel)
|
||||
const highlightedCode = hljs.getLanguage(languageLabel)
|
||||
? hljs.highlight(code, { language: languageLabel }).value
|
||||
: escapeCodeHtml(code)
|
||||
|
||||
return `
|
||||
<div class="md-code-block" data-language="${escapeAttribute(displayLanguage)}">
|
||||
<div class="md-code-block__toolbar">
|
||||
<span class="md-code-block__language">${escapeAttribute(displayLanguage)}</span>
|
||||
<button type="button" class="md-code-block__copy" aria-label="复制代码">复制代码</button>
|
||||
</div>
|
||||
<pre class="hljs"><code>${highlightedCode}</code></pre>
|
||||
</div>
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
const defaultLinkOpenRenderer = markdown.renderer.rules.link_open
|
||||
markdown.renderer.rules.link_open = (tokens, index, options, env, self) => {
|
||||
const token = tokens[index]
|
||||
const hrefIndex = token.attrIndex('href')
|
||||
|
||||
if (hrefIndex >= 0) {
|
||||
token.attrSet('target', '_blank')
|
||||
token.attrSet('rel', 'noopener noreferrer')
|
||||
}
|
||||
|
||||
return defaultLinkOpenRenderer ? defaultLinkOpenRenderer(tokens, index, options, env, self) : self.renderToken(tokens, index, options)
|
||||
}
|
||||
|
||||
markdown.renderer.rules.table_open = () => '<div class="md-table-wrapper"><table>\n'
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n'
|
||||
|
||||
export function renderMarkdown(content = ''): string {
|
||||
const normalizedContent = normalizeMarkdownContent(content)
|
||||
return markdown.render(closeUnclosedCodeFence(normalizedContent))
|
||||
}
|
||||
Reference in New Issue
Block a user