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