mirror of
https://github.com/Jerryplusy/crystelf-plugin.git
synced 2025-12-05 15:41:56 +00:00
feat:优化截图
This commit is contained in:
parent
7b5508b331
commit
f62e5dc405
@ -2,8 +2,9 @@ import ConfigControl from "../config/configControl.js";
|
|||||||
import puppeteer from 'puppeteer';
|
import puppeteer from 'puppeteer';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
import markdownit from 'markdown-it';
|
||||||
|
import hljs from 'highlight.js';
|
||||||
|
|
||||||
//渲染器
|
|
||||||
class Renderer {
|
class Renderer {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.browser = null;
|
this.browser = null;
|
||||||
@ -20,38 +21,32 @@ class Renderer {
|
|||||||
});
|
});
|
||||||
this.isInitialized = true;
|
this.isInitialized = true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`[crystelf-renderer] 初始化失败: ${error.message}`);
|
console.error(`[crystelf-renderer] 初始化失败: ${error.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 渲染代码为图片
|
|
||||||
* @param code 代码
|
|
||||||
* @param language 语言
|
|
||||||
* @returns {Promise<null|string>}
|
|
||||||
*/
|
|
||||||
async renderCode(code, language = 'text') {
|
async renderCode(code, language = 'text') {
|
||||||
if (!this.isInitialized) {
|
if (!this.isInitialized) await this.init();
|
||||||
await this.init();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const page = await this.browser.newPage();
|
const page = await this.browser.newPage();
|
||||||
const codeConfig = this.config?.codeRenderer || {};
|
const html = this.getCodeTemplate(code, language, this.config?.codeRenderer || {});
|
||||||
const html = this.generateCodeHTML(code, language, codeConfig);
|
await page.setContent(html, { waitUntil: 'networkidle0' });
|
||||||
await page.setContent(html);
|
await page.waitForSelector('#render-complete', { timeout: 5000 });
|
||||||
await page.setViewport({ width: 800, height: 600 });
|
const rect = await page.evaluate(() => {
|
||||||
const tempDir = path.join(process.cwd(), 'temp', 'html');
|
const body = document.body;
|
||||||
if (!fs.existsSync(tempDir)) {
|
return { width: body.scrollWidth, height: body.scrollHeight };
|
||||||
fs.mkdirSync(tempDir, { recursive: true });
|
|
||||||
}
|
|
||||||
const filename = `code_${Date.now()}.png`;
|
|
||||||
const filepath = path.join(tempDir, filename);
|
|
||||||
await page.screenshot({
|
|
||||||
path: filepath,
|
|
||||||
fullPage: true,
|
|
||||||
type: 'png'
|
|
||||||
});
|
});
|
||||||
|
await page.setViewport({
|
||||||
|
width: Math.ceil(rect.width),
|
||||||
|
height: Math.ceil(rect.height)
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = path.join(process.cwd(), 'temp', 'html');
|
||||||
|
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
const filepath = path.join(tempDir, `code_${Date.now()}.png`);
|
||||||
|
|
||||||
|
await page.screenshot({ path: filepath, fullPage: false });
|
||||||
await page.close();
|
await page.close();
|
||||||
logger.info(`[crystelf-ai] 代码渲染完成: ${filepath}`);
|
logger.info(`[crystelf-ai] 代码渲染完成: ${filepath}`);
|
||||||
return filepath;
|
return filepath;
|
||||||
@ -61,32 +56,30 @@ class Renderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 渲染md为图片
|
|
||||||
* @param markdown
|
|
||||||
* @returns {Promise<null|string>}
|
|
||||||
*/
|
|
||||||
async renderMarkdown(markdown) {
|
async renderMarkdown(markdown) {
|
||||||
if (!this.isInitialized) {
|
if (!this.isInitialized) await this.init();
|
||||||
await this.init();
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const page = await this.browser.newPage();
|
const page = await this.browser.newPage();
|
||||||
const markdownConfig = this.config?.markdownRenderer || {};
|
const html = this.getMarkdownTemplate(markdown, this.config?.markdownRenderer || {});
|
||||||
const html = this.generateMarkdownHTML(markdown, markdownConfig);
|
|
||||||
await page.setContent(html);
|
await page.setContent(html, { waitUntil: 'networkidle0' });
|
||||||
await page.setViewport({ width: 800, height: 600 });
|
await page.waitForSelector('#render-complete', { timeout: 5000 });
|
||||||
const tempDir = path.join(process.cwd(), 'temp', 'html');
|
|
||||||
if (!fs.existsSync(tempDir)) {
|
const rect = await page.evaluate(() => {
|
||||||
fs.mkdirSync(tempDir, { recursive: true });
|
const body = document.body;
|
||||||
}
|
return { width: body.scrollWidth, height: body.scrollHeight };
|
||||||
const filename = `markdown_${Date.now()}.png`;
|
|
||||||
const filepath = path.join(tempDir, filename);
|
|
||||||
await page.screenshot({
|
|
||||||
path: filepath,
|
|
||||||
fullPage: true,
|
|
||||||
type: 'png'
|
|
||||||
});
|
});
|
||||||
|
await page.setViewport({
|
||||||
|
width: Math.ceil(rect.width),
|
||||||
|
height: Math.ceil(rect.height)
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = path.join(process.cwd(), 'temp', 'html');
|
||||||
|
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
const filepath = path.join(tempDir, `markdown_${Date.now()}.png`);
|
||||||
|
|
||||||
|
await page.screenshot({ path: filepath, fullPage: false });
|
||||||
await page.close();
|
await page.close();
|
||||||
logger.info(`[crystelf-ai] Markdown渲染完成: ${filepath}`);
|
logger.info(`[crystelf-ai] Markdown渲染完成: ${filepath}`);
|
||||||
return filepath;
|
return filepath;
|
||||||
@ -96,143 +89,146 @@ class Renderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getCodeTemplate(code, language = "text", config = {}) {
|
||||||
|
const themeColor = "#0f172a";
|
||||||
|
const fontSize = config.fontSize || 16;
|
||||||
|
const escapedCode = this.escapeHtml(code);
|
||||||
|
|
||||||
/**
|
const colorMap = {
|
||||||
* 生成代码html
|
javascript: "from-yellow-400 to-yellow-600",
|
||||||
* @param code 代码内容
|
typescript: "from-blue-400 to-blue-600",
|
||||||
* @param language 语言
|
python: "from-cyan-400 to-cyan-600",
|
||||||
* @param config 配置
|
html: "from-orange-400 to-red-500",
|
||||||
* @returns {string}
|
css: "from-indigo-400 to-indigo-600",
|
||||||
*/
|
json: "from-emerald-400 to-emerald-600",
|
||||||
generateCodeHTML(code, language, config) {
|
yaml: "from-amber-400 to-amber-600",
|
||||||
const theme = config.theme || 'github';
|
c: "from-blue-300 to-blue-500",
|
||||||
const fontSize = config.fontSize || 14;
|
cpp: "from-blue-400 to-indigo-600",
|
||||||
const lineNumbers = config.lineNumbers !== false;
|
java: "from-red-400 to-orange-500",
|
||||||
const backgroundColor = config.backgroundColor || '#f6f8fa';
|
kotlin: "from-pink-400 to-purple-500",
|
||||||
|
csharp: "from-violet-400 to-purple-600",
|
||||||
|
'c#': "from-violet-400 to-purple-600",
|
||||||
|
dotnet: "from-purple-400 to-indigo-600",
|
||||||
|
bash: "from-gray-400 to-gray-600",
|
||||||
|
shell: "from-gray-400 to-gray-600",
|
||||||
|
text: "from-slate-400 to-slate-600",
|
||||||
|
};
|
||||||
|
const barColor = colorMap[language.toLowerCase()] || "from-cyan-400 to-cyan-600";
|
||||||
|
const highlightedCode = hljs.highlight(code, { language }).value;
|
||||||
|
const lines = highlightedCode.split('\n').map((line, i) => `
|
||||||
|
<div class="line">
|
||||||
|
<span class="line-number">${i + 1}</span>
|
||||||
|
<span class="line-content">${line}</span>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
||||||
<title>Code Render</title>
|
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-${theme}.min.css">
|
|
||||||
<style>
|
<style>
|
||||||
body {
|
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&display=swap');
|
||||||
margin: 0;
|
body { background-color: ${themeColor}; margin: 0; padding: 20px; font-family: 'Fira Code', monospace; }
|
||||||
padding: 20px;
|
.code-container {
|
||||||
background-color: ${backgroundColor};
|
background-color: rgba(30, 41, 59, 0.8);
|
||||||
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
|
border-radius: 10px;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
-webkit-backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
box-shadow: 0 0 20px rgba(0,0,0,0.5);
|
||||||
|
}
|
||||||
|
.code-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
.language-tag {
|
||||||
|
background-image: linear-gradient(to right, ${barColor.replace('-', ' ')});
|
||||||
|
color: white;
|
||||||
|
padding: 3px 8px;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-family: sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.code-body {
|
||||||
|
padding: 15px;
|
||||||
font-size: ${fontSize}px;
|
font-size: ${fontSize}px;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
}
|
|
||||||
pre {
|
|
||||||
margin: 0;
|
|
||||||
padding: 16px;
|
|
||||||
border-radius: 8px;
|
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
background-color: white;
|
|
||||||
border: 1px solid #e1e4e8;
|
|
||||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
||||||
}
|
}
|
||||||
code {
|
.line {
|
||||||
font-family: inherit;
|
display: flex;
|
||||||
}
|
}
|
||||||
${lineNumbers ? `
|
.line-number {
|
||||||
.line-numbers {
|
|
||||||
counter-reset: line;
|
|
||||||
}
|
|
||||||
.line-numbers .line-number {
|
|
||||||
counter-increment: line;
|
|
||||||
position: relative;
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
.line-numbers .line-number:before {
|
|
||||||
content: counter(line);
|
|
||||||
position: absolute;
|
|
||||||
left: -2em;
|
|
||||||
width: 2em;
|
|
||||||
text-align: right;
|
text-align: right;
|
||||||
color: #6a737d;
|
margin-right: 15px;
|
||||||
|
color: #9ca3af;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
` : ''}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<pre class="language-${language}${lineNumbers ? ' line-numbers' : ''}"><code>${this.escapeHtml(code)}</code></pre>
|
<div class="code-container">
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
|
<div class="code-header">
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
|
<span class="language-tag">${language}</span>
|
||||||
|
</div>
|
||||||
|
<div class="code-body">
|
||||||
|
<pre><code class="hljs ${language}">${lines}</code></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="render-complete"></div>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>
|
||||||
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
getMarkdownTemplate(markdown, config = {}) {
|
||||||
* 生成Markdown HTML
|
const themeColor = "#0f172a";
|
||||||
* @param {string} markdown Markdown内容
|
const fontSize = config.fontSize || 18;
|
||||||
* @param {Object} config 配置
|
const md = markdownit({
|
||||||
* @returns {string} HTML内容
|
html: true,
|
||||||
*/
|
linkify: true,
|
||||||
generateMarkdownHTML(markdown, config) {
|
typographer: true,
|
||||||
const theme = config.theme || 'light';
|
highlight: function (str, lang) {
|
||||||
const fontSize = config.fontSize || 14;
|
if (lang && hljs.getLanguage(lang)) {
|
||||||
const codeTheme = config.codeTheme || 'github';
|
try {
|
||||||
|
return '<pre class="hljs"><code>' +
|
||||||
|
hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
|
||||||
|
'</code></pre>';
|
||||||
|
} catch (__) {}
|
||||||
|
}
|
||||||
|
return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
||||||
<title>Markdown Render</title>
|
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown-${theme}.min.css">
|
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-${codeTheme}.min.css">
|
|
||||||
<style>
|
<style>
|
||||||
body {
|
body { background-color: ${themeColor}; color: #e2e8f0; font-family: 'Noto Sans SC', sans-serif; font-size: ${fontSize}px; line-height: 1.6; margin: 0; padding: 20px; }
|
||||||
margin: 0;
|
h1, h2, h3, h4, h5, h6 { color: #f1f5f9; border-bottom: 1px solid #334155; padding-bottom: 5px; }
|
||||||
padding: 20px;
|
a { color: #38bdf8; text-decoration: none; }
|
||||||
font-size: ${fontSize}px;
|
a:hover { text-decoration: underline; }
|
||||||
line-height: 1.6;
|
code { background-color: #1e293b; padding: 2px 5px; border-radius: 5px; }
|
||||||
}
|
pre { background-color: #1e293b; padding: 15px; border-radius: 10px; overflow-x: auto; }
|
||||||
.markdown-body {
|
blockquote { border-left: 4px solid #334155; padding-left: 15px; color: #9ca3af; }
|
||||||
max-width: 800px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 20px;
|
|
||||||
background-color: white;
|
|
||||||
border-radius: 8px;
|
|
||||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
||||||
}
|
|
||||||
${theme === 'dark' ? `
|
|
||||||
.markdown-body {
|
|
||||||
background-color: #0d1117;
|
|
||||||
color: #c9d1d9;
|
|
||||||
}
|
|
||||||
` : ''}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="markdown-body">
|
${md.render(markdown)}
|
||||||
<div id="markdown-content"></div>
|
<div id="render-complete"></div>
|
||||||
</div>
|
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>
|
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
|
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
|
|
||||||
<script>
|
|
||||||
const markdown = \`${this.escapeHtml(markdown)}\`;
|
|
||||||
document.getElementById('markdown-content').innerHTML = marked.parse(markdown);
|
|
||||||
Prism.highlightAll();
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>
|
||||||
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
escapeHtml(text) {
|
escapeHtml(text) {
|
||||||
const map = {
|
const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||||
'&': '&',
|
|
||||||
'<': '<',
|
|
||||||
'>': '>',
|
|
||||||
'"': '"',
|
|
||||||
"'": '''
|
|
||||||
};
|
|
||||||
return text.replace(/[&<>"']/g, (m) => map[m]);
|
return text.replace(/[&<>"']/g, (m) => map[m]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -19,6 +19,8 @@
|
|||||||
"axios": "^1.8.4",
|
"axios": "^1.8.4",
|
||||||
"chalk": "^5.4.1",
|
"chalk": "^5.4.1",
|
||||||
"form-data": "^4.0.2",
|
"form-data": "^4.0.2",
|
||||||
|
"highlight.js": "^11.11.1",
|
||||||
|
"markdown-it": "^14.1.0",
|
||||||
"openai": "^4.89.0",
|
"openai": "^4.89.0",
|
||||||
"pinyin-pro": "^3.27.0",
|
"pinyin-pro": "^3.27.0",
|
||||||
"rss-parser": "^3.13.0"
|
"rss-parser": "^3.13.0"
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user