plugin.js 14 KB

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