@diplodoc/transform
Version:
A simple transformer of text in YFM (Yandex Flavored Markdown) to HTML
104 lines • 3.77 kB
JavaScript
;
const path_1 = require("path");
const chalk_1 = require("chalk");
const svgo_1 = require("svgo");
const fs_1 = require("fs");
const utilsFS_1 = require("../../utilsFS");
const utils_1 = require("../../utils");
function replaceImageSrc(token, state, { assetsPublicPath = path_1.sep, root = '', path: optsPath, log }) {
var _a;
const src = (0, utils_1.getSrcTokenAttr)(token);
const currentPath = state.env.path || optsPath;
if (!(0, utils_1.isLocalUrl)(src)) {
return;
}
const path = (0, utilsFS_1.resolveRelativePath)(currentPath, src);
if ((0, utilsFS_1.isFileExists)(path)) {
(_a = state.md.assets) === null || _a === void 0 ? void 0 : _a.push(src);
}
else {
log.error(`Asset not found: ${(0, chalk_1.bold)(src)} in ${(0, chalk_1.bold)(currentPath)}`);
}
const relativeToRoot = path.replace(root + path_1.sep, '');
const publicSrc = (0, path_1.join)(assetsPublicPath, relativeToRoot);
token.attrSet('src', publicSrc);
}
function prefix() {
const value = Math.floor(Math.random() * 1e9);
return 'rnd-' + value.toString(16);
}
function convertSvg(token, state, { path: optsPath, log, notFoundCb, root }) {
const currentPath = state.env.path || optsPath;
const path = (0, utilsFS_1.resolveRelativePath)(currentPath, (0, utils_1.getSrcTokenAttr)(token));
try {
const raw = (0, fs_1.readFileSync)(path).toString();
const result = (0, svgo_1.optimize)(raw, {
plugins: [
{
name: 'prefixIds',
params: {
prefix: prefix(),
prefixClassNames: false,
},
},
],
});
const content = result.data;
const svgToken = new state.Token('image_svg', '', 0);
svgToken.attrSet('content', content);
return svgToken;
}
catch (e) {
log.error(`SVG ${path} from ${currentPath} not found`);
if (notFoundCb) {
notFoundCb(path.replace(root, ''));
}
return token;
}
}
const index = (md, opts) => {
md.assets = [];
const plugin = (state) => {
const tokens = state.tokens;
let i = 0;
while (i < tokens.length) {
if (tokens[i].type !== 'inline') {
i++;
continue;
}
const childrenTokens = tokens[i].children || [];
let j = 0;
while (j < childrenTokens.length) {
if (childrenTokens[j].type === 'image') {
const didPatch = childrenTokens[j].attrGet('yfm_patched') || false;
if (didPatch) {
return;
}
const imgSrc = (0, utils_1.getSrcTokenAttr)(childrenTokens[j]);
const shouldInlineSvg = opts.inlineSvg !== false && !(0, utils_1.isExternalHref)(imgSrc);
if (imgSrc.endsWith('.svg') && shouldInlineSvg) {
childrenTokens[j] = convertSvg(childrenTokens[j], state, opts);
}
else {
replaceImageSrc(childrenTokens[j], state, opts);
}
childrenTokens[j].attrSet('yfm_patched', '1');
}
j++;
}
i++;
}
};
try {
md.core.ruler.before('includes', 'images', plugin);
}
catch (e) {
md.core.ruler.push('images', plugin);
}
md.renderer.rules.image_svg = (tokens, index) => {
const token = tokens[index];
return token.attrGet('content') || '';
};
};
module.exports = index;
//# sourceMappingURL=index.js.map