vuepress-plugin-photomap
Version:
VuePress2插件,用于在文章中插入照片地图组件,类似Apple相册的PhotoMap功能
66 lines (65 loc) • 3 kB
JavaScript
import { path } from '@vuepress/utils';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// ES模块中获取__dirname的替代方案
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export const photoMapPlugin = (options = {}) => {
return {
name: 'vuepress-plugin-photomap',
// 注册全局组件
clientConfigFile: path.resolve(__dirname, './client/clientConfig.js'),
// 定义markdown容器
extendsMarkdown: async (md) => {
// 使用动态导入
const container = (await import('markdown-it-container')).default || await import('markdown-it-container');
md.use(container, 'photomap', {
validate: (params) => {
return params.trim().match(/^photomap\s*(.*)$/);
},
render: (tokens, idx) => {
if (tokens[idx].nesting === 1) {
// 开始标签 - 提取容器内的图片
let imageList = [];
let currentIdx = idx + 1;
// 查找容器内的所有图片
while (currentIdx < tokens.length && tokens[currentIdx].nesting !== -1) {
const token = tokens[currentIdx];
if (token.type === 'paragraph_open') {
currentIdx++;
continue;
}
if (token.type === 'inline') {
// 解析inline内容中的图片
const imageMatches = token.content.match(/!\[([^\]]*)\]\(([^)]+)\)/g);
if (imageMatches) {
imageMatches.forEach((match) => {
const imgMatch = match.match(/!\[([^\]]*)\]\(([^)]+)\)/);
if (imgMatch) {
const alt = imgMatch[1] || '';
const src = imgMatch[2];
imageList.push(JSON.stringify({ src, alt }));
}
});
}
}
currentIdx++;
}
// 生成PhotoMap组件标签
const imagesJson = `[${imageList.join(',')}]`;
return `<PhotoMap :images='${imagesJson}'>\n`;
}
else {
// 结束标签
return `</PhotoMap>\n`;
}
}
});
},
// 插件选项
define: {
__PHOTOMAP_OPTIONS__: options
}
};
};
export default photoMapPlugin;