index.html 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. <!doctype html>
  2. <html>
  3. <markdown-html version="1.18.2" 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 = pValue) {
  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. // 加载 CSS
  288. function loadCSS(url) {
  289. return new Promise((resolve, reject) => {
  290. //// 检查是否已加载
  291. const existingLinks = document.querySelectorAll(`link[href="${url}"]`);
  292. if (existingLinks.length > 0) {
  293. return resolve(url);
  294. }
  295. //// 创建新的 link 元素
  296. const link = document.createElement('link');
  297. link.rel = 'stylesheet';
  298. link.type = 'text/css';
  299. link.href = url;
  300. //// 成功加载处理
  301. link.onload = () => {
  302. link.onload = null;
  303. link.onerror = null;
  304. resolve(url);
  305. };
  306. //// 加载失败处理
  307. link.onerror = () => {
  308. link.onerror = null;
  309. link.onload = null;
  310. document.head.removeChild(link);
  311. reject(new Error(`无法加载CSS文件: ${url}`));
  312. };
  313. //// 添加到文档头部
  314. document.head.appendChild(link);
  315. });
  316. }
  317. // 等待动画结束
  318. function waitForAnimationsEnd(parentElement, selector, animationNames) {
  319. return new Promise(resolve => {
  320. var completedCount = 0;
  321. const elements = parentElement.querySelectorAll(selector);
  322. const totalElements = elements.length;
  323. const handleAnimationEnd = function (event) {
  324. if (animationNames.includes(event.animationName) && Array.from(elements).includes(event.target)) {
  325. completedCount++;
  326. if (completedCount === totalElements) {
  327. parentElement.removeEventListener('animationend', handleAnimationEnd);
  328. resolve();
  329. }
  330. }
  331. };
  332. parentElement.addEventListener('animationend', handleAnimationEnd);
  333. });
  334. }
  335. // 处理错误
  336. function handleError(mdPath, errorMessage) {
  337. updateContent(`<h1>加载失败</h1><p>加载文档<code>${mdPath}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a class="refresh-btn" href="">重新加载</a>或<a class="back-btn">返回</a>。</p>`, '加载失败');
  338. waitForAnimationsEnd(document.querySelector('.markdown-body'), '.content, .old-content', ['Animation-slideInRight', 'Animation-slideInLeft']).then(() => {
  339. customPushState(window.location.origin + window.location.pathname + (mdPath ? ('?p=' + mdPath) : ''));
  340. });
  341. endLoad();
  342. }
  343. // 更新页面的 markdown 内容
  344. /*
  345. mdPath: 要加载的 markdown 文件路径,最好是带主机名的绝对路径(要用于 fetch())
  346. response: fetch() 的返回值,用于防止二次访问
  347. */
  348. const showMarkdown = async (mdPath, response = null) => {
  349. if (mdPath === null) {
  350. var path = null;
  351. const currentPath = getPath();
  352. // 如果存在 index.md 文件,则返回 index.md,否则返回 README.md
  353. if (notExistIndexPage) {
  354. path = currentPath + 'README.md';
  355. } else if (notExistIndexPage === false) {
  356. path = currentPath + 'index.md';
  357. } else {
  358. response = await fetch(getPath() + 'index.md');
  359. if (response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  360. notExistIndexPage = false;
  361. path = currentPath + 'index.md';
  362. } else {
  363. response = null;
  364. notExistIndexPage = true;
  365. path = currentPath + 'README.md';
  366. }
  367. }
  368. } else if (mdPath.endsWith('about.md')) {
  369. // 特殊处理 about.md
  370. response = await fetch(mdPath);
  371. const about = getAbout();
  372. if (response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  373. var r_text = await response.text();
  374. const content = about + await r_text.replace(/^# .*/m, '');
  375. response = {
  376. ok: true,
  377. status: 200,
  378. statusText: '自生成。',
  379. text: async () => {
  380. return content;
  381. }
  382. };
  383. } else {
  384. response = {
  385. ok: true,
  386. status: 200,
  387. statusText: '自生成。',
  388. text: async () => {
  389. return about + '*无更多详细信息*';
  390. }
  391. };
  392. }
  393. }
  394. try {
  395. pValue = mdPath ? mdPath : path;
  396. updateContent(await getMarkdown((mdPath ? mdPath : path), response))
  397. document.querySelector('html').classList.add('loaded'); //// 防止缓存的页面被自定义 PJAX 中覆写的处理响应的函数捕获
  398. waitForAnimationsEnd(document.querySelector('.markdown-body'), '.content, .old-content', ['Animation-slideInRight', 'Animation-slideInLeft']).then(async () => {
  399. await showMarkdownEnded();
  400. customPushState(window.location.origin + window.location.pathname + (mdPath ? ('?p=' + mdPath) : ''));
  401. });
  402. } catch (error) {
  403. handleError((mdPath ? mdPath : path), error)
  404. }
  405. }
  406. // 读取并解析指定文件
  407. const getMarkdown = async (mdPath, response = null) => {
  408. //// 生成目录
  409. function generateOutline(doc) {
  410. const headings = Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6'));
  411. if (headings.length === 0) return '<i>无目录</i>';
  412. var outline = '<ul>';
  413. var stack = [];
  414. headings.forEach(heading => {
  415. const level = parseInt(heading.tagName.charAt(1));
  416. const id = heading.textContent.toLowerCase()
  417. .replace(/ /g, '-') //// 将空格替换为连字符
  418. .replace(/[^\w\u4e00-\u9fa5-]/g, ''); //// 保留字母、数字、下划线、中文字符和连字符
  419. //// 设置 id 属性以便链接跳转
  420. heading.setAttribute('id', id);
  421. while (stack.length > 0 && stack[stack.length - 1].level >= level) {
  422. stack.pop();
  423. outline += '</ul></li>';
  424. }
  425. if (stack.length === 0 || stack[stack.length - 1].level < level) {
  426. outline += '<li><ul>';
  427. } else {
  428. outline += '</li><li>';
  429. }
  430. outline += `<a href="#${id}">${heading.textContent}</a>`;
  431. stack.push({ level: level });
  432. });
  433. while (stack.length > 0) {
  434. outline += '</ul></li>';
  435. stack.pop();
  436. }
  437. outline += '</ul>';
  438. return outline;
  439. }
  440. if (!response) {
  441. response = await fetch(mdPath);
  442. if (!response.ok && response.headers.get('content-type').startsWith('text/markdown')) {
  443. throw new Error('请求失败:' + mdPath + ',' + response.headers.get('content-type') + ',' + response.status + ',' + response.statusText);
  444. }
  445. }
  446. var markdown_content = await response.text();
  447. var content = marked.parse(markdown_content);
  448. //// 因为是在本页面渲染一个其它页面的文档:
  449. //// - 从 content 中获取所有 href 以 .md 结尾的 a 标签;
  450. //// - 遍历这些 a 标签,如果 href 不是外链,则判断 href 是否为相对路径……最后转换为 ?p=<到该文件的绝对路径>
  451. //// - 从 content 中获取所有 img 标签;
  452. //// - 遍历这些 img 标签,如果 src 不是外链,则判断 src 是否为相对路径……最后转换为 <到该文件的绝对路径>
  453. const linkParser = new DOMParser();
  454. const linkDoc = linkParser.parseFromString(`<div>${content}</div>`, 'text/html');
  455. //// 处理所有以 .md 结尾的链接
  456. const mdLinks = linkDoc.querySelectorAll('a[href$=".md"]');
  457. mdLinks.forEach(link => {
  458. const href = link.getAttribute('href');
  459. if (!isExternalLink(href) && isRelativePath(href)) {
  460. var absolutePath = pValue ? getDirectory(mdPath) + href : getPath() + href;
  461. absolutePath = new URL(absolutePath, 'http://example.com').pathname;
  462. link.setAttribute('href', `?p=${absolutePath}`);
  463. }
  464. });
  465. //// 处理所有图片
  466. const images = linkDoc.querySelectorAll('img');
  467. images.forEach(img => {
  468. const src = img.getAttribute('src');
  469. img.setAttribute('loading', 'lazy');
  470. if (src && !isExternalLink(src) && isRelativePath(src)) {
  471. var absolutePath = pValue ? getDirectory(mdPath) + src : getPath() + src;
  472. absolutePath = new URL(absolutePath, 'http://example.com').pathname;
  473. img.setAttribute('src', absolutePath);
  474. }
  475. });
  476. //// 更新处理后的 markdown 内容
  477. content = linkDoc.body.innerHTML.replace(/^<div>|<\/div>$/g, '');
  478. //// 空文件
  479. if (content === '') {
  480. content = '<i>空文件</i>';
  481. }
  482. //// 添加目录
  483. content = `<details class="outline"><summary>${decodeURIComponent(mdPath)}</summary></details><hr>${content}`;
  484. const parser = new DOMParser();
  485. const doc = parser.parseFromString(content, 'text/html');
  486. const outline = generateOutline(doc);
  487. doc.querySelector('.outline').innerHTML += outline;
  488. return doc.body.innerHTML;
  489. };
  490. // 初始化自定义 PJAX 响应
  491. function initCustomPJAXResponse() {
  492. //// 覆写 PJAX 处理响应的函数,在内容插入页面之前实现 markdown 的渲染
  493. PJAX._handleResponse = PJAX.handleResponse;
  494. PJAX.handleResponse = async function (responseText, request, href, options) {
  495. if (request.responseText.startsWith('<!doctype html><html><markdown-html') || request.responseText.startsWith(`<!doctype html>
  496. <html>
  497. <markdown-html`)) {
  498. await showMarkdown(await decodeMDPath(href));
  499. } else {
  500. PJAX._handleResponse(responseText, request, href, options);
  501. }
  502. }
  503. }
  504. // 初始化自定义 PJAX 事件监听器
  505. function initCustomPJAXEventListener() {
  506. // 监听自定义链接的点击事件
  507. if (existPushState) {
  508. document.querySelector('.markdown-body').addEventListener('click', async function (event) {
  509. const link = event.target.closest('a[href$=".md"]');
  510. if (link) {
  511. try {
  512. event.preventDefault();
  513. startLoad();
  514. await showMarkdown(await decodeMDPath(link.href));
  515. } catch (e) {
  516. console.error('自定义 PJAX 出错:' + e);
  517. }
  518. }
  519. });
  520. }
  521. }
  522. // 自定义推送状态
  523. function customPushState(url = window.location.href) {
  524. if (existPushState) {
  525. if (level > lastLevel) {
  526. history.pushState({ url: url, title: document.title, uid: level }, null, url);
  527. lastLevel = level++;
  528. } else {
  529. lastLevel = level - 1;
  530. }
  531. }
  532. }
  533. // 初始化内容
  534. const initContent = async () => {
  535. try {
  536. await showMarkdown(await getPValue());
  537. } catch (error) {
  538. handleError(await getPValue(), '初始化内容时出错:' + error);
  539. }
  540. };
  541. // 初始化返回首页按钮
  542. function initHomeBtn() {
  543. const homeBtn = document.querySelector('.to-home');
  544. homeBtn.href = window.location.pathname;
  545. }
  546. // 初始化返回首页按钮
  547. function initAboutBtn() {
  548. const aboutBtn = document.querySelector('.about-btn');
  549. aboutBtn.href = `?p=${getDirectory(window.location.pathname)}about.md`;
  550. }
  551. // 初始化
  552. function initialize() {
  553. startLoad(); //// 开始加载动画
  554. initDarkmode(); //// 初始化深色模式
  555. initHomeBtn(); //// 初始化返回首页按钮
  556. initAboutBtn(); //// 初始化关于按钮
  557. initContent(); //// 初始化内容
  558. initTranslate(); //// 初始化页面翻译
  559. initPJAX(); //// 初始化 PJAX
  560. initCustomPJAXResponse(); //// 初始化自定义 PJAX 响应
  561. initCustomPJAXEventListener(); //// 初始化自定义 PJAX 事件监听器
  562. loadCSS('https://chinese-fonts-cdn.deno.dev/packages/maple-mono-cn/dist/MapleMono-CN-Regular/result.css'); //// 加载字体 CSS
  563. endLoad(); //// 结束加载动画
  564. }
  565. // 触发器
  566. //// 网页加载完毕后触发初始化
  567. window.addEventListener('DOMContentLoaded', () => initialize());
  568. //// 翻译执行完成后触发
  569. translate.listener.renderTaskFinish = function (_task) {
  570. endLoad();
  571. }
  572. //// PJAX 开始时执行的函数
  573. document.addEventListener('pjax:send', function () {
  574. startLoad();
  575. });
  576. //// 监听 PJAX 完成后,重新加载
  577. document.addEventListener('pjax:complete', async function () {
  578. await showMarkdown(await getPValue());
  579. initCustomPJAXEventListener(); //// 重新初始化自定义 PJAX 事件监听器
  580. });
  581. //// 监听 animationend 事件
  582. document.addEventListener('animationend', function handleAnimationEnd(event) {
  583. if (event.animationName === 'Animation-slideInRight') {
  584. const element = document.querySelector('.markdown-body .content');
  585. element.classList.remove('Animated');
  586. element.classList.remove('Animate--slideInRight');
  587. } else if (event.animationName === 'Animation-slideInLeft') {
  588. document.querySelector('.markdown-body .old-content').remove();
  589. }
  590. });
  591. //// 点击事件委托
  592. document.addEventListener('click', function (event) {
  593. const imgOrSvg = event.target.closest('.content img, .content svg');
  594. if (imgOrSvg) {
  595. const url = imgOrSvg.getAttribute('src') || imgOrSvg.getAttribute('xlink:href');
  596. if (url) {
  597. window.open(url, '_blank');
  598. event.preventDefault();
  599. } else {
  600. const newWindow = window.open('', '_blank');
  601. newWindow.document.write(imgOrSvg.outerHTML);
  602. newWindow.document.close();
  603. event.preventDefault();
  604. }
  605. return;
  606. }
  607. if (event.target.closest('.back-btn')) {
  608. window.history.back();
  609. } else if (event.target.closest('.refresh-btn')) {
  610. window.location.reload();
  611. } else if (event.target.closest('.dark-btn')) {
  612. darkmode.toggle();
  613. } else if (event.target.closest('.translate-switch')) {
  614. translate.changeLanguage(translate.language.getLocal());
  615. /* 跳转。禁用原因是有些带有特殊字符的链接会出错或无法跳转
  616. } else if (event.target.closest('.content a[href^="#"]')) {
  617. // 目录平滑移动
  618. const href = event.target.getAttribute('href');
  619. if (href !== '#') {
  620. event.preventDefault();
  621. const targetElement = document.querySelector(href);
  622. if (targetElement) {
  623. targetElement.scrollIntoView({
  624. behavior: 'smooth'
  625. });
  626. } else {
  627. console.error(`ID 为 ${targetId} 的元素不存在。`);
  628. }
  629. }
  630. */
  631. } else if (event.target.closest('.content a[href]:not([href=""])')) {
  632. const href = event.target.getAttribute('href');
  633. if (isExternalLink(href)) {
  634. window.open(href, '_blank');
  635. event.preventDefault();
  636. }
  637. }
  638. });
  639. //// 文档内容加载完毕时触发
  640. async function showMarkdownEnded() {
  641. refreshTranslate();
  642. infoTranslate(); //// 检查并提示翻译
  643. await mermaid.init({ noteMargin: 10 }, '.language-mermaid'); //// 初始化 mermaid
  644. translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
  645. hljs.highlightAll(); //// 触发代码块语法高亮
  646. endLoad();
  647. window.scrollTo({
  648. top: 0,
  649. behavior: 'smooth'
  650. });
  651. }
  652. //// 浏览器返回时触发
  653. window.onpopstate = function (event) {
  654. if (level > 1) {
  655. --level;
  656. }
  657. };
  658. })();
  659. </script>
  660. <title>加载中</title>
  661. <style>
  662. /* 全局 */
  663. :root,
  664. html,
  665. body,
  666. button,
  667. input,
  668. select,
  669. textarea,
  670. code,
  671. pre {
  672. font-family: 'Sarasa Term SC Nerd', 'Maple Mono CN', Ubuntu, Roboto, 'Open Sans', 'Microsoft YaHei', Arial, sans-serif;
  673. text-decoration: none;
  674. }
  675. :root,
  676. html,
  677. body {
  678. background-color: #e6e6e6;
  679. }
  680. ::selection {
  681. background-color: #DCEDC8;
  682. }
  683. body {
  684. margin: 0;
  685. }
  686. a {
  687. color: #66BB6A;
  688. cursor: pointer;
  689. text-decoration: none;
  690. }
  691. a:hover {
  692. color: #2E7D32;
  693. }
  694. /* 背景 */
  695. .background {
  696. position: fixed;
  697. left: 0;
  698. top: 0;
  699. height: 100%;
  700. width: 100%;
  701. z-index: -1;
  702. background-color: #e6e6e6;
  703. }
  704. /* 导航栏 */
  705. nav {
  706. position: fixed;
  707. top: 0;
  708. right: 0;
  709. width: min-content;
  710. background-color: #616161;
  711. display: flex;
  712. justify-content: space-between;
  713. align-items: center;
  714. z-index: 1;
  715. }
  716. nav a {
  717. color: #FAFAFA;
  718. padding: .3rem;
  719. transition:
  720. color .2s,
  721. background-color .2s;
  722. }
  723. nav a:hover {
  724. color: #FFF;
  725. background-color: #212121;
  726. }
  727. /* 动画 */
  728. .Animated {
  729. animation-fill-mode: both;
  730. animation-duration: 1s;
  731. }
  732. .Animated-remove {
  733. position: absolute;
  734. }
  735. .Animated--reverse {
  736. animation-direction: reverse
  737. }
  738. .Animate--fast {
  739. animation-duration: .5s
  740. }
  741. .Animate--noDelay {
  742. animation-delay: 0s !important;
  743. }
  744. .Animate--slideInRight {
  745. animation-name: Animation-slideInRight
  746. }
  747. @keyframes Animation-slideInRight {
  748. 0% {
  749. transform: translateX(200%);
  750. }
  751. 100% {
  752. transform: translateX(0);
  753. }
  754. }
  755. .Animate--slideInLeft {
  756. animation-name: Animation-slideInLeft
  757. }
  758. @keyframes Animation-slideInLeft {
  759. 0% {
  760. transform: translateX(-100%);
  761. }
  762. 100% {
  763. transform: translateX(0);
  764. }
  765. }
  766. /* 主要内容 */
  767. .markdown-body {
  768. position: relative;
  769. margin: 3rem auto;
  770. width: 100%;
  771. max-width: 950px;
  772. min-height: 300px;
  773. background-color: #FAFAFA;
  774. color: #212121;
  775. box-sizing: border-box;
  776. overflow-x: hidden;
  777. box-shadow: 0 2px 6px rgba(100, 100, 100, .3);
  778. }
  779. .markdown-body .content,
  780. .markdown-body .old-content {
  781. margin: 2rem;
  782. }
  783. .markdown-body img,
  784. .markdown-body video,
  785. .markdown-body iframe,
  786. .markdown-body object,
  787. .markdown-body embed,
  788. .markdown-body svg,
  789. .markdown-body canvas,
  790. .markdown-body audio {
  791. max-width: 100%;
  792. background-color: rgba(0, 0, 0, 0.05);
  793. }
  794. /* Markdown 样式 */
  795. .markdown-body a {
  796. transition:
  797. color .2s,
  798. background-color .2s;
  799. }
  800. .markdown-body a:hover {
  801. background-color: rgba(255, 255, 255, 0.1);
  802. }
  803. .markdown-body ul,
  804. .markdown-body ol {
  805. padding-left: 2rem;
  806. }
  807. .markdown-body pre {
  808. background-color: rgba(0, 0, 0, 0.05);
  809. padding: .4rem;
  810. border-radius: .1rem;
  811. overflow-y: scroll;
  812. }
  813. .markdown-body code {
  814. font-family: "cousine nerd font mono", monospace;
  815. background-color: rgba(0, 0, 0, 0.05);
  816. font-size: small;
  817. padding: .2rem;
  818. border-radius: .1rem;
  819. }
  820. .markdown-body pre code {
  821. background-color: unset;
  822. font-size: unset;
  823. padding: unset;
  824. border-radius: unset;
  825. }
  826. .markdown-body blockquote {
  827. background-color: rgba(0, 0, 0, 0.05);
  828. font-size: small;
  829. padding: .4rem;
  830. margin: .5rem 2rem;
  831. border-left: 5px solid rgba(0, 0, 0, 0.1);
  832. }
  833. .markdown-body details {
  834. border: 1px solid rgba(0, 0, 0, 0.1);
  835. border-radius: .1rem;
  836. }
  837. .markdown-body summary {
  838. font-size: small;
  839. cursor: pointer;
  840. background-color: rgba(0, 0, 0, 0.05);
  841. padding: .4rem;
  842. font-weight: bold;
  843. }
  844. .markdown-body details a {
  845. margin-left: -2rem;
  846. }
  847. .markdown-body table {
  848. border-spacing: 0;
  849. border-radius: .1rem;
  850. width: 100%;
  851. border-collapse: separate;
  852. border: .1rem solid rgba(0, 0, 0, 0.05);
  853. }
  854. .markdown-body table td,
  855. .markdown-body table th {
  856. border-right: .1rem solid rgba(0, 0, 0, 0.05);
  857. }
  858. .markdown-body table td,
  859. .markdown-body table th {
  860. border-top: .1rem solid rgba(0, 0, 0, 0.05);
  861. }
  862. .markdown-body table td:last-child,
  863. .markdown-body th:last-child {
  864. border-right-color: transparent;
  865. }
  866. .markdown-body table thead tr:first-child>* {
  867. border-top: .1rem solid transparent;
  868. }
  869. /* 加载进度条 */
  870. .loading-bar {
  871. position: fixed;
  872. top: 0;
  873. left: 0;
  874. z-index: 2;
  875. opacity: 0;
  876. transition: opacity .4s linear;
  877. .progress {
  878. position: fixed;
  879. top: 0;
  880. left: 0;
  881. width: 0;
  882. height: 4px;
  883. background-color: #2E7D32;
  884. box-shadow: 0 0 10px rgba(102, 187, 106, .7);
  885. }
  886. &.loading {
  887. opacity: 1;
  888. transition: none;
  889. .progress {
  890. transition: width .4s ease;
  891. }
  892. }
  893. }
  894. /* 翻译按钮相关 */
  895. .translateSelectLanguage {
  896. background-color: #616161;
  897. color: inherit;
  898. z-index: 3;
  899. width: 17%;
  900. height: 100%;
  901. opacity: 0;
  902. cursor: pointer;
  903. position: absolute;
  904. top: 0;
  905. left: 50%;
  906. }
  907. /* 深色模式相关 */
  908. .darkmode--activated .markdown-body img,
  909. .darkmode--activated .markdown-body svg {
  910. isolation: isolate;
  911. mix-blend-mode: difference
  912. }
  913. .darkmode-layer,
  914. .darkmode-toggle {
  915. z-index: 3
  916. }
  917. /* 小屏响应式优化 */
  918. @media only screen and (max-width: 950px) {
  919. html,
  920. body,
  921. .markdown-body {
  922. height: 100%;
  923. }
  924. .markdown-body {
  925. overflow-y: scroll;
  926. min-width: 256px;
  927. top: 0;
  928. margin: 0 0;
  929. }
  930. }
  931. </style>
  932. <link href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-y/highlight.js/11.4.0/styles/default.min.css"
  933. type="text/css" rel="stylesheet" />
  934. </head>
  935. <body>
  936. <!-- 导航栏 -->
  937. <nav>
  938. <a title="返回" class="back-btn">
  939. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  940. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  941. class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-back">
  942. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  943. <path d="M9 11l-4 4l4 4m-4 -4h11a4 4 0 0 0 0 -8h-1" />
  944. </svg>
  945. </a>
  946. <a title="刷新" class="refresh-btn" href="">
  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-refresh">
  950. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  951. <path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" />
  952. <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
  953. </svg>
  954. </a>
  955. <a title="主页" class="to-home">
  956. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  957. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  958. class="icon icon-tabler icons-tabler-outline icon-tabler-home">
  959. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  960. <path d="M5 12l-2 0l9 -9l9 9l-2 0" />
  961. <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
  962. <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
  963. </svg>
  964. </a>
  965. <a title="更改语言" id="translate">
  966. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  967. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  968. class="icon icon-tabler icons-tabler-outline icon-tabler-language">
  969. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  970. <path d="M4 5h7" />
  971. <path d="M9 3v2c0 4.418 -2.239 8 -5 8" />
  972. <path d="M5 9c0 2.144 2.952 3.908 6.7 4" />
  973. <path d="M12 20l4 -9l4 9" />
  974. <path d="M19.1 18h-6.2" />
  975. </svg>
  976. </a>
  977. <a title="切换显示模式" class="dark-btn" href="javascript:;">
  978. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  979. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  980. class="icon icon-tabler icons-tabler-outline icon-tabler-brightness">
  981. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  982. <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />
  983. <path d="M12 3l0 18" />
  984. <path d="M12 9l4.65 -4.65" />
  985. <path d="M12 14.3l7.37 -7.37" />
  986. <path d="M12 19.6l8.85 -8.85" />
  987. </svg>
  988. </a>
  989. <a title="关于" class="about-btn">
  990. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  991. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  992. class="icon icon-tabler icons-tabler-outline icon-tabler-info-circle">
  993. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  994. <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
  995. <path d="M12 9h.01" />
  996. <path d="M11 12h1v4h1" />
  997. </svg>
  998. </a>
  999. </nav>
  1000. <!-- 内容主体 -->
  1001. <div class="markdown-body">
  1002. <div class="content">
  1003. <h1>加载中……</h1>
  1004. <p>请稍等。</p>
  1005. </div>
  1006. </div>
  1007. <!-- 加载动画 -->
  1008. <div class="loading-bar">
  1009. <div class="progress"></div>
  1010. </div>
  1011. <div class="background"></div>
  1012. <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/instant.page/5.1.0/instantpage.min.js"
  1013. type="text/javascript"></script>
  1014. </body>
  1015. </html>