You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

452 lines
13KB

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