Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Test

on:
push:
branches: [master, develop]
pull_request:

permissions:
contents: read

jobs:
mermaid:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Build the fixture site and check mermaid injection
run: node test/run.js
22 changes: 16 additions & 6 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -754,15 +754,25 @@ post:
# 流程图,基于 mermaid-js,具体请见:https://fluid.ist/docs/guide/#mermaid-流程图
# Flow chart, based on mermaid-js, see: https://fluid.ist/docs/en/guide/#mermaid
mermaid:
# 开启后文章默认可用,自定义页面如需使用,需在 Front-matter 中指定 `mermaid: true`
# If you want to use mermaid on the custom page, you need to set `mermaid: true` in Front-matter
# 开启后文章默认可用;页面会自动检测正文中的 mermaid 图表(代码块、`{% mermaid %}` 标签、
# `<div class="mermaid">`),一般无需再写 Front-matter。
# 如果图表是运行时注入的(例如加密插件、动态加载的评论内容),或页面未引入 markdown 正文样式,
# 仍可在 Front-matter 中指定 `mermaid: true` 强制加载脚本。
# Once enabled, posts work out of the box: the theme detects mermaid diagrams in the
# content (code fences, the `{% mermaid %}` tag and `<div class="mermaid">`), so the
# Front-matter flag is usually unnecessary. Set `mermaid: true` in Front-matter when
# diagrams are injected at runtime (encrypted posts, dynamically loaded content) or
# when the page does not include the markdown body styles.
enable: false

# 开启后,只有在文章 Front-matter 里指定 `mermaid: true` 才会在文章页启动公式转换,以便在页面不包含公式时提高加载速度
# If true, only set `mermaid: true` in Front-matter will enable mermaid, to load faster when the page does not contain mermaid
# 开启后,只有当页面包含 mermaid 图表或 Front-matter 指定 `mermaid: true` 时才加载脚本,以便在页面不包含图表时提高加载速度
# 指定 `mermaid: false` 可强制关闭
# If true, the script is only loaded when the page contains mermaid diagrams or `mermaid: true` is set in Front-matter, saving the load on pages without diagrams
# Set `mermaid: false` to opt out explicitly
specific: false

# See: http://mermaid-js.github.io/mermaid/
# 配置项与 mermaid 版本保持一致,可参考:https://mermaid.js.org/config/schema-docs/config.html
# Options follow the mermaid version schema, see: https://mermaid.js.org/config/schema-docs/config.html
options: { theme: 'default' }

# 评论插件
Expand Down Expand Up @@ -1136,7 +1146,7 @@ static_prefix:

clipboard: https://lib.baomitu.com/clipboard.js/2.0.11/

mermaid: https://lib.baomitu.com/mermaid/8.14.0/
mermaid: https://cdn.jsdelivr.net/npm/mermaid@11.16.0/dist/

valine: https://lib.baomitu.com/valine/1.5.1/

Expand Down
51 changes: 47 additions & 4 deletions layout/_partials/head.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,20 @@ var keywords = page.keywords || config.keywords
if (keywords instanceof Array) {
keywords = keywords.join(',')
}
var description = page.description || page.excerpt || (is_post() && page.content) || config.description
var description = page.description || page.excerpt || page.content || config.description
if (description) {
description = strip_html(description).substring(0, 200).trim().replace(/\n/g, ' ')
// 先剥标签再去实体,避免 "&amp;" 这类转义原样进入 meta 和 JSON-LD
// Strip tags first, then decode entities so escaped text stays readable in metadata
// 代码块内容不参与摘要,避免 meta 里出现整段源码
// Code blocks never belong in a summary
description = unescape_html(strip_html(strip_mermaid(description).replace(/<pre[\s\S]*?<\/pre>/gi, ' '))).substring(0, 200).trim().replace(/\n/g, ' ')
}
var ogImage = page.og_img || page.index_img
var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_graph)
// 正文首图优先于站点默认图,避免分享卡片千篇一律;只取绝对地址,
// 相对路径可能指向未提交的图片,分享卡片会从默认图退化成 404
// Only absolute content images: a broken relative path would replace the default card with a 404
var contentImage = ((page.content || '').match(/<img[^>]*\ssrc=["']((?:https?:)?\/\/[^"']+)["']/i) || [])[1]
var ogImage = page.og_img || page.index_img || contentImage || theme.open_graph.image
var ogConfig = Object.assign({ description: description }, theme.open_graph, { image: ogImage && url_for(ogImage) })
%>

