Path: blob/main/src/resources/formats/revealjs/reveal/plugin/highlight/plugin.js
12923 views
import hljs from 'highlight.js';12/* highlightjs-line-numbers.js 2.8.0 | (C) 2018 Yauheni Pakala | MIT License | github.com/wcoder/highlightjs-line-numbers.js */3!function(r,o){"use strict";var e,i="hljs-ln",l="hljs-ln-line",h="hljs-ln-code",s="hljs-ln-numbers",c="hljs-ln-n",m="data-line-number",a=/\r\n|\r|\n/g;function u(e){for(var n=e.toString(),t=e.anchorNode;"TD"!==t.nodeName;)t=t.parentNode;for(var r=e.focusNode;"TD"!==r.nodeName;)r=r.parentNode;var o=parseInt(t.dataset.lineNumber),a=parseInt(r.dataset.lineNumber);if(o==a)return n;var i,l=t.textContent,s=r.textContent;for(a<o&&(i=o,o=a,a=i,i=l,l=s,s=i);0!==n.indexOf(l);)l=l.slice(1);for(;-1===n.lastIndexOf(s);)s=s.slice(0,-1);for(var c=l,u=function(e){for(var n=e;"TABLE"!==n.nodeName;)n=n.parentNode;return n}(t),d=o+1;d<a;++d){var f=p('.{0}[{1}="{2}"]',[h,m,d]);c+="\n"+u.querySelector(f).textContent}return c+="\n"+s}function n(e){try{var n=o.querySelectorAll("code.hljs,code.nohighlight");for(var t in n)n.hasOwnProperty(t)&&(n[t].classList.contains("nohljsln")||d(n[t],e))}catch(e){r.console.error("LineNumbers error: ",e)}}function d(e,n){if("object"==typeof e)e.innerHTML=f(e,n)}function f(e,n){var t,r,o=(t=e,{singleLine:function(e){return!!e.singleLine&&e.singleLine}(r=(r=n)||{}),startFrom:function(e,n){var t=1;isFinite(n.startFrom)&&(t=n.startFrom);var r=function(e,n){return e.hasAttribute(n)?e.getAttribute(n):null}(e,"data-ln-start-from");return null!==r&&(t=function(e,n){if(!e)return n;var t=Number(e);return isFinite(t)?t:n}(r,1)),t}(t,r)});return function e(n){var t=n.childNodes;for(var r in t){var o;t.hasOwnProperty(r)&&(o=t[r],0<(o.textContent.trim().match(a)||[]).length&&(0<o.childNodes.length?e(o):v(o.parentNode)))}}(e),function(e,n){var t=g(e);""===t[t.length-1].trim()&&t.pop();if(1<t.length||n.singleLine){for(var r="",o=0,a=t.length;o<a;o++)r+=p('<tr><td class="{0} {1}" {3}="{5}"><div class="{2}" {3}="{5}"></div></td><td class="{0} {4}" {3}="{5}">{6}</td></tr>',[l,s,c,m,h,o+n.startFrom,0<t[o].length?t[o]:" "]);return p('<table class="{0}">{1}</table>',[i,r])}return e}(e.innerHTML,o)}function v(e){var n=e.className;if(/hljs-/.test(n)){for(var t=g(e.innerHTML),r=0,o="";r<t.length;r++){o+=p('<span class="{0}">{1}</span>\n',[n,0<t[r].length?t[r]:" "])}e.innerHTML=o.trim()}}function g(e){return 0===e.length?[]:e.split(a)}function p(e,t){return e.replace(/\{(\d+)\}/g,function(e,n){return void 0!==t[n]?t[n]:e})}hljs?(hljs.initLineNumbersOnLoad=function(e){"interactive"===o.readyState||"complete"===o.readyState?n(e):r.addEventListener("DOMContentLoaded",function(){n(e)})},hljs.lineNumbersBlock=d,hljs.lineNumbersValue=function(e,n){if("string"!=typeof e)return;var t=document.createElement("code");return t.innerHTML=e,f(t,n)},(e=o.createElement("style")).type="text/css",e.innerHTML=p(".{0}{border-collapse:collapse}.{0} td{padding:0}.{1}:before{content:attr({2})}",[i,c,m]),o.getElementsByTagName("head")[0].appendChild(e)):r.console.error("highlight.js not detected!"),document.addEventListener("copy",function(e){var n,t=window.getSelection();!function(e){for(var n=e;n;){if(n.className&&-1!==n.className.indexOf("hljs-ln-code"))return 1;n=n.parentNode}}(t.anchorNode)||(n=-1!==window.navigator.userAgent.indexOf("Edge")?u(t):t.toString(),e.clipboardData.setData("text/plain",n),e.preventDefault())})}(window,document);456/*!7* reveal.js plugin that adds syntax highlight support.8*/910const Plugin = {1112id: 'highlight',1314HIGHLIGHT_STEP_DELIMITER: '|',15HIGHLIGHT_LINE_DELIMITER: ',',16HIGHLIGHT_LINE_RANGE_DELIMITER: '-',1718hljs,1920/**21* Highlights code blocks within the given deck.22*23* Note that this can be called multiple times if24* there are multiple presentations on one page.25*26* @param {Reveal} reveal the reveal.js instance27*/28init: function( reveal ) {2930// Read the plugin config options and provide fallbacks31let config = reveal.getConfig().highlight || {};3233config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : true;34config.escapeHTML = typeof config.escapeHTML === 'boolean' ? config.escapeHTML : true;3536Array.from( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( block => {3738block.parentNode.classList.add('code-wrapper');3940// Code can optionally be wrapped in script template to avoid41// HTML being parsed by the browser (i.e. when you need to42// include <, > or & in your code).43let substitute = block.querySelector( 'script[type="text/template"]' );44if( substitute ) {45// textContent handles the HTML entity escapes for us46block.textContent = substitute.innerHTML;47}4849// Trim whitespace if the "data-trim" attribute is present50if( block.hasAttribute( 'data-trim' ) && typeof block.innerHTML.trim === 'function' ) {51block.innerHTML = betterTrim( block );52}5354// Escape HTML tags unless the "data-noescape" attrbute is present55if( config.escapeHTML && !block.hasAttribute( 'data-noescape' )) {56block.innerHTML = block.innerHTML.replace( /</g,"<").replace(/>/g, '>' );57}5859// Re-highlight when focus is lost (for contenteditable code)60block.addEventListener( 'focusout', function( event ) {61hljs.highlightElement( event.currentTarget );62}, false );6364} );6566// Triggers a callback function before we trigger highlighting67if( typeof config.beforeHighlight === 'function' ) {68config.beforeHighlight( hljs );69}7071// Run initial highlighting for all code72if( config.highlightOnLoad ) {73Array.from( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( block => {74Plugin.highlightBlock( block );75} );76}7778// If we're printing to PDF, scroll the code highlights of79// all blocks in the deck into view at once80reveal.on( 'pdf-ready', function() {81[].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) {82Plugin.scrollHighlightedLineIntoView( block, {}, true );83} );84} );8586},8788/**89* Highlights a code block. If the <code> node has the90* 'data-line-numbers' attribute we also generate slide91* numbers.92*93* If the block contains multiple line highlight steps,94* we clone the block and create a fragment for each step.95*/96highlightBlock: function( block ) {9798hljs.highlightElement( block );99100// Don't generate line numbers for empty code blocks101if( block.innerHTML.trim().length === 0 ) return;102103if( block.hasAttribute( 'data-line-numbers' ) ) {104hljs.lineNumbersBlock( block, { singleLine: true } );105106var scrollState = { currentBlock: block };107108// If there is more than one highlight step, generate109// fragments110var highlightSteps = Plugin.deserializeHighlightSteps( block.getAttribute( 'data-line-numbers' ) );111if( highlightSteps.length > 1 ) {112113// If the original code block has a fragment-index,114// each clone should follow in an incremental sequence115var fragmentIndex = parseInt( block.getAttribute( 'data-fragment-index' ), 10 );116117if( typeof fragmentIndex !== 'number' || isNaN( fragmentIndex ) ) {118fragmentIndex = null;119}120121// Generate fragments for all steps except the original block122highlightSteps.slice(1).forEach( function( highlight ) {123124var fragmentBlock = block.cloneNode( true );125fragmentBlock.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlight ] ) );126fragmentBlock.classList.add( 'fragment' );127block.parentNode.appendChild( fragmentBlock );128Plugin.highlightLines( fragmentBlock );129130if( typeof fragmentIndex === 'number' ) {131fragmentBlock.setAttribute( 'data-fragment-index', fragmentIndex );132fragmentIndex += 1;133}134else {135fragmentBlock.removeAttribute( 'data-fragment-index' );136}137138// Scroll highlights into view as we step through them139fragmentBlock.addEventListener( 'visible', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock, scrollState ) );140fragmentBlock.addEventListener( 'hidden', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock.previousElementSibling, scrollState ) );141142} );143144block.removeAttribute( 'data-fragment-index' );145block.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlightSteps[0] ] ) );146147}148149// Scroll the first highlight into view when the slide150// becomes visible. Note supported in IE11 since it lacks151// support for Element.closest.152var slide = typeof block.closest === 'function' ? block.closest( 'section:not(.stack)' ) : null;153if( slide ) {154var scrollFirstHighlightIntoView = function() {155Plugin.scrollHighlightedLineIntoView( block, scrollState, true );156slide.removeEventListener( 'visible', scrollFirstHighlightIntoView );157}158slide.addEventListener( 'visible', scrollFirstHighlightIntoView );159}160161Plugin.highlightLines( block );162163}164165},166167/**168* Animates scrolling to the first highlighted line169* in the given code block.170*/171scrollHighlightedLineIntoView: function( block, scrollState, skipAnimation ) {172173cancelAnimationFrame( scrollState.animationFrameID );174175// Match the scroll position of the currently visible176// code block177if( scrollState.currentBlock ) {178block.scrollTop = scrollState.currentBlock.scrollTop;179}180181// Remember the current code block so that we can match182// its scroll position when showing/hiding fragments183scrollState.currentBlock = block;184185var highlightBounds = this.getHighlightedLineBounds( block )186var viewportHeight = block.offsetHeight;187188// Subtract padding from the viewport height189var blockStyles = getComputedStyle( block );190viewportHeight -= parseInt( blockStyles.paddingTop ) + parseInt( blockStyles.paddingBottom );191192// Scroll position which centers all highlights193var startTop = block.scrollTop;194var targetTop = highlightBounds.top + ( Math.min( highlightBounds.bottom - highlightBounds.top, viewportHeight ) - viewportHeight ) / 2;195196// Account for offsets in position applied to the197// <table> that holds our lines of code198var lineTable = block.querySelector( '.hljs-ln' );199if( lineTable ) targetTop += lineTable.offsetTop - parseInt( blockStyles.paddingTop );200201// Make sure the scroll target is within bounds202targetTop = Math.max( Math.min( targetTop, block.scrollHeight - viewportHeight ), 0 );203204if( skipAnimation === true || startTop === targetTop ) {205block.scrollTop = targetTop;206}207else {208209// Don't attempt to scroll if there is no overflow210if( block.scrollHeight <= viewportHeight ) return;211212var time = 0;213var animate = function() {214time = Math.min( time + 0.02, 1 );215216// Update our eased scroll position217block.scrollTop = startTop + ( targetTop - startTop ) * Plugin.easeInOutQuart( time );218219// Keep animating unless we've reached the end220if( time < 1 ) {221scrollState.animationFrameID = requestAnimationFrame( animate );222}223};224225animate();226227}228229},230231/**232* The easing function used when scrolling.233*/234easeInOutQuart: function( t ) {235236// easeInOutQuart237return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t;238239},240241getHighlightedLineBounds: function( block ) {242243var highlightedLines = block.querySelectorAll( '.highlight-line' );244if( highlightedLines.length === 0 ) {245return { top: 0, bottom: 0 };246}247else {248var firstHighlight = highlightedLines[0];249var lastHighlight = highlightedLines[ highlightedLines.length -1 ];250251return {252top: firstHighlight.offsetTop,253bottom: lastHighlight.offsetTop + lastHighlight.offsetHeight254}255}256257},258259/**260* Visually emphasize specific lines within a code block.261* This only works on blocks with line numbering turned on.262*263* @param {HTMLElement} block a <code> block264* @param {String} [linesToHighlight] The lines that should be265* highlighted in this format:266* "1" = highlights line 1267* "2,5" = highlights lines 2 & 5268* "2,5-7" = highlights lines 2, 5, 6 & 7269*/270highlightLines: function( block, linesToHighlight ) {271272var highlightSteps = Plugin.deserializeHighlightSteps( linesToHighlight || block.getAttribute( 'data-line-numbers' ) );273274if( highlightSteps.length ) {275276highlightSteps[0].forEach( function( highlight ) {277278var elementsToHighlight = [];279280// Highlight a range281if( typeof highlight.end === 'number' ) {282elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child(n+'+highlight.start+'):nth-child(-n+'+highlight.end+')' ) );283}284// Highlight a single line285else if( typeof highlight.start === 'number' ) {286elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child('+highlight.start+')' ) );287}288289if( elementsToHighlight.length ) {290elementsToHighlight.forEach( function( lineElement ) {291lineElement.classList.add( 'highlight-line' );292} );293294block.classList.add( 'has-highlights' );295}296297} );298299}300301},302303/**304* Parses and formats a user-defined string of line305* numbers to highlight.306*307* @example308* Plugin.deserializeHighlightSteps( '1,2|3,5-10' )309* // [310* // [ { start: 1 }, { start: 2 } ],311* // [ { start: 3 }, { start: 5, end: 10 } ]312* // ]313*/314deserializeHighlightSteps: function( highlightSteps ) {315316// Remove whitespace317highlightSteps = highlightSteps.replace( /\s/g, '' );318319// Divide up our line number groups320highlightSteps = highlightSteps.split( Plugin.HIGHLIGHT_STEP_DELIMITER );321322return highlightSteps.map( function( highlights ) {323324return highlights.split( Plugin.HIGHLIGHT_LINE_DELIMITER ).map( function( highlight ) {325326// Parse valid line numbers327if( /^[\d-]+$/.test( highlight ) ) {328329highlight = highlight.split( Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER );330331var lineStart = parseInt( highlight[0], 10 ),332lineEnd = parseInt( highlight[1], 10 );333334if( isNaN( lineEnd ) ) {335return {336start: lineStart337};338}339else {340return {341start: lineStart,342end: lineEnd343};344}345346}347// If no line numbers are provided, no code will be highlighted348else {349350return {};351352}353354} );355356} );357358},359360/**361* Serializes parsed line number data into a string so362* that we can store it in the DOM.363*/364serializeHighlightSteps: function( highlightSteps ) {365366return highlightSteps.map( function( highlights ) {367368return highlights.map( function( highlight ) {369370// Line range371if( typeof highlight.end === 'number' ) {372return highlight.start + Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER + highlight.end;373}374// Single line375else if( typeof highlight.start === 'number' ) {376return highlight.start;377}378// All lines379else {380return '';381}382383} ).join( Plugin.HIGHLIGHT_LINE_DELIMITER );384385} ).join( Plugin.HIGHLIGHT_STEP_DELIMITER );386387}388389}390391// Function to perform a better "data-trim" on code snippets392// Will slice an indentation amount on each line of the snippet (amount based on the line having the lowest indentation length)393function betterTrim(snippetEl) {394// Helper functions395function trimLeft(val) {396// Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill397return val.replace(/^[\s\uFEFF\xA0]+/g, '');398}399function trimLineBreaks(input) {400var lines = input.split('\n');401402// Trim line-breaks from the beginning403for (var i = 0; i < lines.length; i++) {404if (lines[i].trim() === '') {405lines.splice(i--, 1);406} else break;407}408409// Trim line-breaks from the end410for (var i = lines.length-1; i >= 0; i--) {411if (lines[i].trim() === '') {412lines.splice(i, 1);413} else break;414}415416return lines.join('\n');417}418419// Main function for betterTrim()420return (function(snippetEl) {421var content = trimLineBreaks(snippetEl.innerHTML);422var lines = content.split('\n');423// Calculate the minimum amount to remove on each line start of the snippet (can be 0)424var pad = lines.reduce(function(acc, line) {425if (line.length > 0 && trimLeft(line).length > 0 && acc > line.length - trimLeft(line).length) {426return line.length - trimLeft(line).length;427}428return acc;429}, Number.POSITIVE_INFINITY);430// Slice each line with this amount431return lines.map(function(line, index) {432return line.slice(pad);433})434.join('\n');435})(snippetEl);436}437438export default () => Plugin;439440441