All files / src/render-enhancers fenced-code-chunks.ts

9.09% Statements 11/121
0% Branches 0/75
20% Functions 1/5
9.09% Lines 11/121

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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282  1x   1x   1x   1x           1x 1x 1x                                                 1x     1x                                                                                                                                                                                                                   1x                                                                                                                                                                                                                                               1x                        
// tslint:disable:ban-types no-var-requires
import { run } from "../code-chunk";
import { CodeChunkData, CodeChunksData } from "../code-chunk-data";
import { BlockInfo, extractCommandFromBlockInfo } from "../lib/block-info";
import { MarkdownEngineRenderOption } from "../markdown-engine";
import { toc } from "../toc";
 
export default async function enhance(
  $,
  codeChunksData: CodeChunksData,
  renderOptions: MarkdownEngineRenderOption,
  runOptions: RunCodeChunkOptions,
): Promise<void> {
  const asyncFunctions = [];
  const arrayOfCodeChunkData = [];
  $('[data-role="codeBlock"]').each((i, container) => {
    const $container = $(container);
    if ($container.data("executor")) {
      return;
    }
 
    const normalizedInfo: BlockInfo = $container.data("normalizedInfo");
    if (!normalizedInfo.attributes["cmd"]) {
      return;
    }
 
    $container.data("executor", "fenced-code-chunks");
 
    asyncFunctions.push(
      renderCodeBlock(
        $container,
        normalizedInfo,
        $,
        codeChunksData,
        arrayOfCodeChunkData,
        renderOptions,
        runOptions,
      ),
    );
  });
  await Promise.all(asyncFunctions);
}
 
export async function renderCodeBlock(
  $container: Cheerio,
  normalizedInfo: BlockInfo,
  $: CheerioStatic,
  codeChunksData: CodeChunksData,
  arrayOfCodeChunkData: CodeChunkData[],
  renderOptions: MarkdownEngineRenderOption,
  runOptions: RunCodeChunkOptions,
): Promise<void> {
  const code = $container.text();
  const id =
    normalizedInfo.attributes["id"] ||
    "code-chunk-id-" + arrayOfCodeChunkData.length;
 
  const cmd = extractCommandFromBlockInfo(normalizedInfo);
  const isJavascript = ["js", "javascript"].indexOf(cmd) !== -1;
 
  const $codeAndOutputWrapper = $('<div class="code-chunk"></div>');
  $codeAndOutputWrapper.attr("data-id", id);
  $codeAndOutputWrapper.attr("data-cmd", cmd);
  if (isJavascript) {
    $codeAndOutputWrapper.attr("data-code", code);
  }
  $container.replaceWith($codeAndOutputWrapper);
 
  const $codeWrapper = $('<div class="input-div"/>');
  $codeWrapper.append($container);
  $codeAndOutputWrapper.append($codeWrapper);
 
  let codeChunkData: CodeChunkData = codeChunksData[id];
  const prev = arrayOfCodeChunkData.length
    ? arrayOfCodeChunkData[arrayOfCodeChunkData.length - 1].id
    : "";
  if (!codeChunkData) {
    codeChunkData = {
      id,
      code,
      normalizedInfo,
      result: "",
      plainResult: "",
      running: false,
      prev,
      next: null,
    };
    codeChunksData[id] = codeChunkData;
  } else {
    codeChunkData.code = code;
    codeChunkData.normalizedInfo = normalizedInfo;
    codeChunkData.prev = prev;
  }
  if (prev && codeChunksData[prev]) {
    codeChunksData[prev].next = id;
  }
 
  // this line has to be put above the `if` statement.
  arrayOfCodeChunkData.push(codeChunkData);
 
  if (
    renderOptions.triggeredBySave &&
    normalizedInfo.attributes["run_on_save"]
  ) {
    await runCodeChunk(id, codeChunksData, runOptions);
  }
 
  let result = codeChunkData.result;
 
  // element attribute
  if (!result && codeChunkData.normalizedInfo.attributes["element"]) {
    result = codeChunkData.normalizedInfo.attributes["element"];
    codeChunkData.result = result;
  }
 
  if (codeChunkData.running) {
    $codeAndOutputWrapper.addClass("running");
  }
  const statusDiv = `<div class="status">running...</div>`;
  const buttonGroup =
    '<div class="btn-group"><div class="run-btn btn"><span>▶︎</span></div><div class="run-all-btn btn">all</div></div>';
  let outputDiv = `<div class="output-div">${result}</div>`;
 
  // check javascript code chunk
  if (!renderOptions.isForPreview && isJavascript) {
    outputDiv += `<script>${code}</script>`;
    result = codeChunkData.normalizedInfo.attributes["element"] || "";
  }
 
  $codeWrapper.append(buttonGroup);
  $codeWrapper.append(statusDiv);
 
  normalizedInfo.attributes["output_first"] === true
    ? $codeAndOutputWrapper.prepend(outputDiv)
    : $codeAndOutputWrapper.append(outputDiv);
}
 
