all files / lib/render/ markdown.js

80.65% Statements 25/31
75% Branches 15/20
75% Functions 3/4
66.67% Lines 12/18
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                                                                                                           
/**
 * Methods for interacting with our Markdown engine.
 * Supports rendering Markdown text and configure the engine.
 */
import Remarkable from 'remarkable';
import highlightjs from 'highlight.js';
 
let md;
 
/**
 * Default options used for Markdown engine.
 * @type {Object}
 */
const DEFAULT_OPTIONS = {
  highlight(str, lang) {
    if (lang && highlightjs.getLanguage(lang)) {
      try {
        return highlightjs.highlight(lang, str).value;
      } catch (e) { /* noop */ }
    }
 
    try {
      return highlightjs.highlightAuto(str).value;
    } catch (e) { /* noop */ }
 
    // use external default escaping
    return '';
  }
};
 
/**
 * Render a piece of string from Markdown to HTML.
 * @param {string} str String to parse.
 * @return {string} Parsed Markdown.
 */
export function render(str = '') {
  return md.render(str);
}
 
/**
 * Configure our Markdown engine.
 * @param {Object} options Configuration object.
 */
export function configure(options = {}) {
  // Lazily create markdown instance.
  if (!md) {
    md = new Remarkable(options.preset);
  }
 
  // Create copy.
  options = Object.assign({}, options);
 
  // If highlight is set to true then attach the highlight function handler.
  if (options.highlight === true) {
    options.highlight = DEFAULT_OPTIONS.highlight;
  }
 
  // Disable Markdown from auto converting indented lines of text to render
  // as a <code/> block. This conflicted when rendering pages so it's being
  // disabled.
  md.block.ruler.disable(['code']);
 
  md.set(options);
}