make plugins work with multiple presentations on same page

master
Hakim El Hattab 2020-04-23 10:54:48 +02:00
parent 210fbb7646
commit b92d16f48d
9 changed files with 626 additions and 561 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
dist/plugin/math.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -10,6 +10,7 @@
<link rel="stylesheet" href="../dist/reveal.css"> <link rel="stylesheet" href="../dist/reveal.css">
<link rel="stylesheet" href="../dist/theme/white.css" id="theme"> <link rel="stylesheet" href="../dist/theme/white.css" id="theme">
<link rel="stylesheet" href="../lib/css/monokai.css">
</head> </head>
<body style="background: #ddd;"> <body style="background: #ddd;">
@ -19,6 +20,14 @@
<div class="slides"> <div class="slides">
<section>Deck 1, Slide 1</section> <section>Deck 1, Slide 1</section>
<section>Deck 1, Slide 2</section> <section>Deck 1, Slide 2</section>
<section>
<pre data-id="code-animation"><code class="hljs" data-trim data-line-numbers>
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
}
</code></pre>
</section>
</div> </div>
</div> </div>
@ -26,16 +35,38 @@
<div class="slides"> <div class="slides">
<section>Deck 2, Slide 1</section> <section>Deck 2, Slide 1</section>
<section>Deck 2, Slide 2</section> <section>Deck 2, Slide 2</section>
<section data-markdown>
<script type="text/template">
## Markdown plugin
- 1
- 2
- 3
</script>
</section>
<section>
<h3>The Lorenz Equations</h3>
\[\begin{aligned}
\dot{x} &amp; = \sigma(y-x) \\
\dot{y} &amp; = \rho x - y - xz \\
\dot{z} &amp; = -\beta z + xy
\end{aligned} \]
</section>
</div> </div>
</div> </div>
</div> </div>
<script src="../dist/reveal.es5.js"></script> <script src="../dist/reveal.es5.js"></script>
<script src="../dist/plugin/highlight.js"></script>
<script src="../dist/plugin/markdown.js"></script>
<script src="../dist/plugin/math.js"></script>
<script> <script>
let deck1 = new Reveal( document.querySelector( '.deck1' ), { let deck1 = new Reveal( document.querySelector( '.deck1' ), {
embedded: true, embedded: true,
keyboard: false keyboard: false,
plugins: [ RevealHighlight ]
} ); } );
deck1.on( 'slidechanged', () => { deck1.on( 'slidechanged', () => {
console.log( 'Deck 1 slide changed' ); console.log( 'Deck 1 slide changed' );
@ -44,7 +75,8 @@
let deck2 = new Reveal( document.querySelector( '.deck2' ), { let deck2 = new Reveal( document.querySelector( '.deck2' ), {
embedded: true, embedded: true,
keyboard: false keyboard: true,
plugins: [ RevealMarkdown, RevealMath ]
} ); } );
deck2.initialize().then( () => { deck2.initialize().then( () => {
deck2.slide(1); deck2.slide(1);

View File

@ -13,14 +13,22 @@ let Plugin = {
HIGHLIGHT_LINE_DELIMITER: ',', HIGHLIGHT_LINE_DELIMITER: ',',
HIGHLIGHT_LINE_RANGE_DELIMITER: '-', HIGHLIGHT_LINE_RANGE_DELIMITER: '-',
init: function( deck ) { /**
* Highlights code blocks withing the given deck.
*
* Note that this can be called multiple times if
* there are multiple presentations on one page.
*
* @param {Reveal} reveal the reveal.js instance
*/
init: function( reveal ) {
// Read the plugin config options and provide fallbacks // Read the plugin config options and provide fallbacks
var config = deck.getConfig().highlight || {}; var config = reveal.getConfig().highlight || {};
config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : true; config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : true;
config.escapeHTML = typeof config.escapeHTML === 'boolean' ? config.escapeHTML : true; config.escapeHTML = typeof config.escapeHTML === 'boolean' ? config.escapeHTML : true;
[].slice.call( document.querySelectorAll( '.reveal pre code' ) ).forEach( function( block ) { [].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( function( block ) {
// Trim whitespace if the "data-trim" attribute is present // Trim whitespace if the "data-trim" attribute is present
if( block.hasAttribute( 'data-trim' ) && typeof block.innerHTML.trim === 'function' ) { if( block.hasAttribute( 'data-trim' ) && typeof block.innerHTML.trim === 'function' ) {
@ -45,8 +53,8 @@ let Plugin = {
// If we're printing to PDF, scroll the code highlights of // If we're printing to PDF, scroll the code highlights of
// all blocks in the deck into view at once // all blocks in the deck into view at once
deck.on( 'pdf-ready', function() { reveal.on( 'pdf-ready', function() {
[].slice.call( document.querySelectorAll( '.reveal pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) { [].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) {
Plugin.scrollHighlightedLineIntoView( block, {}, true ); Plugin.scrollHighlightedLineIntoView( block, {}, true );
} ); } );
} ); } );

View File

@ -6,59 +6,23 @@
import marked from './marked.js' import marked from './marked.js'
let Plugin = { const DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
id: 'markdown',
/**
* Starts processing and converting Markdown within the
* current reveal.js deck.
*/
init: function( deck ) {
// This should no longer be needed, as long as the highlight.js
// plugin is included after the markdown plugin
// if( typeof window.hljs !== 'undefined' ) {
// marked.setOptions({
// highlight: function( code, lang ) {
// return window.hljs.highlightAuto( code, lang ? [lang] : null ).value;
// }
// });
// }
// marked can be configured via reveal.js config options
var options = deck.getConfig().markdown;
if( options ) {
marked.setOptions( options );
}
return processSlides( deck.getRevealElement() ).then( convertSlides );
},
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify,
marked: marked
};
export default () => Plugin;
var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
DEFAULT_NOTES_SEPARATOR = 'notes?:', DEFAULT_NOTES_SEPARATOR = 'notes?:',
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$', DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$'; DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__'; const SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
const Plugin = () => {
/** // The reveal.js instance this plugin is attached to
let deck;
/**
* Retrieves the markdown contents of a slide section * Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace. * element. Normalizes leading tabs/whitespace.
*/ */
function getMarkdownFromSlide( section ) { function getMarkdownFromSlide( section ) {
// look for a <script> or <textarea data-template> wrapper // look for a <script> or <textarea data-template> wrapper
var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' ); var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
@ -81,15 +45,15 @@ function getMarkdownFromSlide( section ) {
return text; return text;
} }
/** /**
* Given a markdown slide section element, this will * Given a markdown slide section element, this will
* return all arguments that aren't related to markdown * return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments * parsing. Used to forward any other user-defined arguments
* to the output markdown slide. * to the output markdown slide.
*/ */
function getForwardedAttributes( section ) { function getForwardedAttributes( section ) {
var attributes = section.attributes; var attributes = section.attributes;
var result = []; var result = [];
@ -111,13 +75,13 @@ function getForwardedAttributes( section ) {
return result.join( ' ' ); return result.join( ' ' );
} }
/** /**
* Inspects the given options and fills out default * Inspects the given options and fills out default
* values for what's not defined. * values for what's not defined.
*/ */
function getSlidifyOptions( options ) { function getSlidifyOptions( options ) {
options = options || {}; options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR; options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
@ -126,12 +90,12 @@ function getSlidifyOptions( options ) {
return options; return options;
} }
/** /**
* Helper function for constructing a markdown slide. * Helper function for constructing a markdown slide.
*/ */
function createMarkdownSlide( content, options ) { function createMarkdownSlide( content, options ) {
options = getSlidifyOptions( options ); options = getSlidifyOptions( options );
@ -147,13 +111,13 @@ function createMarkdownSlide( content, options ) {
return '<script type="text/template">' + content + '</script>'; return '<script type="text/template">' + content + '</script>';
} }
/** /**
* Parses a data string into multiple slides based * Parses a data string into multiple slides based
* on the passed in separator arguments. * on the passed in separator arguments.
*/ */
function slidify( markdown, options ) { function slidify( markdown, options ) {
options = getSlidifyOptions( options ); options = getSlidifyOptions( options );
@ -219,14 +183,14 @@ function slidify( markdown, options ) {
return markdownSections; return markdownSections;
} }
/** /**
* Parses any current data-markdown slides, splits * Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and * multi-slide markdown into separate sections and
* handles loading of external markdown. * handles loading of external markdown.
*/ */
function processSlides( scope ) { function processSlides( scope ) {
return new Promise( function( resolve ) { return new Promise( function( resolve ) {
@ -280,9 +244,9 @@ function processSlides( scope ) {
} ); } );
} }
function loadExternalMarkdown( section ) { function loadExternalMarkdown( section ) {
return new Promise( function( resolve, reject ) { return new Promise( function( resolve, reject ) {
@ -324,9 +288,9 @@ function loadExternalMarkdown( section ) {
} ); } );
} }
/** /**
* Check if a node value has the attributes pattern. * Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes * If yes, extract it and add that value as one or several attributes
* to the target element. * to the target element.
@ -335,7 +299,7 @@ function loadExternalMarkdown( section ) {
* directly on refresh (F5) * directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277 * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/ */
function addAttributeInElement( node, elementTarget, separator ) { function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' ); var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' ); var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' );
@ -357,13 +321,13 @@ function addAttributeInElement( node, elementTarget, separator ) {
return true; return true;
} }
return false; return false;
} }
/** /**
* Add attributes to the parent element of a text node, * Add attributes to the parent element of a text node,
* or the element of an attribute node. * or the element of an attribute node.
*/ */
function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) { function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) { if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
var previousParentElement = element; var previousParentElement = element;
@ -396,15 +360,15 @@ function addAttributes( section, element, previousElement, separatorElementAttri
addAttributeInElement( element, section, separatorSectionAttributes ); addAttributeInElement( element, section, separatorSectionAttributes );
} }
} }
} }
/** /**
* Converts any current data-markdown slides in the * Converts any current data-markdown slides in the
* DOM to HTML. * DOM to HTML.
*/ */
function convertSlides() { function convertSlides() {
var sections = document.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])'); var sections = deck.getRevealElement().querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
[].slice.call( sections ).forEach( function( section ) { [].slice.call( sections ).forEach( function( section ) {
@ -431,4 +395,46 @@ function convertSlides() {
return Promise.resolve(); return Promise.resolve();
} }
return {
id: 'markdown',
/**
* Starts processing and converting Markdown within the
* current reveal.js deck.
*/
init: function( reveal ) {
deck = reveal;
// This should no longer be needed, as long as the highlight.js
// plugin is included after the markdown plugin
// if( typeof window.hljs !== 'undefined' ) {
// marked.setOptions({
// highlight: function( code, lang ) {
// return window.hljs.highlightAuto( code, lang ? [lang] : null ).value;
// }
// });
// }
// marked can be configured via reveal.js config options
var options = deck.getConfig().markdown;
if( options ) {
marked.setOptions( options );
}
return processSlides( deck.getRevealElement() ).then( convertSlides );
},
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify,
marked: marked
}
};
export default Plugin;

View File

@ -4,14 +4,12 @@
* *
* @author Hakim El Hattab * @author Hakim El Hattab
*/ */
let Plugin = (function(){ const Plugin = () => {
var options = Reveal.getConfig().math || {}; // The reveal.js instance this plugin is attached to
var mathjax = options.mathjax || 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js'; let deck;
var config = options.config || 'TeX-AMS_HTML-full';
var url = mathjax + '?config=' + config;
var defaultOptions = { let defaultOptions = {
messageStyle: 'none', messageStyle: 'none',
tex2jax: { tex2jax: {
inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ], inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ],
@ -20,25 +18,15 @@ let Plugin = (function(){
skipStartupTypeset: true skipStartupTypeset: true
}; };
function defaults( options, defaultOptions ) {
for ( var i in defaultOptions ) {
if ( !options.hasOwnProperty( i ) ) {
options[i] = defaultOptions[i];
}
}
}
function loadScript( url, callback ) { function loadScript( url, callback ) {
var head = document.querySelector( 'head' ); let head = document.querySelector( 'head' );
var script = document.createElement( 'script' ); let script = document.createElement( 'script' );
script.type = 'text/javascript'; script.type = 'text/javascript';
script.src = url; script.src = url;
// Wrapper for callback to make sure it only fires once // Wrapper for callback to make sure it only fires once
var finish = function() { let finish = () => {
if( typeof callback === 'function' ) { if( typeof callback === 'function' ) {
callback.call(); callback.call();
callback = null; callback = null;
@ -48,7 +36,7 @@ let Plugin = (function(){
script.onload = finish; script.onload = finish;
// IE // IE
script.onreadystatechange = function() { script.onreadystatechange = () => {
if ( this.readyState === 'loaded' ) { if ( this.readyState === 'loaded' ) {
finish(); finish();
} }
@ -62,10 +50,19 @@ let Plugin = (function(){
return { return {
id: 'math', id: 'math',
init: function( deck ) { init: function( reveal ) {
deck = reveal;
let revealOptions = deck.getConfig().math || {};
let options = { ...defaultOptions, ...revealOptions };
let mathjax = options.mathjax || 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js';
let config = options.config || 'TeX-AMS_HTML-full';
let url = mathjax + '?config=' + config;
options.tex2jax = { ...defaultOptions.tex2jax, ...revealOptions.tex2jax };
defaults( options, defaultOptions );
defaults( options.tex2jax, defaultOptions.tex2jax );
options.mathjax = options.config = null; options.mathjax = options.config = null;
loadScript( url, function() { loadScript( url, function() {
@ -74,7 +71,7 @@ let Plugin = (function(){
// Typeset followed by an immediate reveal.js layout since // Typeset followed by an immediate reveal.js layout since
// the typesetting process could affect slide height // the typesetting process could affect slide height
MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub ] ); MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, deck.getRevealElement() ] );
MathJax.Hub.Queue( deck.layout ); MathJax.Hub.Queue( deck.layout );
// Reprocess equations in slides when they turn visible // Reprocess equations in slides when they turn visible
@ -89,6 +86,6 @@ let Plugin = (function(){
} }
} }
})(); };
export default () => Plugin; export default Plugin;

File diff suppressed because one or more lines are too long