feat: 动态页面
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const moment = require('moment');
|
||||
const { slugize } = require('hexo-util');
|
||||
|
||||
/**
|
||||
* 新建一条动态
|
||||
* 用法:hexo dynamics "今天的晚霞" [--slug custom-slug]
|
||||
* 生成:source/dynamics/<slug>/index.md,该目录同时用于放置配图等资源
|
||||
*/
|
||||
hexo.extend.console.register('dynamics', '新建一条动态(source/dynamics/)', {
|
||||
arguments: [
|
||||
{ name: 'title', desc: '动态标题,可以省略' }
|
||||
],
|
||||
options: [
|
||||
{ name: 'slug', desc: '自定义文件/目录名' }
|
||||
]
|
||||
}, function(args) {
|
||||
const title = (args._ || []).join(' ').replace(/[\r\n]+/g, ' ').trim();
|
||||
const now = moment();
|
||||
const timestamp = now.format('YYYYMMDD-HHmmss');
|
||||
|
||||
let slug = path.basename(String(args.slug || ''));
|
||||
if (!slug && title) {
|
||||
slug = slugize(title, { transform: this.config.filename_case });
|
||||
}
|
||||
slug = slug
|
||||
.replace(/[\\/:*?"<>|\s]+/g, '-')
|
||||
.replace(/^\.+/, '')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
if (!slug || slug === 'index') {
|
||||
slug = title ? `${timestamp}-${slug}`.replace(/-+$/, '') : timestamp;
|
||||
}
|
||||
|
||||
const dynamicsDir = path.join(this.source_dir, 'dynamics');
|
||||
const noteDir = path.join(dynamicsDir, slug);
|
||||
const noteFile = path.join(noteDir, 'index.md');
|
||||
|
||||
// 防止 --slug 通过 .. 等方式写到动态目录之外
|
||||
if (path.resolve(noteDir) !== path.join(path.resolve(dynamicsDir), slug)) {
|
||||
this.log.error('非法的 slug:%s', slug);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (fs.existsSync(noteFile)) {
|
||||
this.log.error('动态已存在:%s', path.relative(this.base_dir, noteFile));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
// 用 JSON 字符串作为 YAML 标量,避免标题里的 : # 等字符破坏 Front-matter
|
||||
const frontMatter = [
|
||||
'---',
|
||||
`title: ${JSON.stringify(title || now.format('YYYY-MM-DD HH:mm'))}`,
|
||||
`date: ${now.format('YYYY-MM-DD HH:mm:ss')}`,
|
||||
'tags:',
|
||||
'---',
|
||||
'',
|
||||
''
|
||||
].join('\n');
|
||||
|
||||
fs.mkdirSync(noteDir, { recursive: true });
|
||||
fs.writeFileSync(noteFile, frontMatter, 'utf8');
|
||||
|
||||
this.log.info('Created: %s', path.relative(this.base_dir, noteFile));
|
||||
this.log.info('把图片放在 %s 目录,正文里用  即可引用;然后运行 hexo generate',
|
||||
path.relative(this.base_dir, noteDir));
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { url_for } = require('hexo-util');
|
||||
|
||||
const DYNAMICS_DIR = 'dynamics/';
|
||||
const ABSOLUTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/|\?)/i;
|
||||
const FENCE_OPEN_RE = /^\s{0,3}(`{3,}|~{3,})/;
|
||||
const INDENTED_CODE_RE = /^(?: {4,}|\t)/;
|
||||
const TAG_CODE_OPEN_RE = /\{%\s*(codeblock|code|raw)\b/;
|
||||
const TAG_CODE_CLOSE_RE = /\{%\s*end(?:codeblock|code|raw)\s*%\}/;
|
||||
const CODE_BLOCK_OPEN = '<hexoPostRenderCodeBlock>';
|
||||
const CODE_BLOCK_CLOSE = '</hexoPostRenderCodeBlock>';
|
||||
const PH_OPEN = '\uE000DYNAMICS_PH_';
|
||||
const PH_CLOSE = '\uE001';
|
||||
const PLACEHOLDER_RE = /\uE000DYNAMICS_PH_(\d+)\uE001/g;
|
||||
|
||||
const isDynamicSource = (source) => {
|
||||
return typeof source === 'string' && source.indexOf(DYNAMICS_DIR) === 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态页面的资源路径基准:把 Windows 反斜杠规范化,并去掉文件名 / index.html,
|
||||
* 最终得到形如 /dynamics/foo/ 的绝对 URL。
|
||||
*/
|
||||
const getBaseUrl = (pagePath) => {
|
||||
if (!pagePath) {
|
||||
return '';
|
||||
}
|
||||
let dir = String(pagePath).replace(/\\/g, '/');
|
||||
if (/index\.html?$/i.test(dir)) {
|
||||
dir = dir.replace(/index\.html?$/i, '');
|
||||
} else {
|
||||
dir = dir.replace(/[^/]*$/, '');
|
||||
}
|
||||
if (!dir) {
|
||||
return '';
|
||||
}
|
||||
const url = url_for.call(hexo, dir);
|
||||
return url.endsWith('/') ? url : `${url}/`;
|
||||
};
|
||||
|
||||
const rewriteUrl = (url, base) => {
|
||||
if (!url || ABSOLUTE_URL_RE.test(url)) {
|
||||
return url;
|
||||
}
|
||||
const joined = `${base}${url.replace(/^\.\//, '')}`.replace(/\\/g, '/');
|
||||
return path.posix.normalize(joined);
|
||||
};
|
||||
|
||||
const protect = (matched, protectedParts) => {
|
||||
protectedParts.push(matched);
|
||||
return `${PH_OPEN}${protectedParts.length - 1}${PH_CLOSE}`;
|
||||
};
|
||||
|
||||
// 单行内的 markdown 链接 / 图片、引用式定义、内嵌 HTML 标签
|
||||
const rewriteLine = (line, base) => {
|
||||
if (!line || (line.indexOf('](') === -1 && line.indexOf('<') === -1
|
||||
&& !/^\s{0,3}\[[^\]\n]+\]:/.test(line))) {
|
||||
return line;
|
||||
}
|
||||
|
||||
const protectedParts = [];
|
||||
let result = line;
|
||||
|
||||
// 保护行内代码、转义的 markdown 语法和脚注语法,避免误改
|
||||
result = result.replace(/(`+)[\s\S]*?\1/g, (match) => protect(match, protectedParts));
|
||||
// 转义的链接整体保留;转义的感叹号只保护自身,后面的链接目标仍然可以补全
|
||||
result = result.replace(/\\\[[^\]]*\]\([^)]*\)/g, (match) => protect(match, protectedParts));
|
||||
result = result.replace(/\\!/g, (match) => protect(match, protectedParts));
|
||||
result = result.replace(/\[\^\d+\]\([^)]*\)/g, (match) => protect(match, protectedParts));
|
||||
|
||||
// Markdown 图片与链接: / [text](file.zip)
|
||||
result = result.replace(/(\]\()(<[^>\n]*>|[^)\s]+)/g, (match, prefix, target) => {
|
||||
if (target.startsWith('<') && target.endsWith('>')) {
|
||||
return `${prefix}<${rewriteUrl(target.slice(1, -1), base)}>`;
|
||||
}
|
||||
return prefix + rewriteUrl(target, base);
|
||||
});
|
||||
|
||||
// 引用式链接定义:[id]: file.png(脚注定义 [^1]: 内容 不处理)
|
||||
result = result.replace(/^(\s{0,3}\[(?!\^)[^\]\n]+\]:[ \t]*)(<?)([^\s>]+)(>?)/,
|
||||
(match, prefix, open, target, close) => {
|
||||
return prefix + open + rewriteUrl(target, base) + close;
|
||||
});
|
||||
|
||||
// 正文里直接写的 HTML 标签
|
||||
result = result.replace(/(<(?:img|a|video|audio|source)\b[^>]*?\b(?:src|href)=)(["'])(.*?)\2/gi,
|
||||
(match, prefix, quote, target) => `${prefix}${quote}${rewriteUrl(target, base)}${quote}`);
|
||||
|
||||
return result.replace(PLACEHOLDER_RE, (match, index) => protectedParts[Number(index)] || '');
|
||||
};
|
||||
|
||||
/**
|
||||
* 与文章一致:动态正文里的相对图片 / 附件路径按该动态详情页的地址补全,
|
||||
* 这样动态既可以直接引用站内绝对路径(/img/xxx.png),
|
||||
* 也可以把图片放在动态自己的目录里用相对路径引用()。
|
||||
*
|
||||
* 注意:hexo-renderer-marked 默认会把相对图片地址加上站点根路径(prependRoot),
|
||||
* 所以在 markdown 渲染之前先转换成绝对地址;代码块 / 行内代码 / 脚注语法保持原样。
|
||||
* 用 priority 9 保证在 Hexo 自带的 backtick_code_block 之前执行,
|
||||
* 从而能按原始的 markdown 代码围栏跳过代码块。
|
||||
*/
|
||||
hexo.extend.filter.register('before_post_render', function(data) {
|
||||
if (!data || !isDynamicSource(data.source) || !data.content) {
|
||||
return data;
|
||||
}
|
||||
|
||||
const base = getBaseUrl(data.path);
|
||||
if (!base) {
|
||||
return data;
|
||||
}
|
||||
|
||||
let fenceChar = '';
|
||||
let fenceLength = 0;
|
||||
let inTagCode = false;
|
||||
let inIndentedCode = false;
|
||||
let inCodeBlock = false;
|
||||
let prevBlank = true;
|
||||
|
||||
data.content = data.content.split('\n').map((line) => {
|
||||
const isBlank = line.trim() === '';
|
||||
let result = line;
|
||||
|
||||
// 兼容其它 filter 已经处理成占位符的代码块(防御性判断)
|
||||
if (inCodeBlock) {
|
||||
if (line.indexOf(CODE_BLOCK_CLOSE) !== -1) {
|
||||
inCodeBlock = false;
|
||||
}
|
||||
}
|
||||
else if (line.indexOf(CODE_BLOCK_OPEN) !== -1) {
|
||||
inCodeBlock = true;
|
||||
}
|
||||
else if (TAG_CODE_OPEN_RE.test(line)) {
|
||||
if (!TAG_CODE_CLOSE_RE.test(line)) {
|
||||
inTagCode = true;
|
||||
}
|
||||
}
|
||||
else if (inTagCode) {
|
||||
if (TAG_CODE_CLOSE_RE.test(line)) {
|
||||
inTagCode = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const fence = FENCE_OPEN_RE.exec(line);
|
||||
if (fence) {
|
||||
const run = fence[1];
|
||||
const char = run.charAt(0);
|
||||
if (!fenceChar) {
|
||||
fenceChar = char;
|
||||
fenceLength = run.length;
|
||||
}
|
||||
else if (char === fenceChar && run.length >= fenceLength) {
|
||||
fenceChar = '';
|
||||
fenceLength = 0;
|
||||
}
|
||||
}
|
||||
else if (fenceChar) {
|
||||
// 代码围栏内,保持原样
|
||||
}
|
||||
else {
|
||||
const isIndented = INDENTED_CODE_RE.test(line);
|
||||
if (inIndentedCode) {
|
||||
if (!isBlank && !isIndented) {
|
||||
inIndentedCode = false;
|
||||
}
|
||||
}
|
||||
else if (isIndented && prevBlank) {
|
||||
// 4 空格 / Tab 缩进的代码块
|
||||
inIndentedCode = true;
|
||||
}
|
||||
if (!inIndentedCode) {
|
||||
result = rewriteLine(line, base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
prevBlank = isBlank;
|
||||
return result;
|
||||
}).join('\n');
|
||||
|
||||
return data;
|
||||
}, 9);
|
||||
@@ -0,0 +1,121 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
const pagination = require('hexo-pagination');
|
||||
|
||||
const DYNAMICS_DIR = 'dynamics';
|
||||
const DEFAULT_PER_PAGE = 10;
|
||||
|
||||
/**
|
||||
* 动态文件统一存放在 source/dynamics/ 目录下,和文章一样是 Markdown + Front-matter。
|
||||
* 支持扁平文件(source/dynamics/foo.md)和文件夹形式(source/dynamics/foo/index.md)。
|
||||
* 该目录下的所有 page 都会被识别为动态,列表页由本 generator 生成。
|
||||
*/
|
||||
const isDynamicPage = (page) => {
|
||||
return page
|
||||
&& typeof page.source === 'string'
|
||||
&& page.source.indexOf(`${DYNAMICS_DIR}/`) === 0
|
||||
&& page.source !== `${DYNAMICS_DIR}/index.md`;
|
||||
};
|
||||
|
||||
const compareNotes = (a, b) => {
|
||||
// top: true 置顶,其余按时间倒序
|
||||
const topA = a.top === true ? 1 : 0;
|
||||
const topB = b.top === true ? 1 : 0;
|
||||
if (topA !== topB) {
|
||||
return topB - topA;
|
||||
}
|
||||
const dateA = a.date ? new Date(a.date).getTime() : 0;
|
||||
const dateB = b.date ? new Date(b.date).getTime() : 0;
|
||||
return dateB - dateA;
|
||||
};
|
||||
|
||||
const normalizeBase = (path) => {
|
||||
let base = typeof path === 'string' ? path.trim() : '';
|
||||
base = base.replace(/^\/+/, '').replace(/\/+$/, '');
|
||||
if (!base) {
|
||||
base = DYNAMICS_DIR;
|
||||
}
|
||||
return `${base}/`;
|
||||
};
|
||||
|
||||
// 给 source/dynamics/ 下的页面套用动态详情页布局
|
||||
const originalPageGenerator = hexo.extend.generator.get('page');
|
||||
|
||||
if (originalPageGenerator) {
|
||||
hexo.extend.generator.register('page', function(locals) {
|
||||
return Promise.resolve(originalPageGenerator.call(this, locals)).then((routes) => {
|
||||
if (!Array.isArray(routes)) {
|
||||
return routes;
|
||||
}
|
||||
return routes.map((route) => {
|
||||
if (route && route.layout && isDynamicPage(route.data)) {
|
||||
const layouts = Array.isArray(route.layout) ? route.layout.slice() : [route.layout];
|
||||
if (layouts[0] !== 'dynamics-note') {
|
||||
layouts.unshift('dynamics-note');
|
||||
}
|
||||
route.layout = layouts;
|
||||
}
|
||||
return route;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
hexo.extend.generator.register('_dynamics', function(locals) {
|
||||
const config = this.theme.config.dynamics || {};
|
||||
if (config.enable === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allPages = typeof locals.pages.toArray === 'function' ? locals.pages.toArray() : [];
|
||||
|
||||
if (allPages.some((page) => page.source === `${DYNAMICS_DIR}/index.md`)) {
|
||||
this.log.warn(
|
||||
'[Fluid] 检测到 source/dynamics/index.md,动态列表页由主题自动生成,请删除该文件,' +
|
||||
'否则会与自动生成的 /dynamics/ 页面冲突'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const notes = allPages.filter(isDynamicPage).sort(compareNotes);
|
||||
const base = normalizeBase(config.path);
|
||||
const paginationDir = this.config.pagination_dir || 'page';
|
||||
|
||||
let perPage = Number.parseInt(config.per_page, 10);
|
||||
if (Number.isNaN(perPage)) {
|
||||
perPage = DEFAULT_PER_PAGE;
|
||||
} else if (perPage < 0) {
|
||||
this.log.warn('[Fluid] dynamics.per_page 不能为负数,已回退为 %d', DEFAULT_PER_PAGE);
|
||||
perPage = DEFAULT_PER_PAGE;
|
||||
}
|
||||
|
||||
const data = {
|
||||
dynamics_total: notes.length
|
||||
};
|
||||
|
||||
if (!notes.length) {
|
||||
return [{
|
||||
path: base,
|
||||
layout: 'dynamics',
|
||||
data: Object.assign({
|
||||
posts: [],
|
||||
base,
|
||||
total: 1,
|
||||
current: 1,
|
||||
prev: 0,
|
||||
prev_link: '',
|
||||
next: 0,
|
||||
next_link: ''
|
||||
}, data)
|
||||
}];
|
||||
}
|
||||
|
||||
return pagination(base, notes, {
|
||||
perPage,
|
||||
layout: 'dynamics',
|
||||
format: `${paginationDir}/%d/`,
|
||||
data
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
// 已经是绝对地址 / 协议地址 / 锚点 / 查询参数,不需要补全
|
||||
const ABSOLUTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/|\?)/i;
|
||||
|
||||
const rewriteUrl = (value, base) => {
|
||||
if (typeof value !== 'string' || !value || ABSOLUTE_URL_RE.test(value)) {
|
||||
return value;
|
||||
}
|
||||
return base + value.replace(/^\.\//, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态列表页会复用多个页面的正文,正文中的相对资源地址会以列表页为基准而失效,
|
||||
* 这里把它们统一改写为相对于该动态详情页的绝对路径。
|
||||
*/
|
||||
hexo.extend.helper.register('dynamics_content', function(content, page) {
|
||||
if (!content || !page || !page.path) {
|
||||
return content || '';
|
||||
}
|
||||
|
||||
const pageUrl = this.url_for(page.path);
|
||||
const base = pageUrl.substring(0, pageUrl.lastIndexOf('/') + 1);
|
||||
if (!base) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return content
|
||||
.replace(/(<img\b[^>]*?\bsrc=")([^"]*)(")/gi,
|
||||
(match, prefix, value, suffix) => prefix + rewriteUrl(value, base) + suffix)
|
||||
.replace(/(<(?:video|audio|source)\b[^>]*?\bsrc=")([^"]*)(")/gi,
|
||||
(match, prefix, value, suffix) => prefix + rewriteUrl(value, base) + suffix)
|
||||
.replace(/(<a\b[^>]*?\bhref=")([^"]*)(")/gi,
|
||||
(match, prefix, value, suffix) => prefix + rewriteUrl(value, base) + suffix);
|
||||
});
|
||||
Reference in New Issue
Block a user