1
0

index.html 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. <!doctype html>
  2. <html>
  3. <markdown-html version="1.18.4" 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. if (event.target.closest('.back-btn')) {
  594. window.history.back();
  595. } else if (event.target.closest('.refresh-btn')) {
  596. window.location.reload();
  597. } else if (event.target.closest('.dark-btn')) {
  598. darkmode.toggle();
  599. } else if (event.target.closest('.translate-switch')) {
  600. translate.changeLanguage(translate.language.getLocal());
  601. /* 跳转。禁用原因是有些带有特殊字符的链接会出错或无法跳转
  602. } else if (event.target.closest('.content a[href^="#"]')) {
  603. // 目录平滑移动
  604. const href = event.target.getAttribute('href');
  605. if (href !== '#') {
  606. event.preventDefault();
  607. const targetElement = document.querySelector(href);
  608. if (targetElement) {
  609. targetElement.scrollIntoView({
  610. behavior: 'smooth'
  611. });
  612. } else {
  613. console.error(`ID 为 ${targetId} 的元素不存在。`);
  614. }
  615. }
  616. */
  617. } else if (event.target.closest('.content a[href]:not([href=""])')) {
  618. const href = event.target.getAttribute('href');
  619. if (isExternalLink(href)) {
  620. window.open(href, '_blank');
  621. event.preventDefault();
  622. }
  623. } else if (event.target.closest('.content img, .content svg')) {
  624. const url = event.target.getAttribute('src') || event.target.getAttribute('xlink:href');
  625. if (url) {
  626. window.open(url, '_blank');
  627. event.preventDefault();
  628. } else {
  629. const newWindow = window.open('', '_blank');
  630. newWindow.document.write(imgOrSvg.outerHTML);
  631. newWindow.document.close();
  632. event.preventDefault();
  633. }
  634. }
  635. });
  636. //// 文档内容加载完毕时触发
  637. async function showMarkdownEnded() {
  638. refreshTranslate();
  639. infoTranslate(); //// 检查并提示翻译
  640. await mermaid.init({ noteMargin: 10 }, '.language-mermaid'); //// 初始化 mermaid
  641. translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
  642. hljs.highlightAll(); //// 触发代码块语法高亮
  643. endLoad();
  644. window.scrollTo({
  645. top: 0,
  646. behavior: 'smooth'
  647. });
  648. }
  649. //// 浏览器返回时触发
  650. window.onpopstate = function (event) {
  651. if (level > 1) {
  652. --level;
  653. }
  654. };
  655. })();
  656. </script>
  657. <title>加载中</title>
  658. <style>
  659. /* 全局 */
  660. :root,
  661. html,
  662. body,
  663. button,
  664. input,
  665. select,
  666. textarea,
  667. code,
  668. pre {
  669. font-family: 'Sarasa Term SC Nerd', 'Maple Mono CN', Ubuntu, Roboto, 'Open Sans', 'Microsoft YaHei', Arial, sans-serif;
  670. text-decoration: none;
  671. }
  672. :root,
  673. html,
  674. body {
  675. background-color: #e6e6e6;
  676. }
  677. ::selection {
  678. background-color: #DCEDC8;
  679. }
  680. body {
  681. margin: 0;
  682. }
  683. a {
  684. color: #66BB6A;
  685. cursor: pointer;
  686. text-decoration: none;
  687. }
  688. a:hover {
  689. color: #2E7D32;
  690. }
  691. /* 背景 */
  692. .background {
  693. position: fixed;
  694. left: 0;
  695. top: 0;
  696. height: 100%;
  697. width: 100%;
  698. z-index: -1;
  699. background-color: #e6e6e6;
  700. }
  701. /* 导航栏 */
  702. nav {
  703. position: fixed;
  704. top: 0;
  705. right: 0;
  706. width: min-content;
  707. background-color: #616161;
  708. display: flex;
  709. justify-content: space-between;
  710. align-items: center;
  711. z-index: 1;
  712. }
  713. nav a {
  714. color: #FAFAFA;
  715. padding: .3rem;
  716. transition:
  717. color .2s,
  718. background-color .2s;
  719. }
  720. nav a:hover {
  721. color: #FFF;
  722. background-color: #212121;
  723. }
  724. /* 动画 */
  725. .Animated {
  726. animation-fill-mode: both;
  727. animation-duration: 1s;
  728. }
  729. .Animated-remove {
  730. position: absolute;
  731. }
  732. .Animated--reverse {
  733. animation-direction: reverse
  734. }
  735. .Animate--fast {
  736. animation-duration: .5s
  737. }
  738. .Animate--noDelay {
  739. animation-delay: 0s !important;
  740. }
  741. .Animate--slideInRight {
  742. animation-name: Animation-slideInRight
  743. }
  744. @keyframes Animation-slideInRight {
  745. 0% {
  746. transform: translateX(200%);
  747. }
  748. 100% {
  749. transform: translateX(0);
  750. }
  751. }
  752. .Animate--slideInLeft {
  753. animation-name: Animation-slideInLeft
  754. }
  755. @keyframes Animation-slideInLeft {
  756. 0% {
  757. transform: translateX(-100%);
  758. }
  759. 100% {
  760. transform: translateX(0);
  761. }
  762. }
  763. /* 主要内容 */
  764. .markdown-body {
  765. position: relative;
  766. margin: 3rem auto;
  767. width: 100%;
  768. max-width: 950px;
  769. min-height: 300px;
  770. background-color: #FAFAFA;
  771. color: #212121;
  772. box-sizing: border-box;
  773. overflow-x: hidden;
  774. box-shadow: 0 2px 6px rgba(100, 100, 100, .3);
  775. }
  776. .markdown-body .content,
  777. .markdown-body .old-content {
  778. margin: 2rem;
  779. }
  780. .markdown-body img,
  781. .markdown-body video,
  782. .markdown-body iframe,
  783. .markdown-body object,
  784. .markdown-body embed,
  785. .markdown-body svg,
  786. .markdown-body canvas,
  787. .markdown-body audio {
  788. max-width: 100%;
  789. background-color: rgba(0, 0, 0, 0.05);
  790. }
  791. /* Markdown 样式 */
  792. .markdown-body a {
  793. transition:
  794. color .2s,
  795. background-color .2s;
  796. }
  797. .markdown-body a:hover {
  798. background-color: rgba(255, 255, 255, 0.1);
  799. }
  800. .markdown-body ul,
  801. .markdown-body ol {
  802. padding-left: 2rem;
  803. }
  804. .markdown-body pre {
  805. background-color: rgba(0, 0, 0, 0.05);
  806. padding: .4rem;
  807. border-radius: .1rem;
  808. overflow-y: scroll;
  809. }
  810. .markdown-body code {
  811. font-family: "cousine nerd font mono", monospace;
  812. background-color: rgba(0, 0, 0, 0.05);
  813. font-size: small;
  814. padding: .2rem;
  815. border-radius: .1rem;
  816. }
  817. .markdown-body pre code {
  818. background-color: unset;
  819. font-size: unset;
  820. padding: unset;
  821. border-radius: unset;
  822. }
  823. .markdown-body blockquote {
  824. background-color: rgba(0, 0, 0, 0.05);
  825. font-size: small;
  826. padding: .4rem;
  827. margin: .5rem 2rem;
  828. border-left: 5px solid rgba(0, 0, 0, 0.1);
  829. }
  830. .markdown-body details {
  831. border: 1px solid rgba(0, 0, 0, 0.1);
  832. border-radius: .1rem;
  833. }
  834. .markdown-body summary {
  835. font-size: small;
  836. cursor: pointer;
  837. background-color: rgba(0, 0, 0, 0.05);
  838. padding: .4rem;
  839. font-weight: bold;
  840. }
  841. .markdown-body details a {
  842. margin-left: -2rem;
  843. }
  844. .markdown-body table {
  845. border-spacing: 0;
  846. border-radius: .1rem;
  847. width: 100%;
  848. border-collapse: separate;
  849. border: .1rem solid rgba(0, 0, 0, 0.05);
  850. }
  851. .markdown-body table td,
  852. .markdown-body table th {
  853. border-right: .1rem solid rgba(0, 0, 0, 0.05);
  854. }
  855. .markdown-body table td,
  856. .markdown-body table th {
  857. border-top: .1rem solid rgba(0, 0, 0, 0.05);
  858. }
  859. .markdown-body table td:last-child,
  860. .markdown-body th:last-child {
  861. border-right-color: transparent;
  862. }
  863. .markdown-body table thead tr:first-child>* {
  864. border-top: .1rem solid transparent;
  865. }
  866. /* 加载进度条 */
  867. .loading-bar {
  868. position: fixed;
  869. top: 0;
  870. left: 0;
  871. z-index: 2;
  872. opacity: 0;
  873. transition: opacity .4s linear;
  874. .progress {
  875. position: fixed;
  876. top: 0;
  877. left: 0;
  878. width: 0;
  879. height: 4px;
  880. background-color: #2E7D32;
  881. box-shadow: 0 0 10px rgba(102, 187, 106, .7);
  882. }
  883. &.loading {
  884. opacity: 1;
  885. transition: none;
  886. .progress {
  887. transition: width .4s ease;
  888. }
  889. }
  890. }
  891. /* 翻译按钮相关 */
  892. .translateSelectLanguage {
  893. background-color: #616161;
  894. color: inherit;
  895. z-index: 3;
  896. width: 17%;
  897. height: 100%;
  898. opacity: 0;
  899. cursor: pointer;
  900. position: absolute;
  901. top: 0;
  902. left: 50%;
  903. }
  904. /* 深色模式相关 */
  905. .darkmode--activated .markdown-body img,
  906. .darkmode--activated .markdown-body svg {
  907. isolation: isolate;
  908. mix-blend-mode: difference
  909. }
  910. .darkmode-layer,
  911. .darkmode-toggle {
  912. z-index: 3
  913. }
  914. /* 小屏响应式优化 */
  915. @media only screen and (max-width: 950px) {
  916. html,
  917. body,
  918. .markdown-body {
  919. height: 100%;
  920. }
  921. .markdown-body {
  922. overflow-y: scroll;
  923. min-width: 256px;
  924. top: 0;
  925. margin: 0 0;
  926. }
  927. }
  928. </style>
  929. <link href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-y/highlight.js/11.4.0/styles/default.min.css"
  930. type="text/css" rel="stylesheet" />
  931. </head>
  932. <body>
  933. <!-- 导航栏 -->
  934. <nav>
  935. <a title="返回" class="back-btn">
  936. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  937. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  938. class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-back">
  939. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  940. <path d="M9 11l-4 4l4 4m-4 -4h11a4 4 0 0 0 0 -8h-1" />
  941. </svg>
  942. </a>
  943. <a title="刷新" class="refresh-btn" href="">
  944. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  945. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  946. class="icon icon-tabler icons-tabler-outline icon-tabler-refresh">
  947. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  948. <path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" />
  949. <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
  950. </svg>
  951. </a>
  952. <a title="主页" class="to-home">
  953. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  954. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  955. class="icon icon-tabler icons-tabler-outline icon-tabler-home">
  956. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  957. <path d="M5 12l-2 0l9 -9l9 9l-2 0" />
  958. <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
  959. <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
  960. </svg>
  961. </a>
  962. <a title="更改语言" id="translate">
  963. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  964. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  965. class="icon icon-tabler icons-tabler-outline icon-tabler-language">
  966. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  967. <path d="M4 5h7" />
  968. <path d="M9 3v2c0 4.418 -2.239 8 -5 8" />
  969. <path d="M5 9c0 2.144 2.952 3.908 6.7 4" />
  970. <path d="M12 20l4 -9l4 9" />
  971. <path d="M19.1 18h-6.2" />
  972. </svg>
  973. </a>
  974. <a title="切换显示模式" class="dark-btn" href="javascript:;">
  975. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  976. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  977. class="icon icon-tabler icons-tabler-outline icon-tabler-brightness">
  978. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  979. <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />
  980. <path d="M12 3l0 18" />
  981. <path d="M12 9l4.65 -4.65" />
  982. <path d="M12 14.3l7.37 -7.37" />
  983. <path d="M12 19.6l8.85 -8.85" />
  984. </svg>
  985. </a>
  986. <a title="关于" class="about-btn">
  987. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
  988. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
  989. class="icon icon-tabler icons-tabler-outline icon-tabler-info-circle">
  990. <path stroke="none" d="M0 0h24v24H0z" fill="none" />
  991. <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
  992. <path d="M12 9h.01" />
  993. <path d="M11 12h1v4h1" />
  994. </svg>
  995. </a>
  996. </nav>
  997. <!-- 内容主体 -->
  998. <div class="markdown-body">
  999. <div class="content">
  1000. <h1>加载中……</h1>
  1001. <p>请稍等。</p>
  1002. </div>
  1003. </div>
  1004. <!-- 加载动画 -->
  1005. <div class="loading-bar">
  1006. <div class="progress"></div>
  1007. </div>
  1008. <div class="background"></div>
  1009. <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/instant.page/5.1.0/instantpage.min.js"
  1010. type="text/javascript"></script>
  1011. </body>
  1012. </html>