plugin.js 13 KB

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