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