make plugins work with multiple presentations on same page

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

View File

@ -3,4 +3,4 @@
/*!
* reveal.js plugin that adds syntax highlight support.
*/
var t={id:"highlight",HIGHLIGHT_STEP_DELIMITER:"|",HIGHLIGHT_LINE_DELIMITER:",",HIGHLIGHT_LINE_RANGE_DELIMITER:"-",init:function(e){var r=e.getConfig().highlight||{};r.highlightOnLoad="boolean"!=typeof r.highlightOnLoad||r.highlightOnLoad,r.escapeHTML="boolean"!=typeof r.escapeHTML||r.escapeHTML,[].slice.call(document.querySelectorAll(".reveal pre code")).forEach((function(e){e.hasAttribute("data-trim")&&"function"==typeof e.innerHTML.trim&&(e.innerHTML=function(e){function t(e){return e.replace(/^[\s\uFEFF\xA0]+/g,"")}return function(e){var r=function(e){for(var t=e.split("\n"),r=0;r<t.length&&""===t[r].trim();r++)t.splice(r--,1);for(r=t.length-1;r>=0&&""===t[r].trim();r--)t.splice(r,1);return t.join("\n")}(e.innerHTML).split("\n"),a=r.reduce((function(e,r){return r.length>0&&t(r).length>0&&e>r.length-t(r).length?r.length-t(r).length:e}),Number.POSITIVE_INFINITY);return r.map((function(e,t){return e.slice(a)})).join("\n")}(e)}(e)),r.escapeHTML&&!e.hasAttribute("data-noescape")&&(e.innerHTML=e.innerHTML.replace(/</g,"&lt;").replace(/>/g,"&gt;")),e.addEventListener("focusout",(function(e){hljs.highlightBlock(e.currentTarget)}),!1),r.highlightOnLoad&&t.highlightBlock(e)})),e.on("pdf-ready",(function(){[].slice.call(document.querySelectorAll(".reveal pre code[data-line-numbers].current-fragment")).forEach((function(e){t.scrollHighlightedLineIntoView(e,{},!0)}))}))},highlightBlock:function(e){if(hljs.highlightBlock(e),0!==e.innerHTML.trim().length&&e.hasAttribute("data-line-numbers")){hljs.lineNumbersBlock(e,{singleLine:!0});var r={currentBlock:e},a=t.deserializeHighlightSteps(e.getAttribute("data-line-numbers"));if(a.length>1){var i=parseInt(e.getAttribute("data-fragment-index"),10);("number"!=typeof i||isNaN(i))&&(i=null),a.slice(1).forEach((function(a){var n=e.cloneNode(!0);n.setAttribute("data-line-numbers",t.serializeHighlightSteps([a])),n.classList.add("fragment"),e.parentNode.appendChild(n),t.highlightLines(n),"number"==typeof i?(n.setAttribute("data-fragment-index",i),i+=1):n.removeAttribute("data-fragment-index"),n.addEventListener("visible",t.scrollHighlightedLineIntoView.bind(t,n,r)),n.addEventListener("hidden",t.scrollHighlightedLineIntoView.bind(t,n.previousSibling,r))})),e.removeAttribute("data-fragment-index"),e.setAttribute("data-line-numbers",t.serializeHighlightSteps([a[0]]))}var n="function"==typeof e.closest?e.closest("section:not(.stack)"):null;if(n){n.addEventListener("visible",(function a(){t.scrollHighlightedLineIntoView(e,r,!0),n.removeEventListener("visible",a)}))}t.highlightLines(e)}},scrollHighlightedLineIntoView:function(e,r,a){cancelAnimationFrame(r.animationFrameID),r.currentBlock&&(e.scrollTop=r.currentBlock.scrollTop),r.currentBlock=e;var i=this.getHighlightedLineBounds(e),n=e.offsetHeight,o=getComputedStyle(e);n-=parseInt(o.paddingTop)+parseInt(o.paddingBottom);var s=e.scrollTop,l=i.top+(Math.min(i.bottom-i.top,n)-n)/2,c=e.querySelector(".hljs-ln");if(c&&(l+=c.offsetTop-parseInt(o.paddingTop)),l=Math.max(Math.min(l,e.scrollHeight-n),0),!0===a||s===l)e.scrollTop=l;else{if(e.scrollHeight<=n)return;var _=0;!function a(){_=Math.min(_+.02,1),e.scrollTop=s+(l-s)*t.easeInOutQuart(_),_<1&&(r.animationFrameID=requestAnimationFrame(a))}()}},easeInOutQuart:function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},getHighlightedLineBounds:function(e){var t=e.querySelectorAll(".highlight-line");if(0===t.length)return{top:0,bottom:0};var r=t[0],a=t[t.length-1];return{top:r.offsetTop,bottom:a.offsetTop+a.offsetHeight}},highlightLines:function(e,r){var a=t.deserializeHighlightSteps(r||e.getAttribute("data-line-numbers"));a.length&&a[0].forEach((function(t){var r=[];"number"==typeof t.end?r=[].slice.call(e.querySelectorAll("table tr:nth-child(n+"+t.start+"):nth-child(-n+"+t.end+")")):"number"==typeof t.start&&(r=[].slice.call(e.querySelectorAll("table tr:nth-child("+t.start+")"))),r.length&&(r.forEach((function(e){e.classList.add("highlight-line")})),e.classList.add("has-highlights"))}))},deserializeHighlightSteps:function(e){return(e=(e=e.replace(/\s/g,"")).split(t.HIGHLIGHT_STEP_DELIMITER)).map((function(e){return e.split(t.HIGHLIGHT_LINE_DELIMITER).map((function(e){if(/^[\d-]+$/.test(e)){e=e.split(t.HIGHLIGHT_LINE_RANGE_DELIMITER);var r=parseInt(e[0],10),a=parseInt(e[1],10);return isNaN(a)?{start:r}:{start:r,end:a}}return{}}))}))},serializeHighlightSteps:function(e){return e.map((function(e){return e.map((function(e){return"number"==typeof e.end?e.start+t.HIGHLIGHT_LINE_RANGE_DELIMITER+e.end:"number"==typeof e.start?e.start:""})).join(t.HIGHLIGHT_LINE_DELIMITER)})).join(t.HIGHLIGHT_STEP_DELIMITER)}};return function(){return t}}));
var t={id:"highlight",HIGHLIGHT_STEP_DELIMITER:"|",HIGHLIGHT_LINE_DELIMITER:",",HIGHLIGHT_LINE_RANGE_DELIMITER:"-",init:function(e){var r=e.getConfig().highlight||{};r.highlightOnLoad="boolean"!=typeof r.highlightOnLoad||r.highlightOnLoad,r.escapeHTML="boolean"!=typeof r.escapeHTML||r.escapeHTML,[].slice.call(e.getRevealElement().querySelectorAll("pre code")).forEach((function(e){e.hasAttribute("data-trim")&&"function"==typeof e.innerHTML.trim&&(e.innerHTML=function(e){function t(e){return e.replace(/^[\s\uFEFF\xA0]+/g,"")}return function(e){var r=function(e){for(var t=e.split("\n"),r=0;r<t.length&&""===t[r].trim();r++)t.splice(r--,1);for(r=t.length-1;r>=0&&""===t[r].trim();r--)t.splice(r,1);return t.join("\n")}(e.innerHTML).split("\n"),a=r.reduce((function(e,r){return r.length>0&&t(r).length>0&&e>r.length-t(r).length?r.length-t(r).length:e}),Number.POSITIVE_INFINITY);return r.map((function(e,t){return e.slice(a)})).join("\n")}(e)}(e)),r.escapeHTML&&!e.hasAttribute("data-noescape")&&(e.innerHTML=e.innerHTML.replace(/</g,"&lt;").replace(/>/g,"&gt;")),e.addEventListener("focusout",(function(e){hljs.highlightBlock(e.currentTarget)}),!1),r.highlightOnLoad&&t.highlightBlock(e)})),e.on("pdf-ready",(function(){[].slice.call(e.getRevealElement().querySelectorAll("pre code[data-line-numbers].current-fragment")).forEach((function(e){t.scrollHighlightedLineIntoView(e,{},!0)}))}))},highlightBlock:function(e){if(hljs.highlightBlock(e),0!==e.innerHTML.trim().length&&e.hasAttribute("data-line-numbers")){hljs.lineNumbersBlock(e,{singleLine:!0});var r={currentBlock:e},a=t.deserializeHighlightSteps(e.getAttribute("data-line-numbers"));if(a.length>1){var i=parseInt(e.getAttribute("data-fragment-index"),10);("number"!=typeof i||isNaN(i))&&(i=null),a.slice(1).forEach((function(a){var n=e.cloneNode(!0);n.setAttribute("data-line-numbers",t.serializeHighlightSteps([a])),n.classList.add("fragment"),e.parentNode.appendChild(n),t.highlightLines(n),"number"==typeof i?(n.setAttribute("data-fragment-index",i),i+=1):n.removeAttribute("data-fragment-index"),n.addEventListener("visible",t.scrollHighlightedLineIntoView.bind(t,n,r)),n.addEventListener("hidden",t.scrollHighlightedLineIntoView.bind(t,n.previousSibling,r))})),e.removeAttribute("data-fragment-index"),e.setAttribute("data-line-numbers",t.serializeHighlightSteps([a[0]]))}var n="function"==typeof e.closest?e.closest("section:not(.stack)"):null;if(n){n.addEventListener("visible",(function a(){t.scrollHighlightedLineIntoView(e,r,!0),n.removeEventListener("visible",a)}))}t.highlightLines(e)}},scrollHighlightedLineIntoView:function(e,r,a){cancelAnimationFrame(r.animationFrameID),r.currentBlock&&(e.scrollTop=r.currentBlock.scrollTop),r.currentBlock=e;var i=this.getHighlightedLineBounds(e),n=e.offsetHeight,o=getComputedStyle(e);n-=parseInt(o.paddingTop)+parseInt(o.paddingBottom);var s=e.scrollTop,l=i.top+(Math.min(i.bottom-i.top,n)-n)/2,c=e.querySelector(".hljs-ln");if(c&&(l+=c.offsetTop-parseInt(o.paddingTop)),l=Math.max(Math.min(l,e.scrollHeight-n),0),!0===a||s===l)e.scrollTop=l;else{if(e.scrollHeight<=n)return;var _=0;!function a(){_=Math.min(_+.02,1),e.scrollTop=s+(l-s)*t.easeInOutQuart(_),_<1&&(r.animationFrameID=requestAnimationFrame(a))}()}},easeInOutQuart:function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},getHighlightedLineBounds:function(e){var t=e.querySelectorAll(".highlight-line");if(0===t.length)return{top:0,bottom:0};var r=t[0],a=t[t.length-1];return{top:r.offsetTop,bottom:a.offsetTop+a.offsetHeight}},highlightLines:function(e,r){var a=t.deserializeHighlightSteps(r||e.getAttribute("data-line-numbers"));a.length&&a[0].forEach((function(t){var r=[];"number"==typeof t.end?r=[].slice.call(e.querySelectorAll("table tr:nth-child(n+"+t.start+"):nth-child(-n+"+t.end+")")):"number"==typeof t.start&&(r=[].slice.call(e.querySelectorAll("table tr:nth-child("+t.start+")"))),r.length&&(r.forEach((function(e){e.classList.add("highlight-line")})),e.classList.add("has-highlights"))}))},deserializeHighlightSteps:function(e){return(e=(e=e.replace(/\s/g,"")).split(t.HIGHLIGHT_STEP_DELIMITER)).map((function(e){return e.split(t.HIGHLIGHT_LINE_DELIMITER).map((function(e){if(/^[\d-]+$/.test(e)){e=e.split(t.HIGHLIGHT_LINE_RANGE_DELIMITER);var r=parseInt(e[0],10),a=parseInt(e[1],10);return isNaN(a)?{start:r}:{start:r,end:a}}return{}}))}))},serializeHighlightSteps:function(e){return e.map((function(e){return e.map((function(e){return"number"==typeof e.end?e.start+t.HIGHLIGHT_LINE_RANGE_DELIMITER+e.end:"number"==typeof e.start?e.start:""})).join(t.HIGHLIGHT_LINE_DELIMITER)})).join(t.HIGHLIGHT_STEP_DELIMITER)}};return function(){return t}}));

