H.-H. PENG (Hsins)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: "透過 GitHub Actions 更新筆記內容 | Update note with GitHub Actions" description: 透過 GitHub Actions 更新筆記內容. image: https://user-images.githubusercontent.com/26391143/156984539-606601e9-ad2c-48d6-a783-f6a95bf0bd44.png author: Hsins tags: HackMD-Theme, HackMD-API --- {%hackmd @themes/notion %} <div style="text-align:center;"> ![](https://user-images.githubusercontent.com/26391143/156984539-606601e9-ad2c-48d6-a783-f6a95bf0bd44.png =150x) # 透過 GitHub Actions 更新筆記內容 </div> > **使用範例**:透過 GitHub Actions 更新筆記內容 > **提案人員**:[@Hsins (H.-H. Peng)](https://hackmd.io/@Hsins) > **聯絡方式**:[hsinspeng@gmail.com](hsinspeng@gmail.com) > **專案倉庫**:[Hsins/hackmd-themes](https://github.com/Hsins/hackmd-themes) <details> <summary>目錄(🔎 點擊展開)</summary> [toc] </details> ## 範例說明 ### 自訂主題 [HackMD](https://hackmd.io/) 允許使用者在文件中添加如下的 [**內部樣式表**](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) 來變更文件樣式: ``` html <style> p { color: #26b72b; } </style> ``` 並且可以透過如下的語法在其他文件中嵌入既有文件: - **固定連結**:`{%hackmd @Hsins/theme-notion %}` - **筆記代號**:`{%hackmd apDKTl3FRzG2MMi8U2L4Mw %}` 因此使用者可以透過在一份文件中定義好樣式主題後,在其他文件中透過文件標識碼 `noteId` 或自訂的永久連結來套用樣式主題。 ### 壓縮體積 在 Yahoo! 開發者團隊多年前的文章 [Best Practices for Speeding Up Your Web Site](https://developer.yahoo.com/performance/rules.html) 中曾提到: ==_Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times._== 由於 HackMD 添加樣式的方式是透過嵌入他篇文章的 CSS 樣式來達成效果,我們可以利用一系列的工具來完成縮小 CSS 樣式大小的操作: - 開發者在 `*.css` 文件中實作並調整樣式,此檔案須交由版本控制軟體進行追蹤 - 提交代碼後,透過 GitHub Actions 觸發任務 1. 透過 CSS 後處理器(Postprocessors) [PostCSS](https://github.com/postcss/postcss) 處理瀏覽器兼容問題並最小化體積 2. 將最小化後的 CSS 樣式填入 `*.md` 文件中 3. 同步更新對應 `noteId` 的文件 ## 實作說明 ### 目錄架構 以專案 [hackmd-themes](https://github.com/Hsins/hackmd-themes) 為例,其目錄架構如下所示: ``` . ├── .github │ └── workflows │ ├── update-themes.yaml │ └── ... ├── commands │ ├── update.js │ └── utils.js ├── styles │ └── [theme-slug].css ├── themes │ └── [theme-slug].md ├── configs.js ├── package.json ├── postcss.config.cjs └── ... ``` - `./.github/workflows/update-themes.yaml` 定義了 GitHub Actions 工作流的觸發事件與具體行為 - `./commands` 存放相關的腳本程式 - `./styles` 存放 `[theme-slug].css` 檔案,主要開發更動都在此處 - `./themes` 存放 `[theme-slug].md` 檔案,會根據設定檔案由 GitHub Actions 執行腳本生成 - `./configs.js` 中存放設定檔案 ### 內容設定 設定檔案 `./configs.js` 中存放了 API 設定、路徑設定與主題資訊,其中主題資訊定義結構如下: ``` javascript // configs.js export const themes = [ { slug: 'theme-notion', noteId: 'apDKTl3FRzG2MMi8U2L4Mw', styleFile: 'notion.css', themeFile: 'notion.md', metadata: { name: 'HackMD Theme - Notion', description: 'Use `{%hackmd @Hsins/theme-notion %}` syntax to include this theme.', tags: ['HackMD-Theme'], }, } // ... ]; ``` 其中 `noteId` 為筆記代號,可以透過 [User Notes API](https://hackmd.io/@hackmd-api/user-notes-api) 獲取,或是從筆記頁面的網址後綴取得。 > 此處也可以添加一個命令 `yarn create`,透過 HackMD API 創建筆記後,將返回的文章編號填入設定檔中,以供後續開發使用。 ### 核心程式 由於作為樣式主題的 HackMD 檔案所需要的內容,只會由兩部分組成: - YAML Matadata 部分 - CSS Stylesheet 部分 主要程式如下: ``` javascript // update.js import { getMetadata, getStyle, updateTheme, uploadTheme } from './utils.js'; import { themes } from '../configs.js'; themes.forEach((theme) => { const metadata = getMetadata(theme); const style = getStyle(theme); const content = metadata + '\n' + style; updateTheme(theme, content); uploadTheme(theme, content); }); ``` 其中 `uploadTheme()` 使用 [`axios`](https://github.com/axios/axios) 函數庫與 HackMD API 交互,透過指定的 `noteId` 更新內容: ``` javascript // utils.js import log from 'log-beautify'; import axios from 'axios'; import { HACKMD_API_URL, HACKMD_API_TOKEN } from '../configs.js'; const uploadTheme = (theme, content) => { const axiosConfig = { method: 'patch', url: `${HACKMD_API_URL}/notes/${theme.noteId}`, headers: { 'Authorization': HACKMD_API_TOKEN, 'Content-Type': 'application/json', }, data: JSON.stringify({ content }), }; axios(axiosConfig) .then((response) => log.success(`Theme upload: ${theme.slug}.`)) .catch((error) => log.error(error)); }; ``` ### 環境變數 由於 API Token 屬於私密訊息,應妥善保存且不以明碼方式存放於程式中,此處可以針對專案倉庫創建一個 [環境(Environment)](https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment) 並將 Token 存放於其 [加密機密(Encrypted secrets)](https://docs.github.com/en/actions/security-guides/encrypted-secrets) 中: <div style="text-align:center;"> ![](https://i.imgur.com/GQe7dPN.png) </div> 在 [`update-themes.yaml`](https://github.com/Hsins/hackmd-themes/blob/main/.github/workflows/update-themes.yaml) 設定中,需要指定環境以及使用的環境變數: ``` yaml=8 jobs: update-themes: # 指定環境 environment: CI runs-on: ubuntu-latest ``` ``` yaml=27 - name: Update themes and upload to HackMD run: yarn update env: # 設定環境變數 HACKMD_API_TOKEN: ${{ secrets.HACKMD_API_TOKEN }} ``` ## 後記 希望可以在目前的 HackMD API 基礎上,添加以下功能: - 更新筆記固定連結 - 使用範本創建筆記 ## 參考資料 - [HackMD API Documentation](https://hackmd.io/@hackmd-api/developer-portal) - [GitHub Actions Documentation](https://docs.github.com/en/actions) - [Best Practices for Speeding Up Your Web Site | Yahoo! Developer](https://developer.yahoo.com/performance/rules.html) - [在筆記中嵌入另一篇筆記 | HackMD 使用教學](https://hackmd.io/c/tutorials-tw/%2Fs%2Fhow-to-embed-note-tw) - [嵌入另一篇筆記,自訂背景主題 | HackMD 使用教學](https://hackmd.io/c/tutorials-tw/%2Fs%2FoaYqEJsHR3m4IwBqEeu2Mg) - [用固定網址發布筆記 | HackMD 使用教學](https://hackmd.io/c/tutorials-tw/%2Fs%2Fhow-to-share-note-tw) <!-- Widgets: License --> {%hackmd @Hsins/widget-license %} <!-- Widgets: Likecoin --> {%hackmd @Hsins/widget-likecoin %}

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully