plugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*!
  2. * The reveal.js markdown plugin. Handles parsing of
  3. * markdown inside of presentations as well as loading
  4. * of external markdown documents.
  5. */
  6. import { marked } from 'marked';
  7. const DEFAULT_SLIDE_SEPARATOR = '\r?\n---\r?\n',
  8. DEFAULT_NOTES_SEPARATOR = 'notes?:',
  9. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
  10. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
  11. const SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
  12. // match an optional line number offset and highlight line numbers
  13. // [<line numbers>] or [<offset>: <line numbers>]
  14. const CODE_LINE_NUMBER_REGEX = /\[\s*((\d*):)?\s*([\s\d,|-]*)\]/;
  15. const HTML_ESCAPE_MAP = {
  16. '&': '&amp;',
  17. '<': '&lt;',
  18. '>': '&gt;',
  19. '"': '&quot;',
  20. "'": '&#39;'
  21. };
  22. const Plugin = () => {
  23. // The reveal.js instance this plugin is attached to
  24. let deck;
  25. /**
  26. * Retrieves the markdown contents of a slide section
  27. * element. Normalizes leading tabs/whitespace.
  28. */
  29. function getMarkdownFromSlide( section ) {
  30. // look for a <script> or <textarea data-template> wrapper
  31. var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
  32. // strip leading whitespace so it isn't evaluated as code
  33. var text = ( template || section ).textContent;
  34. // restore script end tags
  35. text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
  36. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  37. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  38. if( leadingTabs > 0 ) {
  39. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}(.*)','g'), function(m, p1) { return '\n' + p1 ; } );
  40. }
  41. else if( leadingWs > 1 ) {
  42. text = text.replace( new RegExp('\\n? {' + leadingWs + '}(.*)', 'g'), function(m, p1) { return '\n' + p1 ; } );
  43. }
  44. return text;
  45. }
  46. /**
  47. * Given a markdown slide section element, this will
  48. * return all arguments that aren't related to markdown
  49. * parsing. Used to forward any other user-defined arguments
  50. * to the output markdown slide.
  51. */
  52. function getForwardedAttributes( section ) {
  53. var attributes = section.attributes;
  54. var result = [];
  55. for( var i = 0, len = attributes.length; i < len; i++ ) {
  56. var name = attributes[i].name,
  57. value = attributes[i].value;
  58. // disregard attributes that are used for markdown loading/parsing
  59. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  60. if( value ) {
  61. result.push( name + '="' + value + '"' );
  62. }
  63. else {
  64. result.push( name );
  65. }
  66. }
  67. return result.join( ' ' );
  68. }
  69. /**
  70. * Inspects the given options and fills out default
  71. * values for what's not defined.
  72. */
  73. function getSlidifyOptions( options ) {
  74. options = options || {};
  75. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  76. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  77. options.attributes = options.attributes || '';
  78. return options;
  79. }
  80. /**
  81. * Helper function for constructing a markdown slide.
  82. */
  83. function createMarkdownSlide( content, options ) {
  84. options = getSlidifyOptions( options );
  85. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  86. if( notesMatch.length === 2 ) {
  87. content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
  88. }
  89. // prevent script end tags in the content from interfering
  90. // with parsing
  91. content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
  92. return '<script type="text/template">' + content + '</script>';
  93. }
  94. /**
  95. * Parses a data string into multiple slides based
  96. * on the passed in separator arguments.
  97. */
  98. function slidify( markdown, options ) {
  99. options = getSlidifyOptions( options );
  100. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  101. horizontalSeparatorRegex = new RegExp( options.separator );
  102. var matches,
  103. lastIndex = 0,
  104. isHorizontal,
  105. wasHorizontal = true,
  106. content,
  107. sectionStack = [];
  108. // iterate until all blocks between separators are stacked up
  109. while( matches = separatorRegex.exec( markdown ) ) {
  110. var notes = null;
  111. // determine direction (horizontal by default)
  112. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  113. if( !isHorizontal && wasHorizontal ) {
  114. // create vertical stack
  115. sectionStack.push( [] );
  116. }
  117. // pluck slide content from markdown input
  118. content = markdown.substring( lastIndex, matches.index );
  119. if( isHorizontal && wasHorizontal ) {
  120. // add to horizontal stack
  121. sectionStack.push( content );
  122. }
  123. else {
  124. // add to vertical stack
  125. sectionStack[sectionStack.length-1].push( content );
  126. }
  127. lastIndex = separatorRegex.lastIndex;
  128. wasHorizontal = isHorizontal;
  129. }
  130. // add the remaining slide
  131. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  132. var markdownSections = '';
  133. // flatten the hierarchical stack, and insert <section data-markdown> tags
  134. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  135. // vertical
  136. if( sectionStack[i] instanceof Array ) {
  137. markdownSections += '<section '+ options.attributes +'>';
  138. sectionStack[i].forEach( function( child ) {
  139. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  140. } );
  141. markdownSections += '</section>';
  142. }
  143. else {
  144. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  145. }
  146. }
  147. return markdownSections;
  148. }
  149. /**
  150. * Parses any current data-markdown slides, splits
  151. * multi-slide markdown into separate sections and
  152. * handles loading of external markdown.
  153. */
  154. function processSlides( scope ) {
  155. return new Promise( function( resolve ) {
  156. var externalPromises = [];
  157. [].slice.call( scope.querySelectorAll( 'section[data-markdown]:not([data-markdown-parsed])') ).forEach( function( section, i ) {
  158. if( section.getAttribute( 'data-markdown' ).length ) {
  159. externalPromises.push( loadExternalMarkdown( section ).then(
  160. // Finished loading external file
  161. function( xhr, url ) {
  162. section.outerHTML = slidify( xhr.responseText, {
  163. separator: section.getAttribute( 'data-separator' ),
  164. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  165. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  166. attributes: getForwardedAttributes( section )
  167. });
  168. },
  169. // Failed to load markdown
  170. function( xhr, url ) {
  171. section.outerHTML = '<section data-state="alert">' +
  172. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  173. 'Check your browser\'s JavaScript console for more details.' +
  174. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  175. '</section>';
  176. }
  177. ) );
  178. }
  179. else {
  180. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  181. separator: section.getAttribute( 'data-separator' ),
  182. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  183. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  184. attributes: getForwardedAttributes( section )
  185. });
  186. }
  187. });
  188. Promise.all( externalPromises ).then( resolve );
  189. } );
  190. }
  191. function loadExternalMarkdown( section ) {
  192. return new Promise( function( resolve, reject ) {
  193. var xhr = new XMLHttpRequest(),
  194. url = section.getAttribute( 'data-markdown' );
  195. var datacharset = section.getAttribute( 'data-charset' );
  196. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  197. if( datacharset != null && datacharset != '' ) {
  198. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  199. }
  200. xhr.onreadystatechange = function( section, xhr ) {
  201. if( xhr.readyState === 4 ) {
  202. // file protocol yields status code 0 (useful for local debug, mobile applications etc.)
  203. if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
  204. resolve( xhr, url );
  205. }
  206. else {
  207. reject( xhr, url );
  208. }
  209. }
  210. }.bind( this, section, xhr );
  211. xhr.open( 'GET', url, true );
  212. try {
  213. xhr.send();
  214. }
  215. catch ( e ) {
  216. console.warn( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
  217. resolve( xhr, url );
  218. }
  219. } );
  220. }
  221. /**
  222. * Check if a node value has the attributes pattern.
  223. * If yes, extract it and add that value as one or several attributes
  224. * to the target element.
  225. *
  226. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  227. * directly on refresh (F5)
  228. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  229. */
  230. function addAttributeInElement( node, elementTarget, separator ) {
  231. var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
  232. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' );
  233. var nodeValue = node.nodeValue;
  234. var matches,
  235. matchesClass;
  236. if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  237. var classes = matches[1];
  238. nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
  239. node.nodeValue = nodeValue;
  240. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  241. if( matchesClass[2] ) {
  242. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  243. } else {
  244. elementTarget.setAttribute( matchesClass[3], "" );
  245. }
  246. }
  247. return true;
  248. }
  249. return false;
  250. }
  251. /**
  252. * Add attributes to the parent element of a text node,
  253. * or the element of an attribute node.
  254. */
  255. function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
  256. if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
  257. var previousParentElement = element;
  258. for( var i = 0; i < element.childNodes.length; i++ ) {
  259. var childElement = element.childNodes[i];
  260. if ( i > 0 ) {
  261. var j = i - 1;
  262. while ( j >= 0 ) {
  263. var aPreviousChildElement = element.childNodes[j];
  264. if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
  265. previousParentElement = aPreviousChildElement;
  266. break;
  267. }
  268. j = j - 1;
  269. }
  270. }
  271. var parentSection = section;
  272. if( childElement.nodeName == "section" ) {
  273. parentSection = childElement ;
  274. previousParentElement = childElement ;
  275. }
  276. if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
  277. addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
  278. }
  279. }
  280. }
  281. if ( element.nodeType == Node.COMMENT_NODE ) {
  282. if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
  283. addAttributeInElement( element, section, separatorSectionAttributes );
  284. }
  285. }
  286. }
  287. /**
  288. * Converts any current data-markdown slides in the
  289. * DOM to HTML.
  290. */
  291. function convertSlides() {
  292. var sections = deck.getRevealElement().querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
  293. [].slice.call( sections ).forEach( function( section ) {
  294. section.setAttribute( 'data-markdown-parsed', true )
  295. var notes = section.querySelector( 'aside.notes' );
  296. var markdown = getMarkdownFromSlide( section );
  297. section.innerHTML = marked( markdown );
  298. addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
  299. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  300. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
  301. section.getAttribute( 'data-attributes' ) ||
  302. section.parentNode.getAttribute( 'data-attributes' ) ||
  303. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
  304. // If there were notes, we need to re-add them after
  305. // having overwritten the section's HTML
  306. if( notes ) {
  307. section.appendChild( notes );
  308. }
  309. } );
  310. return Promise.resolve();
  311. }
  312. function escapeForHTML( input ) {
  313. return input.replace( /([&<>'"])/g, char => HTML_ESCAPE_MAP[char] );
  314. }
  315. return {
  316. id: 'markdown',
  317. /**
  318. * Starts processing and converting Markdown within the
  319. * current reveal.js deck.
  320. */
  321. init: function( reveal ) {
  322. deck = reveal;
  323. let { renderer, animateLists, ...markedOptions } = deck.getConfig().markdown || {};
  324. if( !renderer ) {
  325. renderer = new marked.Renderer();
  326. renderer.code = ( code, language ) => {
  327. // Off by default
  328. let lineNumberOffset = '';
  329. let lineNumbers = '';
  330. // Users can opt in to show line numbers and highlight
  331. // specific lines.
  332. // ```javascript [] show line numbers
  333. // ```javascript [1,4-8] highlights lines 1 and 4-8
  334. // optional line number offset:
  335. // ```javascript [25: 1,4-8] start line numbering at 25,
  336. // highlights lines 1 (numbered as 25) and 4-8 (numbered as 28-32)
  337. if( CODE_LINE_NUMBER_REGEX.test( language ) ) {
  338. let lineNumberOffsetMatch = language.match( CODE_LINE_NUMBER_REGEX )[2];
  339. if (lineNumberOffsetMatch){
  340. lineNumberOffset = `data-ln-start-from="${lineNumberOffsetMatch.trim()}"`;
  341. }
  342. lineNumbers = language.match( CODE_LINE_NUMBER_REGEX )[3].trim();
  343. lineNumbers = `data-line-numbers="${lineNumbers}"`;
  344. language = language.replace( CODE_LINE_NUMBER_REGEX, '' ).trim();
  345. }
  346. // Escape before this gets injected into the DOM to
  347. // avoid having the HTML parser alter our code before
  348. // highlight.js is able to read it
  349. code = escapeForHTML( code );
  350. // return `<pre><code ${lineNumbers} class="${language}">${code}</code></pre>`;
  351. return `<pre><code ${lineNumbers} ${lineNumberOffset} class="${language}">${code}</code></pre>`;
  352. };
  353. }
  354. if( animateLists === true ) {
  355. renderer.listitem = text => `<li class="fragment">${text}</li>`;
  356. }
  357. marked.setOptions( {
  358. renderer,
  359. ...markedOptions
  360. } );
  361. return processSlides( deck.getRevealElement() ).then( convertSlides );
  362. },
  363. // TODO: Do these belong in the API?
  364. processSlides: processSlides,
  365. convertSlides: convertSlides,
  366. slidify: slidify,
  367. marked: marked
  368. }
  369. };
  370. export default Plugin;