Prechádzať zdrojové kódy

【新增】生成全合一 HTML 文件并优化工作流

- 新增功能:生成全合一 HTML 文件,包含所有外部资源
- 优化 Github Actions 工作流,支持生成多种 HTML 文件
- 更新 README 和文档,增加全合一 HTML 文件说明
- 重构代码,支持生成压缩和全合一 HTML 文件
PJ568 1 rok pred
rodič
commit
4fd66af76a
9 zmenil súbory, kde vykonal 241 pridanie a 66 odobranie
  1. 4 2
      .github/workflows/release.yml
  2. 4 1
      .gitignore
  3. 1 1
      CONTRIBUTING.md
  4. 2 0
      Cargo.toml
  5. 14 3
      README.md
  6. 42 31
      README_EN.md
  7. 22 4
      action.yml
  8. 3 4
      index.html
  9. 149 20
      src/main.rs

+ 4 - 2
.github/workflows/release.yml

@@ -58,7 +58,7 @@ jobs:
 
     - name: Generate minimized HTML
       if: steps.version-check.outputs.version != '0'
-      run: cargo run --release -- index.html index.min.html
+      run: cargo run --release -- index.html
       shell: bash
       working-directory: ${{ github.action_path }}
 
@@ -68,6 +68,8 @@ jobs:
         mkdir -p ../release
         cp -v index.html ../release/
         cp -v index.min.html ../release/
+        cp -v index.allinone.html ../release/
+        cp -v index.allinone.min.html ../release/
       shell: bash
       working-directory: ${{ github.action_path }}
 
@@ -77,7 +79,7 @@ jobs:
       with:
         generateReleaseNotes: true
         tag: "v${{ steps.version-check.outputs.version }}"
-        artifacts: "../release/index.html,../release/index.min.html"
+        artifacts: "../release/index.html,../release/index.min.html,../release/index.allinone.html,../release/index.allinone.min.html"
 
     - name: Delete tag on failure
       if: failure() && steps.push-tag.outputs.tag_name != ''

+ 4 - 1
.gitignore

@@ -1,3 +1,6 @@
 /target
 /Cargo.lock
-index.min.html
+
+index.min.html
+index.allinone.html
+index.allinone.min.html

+ 1 - 1
CONTRIBUTING.md

@@ -21,7 +21,7 @@
 
 1. Fork 源码,下载到本地并运行项目;
 2. 添加或修改代码;
-3. 运行 `cargo run --release -- index.html index.min.html` 命令以生成压缩的最小文件;
+3. 配置 rust 环境并运行 `cargo run --release -- index.html` 命令以生成压缩的最小文件和全合一文件;
 4. 对相关改动进行全面的自我测试;
 5. 确认无误后提交修改到 Github;
 6. 提交 Pull Request。

+ 2 - 0
Cargo.toml

@@ -7,3 +7,5 @@ edition = "2021"
 
 [dependencies]
 minify-html = "0.15.0"
+reqwest = { version = "0.12.20", features = ["blocking"] }
+scraper = "0.23.1"

+ 14 - 3
README.md

@@ -6,7 +6,7 @@
 
 ## 特性
 
-- **依赖少**:仅需一个 HTML 文件、少量 CDN 和服务器程序,即可完成 Markdown 网页渲染。
+- **依赖少**:仅需一个 HTML 文件,即可完成 Markdown 网页渲染。
 - **代码高亮支持**:渲染 Markdown 中的代码块。
 - **Markdown 支持**:将 Markdown 文件渲染为 HTML。
 - **Mermaid 支持**:将 Markdown 中的 Mermaid 语法渲染为图表。
@@ -16,19 +16,30 @@
 
 ## 使用方法
 
