markdown.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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.RevealMarkdown = factory( root.marked );
  13. root.RevealMarkdown.initialize();
  14. }
  15. }( this, function( marked ) {
  16. if( typeof marked === 'undefined' ) {
  17. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  18. }
  19. if( typeof hljs !== 'undefined' ) {
  20. marked.setOptions({
  21. highlight: function( lang, code ) {
  22. return hljs.highlightAuto( lang, code ).value;
  23. }
  24. });
  25. }
  26. var DEFAULT_SLIDE_SEPARATOR = '^\n---\n$',
  27. DEFAULT_NOTES_SEPARATOR = 'note:';
  28. /**
  29. * Retrieves the markdown contents of a slide section
  30. * element. Normalizes leading tabs/whitespace.
  31. */
  32. function getMarkdownFromSlide( section ) {
  33. var template = section.querySelector( 'script' );
  34. // strip leading whitespace so it isn't evaluated as code
  35. var text = ( template || section ).textContent;
  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'), '\n' );
  40. }
  41. else if( leadingWs > 1 ) {
  42. text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
  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" data-markdown>' + notesMatch[1].trim() + '</aside>';
  88. }
  89. return '<script type="text/template">' + content + '</script>';
  90. }
  91. /**
  92. * Parses a data string into multiple slides based
  93. * on the passed in separator arguments.
  94. */
  95. function slidify( markdown, options ) {
  96. options = getSlidifyOptions( options );
  97. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  98. horizontalSeparatorRegex = new RegExp( options.separator );
  99. var matches,
  100. lastIndex = 0,
  101. isHorizontal,
  102. wasHorizontal = true,
  103. content,
  104. sectionStack = [];
  105. // iterate until all blocks between separators are stacked up
  106. while( matches = separatorRegex.exec( markdown ) ) {
  107. notes = null;
  108. // determine direction (horizontal by default)
  109. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  110. if( !isHorizontal && wasHorizontal ) {
  111. // create vertical stack
  112. sectionStack.push( [] );
  113. }
  114. // pluck slide content from markdown input
  115. content = markdown.substring( lastIndex, matches.index );
  116. if( isHorizontal && wasHorizontal ) {
  117. // add to horizontal stack
  118. sectionStack.push( content );
  119. }
  120. else {
  121. // add to vertical stack
  122. sectionStack[sectionStack.length-1].push( content );
  123. }
  124. lastIndex = separatorRegex.lastIndex;
  125. wasHorizontal = isHorizontal;
  126. }
  127. // add the remaining slide
  128. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  129. var markdownSections = '';
  130. // flatten the hierarchical stack, and insert <section data-markdown> tags
  131. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  132. // vertical
  133. if( sectionStack[i].propertyIsEnumerable( length ) && typeof sectionStack[i].splice === 'function' ) {
  134. markdownSections += '<section '+ options.attributes +'>';
  135. sectionStack[i].forEach( function( child ) {
  136. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  137. } );
  138. markdownSections += '</section>';
  139. }
  140. else {
  141. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  142. }
  143. }
  144. return markdownSections;
  145. }
  146. /**
  147. * Parses any current data-markdown slides, splits
  148. * multi-slide markdown into separate sections and
  149. * handles loading of external markdown.
  150. */
  151. function processSlides() {
  152. var sections = document.querySelectorAll( '[data-markdown]'),
  153. section;
  154. for( var i = 0, len = sections.length; i < len; i++ ) {
  155. section = sections[i];
  156. if( section.getAttribute( 'data-markdown' ).length ) {
  157. var xhr = new XMLHttpRequest(),
  158. url = section.getAttribute( 'data-markdown' );
  159. datacharset = section.getAttribute( 'data-charset' );
  160. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  161. if( datacharset != null && datacharset != '' ) {
  162. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  163. }
  164. xhr.onreadystatechange = function() {
  165. if( xhr.readyState === 4 ) {
  166. if ( xhr.status >= 200 && xhr.status < 300 ) {
  167. section.outerHTML = slidify( xhr.responseText, {
  168. separator: section.getAttribute( 'data-separator' ),
  169. verticalSeparator: section.getAttribute( 'data-vertical' ),
  170. notesSeparator: section.getAttribute( 'data-notes' ),
  171. attributes: getForwardedAttributes( section )
  172. });
  173. }
  174. else {
  175. section.outerHTML = '<section data-state="alert">' +
  176. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  177. 'Check your browser\'s JavaScript console for more details.' +
  178. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  179. '</section>';
  180. }
  181. }
  182. };
  183. xhr.open( 'GET', url, false );
  184. try {
  185. xhr.send();
  186. }
  187. catch ( e ) {
  188. 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 );
  189. }
  190. }
  191. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) {
  192. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  193. separator: section.getAttribute( 'data-separator' ),
  194. verticalSeparator: section.getAttribute( 'data-vertical' ),
  195. notesSeparator: section.getAttribute( 'data-notes' ),
  196. attributes: getForwardedAttributes( section )
  197. });
  198. }
  199. else {
  200. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  201. }
  202. }
  203. }
  204. /**
  205. * Converts any current data-markdown slides in the
  206. * DOM to HTML.
  207. */
  208. function convertSlides() {
  209. var sections = document.querySelectorAll( '[data-markdown]');
  210. for( var i = 0, len = sections.length; i < len; i++ ) {
  211. var section = sections[i];
  212. // Only parse the same slide once
  213. if( !section.getAttribute( 'data-markdown-parsed' ) ) {
  214. section.setAttribute( 'data-markdown-parsed', true )
  215. var notes = section.querySelector( 'aside.notes' );
  216. var markdown = getMarkdownFromSlide( section );
  217. section.innerHTML = marked( markdown );
  218. // If there were notes, we need to re-add them after
  219. // having overwritten the section's HTML
  220. if( notes ) {
  221. section.appendChild( notes );
  222. }
  223. }
  224. }
  225. }
  226. // API
  227. return {
  228. initialize: function() {
  229. processSlides();
  230. convertSlides();
  231. },
  232. // TODO: Do these belong in the API?
  233. processSlides: processSlides,
  234. convertSlides: convertSlides,
  235. slidify: slidify
  236. };
  237. }));