markdown.js 13 KB

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