| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177 |
- import { marked, Renderer } from 'marked';
- import type { Tokens } from 'marked';
- import katex from 'katex';
- import DOMPurify from 'dompurify';
- const mdRenderer = new Renderer();
- const defaultLinkRenderer = mdRenderer.link.bind(mdRenderer);
- mdRenderer.link = (token: Tokens.Link): string => {
- const html = defaultLinkRenderer(token);
- return html.replace(/^<a\s/, '<a target="_blank" rel="noopener" ');
- };
- const renderLatexInHtml = (html: string): string => {
- // 匹配块级公式($$...$$)
- html = html.replace(/\$\$(.*?)\$\$/gs, (_match, formula) => {
- return katex.renderToString(formula.trim(), {
- displayMode: true,
- throwOnError: false,
- strict: false,
- trust: true,
- });
- });
- // 匹配行内公式($...$)
- html = html.replace(/\$(.*?)\$/g, (_match, formula) => {
- return katex.renderToString(formula.trim(), {
- displayMode: false,
- throwOnError: false,
- strict: false,
- });
- });
- return html;
- };
- const processFootnotes = (html: string, maxId?: number): string => {
- if (maxId === undefined) {
- // 无 citations 上下文,剥离所有 [^n] 标记
- return html.replace(/\[\^\d+\]/g, '');
- }
- // 有效编号范围 [1, maxId],范围外的剥离
- return html.replace(/\[\^(\d+)\]/g, (_match, n) => {
- const id = parseInt(n, 10);
- if (id >= 1 && id <= maxId) {
- return `<sup class="footnote-ref" data-n="${id}">[${n}]</sup>`;
- }
- return '';
- });
- };
- export const renderMarkdown = (
- text: string,
- icons?: { copy: string; download: string; preview: string; copySuccess: string },
- maxCitationId?: number
- ): string => {
- if (!text) return '';
- const processed = text.replace(/<br\s*\/?>/gi, ' \n');
- let html = marked.parse(processed, { renderer: mdRenderer }) as string;
- html = processFootnotes(html, maxCitationId);
- html = renderLatexInHtml(html);
- // Sanitize HTML to prevent XSS attacks
- html = DOMPurify.sanitize(html, {
- ADD_TAGS: ['img'],
- ADD_ATTR: ['target', 'data-action', 'data-table', 'data-icon', 'data-icon-success', 'data-n'],
- });
- // 原始 HTML 锚点不经过 marked link renderer,统一补 target/rel
- html = html.replace(/<a\b[^>]*>/gi, (tag) => {
- let attrs = '';
- if (!/\btarget\s*=/i.test(tag)) attrs += ' target="_blank"';
- if (!/\brel\s*=/i.test(tag)) attrs += ' rel="noopener"';
- return attrs ? tag.replace(/^<a\b/i, '<a' + attrs) : tag;
- });
- return icons ? wrapTables(html, icons) : html;
- };
- export const wrapTables = (html: string, icons: { copy: string; download: string; preview: string; copySuccess: string }): string => {
- return html.replace(/<table>([\s\S]*?)<\/table>/g, (match) => {
- const encodedTable = encodeURIComponent(match);
- return `<div class="markdown-table-wrapper">
- <div class="table-actions">
- <span class="table-action-btn" data-action="copy" data-table="${encodedTable}" data-icon="${icons.copy}" data-icon-success="${icons.copySuccess}" title="复制Markdown">
- <img src="${icons.copy}" width="14" height="14" />
- </span>
- <span class="table-action-btn" data-action="csv" data-table="${encodedTable}" title="下载CSV">
- <img src="${icons.download}" width="14" height="14" />
- </span>
- <span class="table-action-btn" data-action="preview" data-table="${encodedTable}" title="预览表格">
- <img src="${icons.preview}" width="14" height="14" />
- </span>
- </div>
- ${match}
- </div>`;
- });
- };
- export const tableHtmlToMarkdown = (tableHtml: string): string => {
- const parser = new DOMParser();
- const doc = parser.parseFromString(tableHtml, 'text/html');
- const table = doc.querySelector('table');
- if (!table) return tableHtml;
- const rows: string[][] = [];
- table.querySelectorAll('tr').forEach((tr) => {
- const cells: string[] = [];
- tr.querySelectorAll('th, td').forEach((cell) => {
- cells.push(cell.textContent?.trim() || '');
- });
- rows.push(cells);
- });
- if (rows.length === 0) return tableHtml;
- const colCount = Math.max(...rows.map((r) => r.length));
- const normalized = rows.map((r) => {
- while (r.length < colCount) r.push('');
- return r;
- });
- const lines: string[] = [];
- lines.push('| ' + normalized[0].join(' | ') + ' |');
- lines.push('| ' + normalized[0].map(() => '---').join(' | ') + ' |');
- for (let i = 1; i < normalized.length; i++) {
- lines.push('| ' + normalized[i].join(' | ') + ' |');
- }
- return lines.join('\n');
- };
- export const tableHtmlToCsv = (tableHtml: string): string => {
- const parser = new DOMParser();
- const doc = parser.parseFromString(tableHtml, 'text/html');
- const table = doc.querySelector('table');
- if (!table) return '';
- const rows: string[] = [];
- table.querySelectorAll('tr').forEach((tr) => {
- const cells: string[] = [];
- tr.querySelectorAll('th, td').forEach((cell) => {
- const text = (cell.textContent?.trim() || '').replace(/"/g, '""');
- cells.push(`"${text}"`);
- });
- rows.push(cells.join(','));
- });
- return '' + rows.join('\n');
- };
- export const formatFileSize = (bytes: number): string => {
- if (bytes < 1024) return bytes + ' B';
- if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
- return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
- };
- export const isImageFile = (filename: string): boolean => /\.(jpg|jpeg|png|gif|bmp|webp|svg|ico|tiff|tif)$/i.test(filename);
- export const isPdfFile = (filename: string): boolean => /\.pdf$/i.test(filename);
- export const isVideoFile = (filename: string): boolean => /\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i.test(filename);
- export const isAudioFile = (filename: string): boolean => /\.(mp3|wav|ogg|aac|flac|wma|m4a|opus)$/i.test(filename);
- export const isMdFile = (filename: string): boolean => /\.md$/i.test(filename);
- export const isWordFile = (filename: string): boolean => /\.(doc|docx)$/i.test(filename);
- export const isOldDocFile = (filename: string): boolean => /\.doc$/i.test(filename) && !/\.docx$/i.test(filename);
- export const isExcelFile = (filename: string): boolean => /\.(xls|xlsx)$/i.test(filename);
- export const isCsvFile = (filename: string): boolean => /\.csv$/i.test(filename);
- export const isTextFile = (filename: string): boolean =>
- /\.(txt|md|json|csv|xml|yaml|yml|log|ini|toml|cfg|conf|env|gitignore|dockerignore|editorconfig|prettierrc|eslintrc|babelrc|properties|sh|bat|ps1|cmd|bash|zsh|fish|sql|graphql|proto|js|ts|jsx|tsx|vue|css|scss|sass|less|html|htm|svelte|py|java|kt|kts|c|cpp|h|hpp|cc|cxx|cs|go|rs|rb|php|swift|m|mm|r|R|lua|pl|pm|hs|ex|exs|erl|clj|scala|dart|zig|nim|v|sol|tf|hcl|gradle|cmake|makefile|mk)$/i.test(
- filename
- );
- export const getFileExtension = (filename: string): string => {
- const match = filename.match(/\.([^.]+)$/);
- return match ? `.${match[1]}`.toUpperCase() : '';
- };
|