Download src/shared/markdown-parser.js from chahuadev/chahuadev-markdown-presenter: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/chahuadev/chahuadev-markdown-presenter/resolve/main/src/shared/markdown-parser.js
- Command line
-
hf download hf://datasets/chahuadev/chahuadev-markdown-presenter/src/shared/markdown-parser.js
-
curl -L -o markdown-parser.js https://huggingface.co/datasets/chahuadev/chahuadev-markdown-presenter/resolve/main/src/shared/markdown-parser.js
15.9 kB
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Chahua Markdown Presenter - Markdown Parser | |
| // Parse Markdown into Presentation Slides | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Company: Chahua Development Co., Ltd. | |
| // Version: 2.0.0 | |
| // License: MIT | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| import { MarkdownSyntax, detectBlockType, parseInline } from './markdown-syntax.js'; | |
| import { applyPagination, getPaginationInfo } from './slide-paginator.js'; | |
| export class MarkdownParser { | |
| constructor(options = {}) { | |
| this.options = { | |
| slideBreak: options.slideBreak || '---', // Horizontal rule for slide breaks | |
| h1AsSlide: options.h1AsSlide !== false, // # creates new slide | |
| h2AsSlide: options.h2AsSlide || false, // ## creates new slide | |
| enablePagination: options.enablePagination !== false, // Auto-split long slides | |
| maxLinesPerSlide: options.maxLinesPerSlide || 8, // Max visual lines per slide | |
| ...options | |
| }; | |
| } | |
| /** | |
| * Parse markdown text into slides | |
| * @param {string} markdown - Raw markdown text | |
| * @returns {Array} Array of slide objects | |
| */ | |
| parse(markdown) { | |
| if (!markdown || typeof markdown !== 'string') { | |
| throw new Error('Invalid markdown input'); | |
| } | |
| // Split by slide breaks (---) | |
| const rawSlides = this.splitIntoSlides(markdown); | |
| // Parse each slide | |
| const slides = rawSlides.map((slideText, index) => { | |
| return this.parseSlide(slideText, index); | |
| }); | |
| // Filter empty slides | |
| const nonEmptySlides = slides.filter(slide => slide.content.length > 0); | |
| // Apply pagination if enabled | |
| if (this.options.enablePagination) { | |
| const paginatedSlides = []; | |
| let globalIndex = 0; | |
| for (const slide of nonEmptySlides) { | |
| const pages = applyPagination(slide); | |
| // Update indices | |
| pages.forEach((page, pageIndex) => { | |
| page.index = globalIndex++; | |
| page.originalIndex = slide.index; | |
| paginatedSlides.push(page); | |
| }); | |
| } | |
| return paginatedSlides; | |
| } | |
| return nonEmptySlides; | |
| } | |
| /** | |
| * Split markdown into slides based on rules | |
| */ | |
| splitIntoSlides(markdown) { | |
| const slides = []; | |
| let currentSlide = []; | |
| const lines = markdown.split('\n'); | |
| // Skip frontmatter block if present | |
| let startIndex = 0; | |
| if (lines[0] && lines[0].trim() === '---') { | |
| // Find closing --- | |
| for (let i = 1; i < Math.min(lines.length, 50); i++) { | |
| if (lines[i].trim() === '---') { | |
| startIndex = i + 1; | |
| break; | |
| } | |
| } | |
| } | |
| for (let i = startIndex; i < lines.length; i++) { | |
| const line = lines[i]; | |
| const trimmed = line.trim(); | |
| // Check for slide break (---) | |
| if (trimmed === '---' || trimmed === '___' || trimmed === '***') { | |
| if (currentSlide.length > 0) { | |
| slides.push(currentSlide.join('\n')); | |
| currentSlide = []; | |
| } | |
| continue; | |
| } | |
| // Check for H1 as slide break | |
| if (this.options.h1AsSlide && trimmed.startsWith('# ') && currentSlide.length > 0) { | |
| slides.push(currentSlide.join('\n')); | |
| currentSlide = [line]; | |
| continue; | |
| } | |
| // Check for H2 as slide break | |
| if (this.options.h2AsSlide && trimmed.startsWith('## ') && currentSlide.length > 0) { | |
| slides.push(currentSlide.join('\n')); | |
| currentSlide = [line]; | |
| continue; | |
| } | |
| currentSlide.push(line); | |
| } | |
| // Add last slide | |
| if (currentSlide.length > 0) { | |
| slides.push(currentSlide.join('\n')); | |
| } | |
| return slides; | |
| } | |
| /** | |
| * Parse individual slide content using Markdown Dictionary | |
| */ | |
| parseSlide(slideText, index) { | |
| const content = []; | |
| const lines = slideText.split('\n'); | |
| let title = ''; | |
| let subtitle = ''; | |
| let customDuration = null; | |
| let inCodeBlock = false; | |
| let codeLines = []; | |
| let codeLang = ''; | |
| let codeFence = '```'; | |
| let inBlockquote = false; | |
| let blockquoteLines = []; | |
| let inTable = false; | |
| let tableRows = []; | |
| let inHtml = false; | |
| let htmlLines = []; | |
| for (let i = 0; i < lines.length; i++) { | |
| const line = lines[i]; | |
| const trimmed = line.trim(); | |
| const nextLine = i < lines.length - 1 ? lines[i + 1] : null; | |
| // Skip empty lines (unless in special block) | |
| if (!trimmed && !inCodeBlock && !inHtml) { | |
| // End blockquote on empty line | |
| if (inBlockquote && blockquoteLines.length > 0) { | |
| const quoteText = blockquoteLines.join('\n'); | |
| content.push({ | |
| type: 'blockquote', | |
| content: quoteText, | |
| html: this.parseInline(quoteText) | |
| }); | |
| blockquoteLines = []; | |
| inBlockquote = false; | |
| } | |
| // End table on empty line | |
| if (inTable && tableRows.length > 0) { | |
| content.push({ | |
| type: 'table', | |
| rows: tableRows | |
| }); | |
| tableRows = []; | |
| inTable = false; | |
| } | |
| continue; | |
| } | |
| // Check for metadata (subtitle: or duration:) | |
| if (trimmed.match(/^(subtitle|duration):\s*(.+)$/i)) { | |
| const match = trimmed.match(/^(subtitle|duration):\s*(.+)$/i); | |
| const key = match[1].toLowerCase(); | |
| const value = match[2].trim(); | |
| if (key === 'subtitle') { | |
| subtitle = value; | |
| } else if (key === 'duration') { | |
| customDuration = parseFloat(value); | |
| } | |
| continue; | |
| } | |
| // Code block detection (using dictionary) | |
| const codeBlockCheck = MarkdownSyntax.blocks.codeBlock.detect(trimmed); | |
| if (codeBlockCheck) { | |
| if (codeBlockCheck.type === 'code-fence-start') { | |
| if (!inCodeBlock) { | |
| // Start code block | |
| inCodeBlock = true; | |
| codeLang = codeBlockCheck.language || 'text'; | |
| codeFence = codeBlockCheck.fence || '```'; | |
| codeLines = []; | |
| } else { | |
| // End code block | |
| inCodeBlock = false; | |
| content.push({ | |
| type: 'code', | |
| language: codeLang, | |
| content: codeLines.join('\n') | |
| }); | |
| codeLines = []; | |
| codeLang = ''; | |
| codeFence = '```'; | |
| } | |
| continue; | |
| } else if (codeBlockCheck.type === 'code-indented' && !inCodeBlock) { | |
| // Indented code (4 spaces or tab) | |
| content.push({ | |
| type: 'code', | |
| language: 'text', | |
| content: codeBlockCheck.content | |
| }); | |
| continue; | |
| } | |
| } | |
| if (inCodeBlock) { | |
| codeLines.push(line); | |
| continue; | |
| } | |
| // HTML block detection | |
| const htmlCheck = MarkdownSyntax.blocks.html.detect(trimmed); | |
| if (htmlCheck) { | |
| if (!inHtml) { | |
| inHtml = true; | |
| htmlLines = [line]; | |
| } else { | |
| htmlLines.push(line); | |
| } | |
| // Check if HTML block ends (closing tag) | |
| if (trimmed.match(/<\/[a-z][a-z0-9-]*\s*>/i) || trimmed === '-->') { | |
| inHtml = false; | |
| content.push({ | |
| type: 'html', | |
| content: htmlLines.join('\n') | |
| }); | |
| htmlLines = []; | |
| } | |
| continue; | |
| } | |
| if (inHtml) { | |
| htmlLines.push(line); | |
| continue; | |
| } | |
| // Heading detection (using dictionary - supports both ATX and Setext) | |
| const headingCheck = MarkdownSyntax.blocks.heading.detect(trimmed, nextLine?.trim()); | |
| if (headingCheck) { | |
| const text = headingCheck.content; | |
| const level = headingCheck.level; | |
| const headingHtml = this.parseInline(text); | |
| if (level === 1) { | |
| if (!title) title = text; | |
| content.push({ type: 'h1', content: text, html: headingHtml }); | |
| } else if (level === 2) { | |
| if (!subtitle && title) subtitle = text; | |
| content.push({ type: 'h2', content: text, html: headingHtml }); | |
| } else if (level === 3) { | |
| content.push({ type: 'h3', content: text, html: headingHtml }); | |
| } else if (level === 4) { | |
| content.push({ type: 'h4', content: text, html: headingHtml }); | |
| } else if (level === 5) { | |
| content.push({ type: 'h5', content: text, html: headingHtml }); | |
| } else if (level === 6) { | |
| content.push({ type: 'h6', content: text, html: headingHtml }); | |
| } | |
| // Skip next line if Setext style | |
| if (headingCheck.style === 'setext') { | |
| i++; | |
| } | |
| continue; | |
| } | |
| // Horizontal rule detection | |
| const hrCheck = MarkdownSyntax.blocks.hr.detect(trimmed); | |
| if (hrCheck) { | |
| content.push({ type: 'hr' }); | |
| continue; | |
| } | |
| // Task list detection (GFM) | |
| const taskCheck = MarkdownSyntax.blocks.taskList.detect(trimmed); | |
| if (taskCheck) { | |
| content.push({ | |
| type: 'task-list', | |
| checked: taskCheck.checked, | |
| content: taskCheck.content, | |
| html: this.parseInline(taskCheck.content) | |
| }); | |
| continue; | |
| } | |
| // Table detection (GFM) | |
| const tableCheck = MarkdownSyntax.blocks.table.detect(trimmed); | |
| if (tableCheck) { | |
| inTable = true; | |
| if (tableCheck.type === 'table-row') { | |
| tableRows.push(tableCheck.cells); | |
| } | |
| continue; | |
| } | |
| // List detection (using dictionary - supports -, *, +, and numbered) | |
| const listCheck = MarkdownSyntax.blocks.list.detect(trimmed); | |
| if (listCheck) { | |
| if (listCheck.ordered) { | |
| content.push({ | |
| type: 'numbered-item', | |
| number: listCheck.number, | |
| content: listCheck.content, | |
| html: this.parseInline(listCheck.content) | |
| }); | |
| } else { | |
| content.push({ | |
| type: 'list-item', | |
| marker: listCheck.marker, | |
| content: listCheck.content, | |
| html: this.parseInline(listCheck.content) | |
| }); | |
| } | |
| continue; | |
| } | |
| // Blockquote detection (using dictionary - supports nested >) | |
| const blockquoteCheck = MarkdownSyntax.blocks.blockquote.detect(trimmed); | |
| if (blockquoteCheck) { | |
| inBlockquote = true; | |
| blockquoteLines.push(blockquoteCheck.content); | |
| continue; | |
| } | |
| // Image detection (inline pattern) | |
| if (trimmed.match(MarkdownSyntax.inline.image.patterns[0].regex)) { | |
| const match = trimmed.match(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/); | |
| content.push({ | |
| type: 'image', | |
| alt: match[1] || '', | |
| src: match[2], | |
| title: match[3] || '' | |
| }); | |
| continue; | |
| } | |
| // Link detection (inline pattern) | |
| if (trimmed.match(MarkdownSyntax.inline.link.patterns[0].regex)) { | |
| const match = trimmed.match(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/); | |
| content.push({ | |
| type: 'link', | |
| text: match[1], | |
| url: match[2], | |
| title: match[3] || '', | |
| html: this.parseInline(match[0]) | |
| }); | |
| continue; | |
| } | |
| // Regular text/paragraph (with inline formatting) | |
| if (trimmed) { | |
| content.push({ | |
| type: 'text', | |
| content: trimmed, | |
| html: this.parseInline(trimmed) | |
| }); | |
| } | |
| } | |
| // Flush remaining blocks | |
| if (blockquoteLines.length > 0) { | |
| const quoteText = blockquoteLines.join('\n'); | |
| content.push({ | |
| type: 'blockquote', | |
| content: quoteText, | |
| html: this.parseInline(quoteText) | |
| }); | |
| } | |
| if (tableRows.length > 0) { | |
| content.push({ | |
| type: 'table', | |
| rows: tableRows | |
| }); | |
| } | |
| if (htmlLines.length > 0) { | |
| content.push({ | |
| type: 'html', | |
| content: htmlLines.join('\n') | |
| }); | |
| } | |
| const normalizedTitle = title ? title.trim() : ''; | |
| return { | |
| index, | |
| title: normalizedTitle, | |
| subtitle: subtitle || '', | |
| content, | |
| duration: customDuration !== null ? customDuration : this.calculateDuration(content) | |
| }; | |
| } | |
| /** | |
| * Calculate recommended duration for slide based on content | |
| */ | |
| calculateDuration(content) { | |
| let duration = 3; // Base duration in seconds | |
| content.forEach(item => { | |
| switch (item.type) { | |
| case 'h1': | |
| duration += 2; | |
| break; | |
| case 'h2': | |
| case 'h3': | |
| duration += 1.5; | |
| break; | |
| case 'h4': | |
| case 'h5': | |
| case 'h6': | |
| duration += 1; | |
| break; | |
| case 'list-item': | |
| case 'numbered-item': | |
| case 'task-list': | |
| duration += 1; | |
| break; | |
| case 'code': | |
| const lines = item.content.split('\n').length; | |
| duration += Math.min(lines * 0.5, 10); // Max 10 seconds for code | |
| break; | |
| case 'blockquote': | |
| const words = item.content.split(' ').length; | |
| duration += words * 0.4; // Quotes need more reading time | |
| break; | |
| case 'text': | |
| const textWords = item.content.split(' ').length; | |
| duration += textWords * 0.3; // ~200 words per minute | |
| break; | |
| case 'image': | |
| duration += 3; | |
| break; | |
| case 'table': | |
| const rows = item.rows ? item.rows.length : 1; | |
| duration += rows * 1.5; // Tables need time to understand | |
| break; | |
| case 'html': | |
| duration += 2; // HTML content | |
| break; | |
| case 'hr': | |
| duration += 0.5; // Separator | |
| break; | |
| default: | |
| duration += 1; | |
| } | |
| }); | |
| return Math.round(duration); | |
| } | |
| /** | |
| * Parse inline markdown (bold, italic, code, strikethrough, etc.) | |
| * Uses Markdown Dictionary for comprehensive syntax support | |
| */ | |
| parseInline(text) { | |
| if (!text) return ''; | |
| // Use the dictionary's parseInline function | |
| return parseInline(text); | |
| } | |
| /** | |
| * Get summary of parsed markdown | |
| */ | |
| getSummary(slides) { | |
| const totalPages = slides.reduce((sum, slide) => { | |
| return sum + (slide.totalPages || 1); | |
| }, 0); | |
| return { | |
| totalSlides: slides.length, | |
| totalPages: totalPages, | |
| estimatedDuration: slides.reduce((sum, slide) => sum + slide.duration, 0), | |
| titles: slides.map(slide => slide.title), | |
| paginatedSlides: slides.filter(s => s.totalPages > 1).length | |
| }; | |
| } | |
| /** | |
| * Get pagination info for a slide without parsing | |
| */ | |
| getPaginationPreview(slideContent) { | |
| return getPaginationInfo(slideContent); | |
| } | |
| } | |
| // Export helper function | |
| export function parseMarkdown(markdown, options = {}) { | |
| const parser = new MarkdownParser(options); | |
| return parser.parse(markdown); | |
| } | |