-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
877 lines (742 loc) · 27.7 KB
/
script.js
File metadata and controls
877 lines (742 loc) · 27.7 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
document.addEventListener("DOMContentLoaded", function () {
let markdownRenderTimeout = null;
const RENDER_DELAY = 100;
let syncScrollingEnabled = true;
let isEditorScrolling = false;
let isPreviewScrolling = false;
let scrollSyncTimeout = null;
const SCROLL_SYNC_DELAY = 10;
const markdownEditor = document.getElementById("markdown-editor");
const markdownPreview = document.getElementById("markdown-preview");
const themeToggle = document.getElementById("theme-toggle");
const importButton = document.getElementById("import-button");
const fileInput = document.getElementById("file-input");
const exportMd = document.getElementById("export-md");
const exportHtml = document.getElementById("export-html");
const exportPdf = document.getElementById("export-pdf");
const copyMarkdownButton = document.getElementById("copy-markdown-button");
const dropzone = document.getElementById("dropzone");
const closeDropzoneBtn = document.getElementById("close-dropzone");
const toggleSyncButton = document.getElementById("toggle-sync");
const editorPane = document.getElementById("markdown-editor");
const previewPane = document.querySelector(".preview-pane");
const readingTimeElement = document.getElementById("reading-time");
const wordCountElement = document.getElementById("word-count");
const charCountElement = document.getElementById("char-count");
const mobileMenuToggle = document.getElementById("mobile-menu-toggle");
const mobileMenuPanel = document.getElementById("mobile-menu-panel");
const mobileMenuOverlay = document.getElementById("mobile-menu-overlay");
const mobileCloseMenu = document.getElementById("close-mobile-menu");
const mobileReadingTime = document.getElementById("mobile-reading-time");
const mobileWordCount = document.getElementById("mobile-word-count");
const mobileCharCount = document.getElementById("mobile-char-count");
const mobileToggleSync = document.getElementById("mobile-toggle-sync");
const mobileImportBtn = document.getElementById("mobile-import-button");
const mobileExportMd = document.getElementById("mobile-export-md");
const mobileExportHtml = document.getElementById("mobile-export-html");
const mobileExportPdf = document.getElementById("mobile-export-pdf");
const mobileCopyMarkdown = document.getElementById("mobile-copy-markdown");
const mobileThemeToggle = document.getElementById("mobile-theme-toggle");
// Check dark mode preference first for proper initialization
const prefersDarkMode =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.setAttribute(
"data-theme",
prefersDarkMode ? "dark" : "light"
);
themeToggle.innerHTML = prefersDarkMode
? '<i class="bi bi-sun"></i>'
: '<i class="bi bi-moon"></i>';
const initMermaid = () => {
const currentTheme = document.documentElement.getAttribute("data-theme");
const mermaidTheme = currentTheme === "dark" ? "dark" : "default";
mermaid.initialize({
startOnLoad: false,
theme: mermaidTheme,
securityLevel: 'loose',
flowchart: { useMaxWidth: true, htmlLabels: true },
fontSize: 16
});
};
initMermaid();
const markedOptions = {
gfm: true,
breaks: false,
pedantic: false,
sanitize: false,
smartypants: false,
xhtml: false,
headerIds: true,
mangle: false,
};
const renderer = new marked.Renderer();
renderer.code = function (code, language) {
if (language === 'mermaid') {
const uniqueId = 'mermaid-diagram-' + Math.random().toString(36).substr(2, 9);
return `<div class="mermaid-container"><div class="mermaid" id="${uniqueId}">${code}</div></div>`;
}
const validLanguage = hljs.getLanguage(language) ? language : "plaintext";
const highlightedCode = hljs.highlight(code, {
language: validLanguage,
}).value;
return `<pre><code class="hljs ${validLanguage}">${highlightedCode}</code></pre>`;
};
marked.setOptions({
...markedOptions,
renderer: renderer,
highlight: function (code, language) {
if (language === 'mermaid') return code;
const validLanguage = hljs.getLanguage(language) ? language : "plaintext";
return hljs.highlight(code, { language: validLanguage }).value;
},
});
const sampleMarkdown = `# Welcome to Markdown Viewer
## ✨ Key Features
- **Live Preview** with GitHub styling
- **Smart Import/Export** (MD, HTML, PDF)
- **Mermaid Diagrams** for visual documentation
- **LaTeX Math Support** for scientific notation
- **Emoji Support** 😄 👍 🎉
## 💻 Code with Syntax Highlighting
\`\`\`javascript
function renderMarkdown() {
const markdown = markdownEditor.value;
const html = marked.parse(markdown);
const sanitizedHtml = DOMPurify.sanitize(html);
markdownPreview.innerHTML = sanitizedHtml;
// Apply syntax highlighting to code blocks
markdownPreview.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
}
\`\`\`
## 🧮 Mathematical Expressions
Write complex formulas with LaTeX syntax:
Inline equation: $$E = mc^2$$
Display equations:
$$\\frac{\\partial f}{\\partial x} = \\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}$$
$$\\sum_{i=1}^{n} i^2 = \\frac{n(n+1)(2n+1)}{6}$$
## 📊 Mermaid Diagrams
Create powerful visualizations directly in markdown:
\`\`\`mermaid
flowchart LR
A[Start] --> B{Is it working?}
B -->|Yes| C[Great!]
B -->|No| D[Debug]
C --> E[Deploy]
D --> B
\`\`\`
### Sequence Diagram Example
\`\`\`mermaid
sequenceDiagram
User->>Editor: Type markdown
Editor->>Preview: Render content
User->>Editor: Make changes
Editor->>Preview: Update rendering
User->>Export: Save as PDF
\`\`\`
## 📋 Task Management
- [x] Create responsive layout
- [x] Implement live preview with GitHub styling
- [x] Add syntax highlighting for code blocks
- [x] Support math expressions with LaTeX
- [x] Enable mermaid diagrams
## 🆚 Feature Comparison
| Feature | Markdown Viewer (Ours) | Other Markdown Editors |
|:-------------------------|:----------------------:|:-----------------------:|
| Live Preview | ✅ GitHub-Styled | ✅ |
| Sync Scrolling | ✅ Two-way | 🔄 Partial/None |
| Mermaid Support | ✅ | ❌/Limited |
| LaTeX Math Rendering | ✅ | ❌/Limited |
### 📝 Multi-row Headers Support
<table>
<thead>
<tr>
<th rowspan="2">Document Type</th>
<th colspan="2">Support</th>
</tr>
<tr>
<th>Markdown Viewer (Ours)</th>
<th>Other Markdown Editors</th>
</tr>
</thead>
<tbody>
<tr>
<td>Technical Docs</td>
<td>Full + Diagrams</td>
<td>Limited/Basic</td>
</tr>
<tr>
<td>Research Notes</td>
<td>Full + Math</td>
<td>Partial</td>
</tr>
<tr>
<td>Developer Guides</td>
<td>Full + Export Options</td>
<td>Basic</td>
</tr>
</tbody>
</table>
## 📝 Text Formatting Examples
### Text Formatting
Text can be formatted in various ways for ~~strikethrough~~, **bold**, *italic*, or ***bold italic***.
For highlighting important information, use <mark>highlighted text</mark> or add <u>underlines</u> where appropriate.
### Superscript and Subscript
Chemical formulas: H<sub>2</sub>O, CO<sub>2</sub>
Mathematical notation: x<sup>2</sup>, e<sup>iπ</sup>
### Keyboard Keys
Press <kbd>Ctrl</kbd> + <kbd>B</kbd> for bold text.
### Abbreviations
<abbr title="Graphical User Interface">GUI</abbr>
<abbr title="Application Programming Interface">API</abbr>
### Text Alignment
<div style="text-align: center">
Centered text for headings or important notices
</div>
<div style="text-align: right">
Right-aligned text (for dates, signatures, etc.)
</div>
### **Lists**
Create bullet points:
* Item 1
* Item 2
* Nested item
* Nested further
### **Links and Images**
Add a [link](https://github.com/ThisIs-Developer/Markdown-Viewer) to important resources.
Embed an image:

### **Blockquotes**
Quote someone famous:
> "The best way to predict the future is to invent it." - Alan Kay
---
## 🛡️ Security Note
This is a fully client-side application. Your content never leaves your browser and stays secure on your device.`;
markdownEditor.value = sampleMarkdown;
function renderMarkdown() {
try {
const markdown = markdownEditor.value;
const html = marked.parse(markdown);
const sanitizedHtml = DOMPurify.sanitize(html, {
ADD_TAGS: ['mjx-container'],
ADD_ATTR: ['id', 'class', 'style']
});
markdownPreview.innerHTML = sanitizedHtml;
markdownPreview.querySelectorAll("pre code").forEach((block) => {
try {
if (!block.classList.contains('mermaid')) {
hljs.highlightElement(block);
}
} catch (e) {
console.warn("Syntax highlighting failed for a code block:", e);
}
});
processEmojis(markdownPreview);
// Reinitialize mermaid with current theme before rendering diagrams
initMermaid();
try {
mermaid.init(undefined, markdownPreview.querySelectorAll('.mermaid'));
} catch (e) {
console.warn("Mermaid rendering failed:", e);
}
if (window.MathJax) {
try {
MathJax.typesetPromise([markdownPreview]).catch((err) => {
console.warn('MathJax typesetting failed:', err);
});
} catch (e) {
console.warn("MathJax rendering failed:", e);
}
}
updateDocumentStats();
} catch (e) {
console.error("Markdown rendering failed:", e);
markdownPreview.innerHTML = `<div class="alert alert-danger">
<strong>Error rendering markdown:</strong> ${e.message}
</div>
<pre>${markdownEditor.value}</pre>`;
}
}
function importMarkdownFile(file) {
const reader = new FileReader();
reader.onload = function(e) {
markdownEditor.value = e.target.result;
renderMarkdown();
dropzone.style.display = "none";
};
reader.readAsText(file);
}
function processEmojis(element) {
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
null,
false
);
const textNodes = [];
let node;
while ((node = walker.nextNode())) {
let parent = node.parentNode;
let isInCode = false;
while (parent && parent !== element) {
if (parent.tagName === 'PRE' || parent.tagName === 'CODE') {
isInCode = true;
break;
}
parent = parent.parentNode;
}
if (!isInCode && node.nodeValue.includes(':')) {
textNodes.push(node);
}
}
textNodes.forEach(textNode => {
const text = textNode.nodeValue;
const emojiRegex = /:([\w+-]+):/g;
let match;
let lastIndex = 0;
let result = '';
let hasEmoji = false;
while ((match = emojiRegex.exec(text)) !== null) {
const shortcode = match[1];
const emoji = joypixels.shortnameToUnicode(`:${shortcode}:`);
if (emoji !== `:${shortcode}:`) { // If conversion was successful
hasEmoji = true;
result += text.substring(lastIndex, match.index) + emoji;
lastIndex = emojiRegex.lastIndex;
} else {
result += text.substring(lastIndex, emojiRegex.lastIndex);
lastIndex = emojiRegex.lastIndex;
}
}
if (hasEmoji) {
result += text.substring(lastIndex);
const span = document.createElement('span');
span.innerHTML = result;
textNode.parentNode.replaceChild(span, textNode);
}
});
}
function debouncedRender() {
clearTimeout(markdownRenderTimeout);
markdownRenderTimeout = setTimeout(renderMarkdown, RENDER_DELAY);
}
function updateDocumentStats() {
const text = markdownEditor.value;
const charCount = text.length;
charCountElement.textContent = charCount.toLocaleString();
const wordCount = text.trim() === "" ? 0 : text.trim().split(/\s+/).length;
wordCountElement.textContent = wordCount.toLocaleString();
const readingTimeMinutes = Math.ceil(wordCount / 200);
readingTimeElement.textContent = readingTimeMinutes;
}
function syncEditorToPreview() {
if (!syncScrollingEnabled || isPreviewScrolling) return;
isEditorScrolling = true;
clearTimeout(scrollSyncTimeout);
scrollSyncTimeout = setTimeout(() => {
const editorScrollRatio =
editorPane.scrollTop /
(editorPane.scrollHeight - editorPane.clientHeight);
const previewScrollPosition =
(previewPane.scrollHeight - previewPane.clientHeight) *
editorScrollRatio;
if (!isNaN(previewScrollPosition) && isFinite(previewScrollPosition)) {
previewPane.scrollTop = previewScrollPosition;
}
setTimeout(() => {
isEditorScrolling = false;
}, 50);
}, SCROLL_SYNC_DELAY);
}
function syncPreviewToEditor() {
if (!syncScrollingEnabled || isEditorScrolling) return;
isPreviewScrolling = true;
clearTimeout(scrollSyncTimeout);
scrollSyncTimeout = setTimeout(() => {
const previewScrollRatio =
previewPane.scrollTop /
(previewPane.scrollHeight - previewPane.clientHeight);
const editorScrollPosition =
(editorPane.scrollHeight - editorPane.clientHeight) *
previewScrollRatio;
if (!isNaN(editorScrollPosition) && isFinite(editorScrollPosition)) {
editorPane.scrollTop = editorScrollPosition;
}
setTimeout(() => {
isPreviewScrolling = false;
}, 50);
}, SCROLL_SYNC_DELAY);
}
function toggleSyncScrolling() {
syncScrollingEnabled = !syncScrollingEnabled;
if (syncScrollingEnabled) {
toggleSyncButton.innerHTML = '<i class="bi bi-link-45deg"></i> Sync Off';
toggleSyncButton.classList.add("sync-disabled");
toggleSyncButton.classList.remove("sync-enabled");
toggleSyncButton.classList.add("border-primary");
} else {
toggleSyncButton.innerHTML = '<i class="bi bi-link"></i> Sync On';
toggleSyncButton.classList.add("sync-enabled");
toggleSyncButton.classList.remove("sync-disabled");
toggleSyncButton.classList.remove("border-primary");
}
}
function openMobileMenu() {
mobileMenuPanel.classList.add("active");
mobileMenuOverlay.classList.add("active");
}
function closeMobileMenu() {
mobileMenuPanel.classList.remove("active");
mobileMenuOverlay.classList.remove("active");
}
mobileMenuToggle.addEventListener("click", openMobileMenu);
mobileCloseMenu.addEventListener("click", closeMobileMenu);
mobileMenuOverlay.addEventListener("click", closeMobileMenu);
function updateMobileStats() {
mobileCharCount.textContent = charCountElement.textContent;
mobileWordCount.textContent = wordCountElement.textContent;
mobileReadingTime.textContent = readingTimeElement.textContent;
}
const origUpdateStats = updateDocumentStats;
updateDocumentStats = function() {
origUpdateStats();
updateMobileStats();
};
mobileToggleSync.addEventListener("click", () => {
toggleSyncScrolling();
if (syncScrollingEnabled) {
mobileToggleSync.innerHTML = '<i class="bi bi-link-45deg me-2"></i> Sync Off';
mobileToggleSync.classList.add("sync-disabled");
mobileToggleSync.classList.remove("sync-enabled");
mobileToggleSync.classList.add("border-primary");
} else {
mobileToggleSync.innerHTML = '<i class="bi bi-link me-2"></i> Sync On';
mobileToggleSync.classList.add("sync-enabled");
mobileToggleSync.classList.remove("sync-disabled");
mobileToggleSync.classList.remove("border-primary");
}
});
mobileImportBtn.addEventListener("click", () => fileInput.click());
mobileExportMd.addEventListener("click", () => exportMd.click());
mobileExportHtml.addEventListener("click", () => exportHtml.click());
mobileExportPdf.addEventListener("click", () => exportPdf.click());
mobileCopyMarkdown.addEventListener("click", () => copyMarkdownButton.click());
mobileThemeToggle.addEventListener("click", () => {
themeToggle.click();
mobileThemeToggle.innerHTML = themeToggle.innerHTML + " Toggle Dark Mode";
});
renderMarkdown();
updateMobileStats();
markdownEditor.addEventListener("input", debouncedRender);
editorPane.addEventListener("scroll", syncEditorToPreview);
previewPane.addEventListener("scroll", syncPreviewToEditor);
toggleSyncButton.addEventListener("click", toggleSyncScrolling);
themeToggle.addEventListener("click", function () {
const theme =
document.documentElement.getAttribute("data-theme") === "dark"
? "light"
: "dark";
document.documentElement.setAttribute("data-theme", theme);
if (theme === "dark") {
themeToggle.innerHTML = '<i class="bi bi-sun"></i>';
} else {
themeToggle.innerHTML = '<i class="bi bi-moon"></i>';
}
renderMarkdown();
});
importButton.addEventListener("click", function () {
fileInput.click();
});
fileInput.addEventListener("change", function (e) {
const file = e.target.files[0];
if (file) {
importMarkdownFile(file);
}
this.value = "";
});
exportMd.addEventListener("click", function () {
try {
const blob = new Blob([markdownEditor.value], {
type: "text/markdown;charset=utf-8",
});
saveAs(blob, "document.md");
} catch (e) {
console.error("Export failed:", e);
alert("Export failed: " + e.message);
}
});
exportHtml.addEventListener("click", function () {
try {
const markdown = markdownEditor.value;
const html = marked.parse(markdown);
const sanitizedHtml = DOMPurify.sanitize(html, {
ADD_TAGS: ['mjx-container'],
ADD_ATTR: ['id', 'class', 'style']
});
const isDarkTheme =
document.documentElement.getAttribute("data-theme") === "dark";
const cssTheme = isDarkTheme
? "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.3.0/github-markdown-dark.min.css"
: "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.3.0/github-markdown.min.css";
const fullHtml = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Export</title>
<link rel="stylesheet" href="${cssTheme}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/${
isDarkTheme ? "github-dark" : "github"
}.min.css">
<style>
body {
background-color: ${isDarkTheme ? "#0d1117" : "#ffffff"};
color: ${isDarkTheme ? "#c9d1d9" : "#24292e"};
}
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
background-color: ${isDarkTheme ? "#0d1117" : "#ffffff"};
color: ${isDarkTheme ? "#c9d1d9" : "#24292e"};
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
</style>
</head>
<body>
<article class="markdown-body">
${sanitizedHtml}
</article>
</body>
</html>`;
const blob = new Blob([fullHtml], { type: "text/html;charset=utf-8" });
saveAs(blob, "document.html");
} catch (e) {
console.error("HTML export failed:", e);
alert("HTML export failed: " + e.message);
}
});
exportPdf.addEventListener("click", async function () {
try {
const originalText = exportPdf.innerHTML;
exportPdf.innerHTML = '<i class="bi bi-hourglass-split"></i> Generating...';
exportPdf.disabled = true;
const progressContainer = document.createElement('div');
progressContainer.style.position = 'fixed';
progressContainer.style.top = '50%';
progressContainer.style.left = '50%';
progressContainer.style.transform = 'translate(-50%, -50%)';
progressContainer.style.padding = '15px 20px';
progressContainer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
progressContainer.style.color = 'white';
progressContainer.style.borderRadius = '5px';
progressContainer.style.zIndex = '9999';
progressContainer.style.textAlign = 'center';
const statusText = document.createElement('div');
statusText.textContent = 'Generating PDF...';
progressContainer.appendChild(statusText);
document.body.appendChild(progressContainer);
const markdown = markdownEditor.value;
const html = marked.parse(markdown);
const sanitizedHtml = DOMPurify.sanitize(html, {
ADD_TAGS: ['mjx-container', 'svg', 'path', 'g', 'marker', 'defs', 'pattern', 'clipPath'],
ADD_ATTR: ['id', 'class', 'style', 'viewBox', 'd', 'fill', 'stroke', 'transform', 'marker-end', 'marker-start']
});
const tempElement = document.createElement("div");
tempElement.className = "markdown-body pdf-export";
tempElement.innerHTML = sanitizedHtml;
tempElement.style.padding = "20px";
tempElement.style.width = "210mm";
tempElement.style.margin = "0 auto";
tempElement.style.fontSize = "14px";
tempElement.style.position = "fixed";
tempElement.style.left = "-9999px";
tempElement.style.top = "0";
const currentTheme = document.documentElement.getAttribute("data-theme");
tempElement.style.backgroundColor = currentTheme === "dark" ? "#0d1117" : "#ffffff";
tempElement.style.color = currentTheme === "dark" ? "#c9d1d9" : "#24292e";
document.body.appendChild(tempElement);
await new Promise(resolve => setTimeout(resolve, 200));
try {
await mermaid.run({
nodes: tempElement.querySelectorAll('.mermaid'),
suppressErrors: true
});
} catch (mermaidError) {
console.warn("Mermaid rendering issue:", mermaidError);
}
if (window.MathJax) {
try {
await MathJax.typesetPromise([tempElement]);
} catch (mathJaxError) {
console.warn("MathJax rendering issue:", mathJaxError);
}
}
await new Promise(resolve => setTimeout(resolve, 500));
const pdfOptions = {
orientation: 'portrait',
unit: 'mm',
format: 'a4',
compress: true,
hotfixes: ["px_scaling"]
};
const pdf = new jspdf.jsPDF(pdfOptions);
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const margin = 15;
const contentWidth = pageWidth - (margin * 2);
const canvas = await html2canvas(tempElement, {
scale: 2,
useCORS: true,
allowTaint: true,
logging: false,
windowWidth: 1000,
windowHeight: tempElement.scrollHeight
});
const scaleFactor = canvas.width / contentWidth;
const imgHeight = canvas.height / scaleFactor;
const pagesCount = Math.ceil(imgHeight / (pageHeight - margin * 2));
for (let page = 0; page < pagesCount; page++) {
if (page > 0) pdf.addPage();
const sourceY = page * (pageHeight - margin * 2) * scaleFactor;
const sourceHeight = Math.min(canvas.height - sourceY, (pageHeight - margin * 2) * scaleFactor);
const destHeight = sourceHeight / scaleFactor;
const pageCanvas = document.createElement('canvas');
pageCanvas.width = canvas.width;
pageCanvas.height = sourceHeight;
const ctx = pageCanvas.getContext('2d');
ctx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight);
const imgData = pageCanvas.toDataURL('image/png');
pdf.addImage(imgData, 'PNG', margin, margin, contentWidth, destHeight);
}
pdf.save("document.pdf");
statusText.textContent = 'Download successful!';
setTimeout(() => {
document.body.removeChild(progressContainer);
}, 1500);
document.body.removeChild(tempElement);
exportPdf.innerHTML = originalText;
exportPdf.disabled = false;
} catch (error) {
console.error("PDF export failed:", error);
alert("PDF export failed: " + error.message);
exportPdf.innerHTML = '<i class="bi bi-file-earmark-pdf"></i> Export';
exportPdf.disabled = false;
const progressContainer = document.querySelector('div[style*="Preparing PDF"]');
if (progressContainer) {
document.body.removeChild(progressContainer);
}
}
});
copyMarkdownButton.addEventListener("click", function () {
try {
const markdownText = markdownEditor.value;
copyToClipboard(markdownText);
} catch (e) {
console.error("Copy failed:", e);
alert("Failed to copy Markdown: " + e.message);
}
});
async function copyToClipboard(text) {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
showCopiedMessage();
} else {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand("copy");
document.body.removeChild(textArea);
if (successful) {
showCopiedMessage();
} else {
throw new Error("Copy command was unsuccessful");
}
}
} catch (err) {
console.error("Copy failed:", err);
alert("Failed to copy HTML: " + err.message);
}
}
function showCopiedMessage() {
const originalText = copyMarkdownButton.innerHTML;
copyMarkdownButton.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
setTimeout(() => {
copyMarkdownButton.innerHTML = originalText;
}, 2000);
}
const dropEvents = ["dragenter", "dragover", "dragleave", "drop"];
dropEvents.forEach((eventName) => {
dropzone.addEventListener(eventName, preventDefaults, false);
document.body.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
["dragenter", "dragover"].forEach((eventName) => {
dropzone.addEventListener(eventName, highlight, false);
});
["dragleave", "drop"].forEach((eventName) => {
dropzone.addEventListener(eventName, unhighlight, false);
});
function highlight() {
dropzone.classList.add("active");
}
function unhighlight() {
dropzone.classList.remove("active");
}
dropzone.addEventListener("drop", handleDrop, false);
dropzone.addEventListener("click", function (e) {
if (e.target !== closeDropzoneBtn && !closeDropzoneBtn.contains(e.target)) {
fileInput.click();
}
});
closeDropzoneBtn.addEventListener("click", function(e) {
e.stopPropagation();
dropzone.style.display = "none";
});
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
if (files.length) {
const file = files[0];
const isMarkdownFile =
file.type === "text/markdown" ||
file.name.endsWith(".md") ||
file.name.endsWith(".markdown");
if (isMarkdownFile) {
importMarkdownFile(file);
} else {
alert("Please upload a Markdown file (.md or .markdown)");
}
}
}
document.addEventListener("keydown", function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
exportMd.click();
}
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
e.preventDefault();
copyMarkdownButton.click();
}
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "S") {
e.preventDefault();
toggleSyncScrolling();
}
});
});