chahuadev-markdown-presenter / src /shared /markdown-syntax.js
chahuadev's picture
Upload 51 files
f462b1c verified
// ══════════════════════════════════════════════════════════════════════════════
// Markdown Syntax Dictionary
// Complete Markdown syntax patterns and recognition rules
// ══════════════════════════════════════════════════════════════════════════════
/**
* Markdown Syntax Dictionary
* Based on CommonMark + GitHub Flavored Markdown (GFM)
*/
export const MarkdownSyntax = {
// ════════════════════════════════════════════════════════════════════════════
// Block-level Elements
// ════════════════════════════════════════════════════════════════════════════
blocks: {
// Headings: # H1, ## H2, ### H3, #### H4, ##### H5, ###### H6
heading: {
patterns: [
/^(#{1,6})\s+(.+)$/, // ATX style: # Heading
/^(.+)\n={3,}\s*$/, // Setext H1: underline with ===
/^(.+)\n-{3,}\s*$/ // Setext H2: underline with ---
],
detect: (line, nextLine) => {
// ATX headings
const atx = line.match(/^(#{1,6})\s+(.+)$/);
if (atx) {
return {
type: 'heading',
level: atx[1].length,
content: atx[2].trim(),
style: 'atx'
};
}
// Setext headings (require next line)
if (nextLine) {
if (nextLine.match(/^={3,}\s*$/)) {
return { type: 'heading', level: 1, content: line.trim(), style: 'setext' };
}
if (nextLine.match(/^-{3,}\s*$/) && !line.match(/^\s*$/)) {
return { type: 'heading', level: 2, content: line.trim(), style: 'setext' };
}
}
return null;
}
},
// Horizontal Rules: ---, ***, ___
hr: {
patterns: [
/^-{3,}\s*$/,
/^\*{3,}\s*$/,
/^_{3,}\s*$/,
/^- {0,2}- {0,2}-/,
/^\* {0,2}\* {0,2}\*/,
/^_ {0,2}_ {0,2}_/
],
detect: (line) => {
for (const pattern of MarkdownSyntax.blocks.hr.patterns) {
if (pattern.test(line.trim())) {
return { type: 'hr' };
}
}
return null;
}
},
// Code Blocks: ```lang or indented 4 spaces
codeBlock: {
patterns: [
/^```(\w*)\s*$/, // Fenced code block start
/^~~~(\w*)\s*$/, // Alternative fence
/^ (.+)$/, // Indented code (4 spaces)
/^\t(.+)$/ // Indented code (tab)
],
detect: (line) => {
// Fenced code block
const fenced = line.match(/^```(\w*)\s*$/);
if (fenced) {
return { type: 'code-fence-start', language: fenced[1] || 'text' };
}
const tilde = line.match(/^~~~(\w*)\s*$/);
if (tilde) {
return { type: 'code-fence-start', language: tilde[1] || 'text', fence: '~~~' };
}
// Indented code
if (line.match(/^ (.+)$/) || line.match(/^\t(.+)$/)) {
return { type: 'code-indented', content: line.replace(/^ |\t/, '') };
}
return null;
}
},
// Blockquotes: > Quote
blockquote: {
patterns: [
/^>\s?(.*)$/, // > Quote
/^> ?> ?(.*)$/ // Nested: >> Quote
],
detect: (line) => {
const match = line.match(/^(>+)\s?(.*)$/);
if (match) {
return {
type: 'blockquote',
level: match[1].length,
content: match[2]
};
}
return null;
}
},
// Lists: Unordered (-, *, +) and Ordered (1., 2.)
list: {
patterns: [
/^(\s*)([-*+])\s+(.+)$/, // Unordered: -, *, +
/^(\s*)(\d{1,9})[.)]\s+(.+)$/ // Ordered: 1., 2), etc.
],
detect: (line) => {
// Unordered list
const unordered = line.match(/^(\s*)([-*+])\s+(.+)$/);
if (unordered) {
return {
type: 'list',
ordered: false,
indent: unordered[1].length,
marker: unordered[2],
content: unordered[3]
};
}
// Ordered list
const ordered = line.match(/^(\s*)(\d{1,9})[.)]\s+(.+)$/);
if (ordered) {
return {
type: 'list',
ordered: true,
indent: ordered[1].length,
number: parseInt(ordered[2]),
content: ordered[3]
};
}
return null;
}
},
// Task Lists (GFM): - [ ] Task or - [x] Done
taskList: {
patterns: [
/^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/
],
detect: (line) => {
const match = line.match(/^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/);
if (match) {
return {
type: 'task-list',
indent: match[1].length,
checked: match[3].toLowerCase() === 'x',
content: match[4]
};
}
return null;
}
},
// Tables (GFM): | Header | Header |
table: {
patterns: [
/^\|(.+)\|$/, // Table row
/^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/ // Separator
],
detect: (line) => {
if (line.match(/^\|(.+)\|$/)) {
return { type: 'table-row', cells: line.split('|').filter(c => c.trim()) };
}
if (line.match(/^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/)) {
return { type: 'table-separator' };
}
return null;
}
},
// HTML Blocks: <div>, <!-- comment -->
html: {
patterns: [
/^<([a-z][a-z0-9-]*)\b[^>]*>/i, // Opening tag
/^<\/([a-z][a-z0-9-]*)\s*>/i, // Closing tag
/^<!--/, // Comment start
/^<\?/, // Processing instruction
/^<![A-Z]/, // Declaration
/^<!\[CDATA\[/ // CDATA section
],
detect: (line) => {
for (const pattern of MarkdownSyntax.blocks.html.patterns) {
if (pattern.test(line.trim())) {
return { type: 'html', content: line };
}
}
return null;
}
},
// Metadata blocks (YAML frontmatter, TOML, JSON)
metadata: {
patterns: [
/^---\s*$/, // YAML
/^\+\+\+\s*$/, // TOML
/^;;;\s*$/ // JSON (some parsers)
],
detect: (line) => {
if (line.trim() === '---') return { type: 'metadata', format: 'yaml' };
if (line.trim() === '+++') return { type: 'metadata', format: 'toml' };
if (line.trim() === ';;;') return { type: 'metadata', format: 'json' };
return null;
}
}
},
// ════════════════════════════════════════════════════════════════════════════
// Inline Elements
// ════════════════════════════════════════════════════════════════════════════
inline: {
// Emphasis: *italic*, _italic_, **bold**, __bold__, ***bold italic***
emphasis: {
patterns: [
{ regex: /\*\*\*(.+?)\*\*\*/g, type: 'bold-italic', tag: 'strong-em' },
{ regex: /___(.+?)___/g, type: 'bold-italic', tag: 'strong-em' },
{ regex: /\*\*(.+?)\*\*/g, type: 'bold', tag: 'strong' },
{ regex: /__(.+?)__/g, type: 'bold', tag: 'strong' },
{ regex: /\*(.+?)\*/g, type: 'italic', tag: 'em' },
{ regex: /_(.+?)_/g, type: 'italic', tag: 'em' }
]
},
// Strikethrough (GFM): ~~deleted~~
strikethrough: {
patterns: [
{ regex: /~~(.+?)~~/g, type: 'strikethrough', tag: 'del' }
]
},
// Code: `inline code`
code: {
patterns: [
{ regex: /``(.+?)``/g, type: 'code', tag: 'code' }, // Double backtick
{ regex: /`(.+?)`/g, type: 'code', tag: 'code' } // Single backtick
]
},
// Links: [text](url "title"), [text][ref], <url>
link: {
patterns: [
{ regex: /\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'link' }, // Inline
{ regex: /\[([^\]]+)\]\[([^\]]+)\]/g, type: 'link-ref' }, // Reference
{ regex: /\[([^\]]+)\]/g, type: 'link-shortcut' }, // Shortcut
{ regex: /<(https?:\/\/[^>]+)>/g, type: 'autolink' }, // Autolink
{ regex: /<([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>/g, type: 'email' } // Email
]
},
// Images: ![alt](url "title"), ![alt][ref]
image: {
patterns: [
{ regex: /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'image' }, // Inline
{ regex: /!\[([^\]]*)\]\[([^\]]+)\]/g, type: 'image-ref' } // Reference
]
},
// Line breaks: two spaces + newline, backslash + newline, <br>
lineBreak: {
patterns: [
{ regex: / \n/g, type: 'soft-break' },
{ regex: /\\\n/g, type: 'hard-break' },
{ regex: /<br\s*\/?>/gi, type: 'html-break' }
]
},
// Escape sequences: \*, \[, etc.
escape: {
characters: ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!', '|']
},
// Emoji (GFM): :smile:, :heart:
emoji: {
pattern: /:([a-z0-9_+-]+):/g
},
// Mentions (GFM): @username
mention: {
pattern: /@([a-zA-Z0-9_-]+)/g
},
// Hashtags: #tag
hashtag: {
pattern: /#([a-zA-Z0-9_-]+)/g
}
},
// ════════════════════════════════════════════════════════════════════════════
// Special Constructs
// ════════════════════════════════════════════════════════════════════════════
special: {
// Footnotes: [^1], [^note]
footnote: {
definition: /^\[\^([^\]]+)\]:\s+(.+)$/,
reference: /\[\^([^\]]+)\]/g
},
// Abbreviations: *[HTML]: Hyper Text Markup Language
abbreviation: {
pattern: /^\*\[([^\]]+)\]:\s+(.+)$/
},
// Definition lists:
// Term
// : Definition
definitionList: {
term: /^([^\n:]+)\s*$/,
definition: /^:\s+(.+)$/
},
// Math (KaTeX/MathJax): $inline$, $$block$$
math: {
inline: /\$([^$]+)\$/g,
block: /\$\$([^$]+)\$\$/g
}
}
};
/**
* Check if a line matches any block-level syntax
*/
export function detectBlockType(line, nextLine = null) {
// Check each block type
for (const [blockName, block] of Object.entries(MarkdownSyntax.blocks)) {
const result = block.detect(line, nextLine);
if (result) {
return result;
}
}
return { type: 'paragraph' };
}
/**
* Parse inline markdown syntax
*/
function escapeHtml(str) {
if (str == null) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function parseInline(text) {
if (!text) return '';
let result = escapeHtml(text);
// Images (handle before links so the leading ! is preserved)
result = result.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, alt, url, title) => {
const altAttr = escapeHtml(alt || '');
const srcAttr = escapeHtml(url || '');
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<img src="${srcAttr}" alt="${altAttr}"${titleAttr}>`;
});
// Inline links [text](url "title")
result = result.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, label, url, title) => {
const textContent = escapeHtml(label || '');
const hrefAttr = escapeHtml(url || '#');
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<a href="${hrefAttr}"${titleAttr}>${textContent}</a>`;
});
// Autolinks <https://example.com>
result = result.replace(/&lt;(https?:\/\/[^&]+)&gt;/g, (match, url) => {
const hrefAttr = escapeHtml(url);
return `<a href="${hrefAttr}">${hrefAttr}</a>`;
});
// Email autolinks <user@example.com>
result = result.replace(/&lt;([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})&gt;/g, (match, email) => {
const mailto = `mailto:${email}`;
return `<a href="${escapeHtml(mailto)}">${escapeHtml(email)}</a>`;
});
// Emphasis and code (process complex patterns first)
const replacements = [
{ regex: /\*\*\*(.+?)\*\*\*/g, wrap: content => `<strong><em>${content}</em></strong>` },
{ regex: /___(.+?)___/g, wrap: content => `<strong><em>${content}</em></strong>` },
{ regex: /\*\*(.+?)\*\*/g, wrap: content => `<strong>${content}</strong>` },
{ regex: /__(.+?)__/g, wrap: content => `<strong>${content}</strong>` },
{ regex: /\*(.+?)\*/g, wrap: content => `<em>${content}</em>` },
{ regex: /_(.+?)_/g, wrap: content => `<em>${content}</em>` },
{ regex: /~~(.+?)~~/g, wrap: content => `<del>${content}</del>` },
{ regex: /``(.+?)``/g, wrap: content => `<code>${content}</code>` },
{ regex: /`(.+?)`/g, wrap: content => `<code>${content}</code>` }
];
replacements.forEach(({ regex, wrap }) => {
result = result.replace(regex, (match, content) => wrap(content));
});
// Line breaks
result = result.replace(/ \n/g, '<br>');
result = result.replace(/\\\n/g, '<br>');
result = result.replace(/&lt;br\s*\/?&gt;/gi, '<br>');
return result;
}
/**
* Get syntax info for documentation
*/
export function getSyntaxInfo(category) {
const info = {
blocks: 'Block-level elements (headings, lists, code blocks, etc.)',
inline: 'Inline elements (emphasis, links, images, etc.)',
special: 'Special constructs (footnotes, math, definitions, etc.)'
};
return info[category] || 'Unknown category';
}