markdown.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. var markdownFilesToLoad = 0;
  23. var loadCallback;
  24. /**
  25. * Retrieves the markdown contents of a slide section
  26. * element. Normalizes leading tabs/whitespace.
  27. */
  28. function getMarkdownFromSlide( section ) {
  29. // look for a <script> or <textarea data-template> wrapper
  30. var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
  31. // strip leading whitespace so it isn't evaluated as code
  32. var text = ( template || section ).textContent;
  33. // restore script end tags
  34. text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
  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. * Inspects the given options and fills out default
  70. * values for what's not defined.
  71. */
  72. function getSlidifyOptions( options ) {
  73. options = options || {};
  74. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  75. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  76. options.attributes = options.attributes || '';
  77. return options;
  78. }
  79. /**
  80. * Helper function for constructing a markdown slide.
  81. */
  82. function createMarkdownSlide( content, options ) {
  83. options = getSlidifyOptions( options );
  84. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  85. if( notesMatch.length === 2 ) {
  86. content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
  87. }
  88. // prevent script end tags in the content from interfering
  89. // with parsing
  90. content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
  91. return '<script type="text/template">' + content + '</script>';
  92. }
  93. /**
  94. * Parses a data string into multiple slides based
  95. * on the passed in separator arguments.
  96. */
  97. function slidify( markdown, options ) {
  98. options = getSlidifyOptions( options );
  99. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  100. horizontalSeparatorRegex = new RegExp( options.separator );
  101. var matches,
  102. lastIndex = 0,
  103. isHorizontal,
  104. wasHorizontal = true,
  105. content,
  106. sectionStack = [];
  107. // iterate until all blocks between separators are stacked up
  108. while( matches = separatorRegex.exec( markdown ) ) {
  109. notes = null;
  110. // determine direction (horizontal by default)
  111. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  112. if( !isHorizontal && wasHorizontal ) {
  113. // create vertical stack
  114. sectionStack.push( [] );
  115. }
  116. // pluck slide content from markdown input
  117. content = markdown.substring( lastIndex, matches.index );
  118. if( isHorizontal && wasHorizontal ) {
  119. // add to horizontal stack
  120. sectionStack.push( content );
  121. }
  122. else {
  123. // add to vertical stack
  124. sectionStack[sectionStack.length-1].push( content );
  125. }
  126. lastIndex = separatorRegex.lastIndex;
  127. wasHorizontal = isHorizontal;
  128. }
  129. // add the remaining slide
  130. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  131. var markdownSections = '';
  132. // flatten the hierarchical stack, and insert <section data-markdown> tags
  133. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  134. // vertical
  135. if( sectionStack[i] instanceof Array ) {
  136. markdownSections += '<section '+ options.attributes +'>';
  137. sectionStack[i].forEach( function( child ) {
  138. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  139. } );
  140. markdownSections += '</section>';
  141. }
  142. else {
  143. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  144. }
  145. }
  146. return markdownSections;
  147. }
  148. /**
  149. * Parses any current data-markdown slides, splits
  150. * multi-slide markdown into separate sections and
  151. * handles loading of external markdown.
  152. */
  153. function processSlides() {
  154. [].slice.call( document.querySelectorAll( '[data-markdown]') ).forEach( function( section, i ) {
  155. if( section.getAttribute( 'data-markdown' ).length ) {
  156. loadExternalMarkdown( section );
  157. }
  158. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
  159. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  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. else {
  167. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  168. }
  169. });
  170. checkIfLoaded();
  171. }
  172. function loadExternalMarkdown( section ) {
  173. markdownFilesToLoad += 1;
  174. var xhr = new XMLHttpRequest(),
  175. url = section.getAttribute( 'data-markdown' );
  176. datacharset = section.getAttribute( 'data-charset' );
  177. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  178. if( datacharset != null && datacharset != '' ) {
  179. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  180. }
  181. xhr.onreadystatechange = function( section, xhr ) {
  182. if( xhr.readyState === 4 ) {
  183. // file protocol yields status code 0 (useful for local debug, mobile applications etc.)
  184. if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
  185. section.outerHTML = slidify( xhr.responseText, {
  186. separator: section.getAttribute( 'data-separator' ),
  187. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  188. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  189. attributes: getForwardedAttributes( section )
  190. });
  191. }
  192. else {
  193. section.outerHTML = '<section data-state="alert">' +
  194. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  195. 'Check your browser\'s JavaScript console for more details.' +
  196. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  197. '</section>';
  198. }
  199. convertSlides();
  200. markdownFilesToLoad -= 1;
  201. checkIfLoaded();
  202. }
  203. }.bind( this, section, xhr );
  204. xhr.open( 'GET', url, true );
  205. try {
  206. xhr.send();
  207. }
  208. catch ( e ) {
  209. 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 );
  210. }
  211. }
  212. /**
  213. * Check if a node value has the attributes pattern.
  214. * If yes, extract it and add that value as one or several attributes
  215. * to the target element.
  216. *
  217. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  218. * directly on refresh (F5)
  219. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  220. */
  221. function addAttributeInElement( node, elementTarget, separator ) {
  222. var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
  223. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  224. var nodeValue = node.nodeValue;
  225. if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  226. var classes = matches[1];
  227. nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
  228. node.nodeValue = nodeValue;
  229. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  230. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  231. }
  232. return true;
  233. }
  234. return false;
  235. }
  236. /**
  237. * Add attributes to the parent element of a text node,
  238. * or the element of an attribute node.
  239. */
  240. function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
  241. if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
  242. previousParentElement = element;
  243. for( var i = 0; i < element.childNodes.length; i++ ) {
  244. childElement = element.childNodes[i];
  245. if ( i > 0 ) {
  246. j = i - 1;
  247. while ( j >= 0 ) {
  248. aPreviousChildElement = element.childNodes[j];
  249. if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
  250. previousParentElement = aPreviousChildElement;
  251. break;
  252. }
  253. j = j - 1;
  254. }
  255. }
  256. parentSection = section;
  257. if( childElement.nodeName == "section" ) {
  258. parentSection = childElement ;
  259. previousParentElement = childElement ;
  260. }
  261. if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
  262. addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
  263. }
  264. }
  265. }
  266. if ( element.nodeType == Node.COMMENT_NODE ) {
  267. if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
  268. addAttributeInElement( element, section, separatorSectionAttributes );
  269. }
  270. }
  271. }
  272. /**
  273. * Converts any current data-markdown slides in the
  274. * DOM to HTML.
  275. */
  276. function convertSlides() {
  277. var sections = document.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
  278. [].slice.call( sections ).forEach( function( section ) {
  279. section.setAttribute( 'data-markdown-parsed', true )
  280. var notes = section.querySelector( 'aside.notes' );
  281. var markdown = getMarkdownFromSlide( section );
  282. section.innerHTML = marked( markdown );
  283. addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
  284. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  285. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
  286. section.getAttribute( 'data-attributes' ) ||
  287. section.parentNode.getAttribute( 'data-attributes' ) ||
  288. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
  289. // If there were notes, we need to re-add them after
  290. // having overwritten the section's HTML
  291. if( notes ) {
  292. section.appendChild( notes );
  293. }
  294. } );
  295. }
  296. function checkIfLoaded() {
  297. if( markdownFilesToLoad === 0 ) {
  298. if( loadCallback ) {
  299. loadCallback();
  300. loadCallback = null;
  301. }
  302. }
  303. }
  304. // API
  305. var RevealMarkdown = {
  306. /**
  307. * Starts processing and converting Markdown within the
  308. * current reveal.js deck.
  309. *
  310. * @param {function} callback function to invoke once
  311. * we've finished loading and parsing Markdown
  312. */
  313. init: function( callback ) {
  314. if( typeof marked === 'undefined' ) {
  315. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  316. }
  317. if( typeof hljs !== 'undefined' ) {
  318. marked.setOptions({
  319. highlight: function( code, lang ) {
  320. return hljs.highlightAuto( code, [lang] ).value;
  321. }
  322. });
  323. }
  324. // marked can be configured via reveal.js config options
  325. var options = Reveal.getConfig().markdown;
  326. if( options ) {
  327. marked.setOptions( options );
  328. }
  329. loadCallback = callback;
  330. processSlides();
  331. 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. }));