markdown.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 define === 'function' && define.amd) {
  8. root.marked = require( './marked' );
  9. root.RevealMarkdown = factory( root.marked );
  10. } else if( typeof exports === 'object' ) {
  11. module.exports = factory( require( './marked' ) );
  12. } else {
  13. // Browser globals (root is window)
  14. root.RevealMarkdown = factory( root.marked );
  15. }
  16. }( this, function( marked ) {
  17. var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
  18. DEFAULT_NOTES_SEPARATOR = 'notes?:',
  19. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
  20. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
  21. var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
  22. /**
  23. * Retrieves the markdown contents of a slide section
  24. * element. Normalizes leading tabs/whitespace.
  25. */
  26. function getMarkdownFromSlide( section ) {
  27. // look for a <script> or <textarea data-template> wrapper
  28. var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
  29. // strip leading whitespace so it isn't evaluated as code
  30. var text = ( template || section ).textContent;
  31. // restore script end tags
  32. text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
  33. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  34. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  35. if( leadingTabs > 0 ) {
  36. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  37. }
  38. else if( leadingWs > 1 ) {
  39. text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
  40. }
  41. return text;
  42. }
  43. /**
  44. * Given a markdown slide section element, this will
  45. * return all arguments that aren't related to markdown
  46. * parsing. Used to forward any other user-defined arguments
  47. * to the output markdown slide.
  48. */
  49. function getForwardedAttributes( section ) {
  50. var attributes = section.attributes;
  51. var result = [];
  52. for( var i = 0, len = attributes.length; i < len; i++ ) {
  53. var name = attributes[i].name,
  54. value = attributes[i].value;
  55. // disregard attributes that are used for markdown loading/parsing
  56. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  57. if( value ) {
  58. result.push( name + '="' + value + '"' );
  59. }
  60. else {
  61. result.push( name );
  62. }
  63. }
  64. return result.join( ' ' );
  65. }
  66. /**
  67. * Inspects the given options and fills out default
  68. * values for what's not defined.
  69. */
  70. function getSlidifyOptions( options ) {
  71. options = options || {};
  72. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  73. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  74. options.attributes = options.attributes || '';
  75. return options;
  76. }
  77. /**
  78. * Helper function for constructing a markdown slide.
  79. */
  80. function createMarkdownSlide( content, options ) {
  81. options = getSlidifyOptions( options );
  82. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  83. if( notesMatch.length === 2 ) {
  84. content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
  85. }
  86. // prevent script end tags in the content from interfering
  87. // with parsing
  88. content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
  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] instanceof Array ) {
  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. return new Promise( function( resolve ) {
  153. var externalPromises = [];
  154. [].slice.call( document.querySelectorAll( '[data-markdown]') ).forEach( function( section, i ) {
  155. if( section.getAttribute( 'data-markdown' ).length ) {
  156. externalPromises.push( loadExternalMarkdown( section ).then(
  157. // Finished loading external file
  158. function( xhr, url ) {
  159. section.outerHTML = slidify( xhr.responseText, {
  160. separator: section.getAttribute( 'data-separator' ),
  161. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  162. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  163. attributes: getForwardedAttributes( section )
  164. });
  165. },
  166. // Failed to load markdown
  167. function( xhr, url ) {
  168. section.outerHTML = '<section data-state="alert">' +
  169. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  170. 'Check your browser\'s JavaScript console for more details.' +
  171. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  172. '</section>';
  173. }
  174. ) );
  175. }
  176. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
  177. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  178. separator: section.getAttribute( 'data-separator' ),
  179. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  180. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  181. attributes: getForwardedAttributes( section )
  182. });
  183. }
  184. else {
  185. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  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. 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. 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 );
  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( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  233. var nodeValue = node.nodeValue;
  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. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  240. }
  241. return true;
  242. }
  243. return false;
  244. }
  245. /**
  246. * Add attributes to the parent element of a text node,
  247. * or the element of an attribute node.
  248. */
  249. function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
  250. if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
  251. previousParentElement = element;
  252. for( var i = 0; i < element.childNodes.length; i++ ) {
  253. childElement = element.childNodes[i];
  254. if ( i > 0 ) {
  255. j = i - 1;
  256. while ( j >= 0 ) {
  257. aPreviousChildElement = element.childNodes[j];
  258. if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
  259. previousParentElement = aPreviousChildElement;
  260. break;
  261. }
  262. j = j - 1;
  263. }
  264. }
  265. parentSection = section;
  266. if( childElement.nodeName == "section" ) {
  267. parentSection = childElement ;
  268. previousParentElement = childElement ;
  269. }
  270. if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
  271. addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
  272. }
  273. }
  274. }
  275. if ( element.nodeType == Node.COMMENT_NODE ) {
  276. if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
  277. addAttributeInElement( element, section, separatorSectionAttributes );
  278. }
  279. }
  280. }
  281. /**
  282. * Converts any current data-markdown slides in the
  283. * DOM to HTML.
  284. */
  285. function convertSlides() {
  286. var sections = document.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
  287. [].slice.call( sections ).forEach( function( section ) {
  288. section.setAttribute( 'data-markdown-parsed', true )
  289. var notes = section.querySelector( 'aside.notes' );
  290. var markdown = getMarkdownFromSlide( section );
  291. section.innerHTML = marked( markdown );
  292. addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
  293. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  294. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
  295. section.getAttribute( 'data-attributes' ) ||
  296. section.parentNode.getAttribute( 'data-attributes' ) ||
  297. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
  298. // If there were notes, we need to re-add them after
  299. // having overwritten the section's HTML
  300. if( notes ) {
  301. section.appendChild( notes );
  302. }
  303. } );
  304. return Promise.resolve();
  305. }
  306. // API
  307. var RevealMarkdown = {
  308. /**
  309. * Starts processing and converting Markdown within the
  310. * current reveal.js deck.
  311. *
  312. * @param {function} callback function to invoke once
  313. * we've finished loading and parsing Markdown
  314. */
  315. init: function( callback ) {
  316. if( typeof marked === 'undefined' ) {
  317. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  318. }
  319. if( typeof hljs !== 'undefined' ) {
  320. marked.setOptions({
  321. highlight: function( code, lang ) {
  322. return hljs.highlightAuto( code, [lang] ).value;
  323. }
  324. });
  325. }
  326. // marked can be configured via reveal.js config options
  327. var options = Reveal.getConfig().markdown;
  328. if( options ) {
  329. marked.setOptions( options );
  330. }
  331. return processSlides().then( convertSlides );
  332. },
  333. // TODO: Do these belong in the API?
  334. processSlides: processSlides,
  335. convertSlides: convertSlides,
  336. slidify: slidify
  337. };
  338. // Register our plugin so that reveal.js will call our
  339. // plugin 'init' method as part of the initialization
  340. Reveal.registerPlugin( 'markdown', RevealMarkdown );
  341. return RevealMarkdown;
  342. }));