You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

440 lines
16 KiB

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