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
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// ══════════════════════════════════════════════════════════════════════════════
// 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);
}