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