Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

plugin.js 15KB

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