blob: daebe7e86b37eca79ba9bee285503194acb4cd6d [file] [log] [blame]
Christophe Dervieuxe1893ae2021-10-07 17:09:02 +02001/**
2 * A plugin which enables rendering of math equations inside
3 * of reveal.js slides. Essentially a thin wrapper for MathJax.
4 *
5 * @author Hakim El Hattab
6 */
Christophe Dervieux8afae132021-12-06 15:16:42 +01007export const MathJax2 = () => {
Christophe Dervieuxe1893ae2021-10-07 17:09:02 +02008
9 // The reveal.js instance this plugin is attached to
10 let deck;
11
12 let defaultOptions = {
13 messageStyle: 'none',
14 tex2jax: {
15 inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ],
16 skipTags: [ 'script', 'noscript', 'style', 'textarea', 'pre' ]
17 },
18 skipStartupTypeset: true
19 };
20
21 function loadScript( url, callback ) {
22
23 let head = document.querySelector( 'head' );
24 let script = document.createElement( 'script' );
25 script.type = 'text/javascript';
26 script.src = url;
27
28 // Wrapper for callback to make sure it only fires once
29 let finish = () => {
30 if( typeof callback === 'function' ) {
31 callback.call();
32 callback = null;
33 }
34 }
35
36 script.onload = finish;
37
38 // IE
39 script.onreadystatechange = () => {
40 if ( this.readyState === 'loaded' ) {
41 finish();
42 }
43 }
44
45 // Normal browsers
46 head.appendChild( script );
47
48 }
49
50 return {
Christophe Dervieux8afae132021-12-06 15:16:42 +010051 id: 'mathjax2',
Christophe Dervieuxe1893ae2021-10-07 17:09:02 +020052
53 init: function( reveal ) {
54
55 deck = reveal;
56
Christophe Dervieux8afae132021-12-06 15:16:42 +010057 let revealOptions = deck.getConfig().mathjax2 || deck.getConfig().math || {};
Christophe Dervieuxe1893ae2021-10-07 17:09:02 +020058
59 let options = { ...defaultOptions, ...revealOptions };
Christophe Dervieux8afae132021-12-06 15:16:42 +010060 let mathjax = options.mathjax || 'https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js';
Christophe Dervieuxe1893ae2021-10-07 17:09:02 +020061 let config = options.config || 'TeX-AMS_HTML-full';
62 let url = mathjax + '?config=' + config;
63
64 options.tex2jax = { ...defaultOptions.tex2jax, ...revealOptions.tex2jax };
65
66 options.mathjax = options.config = null;
67
68 loadScript( url, function() {
69
70 MathJax.Hub.Config( options );
71
72 // Typeset followed by an immediate reveal.js layout since
73 // the typesetting process could affect slide height
74 MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, deck.getRevealElement() ] );
75 MathJax.Hub.Queue( deck.layout );
76
77 // Reprocess equations in slides when they turn visible
78 deck.on( 'slidechanged', function( event ) {
79
80 MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, event.currentSlide ] );
81
82 } );
83
84 } );
85
86 }
87 }
88
89};