plugin.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. const Plugin = () => {
  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: 'math',
  42. init: function( reveal ) {
  43. deck = reveal;
  44. let revealOptions = deck.getConfig().math || {};
  45. let options = { ...defaultOptions, ...revealOptions };
  46. let mathjax = options.mathjax || 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/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. };
  65. export default Plugin;