All files / src vega.ts

27.78% Statements 5/18
0% Branches 0/10
0% Functions 0/3
27.78% Lines 5/18

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 511x 1x 1x 1x                                                       1x                                      
import { loader } from "vega-loader";
import * as YAML from "yamljs";
import * as utility from "./utility";
let vega = null;
 
async function renderVega(spec: object, baseURL): Promise<string> {
  const svgHeader =
    '<?xml version="1.0" encoding="utf-8"?>\n' +
    '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ' +
    '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n';
 
  if (baseURL && baseURL[baseURL.length - 1] !== "/") {
    baseURL += "/";
  }
 
  async function helper(): Promise<string> {
    const view = new vega.View(vega.parse(spec), {
      loader: loader({ baseURL }),
      // logLevel: vega.Warn, // <= this will cause Atom unsafe eval error.
      renderer: "none",
    }).initialize();
    return svgHeader + (await view.toSVG());
  }
 
  return await utility.allowUnsafeEvalAndUnsafeNewFunctionAsync(helper);
}
 
/**
 * Modifed from the `vg2svg` file.
 * @param spec The vega code.
 */
export async function toSVG(
  spec: string = "",
  baseURL: string = "",
): Promise<string> {
  if (!vega) {
    vega = utility.loadDependency("vega/vega.min.js");
  }
 
  spec = spec.trim();
  let d;
  if (spec[0] !== "{") {
    // yaml
    d = YAML.parse(spec);
  } else {
    // json
    d = JSON.parse(spec);
  }
  return renderVega(d, baseURL);
}