+| 文件名 | 说明 |
+| :----- | :--- |
+| index.html | 默认 HTML 入口文件,使用 CDN 引入依赖。 |
+| index.min.html | 压缩后的 HTML 入口文件,使用 CDN 引入依赖。 |
+| index.allinone.html | 全合一 HTML 入口文件,默认包含所有可被脚本下载的依赖。 |
+| index.allinone.min.html | 压缩后的全合一 HTML 入口文件,默认包含所有可被脚本下载的依赖。 |
+
 ### 手动部署
 
-1. 下载并重命名本仓库的 `index.html` 文件到你的网站根目录或任何其他目录中;
-2. 当下载并重命名后的 `index.html` 被访问时,将自动渲染同目录下的 `index.md`,如果 `index.md` 不存在,则渲染 `README.md`。
+1. 在[发行页面](https://github.com/PJ-568/MARKDOWN.HTML/releases)下载并重命名您需要的 HTML 文件到你的网站根目录或任何其他目录中;
+2. 当下载并重命名后的 HTML 被访问时,将自动渲染同目录下的 `index.md`,如果 `index.md` 不存在,则渲染 `README.md`。
 
 ### Github Actions
 
+编译并把 HTML 放入指定目录。使用时须将 `<version>` 替换为版本号。
+
 ```yaml
 - name: Deploy markdown.html
   uses: PJ-568/MARKDOWN.HTML@v<version>
   with:
     target-dir: '.'
     file-name: 'index.html'
+    use-minified: 'true'
+    use-all-in-one: 'false'
 ```
 
 ## 其他说明

+ 42 - 31
README_EN.md

@@ -2,74 +2,85 @@
 
 > [简体中文](README.md) | English
 
-This project aims to provide a low-dependency, simple deployment solution for rendering Markdown web pages.
+This project provides a low-dependency, one-click deployment solution for rendering Markdown to web pages.
 
 ## Features
 
-- **Low dependencies**: Only an HTML file, a small number of CDNs, and server programs are required to complete Markdown pages rendering.
-- **Syntax highlighting support**: Renders code blocks in Markdown.
-- **Markdown support**: Renders Markdown files into HTML.
-- **Mermaid support**: Renders Mermaid syntax in Markdown into diagrams.
-- **Multilingual support**: Supports machine translation between multiple languages.
-- **Dark mode support**: Supports light, dark, and system-following modes.
-- **Pjax support**: Supports page navigation without refreshing the whole page.
+- **Minimal dependencies**: Only requires a single HTML file to render Markdown web pages.
+- **Code highlighting**: Supports syntax highlighting for code blocks in Markdown.
+- **Markdown support**: Renders Markdown files to HTML.
+- **Mermaid support**: Renders Mermaid diagrams in Markdown.
+- **Multi-language support**: Provides machine translation between languages.
+- **Dark mode**: Supports light, dark, and system theme modes.
+- **Pjax support**: Enables page navigation without full refresh.
 
 ## Usage
 
+| Filename | Description |
+| :----- | :--- |
+| index.html | Default HTML entry file using CDN dependencies. |
+| index.min.html | Minified HTML entry file using CDN dependencies. |
+| index.allinone.html | All-in-one HTML entry file with embedded dependencies which can be downloaded by script. |
+| index.allinone.min.html | Minified all-in-one HTML entry file with embedded dependencies which can be downloaded by script. |
+
 ### Manual Deployment
 
-1. Download and rename the `index.html` file from this repository and place to your website's root directory or any other directory;
-2. When the html file is accessed, it will automatically render the `index.md` in the same directory. If `index.md` does not exist, it will render `README.md`.
+1. Download the required HTML file from [Releases](https://github.com/PJ-568/MARKDOWN.HTML/releases) and place it in your website root directory;
+2. The HTML file will automatically render `index.md` in the same directory, or `README.md` if `index.md` doesn't exist.
 
 ### Github Actions
 
+Compiles and deploys HTML files to specified directory. Replace `<version>` with actual version number.
+
 ```yaml
 - name: Deploy markdown.html
   uses: PJ-568/MARKDOWN.HTML@v<version>
   with:
     target-dir: '.'
     file-name: 'index.html'
+    use-minified: 'true'
+    use-all-in-one: 'false'
 ```
 
-## Additional Notes
+## Notes
 
-`The open-source projects used in this project allow modifications, but please retain the original author information. If removal is necessary, please contact the author to avoid losing technical support.` For more details, refer to the [license](#license).
+`This open-source project allows modifications but please retain original author information. If removal is necessary, please contact the author to avoid losing technical support.` See [License](#license) for details.
 
-## Code or Content Contributions
+## Contributions
 
-We welcome contributions of code and content from anyone interested in this project.
-Please checkout [程序逻辑](doc/logic.md).
+We welcome contributions to code and content. Please refer to:
 
-For a simpler way to contribute, please refer to the [Contribution Guide](CONTRIBUTING.md) for relevant information.
+- [Logic Documentation](doc/logic.md)
+- [Contribution Guidelines](CONTRIBUTING.md)
 
 ## License
 
-This project is licensed under the [CC BY-SA 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/) license. For full license information, please refer to the [`LICENSE`](LICENSE) file.
+This project is licensed under [CC BY-SA 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). For complete license information, see [`LICENSE`](LICENSE).
 
-### Credits
+### Acknowledgments
 
 #### Projects
 
-|Name|License|URL|
+|Name|License|Links|
 |:-:|:--|:--|
-|tabler-icons|[MIT License](//mit-license.org)|[Github](https://github.com/tabler/tabler-icons)、[Website](https://tabler.io/icons)|
-|highlightjs/highlight.js|[BSD-3-Clause license](https://github.com/highlightjs/highlight.js/raw/refs/heads/main/LICENSE)|[Github](https://github.com/highlightjs/highlight.js)、[Website](https://highlightjs.org)|
-|markedjs/marked|[marked License](https://github.com/markedjs/marked/blob/master/LICENSE.md)|[Github](https://github.com/markedjs/marked)、[Website](https://marked.js.org)|
-|mermaidjs/mermaid|[MIT License](https://github.com/mermaid-js/mermaid/blob/develop/LICENSE)|[Github](https://github.com/mermaid-js/mermaid)、[Website](https://mermaid.js.org)|
-|translate.js|[Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)|[Github](https://github.com/xnx3/translate)、[Gitee](https://gitee.com/mail_osc/translate)、[Website](https://translate.zvo.cn)|
-|darkmode.js|[MIT license](//mit-license.org)|[Github](https://github.com/sandoche/Darkmode.js)、[Website](https://darkmodejs.learn.uno)|
+|tabler-icons|[MIT License](//mit-license.org)|[Github](https://github.com/tabler/tabler-icons), [Website](https://tabler.io/icons)|
+|highlightjs/highlight.js|[BSD-3-Clause license](https://github.com/highlightjs/highlight.js/raw/refs/heads/main/LICENSE)|[Github](https://github.com/highlightjs/highlight.js), [Website](https://highlightjs.org)|
+|markedjs/marked|[marked License](https://github.com/markedjs/marked/blob/master/LICENSE.md)|[Github](https://github.com/markedjs/marked), [Website](https://marked.js.org)|
+|mermaidjs/mermaid|[MIT License](https://github.com/mermaid-js/mermaid/blob/develop/LICENSE)|[Github](https://github.com/mermaid-js/mermaid), [Website](https://mermaid.js.org)|
+|translate.js|[Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)|[Github](https://github.com/xnx3/translate), [Gitee](https://gitee.com/mail_osc/translate), [Website](https://translate.zvo.cn)|
+|darkmode.js|[MIT license](//mit-license.org)|[Github](https://github.com/sandoche/Darkmode.js), [Website](https://darkmodejs.learn.uno)|
 |MoOx/pjax|[MIT license](//mit-license.org)|[Github](https://github.com/MoOx/pjax)|
-|instant.page|[MIT license](//mit-license.org)|[Github](https://github.com/instantpage/instant.page)、[Website](https://instant.page)|
-|Maple Mono|[OFL-1.1 license](https://openfontlicense.org/open-font-license-official-text/)|[Github](https://github.com/subframe7536/maple-font)、[Website](https://font.subf.dev)|
+|instant.page|[MIT license](//mit-license.org)|[Github](https://github.com/instantpage/instant.page), [Website](https://instant.page)|
+|Maple Mono|[OFL-1.1 license](https://openfontlicense.org/open-font-license-official-text/)|[Github](https://github.com/subframe7536/maple-font), [Website](https://font.subf.dev)|
 
 #### Services
 
 |Icon|Name|
 |:-:|:--|
-|None|[360 Frontend Static Resource Library](https://cdn.baomitu.com/)|
-|![ByteDance Static Resource CDN icon](https://cdn.bytedance.com/src/res/logo.svg)|[ByteDance Static Resource CDN](https://cdn.bytedance.com/)|
-|![Chinese Font Network Project](https://chinese-font.netlify.app/favicon.ico)|[Chinese Font Network Project](https://chinese-font.netlify.app)|
+|-|[360 Frontend CDN](https://cdn.baomitu.com/)|
+|![ByteDance Static CDN](https://cdn.bytedance.com/src/res/logo.svg)|[ByteDance Static CDN](https://cdn.bytedance.com/)|
+|![Chinese Web Font Project](https://chinese-font.netlify.app/favicon.ico)|[Chinese Web Font Project](https://chinese-font.netlify.app)|
 
-## Stargazers over time
+## Stars
 
 [![Stargazers over time](https://starchart.cc/PJ-568/MARKDOWN.HTML.svg?variant=adaptive)](https://starchart.cc/PJ-568/MARKDOWN.HTML)

+ 22 - 4
action.yml

@@ -9,28 +9,46 @@ inputs:
   file-name:
     description: Name of the minimized HTML file
     default: "index.html"
+  use-minified:
+    description: Whether to use minified HTML file
+    default: "true"
+  use-all-in-one:
+    description: Whether to use all-in-one HTML file
+    default: "false"
 
 runs:
   using: "composite"
   steps:
     - name: Setup Rust
       uses: MatteoH2O1999/setup-rust@v1
+      if: ${{ inputs.use-minified == 'true' || inputs.use-all-in-one == 'true' }}
 
     - name: Build project
-      run: cargo build --release
+      if: ${{ inputs.use-minified == 'true' || inputs.use-all-in-one == 'true' }}
+      run: cargo install && cargo build --release
       shell: bash
       working-directory: ${{ github.action_path }}
 
     - name: Generate minimized HTML
-      run: cargo run --release -- ${{ github.action_path }}/index.html ${{ github.action_path }}/index.min.html
+      if: ${{ inputs.use-minified == 'true' || inputs.use-all-in-one == 'true' }}
+      run: cargo run --release -- index.html
       shell: bash
       working-directory: ${{ github.action_path }}
 
-    - name: Deploy minimized file
+    - name: Deploy file
       run: |
         mkdir -p "${{ inputs.target-dir }}"
-        cp -uv ${{ github.action_path }}/index.min.html "${{ inputs.target-dir }}/${{ inputs.file-name }}"
+        USE_MINIFIED=""
+        USE_ALL_IN_ONE=""
+        if [ "${{ inputs.use-minified }}" = "true" ]; then
+          USE_MINIFIED=".min"
+        fi
+        if [ "${{ inputs.use-all-in-one }}" = "true" ]; then
+          USE_ALL_IN_ONE=".allinone"
+        fi
+        cp -uv index${USE_ALL_IN_ONE}${USE_MINIFIED}.html "${{ inputs.target-dir }}/${{ inputs.file-name }}"
       shell: bash
+      working-directory: ${{ github.action_path }}
 
 branding:
   icon: 'book-open'

+ 3 - 4
index.html

@@ -1,7 +1,7 @@
 <!doctype html>
 
 <html>
-<markdown-html version="1.14.5" author="PJ568" repo="https://github.com/PJ-568/markdown.html"
+<markdown-html version="1.15.0" author="PJ568" repo="https://github.com/PJ-568/markdown.html"
   license="CC BY-SA 4.0 International"></markdown-html>
 
 <head>
@@ -45,7 +45,7 @@
 
 ### 特性
 
-- **依赖少**:仅需一个 HTML 文件、少量 CDN 和服务器程序,即可完成 Markdown 网页渲染。
+- **依赖少**:仅需一个 HTML 文件,即可完成 Markdown 网页渲染。
 - **Markdown 支持**:将 Markdown 文件渲染为 HTML。
 - **Mermaid 支持**:将 Markdown 中的 Mermaid 语法渲染为图表。
 - **多语言支持**:支持多种语言间的机器互译。
@@ -592,14 +592,13 @@
           if (url) {
             window.open(url, '_blank');
             event.preventDefault();
-            return;
           } else {
             const newWindow = window.open('', '_blank');
             newWindow.document.write(imgOrSvg.outerHTML);
             newWindow.document.close();
             event.preventDefault();
-            return;
           }
+          return;
         }
         if (event.target.closest('nav .back-btn')) {
           window.history.back();

+ 149 - 20
src/main.rs

@@ -1,22 +1,37 @@
 use minify_html::{minify, Cfg};
-use std::fs::write;
+use reqwest::blocking::get;
+use scraper::{Html, Selector};
+use std::fs::{read, write};
+use std::path::{Path, PathBuf};
+use std::error::Error;
+use std::fmt;
 
-fn main() {
-    if std::env::args().len() < 3 {
-        eprintln!("Usage: {} <path_to_html_file> <output_path>", std::env::args().next().unwrap());
-        return;
+#[derive(Debug)]
+struct HtmlProcessorError(String);
+
+impl fmt::Display for HtmlProcessorError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "HtmlProcessorError: {}", self.0)
     }
+}
 
-    let input_path = std::env::args().nth(1).expect("Expected a path to an HTML file");
-    let output_path = std::env::args().nth(2).expect("Expected an output file path");
+impl Error for HtmlProcessorError {}
 
-    let code = match std::fs::read(input_path) {
-        Ok(data) => data,
-        Err(e) => {
-            eprintln!("Error reading file: {}", e);
-            return;
-        }
-    };
+type Result<T> = std::result::Result<T, Box<dyn Error>>;
+
+/// 压缩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()
+        .and_then(|s| s.to_str())
+        .ok_or_else(|| HtmlProcessorError("Invalid input file name".into()))?;
+    
+    let output_path = input_path_obj
+        .parent()
+        .map(|p| p.join(format!("{}.min.html", file_stem)))
+        .unwrap_or_else(|| PathBuf::from(format!("{}.min.html", file_stem)));
+
+    let code = read(input_path)?;
 
     let mut cfg = Cfg::new();
     cfg.do_not_minify_doctype = true;
@@ -27,18 +42,132 @@ fn main() {
     cfg.keep_comments = false;
     cfg.keep_input_type_text_attr = true;
     cfg.keep_ssi_comments = false;
-    // cfg.preserve_brace_template_syntax = false;
-    // cfg.preserve_chevron_percent_template_syntax = false;
     cfg.minify_css = true;
     cfg.minify_js = true;
     cfg.remove_bangs = false;
     cfg.remove_processing_instructions = false;
 
     let minified = minify(&code, &cfg);
+    write(&output_path, minified)?;
+
+    Ok(output_path)
+}
+
+/// 获取外部资源内容
+fn fetch_external_resource(url: &str) -> Result<String> {
+    let client = reqwest::blocking::Client::builder()
+        .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
+        .build()?;
+    
+    let resp = client.get(url).send()?;
+    if !resp.status().is_success() {
+        eprintln!("Warning: Failed to fetch {}: {}", url, resp.status());
+        return Err(Box::new(HtmlProcessorError(format!("Failed to fetch {}", url))));
+    }
+    Ok(resp.text()?)
+}
+
+/// 内联所有外部资源
+pub fn all_in_one(input_path: &str) -> Result<PathBuf> {
+    let input_path_obj = Path::new(input_path);
+    let file_stem = input_path_obj.file_stem()
+        .and_then(|s| s.to_str())
+        .ok_or_else(|| HtmlProcessorError("Invalid input file name".into()))?;
+    
+    let output_path = input_path_obj
+        .parent()
+        .map(|p| p.join(format!("{}.allinone.html", file_stem)))
+        .unwrap_or_else(|| PathBuf::from(format!("{}.allinone.html", file_stem)));
+
+    let html_content = read(input_path)?;
+    let html_str = String::from_utf8_lossy(&html_content);
+    let document = Html::parse_document(&html_str);
+
+    // 保留原始HTML结构,只替换特定标签内容
+    let mut processed_html = html_str.to_string();
+
+    // 处理script标签
+    let script_selector = Selector::parse("script[src]").unwrap();
+    for script in document.select(&script_selector) {
+        if let Some(src) = script.value().attr("src") {
+            if src.starts_with("http") {
+                match fetch_external_resource(src) {
+                    Ok(content) => {
+                        let original = script.html();
+                        let replacement = format!("<script type=\"{}\"{}>{}</script>",
+                            script.value().attr("type").unwrap_or(""),
+                            script.value().attrs()
+                                .filter(|(name, _)| *name != "src" && *name != "type")
+                                .map(|(name, value)| format!(" {}=\"{}\"", name, value))
+                                .collect::<String>(),
+                            content);
+                        processed_html = processed_html.replace(&original, &replacement);
+                    },
+                    Err(e) => {
+                        eprintln!("Warning: Could not inline {}: {}", src, e);
+                    }
+                }
+            }
+        }
+    }
+
+    // 处理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") {
+            if href.starts_with("http") {
+                match fetch_external_resource(href) {
+                    Ok(content) => {
+                        let original = link.html();
+                        let replacement = format!("<style type=\"text/css\"{}>{}</style>",
+                            link.value().attrs()
+                                .filter(|(name, _)| *name != "href" && *name != "rel")
+                                .map(|(name, value)| format!(" {}=\"{}\"", name, value))
+                                .collect::<String>(),
+                            content);
+                        processed_html = processed_html.replace(&original, &replacement);
+                    },
+                    Err(e) => {
+                        eprintln!("Warning: Could not inline {}: {}", href, e);
+                    }
+                }
+            }
+        }
+    }
+
+    write(&output_path, processed_html)?;
+    Ok(output_path)
+}
+
+fn main() {
+    if std::env::args().len() < 2 {
+        eprintln!("Usage: {} <path_to_html_file>", std::env::args().next().unwrap());
+        return;
+    }
+
+    let input_path = std::env::args().nth(1).expect("Expected a path to an HTML file");
+
+    // 1. 生成min.html
+    match minify_html(&input_path) {
+        Ok(minified_path) => {
+            println!("Minified HTML written to {}", minified_path.display());
+        },
+        Err(e) => eprintln!("Error minifying HTML: {}", e),
+    }
 
-    if let Err(e) = write(&output_path, minified) {
-        eprintln!("Error writing to file: {}", e);
-    } else {
-        println!("Minified HTML written to {}", output_path);
+    // 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
+            match minify_html(all_in_one_path.to_str().unwrap()) {
+                Ok(minified_path) => {
+                    println!("Minified all-in-one HTML written to {}", minified_path.display());
+                },
+                Err(e) => eprintln!("Error minifying all-in-one HTML: {}", e),
+            }
+        },
+        Err(e) => eprintln!("Error creating all-in-one HTML: {}", e),
     }
 }