ShtukbaseStandard
package file→ .shtukbase/packages/chat/lens/markdown.js

lens/markdown.js

43 lines, 2.1 KB.

  1. // markdown.js: safe minimal Markdown for assistant text. HTML is escaped first; then code
  2. // fences, paragraphs, lists, headings (as bold lines), inline code, bold, italics, links (http/https only).
  3. (function () {
  4. 'use strict';
  5. function esc(s) {
  6. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  7. }
  8. function inline(s) {
  9. var codes = [];
  10. s = s.replace(/`([^`\n]+)`/g, function (_, c) { codes.push(c); return '\u0000' + (codes.length - 1) + '\u0000'; });
  11. s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
  12. s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>');
  13. s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
  14. return s.replace(/\u0000(\d+)\u0000/g, function (_, i) { return '<code>' + codes[+i] + '</code>'; });
  15. }
  16. function render(text) {
  17. var parts = esc(text || '').split(/^```[^\n]*\n?/m);
  18. var html = '';
  19. parts.forEach(function (part, i) {
  20. if (i % 2 === 1) { html += '<pre><code>' + part.replace(/\n$/, '') + '</code></pre>'; return; }
  21. part.split(/\n{2,}/).forEach(function (block) {
  22. var lines = block.split('\n').filter(function (l) { return l.trim(); });
  23. if (!lines.length) return;
  24. var bullet = /^\s*[-*•]\s+/, num = /^\s*\d+[.)]\s+/, run = null, items = [];
  25. function flush() {
  26. if (!run) return;
  27. if (run === 'p') html += '<p>' + items.join('<br>') + '</p>';
  28. else html += '<' + run + '>' + items.map(function (t) { return '<li>' + t + '</li>'; }).join('') + '</' + run + '>';
  29. run = null; items = [];
  30. }
  31. lines.forEach(function (l) {
  32. var kind = bullet.test(l) ? 'ul' : num.test(l) ? 'ol' : 'p';
  33. if (kind !== run) { flush(); run = kind; }
  34. var h = /^#{1,6}\s+(.*)$/.exec(l);
  35. items.push(kind === 'ul' ? inline(l.replace(bullet, '')) : kind === 'ol' ? inline(l.replace(num, '')) : h ? '<strong>' + inline(h[1]) + '</strong>' : inline(l));
  36. });
  37. flush();
  38. });
  39. });
  40. return html;
  41. }
  42. window.chatMarkdown = render;
  43. })();