1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-21 09:38:01 +02:00
joplin/ReactNativeClient/lib/htmlUtils.js

115 lines
2.4 KiB
JavaScript
Raw Normal View History

const urlUtils = require('lib/urlUtils.js');
const Entities = require('html-entities').AllHtmlEntities;
2019-07-29 15:43:53 +02:00
const htmlentities = new Entities().encode;
// [\s\S] instead of . for multiline matching
// https://stackoverflow.com/a/16119722/561309
2019-07-29 15:43:53 +02:00
const imageRegex = /<img([\s\S]*?)src=["']([\s\S]*?)["']([\s\S]*?)>/gi;
const anchorRegex = /<a([\s\S]*?)href=["']([\s\S]*?)["']([\s\S]*?)>/gi;
const selfClosingElements = [
'area',
'base',
'basefont',
'br',
'col',
'command',
'embed',
'frame',
'hr',
'img',
'input',
'isindex',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr',
];
class HtmlUtils {
headAndBodyHtml(doc) {
const output = [];
if (doc.head) output.push(doc.head.innerHTML);
if (doc.body) output.push(doc.body.innerHTML);
return output.join('\n');
}
isSelfClosingTag(tagName) {
return selfClosingElements.includes(tagName.toLowerCase());
}
extractImageUrls(html) {
if (!html) return [];
2019-07-19 19:18:05 +02:00
const output = [];
let matches;
2019-07-29 15:43:53 +02:00
while ((matches = imageRegex.exec(html))) {
output.push(matches[2]);
}
return output.filter(url => !!url);
}
replaceImageUrls(html, callback) {
return this.processImageTags(html, data => {
const newSrc = callback(data.src);
return {
type: 'replaceSource',
src: newSrc,
};
});
}
processImageTags(html, callback) {
if (!html) return '';
return html.replace(imageRegex, (v, before, src, after) => {
const action = callback({ src: src });
2019-09-19 23:51:18 +02:00
if (!action) return `<img${before}src="${src}"${after}>`;
if (action.type === 'replaceElement') {
return action.html;
}
if (action.type === 'replaceSource') {
2019-09-19 23:51:18 +02:00
return `<img${before}src="${action.src}"${after}>`;
}
if (action.type === 'setAttributes') {
const attrHtml = this.attributesHtml(action.attrs);
2019-09-19 23:51:18 +02:00
return `<img${before}${attrHtml}${after}>`;
}
2019-09-19 23:51:18 +02:00
throw new Error(`Invalid action: ${action.type}`);
});
}
prependBaseUrl(html, baseUrl) {
if (!html) return '';
return html.replace(anchorRegex, (v, before, href, after) => {
const newHref = urlUtils.prependBaseUrl(href, baseUrl);
2019-09-19 23:51:18 +02:00
return `<a${before}href="${newHref}"${after}>`;
});
}
attributesHtml(attr) {
const output = [];
for (const n in attr) {
if (!attr.hasOwnProperty(n)) continue;
2019-09-19 23:51:18 +02:00
output.push(`${n}="${htmlentities(attr[n])}"`);
}
return output.join(' ');
}
}
const htmlUtils = new HtmlUtils();
2019-07-29 15:43:53 +02:00
module.exports = htmlUtils;