mathjax2.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  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. */
  7. export const MathJax2 = () => {
  8. // The reveal.js instance this plugin is attached to
  9. let deck;
  10. let defaultOptions = {
  11. messageStyle: 'none',
  12. tex2jax: {
  13. inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ],
  14. skipTags: [ 'script', 'noscript', 'style', 'textarea', 'pre' ]
  15. },
  16. skipStartupTypeset: true
  17. };
  18. function loadScript( url, callback ) {
  19. let head = document.querySelector( 'head' );
  20. let script = document.createElement( 'script' );
  21. script.type = 'text/javascript';
  22. script.src = url;
  23. // Wrapper for callback to make sure it only fires once
  24. let finish = () => {
  25. if( typeof callback === 'function' ) {
  26. callback.call();
  27. callback = null;
  28. }
  29. }
  30. script.onload = finish;
  31. // IE
  32. script.onreadystatechange = () => {
  33. if ( this.readyState === 'loaded' ) {
  34. finish();
  35. }
  36. }
  37. // Normal browsers
  38. head.appendChild( script );
  39. }
  40. return {
  41. id: 'mathjax2',
  42. init: function( reveal ) {
  43. deck = reveal;
  44. let revealOptions = deck.getConfig().mathjax2 || deck.getConfig().math || {};
  45. let options = { ...defaultOptions, ...revealOptions };
  46. let mathjax = options.mathjax || 'https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js';
  47. let config = options.config || 'TeX-AMS_HTML-full';
  48. let url = mathjax + '?config=' + config;
  49. options.tex2jax = { ...defaultOptions.tex2jax, ...revealOptions.tex2jax };
  50. options.mathjax = options.config = null;
  51. loadScript( url, function() {
  52. MathJax.Hub.Config( options );
  53. // Typeset followed by an immediate reveal.js layout since
  54. // the typesetting process could affect slide height
  55. MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, deck.getRevealElement() ] );
  56. MathJax.Hub.Queue( deck.layout );
  57. // Reprocess equations in slides when they turn visible
  58. deck.on( 'slidechanged', function( event ) {
  59. MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, event.currentSlide ] );
  60. } );
  61. } );
  62. }
  63. }
  64. };