-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
3409 lines (2970 loc) · 117 KB
/
Copy pathscript.js
File metadata and controls
3409 lines (2970 loc) · 117 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
// ===== 应用状态管理 =====
const AppState = {
zoom: 100,
background: 'gradient1',
fontSize: 18,
padding: 40,
width: 640,
mode: 'free', // 'free' | 'xhs'
fixedHeights: { xhs: null },
watermark: 'LanLance'
};
// 状态管理器
const StateManager = {
state: AppState,
listeners: [],
get(key) {
return this.state[key];
},
set(key, value) {
const oldValue = this.state[key];
this.state[key] = value;
this.notify(key, value, oldValue);
},
subscribe(listener) {
this.listeners.push(listener);
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) this.listeners.splice(index, 1);
};
},
notify(key, value, oldValue) {
this.listeners.forEach(fn => {
try {
fn(key, value, oldValue);
} catch (e) {
console.error('状态监听器错误:', e);
}
});
}
};
// 为了兼容性,保留旧的全局变量作为访问器
let currentZoom = AppState.zoom;
let currentBackground = AppState.background;
let currentFontSize = AppState.fontSize;
let currentPadding = AppState.padding;
let currentWidth = AppState.width;
let currentMode = AppState.mode;
let fixedHeights = AppState.fixedHeights;
let currentWatermark = AppState.watermark;
// ===== 工具函数 =====
/**
* 防抖函数:延迟执行,在 delay 毫秒内多次调用只执行最后一次
*/
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
/**
* 动态加载脚本(懒加载 CDN)
*/
const loadedScripts = new Set();
async function loadScript(src) {
if (loadedScripts.has(src)) return;
if (src.includes('html2canvas') && typeof html2canvas !== 'undefined') {
loadedScripts.add(src);
return;
}
if (src.includes('jspdf') && typeof jsPDF !== 'undefined') {
loadedScripts.add(src);
return;
}
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => {
loadedScripts.add(src);
resolve();
};
script.onerror = reject;
document.head.appendChild(script);
});
}
/**
* 可选库配置(按需加载)
*/
const optionalLibs = {
mhchem: 'https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/mhchem.min.js'
};
/**
* 加载可选库
*/
async function loadOptionalLib(name) {
const src = optionalLibs[name];
if (src && !loadedScripts.has(src)) {
await loadScript(src);
}
}
/**
* 确保导出所需的库已加载
*/
async function ensureExportLibsLoaded() {
const libs = [
'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js',
'https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js'
];
await Promise.all(libs.map(loadScript));
}
/**
* CORS 图片代理:将跨域图片 URL 转换为代理 URL
*/
function corsProxyUrl(url) {
// 跳过 data: 和 blob: URL
if (!url || url.startsWith('data:') || url.startsWith('blob:')) return url;
// 跳过同源图片
try {
const imgUrl = new URL(url, window.location.href);
if (imgUrl.origin === window.location.origin) return url;
} catch (e) {
return url;
}
// 使用 weserv.nl 代理(免费、支持 CORS)
return `https://images.weserv.nl/?url=${encodeURIComponent(url)}`;
}
/**
* HTML 清理函数:移除潜在的 XSS 攻击代码
* 注意:这是一个基础版本,建议在生产环境中使用 DOMPurify 等专业库
*/
function sanitizeHTML(html) {
// 创建临时 DOM 容器
const temp = document.createElement('div');
temp.innerHTML = html;
// 移除危险的标签
const dangerousTags = ['script', 'iframe', 'object', 'embed', 'link'];
dangerousTags.forEach(tag => {
const elements = temp.querySelectorAll(tag);
elements.forEach(el => el.remove());
});
// 移除危险的属性(on* 事件处理器)
const allElements = temp.querySelectorAll('*');
allElements.forEach(el => {
// 移除所有 on* 属性
Array.from(el.attributes).forEach(attr => {
if (attr.name.startsWith('on')) {
el.removeAttribute(attr.name);
}
});
// 清理 href 和 src 中的 javascript: 协议
if (el.hasAttribute('href')) {
const href = el.getAttribute('href');
if (href && href.trim().toLowerCase().startsWith('javascript:')) {
el.removeAttribute('href');
}
}
if (el.hasAttribute('src')) {
const src = el.getAttribute('src');
if (src && src.trim().toLowerCase().startsWith('javascript:')) {
el.removeAttribute('src');
}
}
});
return temp.innerHTML;
}
// ===== 撤销/重做管理器 =====
class UndoRedoManager {
constructor(maxHistory = 50) {
this.history = [];
this.index = -1;
this.maxHistory = maxHistory;
this.isUndoRedo = false;
}
push(state) {
if (this.isUndoRedo) return;
// 移除当前位置之后的历史
this.history = this.history.slice(0, this.index + 1);
this.history.push(state);
// 限制历史大小
if (this.history.length > this.maxHistory) {
this.history.shift();
} else {
this.index++;
}
}
undo() {
if (this.index > 0) {
this.index--;
return this.history[this.index];
}
return null;
}
redo() {
if (this.index < this.history.length - 1) {
this.index++;
return this.history[this.index];
}
return null;
}
canUndo() { return this.index > 0; }
canRedo() { return this.index < this.history.length - 1; }
}
const undoRedoManager = new UndoRedoManager();
// ===== 自动保存 =====
const AUTOSAVE_KEY = 'md2pic_draft';
const AUTOSAVE_SETTINGS_KEY = 'md2pic_settings';
function autoSave(content) {
try {
localStorage.setItem(AUTOSAVE_KEY, content);
localStorage.setItem(AUTOSAVE_SETTINGS_KEY, JSON.stringify({
background: currentBackground,
fontSize: typeof currentFontSize !== 'undefined' ? currentFontSize : 18,
width: typeof currentWidth !== 'undefined' ? currentWidth : 640,
padding: typeof currentPadding !== 'undefined' ? currentPadding : 40,
mode: typeof currentMode !== 'undefined' ? currentMode : 'free',
watermark: typeof currentWatermark !== 'undefined' ? currentWatermark : 'LanLance'
}));
} catch (e) {
console.warn('自动保存失败:', e);
// 用户友好提示:可能是存储空间已满
if (typeof showNotification === 'function') {
showNotification('自动保存失败,可能是浏览器存储空间已满', 'warning');
}
}
}
function loadDraft() {
try {
return localStorage.getItem(AUTOSAVE_KEY);
} catch (e) {
console.warn('加载草稿失败:', e);
if (typeof showNotification === 'function') {
showNotification('加载草稿失败,将使用默认内容', 'info');
}
return null;
}
}
function loadSettings() {
try {
const settings = localStorage.getItem(AUTOSAVE_SETTINGS_KEY);
return settings ? JSON.parse(settings) : null;
} catch (e) {
console.warn('加载设置失败:', e);
if (typeof showNotification === 'function') {
showNotification('加载设置失败,将使用默认设置', 'info');
}
return null;
}
}
// ===== 数学公式渲染器 =====
class MathRenderer {
constructor() {
this.isKaTeXLoaded = false;
this.checkKaTeXAvailability();
}
checkKaTeXAvailability() {
this.isKaTeXLoaded = typeof katex !== 'undefined' && typeof renderMathInElement !== 'undefined';
if (!this.isKaTeXLoaded) {
console.warn('KaTeX not loaded. Math formulas will not be rendered.');
} else {
// 检查mhchem扩展是否可用
const hasMhchem = typeof katex.__defineMacro !== 'undefined' ||
(window.katex && window.katex.__plugins && window.katex.__plugins['mhchem']);
if (hasMhchem) {
console.log('KaTeX with mhchem extension loaded successfully');
} else {
console.warn('KaTeX loaded but mhchem extension may not be available');
}
}
}
renderMath(element) {
if (!this.isKaTeXLoaded) {
console.warn('KaTeX not available for math rendering');
return;
}
try {
renderMathInElement(element, {
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\[', right: '\\]', display: true },
{ left: '\\(', right: '\\)', display: false }
],
throwOnError: false,
errorColor: '#cc0000',
strict: false,
trust: true,
macros: {
// 物理常量
'\\emc': 'E=mc^{2}',
'\\hbar': '\\hslash',
'\\kb': 'k_B',
'\\NA': 'N_A',
// 常用符号
'\\R': '\\mathbb{R}',
'\\C': '\\mathbb{C}',
'\\N': '\\mathbb{N}',
'\\Z': '\\mathbb{Z}',
'\\Q': '\\mathbb{Q}',
// 微积分
'\\dd': '\\mathrm{d}',
'\\dv': ['\\frac{\\mathrm{d}#1}{\\mathrm{d}#2}', 2],
'\\pdv': ['\\frac{\\partial#1}{\\partial#2}', 2],
// 向量
'\\vb': ['\\mathbf{#1}', 1],
'\\vu': ['\\hat{\\mathbf{#1}}', 1],
// 物理单位
'\\unit': ['\\,\\mathrm{#1}', 1]
},
fleqn: false,
displayMode: false
});
} catch (error) {
console.error('Math rendering error:', error);
this.showMathError(element, error.message);
}
}
showMathError(element, errorMessage) {
const errorElements = element.querySelectorAll('.katex-error');
errorElements.forEach(errorEl => {
errorEl.style.color = '#cc0000';
errorEl.title = `Math Error: ${errorMessage}`;
});
}
// 预处理Markdown中的数学公式
preprocessMath(markdown) {
// 处理质能守恒公式的特殊情况
markdown = markdown.replace(/E\s*=\s*mc\^?2/g, '$E=mc^{2}$');
// 处理其他常见物理公式
markdown = markdown.replace(/F\s*=\s*ma/g, '$F=ma$');
markdown = markdown.replace(/v\s*=\s*u\s*\+\s*at/g, '$v=u+at$');
markdown = markdown.replace(/s\s*=\s*ut\s*\+\s*½at²/g, '$s=ut+\\frac{1}{2}at^{2}$');
markdown = markdown.replace(/v²\s*=\s*u²\s*\+\s*2as/g, '$v^{2}=u^{2}+2as$');
// 处理数学常量
markdown = markdown.replace(/π/g, '$\\pi$');
markdown = markdown.replace(/∞/g, '$\\infty$');
markdown = markdown.replace(/±/g, '$\\pm$');
markdown = markdown.replace(/≤/g, '$\\leq$');
markdown = markdown.replace(/≥/g, '$\\geq$');
markdown = markdown.replace(/≠/g, '$\\neq$');
markdown = markdown.replace(/∈/g, '$\\in$');
markdown = markdown.replace(/∉/g, '$\\notin$');
markdown = markdown.replace(/⊆/g, '$\\subseteq$');
markdown = markdown.replace(/⊇/g, '$\\supseteq$');
markdown = markdown.replace(/∪/g, '$\\cup$');
markdown = markdown.replace(/∩/g, '$\\cap$');
markdown = markdown.replace(/∅/g, '$\\emptyset$');
// 处理希腊字母
markdown = markdown.replace(/α/g, '$\\alpha$');
markdown = markdown.replace(/β/g, '$\\beta$');
markdown = markdown.replace(/γ/g, '$\\gamma$');
markdown = markdown.replace(/δ/g, '$\\delta$');
markdown = markdown.replace(/ε/g, '$\\epsilon$');
markdown = markdown.replace(/θ/g, '$\\theta$');
markdown = markdown.replace(/λ/g, '$\\lambda$');
markdown = markdown.replace(/μ/g, '$\\mu$');
markdown = markdown.replace(/σ/g, '$\\sigma$');
markdown = markdown.replace(/φ/g, '$\\phi$');
markdown = markdown.replace(/ω/g, '$\\omega$');
return markdown;
}
}
// 创建全局数学渲染器实例
const mathRenderer = new MathRenderer();
// ===== 图表渲染器 =====
class DiagramRenderer {
constructor() {
this.isMermaidLoaded = false;
this.mermaidConfig = {
startOnLoad: false,
theme: 'default',
themeVariables: {
primaryColor: '#6366f1',
primaryTextColor: '#1f2937',
primaryBorderColor: '#4f46e5',
lineColor: '#6b7280',
secondaryColor: '#f3f4f6',
tertiaryColor: '#ffffff'
},
flowchart: {
useMaxWidth: true,
htmlLabels: true
},
sequence: {
useMaxWidth: true,
wrap: true
},
gantt: {
useMaxWidth: true
}
};
this.checkMermaidAvailability();
}
checkMermaidAvailability() {
this.isMermaidLoaded = typeof mermaid !== 'undefined';
if (this.isMermaidLoaded) {
try {
mermaid.initialize(this.mermaidConfig);
console.log('Mermaid initialized successfully');
} catch (error) {
console.error('Mermaid initialization error:', error);
this.isMermaidLoaded = false;
}
} else {
console.warn('Mermaid not loaded. Diagrams will not be rendered.');
}
}
async renderDiagram(element, diagramCode, diagramId) {
if (!this.isMermaidLoaded) {
console.warn('Mermaid not available for diagram rendering');
this.showDiagramError(element, 'Mermaid library not loaded');
return;
}
try {
// 清除之前的内容
element.innerHTML = '';
// 渲染图表
const { svg } = await mermaid.render(diagramId, diagramCode);
element.innerHTML = svg;
// 添加图表容器样式
element.classList.add('mermaid-diagram');
} catch (error) {
console.error('Diagram rendering error:', error);
this.showDiagramError(element, error.message);
}
}
showDiagramError(element, errorMessage) {
element.innerHTML = `
<div class="diagram-error">
<i class="fas fa-exclamation-triangle"></i>
<div class="error-title">图表渲染错误</div>
<div class="error-message">${errorMessage}</div>
</div>
`;
element.classList.add('diagram-error-container');
}
// 预处理Markdown中的图表代码
preprocessDiagram(markdown) {
// 为每个mermaid代码块生成唯一ID
let diagramCounter = 0;
return markdown.replace(/```mermaid\s*\n([\s\S]*?)\n```/g, (match, code) => {
const diagramId = `mermaid-diagram-${++diagramCounter}`;
return `<div class="mermaid-container" data-diagram-id="${diagramId}" data-diagram-code="${encodeURIComponent(code.trim())}"></div>`;
});
}
// 渲染页面中的所有图表
async renderDiagrams(container) {
if (!this.isMermaidLoaded) {
return;
}
const diagramContainers = container.querySelectorAll('.mermaid-container');
for (const diagramContainer of diagramContainers) {
const diagramId = diagramContainer.getAttribute('data-diagram-id');
const diagramCode = decodeURIComponent(diagramContainer.getAttribute('data-diagram-code'));
if (diagramId && diagramCode) {
await this.renderDiagram(diagramContainer, diagramCode, diagramId);
}
}
}
// 设置主题
setTheme(theme) {
if (!this.isMermaidLoaded) {
return;
}
this.mermaidConfig.theme = theme;
try {
mermaid.initialize(this.mermaidConfig);
} catch (error) {
console.error('Theme update error:', error);
}
}
}
// 创建全局图表渲染器实例
const diagramRenderer = new DiagramRenderer();
// ECharts 渲染器类
class EChartsRenderer {
constructor() {
this.isEChartsLoaded = false;
// 使用 WeakMap 存储实例,自动垃圾回收
this.instances = new WeakMap();
this.checkEChartsAvailability();
}
checkEChartsAvailability() {
this.isEChartsLoaded = typeof echarts !== 'undefined';
if (!this.isEChartsLoaded) {
console.warn('ECharts not loaded. ECharts diagrams will not be rendered.');
}
}
async renderEChart(element, chartConfig, chartId) {
if (!this.isEChartsLoaded) {
console.warn('ECharts not available for chart rendering');
this.showEChartError(element, 'ECharts library not loaded');
return;
}
try {
// 清理之前的实例(如果存在)
this.destroy(element);
// 清除之前的内容
element.innerHTML = '';
// 创建图表容器
const chartContainer = document.createElement('div');
chartContainer.id = chartId;
chartContainer.style.width = '100%';
chartContainer.style.height = '400px';
chartContainer.style.minHeight = '300px';
element.appendChild(chartContainer);
// 解析配置
let config;
if (typeof chartConfig === 'string') {
config = JSON.parse(chartConfig);
} else {
config = chartConfig;
}
// 初始化图表
const chart = echarts.init(chartContainer);
chart.setOption(config);
// 响应式调整
const resizeObserver = new ResizeObserver(() => {
chart.resize();
});
resizeObserver.observe(chartContainer);
// 使用 WeakMap 存储图表实例
this.instances.set(element, {
chart,
resizeObserver,
container: chartContainer
});
} catch (error) {
console.error('ECharts rendering error:', error);
this.showEChartError(element, error.message);
}
}
showEChartError(element, errorMessage) {
element.innerHTML = `
<div class="echarts-error" style="
padding: 20px;
border: 2px dashed #ff6b6b;
border-radius: 8px;
background-color: #ffe0e0;
color: #d63031;
text-align: center;
font-family: monospace;
">
<i class="fas fa-exclamation-triangle" style="margin-right: 8px;"></i>
ECharts Error: ${errorMessage}
</div>
`;
}
preprocessECharts(markdown) {
// 处理 ```echarts 代码块
return markdown.replace(/```echarts\s*\n([\s\S]*?)\n```/g, (match, code) => {
const chartId = 'echarts-' + Math.random().toString(36).substr(2, 9);
return `<div class="echarts-container" data-echarts-id="${chartId}" data-echarts-config="${encodeURIComponent(code.trim())}"></div>`;
});
}
async renderECharts(container) {
const echartsElements = container.querySelectorAll('.echarts-container');
for (const element of echartsElements) {
const chartId = element.getAttribute('data-echarts-id');
const configData = decodeURIComponent(element.getAttribute('data-echarts-config'));
await this.renderEChart(element, configData, chartId);
}
}
/**
* 清理单个 ECharts 实例
*/
destroy(element) {
const instance = this.instances.get(element);
if (instance) {
try {
// 断开 ResizeObserver
if (instance.resizeObserver) {
instance.resizeObserver.disconnect();
}
// 销毁图表实例
if (instance.chart) {
instance.chart.dispose();
}
} catch (e) {
console.warn('清理 ECharts 实例失败:', e);
}
// 从 WeakMap 中删除
this.instances.delete(element);
}
}
/**
* 清理指定容器内的所有 ECharts 实例
*/
destroyAll(container) {
if (!container) return;
const echartsElements = container.querySelectorAll('.echarts-container');
echartsElements.forEach(element => {
this.destroy(element);
});
}
}
// 创建全局 ECharts 渲染器实例
const echartsRenderer = new EChartsRenderer();
// ===== 卡片渲染器 =====
class CardRenderer {
constructor() {
// 卡片渲染器不需要外部依赖
}
// 预处理Markdown中的卡片语法
preprocessCards(markdown) {
// 处理 :::card 语法,支持不同类型的卡片
let result = markdown.replace(/:::card(?:\s+(info|success|warning|error))?\s*\n([\s\S]*?)\n:::/g, (match, type, content) => {
const cardType = type || 'default';
const cardId = 'card-' + Math.random().toString(36).substr(2, 9);
return `<div class="card-container" data-card-id="${cardId}" data-card-type="${cardType}" data-card-content="${encodeURIComponent(content.trim())}"></div>`;
});
// 处理 Obsidian Callout 语法:> [!type][-] title(忽略折叠标记,始终展开)
result = result.replace(/^>\s*\[!(\w+)\]([+\-]?)\s*(.*?)\n((?:^>.*\n?)*)/gm, (match, type, collapsible, title, content) => {
const cardId = 'card-' + Math.random().toString(36).substr(2, 9);
const cleanContent = content.replace(/^>\s?/gm, '').trim();
const isCollapsible = false;
const displayTitle = title || type.charAt(0).toUpperCase() + type.slice(1);
// 类型映射:Obsidian 类型 → Madopic 卡片类型
const typeMap = {
note: 'info', abstract: 'info', info: 'info',
tip: 'success', success: 'success',
question: 'info', warning: 'warning',
failure: 'error', danger: 'error', bug: 'error',
example: 'default', quote: 'default'
};
const cardType = typeMap[type.toLowerCase()] || 'info';
return `<div class="card-container obsidian-callout"
data-card-id="${cardId}"
data-card-type="${cardType}"
data-card-title="${encodeURIComponent(displayTitle)}"
data-collapsible="${isCollapsible}"
data-card-content="${encodeURIComponent(cleanContent)}"></div>\n\n`;
});
return result;
}
// 渲染页面中的所有卡片
async renderCards(container) {
const cardContainers = container.querySelectorAll('.card-container');
for (const cardContainer of cardContainers) {
const cardId = cardContainer.getAttribute('data-card-id');
const cardType = cardContainer.getAttribute('data-card-type');
const cardContent = decodeURIComponent(cardContainer.getAttribute('data-card-content'));
if (cardId && cardContent) {
await this.renderCard(cardContainer, cardContent, cardType);
}
}
}
// 渲染单个卡片
async renderCard(element, content, type) {
try {
// 清除之前的内容
element.innerHTML = '';
// 获取 Obsidian Callout 特有属性
const title = element.getAttribute('data-card-title')
? decodeURIComponent(element.getAttribute('data-card-title'))
: '';
const isCollapsible = element.getAttribute('data-collapsible') === 'true';
const isObsidian = element.classList.contains('obsidian-callout');
// 解析卡片内容的Markdown
let htmlContent = '';
try {
htmlContent = marked.parse(content);
} catch (err) {
console.error('卡片内容Markdown解析失败: ', err);
htmlContent = '<p>卡片内容解析失败</p>';
}
// 创建卡片HTML结构
const cardHtml = `
<div class="madopic-card ${type !== 'default' ? 'card-' + type : ''} ${isObsidian ? 'obsidian-style' : ''}">
${title ? `
<div class="card-title ${isCollapsible ? 'collapsible' : ''}"
${isCollapsible ? `onclick="this.parentElement.classList.toggle('collapsed')"` : ''}>
<span class="title-text">${title}</span>
${isCollapsible ? '<span class="toggle-icon">▼</span>' : ''}
</div>
` : ''}
<div class="card-content">
${htmlContent}
</div>
</div>
`;
element.innerHTML = cardHtml;
} catch (error) {
console.error('卡片渲染错误:', error);
element.innerHTML = `
<div class="madopic-card">
<div class="card-content">
<p style="color: #ef4444;">卡片渲染失败:${error.message}</p>
</div>
</div>
`;
}
}
}
// 创建全局卡片渲染器实例
const cardRenderer = new CardRenderer();
// ===== 导出相关常量 =====
// 控制导出清晰度的缩放倍数范围
const EXPORT_MIN_SCALE = 2;
const EXPORT_MAX_SCALE = 3;
function getPreferredExportScale() {
try {
const urlParams = new URLSearchParams(window.location.search);
const urlScale = parseFloat(urlParams.get('scale'));
const storedScale = parseFloat(localStorage.getItem('md2pic_export_scale'));
const base = Number.isFinite(urlScale)
? urlScale
: (Number.isFinite(storedScale)
? storedScale
: Math.max(2, window.devicePixelRatio || 1));
return Math.min(EXPORT_MAX_SCALE, Math.max(EXPORT_MIN_SCALE, base));
} catch (_) {
return Math.max(EXPORT_MIN_SCALE, Math.min(EXPORT_MAX_SCALE, 2));
}
}
const EXPORT_SCALE = getPreferredExportScale();
// 海报背景固定为白色
// DOM 元素
const markdownInput = document.getElementById('markdownInput');
const lineNumbersEl = document.querySelector('.line-numbers');
const posterContent = document.getElementById('posterContent');
const markdownPoster = document.getElementById('markdownPoster');
const previewContent = document.getElementById('previewContent');
const layoutPanel = document.getElementById('layoutPanel');
const overlay = document.getElementById('overlay');
const zoomLevel = document.querySelector('.zoom-level');
// 图片数据存储(使用 Map 提供更好的性能)
const imageDataStore = new Map();
// 图片缓存管理器
const ImageCache = {
cache: new Map(),
maxSize: 50, // 最多缓存 50 张图片
set(url, data) {
// 如果缓存已满,删除最早的项
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(url, {
data,
timestamp: Date.now()
});
},
get(url) {
const item = this.cache.get(url);
return item ? item.data : null;
},
has(url) {
return this.cache.has(url);
},
clear() {
this.cache.clear();
},
// 清理超过指定时间的缓存(默认 30 分钟)
cleanup(maxAge = 30 * 60 * 1000) {
const now = Date.now();
for (const [key, value] of this.cache.entries()) {
if (now - value.timestamp > maxAge) {
this.cache.delete(key);
}
}
}
};
// 预览渲染状态
let hasInitialPreviewRendered = false;
let lastRenderedMarkdown = '';
// 初始化应用
document.addEventListener('DOMContentLoaded', function () {
initializeApp();
setupEventListeners();
updatePreview();
});
// 初始化应用
function initializeApp() {
// 配置 marked 选项(marked v5+ 使用 marked.use,setOptions 已废弃)
marked.use({
breaks: true,
gfm: true,
renderer: {
hr(token) {
return '<hr class="md-hr">\n';
}
}
});
// 海报背景固定白色
markdownPoster.style.background = '#fff';
// 应用初始设置
applyFontSize(currentFontSize);
applyPadding(currentPadding);
applyWidth(currentWidth);
// 初始化图表渲染器主题
diagramRenderer.setTheme('default');
// 更新缩放显示
updateZoomDisplay();
// 初始化行号
updateLineNumbers();
}
// 设置事件监听器
function setupEventListeners() {
// Markdown 输入监听
// 更平滑的输入预览:稍延长防抖并在输入结束时仅渲染一次
markdownInput.addEventListener('input', debounce(updatePreview, 250));
markdownInput.addEventListener('input', updateLineNumbers);
markdownInput.addEventListener('scroll', syncLineNumbersScroll);
// 工具栏按钮
setupToolbarButtons();
// 缩放控制
document.getElementById('zoomIn').addEventListener('click', zoomIn);
document.getElementById('zoomOut').addEventListener('click', zoomOut);
// 文字布局设置面板
document.getElementById('layoutBtn').addEventListener('click', openLayoutPanel);
document.getElementById('cancelLayout').addEventListener('click', closeLayoutPanel);
document.getElementById('applyLayout').addEventListener('click', applyLayoutSettings);
overlay.addEventListener('click', closeAllPanels);
// 滑块事件监听
setupSliders();
// 导出功能
setupExportButtons();
setupModeButtons();
// 图片处理
setupImageHandlers();
// 键盘快捷键
setupKeyboardShortcuts();
}
// 设置导出按钮事件
function setupExportButtons() {
const exportPngBtn = document.getElementById('exportPngBtn');
const exportPdfBtn = document.getElementById('exportPdfBtn');
const exportHtmlBtn = document.getElementById('exportHtmlBtn');
if (exportPngBtn) {
exportPngBtn.addEventListener('click', exportToPNG);
}
if (exportPdfBtn) {
exportPdfBtn.addEventListener('click', exportToPDF);
}
if (exportHtmlBtn) {
exportHtmlBtn.addEventListener('click', exportToHTML);
}
}
// 模式按钮绑定
function setupModeButtons() {
const group = document.getElementById('modeGroup');
if (!group) return;
group.querySelectorAll('button[data-mode]').forEach(btn => {
btn.addEventListener('click', () => {
const mode = btn.getAttribute('data-mode');
setMode(mode);
});
});
}
function setMode(mode) {
if (!['free', 'xhs'].includes(mode)) return;
currentMode = mode;
// 切换按钮激活态
const group = document.getElementById('modeGroup');
if (group) {
group.querySelectorAll('button[data-mode]').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-mode') === mode);
});
}
// PDF/HTML 仅自由模式可用
const exportPdfBtn = document.getElementById('exportPdfBtn');
const exportHtmlBtn = document.getElementById('exportHtmlBtn');
const isFree = mode === 'free';
if (exportPdfBtn) exportPdfBtn.style.display = isFree ? '' : 'none';
if (exportHtmlBtn) exportHtmlBtn.style.display = isFree ? '' : 'none';
// 预览区域视觉反馈(仅预览容器外层,不改导出逻辑)
applyPreviewModeFrame();
}
function applyPreviewModeFrame() {
markdownPoster.dataset.mode = currentMode;
// 移除旧的分页线