Christophe Dervieux | 8afae13 | 2021-12-06 15:16:42 +0100 | [diff] [blame] | 1 | /** |
| 2 | * A plugin which enables rendering of math equations inside |
| 3 | * of reveal.js slides. Essentially a thin wrapper for MathJax 3 |
| 4 | * |
| 5 | * @author Hakim El Hattab |
| 6 | * @author Gerhard Burger |
| 7 | */ |
| 8 | export const MathJax3 = () => { |
| 9 | |
| 10 | // The reveal.js instance this plugin is attached to |
| 11 | let deck; |
| 12 | |
| 13 | let defaultOptions = { |
| 14 | tex: { |
| 15 | inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ] |
| 16 | }, |
| 17 | options: { |
| 18 | skipHtmlTags: [ 'script', 'noscript', 'style', 'textarea', 'pre' ] |
| 19 | }, |
| 20 | startup: { |
| 21 | ready: () => { |
| 22 | MathJax.startup.defaultReady(); |
| 23 | MathJax.startup.promise.then(() => { |
Marc Kupietz | 9c036a4 | 2024-05-14 13:17:25 +0200 | [diff] [blame] | 24 | deck.layout(); |
Christophe Dervieux | 8afae13 | 2021-12-06 15:16:42 +0100 | [diff] [blame] | 25 | }); |
| 26 | } |
| 27 | } |
| 28 | }; |
| 29 | |
| 30 | function loadScript( url, callback ) { |
| 31 | |
| 32 | let script = document.createElement( 'script' ); |
| 33 | script.type = "text/javascript" |
| 34 | script.id = "MathJax-script" |
| 35 | script.src = url; |
| 36 | script.async = true |
| 37 | |
| 38 | // Wrapper for callback to make sure it only fires once |
| 39 | script.onload = () => { |
| 40 | if (typeof callback === 'function') { |
| 41 | callback.call(); |
| 42 | callback = null; |
| 43 | } |
| 44 | }; |
| 45 | |
| 46 | document.head.appendChild( script ); |
| 47 | |
| 48 | } |
| 49 | |
| 50 | return { |
| 51 | id: 'mathjax3', |
| 52 | init: function(reveal) { |
| 53 | |
| 54 | deck = reveal; |
| 55 | |
| 56 | let revealOptions = deck.getConfig().mathjax3 || {}; |
| 57 | let options = {...defaultOptions, ...revealOptions}; |
| 58 | options.tex = {...defaultOptions.tex, ...revealOptions.tex} |
Marc Kupietz | 09b7575 | 2023-10-07 09:32:19 +0200 | [diff] [blame] | 59 | options.options = {...defaultOptions.options, ...revealOptions.options} |
Christophe Dervieux | 8afae13 | 2021-12-06 15:16:42 +0100 | [diff] [blame] | 60 | options.startup = {...defaultOptions.startup, ...revealOptions.startup} |
| 61 | |
| 62 | let url = options.mathjax || 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'; |
| 63 | options.mathjax = null; |
| 64 | |
| 65 | window.MathJax = options; |
| 66 | |
| 67 | loadScript( url, function() { |
| 68 | // Reprocess equations in slides when they turn visible |
Marc Kupietz | 9c036a4 | 2024-05-14 13:17:25 +0200 | [diff] [blame] | 69 | deck.addEventListener( 'slidechanged', function( event ) { |
Christophe Dervieux | 8afae13 | 2021-12-06 15:16:42 +0100 | [diff] [blame] | 70 | MathJax.typeset(); |
| 71 | } ); |
| 72 | } ); |
| 73 | |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | }; |