index.html 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. <!doctype html>
  2. <html>
  3. <!-- 作者:PJ568 -->
  4. <!-- 项目地址:https://github.com/PJ-568/markdown.html/ -->
  5. <!-- 本项目遵循 CC BY-SA 4.0 International 许可协议 -->
  6. <!-- v 1.1.0 -->
  7. <head>
  8. <meta charset="utf-8">
  9. <meta name="description" content="HTML read markdown">
  10. <meta name="viewport" content="width=256, initial-scale=1">
  11. <script defer src="//lib.baomitu.com/marked/4.0.2/marked.min.js" type="text/javascript"></script>
  12. <script src="//lib.baomitu.com/pjax/0.2.8/pjax.min.js" type="text/javascript"></script>
  13. <script src="//lib.baomitu.com/translate.js/3.7.2/translate.js" type="text/javascript"></script>
  14. <script src="//lib.baomitu.com/Darkmode.js/1.5.7/darkmode-js.min.js" type="text/javascript"></script>
  15. <link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/font-awesome/6.0.0/css/all.min.css">
  16. <script>
  17. // 使用 IIFE 包裹以避免全局变量污染
  18. (function () {
  19. // 加载动画相关
  20. var timer = null;
  21. // 文档解析功能相关
  22. var existIndexPage = true; // 是否存在索引页
  23. async function getPValue() {
  24. return await decodeMDPath(window.location.href);
  25. }
  26. // PJAX 相关
  27. let PJAX;
  28. // 深色模式相关
  29. let darkmode;
  30. // 自定义 PJAX 相关
  31. const existPushState = (history && history.pushState);
  32. var level = 1; // 当前页面的层级
  33. var lastLevel = 0;
  34. // 开始加载动画
  35. function startLoad() {
  36. const loadingBar = document.querySelector('.loading-bar');
  37. const progress = document.querySelector('.loading-bar .progress');
  38. var loadingBarWidth = 20;
  39. var MAX_LOADING_WIDTH = 95;
  40. loadingBar.classList.add('loading');
  41. progress.style.width = loadingBarWidth + '%';
  42. clearInterval(timer);
  43. timer = setInterval(function () {
  44. loadingBarWidth += 3;
  45. if (loadingBarWidth > MAX_LOADING_WIDTH) {
  46. loadingBarWidth = MAX_LOADING_WIDTH;
  47. }
  48. progress.style.width = loadingBarWidth + '%';
  49. }, 500);
  50. }
  51. // 停止加载动画
  52. function endLoad() {
  53. const loadingBar = document.querySelector('.loading-bar');
  54. const progress = document.querySelector('.loading-bar .progress');
  55. clearInterval(timer);
  56. progress.style.width = '100%';
  57. loadingBar.classList.remove('loading');
  58. setTimeout(function () {
  59. progress.style.width = 0;
  60. }, 400);
  61. }
  62. // 初始化 PJAX
  63. function initPJAX() {
  64. try {
  65. const Pjax = window.Pjax || function () { };
  66. PJAX = new Pjax({
  67. selectors: [
  68. 'head title',
  69. '#c',
  70. '.pjax-reload'
  71. ],
  72. cacheBust: false
  73. });
  74. } catch (e) {
  75. console.error('PJAX 初始化出错:' + e);
  76. }
  77. }
  78. // translate-js 翻译系统
  79. //// 初始化翻译系统
  80. function initTranslate() {
  81. try {
  82. translate.service.use('client.edge');
  83. translate.request.listener.start();
  84. translate.setAutoDiscriminateLocalLanguage();
  85. translate.language.setUrlParamControl();
  86. translate.ignore.class.push('notTranslate');
  87. translate.execute();
  88. } catch (e) {
  89. console.error('翻译系统出错:' + e);
  90. }
  91. }
  92. // Darkmode.js 深色模式
  93. function initDarkmode() {
  94. try {
  95. const Darkmode = window.Darkmode || function () {
  96. console.warn('Darkmode.js 不存在?');
  97. return;
  98. };
  99. darkmode = new Darkmode();
  100. } catch (e) {
  101. console.error('初始化 Darkmode.js 出错:' + e);
  102. }
  103. }
  104. //// 检查并提示翻译
  105. function infoTranslate() {
  106. try {
  107. var currentLang = translate.language.getCurrent();
  108. var originalLang = translate.language.getLocal();
  109. if (currentLang !== originalLang) {
  110. const translateInfo = document.querySelectorAll('#translate-info');
  111. if (translateInfo) {
  112. translateInfo.forEach(function (item) {
  113. item.remove();
  114. })
  115. }
  116. // 获取 #c 元素
  117. var mainElements = document.querySelector('#c');
  118. var bq = document.createElement('blockquote');
  119. bq.id = 'translate-info';
  120. var infoBody = document.createElement('p');
  121. infoBody.innerText = '当前页面为翻译版本。';
  122. var msgBody = document.createElement('p');
  123. var langIcon = document.createElement('i');
  124. langIcon.classList.add('fa');
  125. langIcon.classList.add('fa-language');
  126. var switchButton = document.createElement('a');
  127. switchButton.id = 'translate-switch';
  128. switchButton.href = 'javascript:;';
  129. switchButton.title = '切换到原语言';
  130. switchButton.innerText = ' 切换到文章原本的语言';
  131. msgBody.appendChild(langIcon);
  132. msgBody.appendChild(switchButton);
  133. bq.appendChild(infoBody);
  134. bq.appendChild(msgBody);
  135. mainElements.insertBefore(bq, mainElements.children[1]);
  136. }
  137. } catch (e) {
  138. console.error('检查并提示翻译出错:' + e);
  139. }
  140. }
  141. //// 刷新翻译
  142. function refreshTranslate() {
  143. try {
  144. translate.selectLanguageTag.refreshRender();
  145. } catch (e) {
  146. console.error('刷新翻译出错:' + e);
  147. }
  148. }
  149. // 获取文件所在目录
  150. function getDirectory(path) {
  151. path = new URL(path, 'http://example.com').pathname;
  152. const lastSlashIndex = path.lastIndexOf('/');
  153. return path.substring(0, lastSlashIndex + 1);
  154. }
  155. // 获取 markdown.html 的当前路径
  156. function getPath() {
  157. return getDirectory(window.location);
  158. }
  159. // 将 ?p= 后面的值转换为绝对路径
  160. /*
  161. 输出的值是 /path/to/file.md
  162. 当其为 null 时,根据是否存在 index.md 文件来决定返回的值
  163. */
  164. async function decodeMDPath(path) {
  165. const url = new URL(path);
  166. const params = new URLSearchParams(url.search);
  167. path = formatMDPath(params.get('p'));
  168. // 如果 path 为 null
  169. if (!path) {
  170. const currentDir = getPath();
  171. // 如果存在 index.md 文件,则返回 index.md,否则返回 README.md
  172. if (existIndexPage) {
  173. const response = await fetch(currentDir + 'index.md');
  174. if (response.ok) {
  175. path = currentDir + 'index.md';
  176. } else {
  177. existIndexPage = false;
  178. path = currentDir + 'README.md';
  179. }
  180. } else {
  181. path = currentDir + 'README.md';
  182. }
  183. }
  184. return path;
  185. }
  186. // 格式化路径
  187. /*
  188. 如果 mdPath 为 null,则返回 null,如果 mdPath 是路径,则返回该路径下 /index.md
  189. return: 返回格式化后的文件路径,一定是绝对路径,或者 null
  190. */
  191. function formatMDPath(mdPath) {
  192. if (mdPath) {
  193. mdPath = new URL(mdPath, 'http://example.com').pathname;
  194. if (!mdPath.endsWith('.md')) {
  195. if (!mdPath.endsWith('/')) {
  196. mdPath += '/';
  197. }
  198. mdPath += 'index.md';
  199. }
  200. }
  201. return mdPath;
  202. }
  203. // 判断路径是否为相对路径
  204. const isRelativePath = (path) => !path.startsWith('/');
  205. // 处理错误
  206. async function handleError(errorMessage) {
  207. document.title = '加载失败'
  208. document.getElementById('c').innerHTML = `<h1>加载失败</h1><p>加载文档<code>${await getPValue()}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a href="">重新加载</a>或<a id="back-btn">返回</a>。</p>`;
  209. }
  210. // 更新页面的 markdown 内容
  211. /*
  212. path: 要加载的 markdown 文件路径,最好是带主机名的绝对路径(要用于 fetch())
  213. response: fetch() 的返回值,用于防止二次访问
  214. */
  215. const showMarkdown = async (mdPath, response = null) => {
  216. try {
  217. const content = await getMarkdown(mdPath, response);
  218. document.getElementById('c').innerHTML = content;
  219. const firstH1 = document.querySelector('h1');
  220. document.title = firstH1 ? firstH1.textContent : mdPath;
  221. showMarkdownEnded();
  222. customPushState(window.location.origin + getPath() + '?p=' + mdPath);
  223. } catch (error) {
  224. handleError(error)
  225. }
  226. }
  227. // 读取并解析指定文件
  228. const getMarkdown = async (mdPath, response = null) => {
  229. // 生成目录
  230. function generateOutline(doc) {
  231. let outline = '<ul>';
  232. let headings = Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6'));
  233. let stack = [];
  234. headings.forEach(heading => {
  235. let level = parseInt(heading.tagName.charAt(1));
  236. // let id = heading.textContent.toLowerCase().replace(/ /g, '-').replace(/[^\w-]/g, '');
  237. // 设置 id 属性以便链接跳转
  238. heading.setAttribute('id', heading.textContent);
  239. while (stack.length > 0 && stack[stack.length - 1].level >= level) {
  240. stack.pop();
  241. outline += '</ul></li>';
  242. }
  243. if (stack.length === 0 || stack[stack.length - 1].level < level) {
  244. outline += '<li><ul>';
  245. } else {
  246. outline += '</li><li>';
  247. }
  248. outline += `<a href="#${heading.textContent}">${heading.textContent}</a>`;
  249. stack.push({ level: level });
  250. });
  251. while (stack.length > 0) {
  252. outline += '</ul></li>';
  253. stack.pop();
  254. }
  255. outline += '</ul>';
  256. return outline;
  257. }
  258. if (!response) {
  259. response = await fetch(mdPath);
  260. if (!response.ok) {
  261. throw new Error('请求失败:' + mdPath + ',' + response.status + ',' + response.statusText);
  262. }
  263. }
  264. var content = marked.parse(await response.text());
  265. content = `<details class="outline"><summary><code>${decodeURIComponent(mdPath)}</code></summary></details><hr>${content}`;
  266. const parser = new DOMParser();
  267. const doc = parser.parseFromString(content, 'text/html');
  268. const outline = generateOutline(doc);
  269. doc.querySelector('.outline').innerHTML += outline;
  270. const links = doc.querySelectorAll('a[href$=".md"]');
  271. const pValue = await getPValue()
  272. links.forEach(link => {
  273. var href = link.getAttribute('href');
  274. /*
  275. 如果 href 是相对路径,则在其前加上当前读取的文档的绝对路径;
  276. 如果不存在当前读取的文档(默认读取的 index.md 或 README.md),
  277. 则在其前加上 markdown.html 的绝对路径。
  278. */
  279. if (isRelativePath(href)) {
  280. if (pValue) {
  281. href = getDirectory(mdPath) + href;
  282. } else {
  283. href = getPath() + href;
  284. }
  285. const absoluteHref = new URL(href, 'http://example.com').pathname;
  286. link.setAttribute('href', `${window.location.pathname}?p=${absoluteHref}`);
  287. } else if (href.startsWith('/')) {
  288. link.setAttribute('href', `${window.location.pathname}?p=${href}`);
  289. }
  290. });
  291. return doc.body.innerHTML;
  292. };
  293. // 初始化自定义 PJAX
  294. function initCustomPJAX() {
  295. // 覆写 PJAX 处理响应的函数,在内容插入页面之前实现 markdown 的渲染
  296. PJAX._handleResponse = PJAX.handleResponse;
  297. PJAX.handleResponse = async function (responseText, request, href, options) {
  298. if (request.responseText.startsWith('<!doctype html>\n<html>\n<!-- 作者:PJ568 -->')) {
  299. await showMarkdown(await decodeMDPath(href));
  300. } else {
  301. PJAX._handleResponse(responseText, request, href, options);
  302. }
  303. }
  304. // 监听自定义链接的点击事件
  305. if (existPushState) {
  306. document.querySelector('#c').addEventListener('click', async function (event) {
  307. const link = event.target.closest('a[href$=".md"]');
  308. if (link) {
  309. try {
  310. event.preventDefault();
  311. startLoad();
  312. await showMarkdown(await decodeMDPath(link.href));
  313. } catch (e) {
  314. console.error('自定义 PJAX 出错:' + e);
  315. }
  316. }
  317. });
  318. }
  319. }
  320. // 自定义推送状态
  321. function customPushState(url = window.location.href) {
  322. if (existPushState) {
  323. if (level > lastLevel) {
  324. history.pushState({ url: url, title: document.title, uid: level }, null, url);
  325. lastLevel = level++;
  326. } else {
  327. lastLevel = level - 1;
  328. }
  329. }
  330. }
  331. // 初始化内容
  332. const initContent = async () => {
  333. try {
  334. await showMarkdown(await getPValue());
  335. } catch (error) {
  336. handleError('初始化内容时出错:', error);
  337. }
  338. };
  339. // 初始化返回首页按钮
  340. function initHomeBtn() {
  341. const homeBtn = document.getElementById('to-home');
  342. homeBtn.href = window.location.pathname;
  343. }
  344. // 初始化
  345. function initialize() {
  346. initDarkmode(); //// 初始化深色模式
  347. initHomeBtn(); //// 初始化返回首页按钮
  348. initContent(); //// 初始化内容
  349. initTranslate(); //// 初始化页面翻译
  350. initPJAX(); //// 初始化 PJAX
  351. initCustomPJAX(); //// 初始化自定义 PJAX
  352. }
  353. // 触发器
  354. //// 网页加载完毕后触发初始化
  355. window.addEventListener('DOMContentLoaded', () => initialize());
  356. //// 翻译执行完成后触发
  357. // translate.listener.renderTaskFinish = function (_task) {
  358. // }
  359. //// PJAX 开始时执行的函数
  360. document.addEventListener('pjax:send', function () {
  361. startLoad();
  362. });
  363. //// 监听 PJAX 完成后,重新加载
  364. document.addEventListener('pjax:complete', function () {
  365. initCustomPJAX(); //// 初始化自定义 PJAX
  366. });
  367. //// 点击事件委托
  368. document.addEventListener('click', function (event) {
  369. if (event.target.closest('#back-btn')) {
  370. window.history.back();
  371. } else if (event.target.closest('#refresh-btn')) {
  372. window.location.reload();
  373. } else if (event.target.closest('#dark_b')) {
  374. darkmode.toggle();
  375. } else if (event.target.closest('#translate-switch')) {
  376. translate.changeLanguage(translate.language.getLocal());
  377. }
  378. });
  379. //// 文档内容加载完毕时触发
  380. function showMarkdownEnded() {
  381. refreshTranslate();
  382. infoTranslate(); //// 检查并提示翻译
  383. translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
  384. endLoad();
  385. document.querySelector('html').classList.add('loaded'); //// 防止缓存的页面被自定义 PJAX 中覆写的处理响应的函数捕获
  386. window.scrollTo({
  387. top: 0,
  388. behavior: 'smooth'
  389. });
  390. }
  391. //// 浏览器返回时触发
  392. window.onpopstate = function (event) {
  393. if (level > 1) {
  394. --level;
  395. }
  396. };
  397. })();
  398. </script>
  399. <title>加载中</title>
  400. <style>
  401. /* 全局 */
  402. * {
  403. font-family: 'Exo', sans-serif;
  404. text-decoration: none;
  405. }
  406. :root {
  407. background-color: #e6e6e6;
  408. }
  409. ::selection {
  410. background-color: #DCEDC8;
  411. }
  412. body {
  413. margin: 0;
  414. }
  415. a {
  416. color: #66BB6A;
  417. cursor: pointer;
  418. text-decoration: none;
  419. }
  420. a:hover {
  421. color: #2E7D32;
  422. }
  423. /* 背景 */
  424. .background {
  425. position: fixed;
  426. left: 0;
  427. top: 0;
  428. height: 100%;
  429. width: 100%;
  430. z-index: -1;
  431. background-color: #e6e6e6;
  432. }
  433. /* 导航栏 */
  434. nav {
  435. position: fixed;
  436. top: 0;
  437. right: 0;
  438. width: min-content;
  439. background-color: #616161;
  440. display: flex;
  441. justify-content: space-between;
  442. align-items: center;
  443. }
  444. nav a {
  445. color: #FAFAFA;
  446. padding: .5rem;
  447. transition:
  448. color .2s,
  449. background-color .2s;
  450. }
  451. nav a:hover {
  452. color: #FFF;
  453. background-color: #212121;
  454. }
  455. /* 主要内容 */
  456. #c {
  457. margin: 3rem auto;
  458. width: 100%;
  459. max-width: 950px;
  460. min-height: 300px;
  461. background-color: #FAFAFA;
  462. color: #212121;
  463. box-sizing: border-box;
  464. overflow-x: hidden;
  465. padding: 30px;
  466. box-shadow: 0 2px 6px rgba(100, 100, 100, .3);
  467. }
  468. #c img,
  469. #c video,
  470. #c iframe,
  471. #c object,
  472. #c embed,
  473. #c svg,
  474. #c canvas,
  475. #c audio {
  476. max-width: 100%;
  477. }
  478. /* Markdown 样式 */
  479. #c a {
  480. transition:
  481. color .2s,
  482. background-color .2s;
  483. }
  484. #c a:hover {
  485. background-color: rgba(255, 255, 255, 0.1);
  486. }
  487. #c ul,
  488. #c ol {
  489. padding-left: 2rem;
  490. }
  491. #c pre {
  492. background-color: rgba(0, 0, 0, 0.05);
  493. padding: .4rem;
  494. border-radius: .1rem;
  495. overflow-y: scroll;
  496. }
  497. #c code {
  498. font-family: "cousine nerd font mono", monospace;
  499. }
  500. #c p code {
  501. background-color: rgba(0, 0, 0, 0.05);
  502. font-size: small;
  503. padding: .2rem;
  504. border-radius: .1rem;
  505. }
  506. #c blockquote {
  507. background-color: rgba(0, 0, 0, 0.05);
  508. font-size: small;
  509. padding: .4rem;
  510. margin: .5rem 2rem;
  511. border-left: 5px solid rgba(0, 0, 0, 0.1);
  512. }
  513. #c details {
  514. border: 1px solid rgba(0, 0, 0, 0.1);
  515. border-radius: .1rem;
  516. }
  517. #c summary {
  518. background-color: rgba(0, 0, 0, 0.05);
  519. padding: .4rem;
  520. font-weight: bold;
  521. }
  522. #c details a {
  523. margin-left: -2rem;
  524. }
  525. #c table {
  526. border-spacing: 0;
  527. border-radius: .1rem;
  528. width: 100%;
  529. border-collapse: separate;
  530. border: .1rem solid rgba(0, 0, 0, 0.05);
  531. }
  532. #c table td,
  533. #c table th {
  534. border-right: .1rem solid rgba(0, 0, 0, 0.05);
  535. }
  536. #c table td,
  537. #c table th {
  538. border-top: .1rem solid rgba(0, 0, 0, 0.05);
  539. }
  540. #c table td:last-child,
  541. #c th:last-child {
  542. border-right-color: transparent;
  543. }
  544. #c table thead tr:first-child>* {
  545. border-top: .1rem solid transparent;
  546. }
  547. /* 加载进度条 */
  548. .loading-bar {
  549. position: fixed;
  550. top: 0;
  551. left: 0;
  552. z-index: 99999;
  553. opacity: 0;
  554. transition: opacity .4s linear;
  555. .progress {
  556. position: fixed;
  557. top: 0;
  558. left: 0;
  559. width: 0;
  560. height: 4px;
  561. background-color: #FFF;
  562. box-shadow: 0 0 10px rgba(102, 187, 106, .7);
  563. }
  564. &.loading {
  565. opacity: 1;
  566. transition: none;
  567. .progress {
  568. transition: width .4s ease;
  569. }
  570. }
  571. }
  572. /* 翻译按钮相关 */
  573. .translateSelectLanguage {
  574. background-color: #616161;
  575. color: inherit;
  576. z-index: 10;
  577. width: 17%;
  578. height: 100%;
  579. opacity: 0;
  580. cursor: pointer;
  581. position: absolute;
  582. top: 0;
  583. left: 50%;
  584. }
  585. /* 深色模式相关 */
  586. .darkmode--activated img,
  587. .darkmode--activated svg {
  588. isolation: isolate;
  589. mix-blend-mode: difference
  590. }
  591. .darkmode-layer,
  592. .darkmode-toggle {
  593. z-index: 2
  594. }
  595. /* 小屏响应式优化 */
  596. @media only screen and (max-width: 950px) {
  597. html,
  598. body,
  599. #c {
  600. height: 100%;
  601. }
  602. #c {
  603. overflow-y: scroll;
  604. min-width: 256px;
  605. top: 0;
  606. margin: 0 0;
  607. }
  608. }
  609. </style>
  610. </head>
  611. <body>
  612. <!-- 导航栏 -->
  613. <nav>
  614. <a title="返回" id="back-btn"><i class="fa fa-backward"></i></a>
  615. <a title="刷新" id="refresh-btn" href=""><i class="fa fa-arrows-rotate"></i></a>
  616. <a title="主页" id="to-home"><i class="fa fa-home"></i></a>
  617. <a title="更改语言" id="translate"><i class="fa fa-language"></i></a>
  618. <a title="切换显示模式" id="dark_b" href="javascript:;"><i class="fa fa-adjust"></i></a>
  619. <a title="关于" href="https://github.com/PJ-568/markdown.html/"><i class="fa fa-info-circle"></i></a>
  620. </nav>
  621. <!-- 内容主体 -->
  622. <div id="c">
  623. <h1>加载中……</h1>
  624. <p>请稍等。</p>
  625. </div>
  626. <!-- 加载动画 -->
  627. <div class="loading-bar">
  628. <div class="progress"></div>
  629. </div>
  630. <div class="background"></div>
  631. <script src="//lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/instant.page/5.1.0/instantpage.min.js"
  632. type="text/javascript"></script>
  633. </body>
  634. </html>