plugin.js 15 KB

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