honkit
Version:
HonKit is building beautiful books using Markdown.
59 lines (56 loc) • 2.17 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const crc_1 = __importDefault(require("crc"));
const dom_serializer_1 = __importDefault(require("dom-serializer"));
const editHTMLElement_1 = __importDefault(require("./editHTMLElement"));
const fs_1 = __importDefault(require("../../utils/fs"));
const location_1 = __importDefault(require("../../utils/location"));
/**
Render a cheerio DOM as html
@param {HTMLDom} $
@param {HTMLElement} dom
@param {Object}
@return {string}
*/
function renderDOM($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options || dom.options || $._options;
return (0, dom_serializer_1.default)(dom, options);
}
/**
Replace SVG tag by IMG
@param {string} baseFolder
@param {HTMLDom} $
*/
function svgToImg(baseFolder, currentFile, $) {
const currentDirectory = path_1.default.dirname(currentFile);
return (0, editHTMLElement_1.default)($, "svg", ($svg) => {
if ($svg.attr("fill")) {
return;
}
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 2.
const content = `<?xml version="1.0" encoding="UTF-8"?>${renderDOM($, $svg)}`;
// We avoid generating twice the same PNG
const hash = crc_1.default.crc32(content).toString(16);
const fileName = `${hash}.svg`;
const filePath = path_1.default.join(baseFolder, fileName);
// Write the svg to the file
return (fs_1.default
.assertFile(filePath, () => {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 2 arguments, but got 3.
return fs_1.default.writeFile(filePath, content, "utf8");
})
// Return as image
.then(() => {
const src = location_1.default.relative(currentDirectory, fileName);
$svg.replaceWith(`<img src="${src}" />`);
}));
});
}
exports.default = svgToImg;