markdown.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. (function( root, factory ) {
  7. if( typeof exports === 'object' ) {
  8. module.exports = factory( require( './marked' ) );
  9. }
  10. else {
  11. // Browser globals (root is window)
  12. root.returnExports = factory( root.marked );
  13. root.returnExports.processSlides();
  14. root.returnExports.convertSlides();
  15. }
  16. }( this, function( marked ) {
  17. if( typeof marked === 'undefined' ) {
  18. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  19. }
  20. if( typeof hljs !== 'undefined' ) {
  21. marked.setOptions({
  22. highlight: function( lang, code ) {
  23. return hljs.highlightAuto( lang, code ).value;
  24. }
  25. });
  26. }
  27. /**
  28. * Retrieves the markdown contents of a slide section
  29. * element. Normalizes leading tabs/whitespace.
  30. */
  31. function getMarkdownFromSlide( section ) {
  32. var template = section.querySelector( 'script' );
  33. // strip leading whitespace so it isn't evaluated as code
  34. var text = ( template || section ).textContent;
  35. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  36. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  37. if( leadingTabs > 0 ) {
  38. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  39. }
  40. else if( leadingWs > 1 ) {
  41. text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
  42. }
  43. return text;
  44. }
  45. /**
  46. * Given a markdown slide section element, this will
  47. * return all arguments that aren't related to markdown
  48. * parsing. Used to forward any other user-defined arguments
  49. * to the output markdown slide.
  50. */
  51. function getForwardedAttributes( section ) {
  52. var attributes = section.attributes;
  53. var result = [];
  54. for( var i = 0, len = attributes.length; i < len; i++ ) {
  55. var name = attributes[i].name,
  56. value = attributes[i].value;
  57. // disregard attributes that are used for markdown loading/parsing
  58. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  59. if( value ) {
  60. result.push( name + '=' + value );
  61. }
  62. else {
  63. result.push( name );
  64. }
  65. }
  66. return result.join( ' ' );
  67. }
  68. /**
  69. * Helper function for constructing a markdown slide.
  70. */
  71. function createMarkdownSlide( content, options ) {
  72. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  73. if( notesMatch.length === 2 ) {
  74. content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
  75. }
  76. return '<script type="text/template">' + content + '</script>';
  77. }
  78. /**
  79. * Parses a data string into multiple slides based
  80. * on the passed in separator arguments.
  81. */
  82. function slidify( markdown, options ) {
  83. options = options || {};
  84. options.separator = options.separator || '^\n---\n$';
  85. options.notesSeparator = options.notesSeparator || 'note:';
  86. options.attributes = options.attributes || '';
  87. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  88. horizontalSeparatorRegex = new RegExp( options.separator );
  89. var matches,
  90. lastIndex = 0,
  91. isHorizontal,
  92. wasHorizontal = true,
  93. content,
  94. sectionStack = [];
  95. // iterate until all blocks between separators are stacked up
  96. while( matches = separatorRegex.exec( markdown ) ) {
  97. notes = null;
  98. // determine direction (horizontal by default)
  99. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  100. if( !isHorizontal && wasHorizontal ) {
  101. // create vertical stack
  102. sectionStack.push( [] );
  103. }
  104. // pluck slide content from markdown input
  105. content = markdown.substring( lastIndex, matches.index );
  106. if( isHorizontal && wasHorizontal ) {
  107. // add to horizontal stack
  108. sectionStack.push( content );
  109. }
  110. else {
  111. // add to vertical stack
  112. sectionStack[sectionStack.length-1].push( content );
  113. }
  114. lastIndex = separatorRegex.lastIndex;
  115. wasHorizontal = isHorizontal;
  116. }
  117. // add the remaining slide
  118. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  119. var markdownSections = '';
  120. // flatten the hierarchical stack, and insert <section data-markdown> tags
  121. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  122. // vertical
  123. if( sectionStack[i].propertyIsEnumerable( length ) && typeof sectionStack[i].splice === 'function' ) {
  124. markdownSections += '<section '+ options.attributes +'>';
  125. sectionStack[i].forEach( function( child ) {
  126. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  127. } );
  128. markdownSections += '</section>';
  129. }
  130. else {
  131. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  132. }
  133. }
  134. return markdownSections;
  135. }
  136. /**
  137. * Parses any current data-markdown slides, splits
  138. * multi-slide markdown into separate sections and
  139. * handles loading of external markdown.
  140. */
  141. function processSlides() {
  142. var sections = document.querySelectorAll( '[data-markdown]'),
  143. section;
  144. for( var i = 0, len = sections.length; i < len; i++ ) {
  145. section = sections[i];
  146. if( section.getAttribute( 'data-markdown' ).length ) {
  147. var xhr = new XMLHttpRequest(),
  148. url = section.getAttribute( 'data-markdown' );
  149. datacharset = section.getAttribute( 'data-charset' );
  150. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  151. if( datacharset != null && datacharset != '' ) {
  152. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  153. }
  154. xhr.onreadystatechange = function() {
  155. if( xhr.readyState === 4 ) {
  156. if ( xhr.status >= 200 && xhr.status < 300 ) {
  157. section.outerHTML = slidify( xhr.responseText, {
  158. separator: section.getAttribute( 'data-separator' ),
  159. verticalSeparator: section.getAttribute( 'data-vertical' ),
  160. notesSeparator: section.getAttribute( 'data-notes' ),
  161. attributes: getForwardedAttributes( section )
  162. });
  163. }
  164. else {
  165. section.outerHTML = '<section data-state="alert">' +
  166. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  167. 'Check your browser\'s JavaScript console for more details.' +
  168. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  169. '</section>';
  170. }
  171. }
  172. };
  173. xhr.open( 'GET', url, false );
  174. try {
  175. xhr.send();
  176. }
  177. catch ( e ) {
  178. alert( '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 );
  179. }
  180. }
  181. else if( section.getAttribute( 'data-separator' ) ) {
  182. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  183. separator: section.getAttribute( 'data-separator' ),
  184. verticalSeparator: section.getAttribute( 'data-vertical' ),
  185. notesSeparator: section.getAttribute( 'data-notes' ),
  186. attributes: getForwardedAttributes( section )
  187. });
  188. }
  189. }
  190. }
  191. /**
  192. * Converts any current data-markdown slides in the
  193. * DOM to HTML.
  194. */
  195. function convertSlides() {
  196. var sections = document.querySelectorAll( '[data-markdown]');
  197. for( var i = 0, len = sections.length; i < len; i++ ) {
  198. var section = sections[i];
  199. var notes = section.querySelector( 'aside.notes' );
  200. var markdown = getMarkdownFromSlide( section );
  201. section.innerHTML = marked( markdown );
  202. // If there were notes, we need to re-add them after
  203. // having overwritten the section's HTML
  204. if( notes ) {
  205. section.appendChild( notes );
  206. }
  207. }
  208. }
  209. return {
  210. processSlides: processSlides,
  211. convertSlides: convertSlides,
  212. slidify: slidify
  213. };
  214. }));