File diff suppressed because one or more lines are too long

2
dist/plugin/math.js vendored
View File

@ -1 +1 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).RevealMath=t()}(this,(function(){"use strict";var e=function(){var e=Reveal.getConfig().math||{},t=(e.mathjax||"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js")+"?config="+(e.config||"TeX-AMS_HTML-full"),n={messageStyle:"none",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]],skipTags:["script","noscript","style","textarea","pre"]},skipStartupTypeset:!0};function a(e,t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}return{id:"math",init:function(o){a(e,n),a(e.tex2jax,n.tex2jax),e.mathjax=e.config=null,function(e,t){var n=document.querySelector("head"),a=document.createElement("script");a.type="text/javascript",a.src=e;var o=function(){"function"==typeof t&&(t.call(),t=null)};a.onload=o,a.onreadystatechange=function(){"loaded"===this.readyState&&o()},n.appendChild(a)}(t,(function(){MathJax.Hub.Config(e),MathJax.Hub.Queue(["Typeset",MathJax.Hub]),MathJax.Hub.Queue(o.layout),o.on("slidechanged",(function(e){MathJax.Hub.Queue(["Typeset",MathJax.Hub,e.currentSlide])}))}))}}}();return function(){return e}}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).RevealMath=t()}(this,(function(){"use strict";function e(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var a=null!=arguments[r]?arguments[r]:{};r%2?t(Object(a),!0).forEach((function(t){e(n,t,a[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(a)):t(Object(a)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(a,e))}))}return n}return function(){var e,t={messageStyle:"none",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]],skipTags:["script","noscript","style","textarea","pre"]},skipStartupTypeset:!0};return{id:"math",init:function(r){var a=(e=r).getConfig().math||{},o=n({},t,{},a),c=(o.mathjax||"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js")+"?config="+(o.config||"TeX-AMS_HTML-full");o.tex2jax=n({},t.tex2jax,{},a.tex2jax),o.mathjax=o.config=null,function(e,t){var n=this,r=document.querySelector("head"),a=document.createElement("script");a.type="text/javascript",a.src=e;var o=function(){"function"==typeof t&&(t.call(),t=null)};a.onload=o,a.onreadystatechange=function(){"loaded"===n.readyState&&o()},r.appendChild(a)}(c,(function(){MathJax.Hub.Config(o),MathJax.Hub.Queue(["Typeset",MathJax.Hub,e.getRevealElement()]),MathJax.Hub.Queue(e.layout),e.on("slidechanged",(function(e){MathJax.Hub.Queue(["Typeset",MathJax.Hub,e.currentSlide])}))}))}}}}));

