All files / src/render-enhancers embedded-svgs.ts

17.39% Statements 4/23
0% Branches 0/6
0% Functions 0/4
17.39% Lines 4/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 481x 1x   1x           1x                                                                            
import { readFile } from "fs";
import { extname } from "path";
import { MarkdownEngineConfig } from "../mume";
import { removeFileProtocol } from "../utility";
 
/**
 * Load local svg files and embed them into html directly.
 * @param $
 */
export default async function enhance(
  $: CheerioStatic,
  options: MarkdownEngineConfig,
  resolveFilePath: (path: string, useRelativeFilePath: boolean) => string,
): Promise<void> {
  const asyncFunctions = [];
  $("img").each((i, img) => {
    const $img = $(img);
    let src = resolveFilePath($img.attr("src"), false);
 
    const fileProtocolMatch = src.match(/^(file|vscode\-resource):\/\/+/);
    if (fileProtocolMatch) {
      src = removeFileProtocol(src);
      src = src.replace(/\?(\.|\d)+$/, ""); // remove cache
      const imageType = extname(src).slice(1);
      if (imageType !== "svg") {
        return;
      }
      asyncFunctions.push(
        new Promise((resolve, reject) => {
          readFile(decodeURI(src), (error, data) => {
            if (error) {
              return resolve(null);
            }
            const base64 = new Buffer(data).toString("base64");
            $img.attr(
              "src",
              `data:image/svg+xml;charset=utf-8;base64,${base64}`,
            );
            return resolve(base64);
          });
        }),
      );
    }
  });
 
  await Promise.all(asyncFunctions);
}