update code

This commit is contained in:
lychang
2025-11-19 12:10:42 +08:00
parent 37c6ae9457
commit 8ff1b80be6
6 changed files with 1162 additions and 0 deletions

274
static/css/markdown.css Normal file
View File

@@ -0,0 +1,274 @@
:root {
--primary-color: #2c3e50;
--secondary-color: #3498db;
--accent-color: #e74c3c;
--light-bg: #f8f9fa;
--dark-bg: #2c3e50;
--text-color: #333;
--border-color: #e0e0e0;
--shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
* {
margin: 5px;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1400px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
.header {
text-align: center;
margin-bottom: 30px;
color: white;
}
.header h1 {
font-size: 2.5rem;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.header p {
font-size: 1.1rem;
opacity: 0.9;
}
.main-content {
background: white;
border-radius: 15px;
padding: 30px;
box-shadow: var(--shadow);
margin-bottom: 30px;
}
.container {
display: flex;
gap: 30px;
margin-bottom: 40px;
}
.editor, .preview {
flex: 1;
border: 2px solid var(--border-color);
padding: 25px;
border-radius: 10px;
background: white;
transition: all 0.3s ease;
}
.editor:hover, .preview:hover {
border-color: var(--secondary-color);
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.2);
}
.editor h3, .preview h3 {
color: var(--primary-color);
margin-bottom: 15px;
font-size: 1.3rem;
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 10px;
}
textarea {
width: 100%;
height: 400px;
font-family: 'Fira Code', 'Courier New', monospace;
font-size: 14px;
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 15px;
resize: vertical;
transition: all 0.3s ease;
background: #fafafa;
}
textarea:focus {
outline: none;
border-color: var(--secondary-color);
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
background: white;
}
.toolbar {
margin-top: 20px;
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 12px 24px;
background: linear-gradient(135deg, var(--secondary-color), #2980b9);
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}
button:active {
transform: translateY(0);
}
#htmlPreview {
min-height: 400px;
padding: 15px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: #fafafa;
overflow-y: auto;
}
#htmlPreview::-webkit-scrollbar {
display: none;
}
.syntax-guide {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.guide-card {
background: var(--light-bg);
padding: 20px;
border-radius: 10px;
border-left: 4px solid var(--secondary-color);
}
.guide-card h3 {
color: var(--primary-color);
margin-bottom: 15px;
font-size: 1.2rem;
}
.syntax {
background: #2c3e50;
color: white;
padding: 8px 12px;
border-radius: 5px;
font-family: 'Fira Code', monospace;
font-size: 13px;
margin: 5px 0;
display: inline-block;
}
@keyframes slideIn {
from {
transform: translateY(-10px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
/* Blockquote 样式 - 注释样式,字体变小,颜色变灰 */
blockquote {
background: linear-gradient(135deg, #f8f9fa, #e9ecef);
border-left: 4px solid #6c757d;
margin: 20px 0;
padding: 15px 20px;
font-size: 0.9em;
color: #6c757d;
font-style: italic;
border-radius: 0 8px 8px 0;
position: relative;
}
blockquote::before {
content: "❝";
font-size: 2em;
color: #adb5bd;
position: absolute;
left: 10px;
top: 5px;
opacity: 0.5;
}
blockquote p {
margin: 0;
line-height: 1.5;
}
/* CodeBlock 样式 - 更鲜艳的样式 */
pre {
background: linear-gradient(135deg, #2d3748, #4a5568);
border: 1px solid #4a5568;
border-radius: 8px;
padding: 20px;
margin: 20px 0;
overflow-x: auto;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
position: relative;
white-space: pre;
font-family: 'Fira Code', monospace;
font-size: 13px;
line-height: 1.4;
color: #e2e8f0;
}
pre::before {
content: "</>";
position: absolute;
top: 10px;
right: 15px;
color: #81e6d9;
font-size: 0.8em;
font-weight: bold;
opacity: 0.7;
}
/* 行内代码样式 */
:not(pre) > code {
background: linear-gradient(135deg, #fed7e2, #fbb6ce);
color: #702459;
padding: 2px 6px;
border-radius: 4px;
line-height: 1.4;
border: 1px solid #fbb6ce;
}
.footer {
text-align: center;
color: white;
margin-top: 30px;
opacity: 0.8;
}
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.syntax-guide {
grid-template-columns: 1fr;
}
.header h1 {
font-size: 2rem;
}
}

View File

@@ -0,0 +1,301 @@
/**
* 基础Markdown解析器
* 支持标题、粗体、斜体、列表、链接、图片、代码、引用等基础语法
*/
class MarkdownParser {
constructor() {
this.patterns = {
heading: /^(#{1,6})\s+(.+)$/gm,
bold: /\*\*(.*?)\*\*/g,
italic: /\*(.*?)\*/g,
inlineCode: /`(.*?)`/g,
image: /!\[(.*?)]\((.*?)\)/g,
base64Image: /!\[(.*?)]\((data:image\/[^;]+;base64,[^\)]+)\)/gi,
imageLink: /\[(.*?)]\((.*?\.(?:jpg|jpeg|png|gif|bmp|webp|svg))\s*(?:"(.*?)")?\)/gi,
link: /\[(.*?)]\((?!.*\.(?:jpg|jpeg|png|gif|bmp|webp|svg))(.*?)\)/g,
blockquote: /^>\s+(.+)$/gm,
unorderedList: /^\s*[-*+]\s+(.+)$/gm,
orderedList: /^\d+\.\s+(.+)$/gm,
codeBlock: /```.*?\n([\s\S]*?)```/g,
horizontalRule: /^---$/gm,
comment: /<!--([\s\S]*?)-->/g
};
}
/**
* 解析Markdown文本为HTML
* @param {string} markdown - Markdown文本
* @returns {string} - HTML文本
*/
parse(markdown) {
let html = markdown;
// 处理代码块(先处理,避免其他语法干扰)
html = html.replace(this.patterns.codeBlock, (match, code) => {
// 保留代码内部的换行符,只去除首尾空白
let codeLines = code.split('\n');
let result = '<pre>';
for (let i in codeLines) {
if (codeLines[i].trim() === '') {
continue;
} else {
result += `<code>${codeLines[i]}</code><br>`;
}
}
result += '</pre>';
return result;
});
// 处理块引用
html = html.replace(this.patterns.blockquote, (match, text) => {
return `<blockquote>${this.parseInline(text)}</blockquote>`;
});
// 处理水平分割线
html = html.replace(this.patterns.horizontalRule, '<hr>');
// 处理注释(保留HTML注释)
html = html.replace(this.patterns.comment, '<!--$1-->');
// 处理列表(先处理有序列表,再处理无序列表,避免冲突)
html = this.processLists(html);
// 处理段落(将连续文本包装为段落)
html = this.wrapParagraphs(html);
return html;
}
/**
* 解析行内元素
* @param {string} text - 文本内容
* @returns {string} - 解析后的HTML
*/
parseInline(text) {
let html = text;
// 处理粗体
html = html.replace(this.patterns.bold, '<strong>$1</strong>');
// 处理斜体
html = html.replace(this.patterns.italic, '<em>$1</em>');
// 处理行内代码
html = html.replace(this.patterns.inlineCode, '<code>$1</code>');
// 处理普通图片格式 ![alt](url)
html = html.replace(this.patterns.image, '<img width="100%" src="$2" alt="$1">');
// 处理base64图片格式 ![alt](data:image/...)
html = html.replace(this.patterns.base64Image, '<img width="100%" src="$2" alt="$1">');
// 处理图片链接格式 [alt](image.jpg "title")
html = html.replace(this.patterns.imageLink, (match, alt, src, title) => {
const titleAttr = title ? ` title="${title}"` : '';
return `<img width="100%" src="${src}" alt="${alt}"${titleAttr}>`;
});
// 处理链接
html = html.replace(this.patterns.link, '<a href="$2">$1</a>');
return html;
}
/**
* 处理所有列表,先识别列表类型再处理列表项
* @param {string} html - HTML文本
* @returns {string} - 处理后的HTML
*/
processLists(html) {
// 先识别并标记列表类型
const lines = html.split('\n');
let result = '';
let currentListType = '';
let listItems = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.match(/^\d+\.\s/)) {
// 有序列表项
if (currentListType !== 'ol') {
// 结束前一个列表
if (listItems.length > 0) {
result += this.wrapListItems(listItems, currentListType);
listItems = [];
}
currentListType = 'ol';
}
const content = line.replace(/^\d+\.\s+/, '');
listItems.push(`<li>${this.parseInline(content)}</li>`);
} else if (line.match(/^[-*+]\s/)) {
// 无序列表项
if (currentListType !== 'ul') {
// 结束前一个列表
if (listItems.length > 0) {
result += this.wrapListItems(listItems, currentListType);
listItems = [];
}
currentListType = 'ul';
}
const content = line.replace(/^[-*+]\s+/, '');
listItems.push(`<li>${this.parseInline(content)}</li>`);
} else {
// 非列表项
if (listItems.length > 0) {
result += this.wrapListItems(listItems, currentListType);
listItems = [];
currentListType = '';
}
result += lines[i] + '\n';
}
}
// 处理最后一个列表
if (listItems.length > 0) {
result += this.wrapListItems(listItems, currentListType);
}
return result;
}
/**
* 包装列表项
* @param {Array} listItems - 列表项数组
* @param {string} listType - 列表类型(ul或ol)
* @returns {string} - 包装后的HTML列表
*/
wrapListItems(listItems, listType) {
if (listItems.length === 0) return '';
const listTag = listType === 'ol' ? 'ol' : 'ul';
return `<${listTag}>\n${listItems.join('\n')}\n</${listTag}>\n`;
}
/**
* 包装段落,保留Markdown原有换行
* @param {string} html - HTML文本
* @returns {string} - 包装后的HTML
*/
wrapParagraphs(html) {
const lines = html.split('\n');
let result = '';
let currentParagraph = '';
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const trimmedLine = line.trim();
if (!trimmedLine) {
// 空行,结束当前段落
if (currentParagraph) {
// 检查当前段落是否已经是块级元素
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
result += `<p>${this.parseInline(currentParagraph)}</p>`;
} else {
result += currentParagraph;
}
currentParagraph = '';
}
result += '\n';
} else if (trimmedLine.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
// 已经是块级元素,直接添加
if (currentParagraph) {
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
result += `<p>${this.parseInline(currentParagraph)}</p>`;
} else {
result += currentParagraph;
}
currentParagraph = '';
}
result += line + '\n';
} else {
// 保留原有换行,不合并为一行
if (currentParagraph) {
currentParagraph += '\n' + line;
} else {
currentParagraph = line;
}
}
}
// 处理最后一个段落
if (currentParagraph) {
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
result += `<p>${this.parseInline(currentParagraph)}</p>`;
} else {
result += currentParagraph;
}
}
return result;
}
/**
* HTML转义
* @param {string} text - 原始文本
* @returns {string} - 转义后的文本
*/
escapeHTML(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* 专门解析表格(与MergeTableParser配合使用)
* @param {string} markdown - Markdown表格文本
* @returns {string} - HTML表格
*/
parseTable(markdown) {
// 使用MergeTableParser处理表格
if (typeof MergeTableParser !== 'undefined') {
const tableParser = new MergeTableParser();
return tableParser.parseMarkdownTable(markdown);
}
return markdown;
}
/**
* 完整解析Markdown,包含表格处理
* @param {string} markdown - 完整Markdown文本
* @returns {string} - 完整HTML
*/
parseFull(markdown) {
let html = markdown;
// 先处理标题,避免表格干扰
html = html.replace(this.patterns.heading, (match, hashes, text) => {
const level = hashes.length;
return `<h${level}>${this.parseInline(text)}</h${level}>`;
});
// 再提取并处理表格
const tableRegex = /(\|.*?\|\s*\n)+/g;
html = html.replace(tableRegex, (match) => {
// 检查是否是有效的表格格式
const lines = match.trim().split('\n');
if (lines.length >= 2 && lines.every(line => line.trim().startsWith('|') && line.trim().endsWith('|'))) {
return this.parseTable(match);
}
return match;
});
// 然后处理其他Markdown语法
return this.parse(html);
}
}
// 导出为全局变量
if (typeof window !== 'undefined') {
window.MarkdownParser = MarkdownParser;
}
// 使用示例
if (typeof module !== 'undefined' && module.exports) {
module.exports = MarkdownParser;
}

View File

@@ -0,0 +1,263 @@
/**
* 支持合并单元格的Markdown表格解析器
* 语法说明:
* ^n# - 向上合并n个单元格
* >n# - 向左合并n个单元格
* ^n>m# - 同时向上合并n个单元格,向左合并m个单元格
*/
class MergeTableParser {
constructor() {
this.patterns = {
mergeUp: /\^(\d+)#/, // ^2#
mergeLeft: />(\d+)#/, // >3#
mergeBoth: /\^(\d+)>(\d+)#/, // ^2>3#
};
}
/**
* 解析Markdown表格并转换为HTML表格
* @param {string} markdown - Markdown表格文本
* @returns {string} - HTML表格
*/
parseMarkdownTable(markdown) {
const lines = markdown.trim().split('\n');
const tableData = this.parseTableLines(lines);
return this.generateHTMLTable(tableData);
}
/**
* 解析表格行数据
* @param {string[]} lines - 表格行数组
* @returns {Object} - 表格数据对象
*/
parseTableLines(lines) {
const rows = [];
let headers = [];
let separatorIndex = -1;
// 解析表头和分隔符
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith('|') && line.endsWith('|')) {
const cells = line.slice(1, -1).split('|').map(cell => cell.trim());
if (line.includes('---') || line.includes('===')) {
separatorIndex = i;
continue;
}
if (separatorIndex === -1) {
headers = cells;
} else {
rows.push(cells);
}
}
}
return { headers, rows, separatorIndex };
}
/**
* 生成HTML表格
* @param {Object} tableData - 表格数据
* @returns {string} - HTML表格字符串
*/
generateHTMLTable(tableData) {
const { headers, rows } = tableData;
const skipMap = new Map(); // 用于标记需要跳过的单元格
let html = '<table border="1" style="border-collapse: collapse; width: 100%;">\n';
// 生成表头(支持合并单元格)
if (headers.length > 0) {
html += ' <thead>\n <tr>\n';
// 处理表头合并单元格
headers.forEach((header, colIndex) => {
// 检查当前单元格是否应该被跳过
const key = `-1,${colIndex}`; // 表头行索引为-1
if (skipMap.has(key)) {
return;
}
const mergeInfo = this.parseMergeSyntax(header);
let cellHtml = '';
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
cellHtml = ` <th rowspan="${mergeInfo.rowspan}" colspan="${mergeInfo.colspan}">${this.escapeHTML(mergeInfo.content)}</th>\n`;
// 标记被合并的表头单元格
this.markMergedCells(-1, colIndex, mergeInfo, skipMap);
} else {
cellHtml = ` <th>${this.escapeHTML(header)}</th>\n`;
}
html += cellHtml;
});
html += ' </tr>\n </thead>\n';
}
// 生成表格主体
html += ' <tbody>\n';
// 第一遍:标记所有需要合并的单元格
rows.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
const mergeInfo = this.parseMergeSyntax(cell);
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
this.markMergedCells(rowIndex, colIndex, mergeInfo, skipMap);
}
});
});
// 第二遍:生成HTML,跳过被合并的单元格
rows.forEach((row, rowIndex) => {
html += ' <tr>\n';
let colOffset = 0; // 列偏移量,用于处理被跳过的单元格
row.forEach((cell, colIndex) => {
// 检查当前单元格是否应该被跳过
const key = `${rowIndex},${colIndex}`;
if (skipMap.has(key)) {
colOffset++;
return;
}
const mergeInfo = this.parseMergeSyntax(cell);
let cellHtml = '';
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
cellHtml = ` <td rowspan="${mergeInfo.rowspan}" colspan="${mergeInfo.colspan}">${this.escapeHTML(mergeInfo.content)}</td>\n`;
} else {
cellHtml = ` <td>${this.escapeHTML(cell)}</td>\n`;
}
html += cellHtml;
});
html += ' </tr>\n';
});
html += ' </tbody>\n</table>';
return html;
}
/**
* 解析合并语法
* @param {string} cell - 单元格内容
* @returns {Object} - 合并信息
*/
parseMergeSyntax(cell) {
const result = {
content: cell,
rowspan: 1,
colspan: 1,
shouldSkip: false
};
// 检查合并语法
const bothMatch = cell.match(this.patterns.mergeBoth);
const upMatch = cell.match(this.patterns.mergeUp);
const leftMatch = cell.match(this.patterns.mergeLeft);
if (bothMatch) {
result.rowspan = parseInt(bothMatch[1]) + 1;
result.colspan = parseInt(bothMatch[2]) + 1;
result.content = cell.replace(this.patterns.mergeBoth, '').trim();
} else if (upMatch) {
result.rowspan = parseInt(upMatch[1]) + 1;
result.content = cell.replace(this.patterns.mergeUp, '').trim();
} else if (leftMatch) {
result.colspan = parseInt(leftMatch[1]) + 1;
result.content = cell.replace(this.patterns.mergeLeft, '').trim();
}
return result;
}
/**
* 标记被合并的单元格
* @param {number} rowIndex - 行索引
* @param {number} colIndex - 列索引
* @param {Object} mergeInfo - 合并信息
* @param {Map} skipMap - 跳过映射
*/
markMergedCells(rowIndex, colIndex, mergeInfo, skipMap) {
for (let r = 0; r < mergeInfo.rowspan; r++) {
for (let c = 0; c < mergeInfo.colspan; c++) {
if (r === 0 && c === 0) continue; // 跳过主单元格
// 处理表头合并(行索引为-1)
const targetRow = rowIndex === -1 ? -1 : rowIndex + r;
const key = `${targetRow},${colIndex + c}`;
skipMap.set(key, true);
}
}
}
/**
* HTML转义
* @param {string} text - 原始文本
* @returns {string} - 转义后的文本
*/
escapeHTML(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* 将HTML表格转换回Markdown格式
* @param {string} html - HTML表格
* @returns {string} - Markdown表格
*/
htmlToMarkdown(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const table = doc.querySelector('table');
if (!table) return '';
let markdown = '';
const rows = table.querySelectorAll('tr');
rows.forEach((row, rowIndex) => {
const cells = row.querySelectorAll('th, td');
let rowMarkdown = '|';
cells.forEach(cell => {
const rowspan = parseInt(cell.getAttribute('rowspan') || '1');
const colspan = parseInt(cell.getAttribute('colspan') || '1');
let content = cell.textContent.trim();
// 添加合并语法
if (rowspan > 1) {
content += ` ^${rowspan - 1}`;
}
if (colspan > 1) {
content += ` >${colspan - 1}`;
}
rowMarkdown += ` ${content} |`;
});
markdown += rowMarkdown + '\n';
// 添加分隔符行(仅在第一行后)
if (rowIndex === 0) {
markdown += '|' + cells.map(() => '---').join('|') + '|\n';
}
});
return markdown;
}
}
// 导出为全局变量
if (typeof window !== 'undefined') {
window.MergeTableParser = MergeTableParser;
}
// 使用示例
if (typeof module !== 'undefined' && module.exports) {
module.exports = MergeTableParser;
}