markdown.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 exports === 'object' ) {
  8. module.exports = factory( require( './marked' ) );
  9. }
  10. else {
  11. // Browser globals (root is window)
  12. root.RevealMarkdown = factory( root.marked );
  13. root.RevealMarkdown.initialize();
  14. }
  15. }( this, function( marked ) {
  16. if( typeof marked === 'undefined' ) {
  17. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  18. }
  19. if( typeof hljs !== 'undefined' ) {
  20. marked.setOptions({
  21. highlight: function( lang, code ) {
  22. return hljs.highlightAuto( lang, code ).value;
  23. }
  24. });
  25. }
  26. var DEFAULT_SLIDE_SEPARATOR = '^\n---\n$',
  27. DEFAULT_NOTES_SEPARATOR = 'note:';
  28. /**
  29. * Retrieves the markdown contents of a slide section
  30. * element. Normalizes leading tabs/whitespace.
  31. */
  32. function getMarkdownFromSlide( section ) {
  33. var template = section.querySelector( 'script' );
  34. // strip leading whitespace so it isn't evaluated as code
  35. var text = ( template || section ).textContent;
  36. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  37. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  38. if( leadingTabs > 0 ) {
  39. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  40. }
  41. else if( leadingWs > 1 ) {
  42. text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
  43. }
  44. return text;
  45. }
  46. /**
  47. * Given a markdown slide section element, this will
  48. * return all arguments that aren't related to markdown
  49. * parsing. Used to forward any other user-defined arguments
  50. * to the output markdown slide.
  51. */
  52. function getForwardedAttributes( section ) {
  53. var attributes = section.attributes;
  54. var result = [];
  55. for( var i = 0, len = attributes.length; i < len; i++ ) {
  56. var name = attributes[i].name,
  57. value = attributes[i].value;
  58. // disregard attributes that are used for markdown loading/parsing
  59. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  60. if( value ) {
  61. result.push( name + '=' + value );
  62. }
  63. else {
  64. result.push( name );
  65. }
  66. }
  67. return result.join( ' ' );
  68. }
  69. /**
  70. * Inspects the given options and fills out default
  71. * values for what's not defined.
  72. */
  73. function getSlidifyOptions( options ) {
  74. options = options || {};
  75. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  76. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  77. options.attributes = options.attributes || '';
  78. return options;
  79. }
  80. /**
  81. * Helper function for constructing a markdown slide.
  82. */
  83. function createMarkdownSlide( content, options ) {
  84. options = getSlidifyOptions( options );
  85. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  86. if( notesMatch.length === 2 ) {
  87. content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
  88. }
  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. var sections = document.querySelectorAll( '[data-markdown]'),
  153. section;
  154. for( var i = 0, len = sections.length; i < len; i++ ) {
  155. section = sections[i];
  156. if( section.getAttribute( 'data-markdown' ).length ) {
  157. var xhr = new XMLHttpRequest(),
  158. url = section.getAttribute( 'data-markdown' );
  159. datacharset = section.getAttribute( 'data-charset' );
  160. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  161. if( datacharset != null && datacharset != '' ) {
  162. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  163. }
  164. xhr.onreadystatechange = function() {
  165. if( xhr.readyState === 4 ) {
  166. if ( xhr.status >= 200 && xhr.status < 300 ) {
  167. section.outerHTML = slidify( xhr.responseText, {
  168. separator: section.getAttribute( 'data-separator' ),
  169. verticalSeparator: section.getAttribute( 'data-vertical' ),
  170. notesSeparator: section.getAttribute( 'data-notes' ),
  171. attributes: getForwardedAttributes( section )
  172. });
  173. }
  174. else {
  175. section.outerHTML = '<section data-state="alert">' +
  176. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  177. 'Check your browser\'s JavaScript console for more details.' +
  178. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  179. '</section>';
  180. }
  181. }
  182. };
  183. xhr.open( 'GET', url, false );
  184. try {
  185. xhr.send();
  186. }
  187. catch ( e ) {
  188. 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 );
  189. }
  190. }
  191. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) {
  192. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  193. separator: section.getAttribute( 'data-separator' ),
  194. verticalSeparator: section.getAttribute( 'data-vertical' ),
  195. notesSeparator: section.getAttribute( 'data-notes' ),
  196. attributes: getForwardedAttributes( section )
  197. });
  198. }
  199. else {
  200. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  201. }
  202. }
  203. }
  204. /**
  205. * Check if a node value has the attributes pattern.
  206. * If yes, extract it and add that value as one or several attributes
  207. * the the terget element.
  208. *
  209. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  210. * directly on refresh (F5)
  211. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  212. */
  213. function addAttributeInElement(node, elementTarget){
  214. var mardownClassesInElementsRegex = new RegExp( "{\\\.\s*?([^}]+?)}", 'mg' );
  215. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  216. var nodeValue = node.nodeValue;
  217. if ( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  218. var classes = matches[1];
  219. console.log("'" + classes + "'");
  220. nodeValue = nodeValue.substring(0,matches.index) + nodeValue.substring(mardownClassesInElementsRegex.lastIndex) + "ee";
  221. console.log("'" + nodeValue + "'");
  222. node.nodeValue = nodeValue;
  223. console.log("'" + elementTarget.tagName + "'");
  224. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  225. console.log("attr='" + matchesClass[1] + "'='" + matchesClass[2] + "'");
  226. elementTarget.setAttribute(matchesClass[1], matchesClass[2]);
  227. console.log("=>'" + elementTarget.attributes[matchesClass[1]].nodeValue + "'");
  228. }
  229. }
  230. }
  231. /**
  232. * Add classes to the parent element of a text node
  233. * From http://stackoverflow.com/questions/9178174/find-all-text-nodes
  234. */
  235. function addAttributes(element)
  236. {
  237. if ( element.childNodes.length > 0 ) {
  238. for (var i = 0; i < element.childNodes.length; i++) {
  239. addAttributes(element.childNodes[i]);
  240. }
  241. }
  242. var nodeValue;
  243. var elementTarget;
  244. if ( element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue) ) {
  245. addAttributeInElement(element, element.parentNode);
  246. }
  247. if ( element.nodeType == Node.ELEMENT_NODE && element.attributes.length > 0 ) {
  248. console.log("Element '" + element.tagName + "' has " + element.attributes.length + " attributes");
  249. for (iattr=0; iattr<element.attributes.length; iattr++){
  250. var attr = element.attributes[iattr];
  251. console.log("Check attr '" + attr + "', name='" + attr.name + "'='" + attr.value + "'");
  252. addAttributeInElement(attr, element)
  253. }
  254. console.log("<== Element '" + element.tagName + "' had " + element.attributes.length + " attributes");
  255. }
  256. }
  257. /**
  258. * Converts any current data-markdown slides in the
  259. * DOM to HTML.
  260. */
  261. function convertSlides() {
  262. var sections = document.querySelectorAll( '[data-markdown]');
  263. for( var i = 0, len = sections.length; i < len; i++ ) {
  264. var section = sections[i];
  265. // Only parse the same slide once
  266. if( !section.getAttribute( 'data-markdown-parsed' ) ) {
  267. section.setAttribute( 'data-markdown-parsed', true )
  268. var notes = section.querySelector( 'aside.notes' );
  269. var markdown = getMarkdownFromSlide( section );
  270. section.innerHTML = marked( markdown );
  271. addAttributes(section);
  272. // If there were notes, we need to re-add them after
  273. // having overwritten the section's HTML
  274. if( notes ) {
  275. section.appendChild( notes );
  276. }
  277. }
  278. }
  279. }
  280. // API
  281. return {
  282. initialize: function() {
  283. processSlides();
  284. convertSlides();
  285. },
  286. // TODO: Do these belong in the API?
  287. processSlides: processSlides,
  288. convertSlides: convertSlides,
  289. slidify: slidify
  290. };
  291. }));