1
0

index.html 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. <!doctype html>
  2. <html>
  3. <markdown-html version="1.17.1" author="PJ568" repo="https://github.com/PJ-568/markdown.html"
  4. license="CC BY-SA 4.0 International"></markdown-html>
  5. <head>
  6. <meta charset="utf-8">
  7. <meta name="description" content="HTML read markdown">
  8. <meta name="keywords" content="markdown, html, renderer, low-dependency, one-click deployment">
  9. <meta name="author" content="PJ568">
  10. <link rel="icon" type="image/svg+xml"
  11. href="data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiI+CiAgPCEtLSDog4zmma/mlrnlnZfku6PooajmlofmoaMgLS0+CiAgPHJlY3QgeD0iNjQiIHk9IjY0IiB3aWR0aD0iMzg0IiBoZWlnaHQ9IjM4NCIgcng9IjI0IiBmaWxsPSIjMkU3RDMyIiBzdHJva2U9IiMxQjVFMjAiIHN0cm9rZS13aWR0aD0iOCIvPgogIAogIDwhLS0g5paH5qGj5YaF5a6557q/5p2hIC0tPgogIDxyZWN0IHg9Ijk2IiB5PSIxMjgiIHdpZHRoPSIzMjAiIGhlaWdodD0iMTYiIHJ4PSI0IiBmaWxsPSIjRThGNUU5Ii8+CiAgPHJlY3QgeD0iOTYiIHk9IjE2OCIgd2lkdGg9IjI4MCIgaGVpZ2h0PSIxNiIgcng9IjQiIGZpbGw9IiNFOEY1RTkiLz4KICA8cmVjdCB4PSI5NiIgeT0iMjA4IiB3aWR0aD0iMjQwIiBoZWlnaHQ9IjE2IiByeD0iNCIgZmlsbD0iI0U4RjVFOSIvPgogIDxyZWN0IHg9Ijk2IiB5PSIyNDgiIHdpZHRoPSIzMjAiIGhlaWdodD0iMTYiIHJ4PSI0IiBmaWxsPSIjRThGNUU5Ii8+CiAgPHJlY3QgeD0iOTYiIHk9IjI4OCIgd2lkdGg9IjI4MCIgaGVpZ2h0PSIxNiIgcng9IjQiIGZpbGw9IiNFOEY1RTkiLz4KICA8cmVjdCB4PSI5NiIgeT0iMzI4IiB3aWR0aD0iMjQwIiBoZWlnaHQ9IjE2IiByeD0iNCIgZmlsbD0iI0U4RjVFOSIvPgogIAogIDwhLS0g6aG555uu5ZCN56ew57yp5YaZIC0tPgogIDx0ZXh0IHg9IjI1NiIgeT0iNDIwIiBmb250LWZhbWlseT0iU2FyYXNhIFRlcm0gU0MgTmVyZCcsICdNYXBsZSBNb25vIENOJywgVWJ1bnR1LCBSb2JvdG8sICdPcGVuIFNhbnMnLCAnTWljcm9zb2Z0IFlhSGVpJywgQXJpYWwsIHNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iNDgiIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjRThGNUU5Ij4mbHQ7TUgmZ3Q7PC90ZXh0Pgo8L3N2Zz4=">
  12. <meta name="viewport" content="width=256, initial-scale=1">
  13. <script defer src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/marked/4.0.2/marked.min.js"
  14. type="text/javascript"></script>
  15. <script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js" type="text/javascript"></script>
  16. <script src="https://lib.baomitu.com/translate.js/3.7.2/translate.js" type="text/javascript"></script>
  17. <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/Darkmode.js/1.5.7/darkmode-js.min.js"
  18. type="application/javascript"></script>
  19. <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-y/mermaid/8.14.0/mermaid.min.js"
  20. type="application/javascript"></script>
  21. <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-y/highlight.js/11.4.0/highlight.min.js"
  22. type="application/javascript"></script>
  23. <script>
  24. // 使用 IIFE 包裹以避免全局变量污染
  25. (function () {
  26. function getVersion() {
  27. const markdownElement = document.querySelector('markdown-html');
  28. if (markdownElement) {
  29. const version = markdownElement.getAttribute('version');
  30. return version;
  31. } else {
  32. return '未知';
  33. }
  34. }
  35. function getAbout() {
  36. return `
  37. # 关于
  38. ## MARKDOWN.HTML
  39. 版本:${getVersion()}
  40. 旨在提供低依赖、一键部署的 Markdown 网页渲染方案。
  41. ### 特性
  42. - **依赖少**:仅需一个 HTML 文件,即可完成 Markdown 网页渲染。
  43. - **Markdown 支持**:将 Markdown 文件渲染为 HTML。
  44. - **Mermaid 支持**:将 Markdown 中的 Mermaid 语法渲染为图表。
  45. - **多语言支持**:支持多种语言间的机器互译。
  46. - **深色模式**:支持浅色、深色、跟随系统。
  47. - **Pjax 支持**:支持无刷新页面跳转。
  48. 详情请访问 [GitHub](https://github.com/PJ-568/MARKDOWN.HTML) 或 [Gitee](https://gitee.com/PJ-568/MARKDOWN.HTML) 仓库。
  49. `;
  50. }
  51. // 加载动画相关
  52. var loadingState = {
  53. countLoading: 0
  54. };
  55. Object.defineProperty(loadingState, 'countLoading', {
  56. get: function () {
  57. return this._countLoading;
  58. },
  59. set: function (newValue) {
  60. if (newValue < 0) {
  61. newValue = 0;
  62. }
  63. const loadingBar = document.querySelector('.loading-bar');
  64. const progress = document.querySelector('.loading-bar .progress');
  65. if (this.countLoading === 0 && newValue > 0) {
  66. var loadingBarWidth = 20;
  67. var MAX_LOADING_WIDTH = 95;
  68. loadingBar.classList.add('loading');
  69. progress.style.width = loadingBarWidth + '%';
  70. clearInterval(timer);
  71. timer = setInterval(function () {
  72. loadingBarWidth += 3;
  73. if (loadingBarWidth > MAX_LOADING_WIDTH) {
  74. loadingBarWidth = MAX_LOADING_WIDTH;
  75. }
  76. progress.style.width = loadingBarWidth + '%';
  77. }, 500);
  78. } else if (this.countLoading > 0 && newValue === 0) {
  79. clearInterval(timer);
  80. progress.style.width = '100%';
  81. loadingBar.classList.remove('loading');
  82. setTimeout(function () {
  83. progress.style.width = 0;
  84. }, 400);
  85. }
  86. this._countLoading = newValue;
  87. }
  88. });
  89. loadingState.countLoading = 0;
  90. function startLoad() {
  91. loadingState.countLoading = loadingState.countLoading + 1;
  92. }
  93. function endLoad() {
  94. loadingState.countLoading = loadingState.countLoading - 1;
  95. }
  96. var timer = null;
  97. // 文档解析功能相关
  98. var notExistIndexPage = null; // 是否不存在索引页
  99. var pValue = null;
  100. async function getPValue() {
  101. if (pValue) {
  102. return pValue;
  103. } else {
  104. return await decodeMDPath(window.location.href);
  105. }
  106. }
  107. // PJAX 相关
  108. let PJAX;
  109. // 深色模式相关
  110. let darkmode;
  111. // 自定义 PJAX 相关
  112. const existPushState = (history && history.pushState);
  113. var level = 1; // 当前页面的层级
  114. var lastLevel = 0;
  115. // 初始化 PJAX
  116. function initPJAX() {
  117. try {
  118. const Pjax = window.Pjax || function () {
  119. console.warn('Pjax 不存在?');
  120. };
  121. PJAX = new Pjax({
  122. selectors: [
  123. 'head title',
  124. '.markdown-body',
  125. '.pjax-reload'
  126. ],
  127. switches: {
  128. ".markdown-body": Pjax.switches.sideBySide
  129. },
  130. switchesOptions: {
  131. ".markdown-body": {
  132. classNames: {
  133. remove: "Animated Animated-remove Animated--reverse Animate--fast Animate--noDelay",
  134. add: "Animated",
  135. backward: "Animate--slideInRight",
  136. forward: "Animate--slideInLeft"
  137. }
  138. }
  139. },
  140. cacheBust: false
  141. });
  142. } catch (e) {
  143. console.error('PJAX 初始化出错:' + e);
  144. }
  145. }
  146. // translate-js 翻译系统
  147. //// 初始化翻译系统
  148. function initTranslate() {
  149. try {
  150. translate.service.use('client.edge');
  151. translate.request.listener.start();
  152. translate.setAutoDiscriminateLocalLanguage();
  153. translate.language.setUrlParamControl();
  154. translate.ignore.class.push('notTranslate');
  155. translate.execute();
  156. } catch (e) {
  157. console.error('翻译系统出错:' + e);
  158. }
  159. }
  160. // Darkmode.js 深色模式
  161. function initDarkmode() {
  162. try {
  163. const Darkmode = window.Darkmode || function () {
  164. console.warn('Darkmode.js 不存在?');
  165. };
  166. darkmode = new Darkmode();
  167. } catch (e) {
  168. console.error('初始化 Darkmode.js 出错:' + e);
  169. }
  170. }
  171. //// 检查并提示翻译
  172. function infoTranslate() {
  173. try {
  174. const currentLang = translate.language.getCurrent();
  175. const originalLang = translate.language.getLocal();
  176. if (currentLang !== originalLang) {
  177. const translateInfo = document.querySelectorAll('.translate-info');
  178. if (translateInfo) {
  179. translateInfo.forEach(function (item) {
  180. item.remove();
  181. })
  182. }
  183. // 获取 .markdown-body 元素
  184. var bq = document.createElement('blockquote');
  185. bq.classList.add('translate-info');
  186. var infoBody = document.createElement('p');
  187. infoBody.innerText = '当前页面已翻译。您可以:';
  188. var msgBody = document.createElement('p');
  189. var switchButton = document.createElement('a');
  190. switchButton.classList.add('translate-switch');
  191. switchButton.href = 'javascript:;';
  192. switchButton.title = '切换到原语言';
  193. switchButton.innerText = '切换到文章原本的语言';
  194. bq.appendChild(infoBody);
  195. bq.appendChild(switchButton);
  196. const mainElement = document.querySelector('.markdown-body .content');
  197. mainElement.insertBefore(bq, mainElement.children[1]);
  198. }
  199. } catch (e) {
  200. console.error('检查并提示翻译出错:' + e);
  201. }
  202. }
  203. //// 刷新翻译
  204. function refreshTranslate() {
  205. try {
  206. translate.selectLanguageTag.refreshRender();
  207. } catch (e) {
  208. console.error('刷新翻译出错:' + e);
  209. }
  210. }
  211. // 获取文件所在目录
  212. function getDirectory(path) {
  213. path = new URL(path, 'http://example.com').pathname;
  214. const lastSlashIndex = path.lastIndexOf('/');
  215. return path.substring(0, lastSlashIndex + 1);
  216. }
  217. // 获取 markdown.html 当前所加载的 md 文件的所在路径
  218. function getPath() {
  219. return getDirectory(window.location.href);
  220. }
  221. // 将 ?p= 后面的值转换为绝对路径
  222. /*
  223. 输出的值是 /path/to/file.md
  224. 当其为 null 时,根据是否存在 index.md 文件来决定返回的值
  225. */
  226. async function decodeMDPath(path) {
  227. const url = new URL(path);
  228. const params = new URLSearchParams(url.search);
  229. path = formatMDPath(params.get('p'));
  230. return path;
  231. }
  232. // 格式化路径
  233. /*
  234. 如果 mdPath 为 null,则返回 null,如果 mdPath 是路径,则返回该路径下 /index.md
  235. return: 返回格式化后的文件路径,一定是绝对路径,或者 null
  236. */
  237. function formatMDPath(mdPath) {
  238. if (mdPath) {
  239. if (isRelativePath(mdPath)) {
  240. mdPath = getPath() + mdPath;
  241. }
  242. mdPath = new URL(mdPath, 'http://example.com').pathname;
  243. if (!mdPath.endsWith('.md')) {
  244. if (!mdPath.endsWith('/')) {
  245. mdPath += '/';
  246. }
  247. mdPath += 'index.md';
  248. }
  249. }
  250. return mdPath;
  251. }
  252. // 判断链接是否为外链
  253. function isExternalLink(url) {
  254. if (!url || typeof url !== 'string') return false;
  255. //// 排除特殊协议
  256. const excludedProtocols = ['#', 'javascript:', 'mailto:', 'tel:', 'data:'];
  257. if (excludedProtocols.some(proto => url.startsWith(proto))) {
  258. return false;
  259. }
  260. try {
  261. const currentUrl = new URL(window.location.href);
  262. const targetUrl = new URL(url, currentUrl.origin);
  263. //// 排除非 HTTP(S) 协议
  264. if (!['http:', 'https:'].includes(targetUrl.protocol)) return false;
  265. //// 域名统一转小写比较
  266. const currentHost = currentUrl.hostname.toLowerCase();
  267. const targetHost = targetUrl.hostname.toLowerCase();
  268. return currentHost !== targetHost;
  269. } catch (e) {
  270. return false;
  271. }
  272. }
  273. // 判断路径是否为相对路径
  274. function isRelativePath(path) {
  275. return !path.match(/^\//); //// 不以 / 开头
  276. }
  277. // 处理错误
  278. function updateContent(article, title = null, mdPath = null) {
  279. try {
  280. 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>`;
  281. firstH1 = document.querySelector('.markdown-body .content h1');
  282. document.title = title ? title : (firstH1 ? firstH1.textContent : mdPath);
  283. } catch (error) {
  284. throw error;
  285. }
  286. }
  287. // 等待动画结束
  288. function waitForAnimationsEnd(parentElement, selector, animationNames) {
  289. return new Promise(resolve => {
  290. var completedCount = 0;
  291. const elements = parentElement.querySelectorAll(selector);
  292. const totalElements = elements.length;
  293. const handleAnimationEnd = function (event) {
  294. if (animationNames.includes(event.animationName) && Array.from(elements).includes(event.target)) {
  295. completedCount++;
  296. if (completedCount === totalElements) {
  297. parentElement.removeEventListener('animationend', handleAnimationEnd);
  298. resolve();
  299. }
  300. }
  301. };
  302. parentElement.addEventListener('animationend', handleAnimationEnd);
  303. });
  304. }
  305. // 处理错误
  306. function handleError(mdPath, errorMessage) {
  307. updateContent(`<h1>加载失败</h1><p>加载文档<code>${mdPath}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a class="refresh-btn" href="">重新加载</a>或<a class="back-btn">返回</a>。</p>`, '加载失败');
  308. customPushState(window.location.origin + window.location.pathname + '?p=error.md');
  309. waitForAnimationsEnd(document.querySelector('.markdown-body'), '.content, .old-content', ['Animation-slideInRight', 'Animation-slideInLeft']).then(() => {
  310. customPushState(window.location.origin + window.location.pathname + (mdPath ? ('?p=' + mdPath) : ''));
  311. });
  312. endLoad();
  313. }
  314. // 更新页面的 markdown 内容
  315. /*
  316. mdPath: 要加载的 markdown 文件路径,最好是带主机名的绝对路径(要用于 fetch())
  317. response: fetch() 的返回值,用于防止二次访问
  318. */
  319. const showMarkdown = async (mdPath, response = null) => {
  320. if (mdPath === null) {
  321. var path = null;
  322. const currentPath = getPath();
  323. // 如果存在 index.md 文件,则返回 index.md,否则返回 README.md
  324. if (notExistIndexPage) {
  325. path = currentPath + 'README.md';
  326. } else if (notExistIndexPage === false) {
  327. path = currentPath + 'index.md';
  328. } else {
  329. response = await fetch(getPath() + 'index.md');
  330. if (response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  331. notExistIndexPage = false;
  332. path = currentPath + 'index.md';
  333. } else {
  334. response = null;
  335. notExistIndexPage = true;
  336. path = currentPath + 'README.md';
  337. }
  338. }
  339. } else if (mdPath.endsWith('about.md')) {
  340. // 特殊处理 about.md
  341. response = await fetch(mdPath);
  342. const about = getAbout();
  343. if (response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  344. var r_text = await response.text();
  345. const content = about + await r_text.replace(/^# .*/m, '');
  346. response = {
  347. ok: true,
  348. status: 200,
  349. statusText: '自生成。',
  350. text: async () => {
  351. return content;
  352. }
  353. };
  354. } else {
  355. response = {
  356. ok: true,
  357. status: 200,
  358. statusText: '自生成。',
  359. text: async () => {
  360. return about + '*无更多详细信息*';
  361. }
  362. };
  363. }
  364. }
  365. try {
  366. pValue = mdPath ? mdPath : path;
  367. updateContent(await getMarkdown((mdPath ? mdPath : path), response))
  368. document.querySelector('html').classList.add('loaded'); //// 防止缓存的页面被自定义 PJAX 中覆写的处理响应的函数捕获
  369. waitForAnimationsEnd(document.querySelector('.markdown-body'), '.content, .old-content', ['Animation-slideInRight', 'Animation-slideInLeft']).then(async () => {
  370. await showMarkdownEnded();
  371. customPushState(window.location.origin + window.location.pathname + (mdPath ? ('?p=' + mdPath) : ''));
  372. });
  373. } catch (error) {
  374. handleError((mdPath ? mdPath : path), error)
  375. }
  376. }
  377. // 读取并解析指定文件
  378. const getMarkdown = async (mdPath, response = null) => {
  379. // 生成目录
  380. function generateOutline(doc) {
  381. const headings = Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6'));
  382. if (headings.length === 0) return '<i>无目录</i>';
  383. var outline = '<ul>';
  384. var stack = [];
  385. headings.forEach(heading => {
  386. const level = parseInt(heading.tagName.charAt(1));
  387. const id = heading.textContent.toLowerCase()
  388. .replace(/ /g, '-') // 将空格替换为连字符
  389. .replace(/[^\w\u4e00-\u9fa5-]/g, ''); // 保留字母、数字、下划线、中文字符和连字符
  390. // 设置 id 属性以便链接跳转
  391. heading.setAttribute('id', id);
  392. while (stack.length > 0 && stack[stack.length - 1].level >= level) {
  393. stack.pop();
  394. outline += '</ul></li>';
  395. }
  396. if (stack.length === 0 || stack[stack.length - 1].level < level) {
  397. outline += '<li><ul>';
  398. } else {
  399. outline += '</li><li>';
  400. }
  401. outline += `<a href="#${id}">${heading.textContent}</a>`;
  402. stack.push({ level: level });
  403. });
  404. while (stack.length > 0) {
  405. outline += '</ul></li>';
  406. stack.pop();
  407. }
  408. outline += '</ul>';
  409. return outline;
  410. }
  411. if (!response) {
  412. response = await fetch(mdPath);
  413. if (!response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  414. throw new Error('请求失败:' + mdPath + ',' + response.headers.get('content-type') + ',' + response.status + ',' + response.statusText);
  415. }
  416. }
  417. var markdown_content = await response.text();
  418. // 如果 markdown_content 中发现 `[任意标题](路径文件名.md)`
  419. /*
  420. 如果 href 是相对路径,则在其前加上当前读取的文档的绝对路径;
  421. 如果不存在当前读取的文档(默认读取的 index.md 或 README.md),
  422. 则在其前加上 markdown.html 的绝对路径。
  423. */
  424. const links = markdown_content.match(/\[.*\]\(.*\.md\)/g);
  425. if (links) {
  426. links.forEach(link => {
  427. const linkText = link.match(/\[.*\]/)[0].slice(1, -1);
  428. var linkHref = link.match(/\(.*\)/)[0].slice(1, -1);
  429. if (isExternalLink(linkHref)) {
  430. ;
  431. } else if (isRelativePath(linkHref)) {
  432. if (pValue) {
  433. linkHref = getDirectory(mdPath) + linkHref;
  434. } else {
  435. linkHref = getPath() + linkHref;
  436. }
  437. linkHref = new URL(linkHref, 'http://example.com').pathname;
  438. }
  439. const newLink = `[${linkText}](?p=${linkHref})`; // 链接格式与 window.location.search 一致
  440. markdown_content = markdown_content.replace(link, newLink);
  441. });
  442. }
  443. const images = markdown_content.match(/!\[.*\]\(.*\)/g);
  444. if (images) {
  445. images.forEach(image => {
  446. const imageText = image.match(/\[.*\]/)[0].slice(1, -1);
  447. var imageHref = image.match(/\(.*\)/)[0].slice(1, -1);
  448. if (isExternalLink(imageHref)) {
  449. ;
  450. } else if (isRelativePath(imageHref)) {
  451. if (pValue) {
  452. imageHref = getDirectory(mdPath) + imageHref;
  453. } else {
  454. imageHref = getPath() + imageHref;
  455. }
  456. imageHref = new URL(imageHref, 'http://example.com').pathname;
  457. }
  458. const newImage = `![${imageText}](${imageHref})`;
  459. markdown_content = markdown_content.replace(image, newImage);
  460. });
  461. }
  462. var content = marked.parse(markdown_content);
  463. if (content === '') {
  464. content = '<i>空文件</i>';
  465. }
  466. content = `<details class="outline"><summary>${decodeURIComponent(mdPath)}</summary></details><hr>${content}`;
  467. const parser = new DOMParser();
  468. const doc = parser.parseFromString(content, 'text/html');
  469. const outline = generateOutline(doc);
  470. doc.querySelector('.outline').innerHTML += outline;
  471. return doc.body.innerHTML;
  472. };
  473. // 初始化自定义 PJAX 响应
  474. function initCustomPJAXResponse() {
  475. // 覆写 PJAX 处理响应的函数,在内容插入页面之前实现 markdown 的渲染
  476. PJAX._handleResponse = PJAX.handleResponse;
  477. PJAX.handleResponse = async function (responseText, request, href, options) {
  478. if (request.responseText.startsWith('<!doctype html><html><markdown-html') || request.responseText.startsWith(`<!doctype html>
  479. <html>
  480. <markdown-html`)) {
  481. await showMarkdown(await decodeMDPath(href));
  482. } else {
  483. PJAX._handleResponse(responseText, request, href, options);
  484. }
  485. }
  486. }
  487. // 初始化自定义 PJAX 事件监听器
  488. function initCustomPJAXEventListener() {
  489. // 监听自定义链接的点击事件
  490. if (existPushState) {
  491. document.querySelector('.markdown-body').addEventListener('click', async function (event) {
  492. const link = event.target.closest('a[href$=".md"]');
  493. if (link) {
  494. try {
  495. event.preventDefault();
  496. startLoad();
  497. await showMarkdown(await decodeMDPath(link.href));
  498. } catch (e) {
  499. console.error('自定义 PJAX 出错:' + e);
  500. }
  501. }
  502. });
  503. }
  504. }
  505. // 自定义推送状态
  506. function customPushState(url = window.location.href) {
  507. if (existPushState) {
  508. if (level > lastLevel) {
  509. history.pushState({ url: url, title: document.title, uid: level }, null, url);
  510. lastLevel = level++;
  511. } else {
  512. lastLevel = level - 1;
  513. }
  514. }
  515. }
  516. // 初始化内容
  517. const initContent = async () => {
  518. try {
  519. await showMarkdown(await getPValue());
  520. } catch (error) {
  521. handleError(await getPValue(), '初始化内容时出错:' + error);
  522. }
  523. };
  524. // 初始化返回首页按钮
  525. function initHomeBtn() {
  526. const homeBtn = document.querySelector('.to-home');
  527. homeBtn.href = window.location.pathname;
  528. }
  529. // 初始化返回首页按钮
  530. function initAboutBtn() {
  531. const aboutBtn = document.querySelector('.about-btn');
  532. aboutBtn.href = `?p=${getDirectory(window.location.pathname)}about.md`;
  533. }
  534. // 初始化
  535. function initialize() {
  536. initDarkmode(); //// 初始化深色模式
  537. initHomeBtn(); //// 初始化返回首页按钮
  538. initAboutBtn(); //// 初始化关于按钮
  539. initContent(); //// 初始化内容
  540. initTranslate(); //// 初始化页面翻译
  541. initPJAX(); //// 初始化 PJAX
  542. initCustomPJAXResponse(); //// 初始化自定义 PJAX 响应
  543. initCustomPJAXEventListener(); //// 初始化自定义 PJAX 事件监听器
  544. }
  545. // 触发器
  546. //// 网页加载完毕后触发初始化
  547. window.addEventListener('DOMContentLoaded', () => initialize());
  548. //// 翻译执行完成后触发
  549. translate.listener.renderTaskFinish = function (_task) {
  550. endLoad();
  551. }
  552. //// PJAX 开始时执行的函数
  553. document.addEventListener('pjax:send', function () {
  554. startLoad();
  555. });
  556. //// 监听 PJAX 完成后,重新加载
  557. document.addEventListener('pjax:complete', async function () {
  558. await showMarkdown(await getPValue());
  559. initCustomPJAXEventListener(); //// 重新初始化自定义 PJAX 事件监听器
  560. });
  561. //// 监听 animationend 事件
  562. document.addEventListener('animationend', function handleAnimationEnd(event) {
  563. if (event.animationName === 'Animation-slideInRight') {
  564. const element = document.querySelector('.markdown-body .content');
  565. element.classList.remove('Animated');
  566. element.classList.remove('Animate--slideInRight');
  567. } else if (event.animationName === 'Animation-slideInLeft') {
  568. document.querySelector('.markdown-body .old-content').remove();
  569. }
  570. });
  571. //// 点击事件委托
  572. document.addEventListener('click', function (event) {
  573. const imgOrSvg = event.target.closest('.content img, .content svg');
  574. if (imgOrSvg) {
  575. const url = imgOrSvg.getAttribute('src') || imgOrSvg.getAttribute('xlink:href');
  576. if (url) {
  577. window.open(url, '_blank');
  578. event.preventDefault();
  579. } else {
  580. const newWindow = window.open('', '_blank');
  581. newWindow.document.write(imgOrSvg.outerHTML);
  582. newWindow.document.close();
  583. event.preventDefault();
  584. }
  585. return;
  586. }
  587. if (event.target.closest('.back-btn')) {
  588. window.history.back();
  589. } else if (event.target.closest('.refresh-btn')) {
  590. window.location.reload();
  591. } else if (event.target.closest('.dark-btn')) {
  592. darkmode.toggle();
  593. } else if (event.target.closest('.translate-switch')) {
  594. translate.changeLanguage(translate.language.getLocal());
  595. // 跳转。禁用原因是有些带有特殊字符的链接会出错或无法跳转
  596. // } else if (event.target.closest('.content a[href^="#"]')) {
  597. // // 目录平滑移动
  598. // const href = event.target.getAttribute('href');
  599. // if (href !== '#') {
  600. // event.preventDefault();
  601. // const targetElement = document.querySelector(href);
  602. // if (targetElement) {
  603. // targetElement.scrollIntoView({
  604. // behavior: 'smooth'
  605. // });
  606. // } else {
  607. // console.error(`ID 为 ${targetId} 的元素不存在。`);
  608. // }
  609. // }
  610. } else if (event.target.closest('.content a[href]:not([href=""])')) {
  611. const href = event.target.getAttribute('href');
  612. if (isExternalLink(href)) {
  613. window.open(href, '_blank');
  614. event.preventDefault();
  615. }
  616. }
  617. });
  618. //// 文档内容加载完毕时触发
  619. async function showMarkdownEnded() {
  620. refreshTranslate();
  621. infoTranslate(); //// 检查并提示翻译
  622. await mermaid.init({ noteMargin: 10 }, '.language-mermaid'); //// 初始化 mermaid
  623. translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
  624. hljs.highlightAll(); //// 触发代码块语法高亮
  625. endLoad();
  626. window.scrollTo({
  627. top: 0,
  628. behavior: 'smooth'
  629. });
  630. }
  631. //// 浏览器返回时触发
  632. window.onpopstate = function (event) {
  633. if (level > 1) {
  634. --level;
  635. }
  636. };
  637. })();
  638. </script>
  639. <title>加载中</title>
  640. <style>
  641. /* 全局 */
  642. :root,
  643. html,
  644. body,
  645. button,
  646. input,
  647. select,
  648. textarea,
  649. code,
  650. pre {
  651. font-family: 'Sarasa Term SC Nerd', 'Maple Mono CN', Ubuntu, Roboto, 'Open Sans', 'Microsoft YaHei', Arial, sans-serif;
  652. text-decoration: none;
  653. }
  654. :root,
  655. html,
  656. body {
  657. background-color: #e6e6e6;
  658. }
  659. ::selection {
  660. background-color: #DCEDC8;
  661. }
  662. body {
  663. margin: 0;
  664. }
  665. a {
  666. color: #66BB6A;
  667. cursor: pointer;
  668. text-decoration: none;
  669. }
  670. a:hover {
  671. color: #2E7D32;
  672. }
  673. /* 背景 */
  674. .background {
  675. position: fixed;
  676. left: 0;
  677. top: 0;
  678. height: 100%;
  679. width: 100%;
  680. z-index: -1;
  681. background-color: #e6e6e6;
  682. }
  683. /* 导航栏 */
  684. nav {
  685. position: fixed;
  686. top: 0;
  687. right: 0;
  688. width: min-content;
  689. background-color: #616161;
  690. display: flex;
  691. justify-content: space-between;
  692. align-items: center;
  693. z-index: 1;
  694. }
  695. nav a {
  696. color: #FAFAFA;
  697. padding: .3rem;
  698. transition:
  699. color .2s,
  700. background-color .2s;
  701. }
  702. nav a:hover {
  703. color: #FFF;
  704. background-color: #212121;
  705. }
  706. /* 动画 */
  707. .Animated {
  708. animation-fill-mode: both;
  709. animation-duration: 1s;
  710. }
  711. .Animated-remove {
  712. position: absolute;
  713. }
  714. .Animated--reverse {
  715. animation-direction: reverse
  716. }
  717. .Animate--fast {
  718. animation-duration: .5s
  719. }
  720. .Animate--noDelay {
  721. animation-delay: 0s !important;
  722. }
  723. .Animate--slideInRight {
  724. animation-name: Animation-slideInRight
  725. }
  726. @keyframes Animation-slideInRight {
  727. 0% {
  728. transform: translateX(200%);
  729. }
  730. 100% {
  731. transform: translateX(0);
  732. }
  733. }
  734. .Animate--slideInLeft {
  735. animation-name: Animation-slideInLeft
  736. }
  737. @keyframes Animation-slideInLeft {
  738. 0% {
  739. transform: translateX(-100%);
  740. }
  741. 100% {
  742. transform: translateX(0);
  743. }
  744. }
  745. /* 主要内容 */
  746. .markdown-body {
  747. position: relative;
  748. margin: 3rem auto;
  749. width: 100%;
  750. max-width: 950px;
  751. min-height: 300px;
  752. background-color: #FAFAFA;
  753. color: #212121;
  754. box-sizing: border-box;
  755. overflow-x: hidden;
  756. box-shadow: 0 2px 6px rgba(100, 100, 100, .3);
  757. }
  758. .markdown-body .content,
  759. .markdown-body .old-content {
  760. margin: 2rem;
  761. }
  762. .markdown-body img,
  763. .markdown-body video,
  764. .markdown-body iframe,
  765. .markdown-body object,
  766. .markdown-body embed,
  767. .markdown-body svg,
  768. .markdown-body canvas,
  769. .markdown-body audio {
  770. max-width: 100%;
  771. background-color: rgba(0, 0, 0, 0.05);
  772. }
  773. /* Markdown 样式 */
  774. .markdown-body a {
  775. transition:
  776. color .2s,
  777. background-color .2s;
  778. }
  779. .markdown-body a:hover {
  780. background-color: rgba(255, 255, 255, 0.1);
  781. }
  782. .markdown-body ul,
  783. .markdown-body ol {
  784. padding-left: 2rem;
  785. }
  786. .markdown-body pre {
  787. background-color: rgba(0, 0, 0, 0.05);
  788. padding: .4rem;
  789. border-radius: .1rem;
  790. overflow-y: scroll;
  791. }
  792. .markdown-body code {
  793. font-family: "cousine nerd font mono", monospace;
  794. background-color: rgba(0, 0, 0, 0.05);
  795. font-size: small;
  796. padding: .2rem;
  797. border-radius: .1rem;
  798. }
  799. .markdown-body pre code {
  800. background-color: unset;
  801. font-size: unset;
  802. padding: unset;
  803. border-radius: unset;
  804. }
  805. .markdown-body blockquote {
  806. background-color: rgba(0, 0, 0, 0.05);
  807. font-size: small;
  808. padding: .4rem;
  809. margin: .5rem 2rem;
  810. border-left: 5px solid rgba(0, 0, 0, 0.1);
  811. }
  812. .markdown-body details {
  813. border: 1px solid rgba(0, 0, 0, 0.1);
  814. border-radius: .1rem;
  815. }
  816. .markdown-body summary {
  817. font-size: small;
  818. cursor: pointer;
  819. background-color: rgba(0, 0, 0, 0.05);
  820. padding: .4rem;
  821. font-weight: bold;
  822. }
  823. .markdown-body details a {
  824. margin-left: -2rem;
  825. }
  826. .markdown-body table {
  827. border-spacing: 0;
  828. border-radius: .1rem;
  829. width: 100%;
  830. border-collapse: separate;
  831. border: .1rem solid rgba(0, 0, 0, 0.05);
  832. }
  833. .markdown-body table td,
  834. .markdown-body table th {
  835. border-right: .1rem solid rgba(0, 0, 0, 0.05);
  836. }
  837. .markdown-body table td,
  838. .markdown-body table th {
  839. border-top: .1rem solid rgba(0, 0, 0, 0.05);
  840. }
  841. .markdown-body table td:last-child,
  842. .markdown-body th:last-child {
  843. border-right-color: transparent;
  844. }
  845. .markdown-body table thead tr:first-child>* {
  846. border-top: .1rem solid transparent;
  847. }
  848. /* 加载进度条 */
  849. .loading-bar {
  850. position: fixed;
  851. top: 0;
  852. left: 0;
  853. z-index: 2;
  854. opacity: 0;
  855. transition: opacity .4s linear;
  856. .progress {
  857. position: fixed;
  858. top: 0;
  859. left: 0;
  860. width: 0;
  861. height: 4px;
  862. background-color: #2E7D32;
  863. box-shadow: 0 0 10px rgba(102, 187, 106, .7);
  864. }
  865. &.loading {
  866. opacity: 1;
  867. transition: none;
  868. .progress {
  869. transition: width .4s ease;
  870. }
  871. }
  872. }
  873. /* 翻译按钮相关 */
  874. .translateSelectLanguage {
  875. background-color: #616161;
  876. color: inherit;
  877. z-index: 3;
  878. width: 17%;
  879. height: 100%;
  880. opacity: 0;
  881. cursor: pointer;
  882. position: absolute;
  883. top: 0;
  884. left: 50%;
  885. }
  886. /* 深色模式相关 */
  887. .darkmode--activated .markdown-body img,
  888. .darkmode--activated .markdown-body svg {
  889. isolation: isolate;
  890. mix-blend-mode: difference
  891. }
  892. .darkmode-layer,
  893. .darkmode-toggle {
  894. z-index: 3
  895. }
  896. /* 小屏响应式优化 */
  897. @media only screen and (max-width: 950px) {
  898. html,
  899. body,
  900. .markdown-body {
  901. height: 100%;
  902. }
  903. .markdown-body {
  904. overflow-y: scroll;
  905. min-width: 256px;
  906. top: 0;
  907. margin: 0 0;
  908. }
  909. }
  910. </style>
  911. <link href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-y/highlight.js/11.4.0/styles/default.min.css"
  912. type="text/css" rel="stylesheet" />
  913. <link rel="stylesheet"
  914. href="https://chinese-fonts-cdn.deno.dev/packages/maple-mono-cn/dist/MapleMono-CN-Regular/result.css" />
  915. </head>
  916. <body>
  917. <!-- 导航栏 -->
  918. <nav>
  919. <a title="返回" class="back-btn">
  920. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  921. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  922. class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-back">
  923. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  924. <path d="M9 11l-4 4l4 4m-4 -4h11a4 4 0 0 0 0 -8h-1" />
  925. </svg>
  926. </a>
  927. <a title="刷新" class="refresh-btn" href="">
  928. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  929. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  930. class="icon icon-tabler icons-tabler-outline icon-tabler-refresh">
  931. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  932. <path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" />
  933. <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
  934. </svg>
  935. </a>
  936. <a title="主页" class="to-home">
  937. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  938. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  939. class="icon icon-tabler icons-tabler-outline icon-tabler-home">
  940. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  941. <path d="M5 12l-2 0l9 -9l9 9l-2 0" />
  942. <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
  943. <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
  944. </svg>
  945. </a>
  946. <a title="更改语言" id="translate">
  947. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  948. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  949. class="icon icon-tabler icons-tabler-outline icon-tabler-language">
  950. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  951. <path d="M4 5h7" />
  952. <path d="M9 3v2c0 4.418 -2.239 8 -5 8" />
  953. <path d="M5 9c0 2.144 2.952 3.908 6.7 4" />
  954. <path d="M12 20l4 -9l4 9" />
  955. <path d="M19.1 18h-6.2" />
  956. </svg>
  957. </a>
  958. <a title="切换显示模式" class="dark-btn" href="javascript:;">
  959. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  960. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  961. class="icon icon-tabler icons-tabler-outline icon-tabler-brightness">
  962. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  963. <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />
  964. <path d="M12 3l0 18" />
  965. <path d="M12 9l4.65 -4.65" />
  966. <path d="M12 14.3l7.37 -7.37" />
  967. <path d="M12 19.6l8.85 -8.85" />
  968. </svg>
  969. </a>
  970. <a title="关于" class="about-btn">
  971. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  972. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  973. class="icon icon-tabler icons-tabler-outline icon-tabler-info-circle">
  974. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  975. <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
  976. <path d="M12 9h.01" />
  977. <path d="M11 12h1v4h1" />
  978. </svg>
  979. </a>
  980. </nav>
  981. <!-- 内容主体 -->
  982. <div class="markdown-body">
  983. <div class="content">
  984. <h1>加载中……</h1>
  985. <p>请稍等。</p>
  986. </div>
  987. </div>
  988. <!-- 加载动画 -->
  989. <div class="loading-bar">
  990. <div class="progress"></div>
  991. </div>
  992. <div class="background"></div>
  993. <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/instant.page/5.1.0/instantpage.min.js"
  994. type="text/javascript"></script>
  995. </body>
  996. </html>