plugin.js 15 KB

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