-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2009 lines (1682 loc) · 59.1 KB
/
script.js
File metadata and controls
2009 lines (1682 loc) · 59.1 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
// 配置marked选项
const renderer = new marked.Renderer();
// 自定义代码块渲染
renderer.code = function(code, language) {
const lang = language || 'text';
let highlightedCode;
if (language && hljs.getLanguage(language)) {
try {
highlightedCode = hljs.highlight(code, { language: language }).value;
} catch (err) {
highlightedCode = hljs.highlightAuto(code).value;
}
} else {
highlightedCode = hljs.highlightAuto(code).value;
}
return `
<div class="code-block-container">
<div class="code-block-header">
<span class="code-language">${lang}</span>
<button class="code-copy-btn" onclick="copyCodeToClipboard(this)" title="复制代码">
<i data-lucide="copy"></i>
复制
</button>
</div>
<pre><code class="language-${lang}">${highlightedCode}</code></pre>
</div>
`;
};
marked.setOptions({
renderer: renderer,
breaks: true,
gfm: true
});
const input = document.getElementById('markdown-input');
const preview = document.getElementById('preview');
function updatePreview() {
let markdownText = input.value;
// 预处理:处理跨行的$$公式块
markdownText = preprocessMath(markdownText);
const htmlContent = marked.parse(markdownText);
preview.innerHTML = htmlContent;
// 渲染LaTeX数学公式
renderMathInElement(preview, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\[', right: '\\]', display: true},
{left: '\\(', right: '\\)', display: false}
],
throwOnError: false,
errorColor: '#cc0000',
strict: false,
trust: false,
ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
macros: {
"\\RR": "\\mathbb{R}",
"\\NN": "\\mathbb{N}",
"\\ZZ": "\\mathbb{Z}",
"\\QQ": "\\mathbb{Q}",
"\\CC": "\\mathbb{C}"
}
});
// 设置所有链接在新标签页打开
const links = preview.querySelectorAll('a[href]');
links.forEach(link => {
// 只处理外部链接,内部锚点链接保持原样
if (link.getAttribute('href').startsWith('http') ||
link.getAttribute('href').startsWith('//') ||
link.getAttribute('href').startsWith('www.')) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
});
// 重新初始化新添加的图标
lucide.createIcons();
// 更新滚动映射
updateScrollMapping();
}
// 预处理数学公式,处理跨行的$$块
function preprocessMath(text) {
// 分行处理,避免跨段落匹配
const lines = text.split('\n');
const result = [];
let inMathBlock = false;
let mathContent = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const trimmedLine = line.trim();
if (!inMathBlock && trimmedLine === '$$') {
// 开始数学块
inMathBlock = true;
mathContent = [];
} else if (inMathBlock && trimmedLine === '$$') {
// 结束数学块
inMathBlock = false;
const formula = mathContent.join(' ').trim();
result.push('$$' + formula + '$$');
mathContent = [];
} else if (inMathBlock) {
// 在数学块内部
mathContent.push(trimmedLine);
} else {
// 普通行
result.push(line);
}
}
// 如果还有未闭合的数学块,按原样处理
if (inMathBlock) {
result.push('$$');
result.push(...mathContent);
}
return result.join('\n');
}
// 复制代码到剪贴板
function copyCodeToClipboard(button) {
const codeBlock = button.closest('.code-block-container').querySelector('pre code');
const codeText = codeBlock.textContent;
const originalText = button.innerHTML;
const showSuccess = () => {
button.innerHTML = '<i data-lucide="check"></i>已复制';
lucide.createIcons();
setTimeout(() => {
button.innerHTML = originalText;
lucide.createIcons();
}, 2000);
};
navigator.clipboard.writeText(codeText).then(showSuccess).catch(err => {
console.error('复制失败:', err);
// 降级方案
const textArea = document.createElement('textarea');
textArea.value = codeText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
showSuccess();
});
}
// 初始化预览
updatePreview();
// 初始化图标
lucide.createIcons();
// 监听输入变化
input.addEventListener('input', function() {
updatePreview();
updateWordCount();
saveContent();
});
// 字数统计功能
function updateWordCount() {
const content = input.value;
const charCount = content.length;
const wordCountElement = document.getElementById('wordCount');
if (wordCountElement) {
wordCountElement.textContent = `${charCount} 字符`;
}
}
// 全屏功能
function toggleFullscreen() {
const container = document.querySelector('.container');
const fullscreenBtn = document.getElementById('fullscreenBtn');
if (!document.fullscreenElement) {
container.requestFullscreen().then(() => {
fullscreenBtn.innerHTML = '<i data-lucide="minimize"></i>';
lucide.createIcons();
}).catch(err => {
console.error('无法进入全屏模式:', err);
});
} else {
document.exitFullscreen().then(() => {
fullscreenBtn.innerHTML = '<i data-lucide="maximize"></i>';
lucide.createIcons();
});
}
}
// 监听全屏状态变化
document.addEventListener('fullscreenchange', function() {
const fullscreenBtn = document.getElementById('fullscreenBtn');
if (!document.fullscreenElement) {
fullscreenBtn.innerHTML = '<i data-lucide="maximize"></i>';
lucide.createIcons();
}
});
// 快捷键支持
document.addEventListener('keydown', function(e) {
// 全屏 F11
if (e.key === 'F11') {
e.preventDefault();
toggleFullscreen();
}
// ESC键关闭弹窗
if (e.key === 'Escape') {
hideConfirmModal();
hideInstallModal();
}
});
// 主题切换功能
function toggleTheme() {
const body = document.body;
const container = document.querySelector('.container');
const toolbar = document.getElementById('toolbar');
const editorPanel = document.getElementById('editorPanel');
const previewPanel = document.getElementById('previewPanel');
const editorHeader = document.getElementById('editorHeader');
const previewHeader = document.getElementById('previewHeader');
const markdownInput = document.getElementById('markdown-input');
const preview = document.getElementById('preview');
const themeToggle = document.getElementById('themeToggle');
const isDark = body.classList.contains('dark');
if (isDark) {
// 切换到浅色模式
body.classList.remove('dark');
container.classList.remove('dark');
toolbar.classList.remove('dark');
editorPanel.classList.remove('dark');
previewPanel.classList.remove('dark');
editorHeader.classList.remove('dark');
previewHeader.classList.remove('dark');
markdownInput.classList.remove('dark');
preview.classList.remove('dark');
themeToggle.innerHTML = '<i data-lucide="sun"></i>';
} else {
// 切换到暗黑模式
body.classList.add('dark');
container.classList.add('dark');
toolbar.classList.add('dark');
editorPanel.classList.add('dark');
previewPanel.classList.add('dark');
editorHeader.classList.add('dark');
previewHeader.classList.add('dark');
markdownInput.classList.add('dark');
preview.classList.add('dark');
themeToggle.innerHTML = '<i data-lucide="moon"></i>';
}
// 重新初始化图标
lucide.createIcons();
// 保存主题设置
localStorage.setItem('theme', isDark ? 'light' : 'dark');
}
// 加载保存的主题设置
function loadTheme() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
toggleTheme();
}
}
// 页面加载时应用保存的主题
loadTheme();
// PWA功能
let deferredPrompt;
let isInstalled = false;
// 检测PWA安装状态
function checkPWAInstallStatus() {
// 检查是否在独立模式下运行(已安装)
if (window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true) {
isInstalled = true;
document.getElementById('installBtn').style.display = 'none';
}
}
// 监听PWA安装提示事件
window.addEventListener('beforeinstallprompt', (e) => {
console.log('PWA: Install prompt available');
e.preventDefault();
deferredPrompt = e;
// 显示安装按钮
const installBtn = document.getElementById('installBtn');
if (installBtn && !isInstalled) {
installBtn.style.display = 'flex';
}
// 首次访问时显示安装提示(可选)
const hasShownInstallPrompt = localStorage.getItem('hasShownInstallPrompt');
if (!hasShownInstallPrompt && !isInstalled) {
setTimeout(() => {
showInstallModal();
localStorage.setItem('hasShownInstallPrompt', 'true');
}, 5000); // 5秒后显示
}
});
// 监听PWA安装完成事件
window.addEventListener('appinstalled', () => {
console.log('PWA: App installed successfully');
isInstalled = true;
deferredPrompt = null;
// 隐藏安装按钮
document.getElementById('installBtn').style.display = 'none';
hideInstallModal();
// 显示安装成功提示
showInstallSuccessToast();
});
// 显示安装提示
function showInstallPrompt() {
// 记录用户尝试安装PWA的意图
localStorage.setItem('pwa-install-attempted', 'true');
if (deferredPrompt && !isInstalled) {
showInstallModal();
} else if (isInstalled) {
alert('应用已经安装!');
} else {
alert('您的浏览器不支持应用安装功能');
}
}
// 显示安装弹窗
function showInstallModal() {
const modal = document.getElementById('installModal');
const modalElement = document.getElementById('installModalContent');
// 应用当前主题
if (document.body.classList.contains('dark')) {
modalElement.classList.add('dark');
} else {
modalElement.classList.remove('dark');
}
modal.classList.add('show');
setTimeout(() => {
lucide.createIcons();
}, 100);
}
// 隐藏安装弹窗
function hideInstallModal() {
const modal = document.getElementById('installModal');
modal.classList.remove('show');
// 记录用户关闭了安装弹窗(可能表示不感兴趣)
localStorage.setItem('pwa-install-dismissed', 'true');
}
// 执行PWA安装
async function installPWA() {
if (!deferredPrompt) {
alert('安装功能暂时不可用');
return;
}
try {
// 显示安装提示
deferredPrompt.prompt();
// 等待用户响应
const { outcome } = await deferredPrompt.userChoice;
if (outcome === 'accepted') {
console.log('PWA: User accepted the install prompt');
} else {
console.log('PWA: User dismissed the install prompt');
}
deferredPrompt = null;
hideInstallModal();
} catch (error) {
console.error('PWA: Install failed:', error);
alert('安装失败,请重试');
}
}
// 通用Toast创建函数
function createToast(message, bgColor = '#4CAF50', position = 'top') {
const toast = document.createElement('div');
const positionStyle = position === 'top' ? 'top: 20px; right: 20px;' : 'bottom: 20px; left: 50%; transform: translateX(-50%);';
toast.style.cssText = `
position: fixed;
${positionStyle}
background: ${bgColor};
color: white;
padding: 16px 24px;
border-radius: 8px;
z-index: 10000;
font-family: "LXGW WenKai", sans-serif;
font-size: 14px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
gap: 8px;
`;
toast.innerHTML = message;
return toast;
}
// 显示并自动移除Toast
function showToast(message, bgColor = '#4CAF50', position = 'top', duration = 3000) {
const toast = createToast(message, bgColor, position);
document.body.appendChild(toast);
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
}, duration);
}
// 显示安装成功提示
function showInstallSuccessToast() {
showToast('✅ MarkDo已成功安装到您的设备!', '#4CAF50');
}
// 检查是否为PWA环境
function isPWAEnvironment() {
// 检查是否在独立模式下运行(已安装的PWA)
return window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true ||
document.referrer.includes('android-app://');
}
// 检查用户是否有PWA安装意图
function hasUserPWAIntent() {
// 检查用户是否曾经与PWA安装功能交互过
return localStorage.getItem('pwa-install-attempted') === 'true' ||
localStorage.getItem('pwa-install-dismissed') === 'true' ||
isPWAEnvironment();
}
// 注册Service Worker
async function registerServiceWorker() {
if ('serviceWorker' in navigator) {
try {
const registration = await navigator.serviceWorker.register('./sw.js');
console.log('PWA: Service Worker registered successfully:', registration);
// 监听Service Worker更新
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
// 只有在PWA环境或用户有PWA使用意图时才显示更新提示
if (isPWAEnvironment() || hasUserPWAIntent()) {
showUpdateAvailableToast();
} else {
console.log('PWA: 新版本已缓存,但用户未使用PWA模式,不显示更新提示');
}
}
});
});
} catch (error) {
console.error('PWA: Service Worker registration failed:', error);
}
}
}
// 显示更新可用提示
function showUpdateAvailableToast() {
const toast = createToast('🔄 有新版本可用', '#2196F3', 'bottom');
const updateBtn = document.createElement('button');
updateBtn.textContent = '立即更新';
updateBtn.style.cssText = `
background: white;
color: #2196F3;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
margin-left: 12px;
`;
updateBtn.onclick = () => window.location.reload();
toast.appendChild(updateBtn);
document.body.appendChild(toast);
}
// 初始化PWA
function initPWA() {
checkPWAInstallStatus();
registerServiceWorker();
}
// 页面加载完成后初始化PWA
window.addEventListener('load', initPWA);
// 保存内容到本地存储
function saveContent() {
const content = input.value;
localStorage.setItem('markdownContent', content);
}
// 从本地存储加载内容
function loadContent() {
const savedContent = localStorage.getItem('markdownContent');
if (savedContent !== null && savedContent.trim() !== '') {
input.value = savedContent;
} else {
// 如果没有保存的内容,显示默认示例
input.value = `# 欢迎使用MarkDo
这是一个**优雅简洁**的Markdown编辑器,支持实时预览和自动保存。
## 功能特点
- ⚡ 实时预览
- 🌈 代码语法高亮
- 📐 LaTeX数学公式支持
- 🌙 暗黑模式切换
## 示例
### 代码块
\`\`\`javascript
console.log('Hello, Markdown!');
\`\`\`
### 数学公式
行内公式:$E = mc^2$
块级公式:
$$\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$$
> 您的内容会自动保存,开始您的MarkDo写作之旅吧!`;
}
updatePreview();
}
// 页面加载时恢复保存的内容
loadContent();
// 初始化字数统计
updateWordCount();
// 定期自动保存(每30秒)
setInterval(saveContent, 30000);
// 文件导入功能
function importMarkdown() {
const fileInput = document.getElementById('fileInput');
fileInput.click();
}
// 处理文件导入
document.getElementById('fileInput').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
// 检查文件类型
const validTypes = ['.md', '.markdown', '.txt'];
const fileName = file.name.toLowerCase();
const isValidType = validTypes.some(type => fileName.endsWith(type));
if (!isValidType) {
alert('请选择 .md、.markdown 或 .txt 文件');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
input.value = content;
updatePreview();
updateWordCount();
saveContent();
};
reader.readAsText(file, 'UTF-8');
// 清空文件输入,允许重复选择同一文件
e.target.value = '';
});
// HTML导出功能
function exportToHTML() {
try {
// 检查是否有内容
if (!input.value.trim()) {
alert('请先输入一些内容再导出');
return;
}
const filename = getExportFilename();
const htmlContent = generateHTMLContent();
// 创建下载链接
const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename + '.html';
// 触发下载
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 清理URL对象
URL.revokeObjectURL(url);
console.log('HTML导出成功');
} catch (error) {
console.error('HTML导出失败:', error);
alert('HTML导出失败,请重试。错误信息:' + error.message);
}
}
function generateHTMLContent() {
const markdownContent = input.value;
const htmlBody = marked.parse(markdownContent);
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MarkDo导出文档</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets@11.9.0/styles/github.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css">
<style>
body {
font-family: "LXGW WenKai", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
line-height: 1.7;
color: #444444;
max-width: 800px;
margin: 0 auto;
padding: 40px 20px;
background: #ffffff;
}
h1, h2, h3, h4, h5, h6 {
margin: 0.5em 0 0.5em 0;
color: #555555;
font-weight: 600;
}
h1 {
font-size: 2.2em;
border-bottom: 3px solid #aaaaaa;
padding-bottom: 10px;
}
h2 {
font-size: 1.8em;
border-bottom: 2px solid #bbbbbb;
padding-bottom: 8px;
}
h3 {
font-size: 1.5em;
color: #777777;
}
p {
margin: 0.8em 0;
text-align: justify;
}
blockquote {
border-left: 4px solid #3498db;
margin: 1.5em 0;
padding: 0.5em 1em;
background: #ecf0f1;
font-style: italic;
}
code {
background: #f8f9fa;
padding: 2px 6px;
border-radius: 3px;
font-family: 'Consolas', 'Monaco', monospace;
color: #e74c3c;
font-size: 0.9em;
}
pre {
background: #f8f9fa;
color: #495057;
padding: 1.5em;
border-radius: 5px;
overflow-x: auto;
margin: 1.5em 0;
border: 1px solid #e9ecef;
}
pre code {
background: none;
color: inherit;
padding: 0;
}
ul, ol {
margin: 1em 0;
padding-left: 2em;
}
li {
margin: 0.5em 0;
}
table {
border-collapse: collapse;
width: 100%;
margin: 1.5em 0;
}
th, td {
border: 1px solid #bdc3c7;
padding: 12px;
text-align: left;
}
th {
background: #34495e;
color: white;
font-weight: 600;
}
tr:nth-child(even) {
background: #f8f9fa;
}
a {
color: #3498db;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
img {
max-width: 100%;
height: auto;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
margin: 1em 0;
}
hr {
border: none;
border-top: 2px solid #eee;
margin: 2em 0;
}
</style>
</head>
<body>
${htmlBody}
<script src="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets@11.9.0/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js"></script>
<script>
// 代码高亮
hljs.highlightAll();
// 数学公式渲染
renderMathInElement(document.body, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\\\[', right: '\\\\]', display: true},
{left: '\\\\(', right: '\\\\)', display: false}
],
throwOnError: false
});
</script>
</body>
</html>`;
}
// 显示确认弹窗
function clearContent() {
showConfirmModal();
}
// 显示自定义确认弹窗
function showConfirmModal() {
const modal = document.getElementById('confirmModal');
const modalElement = document.getElementById('modal');
// 应用当前主题
if (document.body.classList.contains('dark')) {
modalElement.classList.add('dark');
} else {
modalElement.classList.remove('dark');
}
modal.classList.add('show');
// 重新初始化图标
setTimeout(() => {
lucide.createIcons();
}, 100);
}
// 隐藏确认弹窗
function hideConfirmModal() {
const modal = document.getElementById('confirmModal');
modal.classList.remove('show');
}
// 确认清空内容
function confirmClearContent() {
input.value = '';
updatePreview();
saveContent();
input.focus();
hideConfirmModal();
}
// 点击遮罩层关闭弹窗
document.getElementById('confirmModal').addEventListener('click', function(e) {
if (e.target === this) {
hideConfirmModal();
}
});
// ESC键关闭弹窗
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
hideConfirmModal();
}
});
// 下载Markdown文件
function downloadMarkdown() {
const markdownContent = input.value;
const filename = getExportFilename();
// 创建下载链接
const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename + '.md';
// 触发下载
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 清理URL对象
URL.revokeObjectURL(url);
}
// 精准滚动同步功能
let isScrolling = false;
let lineMapping = new Map(); // 存储行号到预览元素的映射
// 计算行号到预览元素的映射关系
function calculateLineMapping() {
const content = input.value;
const lines = content.split('\n');
const previewElements = preview.querySelectorAll('h1, h2, h3, h4, h5, h6, p, blockquote, pre, ul, ol, table, hr, .katex-display');
lineMapping.clear();
let elementIndex = 0;
let inCodeBlock = false;
let inMathBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const prevLine = i > 0 ? lines[i - 1] : '';
const nextLine = i < lines.length - 1 ? lines[i + 1] : '';
// 处理代码块状态
if (line.trim().startsWith('```')) {
inCodeBlock = !inCodeBlock;
if (!inCodeBlock && elementIndex < previewElements.length) {
// 代码块结束,映射到pre元素
const element = previewElements[elementIndex];
if (element.tagName === 'PRE' || element.classList.contains('code-block-container')) {
lineMapping.set(i - getCodeBlockLength(lines, i), {
element: element,
offsetTop: element.offsetTop,
lineNumber: i - getCodeBlockLength(lines, i)
});
elementIndex++;
}
}
continue;
}
// 处理数学公式块状态
if (line.trim() === '$$') {
inMathBlock = !inMathBlock;
if (!inMathBlock && elementIndex < previewElements.length) {
// 数学公式块结束
const element = previewElements[elementIndex];
if (element.classList.contains('katex-display')) {
lineMapping.set(i - getMathBlockLength(lines, i), {
element: element,
offsetTop: element.offsetTop,
lineNumber: i - getMathBlockLength(lines, i)
});
elementIndex++;
}
}
continue;
}
// 跳过代码块和数学公式块内部的行
if (inCodeBlock || inMathBlock) continue;
// 检查是否是Markdown元素的开始
if (isMarkdownElement(line, prevLine, nextLine)) {
if (elementIndex < previewElements.length) {
const element = previewElements[elementIndex];
lineMapping.set(i, {
element: element,
offsetTop: element.offsetTop,
lineNumber: i
});
elementIndex++;
}
}
}
}
// 获取代码块的长度
function getCodeBlockLength(lines, endIndex) {
let length = 0;
for (let i = endIndex - 1; i >= 0; i--) {
length++;
if (lines[i].trim().startsWith('```')) {
break;
}
}
return length - 1;
}
// 获取数学公式块的长度
function getMathBlockLength(lines, endIndex) {
let length = 0;
for (let i = endIndex - 1; i >= 0; i--) {
length++;
if (lines[i].trim() === '$$') {
break;
}
}
return length - 1;
}
// 判断是否是Markdown元素
function isMarkdownElement(line, prevLine = '', nextLine = '') {
const trimmed = line.trim();
// 空行不是元素
if (!trimmed) return false;