-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1386 lines (1256 loc) · 44 KB
/
index.html
File metadata and controls
1386 lines (1256 loc) · 44 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
<!doctype html>
<html>
<markdown-html
version="1.20.11"
author="PJ568"
repo="https://github.com/PJ-568/markdown.html"
license="CC BY-SA 4.0 International"
>
</markdown-html>
<head>
<meta charset="utf-8" />
<meta name="description" content="HTML read markdown" />
<meta
name="keywords"
content="markdown, html, renderer, low-dependency, one-click deployment"
/>
<meta name="author" content="PJ568" />
<link
rel="icon"
type="image/svg+xml"
href="data:image/svg+xml;charset=utf-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDQ4IDQ4IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB4PSI2IiB5PSI2IiB3aWR0aD0iMzYiIGhlaWdodD0iMzYiIHJ4PSIyLjI1IiBmaWxsPSIjMmU3ZDMyIiBzdHJva2U9IiMxYjVlMjAiIHN0cm9rZS13aWR0aD0iLjc1Ii8+CjxnIGZpbGw9IiNlOGY1ZTkiIHN0cm9rZS13aWR0aD0iLjA5Mzc1Ij4KPHJlY3QgeD0iOSIgeT0iMTIiIHdpZHRoPSIzMCIgaGVpZ2h0PSIxLjUiIHJ4PSIuMzc1Ii8+CjxyZWN0IHg9IjkiIHk9IjE1Ljc1IiB3aWR0aD0iMjYuMjUiIGhlaWdodD0iMS41IiByeD0iLjM3NSIvPgo8cmVjdCB4PSI5IiB5PSIxOS41IiB3aWR0aD0iMjIuNSIgaGVpZ2h0PSIxLjUiIHJ4PSIuMzc1Ii8+CjxyZWN0IHg9IjkiIHk9IjIzLjI1IiB3aWR0aD0iMzAiIGhlaWdodD0iMS41IiByeD0iLjM3NSIvPgo8cmVjdCB4PSI5IiB5PSIyNyIgd2lkdGg9IjI2LjI1IiBoZWlnaHQ9IjEuNSIgcng9Ii4zNzUiLz4KPHJlY3QgeD0iOSIgeT0iMzAuNzUiIHdpZHRoPSIyMi41IiBoZWlnaHQ9IjEuNSIgcng9Ii4zNzUiLz4KPHRleHQgeD0iMjQiIHk9IjM5LjM3NSIgZm9udC1mYW1pbHk9IidTYXJhc2EgVGVybSBTQyBOZXJkXFxcXFxcXFxcXFxcXFxcJycsICdNYXBsZSBNb25vIENOJywgVWJ1bnR1LCBSb2JvdG8sICdPcGVuIFNhbnMnLCAnTWljcm9zb2Z0IFlhSGVpJywgQXJpYWwsIHNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iNC41cHgiIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj4mbHQ7TUgmZ3Q7PC90ZXh0Pgo8L2c+Cjwvc3ZnPgo="
/>
<meta name="viewport" content="width=256, initial-scale=1" />
<script
defer
src="https://lib.baomitu.com/marked/4.0.2/marked.min.js"
type="application/javascript"
></script>
<script
src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"
type="application/javascript"
></script>
<script
src="https://lib.baomitu.com/translate.js/3.17.0/translate.js"
type="application/javascript"
></script>
<script
src="https://lib.baomitu.com/Darkmode.js/1.5.7/darkmode-js.min.js"
type="application/javascript"
></script>
<script
src="https://lib.baomitu.com/mermaid/8.14.0/mermaid.min.js"
type="application/javascript"
></script>
<script
src="https://lib.baomitu.com/highlight.js/11.4.0/highlight.min.js"
type="application/javascript"
></script>
<script>
// 使用 IIFE 包裹以避免全局变量污染
(function () {
function getVersion() {
const markdownElement = document.querySelector("markdown-html");
if (markdownElement) {
const version = markdownElement.getAttribute("version");
return version;
} else {
return "未知";
}
}
function getAbout() {
return `
# 关于
## MARKDOWN.HTML
版本:${getVersion()}
旨在提供低依赖、一键部署的 Markdown 网页渲染方案。
### 特性
- **依赖少**:仅需一个 HTML 文件,即可完成 Markdown 网页渲染。
- **Markdown 支持**:将 Markdown 文件渲染为 HTML。
- **Mermaid 支持**:将 Markdown 中的 Mermaid 语法渲染为图表。
- **多语言支持**:支持多种语言间的机器互译。
- **深色模式**:支持浅色、深色、跟随系统。
- **Pjax 支持**:支持无刷新页面跳转。
详情请访问 [GitHub](https://github.com/PJ-568/MARKDOWN.HTML) 或 [Gitee](https://gitee.com/PJ-568/MARKDOWN.HTML) 仓库。
`;
}
// 加载动画相关
var loadingState = {
countLoading: 0,
};
Object.defineProperty(loadingState, "countLoading", {
get: function () {
return this._countLoading;
},
set: function (newValue) {
if (newValue < 0) {
newValue = 0;
}
const loadingBar = document.querySelector(".loading-bar");
const progress = document.querySelector(".loading-bar .progress");
if (this.countLoading === 0 && newValue > 0) {
var loadingBarWidth = 20;
var MAX_LOADING_WIDTH = 95;
loadingBar.classList.add("loading");
progress.style.width = loadingBarWidth + "%";
clearInterval(timer);
timer = setInterval(function () {
loadingBarWidth += 3;
if (loadingBarWidth > MAX_LOADING_WIDTH) {
loadingBarWidth = MAX_LOADING_WIDTH;
}
progress.style.width = loadingBarWidth + "%";
}, 500);
} else if (this.countLoading > 0 && newValue === 0) {
clearInterval(timer);
progress.style.width = "100%";
loadingBar.classList.remove("loading");
setTimeout(function () {
progress.style.width = 0;
}, 400);
}
this._countLoading = newValue;
},
});
loadingState.countLoading = 0;
function startLoad() {
loadingState.countLoading = loadingState.countLoading + 1;
}
function endLoad() {
loadingState.countLoading = loadingState.countLoading - 1;
}
var timer = null;
// 文档解析功能相关
var notExistIndexPage = null; // 是否不存在索引页
var pValue = null;
async function getPValue() {
if (pValue) {
return pValue;
} else {
return await decodeMDPath(window.location.href);
}
}
// PJAX 相关
let PJAX;
// 深色模式相关
let darkmode;
// 自定义 PJAX 相关
const existPushState = history && history.pushState;
var level = 1; // 当前页面的层级
var lastLevel = 0;
// 初始化 PJAX
function initPJAX() {
try {
const Pjax =
window.Pjax ||
function () {
console.warn("Pjax 不存在?");
};
PJAX = new Pjax({
selectors: ["head title", ".markdown-body", ".pjax-reload"],
switches: {
".markdown-body": Pjax.switches.sideBySide,
},
switchesOptions: {
".markdown-body": {
classNames: {
remove:
"Animated Animated-remove Animated--reverse Animate--fast Animate--noDelay",
add: "Animated",
backward: "Animate--slideInRight",
forward: "Animate--slideInLeft",
},
},
},
cacheBust: false,
});
} catch (e) {
console.error("PJAX 初始化出错:" + e);
}
}
// translate-js 翻译系统
//// 初始化翻译系统
function initTranslate() {
try {
translate.service.use("client.edge");
translate.request.listener.start();
translate.setAutoDiscriminateLocalLanguage();
translate.language.setUrlParamControl();
translate.ignore.class.push("notTranslate");
translate.execute();
} catch (e) {
console.error("翻译系统出错:" + e);
}
}
// Darkmode.js 深色模式
function initDarkmode() {
try {
const Darkmode =
window.Darkmode ||
function () {
console.warn("Darkmode.js 不存在?");
};
darkmode = new Darkmode();
} catch (e) {
console.error("初始化 Darkmode.js 出错:" + e);
}
}
//// 检查并提示翻译
function infoTranslate() {
try {
const currentLang = translate.language.getCurrent();
const originalLang = translate.language.getLocal();
if (currentLang !== originalLang) {
const translateInfo =
document.querySelectorAll(".translate-info");
if (translateInfo) {
translateInfo.forEach(function (item) {
item.remove();
});
}
// 获取 .markdown-body 元素
var bq = document.createElement("blockquote");
bq.classList.add("translate-info");
var infoBody = document.createElement("p");
infoBody.innerText = "当前页面已翻译。您可以:";
var msgBody = document.createElement("p");
var switchButton = document.createElement("a");
switchButton.classList.add("translate-switch");
switchButton.href = "javascript:;";
switchButton.title = "切换到原语言";
switchButton.innerText = "切换到文章原本的语言";
bq.appendChild(infoBody);
bq.appendChild(switchButton);
const mainElement = document.querySelector(
".markdown-body .content",
);
mainElement.insertBefore(bq, mainElement.children[1]);
}
} catch (e) {
console.error("检查并提示翻译出错:" + e);
}
}
//// 刷新翻译
function refreshTranslate() {
try {
translate.selectLanguageTag.refreshRender();
} catch (e) {
console.error("刷新翻译出错:" + e);
}
}
// 获取文件所在目录
function getDirectory(path) {
path = new URL(path, "http://example.com").pathname;
const lastSlashIndex = path.lastIndexOf("/");
return path.substring(0, lastSlashIndex + 1);
}
// 获取 markdown.html 当前所加载的 md 文件的所在路径
function getPath() {
return getDirectory(window.location.href);
}
// 将 ?p= 后面的值转换为绝对路径
/*
输出的值是 /path/to/file.md
当其为 null 时,根据是否存在 index.md 文件来决定返回的值
*/
async function decodeMDPath(path) {
const url = new URL(path);
const params = new URLSearchParams(url.search);
path = formatMDPath(params.get("p"));
return path;
}
// 格式化路径
/*
如果 mdPath 为 null,则返回 null,如果 mdPath 是路径,则返回该路径下 /index.md
return: 返回格式化后的文件路径,一定是绝对路径,或者 null
*/
function formatMDPath(mdPath) {
if (mdPath) {
if (isRelativePath(mdPath)) {
mdPath = getPath() + mdPath;
}
mdPath = new URL(mdPath, "http://example.com").pathname;
if (!mdPath.endsWith(".md")) {
if (!mdPath.endsWith("/")) {
mdPath += "/";
}
mdPath += "index.md";
}
}
return mdPath;
}
// 判断是否为其它协议(是 HTTP(S) 协议)
function isProtocol(url) {
//// 排除特殊协议
const excludedProtocols = [
"#",
"javascript:",
"mailto:",
"tel:",
"data:",
"ftp:",
"about:",
];
if (excludedProtocols.some((proto) => url.startsWith(proto))) {
return false;
} else {
return true;
}
}
// 判断链接是否为外链
function isExternalLink(url) {
if (!url || typeof url !== "string") return false;
if (!isProtocol(url)) {
return false;
}
try {
const currentUrl = new URL(window.location.href);
const targetUrl = new URL(url, currentUrl.origin);
//// 排除非 HTTP(S) 协议
if (!["http:", "https:"].includes(targetUrl.protocol)) return false;
//// 域名统一转小写比较
const currentHost = currentUrl.hostname.toLowerCase();
const targetHost = targetUrl.hostname.toLowerCase();
return currentHost !== targetHost;
} catch (e) {
return false;
}
}
// 判断路径是否为相对路径
function isRelativePath(path) {
return !path.match(/^\//); //// 不以 / 开头
}
// 处理错误
function updateContent(article, title = null, mdPath = pValue) {
try {
document.querySelector(".markdown-body").innerHTML =
`<div class="old-content Animated Animated-remove Animated--reverse Animate--fast Animate--noDelay Animate--slideInLeft">${
document.querySelector(".markdown-body .content").innerHTML
}</div><div class="content Animated Animate--slideInRight">${article}</div>`;
firstH1 = document.querySelector(".markdown-body .content h1");
document.title = title
? title
: firstH1
? firstH1.textContent
: mdPath;
} catch (error) {
throw error;
}
}
// 加载 CSS
function loadCSS(url) {
return new Promise((resolve, reject) => {
//// 检查是否已加载
const existingLinks = document.querySelectorAll(
`link[href="${url}"]`,
);
if (existingLinks.length > 0) {
return resolve(url);
}
//// 创建新的 link 元素
const link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
//// 成功加载处理
link.onload = () => {
link.onload = null;
link.onerror = null;
resolve(url);
};
//// 加载失败处理
link.onerror = () => {
link.onerror = null;
link.onload = null;
document.head.removeChild(link);
reject(new Error(`无法加载 CSS 文件:${url}`));
};
//// 添加到文档头部
document.head.appendChild(link);
});
}
// 等待动画结束
function waitForAnimationsEnd(parentElement, selector, animationNames) {
return new Promise((resolve) => {
var completedCount = 0;
const elements = parentElement.querySelectorAll(selector);
const totalElements = elements.length;
const handleAnimationEnd = function (event) {
if (
animationNames.includes(event.animationName) &&
Array.from(elements).includes(event.target)
) {
completedCount++;
if (completedCount === totalElements) {
parentElement.removeEventListener(
"animationend",
handleAnimationEnd,
);
resolve();
}
}
};
parentElement.addEventListener("animationend", handleAnimationEnd);
});
}
// 处理错误
function handleError(mdPath, errorMessage) {
updateContent(
`<h1>加载失败</h1><p>加载文档<code>${mdPath}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a class="refresh-btn" href="">重新加载</a>或<a class="back-btn">返回</a>。</p>`,
"加载失败",
);
waitForAnimationsEnd(
document.querySelector(".markdown-body"),
".content, .old-content",
["Animation-slideInRight", "Animation-slideInLeft"],
).then(() => {
customPushState(
window.location.origin +
window.location.pathname +
(mdPath ? "?p=" + mdPath : ""),
);
});
endLoad();
}
// 更新页面的 markdown 内容
/*
mdPath: 要加载的 markdown 文件路径,最好是带主机名的绝对路径(要用于 fetch())
response: fetch() 的返回值,用于防止二次访问
*/
const showMarkdown = async (mdPath, response = null) => {
if (mdPath === null) {
var path = null;
const currentPath = getPath();
// 如果存在 index.md 文件,则返回 index.md,否则返回 README.md
if (notExistIndexPage) {
path = currentPath + "README.md";
} else if (notExistIndexPage === false) {
path = currentPath + "index.md";
} else {
response = await fetch(getPath() + "index.md");
if (
response.ok &&
response.headers.get("content-type").startsWith("text/markdown")
) {
notExistIndexPage = false;
path = currentPath + "index.md";
} else {
response = null;
notExistIndexPage = true;
path = currentPath + "README.md";
}
}
} else if (mdPath.endsWith("about.md")) {
// 特殊处理 about.md
response = await fetch(mdPath);
const about = getAbout();
if (
response.ok &&
response.headers.get("content-type").startsWith("text/markdown")
) {
var r_text = await response.text();
const content = about + (await r_text.replace(/^# .*/m, ""));
response = {
ok: true,
status: 200,
statusText: "自生成。",
text: async () => {
return content;
},
};
} else {
response = {
ok: true,
status: 200,
statusText: "自生成。",
text: async () => {
return about + "*无更多详细信息*";
},
};
}
}
try {
pValue = mdPath ? mdPath : path;
updateContent(await getMarkdown(mdPath ? mdPath : path, response));
document.querySelector("html").classList.add("loaded"); //// 防止缓存的页面被自定义 PJAX 中覆写的处理响应的函数捕获
waitForAnimationsEnd(
document.querySelector(".markdown-body"),
".content, .old-content",
["Animation-slideInRight", "Animation-slideInLeft"],
).then(async () => {
await showMarkdownEnded();
customPushState(
window.location.origin +
window.location.pathname +
(mdPath ? "?p=" + mdPath : ""),
);
});
} catch (error) {
handleError(mdPath ? mdPath : path, error);
}
};
// 读取并解析指定文件
const getMarkdown = async (mdPath, response = null) => {
//// 生成目录
function generateOutline(doc) {
const headings = Array.from(
doc.querySelectorAll("h1, h2, h3, h4, h5, h6"),
);
if (headings.length === 0) return "<i>无目录</i>";
var outline = "<ul>";
var stack = [];
headings.forEach((heading) => {
const level = parseInt(heading.tagName.charAt(1));
const id = heading.textContent
.toLowerCase()
.replace(/ /g, "-") //// 将空格替换为连字符
.replace(/[^\w\u4e00-\u9fa5-]/g, ""); //// 保留字母、数字、下划线、中文字符和连字符
//// 设置 id 属性以便链接跳转
heading.setAttribute("id", id);
while (
stack.length > 0 &&
stack[stack.length - 1].level >= level
) {
stack.pop();
outline += "</ul></li>";
}
if (stack.length === 0 || stack[stack.length - 1].level < level) {
outline += "<li><ul>";
} else {
outline += "</li><li>";
}
outline += `<a href="#${id}">${heading.textContent}</a>`;
stack.push({ level: level });
});
while (stack.length > 0) {
outline += "</ul></li>";
stack.pop();
}
outline += "</ul>";
return outline;
}
if (!response) {
response = await fetch(mdPath);
if (
!response.ok &&
response.headers.get("content-type").startsWith("text/markdown")
) {
throw new Error(
"请求失败:" +
mdPath +
"," +
response.headers.get("content-type") +
"," +
response.status +
"," +
response.statusText,
);
}
}
var markdown_content = await response.text();
var content = marked.parse(markdown_content);
//// 因为是在本页面渲染一个其它页面的文档:
//// - 从 content 中获取所有 href 以 .md 结尾的 a 标签;
//// - 遍历这些 a 标签,如果 href 不是外链,则判断 href 是否为相对路径……最后转换为 ?p=<到该文件的绝对路径>
//// - 从 content 中获取所有 img 标签;
//// - 遍历这些 img 标签,如果 src 不是外链,则判断 src 是否为相对路径……最后转换为 <到该文件的绝对路径>
const linkParser = new DOMParser();
const linkDoc = linkParser.parseFromString(
`<div>${content}</div>`,
"text/html",
);
//// 处理所有 a 链接
const mdLinks = linkDoc.querySelectorAll('a[href]:not([href=""])');
mdLinks.forEach((link) => {
const href = link.getAttribute("href");
//// 是相对路径
if (!isExternalLink(href) && isRelativePath(href) && isProtocol(href)) {
var absolutePath = pValue
? getDirectory(mdPath) + href
: getPath() + href;
absolutePath = new URL(absolutePath, "http://example.com")
.pathname;
if (absolutePath.endsWith(".md")) {
link.setAttribute("href", `?p=${absolutePath}`);
} else {
link.setAttribute("href", absolutePath);
}
}
});
//// 处理所有图片
const images = linkDoc.querySelectorAll("img");
images.forEach((img) => {
const src = img.getAttribute("src");
img.setAttribute("loading", "lazy");
if (
src &&
!src.startsWith("data:") &&
!isExternalLink(src) &&
isRelativePath(src)
) {
var absolutePath = pValue
? getDirectory(mdPath) + src
: getPath() + src;
absolutePath = new URL(absolutePath, "http://example.com")
.pathname;
img.setAttribute("src", absolutePath);
}
});
//// 更新处理后的 markdown 内容
content = linkDoc.body.innerHTML.replace(/^<div>|<\/div>$/g, "");
//// 空文件
if (content === "") {
content = "<i>空文件</i>";
}
//// 添加目录
content = `<details class="outline"><summary>${decodeURIComponent(
mdPath,
)}</summary></details><hr>${content}`;
const parser = new DOMParser();
const doc = parser.parseFromString(content, "text/html");
const outline = generateOutline(doc);
doc.querySelector(".outline").innerHTML += outline;
return doc.body.innerHTML;
};
// 初始化自定义 PJAX 响应
function initCustomPJAXResponse() {
//// 覆写 PJAX 处理响应的函数,在内容插入页面之前实现 markdown 的渲染
PJAX._handleResponse = PJAX.handleResponse;
PJAX.handleResponse = async function (
responseText,
request,
href,
options,
) {
if (
/^<!doctype html>[\s\S]*?<html>[\s\S]*?<markdown-html/i.test(
request.responseText,
)
) {
await showMarkdown(await decodeMDPath(href));
} else {
PJAX._handleResponse(responseText, request, href, options);
}
};
}
// 初始化自定义 PJAX 事件监听器
function initCustomPJAXEventListener() {
// 监听自定义链接的点击事件
if (existPushState) {
document
.querySelector(".markdown-body")
.addEventListener("click", async function (event) {
const link = event.target.closest('a[href$=".md"]');
if (link) {
try {
event.preventDefault();
startLoad();
await showMarkdown(await decodeMDPath(link.href));
} catch (e) {
console.error("自定义 PJAX 出错:" + e);
}
}
});
}
}
// 自定义推送状态
function customPushState(url = window.location.href) {
if (existPushState) {
if (level > lastLevel) {
history.pushState(
{ url: url, title: document.title, uid: level },
null,
url,
);
lastLevel = level++;
} else {
lastLevel = level - 1;
}
}
}
// 初始化内容
const initContent = async () => {
try {
await showMarkdown(await getPValue());
} catch (error) {
handleError(await getPValue(), "初始化内容时出错:" + error);
}
};
// 初始化返回首页按钮
function initHomeBtn() {
const homeBtn = document.querySelector(".to-home");
homeBtn.href = window.location.pathname;
}
// 初始化返回首页按钮
function initAboutBtn() {
const aboutBtn = document.querySelector(".about-btn");
aboutBtn.href = `?p=${getDirectory(
window.location.pathname,
)}about.md`;
}
// 初始化
function initialize() {
startLoad(); //// 开始加载动画
initDarkmode(); //// 初始化深色模式
initHomeBtn(); //// 初始化返回首页按钮
initAboutBtn(); //// 初始化关于按钮
initContent(); //// 初始化内容
initTranslate(); //// 初始化页面翻译
initPJAX(); //// 初始化 PJAX
initCustomPJAXResponse(); //// 初始化自定义 PJAX 响应
initCustomPJAXEventListener(); //// 初始化自定义 PJAX 事件监听器
// loadCSS(
// "https://chinese-fonts-cdn.deno.dev/packages/maple-mono-cn/dist/MapleMono-CN-Regular/result.css"
// ); //// 加载字体 CSS,会造成渲染阻塞,暂时禁用
endLoad(); //// 结束加载动画
}
// 触发器
//// 网页加载完毕后触发初始化
window.addEventListener("DOMContentLoaded", () => initialize());
//// 翻译执行完成后触发
translate.listener.renderTaskFinish = function (_task) {
endLoad();
};
//// PJAX 开始时执行的函数
document.addEventListener("pjax:send", function () {
startLoad();
});
//// 监听 PJAX 完成后,重新加载
document.addEventListener("pjax:complete", async function () {
await showMarkdown(await getPValue());
initCustomPJAXEventListener(); //// 重新初始化自定义 PJAX 事件监听器
});
//// 监听 animationend 事件
document.addEventListener(
"animationend",
function handleAnimationEnd(event) {
if (event.animationName === "Animation-slideInRight") {
const element = document.querySelector(".markdown-body .content");
element.classList.remove("Animated");
element.classList.remove("Animate--slideInRight");
} else if (event.animationName === "Animation-slideInLeft") {
document.querySelector(".markdown-body .old-content").remove();
}
},
);
//// 点击事件委托
document.addEventListener("click", function (event) {
const imgOrSvg = event.target.closest(".content img, .content svg");
if (imgOrSvg) {
const url =
imgOrSvg.getAttribute("src") ||
imgOrSvg.getAttribute("xlink:href");
if (url) {
window.open(url, "_blank");
event.preventDefault();
} else {
const newWindow = window.open("", "_blank");
newWindow.document.write(imgOrSvg.outerHTML);
newWindow.document.close();
event.preventDefault();
}
return;
}
if (event.target.closest(".back-btn")) {
window.history.back();
} else if (event.target.closest(".refresh-btn")) {
window.location.reload();
} else if (event.target.closest(".dark-btn")) {
darkmode.toggle();
} else if (event.target.closest(".translate-switch")) {
translate.changeLanguage(translate.language.getLocal());
/* 跳转。禁用原因是有些带有特殊字符的链接会出错或无法跳转
} else if (event.target.closest('.content a[href^="#"]')) {
// 目录平滑移动
const href = event.target.getAttribute('href');
if (href !== '#') {
event.preventDefault();
const targetElement = document.querySelector(href);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth'
});
} else {
console.error(`ID 为 ${targetId} 的元素不存在。`);
}
}
*/
} else if (event.target.closest('.content a[href]:not([href=""])')) {
const href = event.target.getAttribute("href");
if (isExternalLink(href)) {
window.open(href, "_blank");
event.preventDefault();
}
} else if (event.target.closest(".content img, .content svg")) {
const url =
event.target.getAttribute("src") ||
event.target.getAttribute("xlink:href");
if (url) {
window.open(url, "_blank");
event.preventDefault();
} else {
const newWindow = window.open("", "_blank");
newWindow.document.write(imgOrSvg.outerHTML);
newWindow.document.close();
event.preventDefault();
}
}
});
//// 文档内容加载完毕时触发
async function showMarkdownEnded() {
refreshTranslate();
infoTranslate(); //// 检查并提示翻译
await mermaid.init({ noteMargin: 10 }, ".language-mermaid"); //// 初始化 mermaid
translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
hljs.highlightAll(); //// 触发代码块语法高亮
endLoad();
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
//// 浏览器返回时触发
window.onpopstate = function (event) {
if (level > 1) {
--level;
}
};
})();
</script>
<title>加载中</title>
<style>
/* 全局 */
:root,
html,
body,
button,
input,
select,
textarea,
code,
pre {
font-family:
"Sarasa Term SC Nerd", "Maple Mono CN", Ubuntu, Roboto, "Open Sans",
"Microsoft YaHei", Arial, sans-serif;
text-decoration: none;
}
:root,
html,
body {
background-color: #e6e6e6;
}
::selection {
background-color: #dcedc8;
}
body {
margin: 0;
}
a {
color: #66bb6a;
cursor: pointer;
text-decoration: none;
}
a:hover {
color: #2e7d32;
}
/* 背景 */
.background {
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
z-index: -1;
background-color: #e6e6e6;
}
/* 导航栏 */
nav {
position: fixed;
top: 0;
right: 0;
width: min-content;
background-color: #616161;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 1;
}
nav a {
color: #fafafa;
padding: 0.3rem;
transition:
color 0.2s,
background-color 0.2s;
}
nav a:hover {
color: #fff;
background-color: #212121;
}
/* 动画 */
.Animated {
animation-fill-mode: both;
animation-duration: 1s;
}
.Animated-remove {
position: absolute;
}
.Animated--reverse {
animation-direction: reverse;
}
.Animate--fast {
animation-duration: 0.5s;
}
.Animate--noDelay {
animation-delay: 0s !important;
}
.Animate--slideInRight {
animation-name: Animation-slideInRight;
}