包文件→ .shtukbase/packages/chat/lens/markdown.js
lens/markdown.js
43 行, 2.1 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // markdown.js: safe minimal Markdown for assistant text. HTML is escaped first; then code
- // fences, paragraphs, lists, headings (as bold lines), inline code, bold, italics, links (http/https only).
- (function () {
- 'use strict';
- function esc(s) {
- return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
- }
- function inline(s) {
- var codes = [];
- s = s.replace(/`([^`\n]+)`/g, function (_, c) { codes.push(c); return '\u0000' + (codes.length - 1) + '\u0000'; });
- s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
- s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>');
- s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
- return s.replace(/\u0000(\d+)\u0000/g, function (_, i) { return '<code>' + codes[+i] + '</code>'; });
- }
- function render(text) {
- var parts = esc(text || '').split(/^```[^\n]*\n?/m);
- var html = '';
- parts.forEach(function (part, i) {
- if (i % 2 === 1) { html += '<pre><code>' + part.replace(/\n$/, '') + '</code></pre>'; return; }
- part.split(/\n{2,}/).forEach(function (block) {
- var lines = block.split('\n').filter(function (l) { return l.trim(); });
- if (!lines.length) return;
- var bullet = /^\s*[-*•]\s+/, num = /^\s*\d+[.)]\s+/, run = null, items = [];
- function flush() {
- if (!run) return;
- if (run === 'p') html += '<p>' + items.join('<br>') + '</p>';
- else html += '<' + run + '>' + items.map(function (t) { return '<li>' + t + '</li>'; }).join('') + '</' + run + '>';
- run = null; items = [];
- }
- lines.forEach(function (l) {
- var kind = bullet.test(l) ? 'ul' : num.test(l) ? 'ol' : 'p';
- if (kind !== run) { flush(); run = kind; }
- var h = /^#{1,6}\s+(.*)$/.exec(l);
- items.push(kind === 'ul' ? inline(l.replace(bullet, '')) : kind === 'ol' ? inline(l.replace(num, '')) : h ? '<strong>' + inline(h[1]) + '</strong>' : inline(l));
- });
- flush();
- });
- });
- return html;
- }
- window.chatMarkdown = render;
- })();