Просмотр исходного кода

【修复】文档和页面压缩格式化问题

PJ568 10 месяцев назад
Родитель
Сommit
ebd2548333
5 измененных файлов с 62 добавлено и 57 удалено
  1. 2 2
      CONTRIBUTING.md
  2. 8 8
      doc/scripts.md
  3. 2 2
      doc/workflow.md
  4. 43 38
      index.html
  5. 7 7
      src/main.rs

+ 2 - 2
CONTRIBUTING.md

@@ -28,8 +28,8 @@
 
 ### 注意事项
 
-- 单次 Pull Request 不应提交过多修改,请确保每次提交都针对特定的功能且务必说明本次改动的具体目的,例如:修复某 bug 、优化某方法 等,方便进行 Code Review;
+- 单次 Pull Request 不应提交过多修改,请确保每次提交都针对特定的功能且务必说明本次改动的具体目的,例如:修复某 bug、优化某方法 等,方便进行 Code Review;
 - 对于 bug 的修复,应该将本次 Pull Request 和相对应 bug 的 issue 关联起来,让别人知道该问题已经被修复;
-- 对于较大的新功能,你需要先提交 Issues,例如 “【新增】添加 XXX 功能”,确认该功能有被添加的必要后,再开始工作;
+- 对于较大的新功能,你需要先提交 Issues,例如“【新增】添加 XXX 功能”,确认该功能有被添加的必要后,再开始工作;
 - 对于一些主观的样式、交互逻辑调整:如颜色、图标的使用,某些预设配置的增减修改等,一般不予通过。但可以在 Discussions 中进行讨论;
 - 其他如简单的代码优化、文档修正等,只要修改合理都会被接受。

+ 8 - 8
doc/scripts.md

@@ -2,7 +2,7 @@
 
 ## 1. 引言
 
-本文档详细说明项目中三个 Bash 脚本(`get-version.bash`, `is-newer-version.bash`, `release.bash`)和主程序(`src/main.rs`)的设计与功能。这些组件协同工作,实现版本管理、发布流程和 HTML 处理功能。
+本文档详细说明项目中三个 Bash 脚本 (`get-version.bash`, `is-newer-version.bash`, `release.bash`) 和主程序 (`src/main.rs`) 的设计与功能。这些组件协同工作,实现版本管理、发布流程和 HTML 处理功能。
 
 ```mermaid
 graph TD
@@ -22,9 +22,9 @@ graph TD
 
 1. **路径解析**:
 
-   - 自动检测脚本所在目录(`$SCRIPT_DIR`)
-   - 计算仓库根目录(`$REPO_DIR`)
-   - 支持自定义文件路径参数(`$1`)
+   - 自动检测脚本所在目录 (`$SCRIPT_DIR`)
+   - 计算仓库根目录 (`$REPO_DIR`)
+   - 支持自定义文件路径参数 (`$1`)
 
 2. **多语言支持**:
 
@@ -39,8 +39,8 @@ VERSION=$(grep -oP '<markdown-html\s+version="\K[^"]+' "$FILE_PATH" | head -1)
 ```
 
 4. **错误处理**:
-   - 文件不存在检测(`[ ! -f "$FILE_PATH" ]`)
-   - 版本号缺失检测(`[ -z "$VERSION" ]`)
+   - 文件不存在检测 (`[ ! -f "$FILE_PATH" ]`)
+   - 版本号缺失检测 (`[ -z "$VERSION" ]`)
 
 **使用示例**:
 
@@ -58,7 +58,7 @@ VERSION=$(grep -oP '<markdown-html\s+version="\K[^"]+' "$FILE_PATH" | head -1)
 1. **版本获取**:
 
    - 调用`get-version.bash`获取当前版本
-   - 获取最新 Git 标签(`git tag -l 'v*'`)
+   - 获取最新 Git 标签 (`git tag -l 'v*'`)
 
 2. **版本比较算法**:
 
@@ -109,7 +109,7 @@ sequenceDiagram
    - 标签创建/推送失败
 4. **多语言界面**:所有交互提示支持中英文
 
-## 3. 主程序分析(src/main.rs)
+## 3. 主程序分析 (src/main.rs)
 
 HTML 处理核心程序,提供压缩和内联功能。
 

+ 2 - 2
doc/workflow.md

@@ -22,7 +22,7 @@ graph LR
 工作流在以下事件触发:
 
 - 推送到`master`分支
-- 手动触发(`workflow_dispatch`)
+- 手动触发 (`workflow_dispatch`)
 
 ## 3. 核心阶段详解
 
@@ -81,7 +81,7 @@ sequenceDiagram
    - 设置 Rust 编译环境
    - 缓存依赖加速构建
 2. **项目构建**:
-   - 发布模式编译(`cargo build --release`)
+   - 发布模式编译 (`cargo build --release`)
 3. **HTML 生成**:
    - 执行主程序处理 index.html
    - 产出四种 HTML 变体

+ 43 - 38
index.html

