Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

420 Zeilen
14KB

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