export interface RunCodeChunkOptions {
  enableScriptExecution: boolean;
  fileDirectoryPath: string;
  filePath: string;
  imageFolderPath: string;
  latexEngine: any;
  modifySource: any;
  parseMD: any;
  headings: any;
  resolveFilePath: any;
}
 
export async function runCodeChunk(
  id: string,
  codeChunksData: CodeChunksData,
  runOptions: RunCodeChunkOptions,
): Promise<string> {
  const {
    headings,
    enableScriptExecution,
    filePath,
    fileDirectoryPath,
    latexEngine,
    modifySource,
    parseMD,
  } = runOptions;
  const codeChunkData = codeChunksData[id];
  if (!codeChunkData || codeChunkData.running) {
    return "";
  }
 
  const combinedCodeAsArray = [codeChunkData.code];
  let patentCodeChunkData = codeChunkData;
  while (patentCodeChunkData.normalizedInfo.attributes["continue"]) {
    let parentId = patentCodeChunkData.normalizedInfo.attributes["continue"];
    if (parentId === true) {
      parentId = patentCodeChunkData.prev;
    }
    patentCodeChunkData = codeChunksData[parentId];
    if (!patentCodeChunkData) {
      break;
    }
    combinedCodeAsArray.unshift(patentCodeChunkData.code);
  }
  const code = combinedCodeAsArray.join("\n");
  const cmd = extractCommandFromBlockInfo(codeChunkData.normalizedInfo);
 
  codeChunkData.running = true;
  let result;
  let outputFormat = "text";
  let blockModifiesSource =
    codeChunkData.normalizedInfo.attributes["modify_source"];
  try {
    const normalizedAttributes = codeChunkData.normalizedInfo.attributes;
    if (cmd === "toc") {
      // toc code chunk. <= this is a special code chunk.
      const tocObject = toc(headings, {
        ordered: normalizedAttributes["ordered_list"],
        depthFrom: normalizedAttributes["depth_from"],
        depthTo: normalizedAttributes["depth_to"],
        tab: normalizedAttributes["tab"] || "  ",
        ignoreLink: normalizedAttributes["ignore_link"],
      });
      result = tocObject.content;
      outputFormat = "markdown";
      blockModifiesSource = true;
    } else {
      // common code chunk
      // I put this line here because some code chunks like `toc` still need to be run.
      if (!enableScriptExecution) {
        return ""; // code chunk is disabled.
      }
 
      result = await run(
        code,
        fileDirectoryPath,
        cmd,
        codeChunkData.normalizedInfo.attributes,
        latexEngine,
      );
    }
    codeChunkData.plainResult = result;
 
    if (
      blockModifiesSource &&
      "code_chunk_offset" in codeChunkData.normalizedInfo.attributes
    ) {
      codeChunkData.result = "";
      return modifySource(codeChunkData, result, filePath);
    }
 
    // set output format for a few special cases
    if (cmd.match(/(la)?tex/) || cmd === "pdflatex") {
      outputFormat = "markdown";
    } else if (
      cmd.match(/python/) &&
      (normalizedAttributes["matplotlib"] || normalizedAttributes["mpl"])
    ) {
      outputFormat = "markdown";
    } else if (codeChunkData.normalizedInfo.attributes["output"]) {
      outputFormat = codeChunkData.normalizedInfo.attributes["output"];
    }
 
    if (!result) {
      // do nothing
      result = "";
    } else if (outputFormat === "html") {
      result = result;
    } else if (outputFormat === "png") {
      const base64 = new Buffer(result).toString("base64");
      result = `<img src="data:image/png;charset=utf-8;base64,${base64}">`;
    } else if (outputFormat === "markdown") {
      const { html } = await parseMD(result, {
        useRelativeFilePath: true,
        isForPreview: false,
        hideFrontMatter: true,
      });
      result = html;
    } else if (outputFormat === "none") {
      result = "";
    } else {
      result = `<pre class="language-text">${result}</pre>`;
    }
  } catch (error) {
    result = `<pre class="language-text">${error}</pre>`;
  }
 
  codeChunkData.result = result; // save result.
  codeChunkData.running = false;
  return result;
}
 
export async function runCodeChunks(
  codeChunksData: CodeChunksData,
  runOptions: RunCodeChunkOptions,
) {
  const asyncFunctions = [];
  for (const id in codeChunksData) {
    if (codeChunksData.hasOwnProperty(id)) {
      asyncFunctions.push(runCodeChunk(id, codeChunksData, runOptions));
    }
  }
  return Promise.all(asyncFunctions);
}