@@ -1,12 +1,13 @@
-<!DOCTYPE html>
+<!doctype html>
 
 <html>
   <markdown-html
-    version="1.20.8"
+    version="1.20.9"
     author="PJ568"
     repo="https://github.com/PJ-568/markdown.html"
     license="CC BY-SA 4.0 International"
-  ></markdown-html>
+  >
+  </markdown-html>
 
   <head>
     <meta charset="utf-8" />
@@ -249,7 +250,7 @@
               bq.appendChild(switchButton);
 
               const mainElement = document.querySelector(
-                ".markdown-body .content"
+                ".markdown-body .content",
               );
               mainElement.insertBefore(bq, mainElement.children[1]);
             }
@@ -353,17 +354,16 @@
         // 处理错误
         function updateContent(article, title = null, mdPath = pValue) {
           try {
-            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>`;
+            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>`;
             firstH1 = document.querySelector(".markdown-body .content h1");
             document.title = title
               ? title
               : firstH1
-              ? firstH1.textContent
-              : mdPath;
+                ? firstH1.textContent
+                : mdPath;
           } catch (error) {
             throw error;
           }
@@ -374,7 +374,7 @@
           return new Promise((resolve, reject) => {
             //// 检查是否已加载
             const existingLinks = document.querySelectorAll(
-              `link[href="${url}"]`
+              `link[href="${url}"]`,
             );
             if (existingLinks.length > 0) {
               return resolve(url);
@@ -398,7 +398,7 @@
               link.onerror = null;
               link.onload = null;
               document.head.removeChild(link);
-              reject(new Error(`无法加载CSS文件: ${url}`));
+              reject(new Error(`无法加载 CSS 文件:${url}`));
             };
 
             //// 添加到文档头部
@@ -422,7 +422,7 @@
                 if (completedCount === totalElements) {
                   parentElement.removeEventListener(
                     "animationend",
-                    handleAnimationEnd
+                    handleAnimationEnd,
                   );
                   resolve();
                 }
@@ -437,17 +437,17 @@
         function handleError(mdPath, errorMessage) {
           updateContent(
             `<h1>加载失败</h1><p>加载文档<code>${mdPath}</code>时出错:<code>${errorMessage}</code>。您可以尝试<a class="refresh-btn" href="">重新加载</a>或<a class="back-btn">返回</a>。</p>`,
-            "加载失败"
+            "加载失败",
           );
           waitForAnimationsEnd(
             document.querySelector(".markdown-body"),
             ".content, .old-content",
-            ["Animation-slideInRight", "Animation-slideInLeft"]
+            ["Animation-slideInRight", "Animation-slideInLeft"],
           ).then(() => {
             customPushState(
               window.location.origin +
                 window.location.pathname +
-                (mdPath ? "?p=" + mdPath : "")
+                (mdPath ? "?p=" + mdPath : ""),
             );
           });
           endLoad();
@@ -517,13 +517,13 @@
             waitForAnimationsEnd(
               document.querySelector(".markdown-body"),
               ".content, .old-content",
-              ["Animation-slideInRight", "Animation-slideInLeft"]
+              ["Animation-slideInRight", "Animation-slideInLeft"],
             ).then(async () => {
               await showMarkdownEnded();
               customPushState(
                 window.location.origin +
                   window.location.pathname +
-                  (mdPath ? "?p=" + mdPath : "")
+                  (mdPath ? "?p=" + mdPath : ""),
               );
             });
           } catch (error) {
@@ -536,7 +536,7 @@
           //// 生成目录
           function generateOutline(doc) {
             const headings = Array.from(
-              doc.querySelectorAll("h1, h2, h3, h4, h5, h6")
+              doc.querySelectorAll("h1, h2, h3, h4, h5, h6"),
             );
             if (headings.length === 0) return "<i>无目录</i>";
             var outline = "<ul>";
@@ -593,7 +593,7 @@
                   "," +
                   response.status +
                   "," +
-                  response.statusText
+                  response.statusText,
               );
             }
           }
@@ -608,7 +608,7 @@
           const linkParser = new DOMParser();
           const linkDoc = linkParser.parseFromString(
             `<div>${content}</div>`,
-            "text/html"
+            "text/html",
           );
 
           //// 处理所有 a 链接
@@ -659,7 +659,7 @@
 
           //// 添加目录
           content = `<details class="outline"><summary>${decodeURIComponent(
-            mdPath
+            mdPath,
           )}</summary></details><hr>${content}`;
           const parser = new DOMParser();
           const doc = parser.parseFromString(content, "text/html");
@@ -678,11 +678,11 @@
             responseText,
             request,
             href,
-            options
+            options,
           ) {
             if (
               /^<!doctype html>[\s\S]*?<html>[\s\S]*?<markdown-html/i.test(
-                request.responseText
+                request.responseText,
               )
             ) {
               await showMarkdown(await decodeMDPath(href));
@@ -720,7 +720,7 @@
               history.pushState(
                 { url: url, title: document.title, uid: level },
                 null,
-                url
+                url,
               );
               lastLevel = level++;
             } else {
@@ -748,7 +748,7 @@
         function initAboutBtn() {
           const aboutBtn = document.querySelector(".about-btn");
           aboutBtn.href = `?p=${getDirectory(
-            window.location.pathname
+            window.location.pathname,
           )}about.md`;
         }
 
@@ -796,7 +796,7 @@
             } else if (event.animationName === "Animation-slideInLeft") {
               document.querySelector(".markdown-body .old-content").remove();
             }
-          }
+          },
         );
         //// 点击事件委托
         document.addEventListener("click", function (event) {
@@ -894,8 +894,9 @@
       textarea,
       code,
       pre {
-        font-family: "Sarasa Term SC Nerd", "Maple Mono CN", Ubuntu, Roboto,
-          "Open Sans", "Microsoft YaHei", Arial, sans-serif;
+        font-family:
+          "Sarasa Term SC Nerd", "Maple Mono CN", Ubuntu, Roboto, "Open Sans",
+          "Microsoft YaHei", Arial, sans-serif;
         text-decoration: none;
       }
 
@@ -950,7 +951,9 @@
       nav a {
         color: #fafafa;
         padding: 0.3rem;
-        transition: color 0.2s, background-color 0.2s;
+        transition:
+          color 0.2s,
+          background-color 0.2s;
       }
 
       nav a:hover {
@@ -1041,7 +1044,9 @@
 
       /* Markdown 样式 */
       .markdown-body a {
-        transition: color 0.2s, background-color 0.2s;
+        transition:
+          color 0.2s,
+          background-color 0.2s;
       }
 
       .markdown-body a:hover {
@@ -1225,7 +1230,7 @@
     <!-- 导航栏 -->
     <nav>
       <a title="返回" class="back-btn">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"
@@ -1243,7 +1248,7 @@
         </svg>
       </a>
       <a title="刷新" class="refresh-btn" href="">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"
@@ -1262,7 +1267,7 @@
         </svg>
       </a>
       <a title="主页" class="to-home">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"
@@ -1282,7 +1287,7 @@
         </svg>
       </a>
       <a title="更改语言" id="translate">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"
@@ -1304,7 +1309,7 @@
         </svg>
       </a>
       <a title="切换显示模式" class="dark-btn" href="javascript:;">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"
@@ -1326,7 +1331,7 @@
         </svg>
       </a>
       <a title="关于" class="about-btn">
-        <license content="Copyright (c) 2018-2025 Tabler" />
+        <license content="Copyright (c) 2018-2025 Tabler"></license>
         <svg
           xmlns="http://www.w3.org/2000/svg"
           width="24"

+ 7 - 7
src/main.rs

@@ -18,7 +18,7 @@ impl Error for HtmlProcessorError {}
 
 type Result<T> = std::result::Result<T, Box<dyn Error>>;
 
-/// 压缩HTML文件
+/// 压缩 HTML 文件
 pub fn minify_html(input_path: &str) -> Result<PathBuf> {
     let input_path_obj = Path::new(input_path);
     let file_stem = input_path_obj.file_stem()
@@ -82,10 +82,10 @@ pub fn all_in_one(input_path: &str) -> Result<PathBuf> {
     let html_str = String::from_utf8_lossy(&html_content);
     let document = Html::parse_document(&html_str);
 
-    // 保留原始HTML结构,只替换特定标签内容
+    // 保留原始 HTML 结构,只替换特定标签内容
     let mut processed_html = html_str.to_string();
 
-    // 处理script标签
+    // 处理 script 标签
     let script_selector = Selector::parse("script[src]").unwrap();
     for script in document.select(&script_selector) {
         if let Some(src) = script.value().attr("src") {
@@ -110,7 +110,7 @@ pub fn all_in_one(input_path: &str) -> Result<PathBuf> {
         }
     }
 
-    // 处理link标签
+    // 处理 link 标签
     let link_selector = Selector::parse("link[rel=stylesheet]").unwrap();
     for link in document.select(&link_selector) {
         if let Some(href) = link.value().attr("href") {
@@ -146,7 +146,7 @@ fn main() {
 
     let input_path = std::env::args().nth(1).expect("Expected a path to an HTML file");
 
-    // 1. 生成min.html
+    // 1. 生成 min.html
     match minify_html(&input_path) {
         Ok(minified_path) => {
             println!("Minified HTML written to {}", minified_path.display());
@@ -154,12 +154,12 @@ fn main() {
         Err(e) => eprintln!("Error minifying HTML: {}", e),
     }
 
-    // 2. 生成allinone.html
+    // 2. 生成 allinone.html
     match all_in_one(&input_path) {
         Ok(all_in_one_path) => {
             println!("All-in-one HTML written to {}", all_in_one_path.display());
             
-            // 3. 生成allinone.min.html
+            // 3. 生成 allinone.min.html
             match minify_html(all_in_one_path.to_str().unwrap()) {
                 Ok(minified_path) => {
                     println!("Minified all-in-one HTML written to {}", minified_path.display());