View File

@ -3,5 +3,5 @@
* Handles finding a text string anywhere in the slides and showing the next occurrence to the user
* by navigatating to that slide and highlighting it.
*
* By Jon Snyder <snyder.jon@gmail.com>, February 2013
*/var e=function(){var e,t,n,i;function r(e,t){var n=document.getElementById(e)||document.body,i=t||"EM",r=new RegExp("^(?:"+i+"|SCRIPT|FORM)$"),o=["#ff6","#a0ffff","#9f9","#f99","#f6f"],d=[],l=0,a="",c=[];this.setRegex=function(e){e=e.replace(/^[^\w]+|[^\w]+$/g,"").replace(/[^\w'-]+/g,"|"),a=new RegExp("("+e+")","i")},this.getRegex=function(){return a.toString().replace(/^\/\\b\(|\)\\b\/i$/g,"").replace(/\|/g," ")},this.hiliteWords=function(e){if(null!=e&&e&&a&&!r.test(e.nodeName)){if(e.hasChildNodes())for(var t=0;t<e.childNodes.length;t++)this.hiliteWords(e.childNodes[t]);if(3==e.nodeType&&(nv=e.nodeValue)&&(regs=a.exec(nv))){for(var n=e;null!=n&&"SECTION"!=n.nodeName;)n=n.parentNode;var s=Reveal.getIndices(n),u=c.length,h=!1;for(t=0;t<u;t++)c[t].h===s.h&&c[t].v===s.v&&(h=!0);h||c.push(s),d[regs[0].toLowerCase()]||(d[regs[0].toLowerCase()]=o[l++%o.length]);var p=document.createElement(i);p.appendChild(document.createTextNode(regs[0])),p.style.backgroundColor=d[regs[0].toLowerCase()],p.style.fontStyle="inherit",p.style.color="#000";var f=e.splitText(regs.index);f.nodeValue=f.nodeValue.substring(regs[0].length),e.parentNode.insertBefore(p,f)}}},this.remove=function(){for(var e=document.getElementsByTagName(i);e.length&&(el=e[0]);)el.parentNode.replaceChild(el.firstChild,el)},this.apply=function(e){if(null!=e&&e)return this.remove(),this.setRegex(e),this.hiliteWords(n),c}}function o(){var e=document.getElementById("searchinputdiv"),t=document.getElementById("searchinput");e.style.display="inline",t.focus(),t.select()}function d(){document.getElementById("searchinputdiv").style.display="none",i&&i.remove()}function l(){if(n){var o=document.getElementById("searchinput").value;""===o?(i&&i.remove(),e=null):(i=new r("slidecontent"),e=i.apply(o),t=0)}e&&(e.length&&e.length<=t&&(t=0),e.length>t&&(Reveal.slide(e[t].h,e[t].v),t++))}var a={};if(a.wrapper=document.querySelector(".reveal"),!a.wrapper.querySelector(".searchbox")){var c=document.createElement("div");c.id="searchinputdiv",c.classList.add("searchdiv"),c.style.position="absolute",c.style.top="10px",c.style.right="10px",c.style.zIndex=10,c.innerHTML='<span><input type="search" id="searchinput" class="searchinput" style="vertical-align: top;"/><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJiSURBVHjatFZNaxNBGH5md+Mmu92NVdKDRipSAyqCghgQD4L4cRe86UUtAQ+eFCxoa4/25EXBFi8eBE+eRPoDhB6KgiiixdAPCEkx2pjvTXadd9yNsflwuyUDD/O+u8PzzDPvzOwyx3EwyCZhwG3gAkp7MnpjgbopjsltcD4gjuXZZKeAR348MYLYTm3LzOs/y3j3JTfZxgXWXmTuwPHIc4VmoOmv5IrI53+AO2DdHLjkDWQ3GoEEVFXtXQOvkSnPWcyUceviLhwbDYv8/XIVj97kse7TodLvZXxYxrPUHkQ1ufXs3FEdybEIxucySOesoNvUgWU1cP3MkCBfTFdw9fGaAMVmRELq7LBw2Q3/FaAxxWIRpw+ZIr/7IouPqzUBiqmdHAv7EuhRAwf1er2Vy4x1jW3b2d5Jfvu5IPp7l2LYbcgCFFNb+FoJ7oBqEAqFMPNqFcmEgVMJDfMT+1tvN0pNjERlMS6QA5pFOKxiKVPFhakPeL3It+WGJUDxt2wFR+JhzI7v5ctkd8DXOZAkCYYxhO+lKm4+Xfqz/rIixBuNBl7eOYzkQQNzqX249mRl6zUgEcYkaJrGhUwBinVdh6IouPzwE6/DL5w4oLkH8y981aDf+uq6hlKpJESiUdNfDZi7/ehG9K6KfiA3pml0PLcsq+cSMTj2NL9ukc4UOmz7AZ3+crkC4mHujFvXNaMFB3bEr8xPS6p5O+jXxq4VZtaen7/PwzrntjcLUE0iHPS1Ud1cdiEJl/8WivZk0wXd7zWOMkeF8s0CcAmkNrC2nvXZDbbbN73ccYnZoH9bfgswAFzAe9/h3dbKAAAAAElFTkSuQmCC" id="searchbutton" class="searchicon" style="vertical-align: top; margin-top: -1px;"/></span>',a.wrapper.appendChild(c)}return document.getElementById("searchbutton").addEventListener("click",(function(e){l()}),!1),document.getElementById("searchinput").addEventListener("keyup",(function(e){switch(e.keyCode){case 13:e.preventDefault(),l(),n=!1;break;default:n=!0}}),!1),document.addEventListener("keydown",(function(e){"F"==e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),"inline"!==document.getElementById("searchinputdiv").style.display?o():d())}),!1),d(),{id:"search",init:function(e){e.registerKeyboardShortcut("CTRL + Shift + F","Search")},open:o}}();return function(){return e}}));
* @author Jon Snyder <snyder.jon@gmail.com>, February 2013
*/return function(){var e,t,n,o,i,l,r;function s(){(t=document.createElement("div")).classList.add("searchbox"),t.style.position="absolute",t.style.top="10px",t.style.right="10px",t.style.zIndex=10,t.innerHTML='<input type="search" class="searchinput" placeholder="Search..." style="vertical-align: top;"/>\n\t\t</span>',(n=t.querySelector(".searchinput")).style.width="240px",n.style.fontSize="14px",n.style.padding="4px 6px",n.style.color="#000",n.style.background="#fff",n.style.borderRadius="2px",n.style.border="0",n.style.outline="0",n.style.boxShadow="0 2px 18px rgba(0, 0, 0, 0.2)",n.style["-webkit-appearance"]="none",e.getRevealElement().appendChild(t),n.addEventListener("keyup",(function(t){switch(t.keyCode){case 13:t.preventDefault(),function(){if(l){var t=n.value;""===t?(r&&r.remove(),o=null):(r=new c("slidecontent"),o=r.apply(t),i=0)}o&&(o.length&&o.length<=i&&(i=0),o.length>i&&(e.slide(o[i].h,o[i].v),i++))}(),l=!1;break;default:l=!0}}),!1),d()}function a(){t||s(),t.style.display="inline",n.focus(),n.select()}function d(){t||s(),t.style.display="none",r&&r.remove()}function c(t,n){var o=document.getElementById(t)||document.body,i=n||"EM",l=new RegExp("^(?:"+i+"|SCRIPT|FORM)$"),r=["#ff6","#a0ffff","#9f9","#f99","#f6f"],s=[],a=0,d="",c=[];this.setRegex=function(e){e=e.replace(/^[^\w]+|[^\w]+$/g,"").replace(/[^\w'-]+/g,"|"),d=new RegExp("("+e+")","i")},this.getRegex=function(){return d.toString().replace(/^\/\\b\(|\)\\b\/i$/g,"").replace(/\|/g," ")},this.hiliteWords=function(t){if(null!=t&&t&&d&&!l.test(t.nodeName)){if(t.hasChildNodes())for(var n=0;n<t.childNodes.length;n++)this.hiliteWords(t.childNodes[n]);var o,f;if(3==t.nodeType)if((o=t.nodeValue)&&(f=d.exec(o))){for(var u=t;null!=u&&"SECTION"!=u.nodeName;)u=u.parentNode;var p=e.getIndices(u),h=c.length,y=!1;for(n=0;n<h;n++)c[n].h===p.h&&c[n].v===p.v&&(y=!0);y||c.push(p),s[f[0].toLowerCase()]||(s[f[0].toLowerCase()]=r[a++%r.length]);var g=document.createElement(i);g.appendChild(document.createTextNode(f[0])),g.style.backgroundColor=s[f[0].toLowerCase()],g.style.fontStyle="inherit",g.style.color="#000";var v=t.splitText(f.index);v.nodeValue=v.nodeValue.substring(f[0].length),t.parentNode.insertBefore(g,v)}}},this.remove=function(){for(var e,t=document.getElementsByTagName(i);t.length&&(e=t[0]);)e.parentNode.replaceChild(e.firstChild,e)},this.apply=function(e){if(null!=e&&e)return this.remove(),this.setRegex(e),this.hiliteWords(o),c}}return{id:"search",init:function(n){(e=n).registerKeyboardShortcut("CTRL + Shift + F","Search"),document.addEventListener("keydown",(function(e){"F"==e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),t||s(),"inline"!==t.style.display?a():d())}),!1)},open:a}}}));

View File

@ -10,6 +10,7 @@
<link rel="stylesheet" href="../dist/reveal.css">
<link rel="stylesheet" href="../dist/theme/white.css" id="theme">
<link rel="stylesheet" href="../lib/css/monokai.css">
</head>
<body style="background: #ddd;">
@ -19,6 +20,14 @@
<div class="slides">
<section>Deck 1, Slide 1</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>
@ -26,16 +35,38 @@
<div class="slides">
<section>Deck 2, Slide 1</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>
<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>
let deck1 = new Reveal( document.querySelector( '.deck1' ), {
embedded: true,
keyboard: false
keyboard: false,
plugins: [ RevealHighlight ]
} );
deck1.on( 'slidechanged', () => {
console.log( 'Deck 1 slide changed' );
@ -44,7 +75,8 @@
let deck2 = new Reveal( document.querySelector( '.deck2' ), {
embedded: true,
keyboard: false
keyboard: true,
plugins: [ RevealMarkdown, RevealMath ]
} );
deck2.initialize().then( () => {
deck2.slide(1);

View File

@ -13,14 +13,22 @@ let Plugin = {
HIGHLIGHT_LINE_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
var config = deck.getConfig().highlight || {};
var config = reveal.getConfig().highlight || {};
config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : 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
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
// all blocks in the deck into view at once
deck.on( 'pdf-ready', function() {
[].slice.call( document.querySelectorAll( '.reveal pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) {
reveal.on( 'pdf-ready', function() {
[].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) {
Plugin.scrollHighlightedLineIntoView( block, {}, true );
} );
} );

View File

@ -6,429 +6,435 @@
import marked from './marked.js'
let Plugin = {
const DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
DEFAULT_NOTES_SEPARATOR = 'notes?:',
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
id: 'markdown',
const SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
const Plugin = () => {
// The reveal.js instance this plugin is attached to
let deck;
/**
* Starts processing and converting Markdown within the
* current reveal.js deck.
* Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace.
*/
init: function( deck ) {
function getMarkdownFromSlide( section ) {
// 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;
// }
// });
// }
// look for a <script> or <textarea data-template> wrapper
var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
// marked can be configured via reveal.js config options
var options = deck.getConfig().markdown;
if( options ) {
marked.setOptions( options );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
// restore script end tags
text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
}
return processSlides( deck.getRevealElement() ).then( convertSlides );
return text;
},
// 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_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
/**
* Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace.
*/
function getMarkdownFromSlide( section ) {
// look for a <script> or <textarea data-template> wrapper
var template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
// restore script end tags
text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
}
return text;
/**
* Given a markdown slide section element, this will
* return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments
* to the output markdown slide.
*/
function getForwardedAttributes( section ) {
}
var attributes = section.attributes;
var result = [];
/**
* Given a markdown slide section element, this will
* return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments
* to the output markdown slide.
*/
function getForwardedAttributes( section ) {
for( var i = 0, len = attributes.length; i < len; i++ ) {
var name = attributes[i].name,
value = attributes[i].value;
var attributes = section.attributes;
var result = [];
for( var i = 0, len = attributes.length; i < len; i++ ) {
var name = attributes[i].name,
value = attributes[i].value;
// disregard attributes that are used for markdown loading/parsing
if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
if( value ) {
result.push( name + '="' + value + '"' );
}
else {
result.push( name );
}
}
return result.join( ' ' );
}
/**
* Inspects the given options and fills out default
* values for what's not defined.
*/
function getSlidifyOptions( options ) {
options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
options.attributes = options.attributes || '';
return options;
}
/**
* Helper function for constructing a markdown slide.
*/
function createMarkdownSlide( content, options ) {
options = getSlidifyOptions( options );
var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
if( notesMatch.length === 2 ) {
content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
}
// prevent script end tags in the content from interfering
// with parsing
content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
return '<script type="text/template">' + content + '</script>';
}
/**
* Parses a data string into multiple slides based
* on the passed in separator arguments.
*/
function slidify( markdown, options ) {
options = getSlidifyOptions( options );
var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
horizontalSeparatorRegex = new RegExp( options.separator );
var matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [];
// iterate until all blocks between separators are stacked up
while( matches = separatorRegex.exec( markdown ) ) {
var notes = null;
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test( matches[0] );
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push( [] );
}
// pluck slide content from markdown input
content = markdown.substring( lastIndex, matches.index );
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( content );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( content );
}
lastIndex = separatorRegex.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
var markdownSections = '';
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var i = 0, len = sectionStack.length; i < len; i++ ) {
// vertical
if( sectionStack[i] instanceof Array ) {
markdownSections += '<section '+ options.attributes +'>';
sectionStack[i].forEach( function( child ) {
markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
} );
markdownSections += '</section>';
}
else {
markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
}
}
return markdownSections;
}
/**
* Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and
* handles loading of external markdown.
*/
function processSlides( scope ) {
return new Promise( function( resolve ) {
var externalPromises = [];
[].slice.call( scope.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])') ).forEach( function( section, i ) {
if( section.getAttribute( 'data-markdown' ).length ) {
externalPromises.push( loadExternalMarkdown( section ).then(
// Finished loading external file
function( xhr, url ) {
section.outerHTML = slidify( xhr.responseText, {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
},
// Failed to load markdown
function( xhr, url ) {
section.outerHTML = '<section data-state="alert">' +
'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
'Check your browser\'s JavaScript console for more details.' +
'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
'</section>';
}
) );
}
else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
section.outerHTML = slidify( getMarkdownFromSlide( section ), {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
// disregard attributes that are used for markdown loading/parsing
if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
if( value ) {
result.push( name + '="' + value + '"' );
}
else {
section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
result.push( name );
}
});
Promise.all( externalPromises ).then( resolve );
} );
}
function loadExternalMarkdown( section ) {
return new Promise( function( resolve, reject ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute( 'data-markdown' );
var datacharset = section.getAttribute( 'data-charset' );
// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
if( datacharset != null && datacharset != '' ) {
xhr.overrideMimeType( 'text/html; charset=' + datacharset );
}
xhr.onreadystatechange = function( section, xhr ) {
if( xhr.readyState === 4 ) {
// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
return result.join( ' ' );
resolve( xhr, url );
}
/**
* Inspects the given options and fills out default
* values for what's not defined.
*/
function getSlidifyOptions( options ) {
options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
options.attributes = options.attributes || '';
return options;
}
/**
* Helper function for constructing a markdown slide.
*/
function createMarkdownSlide( content, options ) {
options = getSlidifyOptions( options );
var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
if( notesMatch.length === 2 ) {
content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
}
// prevent script end tags in the content from interfering
// with parsing
content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
return '<script type="text/template">' + content + '</script>';
}
/**
* Parses a data string into multiple slides based
* on the passed in separator arguments.
*/
function slidify( markdown, options ) {
options = getSlidifyOptions( options );
var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
horizontalSeparatorRegex = new RegExp( options.separator );
var matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [];
// iterate until all blocks between separators are stacked up
while( matches = separatorRegex.exec( markdown ) ) {
var notes = null;
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test( matches[0] );
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push( [] );
}
// pluck slide content from markdown input
content = markdown.substring( lastIndex, matches.index );
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( content );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( content );
}
lastIndex = separatorRegex.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
var markdownSections = '';
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var i = 0, len = sectionStack.length; i < len; i++ ) {
// vertical
if( sectionStack[i] instanceof Array ) {
markdownSections += '<section '+ options.attributes +'>';
sectionStack[i].forEach( function( child ) {
markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
} );
markdownSections += '</section>';
}
else {
markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
}
}
return markdownSections;
}
/**
* Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and
* handles loading of external markdown.
*/
function processSlides( scope ) {
return new Promise( function( resolve ) {
var externalPromises = [];
[].slice.call( scope.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])') ).forEach( function( section, i ) {
if( section.getAttribute( 'data-markdown' ).length ) {
externalPromises.push( loadExternalMarkdown( section ).then(
// Finished loading external file
function( xhr, url ) {
section.outerHTML = slidify( xhr.responseText, {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
},
// Failed to load markdown
function( xhr, url ) {
section.outerHTML = '<section data-state="alert">' +
'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
'Check your browser\'s JavaScript console for more details.' +
'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
'</section>';
}
) );
}
else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
section.outerHTML = slidify( getMarkdownFromSlide( section ), {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
}
else {
reject( xhr, url );
section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
}
}
}.bind( this, section, xhr );
xhr.open( 'GET', url, true );
});
try {
xhr.send();
}
catch ( e ) {
console.warn( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
resolve( xhr, url );
}
Promise.all( externalPromises ).then( resolve );
} );
} );
}
/**
* Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes
* to the target element.
*
* You need Cache Killer on Chrome to see the effect on any FOM transformation
* directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/
function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' );
var nodeValue = node.nodeValue;
var matches,
matchesClass;
if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
var classes = matches[1];
nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
node.nodeValue = nodeValue;
while( matchesClass = mardownClassRegex.exec( classes ) ) {
if( matchesClass[2] ) {
elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
} else {
elementTarget.setAttribute( matchesClass[3], "" );
}
}
return true;
}
return false;
}
/**
* Add attributes to the parent element of a text node,
* or the element of an attribute node.
*/
function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
function loadExternalMarkdown( section ) {
return new Promise( function( resolve, reject ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute( 'data-markdown' );
var datacharset = section.getAttribute( 'data-charset' );
// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
if( datacharset != null && datacharset != '' ) {
xhr.overrideMimeType( 'text/html; charset=' + datacharset );
}
xhr.onreadystatechange = function( section, xhr ) {
if( xhr.readyState === 4 ) {
// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
resolve( xhr, url );
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
var previousParentElement = element;
for( var i = 0; i < element.childNodes.length; i++ ) {
var childElement = element.childNodes[i];
if ( i > 0 ) {
var j = i - 1;
while ( j >= 0 ) {
var aPreviousChildElement = element.childNodes[j];
if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
previousParentElement = aPreviousChildElement;
break;
}
j = j - 1;
else {
reject( xhr, url );
}
}
}.bind( this, section, xhr );
xhr.open( 'GET', url, true );
try {
xhr.send();
}
catch ( e ) {
console.warn( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
resolve( xhr, url );
}
} );
}
/**
* Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes
* to the target element.
*
* You need Cache Killer on Chrome to see the effect on any FOM transformation
* directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/
function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' );
var nodeValue = node.nodeValue;
var matches,
matchesClass;
if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
var classes = matches[1];
nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
node.nodeValue = nodeValue;
while( matchesClass = mardownClassRegex.exec( classes ) ) {
if( matchesClass[2] ) {
elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
} else {
elementTarget.setAttribute( matchesClass[3], "" );
}
}
var parentSection = section;
if( childElement.nodeName == "section" ) {
parentSection = childElement ;
previousParentElement = childElement ;
return true;
}
return false;
}
/**
* Add attributes to the parent element of a text node,
* or the element of an attribute node.
*/
function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
var previousParentElement = element;
for( var i = 0; i < element.childNodes.length; i++ ) {
var childElement = element.childNodes[i];
if ( i > 0 ) {
var j = i - 1;
while ( j >= 0 ) {
var aPreviousChildElement = element.childNodes[j];
if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
previousParentElement = aPreviousChildElement;
break;
}
j = j - 1;
}
}
var parentSection = section;
if( childElement.nodeName == "section" ) {
parentSection = childElement ;
previousParentElement = childElement ;
}
if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
}
}
if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
}
if ( element.nodeType == Node.COMMENT_NODE ) {
if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
addAttributeInElement( element, section, separatorSectionAttributes );
}
}
}
if ( element.nodeType == Node.COMMENT_NODE ) {
if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
addAttributeInElement( element, section, separatorSectionAttributes );
}
/**
* Converts any current data-markdown slides in the
* DOM to HTML.
*/
function convertSlides() {
var sections = deck.getRevealElement().querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
[].slice.call( sections ).forEach( function( section ) {
section.setAttribute( 'data-markdown-parsed', true )
var notes = section.querySelector( 'aside.notes' );
var markdown = getMarkdownFromSlide( section );
section.innerHTML = marked( markdown );
addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
section.parentNode.getAttribute( 'data-element-attributes' ) ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute( 'data-attributes' ) ||
section.parentNode.getAttribute( 'data-attributes' ) ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if( notes ) {
section.appendChild( notes );
}
} );
return Promise.resolve();
}
}
/**
* Converts any current data-markdown slides in the
* DOM to HTML.
*/
function convertSlides() {
return {
id: 'markdown',
var sections = document.querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');
/**
* Starts processing and converting Markdown within the
* current reveal.js deck.
*/
init: function( reveal ) {
[].slice.call( sections ).forEach( function( section ) {
deck = reveal;
section.setAttribute( 'data-markdown-parsed', true )
// 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;
// }
// });
// }
var notes = section.querySelector( 'aside.notes' );
var markdown = getMarkdownFromSlide( section );
// marked can be configured via reveal.js config options
var options = deck.getConfig().markdown;
if( options ) {
marked.setOptions( options );
}
section.innerHTML = marked( markdown );
addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
section.parentNode.getAttribute( 'data-element-attributes' ) ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute( 'data-attributes' ) ||
section.parentNode.getAttribute( 'data-attributes' ) ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
return processSlides( deck.getRevealElement() ).then( convertSlides );
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if( notes ) {
section.appendChild( notes );
}
},
} );
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify,
marked: marked
}
return Promise.resolve();
};
}
export default Plugin;

View File

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

View File

@ -2,130 +2,89 @@
* Handles finding a text string anywhere in the slides and showing the next occurrence to the user
* by navigatating to that slide and highlighting it.
*
* By Jon Snyder <snyder.jon@gmail.com>, February 2013
* @author Jon Snyder <snyder.jon@gmail.com>, February 2013
*/
var Plugin = (function() {
const Plugin = () => {
var matchedSlides;
var currentMatchedIndex;
var searchboxDirty;
var myHilitor;
// The reveal.js instance this plugin is attached to
let deck;
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
// 2/2013 jon: modified regex to display any match, not restricted to word boundaries.
let searchElement;
let searchButton;
let searchInput;
function Hilitor(id, tag)
{
let matchedSlides;
let currentMatchedIndex;
let searchboxDirty;
let hilitor;
var targetNode = document.getElementById(id) || document.body;
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var matchingSlides = [];
function render() {
this.setRegex = function(input)
{
input = input.replace(/^[^\w]+|[^\w]+$/g, "").replace(/[^\w'-]+/g, "|");
matchRegex = new RegExp("(" + input + ")","i");
}
searchElement = document.createElement( 'div' );
searchElement.classList.add( 'searchbox' );
searchElement.style.position = 'absolute';
searchElement.style.top = '10px';
searchElement.style.right = '10px';
searchElement.style.zIndex = 10;
this.getRegex = function()
{
return matchRegex.toString().replace(/^\/\\b\(|\)\\b\/i$/g, "").replace(/\|/g, " ");
}
//embedded base64 search icon Designed by Sketchdock - http://www.sketchdock.com/:
searchElement.innerHTML = `<input type="search" class="searchinput" placeholder="Search..." style="vertical-align: top;"/>
</span>`;
// recursively apply word highlighting
this.hiliteWords = function(node)
{
if(node == undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
searchInput = searchElement.querySelector( '.searchinput' );
searchInput.style.width = '240px';
searchInput.style.fontSize = '14px';
searchInput.style.padding = '4px 6px';
searchInput.style.color = '#000';
searchInput.style.background = '#fff';
searchInput.style.borderRadius = '2px';
searchInput.style.border = '0';
searchInput.style.outline = '0';
searchInput.style.boxShadow = '0 2px 18px rgba(0, 0, 0, 0.2)';
searchInput.style['-webkit-appearance'] = 'none';
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
//find the slide's section element and save it in our list of matching slides
var secnode = node;
while (secnode != null && secnode.nodeName != 'SECTION') {
secnode = secnode.parentNode;
}
deck.getRevealElement().appendChild( searchElement );
var slideIndex = Reveal.getIndices(secnode);
var slidelen = matchingSlides.length;
var alreadyAdded = false;
for (var i=0; i < slidelen; i++) {
if ( (matchingSlides[i].h === slideIndex.h) && (matchingSlides[i].v === slideIndex.v) ) {
alreadyAdded = true;
}
}
if (! alreadyAdded) {
matchingSlides.push(slideIndex);
}
// searchButton.addEventListener( 'click', function(event) {
// doSearch();
// }, false );
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
searchInput.addEventListener( 'keyup', function( event ) {
switch (event.keyCode) {
case 13:
event.preventDefault();
doSearch();
searchboxDirty = false;
break;
default:
searchboxDirty = true;
}
}
};
}, false );
// remove highlighting
this.remove = function()
{
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
el.parentNode.replaceChild(el.firstChild, el);
}
};
closeSearch();
// start highlighting at target node
this.apply = function(input)
{
if(input == undefined || !input) return;
this.remove();
this.setRegex(input);
this.hiliteWords(targetNode);
return matchingSlides;
};
}
}
function openSearch() {
//ensure the search term input dialog is visible and has focus:
var inputboxdiv = document.getElementById("searchinputdiv");
var inputbox = document.getElementById("searchinput");
inputboxdiv.style.display = "inline";
inputbox.focus();
inputbox.select();
if( !searchElement ) render();
searchElement.style.display = 'inline';
searchInput.focus();
searchInput.select();
}
function closeSearch() {
var inputboxdiv = document.getElementById("searchinputdiv");
inputboxdiv.style.display = "none";
if(myHilitor) myHilitor.remove();
if( !searchElement ) render();
searchElement.style.display = 'none';
if(hilitor) hilitor.remove();
}
function toggleSearch() {
var inputboxdiv = document.getElementById("searchinputdiv");
if (inputboxdiv.style.display !== "inline") {
if( !searchElement ) render();
if (searchElement.style.display !== 'inline') {
openSearch();
}
else {
@ -136,16 +95,16 @@ function Hilitor(id, tag)
function doSearch() {
//if there's been a change in the search term, perform a new search:
if (searchboxDirty) {
var searchstring = document.getElementById("searchinput").value;
var searchstring = searchInput.value;
if (searchstring === '') {
if(myHilitor) myHilitor.remove();
if(hilitor) hilitor.remove();
matchedSlides = null;
}
else {
//find the keyword amongst the slides
myHilitor = new Hilitor("slidecontent");
matchedSlides = myHilitor.apply(searchstring);
hilitor = new Hilitor("slidecontent");
matchedSlides = hilitor.apply(searchstring);
currentMatchedIndex = 0;
}
}
@ -156,66 +115,129 @@ function Hilitor(id, tag)
currentMatchedIndex = 0;
}
if (matchedSlides.length > currentMatchedIndex) {
Reveal.slide(matchedSlides[currentMatchedIndex].h, matchedSlides[currentMatchedIndex].v);
deck.slide(matchedSlides[currentMatchedIndex].h, matchedSlides[currentMatchedIndex].v);
currentMatchedIndex++;
}
}
}
var dom = {};
dom.wrapper = document.querySelector( '.reveal' );
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
// 2/2013 jon: modified regex to display any match, not restricted to word boundaries.
function Hilitor(id, tag) {
var targetNode = document.getElementById(id) || document.body;
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var matchingSlides = [];
this.setRegex = function(input)
{
input = input.replace(/^[^\w]+|[^\w]+$/g, "").replace(/[^\w'-]+/g, "|");
matchRegex = new RegExp("(" + input + ")","i");
}
this.getRegex = function()
{
return matchRegex.toString().replace(/^\/\\b\(|\)\\b\/i$/g, "").replace(/\|/g, " ");
}
// recursively apply word highlighting
this.hiliteWords = function(node)
{
if(node == undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
var nv, regs;
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
//find the slide's section element and save it in our list of matching slides
var secnode = node;
while (secnode != null && secnode.nodeName != 'SECTION') {
secnode = secnode.parentNode;
}
var slideIndex = deck.getIndices(secnode);
var slidelen = matchingSlides.length;
var alreadyAdded = false;
for (var i=0; i < slidelen; i++) {
if ( (matchingSlides[i].h === slideIndex.h) && (matchingSlides[i].v === slideIndex.v) ) {
alreadyAdded = true;
}
}
if (! alreadyAdded) {
matchingSlides.push(slideIndex);
}
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
}
};
// remove highlighting
this.remove = function()
{
var arr = document.getElementsByTagName(hiliteTag);
var el;
while(arr.length && (el = arr[0])) {
el.parentNode.replaceChild(el.firstChild, el);
}
};
// start highlighting at target node
this.apply = function(input)
{
if(input == undefined || !input) return;
this.remove();
this.setRegex(input);
this.hiliteWords(targetNode);
return matchingSlides;
};
if( !dom.wrapper.querySelector( '.searchbox' ) ) {
var searchElement = document.createElement( 'div' );
searchElement.id = "searchinputdiv";
searchElement.classList.add( 'searchdiv' );
searchElement.style.position = 'absolute';
searchElement.style.top = '10px';
searchElement.style.right = '10px';
searchElement.style.zIndex = 10;
//embedded base64 search icon Designed by Sketchdock - http://www.sketchdock.com/:
searchElement.innerHTML = '<span><input type="search" id="searchinput" class="searchinput" style="vertical-align: top;"/><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJiSURBVHjatFZNaxNBGH5md+Mmu92NVdKDRipSAyqCghgQD4L4cRe86UUtAQ+eFCxoa4/25EXBFi8eBE+eRPoDhB6KgiiixdAPCEkx2pjvTXadd9yNsflwuyUDD/O+u8PzzDPvzOwyx3EwyCZhwG3gAkp7MnpjgbopjsltcD4gjuXZZKeAR348MYLYTm3LzOs/y3j3JTfZxgXWXmTuwPHIc4VmoOmv5IrI53+AO2DdHLjkDWQ3GoEEVFXtXQOvkSnPWcyUceviLhwbDYv8/XIVj97kse7TodLvZXxYxrPUHkQ1ufXs3FEdybEIxucySOesoNvUgWU1cP3MkCBfTFdw9fGaAMVmRELq7LBw2Q3/FaAxxWIRpw+ZIr/7IouPqzUBiqmdHAv7EuhRAwf1er2Vy4x1jW3b2d5Jfvu5IPp7l2LYbcgCFFNb+FoJ7oBqEAqFMPNqFcmEgVMJDfMT+1tvN0pNjERlMS6QA5pFOKxiKVPFhakPeL3It+WGJUDxt2wFR+JhzI7v5ctkd8DXOZAkCYYxhO+lKm4+Xfqz/rIixBuNBl7eOYzkQQNzqX249mRl6zUgEcYkaJrGhUwBinVdh6IouPzwE6/DL5w4oLkH8y981aDf+uq6hlKpJESiUdNfDZi7/ehG9K6KfiA3pml0PLcsq+cSMTj2NL9ukc4UOmz7AZ3+crkC4mHujFvXNaMFB3bEr8xPS6p5O+jXxq4VZtaen7/PwzrntjcLUE0iHPS1Ud1cdiEJl/8WivZk0wXd7zWOMkeF8s0CcAmkNrC2nvXZDbbbN73ccYnZoH9bfgswAFzAe9/h3dbKAAAAAElFTkSuQmCC" id="searchbutton" class="searchicon" style="vertical-align: top; margin-top: -1px;"/></span>';
dom.wrapper.appendChild( searchElement );
}
document.getElementById( 'searchbutton' ).addEventListener( 'click', function(event) {
doSearch();
}, false );
document.getElementById( 'searchinput' ).addEventListener( 'keyup', function( event ) {
switch (event.keyCode) {
case 13:
event.preventDefault();
doSearch();
searchboxDirty = false;
break;
default:
searchboxDirty = true;
}
}, false );
document.addEventListener( 'keydown', function( event ) {
if( event.key == "F" && (event.ctrlKey || event.metaKey) ) { //Control+Shift+f
event.preventDefault();
toggleSearch();
}
}, false );
closeSearch();
return {
id: 'search',
init: reveal => {
reveal.registerKeyboardShortcut( 'CTRL + Shift + F', 'Search' );
deck = reveal;
deck.registerKeyboardShortcut( 'CTRL + Shift + F', 'Search' );
document.addEventListener( 'keydown', function( event ) {
if( event.key == "F" && (event.ctrlKey || event.metaKey) ) { //Control+Shift+f
event.preventDefault();
toggleSearch();
}
}, false );
},
open: openSearch
}
})();
};
export default () => Plugin;
export default Plugin;