-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkpaper.js
More file actions
1441 lines (1273 loc) · 49.9 KB
/
markpaper.js
File metadata and controls
1441 lines (1273 loc) · 49.9 KB
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* @file markpaper.js
* @description A clean and academic Markdown renderer for the web.
* Includes support for extended syntax (alerts, footnotes), KaTeX, PrismJS, and theme management.
* @version 1.2.0
*/
// ============================================================================
// 1. CONFIGURATION & CONSTANTS
// ============================================================================
/**
* Global configuration object containing whitelists and regex patterns.
* @constant {Object}
*/
const CONFIG = {
/**
* List of HTML tags allowed in the final output.
* Used by the sanitization function to prevent XSS attacks.
*/
ALLOWED_TAGS: [
'strong', 'b', 'em', 'i', 'u', 's', 'del', 'ins', 'mark',
'span', 'div', 'p', 'br', 'hr', 'code', 'pre',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
'blockquote', 'q', 'cite',
'table', 'thead', 'tbody', 'tr', 'th', 'td',
'a', 'img', 'sub', 'sup', 'small', 'abbr', 'time',
'figure', 'figcaption',
'iframe', 'details', 'summary',
// Allowed MathML/HTML tags generated by KaTeX
'math', 'semantics', 'mrow', 'mi', 'mo', 'mn', 'msup', 'msub', 'annotation'
],
/**
* List of HTML attributes allowed on the tags above.
*/
ALLOWED_ATTRIBUTES: [
'class', 'id', 'style', 'title', 'lang', 'dir',
'href', 'target', 'rel', // specific to <a>
'src', 'alt', 'width', 'height', // specific to <img>
'colspan', 'rowspan', // specific to <table>
'datetime', 'cite', 'type', 'disabled', 'checked', // specific to <input>, <time>
'frameborder', 'allow', 'allowfullscreen', 'loading', // video embeds
'aria-hidden' // Accessibility for KaTeX
],
/**
* Regular expression patterns to identify Markdown syntax elements.
* Compiled once here for performance efficiency.
*/
PATTERNS: {
METADATA: /^(\w+):\s*(.+)$/, // Metadata key: value
H1: /^#\s+(.*)/, // # Title
HEADING: /^(#{2,6})\s+(.*)/, // ##... Subtitles
HR: /^(\*{3,}|-{3,}|_{3,})$/, // Horizontal Rule
LIST_UL: /^(\s*)\*\s+(.*)$/, // Unordered list
LIST_OL: /^(\s*)(-|\d+\.)\s+(.*)$/, // Ordered list
CHECKBOX: /^\[([xX ]?)\]\s+(.*)$/, // Task list checkbox
BLOCKQUOTE: /^> ?(.*)/, // Blockquote
ALERT: /^\[!(NOTE|WARNING|IMPORTANT|TIP|CAUTION)\]$/, // GitHub-style alerts
FENCE_START: /^(```+|````+)(\w*)/, // Code block start
MATH_BLOCK_START: /^\$\$/, // Math block start/end
TABLE_ROW: /^\s*\|?(.+)\|?\s*$/, // Table row
IMAGE: /^!\[([^\]]*)\]\(([^)]+)\)/, // Image syntax
FOOTNOTE_DEF: /^\[\^([^\]]+)\]:\s*(.+)$/, // Footnote definition
// Regex for auto-embedding videos (standalone lines)
VIDEO_YOUTUBE: /^https?:\/\/(?:www\.|m\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)(?:[\?&][\w=-]+)*$/,
VIDEO_VIMEO: /^https?:\/\/(?:www\.)?vimeo\.com\/(\d+)$/,
// Detect lines starting with Block HTML tags to prevent <p> wrapping
BLOCK_HTML_START: /^\s*<\/?(dl|dt|dd|details|summary|div|figure|figcaption|iframe|video|audio)[\s>]/i
},
/**
* Default values for CSS variables used in the theme system.
*/
DEFAULTS: {
'--font-base-size': '16px',
'--text-color': '#212529',
'--background-color': '#FFFFFF',
'--accent-color': '#4a6a70',
'--current-font-family': 'serif',
'--border-color': '#e9ecef',
'--modal-header-bg': '#f8f9fa',
'--light-gray-color': '#f8f9fa',
'--code-background': '#f8f9fa'
}
};
// ============================================================================
// 2. PARSER CORE
// ============================================================================
/**
* Main class responsible for parsing raw Markdown text into HTML.
* It handles state management for nested blocks (lists, code, tables).
*/
class MarkPaperParser {
/**
* Initializes the parser.
*/
constructor() {
this.reset();
}
/**
* Resets the internal state of the parser.
* Must be called before parsing a new file.
*/
reset() {
this.html = '';
this.globalFigureNum = 0;
this.currentFileName = '';
// Section Numbering State
this.chapterNum = 0;
this.sectionNum = 0;
this.currentSectionLevel = 0; // 1=h1, 2=h2...
// Footnote State
this.footnotesDef = {}; // Stores footnote content (id -> content)
this.sectionFootnotes = []; // Tracks footnotes used in the current section
// Block Context State
this.state = {
inCodeBlock: false, codeFence: '', codeLang: '', codeBuffer: [],
inMathBlock: false, mathBuffer: [],
inTable: false, tableHeader: null, tableRows: [],
inBlockquote: false, blockquoteBuffer: [],
inAlert: false, alertType: '', alertBuffer: [],
listStack: [], listCounters: [] // Handles nested lists
};
}
/**
* The main method to convert Markdown to HTML.
* @param {string} markdown - The raw Markdown text.
* @param {string} fileName - The name of the file (used for metadata/footer).
* @returns {string} - The compiled and sanitized HTML string.
*/
parse(markdown, fileName = 'unknown file') {
this.reset();
this.currentFileName = fileName;
const rawLines = markdown.split(/\r?\n/);
// Preprocess to extract footnote definitions from the bottom/text
const lines = this.preprocess(rawLines);
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trimEnd();
// 1. Handle Code Blocks (Highest priority)
if (this.processCodeBlock(line)) continue;
if (this.state.inCodeBlock) {
this.state.codeBuffer.push(line);
continue;
}
// 2. Handle Math Blocks
if (this.processMathBlock(line)) continue;
if (this.state.inMathBlock) {
this.state.mathBuffer.push(line);
continue;
}
// 3. Handle Empty Lines (Triggers block closures)
if (line.trim() === '') {
this.processEmptyLine();
continue;
}
// 4. Handle Indented Code Blocks
if (this.processIndentedCode(line)) continue;
// 5. Handle Headings
if (this.processHeadings(line, i, lines)) continue;
// 6. Handle Horizontal Rules
if (CONFIG.PATTERNS.HR.test(line.trim())) {
this.closeAllBlocks();
this.html += '<hr>\n';
continue;
}
// 7. Handle Lists
if (this.processLists(line)) continue;
// 8. Handle Tables
if (this.processTables(line, i, lines)) continue;
// 9. Handle Blockquotes & Alerts
if (this.processQuotesAndAlerts(line)) continue;
// 10. Handle Standalone Images
if (this.processStandaloneImage(line)) continue;
// 11. Handle Video Embeds (YouTube/Vimeo)
if (this.processMediaEmbeds(line)) continue;
// 12. Handle Raw Block HTML
if (this.processBlockHtml(line)) continue;
// 13. Default: Paragraph
// Close strictly block-level elements before starting a paragraph
this.closeList();
this.closeTable();
this.closeBlockquote();
this.closeAlert();
this.html += `<p>${this.escapeInline(line)}</p>\n`;
}
// Final Cleanup (Close any open blocks at EOF)
this.closeAllBlocks();
this.appendSectionFootnotes();
this.html += this.generateFooter();
return this.html;
}
/**
* Pre-processes lines to extract footnote definitions.
* Definitions are stored and removed from the main flow.
* @param {string[]} lines - The array of markdown lines.
* @returns {string[]} - The filtered array of lines.
*/
preprocess(lines) {
const cleanedLines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const fnMatch = line.match(CONFIG.PATTERNS.FOOTNOTE_DEF);
if (fnMatch) {
this.footnotesDef[fnMatch[1]] = fnMatch[2];
continue;
}
cleanedLines.push(line);
}
return cleanedLines;
}
// --- Block Handlers ---
/**
* Detects and manages the state of code blocks (```).
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processCodeBlock(line) {
const match = line.match(CONFIG.PATTERNS.FENCE_START);
if (match) {
const fence = match[1];
const lang = match[2];
if (this.state.inCodeBlock) {
// Check if closing fence matches opening fence
if (fence === this.state.codeFence) {
this.flushCodeBlock();
return true;
}
return false;
} else {
// Start new block
this.closeAllBlocks();
this.state.inCodeBlock = true;
this.state.codeFence = fence;
this.state.codeLang = lang;
this.state.codeBuffer = [];
return true;
}
}
return false;
}
/**
* Detects and manages Math blocks ($$).
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processMathBlock(line) {
const match = line.match(CONFIG.PATTERNS.MATH_BLOCK_START);
// Handle inline display math: $$...$$ on a single line
const singleLineMatch = line.match(/^\$\$(.+)\$\$$/);
if (singleLineMatch && !this.state.inMathBlock) {
this.closeAllBlocks();
this.html += this.renderKaTeX(singleLineMatch[1], true);
return true;
}
if (match) {
if (this.state.inMathBlock) {
this.flushMathBlock();
return true;
} else {
this.closeAllBlocks();
this.state.inMathBlock = true;
this.state.mathBuffer = [];
return true;
}
}
return false;
}
/**
* Handles indented code blocks (4 spaces or tab).
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processIndentedCode(line) {
if ((line.startsWith(' ') || line.startsWith('\t')) &&
!CONFIG.PATTERNS.LIST_UL.test(line) &&
!CONFIG.PATTERNS.LIST_OL.test(line) &&
!this.state.inMathBlock) {
this.closeList();
const codeText = line.replace(/^( |\t)/, '');
this.html += `<div class="code-block-container"><button class="copy-btn">Copy</button><pre><code class="language-plaintext">${this.escapeHTML(codeText)}</code></pre></div>\n`;
return true;
}
return false;
}
/**
* Processes headings (#) and metadata blocks at the top of the file.
* @param {string} line - Current line.
* @param {number} index - Current line index.
* @param {string[]} lines - All lines (to read ahead for metadata).
* @returns {boolean} - True if line was consumed.
*/
processHeadings(line, index, lines) {
const h1Match = line.match(CONFIG.PATTERNS.H1);
if (h1Match) {
this.closeAllBlocks();
this.appendSectionFootnotes();
this.currentSectionLevel = 1;
let metadata = {};
// Look ahead for metadata (author: ...)
let k = index + 1;
while (k < lines.length) {
const nextLine = lines[k].trim();
if (nextLine === '') { k++; continue; }
const metaMatch = nextLine.match(CONFIG.PATTERNS.METADATA);
if (metaMatch) {
metadata[metaMatch[1]] = metaMatch[2];
lines[k] = ''; // Consume line
k++;
} else { break; }
}
this.html += this.renderDocumentHeader(h1Match[1], metadata);
return true;
}
const hMatch = line.match(CONFIG.PATTERNS.HEADING);
if (hMatch) {
this.closeAllBlocks();
const level = hMatch[1].length;
const text = hMatch[2];
// Flush footnotes when section level changes appropriately
if (level <= this.currentSectionLevel || this.currentSectionLevel >= 3) {
this.appendSectionFootnotes();
}
this.currentSectionLevel = level;
// Auto-numbering logic for H2 and H3
let displayText = text;
if (level === 2) {
this.chapterNum++; this.sectionNum = 0;
displayText = `${this.chapterNum} ${text}`;
} else if (level === 3) {
this.sectionNum++;
displayText = `${this.chapterNum}.${this.sectionNum} ${text}`;
}
// Generate ID for TOC
const id = `section-${this.chapterNum}-${this.sectionNum}`;
this.html += `<h${level} id="${id}">${this.escapeInline(displayText)}</h${level}>\n`;
return true;
}
return false;
}
/**
* Processes unordered and ordered lists, including nesting.
* Uses adaptive indentation to prevent numbering gaps.
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processLists(line) {
let match, type, content;
const ulMatch = line.match(CONFIG.PATTERNS.LIST_UL);
const olMatch = line.match(CONFIG.PATTERNS.LIST_OL);
if (ulMatch) { match = ulMatch; type = 'ul'; content = match[2]; }
else if (olMatch) { match = olMatch; type = 'ol'; content = match[3]; }
else { return false; }
this.closeBlockquote(); this.closeAlert(); this.closeTable();
const indent = match[1].length;
// Adaptive Indentation Logic:
// Instead of hardcoding "2 spaces = 1 level", we compare with the current stack
let targetLevel = 0;
if (this.state.listStack.length > 0) {
// Find the deepest list in the stack that has indentation <= current line
let bestMatchIndex = -1;
for (let i = this.state.listStack.length - 1; i >= 0; i--) {
const stackItem = this.state.listStack[i];
if (indent > stackItem.indent) {
// It's a child of this item -> Target is one level deeper
bestMatchIndex = i + 1;
break;
} else if (indent === stackItem.indent) {
// It's a sibling of this item -> Target is same level
bestMatchIndex = i;
break;
}
}
// If indent is smaller than everything, it resets to root (level 0)
if (bestMatchIndex === -1 && indent < this.state.listStack[0].indent) {
targetLevel = 0;
} else {
// Default to calculated index, or 0 if stack was empty/logic fell through
targetLevel = bestMatchIndex > -1 ? bestMatchIndex : 0;
}
}
// Close nested levels if we need to go back up
while (this.state.listStack.length > targetLevel + 1) {
this.closeOneListLevel();
}
// Open new level if needed (Target is deeper than current)
// Using 'while' handles cases where we might need to recover structure,
// though adaptive logic usually results in just 1 iteration max.
while (this.state.listStack.length <= targetLevel) {
if (this.state.listStack.length === targetLevel + 1 && this.state.listStack[targetLevel].type !== type) {
this.closeOneListLevel(); // Switch type (ul <-> ol)
}
if (this.state.listStack.length <= targetLevel) {
this.html += `<${type}>\n`;
// Store 'indent' in the stack to compare against future lines
this.state.listStack.push({ type: type, level: targetLevel, indent: indent });
}
}
// Handle Task List Items [x]
const taskMatch = content.match(CONFIG.PATTERNS.CHECKBOX);
if (taskMatch) {
const checked = taskMatch[1].toLowerCase() === 'x' ? 'checked' : '';
const text = taskMatch[2];
this.html += `<li class="task-list-item"><input type="checkbox" disabled ${checked}> ${this.escapeInline(text)}</li>\n`;
} else {
this.html += `<li>${this.escapeInline(content)}</li>\n`;
}
return true;
}
/**
* Processes table rows and headers.
* @param {string} line - Current line.
* @param {number} index - Current line index.
* @param {string[]} lines - All lines.
* @returns {boolean} - True if line was consumed.
*/
processTables(line, index, lines) {
if (!line.includes('|')) return false;
const match = line.match(CONFIG.PATTERNS.TABLE_ROW);
if (!match) return false;
const cells = match[1].split('|').map(c => c.trim()).filter(c => c !== '');
// Detect separator line |---|---|
const isSeparator = cells.every(c => /^[-\s:]+$/.test(c));
if (isSeparator) return true; // Consume but do nothing
this.closeList(); this.closeBlockquote(); this.closeAlert();
if (!this.state.inTable) {
this.state.inTable = true;
// Look ahead to check if next line is separator (implies current is header)
const nextLine = (index + 1 < lines.length) ? lines[index + 1] : '';
if (nextLine.includes('|') && nextLine.includes('-')) {
this.state.tableHeader = cells;
} else {
this.state.tableRows.push(cells);
}
} else {
this.state.tableRows.push(cells);
}
return true;
}
/**
* Processes blockquotes (>) and GitHub-style alerts.
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processQuotesAndAlerts(line) {
const isQuoteChar = line.startsWith('>');
if (!isQuoteChar && !this.state.inAlert && !this.state.inBlockquote) return false;
let content = '';
if (isQuoteChar) { content = line.slice(1).trim(); }
else {
// Handle multi-line content inside block
if (this.state.inAlert) content = line;
else if (this.state.inBlockquote) content = line;
else return false;
}
// Check if it's the start of an Alert
const alertMatch = content.match(CONFIG.PATTERNS.ALERT);
if (alertMatch) {
this.closeList(); this.closeAlert(); this.closeBlockquote();
this.state.inAlert = true;
this.state.alertType = alertMatch[1].toLowerCase();
return true;
}
if (this.state.inAlert) { this.state.alertBuffer.push(content); return true; }
// If not alert, assume blockquote
this.closeList(); this.closeAlert();
if (!this.state.inBlockquote) this.state.inBlockquote = true;
this.state.blockquoteBuffer.push(content);
return true;
}
/**
* Processes standalone images (figures with captions).
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processStandaloneImage(line) {
const match = line.match(CONFIG.PATTERNS.IMAGE);
if (match) {
// Check for width attributes syntax {width=50%}
const fullMatch = line.match(/^!\[([^\]]*)\]\(([^)]+)\)\s*(?:\{([^}]+)\})?$/);
if (fullMatch) {
this.closeAllBlocks();
const [_, alt, src, attrs] = fullMatch;
let style = '';
if (attrs) {
const w = attrs.match(/width\s*=\s*"?([^"}]+)"?/);
if (w) style = ` style="width: ${this.escapeHTML(w[1])};"`;
}
this.html += `<figure class="image-figure">`;
this.html += `<img src="${src}" alt="${this.escapeHTML(alt)}"${style} />`;
if (alt && alt.trim()) {
this.globalFigureNum++;
this.html += `<figcaption>Fig ${this.globalFigureNum} ${this.escapeHTML(alt)}</figcaption>`;
}
this.html += `</figure>\n`;
return true;
}
}
return false;
}
/**
* Detects standalone YouTube or Vimeo links and converts them to responsive iframes.
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processMediaEmbeds(line) {
const trimmed = line.trim();
// Check YouTube
const ytMatch = trimmed.match(CONFIG.PATTERNS.VIDEO_YOUTUBE);
if (ytMatch) {
this.closeAllBlocks();
const videoId = ytMatch[1];
// Responsive wrapper for 16:9 aspect ratio
this.html += `<div class="video-container" style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;margin-bottom:1.75rem;">
<iframe
src="https://www.youtube.com/embed/${videoId}"
style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;border-radius:4px;"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
loading="lazy">
</iframe>
</div>\n`;
return true;
}
// Check Vimeo
const vimeoMatch = trimmed.match(CONFIG.PATTERNS.VIDEO_VIMEO);
if (vimeoMatch) {
this.closeAllBlocks();
const videoId = vimeoMatch[1];
this.html += `<div class="video-container" style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;margin-bottom:1.75rem;">
<iframe
src="https://player.vimeo.com/video/${videoId}"
style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;border-radius:4px;"
allow="autoplay; fullscreen; picture-in-picture"
allowfullscreen
loading="lazy">
</iframe>
</div>\n`;
return true;
}
return false;
}
/**
* Detects lines starting with block-level HTML tags (dl, details, etc.)
* and renders them directly without wrapping in <p> tags.
* @param {string} line - Current line.
* @returns {boolean} - True if line was consumed.
*/
processBlockHtml(line) {
if (CONFIG.PATTERNS.BLOCK_HTML_START.test(line)) {
this.closeList();
this.closeTable();
this.closeBlockquote();
this.closeAlert();
// Render the line using escapeInline to ensure sanitization (XSS protection)
// but do NOT wrap it in <p>.
this.html += `${this.escapeInline(line)}\n`;
return true;
}
return false;
}
/**
* Handles empty lines to determine if blocks should be closed.
*/
processEmptyLine() {
if (this.state.inCodeBlock) this.state.codeBuffer.push('');
else if (this.state.inMathBlock) this.state.mathBuffer.push('');
else if (this.state.inAlert) this.state.alertBuffer.push('');
else if (this.state.inBlockquote) this.state.blockquoteBuffer.push('');
else {
// General close for blocks that end on double newline
this.closeList(); this.closeTable(); this.closeBlockquote(); this.closeAlert();
}
}
// --- Closers & Rendering Helper Methods ---
/** Converts buffered code lines into HTML. */
flushCodeBlock() {
if (!this.state.inCodeBlock) return;
const rawLang = this.state.codeLang.toLowerCase() || 'plaintext';
// Map short codes to PrismJS classes
const lang = rawLang === 'js' ? 'javascript' : rawLang === 'py' ? 'python' : rawLang;
const langClass = ` class="language-${lang}"`;
this.html += `<div class="code-block-container"><button class="copy-btn">Copy</button><pre><code${langClass}>`;
this.html += this.state.codeBuffer.map(l => this.escapeHTML(l)).join('\n');
this.html += `</code></pre></div>\n`;
this.state.inCodeBlock = false; this.state.codeBuffer = []; this.state.codeLang = '';
}
/** Converts buffered math lines into KaTeX HTML. */
flushMathBlock() {
if (!this.state.inMathBlock) return;
const tex = this.state.mathBuffer.join('\n');
this.html += this.renderKaTeX(tex, true);
this.state.inMathBlock = false; this.state.mathBuffer = [];
}
/** Closes one level of list nesting. */
closeOneListLevel() {
if (this.state.listStack.length === 0) return;
const item = this.state.listStack.pop();
this.html += `</${item.type}>\n`;
}
/** Closes all open lists. */
closeList() { while (this.state.listStack.length > 0) this.closeOneListLevel(); }
/** Renders the buffered table data. */
closeTable() {
if (!this.state.inTable) return;
this.html += '<table>\n';
if (this.state.tableHeader) {
this.html += '<thead>\n<tr>\n';
this.state.tableHeader.forEach(h => this.html += `<th>${this.escapeInline(h)}</th>\n`);
this.html += '</tr>\n</thead>\n';
}
if (this.state.tableRows.length > 0) {
this.html += '<tbody>\n';
this.state.tableRows.forEach(row => {
this.html += '<tr>\n';
row.forEach(cell => this.html += `<td>${this.escapeInline(cell)}</td>\n`);
this.html += '</tr>\n';
});
this.html += '</tbody>\n';
}
this.html += '</table>\n';
this.state.inTable = false; this.state.tableHeader = null; this.state.tableRows = [];
}
/** Renders buffered blockquote text. */
closeBlockquote() {
if (!this.state.inBlockquote) return;
this.html += '<blockquote>';
this.html += this.renderBufferedParagraphs(this.state.blockquoteBuffer);
this.html += '</blockquote>\n';
this.state.inBlockquote = false; this.state.blockquoteBuffer = [];
}
/** Renders buffered alert text with proper styling. */
closeAlert() {
if (!this.state.inAlert) return;
const titles = { 'note': 'Note', 'warning': 'Warning', 'important': 'Important', 'tip': 'Tip', 'caution': 'Caution' };
const title = titles[this.state.alertType] || 'Alert';
this.html += `<div class="alert alert-${this.state.alertType}">`;
this.html += `<div class="alert-header"><span class="alert-title">${title}</span></div>`;
this.html += `<div class="alert-content">`;
this.html += this.renderBufferedParagraphs(this.state.alertBuffer);
this.html += `</div></div>\n`;
this.state.inAlert = false; this.state.alertBuffer = []; this.state.alertType = '';
}
/** Helper to close everything at once (used at EOF or HR). */
closeAllBlocks() {
this.flushCodeBlock(); this.flushMathBlock(); this.closeList();
this.closeTable(); this.closeAlert(); this.closeBlockquote();
}
/**
* Renders array of text lines as HTML paragraphs.
* @param {string[]} lines - Lines of text.
* @returns {string} - HTML string.
*/
renderBufferedParagraphs(lines) {
let output = ''; let pBuffer = [];
const flushP = () => {
if (pBuffer.length > 0) {
const text = pBuffer.map(l => this.escapeInline(l)).join(' ');
output += `<p>${text}</p>`; pBuffer = [];
}
};
lines.forEach(l => { if (l === '') flushP(); else pBuffer.push(l); });
flushP();
return output;
}
/** Generates the document title header. */
renderDocumentHeader(title, meta) {
let h = `<header class="document-header">\n`;
h += `<h1>${this.escapeInline(title)}</h1>\n`;
if (meta.author) h += `<div class="author">${this.escapeHTML(meta.author)}</div>\n`;
if (meta.date) h += `<div class="date">${this.escapeHTML(meta.date)}</div>\n`;
if (meta.institution) h += `<div class="institution">${this.escapeHTML(meta.institution)}</div>\n`;
if (meta.editor) h += `<div class="editor">Edited by ${this.escapeHTML(meta.editor)}</div>\n`;
h += `</header>\n`;
return h;
}
/** Generates the footer. */
generateFooter() {
return `
<footer class="markpaper-footer">
<p id="generated-by">Generated by <a href="https://github.com/rubensbraz/MarkPaper" target="_blank">MarkPaper</a>.</p><br>
<p><b>Original project: <a href="https://github.com/TetsuakiBaba/MarkPaper" target="_blank">MarkPaper (Tetsuaki Baba)</a>.</b></p>
<p><b>Refactor (this version): <a href="https://github.com/rubensbraz/MarkPaper" target="_blank">MarkPaper (Rubens Braz)</a>.</b></p>
</footer>`;
}
/** Renders footnotes collected for the current section. */
appendSectionFootnotes() {
if (this.sectionFootnotes.length === 0) return;
this.html += '<div class="footnotes">\n';
this.sectionFootnotes.forEach(id => {
if (this.footnotesDef[id]) {
this.html += `<div class="footnote" id="footnote-${id}"><sup>${id}</sup> ${this.escapeInline(this.footnotesDef[id])}</div>\n`;
}
});
this.html += '</div>\n';
this.sectionFootnotes = [];
}
/** Wrapper for KaTeX rendering with error handling. */
renderKaTeX(tex, displayMode = false) {
if (typeof katex === 'undefined') return displayMode ? `<pre>${tex}</pre>` : `<code>${tex}</code>`;
try {
return katex.renderToString(tex, { displayMode: displayMode, throwOnError: false });
} catch (e) {
console.error('KaTeX error:', e); return `<span style="color:red">Error parsing math</span>`;
}
}
// --- Sanitization & Escaping ---
/** Escapes basic HTML characters. */
escapeHTML(text) {
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
/**
* Sanitizes HTML string using whitelist.
* Removes dangerous attributes (on*, javascript:).
*/
sanitizeHTML(text) {
return text.replace(/<(\/?)([\w-]+)([^>]*)>/gi, (match, slash, tag, attrs) => {
const tagLower = tag.toLowerCase();
// Filter tag name
if (!CONFIG.ALLOWED_TAGS.includes(tagLower)) return match.replace(/</g, '<').replace(/>/g, '>');
if (slash === '/') return `</${tag}>`;
let safeAttrs = '';
if (attrs.trim()) {
const attrMatches = attrs.match(/\s+([^=\s]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g);
if (attrMatches) {
attrMatches.forEach(attrMatch => {
const parts = attrMatch.trim().match(/^([^=\s]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?$/);
if (parts) {
const name = parts[1].toLowerCase();
const val = parts[2] || parts[3] || parts[4] || '';
// Filter attribute name
if (CONFIG.ALLOWED_ATTRIBUTES.includes(name)) {
// Filter dangerous protocols
const isJs = /^(javascript:|vbscript:|data:|about:)/i.test(val);
if ((name === 'href' || name === 'src') && isJs) return;
safeAttrs += ` ${name}="${val.replace(/"/g, '"')}"`;
}
}
});
}
}
return `<${tag}${safeAttrs}>`;
});
}
/**
* Parses inline Markdown syntax (bold, italic, links, etc.).
* Uses protection maps to prevent recursive parsing of protected blocks.
* @param {string} text - The line text.
* @returns {string} - HTML string.
*/
escapeInline(text) {
const mathMap = new Map(); let mCounter = 0;
// Protect Inline Math ($...$)
text = text.replace(/\$((?:[^\$]|\\\$)+)\$/g, (match, tex) => {
const key = `__MATH_${mCounter++}__`;
mathMap.set(key, this.renderKaTeX(tex, false));
return key;
});
// Sanitize raw HTML
let escaped = this.sanitizeHTML(text);
// Protect Valid HTML Tags
const protectionMap = new Map(); let pCounter = 0;
escaped = escaped.replace(/<(\/?)([\w-]+)([^>]*)>/g, (match, slash, tag) => {
if (CONFIG.ALLOWED_TAGS.includes(tag.toLowerCase())) {
const key = `__TAG_${pCounter++}__`;
protectionMap.set(key, match); return key;
}
return match;
});
// Escape special chars outside protected areas
escaped = escaped.replace(/&(?![a-zA-Z0-9#]+;)/g, '&').replace(/</g, '<').replace(/>/g, '>');
// Restore protections
protectionMap.forEach((val, key) => { escaped = escaped.replace(key, val); });
mathMap.forEach((val, key) => { escaped = escaped.replace(key, val); });
// Parse Markdown Syntax
escaped = escaped.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
escaped = escaped.replace(/\*(.+?)\*/g, '<em>$1</em>');
escaped = escaped.replace(/~~(.+?)~~/g, '<s>$1</s>');
escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
// Images
escaped = escaped.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
return `<img src="${src}" alt="${this.escapeHTML(alt)}">`;
});
// Links
escaped = escaped.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
// Footnote References
escaped = escaped.replace(/\[\^([^\]]+)\]/g, (match, id) => {
if (!this.sectionFootnotes.includes(id)) this.sectionFootnotes.push(id);
return `<sup><a href="#footnote-${id}" class="footnote-ref">${id}</a></sup>`;
});
// Auto Links
const urlPattern = /(https?:\/\/[^\s<>"']+|ftp:\/\/[^\s<>"']+)/g;
escaped = escaped.replace(urlPattern, (match) => { return `<a href="${match}" target="_blank" rel="noopener noreferrer">${match}</a>`; });
// Fix nested links bug
escaped = escaped.replace(/href="<a href="([^"]+)"[^>]*>[^<]+<\/a>"/g, 'href="$1"');
return escaped;
}
}
// ============================================================================
// 3. UI & DOM CONTROLLER
// ============================================================================
/**
* Manages DOM elements, Event Listeners, and interactive UI components.
*/
class MarkPaperUI {
constructor() {
this.dom = {};
this.settings = new SettingsController(this);
}
/** Initializes all UI components. */
init() {
this.createDomElements();
this.setupMenu();
this.setupToc();
this.setupScrollSpy();
this.setupCopyButtons();
this.triggerSyntaxHighlight();
this.updateDocumentTitle();
this.setupProgressBar();
this.setupAnchors();
this.setupScrollHistory();
this.settings.init();
}
/** Triggers PrismJS highlighting if available. */
triggerSyntaxHighlight() {
if (typeof Prism !== 'undefined') {
Prism.highlightAll();
} else {
setTimeout(() => { if (typeof Prism !== 'undefined') Prism.highlightAll(); }, 500);
}
}
/** Sets the document <title> based on the H1. */
updateDocumentTitle() {
const h1 = document.querySelector('h1');
if (h1) {
document.title = h1.innerText + ' - MarkPaper';
}
}
/** Restores scroll position on page load. */
setupScrollHistory() {
const savedPos = localStorage.getItem('markpaper_scrollpos');
const currentFile = window.location.search || 'default';
if (savedPos) {
try {
const data = JSON.parse(savedPos);
if (data.file === currentFile) {
setTimeout(() => window.scrollTo(0, data.y), 100);
}
} catch (e) { console.error('Error reading scroll history', e); }
}
// Save scroll position
window.addEventListener('scroll', () => {
const state = { file: currentFile, y: window.scrollY };
localStorage.setItem('markpaper_scrollpos', JSON.stringify(state));
}, { passive: true });
}
/** Updates the top progress bar as the user scrolls. */
setupProgressBar() {
const bar = document.getElementById('reading-progress');
if (!bar) return;
window.addEventListener('scroll', () => {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = (scrollTop / scrollHeight) * 100;
bar.style.width = scrolled + "%";
}, { passive: true });
}
/** Adds clickable anchor links (#) next to headings. */
setupAnchors() {
const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
headings.forEach(h => {
if (!h.id) return;
const anchor = document.createElement('a');
anchor.className = 'heading-anchor';
anchor.href = `#${h.id}`;
anchor.innerHTML = '#';
anchor.title = 'Copy link to this section';
anchor.setAttribute('aria-hidden', 'true');
anchor.onclick = (e) => {
e.preventDefault();
const url = window.location.origin + window.location.pathname + window.location.search + '#' + h.id;
navigator.clipboard.writeText(url).then(() => {
anchor.style.color = 'var(--accent-hover-color)';
setTimeout(() => anchor.style.color = '', 500);
});
history.pushState(null, null, `#${h.id}`);
h.scrollIntoView({ behavior: 'smooth' });
};
h.appendChild(anchor);