plugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import hljs from 'highlight.js'
  2. /* highlightjs-line-numbers.js 2.6.0 | (C) 2018 Yauheni Pakala | MIT License | github.com/wcoder/highlightjs-line-numbers.js */
  3. /* Edited by Hakim for reveal.js; removed async timeout */
  4. !function(n,e){"use strict";function t(){var n=e.createElement("style");n.type="text/css",n.innerHTML=g(".{0}{border-collapse:collapse}.{0} td{padding:0}.{1}:before{content:attr({2})}",[v,L,b]),e.getElementsByTagName("head")[0].appendChild(n)}function r(t){"interactive"===e.readyState||"complete"===e.readyState?i(t):n.addEventListener("DOMContentLoaded",function(){i(t)})}function i(t){try{var r=e.querySelectorAll("code.hljs,code.nohighlight");for(var i in r)r.hasOwnProperty(i)&&l(r[i],t)}catch(o){n.console.error("LineNumbers error: ",o)}}function l(n,e){"object"==typeof n&&f(function(){n.innerHTML=s(n,e)})}function o(n,e){if("string"==typeof n){var t=document.createElement("code");return t.innerHTML=n,s(t,e)}}function s(n,e){e=e||{singleLine:!1};var t=e.singleLine?0:1;return c(n),a(n.innerHTML,t)}function a(n,e){var t=u(n);if(""===t[t.length-1].trim()&&t.pop(),t.length>e){for(var r="",i=0,l=t.length;i<l;i++)r+=g('<tr><td class="{0}"><div class="{1} {2}" {3}="{5}"></div></td><td class="{4}"><div class="{1}">{6}</div></td></tr>',[j,m,L,b,p,i+1,t[i].length>0?t[i]:" "]);return g('<table class="{0}">{1}</table>',[v,r])}return n}function c(n){var e=n.childNodes;for(var t in e)if(e.hasOwnProperty(t)){var r=e[t];h(r.textContent)>0&&(r.childNodes.length>0?c(r):d(r.parentNode))}}function d(n){var e=n.className;if(/hljs-/.test(e)){for(var t=u(n.innerHTML),r=0,i="";r<t.length;r++){var l=t[r].length>0?t[r]:" ";i+=g('<span class="{0}">{1}</span>\n',[e,l])}n.innerHTML=i.trim()}}function u(n){return 0===n.length?[]:n.split(y)}function h(n){return(n.trim().match(y)||[]).length}function f(e){e()}function g(n,e){return n.replace(/\{(\d+)\}/g,function(n,t){return e[t]?e[t]:n})}var v="hljs-ln",m="hljs-ln-line",p="hljs-ln-code",j="hljs-ln-numbers",L="hljs-ln-n",b="data-line-number",y=/\r\n|\r|\n/g;hljs?(hljs.initLineNumbersOnLoad=r,hljs.lineNumbersBlock=l,hljs.lineNumbersValue=o,t()):n.console.error("highlight.js not detected!")}(window,document);
  5. /*!
  6. * reveal.js plugin that adds syntax highlight support.
  7. */
  8. const Plugin = {
  9. id: 'highlight',
  10. HIGHLIGHT_STEP_DELIMITER: '|',
  11. HIGHLIGHT_LINE_DELIMITER: ',',
  12. HIGHLIGHT_LINE_RANGE_DELIMITER: '-',
  13. /**
  14. * Highlights code blocks withing the given deck.
  15. *
  16. * Note that this can be called multiple times if
  17. * there are multiple presentations on one page.
  18. *
  19. * @param {Reveal} reveal the reveal.js instance
  20. */
  21. init: function( reveal ) {
  22. // Read the plugin config options and provide fallbacks
  23. var config = reveal.getConfig().highlight || {};
  24. config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : true;
  25. config.escapeHTML = typeof config.escapeHTML === 'boolean' ? config.escapeHTML : true;
  26. [].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( function( block ) {
  27. // Trim whitespace if the "data-trim" attribute is present
  28. if( block.hasAttribute( 'data-trim' ) && typeof block.innerHTML.trim === 'function' ) {
  29. block.innerHTML = betterTrim( block );
  30. }
  31. // Escape HTML tags unless the "data-noescape" attrbute is present
  32. if( config.escapeHTML && !block.hasAttribute( 'data-noescape' )) {
  33. block.innerHTML = block.innerHTML.replace( /</g,"&lt;").replace(/>/g, '&gt;' );
  34. }
  35. // Re-highlight when focus is lost (for contenteditable code)
  36. block.addEventListener( 'focusout', function( event ) {
  37. hljs.highlightBlock( event.currentTarget );
  38. }, false );
  39. if( config.highlightOnLoad ) {
  40. Plugin.highlightBlock( block );
  41. }
  42. } );
  43. // If we're printing to PDF, scroll the code highlights of
  44. // all blocks in the deck into view at once
  45. reveal.on( 'pdf-ready', function() {
  46. [].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) {
  47. Plugin.scrollHighlightedLineIntoView( block, {}, true );
  48. } );
  49. } );
  50. },
  51. /**
  52. * Highlights a code block. If the <code> node has the
  53. * 'data-line-numbers' attribute we also generate slide
  54. * numbers.
  55. *
  56. * If the block contains multiple line highlight steps,
  57. * we clone the block and create a fragment for each step.
  58. */
  59. highlightBlock: function( block ) {
  60. hljs.highlightBlock( block );
  61. // Don't generate line numbers for empty code blocks
  62. if( block.innerHTML.trim().length === 0 ) return;
  63. if( block.hasAttribute( 'data-line-numbers' ) ) {
  64. hljs.lineNumbersBlock( block, { singleLine: true } );
  65. var scrollState = { currentBlock: block };
  66. // If there is at least one highlight step, generate
  67. // fragments
  68. var highlightSteps = Plugin.deserializeHighlightSteps( block.getAttribute( 'data-line-numbers' ) );
  69. if( highlightSteps.length > 1 ) {
  70. // If the original code block has a fragment-index,
  71. // each clone should follow in an incremental sequence
  72. var fragmentIndex = parseInt( block.getAttribute( 'data-fragment-index' ), 10 );
  73. if( typeof fragmentIndex !== 'number' || isNaN( fragmentIndex ) ) {
  74. fragmentIndex = null;
  75. }
  76. // Generate fragments for all steps except the original block
  77. highlightSteps.slice(1).forEach( function( highlight ) {
  78. var fragmentBlock = block.cloneNode( true );
  79. fragmentBlock.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlight ] ) );
  80. fragmentBlock.classList.add( 'fragment' );
  81. block.parentNode.appendChild( fragmentBlock );
  82. Plugin.highlightLines( fragmentBlock );
  83. if( typeof fragmentIndex === 'number' ) {
  84. fragmentBlock.setAttribute( 'data-fragment-index', fragmentIndex );
  85. fragmentIndex += 1;
  86. }
  87. else {
  88. fragmentBlock.removeAttribute( 'data-fragment-index' );
  89. }
  90. // Scroll highlights into view as we step through them
  91. fragmentBlock.addEventListener( 'visible', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock, scrollState ) );
  92. fragmentBlock.addEventListener( 'hidden', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock.previousSibling, scrollState ) );
  93. } );
  94. block.removeAttribute( 'data-fragment-index' )
  95. block.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlightSteps[0] ] ) );
  96. }
  97. // Scroll the first highlight into view when the slide
  98. // becomes visible. Note supported in IE11 since it lacks
  99. // support for Element.closest.
  100. var slide = typeof block.closest === 'function' ? block.closest( 'section:not(.stack)' ) : null;
  101. if( slide ) {
  102. var scrollFirstHighlightIntoView = function() {
  103. Plugin.scrollHighlightedLineIntoView( block, scrollState, true );
  104. slide.removeEventListener( 'visible', scrollFirstHighlightIntoView );
  105. }
  106. slide.addEventListener( 'visible', scrollFirstHighlightIntoView );
  107. }
  108. Plugin.highlightLines( block );
  109. }
  110. },
  111. /**
  112. * Animates scrolling to the first highlighted line
  113. * in the given code block.
  114. */
  115. scrollHighlightedLineIntoView: function( block, scrollState, skipAnimation ) {
  116. cancelAnimationFrame( scrollState.animationFrameID );
  117. // Match the scroll position of the currently visible
  118. // code block
  119. if( scrollState.currentBlock ) {
  120. block.scrollTop = scrollState.currentBlock.scrollTop;
  121. }
  122. // Remember the current code block so that we can match
  123. // its scroll position when showing/hiding fragments
  124. scrollState.currentBlock = block;
  125. var highlightBounds = this.getHighlightedLineBounds( block )
  126. var viewportHeight = block.offsetHeight;
  127. // Subtract padding from the viewport height
  128. var blockStyles = getComputedStyle( block );
  129. viewportHeight -= parseInt( blockStyles.paddingTop ) + parseInt( blockStyles.paddingBottom );
  130. // Scroll position which centers all highlights
  131. var startTop = block.scrollTop;
  132. var targetTop = highlightBounds.top + ( Math.min( highlightBounds.bottom - highlightBounds.top, viewportHeight ) - viewportHeight ) / 2;
  133. // Account for offsets in position applied to the
  134. // <table> that holds our lines of code
  135. var lineTable = block.querySelector( '.hljs-ln' );
  136. if( lineTable ) targetTop += lineTable.offsetTop - parseInt( blockStyles.paddingTop );
  137. // Make sure the scroll target is within bounds
  138. targetTop = Math.max( Math.min( targetTop, block.scrollHeight - viewportHeight ), 0 );
  139. if( skipAnimation === true || startTop === targetTop ) {
  140. block.scrollTop = targetTop;
  141. }
  142. else {
  143. // Don't attempt to scroll if there is no overflow
  144. if( block.scrollHeight <= viewportHeight ) return;
  145. var time = 0;
  146. var animate = function() {
  147. time = Math.min( time + 0.02, 1 );
  148. // Update our eased scroll position
  149. block.scrollTop = startTop + ( targetTop - startTop ) * Plugin.easeInOutQuart( time );
  150. // Keep animating unless we've reached the end
  151. if( time < 1 ) {
  152. scrollState.animationFrameID = requestAnimationFrame( animate );
  153. }
  154. };
  155. animate();
  156. }
  157. },
  158. /**
  159. * The easing function used when scrolling.
  160. */
  161. easeInOutQuart: function( t ) {
  162. // easeInOutQuart
  163. return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t;
  164. },
  165. getHighlightedLineBounds: function( block ) {
  166. var highlightedLines = block.querySelectorAll( '.highlight-line' );
  167. if( highlightedLines.length === 0 ) {
  168. return { top: 0, bottom: 0 };
  169. }
  170. else {
  171. var firstHighlight = highlightedLines[0];
  172. var lastHighlight = highlightedLines[ highlightedLines.length -1 ];
  173. return {
  174. top: firstHighlight.offsetTop,
  175. bottom: lastHighlight.offsetTop + lastHighlight.offsetHeight
  176. }
  177. }
  178. },
  179. /**
  180. * Visually emphasize specific lines within a code block.
  181. * This only works on blocks with line numbering turned on.
  182. *
  183. * @param {HTMLElement} block a <code> block
  184. * @param {String} [linesToHighlight] The lines that should be
  185. * highlighted in this format:
  186. * "1" = highlights line 1
  187. * "2,5" = highlights lines 2 & 5
  188. * "2,5-7" = highlights lines 2, 5, 6 & 7
  189. */
  190. highlightLines: function( block, linesToHighlight ) {
  191. var highlightSteps = Plugin.deserializeHighlightSteps( linesToHighlight || block.getAttribute( 'data-line-numbers' ) );
  192. if( highlightSteps.length ) {
  193. highlightSteps[0].forEach( function( highlight ) {
  194. var elementsToHighlight = [];
  195. // Highlight a range
  196. if( typeof highlight.end === 'number' ) {
  197. elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child(n+'+highlight.start+'):nth-child(-n+'+highlight.end+')' ) );
  198. }
  199. // Highlight a single line
  200. else if( typeof highlight.start === 'number' ) {
  201. elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child('+highlight.start+')' ) );
  202. }
  203. if( elementsToHighlight.length ) {
  204. elementsToHighlight.forEach( function( lineElement ) {
  205. lineElement.classList.add( 'highlight-line' );
  206. } );
  207. block.classList.add( 'has-highlights' );
  208. }
  209. } );
  210. }
  211. },
  212. /**
  213. * Parses and formats a user-defined string of line
  214. * numbers to highlight.
  215. *
  216. * @example
  217. * Plugin.deserializeHighlightSteps( '1,2|3,5-10' )
  218. * // [
  219. * // [ { start: 1 }, { start: 2 } ],
  220. * // [ { start: 3 }, { start: 5, end: 10 } ]
  221. * // ]
  222. */
  223. deserializeHighlightSteps: function( highlightSteps ) {
  224. // Remove whitespace
  225. highlightSteps = highlightSteps.replace( /\s/g, '' );
  226. // Divide up our line number groups
  227. highlightSteps = highlightSteps.split( Plugin.HIGHLIGHT_STEP_DELIMITER );
  228. return highlightSteps.map( function( highlights ) {
  229. return highlights.split( Plugin.HIGHLIGHT_LINE_DELIMITER ).map( function( highlight ) {
  230. // Parse valid line numbers
  231. if( /^[\d-]+$/.test( highlight ) ) {
  232. highlight = highlight.split( Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER );
  233. var lineStart = parseInt( highlight[0], 10 ),
  234. lineEnd = parseInt( highlight[1], 10 );
  235. if( isNaN( lineEnd ) ) {
  236. return {
  237. start: lineStart
  238. };
  239. }
  240. else {
  241. return {
  242. start: lineStart,
  243. end: lineEnd
  244. };
  245. }
  246. }
  247. // If no line numbers are provided, no code will be highlighted
  248. else {
  249. return {};
  250. }
  251. } );
  252. } );
  253. },
  254. /**
  255. * Serializes parsed line number data into a string so
  256. * that we can store it in the DOM.
  257. */
  258. serializeHighlightSteps: function( highlightSteps ) {
  259. return highlightSteps.map( function( highlights ) {
  260. return highlights.map( function( highlight ) {
  261. // Line range
  262. if( typeof highlight.end === 'number' ) {
  263. return highlight.start + Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER + highlight.end;
  264. }
  265. // Single line
  266. else if( typeof highlight.start === 'number' ) {
  267. return highlight.start;
  268. }
  269. // All lines
  270. else {
  271. return '';
  272. }
  273. } ).join( Plugin.HIGHLIGHT_LINE_DELIMITER );
  274. } ).join( Plugin.HIGHLIGHT_STEP_DELIMITER );
  275. }
  276. }
  277. // Function to perform a better "data-trim" on code snippets
  278. // Will slice an indentation amount on each line of the snippet (amount based on the line having the lowest indentation length)
  279. function betterTrim(snippetEl) {
  280. // Helper functions
  281. function trimLeft(val) {
  282. // Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
  283. return val.replace(/^[\s\uFEFF\xA0]+/g, '');
  284. }
  285. function trimLineBreaks(input) {
  286. var lines = input.split('\n');
  287. // Trim line-breaks from the beginning
  288. for (var i = 0; i < lines.length; i++) {
  289. if (lines[i].trim() === '') {
  290. lines.splice(i--, 1);
  291. } else break;
  292. }
  293. // Trim line-breaks from the end
  294. for (var i = lines.length-1; i >= 0; i--) {
  295. if (lines[i].trim() === '') {
  296. lines.splice(i, 1);
  297. } else break;
  298. }
  299. return lines.join('\n');
  300. }
  301. // Main function for betterTrim()
  302. return (function(snippetEl) {
  303. var content = trimLineBreaks(snippetEl.innerHTML);
  304. var lines = content.split('\n');
  305. // Calculate the minimum amount to remove on each line start of the snippet (can be 0)
  306. var pad = lines.reduce(function(acc, line) {
  307. if (line.length > 0 && trimLeft(line).length > 0 && acc > line.length - trimLeft(line).length) {
  308. return line.length - trimLeft(line).length;
  309. }
  310. return acc;
  311. }, Number.POSITIVE_INFINITY);
  312. // Slice each line with this amount
  313. return lines.map(function(line, index) {
  314. return line.slice(pad);
  315. })
  316. .join('\n');
  317. })(snippetEl);
  318. }
  319. export default () => Plugin;