1
0

index.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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.0.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. const _isSameDomain = (url) => {
  207. const currentDomain = window.location.origin;
  208. const targetDomain = new URL(url).origin;
  209. return currentDomain === targetDomain;
  210. }
  211. // 处理错误
  212. async function handleError(errorMessage) {
  213. document.title = '加载失败'
  214. document.getElementById('c').innerHTML = `<h1>加载失败</h1><p>加载文档<code>${await getPValue()}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a href="">重新加载</a>或<a id="back-btn">返回</a>。</p>`;
  215. }
  216. // 更新页面的 markdown 内容
  217. /*
  218. path: 要加载的 markdown 文件路径,最好是带主机名的绝对路径(要用于 fetch())
  219. response: fetch() 的返回值,用于防止二次访问
  220. */
  221. const showMarkdown = async (mdPath, response = null) => {
  222. try {
  223. const content = await getMarkdown(mdPath, response);
  224. document.getElementById('c').innerHTML = content;
  225. const firstH1 = document.querySelector('h1');
  226. document.title = firstH1 ? firstH1.textContent : mdPath;
  227. showMarkdownEnded();
  228. customPushState(window.location.origin + getPath() + '?p=' + mdPath);
  229. } catch (error) {
  230. handleError(error)
  231. }
  232. }
  233. // 读取并解析指定文件
  234. const getMarkdown = async (mdPath, response = null) => {
  235. if (!response) {
  236. response = await fetch(mdPath);
  237. if (!response.ok) {
  238. throw new Error('请求失败:' + mdPath + ',' + response.status + ',' + response.statusText);
  239. }
  240. }
  241. var content = marked.parse(await response.text());
  242. content = `<blockquote><code>${decodeURIComponent(mdPath)}</code></blockquote>${content}`;
  243. const parser = new DOMParser();
  244. const doc = parser.parseFromString(content, 'text/html');
  245. const links = doc.querySelectorAll('a[href$=".md"]');
  246. const pValue = await getPValue()
  247. links.forEach(link => {
  248. var href = link.getAttribute('href');
  249. /*
  250. 如果 href 是相对路径,则在其前加上当前读取的文档的绝对路径;
  251. 如果不存在当前读取的文档(默认读取的 index.md 或 README.md),
  252. 则在其前加上 markdown.html 的绝对路径。
  253. */
  254. if (isRelativePath(href)) {
  255. if (pValue) {
  256. href = getDirectory(mdPath) + href;
  257. } else {
  258. href = getPath() + href;
  259. }
  260. const absoluteHref = new URL(href, 'http://example.com').pathname;
  261. link.setAttribute('href', `${window.location.pathname}?p=${absoluteHref}`);
  262. } else if (href.startsWith('/')) {
  263. link.setAttribute('href', `${window.location.pathname}?p=${href}`);
  264. }
  265. });
  266. return doc.body.innerHTML;
  267. };
  268. // 初始化自定义 PJAX
  269. function initCustomPJAX() {
  270. // 覆写 PJAX 处理响应的函数,在内容插入页面之前实现 markdown 的渲染
  271. PJAX._handleResponse = PJAX.handleResponse;
  272. PJAX.handleResponse = async function (responseText, request, href, options) {
  273. if (request.responseText.startsWith('<!doctype html>\n<html>\n<!-- 作者:PJ568 -->')) {
  274. await showMarkdown(await decodeMDPath(href));
  275. } else {
  276. PJAX._handleResponse(responseText, request, href, options);
  277. }
  278. }
  279. // 监听自定义链接的点击事件
  280. if (existPushState) {
  281. document.querySelector('#c').addEventListener('click', async function (event) {
  282. const link = event.target.closest('a[href$=".md"]');
  283. if (link) {
  284. try {
  285. event.preventDefault();
  286. startLoad();
  287. await showMarkdown(await decodeMDPath(link.href));
  288. } catch (e) {
  289. console.error('自定义 PJAX 出错:' + e);
  290. }
  291. }
  292. });
  293. }
  294. }
  295. // 自定义推送状态
  296. function customPushState(url = window.location.href) {
  297. if (existPushState) {
  298. if (level > lastLevel) {
  299. history.pushState({ url: url, title: document.title, uid: level }, null, url);
  300. lastLevel = level++;
  301. } else {
  302. lastLevel = level - 1;
  303. }
  304. }
  305. }
  306. // 初始化内容
  307. const initContent = async () => {
  308. try {
  309. await showMarkdown(await getPValue());
  310. } catch (error) {
  311. handleError('初始化内容时出错:', error);
  312. }
  313. };
  314. // 初始化返回首页按钮
  315. function initHomeBtn() {
  316. const homeBtn = document.getElementById('to-home');
  317. homeBtn.href = window.location.pathname;
  318. }
  319. // 初始化
  320. function initialize() {
  321. initDarkmode(); //// 初始化深色模式
  322. initHomeBtn(); //// 初始化返回首页按钮
  323. initContent(); //// 初始化内容
  324. initTranslate(); //// 初始化页面翻译
  325. initPJAX(); //// 初始化 PJAX
  326. initCustomPJAX(); //// 初始化自定义 PJAX
  327. }
  328. // 触发器
  329. //// 网页加载完毕后触发初始化
  330. window.addEventListener('DOMContentLoaded', () => initialize());
  331. //// 翻译执行完成后触发
  332. // translate.listener.renderTaskFinish = function (_task) {
  333. // }
  334. //// PJAX 开始时执行的函数
  335. document.addEventListener('pjax:send', function () {
  336. startLoad();
  337. });
  338. //// 监听 PJAX 完成后,重新加载
  339. document.addEventListener('pjax:complete', function () {
  340. initCustomPJAX(); //// 初始化自定义 PJAX
  341. });
  342. //// 点击事件委托
  343. document.addEventListener('click', function (event) {
  344. if (event.target.closest('#back-btn')) {
  345. window.history.back();
  346. } else if (event.target.closest('#dark_b')) {
  347. darkmode.toggle();
  348. } else if (event.target.closest('#translate-switch')) {
  349. translate.changeLanguage(translate.language.getLocal());
  350. }
  351. });
  352. //// 文档内容加载完毕时触发
  353. function showMarkdownEnded() {
  354. refreshTranslate();
  355. infoTranslate(); //// 检查并提示翻译
  356. translate.execute(); //// 手动触发翻译,但是理论上 translate-js 会监听页面变化
  357. endLoad();
  358. document.querySelector('html').classList.add('loaded'); //// 防止缓存的页面被自定义 PJAX 中覆写的处理响应的函数捕获
  359. }
  360. //// 浏览器返回时触发
  361. window.onpopstate = function (event) {
  362. if (level > 1) {
  363. --level;
  364. }
  365. };
  366. })();
  367. </script>
  368. <title>加载中</title>
  369. <style>
  370. /* 全局 */
  371. * {
  372. font-family: 'Exo', sans-serif;
  373. text-decoration: none;
  374. }
  375. :root {
  376. background-color: #e6e6e6;
  377. }
  378. ::selection {
  379. background-color: #DCEDC8;
  380. }
  381. body {
  382. margin: 0;
  383. }
  384. a {
  385. color: #66BB6A;
  386. cursor: pointer;
  387. text-decoration: none;
  388. }
  389. a:hover {
  390. color: #2E7D32;
  391. }
  392. /* 背景 */
  393. .background {
  394. position: fixed;
  395. left: 0;
  396. top: 0;
  397. height: 100%;
  398. width: 100%;
  399. z-index: -1;
  400. background-color: #e6e6e6;
  401. }
  402. /* 导航栏 */
  403. nav {
  404. position: fixed;
  405. top: 0;
  406. right: 0;
  407. width: min-content;
  408. background-color: #616161;
  409. display: flex;
  410. justify-content: space-between;
  411. align-items: center;
  412. }
  413. nav a {
  414. color: #FAFAFA;
  415. padding: .5rem;
  416. transition:
  417. color .2s,
  418. background-color .2s;
  419. }
  420. nav a:hover {
  421. color: #FFF;
  422. background-color: #212121;
  423. }
  424. /* 主要内容 */
  425. #c {
  426. margin: 3rem auto;
  427. width: 100%;
  428. max-width: 950px;
  429. min-height: 300px;
  430. background-color: #FAFAFA;
  431. color: #212121;
  432. box-sizing: border-box;
  433. overflow-x: hidden;
  434. padding: 30px;
  435. box-shadow: 0 2px 6px rgba(100, 100, 100, .3);
  436. }
  437. #c img,
  438. #c video,
  439. #c iframe,
  440. #c object,
  441. #c embed,
  442. #c svg,
  443. #c canvas,
  444. #c audio {
  445. max-width: 100%;
  446. }
  447. /* Markdown 样式 */
  448. #c a {
  449. transition:
  450. color .2s,
  451. background-color .2s;
  452. }
  453. #c a:hover {
  454. background-color: rgba(255, 255, 255, 0.1);
  455. }
  456. #c pre {
  457. background-color: rgba(0, 0, 0, 0.05);
  458. padding: .4rem;
  459. border-radius: .5rem;
  460. overflow-y: scroll;
  461. }
  462. #c code {
  463. font-family: "cousine nerd font mono", monospace;
  464. }
  465. #c p code {
  466. background-color: rgba(0, 0, 0, 0.05);
  467. font-size: small;
  468. padding: .2rem;
  469. border-radius: .1rem;
  470. }
  471. #c blockquote {
  472. background-color: rgba(0, 0, 0, 0.05);
  473. font-size: small;
  474. padding: .4rem;
  475. border-left: 5px solid rgba(0, 0, 0, 0.1);
  476. }
  477. #c table {
  478. border-spacing: 0;
  479. border-radius: .1rem;
  480. width: 100%;
  481. border-collapse: separate;
  482. border: .1rem solid rgba(0, 0, 0, 0.05);
  483. }
  484. #c table td,
  485. #c table th {
  486. border-right: .1rem solid rgba(0, 0, 0, 0.05);
  487. }
  488. #c table td,
  489. #c table th {
  490. border-top: .1rem solid rgba(0, 0, 0, 0.05);
  491. }
  492. #c table td:last-child,
  493. #c th:last-child {
  494. border-right-color: transparent;
  495. }
  496. #c table thead tr:first-child>* {
  497. border-top: .1rem solid transparent;
  498. }
  499. /* 加载进度条 */
  500. .loading-bar {
  501. position: fixed;
  502. top: 0;
  503. left: 0;
  504. z-index: 99999;
  505. opacity: 0;
  506. transition: opacity .4s linear;
  507. .progress {
  508. position: fixed;
  509. top: 0;
  510. left: 0;
  511. width: 0;
  512. height: 4px;
  513. background-color: #FFF;
  514. box-shadow: 0 0 10px rgba(102, 187, 106, .7);
  515. }
  516. &.loading {
  517. opacity: 1;
  518. transition: none;
  519. .progress {
  520. transition: width .4s ease;
  521. }
  522. }
  523. }
  524. /* 翻译按钮相关 */
  525. .translateSelectLanguage {
  526. background-color: #616161;
  527. color: inherit;
  528. z-index: 10;
  529. width: 17%;
  530. height: 100%;
  531. opacity: 0;
  532. cursor: pointer;
  533. position: absolute;
  534. top: 0;
  535. left: 50%;
  536. }
  537. /* 深色模式相关 */
  538. .darkmode--activated img,
  539. .darkmode--activated svg {
  540. isolation: isolate;
  541. mix-blend-mode: difference
  542. }
  543. .darkmode-layer,
  544. .darkmode-toggle {
  545. z-index: 2
  546. }
  547. /* 小屏响应式优化 */
  548. @media only screen and (max-width: 950px) {
  549. html,
  550. body,
  551. #c {
  552. height: 100%;
  553. }
  554. #c {
  555. overflow-y: scroll;
  556. min-width: 256px;
  557. top: 0;
  558. margin: 0 0;
  559. }
  560. }
  561. </style>
  562. </head>
  563. <body>
  564. <!-- 导航栏 -->
  565. <nav>
  566. <a title="返回" id="back-btn"><i class="fa fa-backward"></i></a>
  567. <a title="刷新" href=""><i class="fa fa-arrows-rotate"></i></a>
  568. <a title="主页" id="to-home"><i class="fa fa-home"></i></a>
  569. <a title="更改语言" id="translate"><i class="fa fa-language"></i></a>
  570. <a title="切换显示模式" id="dark_b" href="javascript:;"><i class="fa fa-adjust"></i></a>
  571. <a title="关于" href="https://github.com/PJ-568/markdown.html/"><i class="fa fa-info-circle"></i></a>
  572. </nav>
  573. <!-- 内容主体 -->
  574. <div id="c">
  575. <h1>加载中……</h1>
  576. <p>请稍等。</p>
  577. </div>
  578. <!-- 加载动画 -->
  579. <div class="loading-bar">
  580. <div class="progress"></div>
  581. </div>
  582. <div class="background"></div>
  583. <script src="//lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/instant.page/5.1.0/instantpage.min.js"
  584. type="text/javascript"></script>
  585. </body>
  586. </html>