markdown.js 12 KB

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