<head>
Expand All @@ -35,6 +43,41 @@ var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_
<% } else { %>
<meta name="description" content="<%= description %>">
<% } %>
<%
// 结构化数据:文章输出 BlogPosting,首页输出 WebSite
// Structured data: BlogPosting for posts, WebSite for the home page
var jsonLd = null
var pageUrl = url_join(config.url, (page.canonical_path || page.path || '').replace('index.html', ''))
if (is_post()) {
jsonLd = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: page.title,
description: description,
url: pageUrl,
mainEntityOfPage: { '@type': 'WebPage', '@id': pageUrl },
author: { '@type': 'Person', name: page.author || config.author },
publisher: { '@type': 'Organization', name: config.title },
inLanguage: config.language
}
if (page.date) jsonLd.datePublished = page.date.toISOString()
if (page.updated || page.date) jsonLd.dateModified = (page.updated || page.date).toISOString()
if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image)
} else if (is_home() && page.current === 1) {
jsonLd = {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: config.title,
url: config.url,
description: description,
inLanguage: config.language
}
if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image)
}
%>
<% if (jsonLd) { %>
<%- json_ld(jsonLd) %>
<% } %>
<% if ((theme.post.meta.views.enable && theme.post.meta.views.source === 'busuanzi')
|| (theme.footer.statistics.enable && theme.footer.statistics.source === 'busuanzi')) { %>
<meta name="referrer" content="no-referrer-when-downgrade">
Expand Down
13 changes: 12 additions & 1 deletion layout/_partials/markdown-plugins.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@
<% if (theme.post.math.enable && (!theme.post.math.specific || (theme.post.math.specific && page.math))) { %>
<%- partial('_partials/plugins/math.ejs') %>
<% } %>
<% if (theme.post.mermaid.enable && (!theme.post.mermaid.specific || (theme.post.mermaid.specific && page.mermaid))) { %>
<%
// mermaid 块可能来自 ```mermaid 代码块、{% mermaid %} 标签,也可能是正文里的
// <div class="mermaid">;检测到页面内确实存在图表元素时才加载脚本,
// 特定模式下无需再手动写 Front-matter。
// Detect the elements mermaid will render, so that `specific: true` does not
// silently skip the script when the Front-matter flag is missing.
var hasMermaidBlock = has_mermaid(page.content || '');
var needMermaid = theme.post.mermaid.enable
&& page.mermaid !== false
&& (!theme.post.mermaid.specific || page.mermaid || hasMermaidBlock);
%>
<% if (needMermaid) { %>
<%- partial('_partials/plugins/mermaid.ejs') %>
<% } %>
39 changes: 31 additions & 8 deletions layout/_partials/plugins/mermaid.ejs
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
<script>
Fluid.utils.createScript('<%= url_join(theme.static_prefix.mermaid, 'mermaid.min.js') %>', function() {
mermaid.initialize(<%- JSON.stringify(theme.post.mermaid.options || {}) %>);
var mermaidUrl = '<%= url_join(theme.static_prefix.mermaid, 'mermaid.min.js') %>';
Fluid.utils.createScript(mermaidUrl, function() {
// 关闭 mermaid 的自动渲染,统一由 renderMermaid 控制渲染时机,
// 避免自动渲染发生在 initialize 应用配置之前
// Disable mermaid's automatic rendering so that the configuration is
// always applied before the first render
var options = Object.assign({}, <%- JSON.stringify(theme.post.mermaid.options || {}) %>, { startOnLoad: false });
mermaid.initialize(options);

Fluid.utils.listenDOMLoaded(function() {
Fluid.events.registerRefreshCallback(function() {
if ('mermaid' in window) {
mermaid.init();
}
var renderMermaid = function() {
if (!('mermaid' in window)) {
return;
}
// mermaid.init 自 mermaid 10 起已废弃,改用 mermaid.run
// mermaid.init is deprecated since mermaid 10, use mermaid.run instead
// 不要加 suppressErrors:run() 会逐图捕获错误、继续渲染其他图表,
// 最后统一 reject;加上 suppressErrors 会让这里的 catch 永远收不到错误
// Do not pass suppressErrors: run() handles errors per diagram, keeps
// rendering the others and rejects at the end. With suppressErrors the
// rejection is swallowed and this catch never runs.
// 传入 options 会覆盖默认的 querySelector,必须显式指定
// Passing options replaces the default querySelector, so set it explicitly
mermaid.run({ querySelector: '.mermaid' }).catch(function(err) {
console.error('[Fluid] Mermaid render failed:', err);
});
});
};

Fluid.utils.listenDOMLoaded(renderMermaid);
Fluid.events.registerRefreshCallback(renderMermaid);
}, function() {
// 脚本加载失败时图表会保持纯文本,这里给出可排查的提示
// Keep a diagnosable message when the script cannot be loaded
console.error('[Fluid] Failed to load mermaid from ' + mermaidUrl);
});
</script>
2 changes: 1 addition & 1 deletion layout/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ page.banner_mask_alpha = theme.index.banner_mask_alpha
<% var excerpt = post.description || post.excerpt || (theme.index.auto_excerpt.enable && !post.encrypt && post.content) %>
<a class="index-excerpt <%= index_img ? '' : 'index-excerpt__noimg' %>" href="<%= post_url %>" target="<%- theme.index.post_url_target %>">
<div>
<%- strip_html(excerpt).substring(0, 200).trim().replace(/\n/g, ' ') %>
<%- strip_html(strip_mermaid(excerpt)).substring(0, 200).trim().replace(/\n/g, ' ') %>
</div>
</a>

Expand Down
1 change: 1 addition & 0 deletions scripts/events/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ hexo.on('generateBefore', () => {
require('./lib/compatible-configs')(hexo);
require('./lib/injects')(hexo);
require('./lib/highlight')(hexo);
require('./lib/mermaid')(hexo);
require('./lib/lazyload')(hexo);
require('./lib/footnote')(hexo);
});
Expand Down
10 changes: 5 additions & 5 deletions scripts/events/lib/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ try {
const fs = require('fs');
const objUtil = require('../../utils/object');
const resolveModule = require('../../utils/resolve');
const { hasMermaidCode, toMermaidClass } = require('../../utils/mermaid');

module.exports = (hexo) => {

Expand Down Expand Up @@ -94,14 +95,14 @@ module.exports = (hexo) => {
hexo.extend.filter.register('after_post_render', (page) => {
if (hexo.config.highlight.line_number) {
page.content = page.content.replace(/<figure[^>]+?highlight.+?<td[^>]+?code[^>]+?>.*?(<pre.+?<\/pre>).+?<\/figure>/gims, (str, p1) => {
if (/<code[^>]+?mermaid[^>]+?>/ims.test(p1)) {
if (hasMermaidCode(p1)) {
return p1.replace(/(class="[^>]*?)hljs([^>]*?")/gims, '$1$2').replace(/<br>/gims, '\n');
}
return str;
});
} else {
page.content = page.content.replace(/(?<!<div class="code-wrapper">)<pre.+?<\/pre>/gims, (str) => {
if (/<code[^>]+?mermaid[^>]+?>/ims.test(str)) {
if (hasMermaidCode(str)) {
return str.replace(/(class=".*?)hljs(.*?")/gims, '$1$2');
}
return `<div class="code-wrapper">${str}</div>`;
Expand Down Expand Up @@ -133,12 +134,11 @@ module.exports = (hexo) => {

hexo.extend.filter.register('after_post_render', (page) => {
page.content = page.content.replace(/(?<!<div class="code-wrapper">)<pre.+?<\/pre>/gims, (str) => {
if (/<code[^>]+?mermaid[^>]+?>/ims.test(str)) {
if (hasMermaidCode(str)) {
if (hexo.config.highlight.line_number) {
str = str.replace(/<span[^>]+?line-numbers-rows[^>]+?>.+?<\/span><\/code>/, '</code>');
}
str = str.replace(/<pre[^>]*?>/gims, '<pre>')
.replace(/(class=".*?)language-mermaid(.*?")/gims, '$1mermaid$2')
str = toMermaidClass(str.replace(/<pre[^>]*?>/gims, '<pre>'))
.replace(/<span[^>]+?>(.+?)<\/span>/gims, '$1');
return str;
}
Expand Down
24 changes: 24 additions & 0 deletions scripts/events/lib/mermaid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/* global hexo */

'use strict';

const { hasMermaidElement } = require('../../utils/mermaid');

module.exports = (hexo) => {
// 构建期提示:页面里有 mermaid 块,但配置导致脚本不会被加载时给出警告,
// 避免图表被当成普通文本静默展示
// Build-time warning: the page contains mermaid blocks but the script will not
// be loaded, so the diagrams would silently show up as plain text
hexo.extend.filter.register('after_post_render', (page) => {
const config = hexo.theme.config.post.mermaid;
if (!config || !hasMermaidElement(page.content || '')) {
return page;
}
if (!config.enable) {
hexo.log.warn(`[Fluid] Mermaid block found in "${page.path}" but "post.mermaid.enable" is false, it will be rendered as plain text.`);
} else if (page.mermaid === false) {
hexo.log.warn(`[Fluid] Mermaid block found in "${page.path}" but it is disabled by "mermaid: false" in Front-matter.`);
}
return page;
});
};
9 changes: 9 additions & 0 deletions scripts/helpers/mermaid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* global hexo */

'use strict';

const { hasMermaidElement } = require('../utils/mermaid');

// EJS 模板里不能 require,检测逻辑通过 helper 暴露给 layout
// EJS templates cannot require modules, so expose the detector as a helper
hexo.extend.helper.register('has_mermaid', (content) => hasMermaidElement(content));
38 changes: 37 additions & 1 deletion scripts/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
'use strict';

const md5 = require('../utils/crypto');
const { decodeURL } = require('hexo-util');
const { decodeURL, unescapeHTML } = require('hexo-util');
const compareVersions = require('../../scripts/utils/compare-versions');

hexo.extend.helper.register('md5', function(string) {
Expand All @@ -27,3 +27,39 @@ hexo.extend.helper.register('deduplicate', function(arr) {
});

hexo.extend.helper.register('decode_url', decodeURL);

// 移除正文里的 mermaid 源码,避免图表代码进入摘要和 meta description
// Strip mermaid source so diagram code never leaks into excerpts or meta descriptions
// 只匹配独立的 mermaid 类名,避免误伤 mermaid-wrapper 之类的复合类名;单双引号都支持
// Match only the exact `mermaid` class token, so names like mermaid-wrapper survive
const MERMAID_BLOCK = /<(pre|div|code)\b[^>]*\bclass=(["'])(?:[^"']*\s)?(?:language-)?mermaid(?:\s[^"']*)?\2[^>]*>[\s\S]*?<\/\1>/gi;

hexo.extend.helper.register('strip_mermaid', function(html) {
// 第二步清掉只剩空壳的 <pre>,fenced 代码块被剥离后会留下它
// Second pass removes the empty <pre> left behind by a fenced block
return String(html || '').replace(MERMAID_BLOCK, ' ').replace(/<pre[^>]*>\s*<\/pre>/gi, ' ');
});

// 解码 HTML 实体,避免 "&amp;" 原样出现在 meta description 和 JSON-LD 里
// Decode HTML entities so escaped text does not leak into meta tags and JSON-LD
hexo.extend.helper.register('unescape_html', function(value) {
// hexo-util 只覆盖少量实体,这里补上十进制数字实体(如 &#123;)
// hexo-util covers only a few entities; decode decimal numerics as well
return unescapeHTML(String(value == null ? '' : value)).replace(/&#(\d+);/g, function(match, code) {
const n = Number(code);
if (!(n > 0 && n <= 0x10ffff) || (n >= 0xd800 && n <= 0xdfff)) {
return match;
}
return String.fromCodePoint(n);
});
});

// 输出 JSON-LD,转义 < 防止正文里的 </script> 提前闭合标签
// Emit JSON-LD with < escaped so content cannot close the script tag early
hexo.extend.helper.register('json_ld', function(data) {
if (!data) {
return '';
}
const json = JSON.stringify(data).replace(/</g, '\\u003c');
return `<script type="application/ld+json">${json}</script>`;
});
Loading
Loading