2020-10-21 01:23:55 +02:00
|
|
|
import { RuleOptions } from "lib/joplin-renderer/MdToHtml";
|
|
|
|
|
2020-01-30 23:05:23 +02:00
|
|
|
const htmlUtils = require('../../htmlUtils.js');
|
|
|
|
const utils = require('../../utils');
|
|
|
|
|
2020-10-21 01:23:55 +02:00
|
|
|
function renderImageHtml(before:string, src:string, after:string, ruleOptions:RuleOptions) {
|
2020-08-18 22:52:00 +02:00
|
|
|
const r = utils.imageReplacement(ruleOptions.ResourceModel, src, ruleOptions.resources, ruleOptions.resourceBaseUrl);
|
2020-01-30 23:05:23 +02:00
|
|
|
if (typeof r === 'string') return r;
|
|
|
|
if (r) return `<img ${before} ${htmlUtils.attributesHtml(r)} ${after}/>`;
|
|
|
|
return `[Image: ${src}]`;
|
|
|
|
}
|
|
|
|
|
2020-10-21 01:23:55 +02:00
|
|
|
function plugin(markdownIt:any, ruleOptions:RuleOptions) {
|
2020-01-30 23:05:23 +02:00
|
|
|
const Resource = ruleOptions.ResourceModel;
|
|
|
|
|
|
|
|
const htmlBlockDefaultRender =
|
|
|
|
markdownIt.renderer.rules.html_block ||
|
2020-10-21 01:23:55 +02:00
|
|
|
function(tokens:any[], idx:number, options:any, _env:any, self:any) {
|
2020-01-30 23:05:23 +02:00
|
|
|
return self.renderToken(tokens, idx, options);
|
|
|
|
};
|
|
|
|
|
|
|
|
const htmlInlineDefaultRender =
|
|
|
|
markdownIt.renderer.rules.html_inline ||
|
2020-10-21 01:23:55 +02:00
|
|
|
function(tokens:any[], idx:number, options:any, _env:any, self:any) {
|
2020-01-30 23:05:23 +02:00
|
|
|
return self.renderToken(tokens, idx, options);
|
|
|
|
};
|
|
|
|
|
|
|
|
const imageRegex = /<img(.*?)src=["'](.*?)["'](.*?)>/gi;
|
|
|
|
|
2020-10-21 01:23:55 +02:00
|
|
|
const handleImageTags = function(defaultRender:Function) {
|
|
|
|
return function(tokens:any[], idx:number, options:any, env:any, self:any) {
|
2020-01-30 23:05:23 +02:00
|
|
|
const token = tokens[idx];
|
|
|
|
const content = token.content;
|
|
|
|
|
|
|
|
if (!content.match(imageRegex)) return defaultRender(tokens, idx, options, env, self);
|
|
|
|
|
2020-10-21 01:23:55 +02:00
|
|
|
return content.replace(imageRegex, (_v:any, before:string, src:string, after:string) => {
|
2020-03-06 02:54:21 +02:00
|
|
|
if (!Resource.isResourceUrl(src)) return `<img${before}src="${src}"${after}>`;
|
2020-01-30 23:05:23 +02:00
|
|
|
return renderImageHtml(before, src, after, ruleOptions);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
// It seems images sometimes are inline, sometimes a block
|
|
|
|
// to make sure they both render correctly.
|
|
|
|
markdownIt.renderer.rules.html_block = handleImageTags(htmlBlockDefaultRender);
|
|
|
|
markdownIt.renderer.rules.html_inline = handleImageTags(htmlInlineDefaultRender);
|
|
|
|
}
|
|
|
|
|
2020-10-21 01:23:55 +02:00
|
|
|
export default { plugin }
|