diff --git a/lib/renderer.js b/lib/renderer.js index c659ee7..c5e3137 100644 --- a/lib/renderer.js +++ b/lib/renderer.js @@ -3,7 +3,6 @@ const marked = require('marked'); const { encodeURL, slugize, stripHTML, url_for, isExternalLink } = require('hexo-util'); const MarkedRenderer = marked.Renderer; -const { sep } = require('path'); const anchorId = (str, transformOption) => { return slugize(str.trim(), {transform: transformOption}); @@ -91,14 +90,15 @@ class Renderer extends MarkedRenderer { image(href, title, text) { const { hexo, options } = this; const { relative_link } = hexo.config; - const { lazyload, prependRoot, postId } = options; + const { lazyload, prependRoot, postPath } = options; if (!/^(#|\/\/|http(s)?:)/.test(href) && !relative_link && prependRoot) { - if (!/^(\/|\\)/.test(href) && postId) { + if (!href.startsWith('/') && !href.startsWith('\\') && postPath) { const PostAsset = hexo.model('PostAsset'); - // slug requires platform-specific path - const asset = PostAsset.findOne({ post: postId, slug: href.replace(/\/|\\/g, sep) }); - if (asset) href = encodeURL(('/' + asset.path).replace(/\\/g, '/').replace(/\/{2,}/g, '/')); + // findById requires forward slash + const asset = PostAsset.findById(postPath + href.replace(/\\/g, '/')); + // asset.path is backward slash in Windows + if (asset) href = asset.path.replace(/\\/g, '/'); } href = url_for.call(hexo, href); } @@ -118,7 +118,7 @@ marked.setOptions({ }); module.exports = function(data, options) { - const { post_asset_folder, marked: markedCfg } = this.config; + const { post_asset_folder, marked: markedCfg, source_dir } = this.config; const { prependRoot, postAsset } = markedCfg; const { path, text } = data; @@ -126,16 +126,16 @@ module.exports = function(data, options) { const renderer = new Renderer(this); this.execFilterSync('marked:renderer', renderer, {context: this}); - let postId = ''; + let postPath = ''; if (path && post_asset_folder && prependRoot && postAsset) { const Post = this.model('Post'); // Windows compatibility, Post.findOne() requires forward slash - const source = path.replace(this.source_dir, '').replace('\\', '/'); + const source = path.substring(this.source_dir.length).replace(/\\/g, '/'); const post = Post.findOne({ source }); - postId = post ? post._id : ''; + postPath = post ? source_dir + '/_posts/' + post.slug + '/' : ''; } return marked(text, Object.assign({ renderer - }, markedCfg, options, { postId })); + }, markedCfg, options, { postPath })); };