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
44 changes: 36 additions & 8 deletions extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ function convertMarkdownToHtml(filename, type, text) {
}

// convert the img src of the markdown
var cheerio = require('cheerio');
var defaultRender = md.renderer.rules.image;
md.renderer.rules.image = function (tokens, idx, options, env, self) {
var token = tokens[idx];
Expand All @@ -203,16 +202,11 @@ function convertMarkdownToHtml(filename, type, text) {
};

if (type !== 'html') {
const converter = convertHtmlImgPath(filename);
// convert the img src of the html
md.renderer.rules.html_block = function (tokens, idx) {
var html = tokens[idx].content;
var $ = cheerio.load(html);
$('img').each(function () {
var src = $(this).attr('src');
var href = convertImgPath(src, filename);
$(this).attr('src', href);
});
return $.html();
return converter(html);
};
}

Expand Down Expand Up @@ -638,6 +632,40 @@ function readFile(filename, encode) {
}
}

function convertHtmlImgPath(filename) {
let output = '';
const parser = require('htmlparser2');
const p = new parser.Parser({
onclosetag(name, isImplied) {
if (isImplied) return;
output += `</${name}>`
},
onopentag(name, attribs, isImplied) {
if (isImplied) return;

if (name === 'img') {
var src = attribs['src'];
var href = convertImgPath(src, filename);
attribs['src'] = href;
}
const attrStr = Object.entries(attribs).map(([k, v]) => `${k}="${v}"`).join(' ');
output += `<${name} ${attrStr}>`
},
ontext(data) {
output += data;
},
oncomment(data) {
output += `<!--${data}-->`
},
}, { decodeEntities: false, });
return function (input) {
p.write(input);
const result = output;
output = '';
return result;
}
}

function convertImgPath(src, filename) {
try {
var href = decodeURIComponent(src);
Expand Down
Loading