forked from romannurik/SlidesCodeHighlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
546 lines (458 loc) · 14.7 KB
/
index.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {DEFAULT_THEMES, THEME_PROPERTIES, setTheme} from './themes.js';
const WARN_LINES = 15;
const WARN_LINE_LENGTH = 80;
const $editor = $('#editor');
const $output = $('#output');
let config = {
code: localStorage.highlighterCode || '',
theme: localStorage.highlighterTheme || 'light',
lang: localStorage.highlighterLang || '(auto)',
font: localStorage.highlighterFont || 'Roboto Mono',
tabSize: Number(localStorage.highlighterTabSize || '4'),
typeSize: Number(localStorage.highlighterTypeSize || '40'),
selectionTreatment: localStorage.highlighterSelectionTreatment || '--',
customTheme: JSON.parse(localStorage.customTheme || JSON.stringify(DEFAULT_THEMES['light'])),
};
if (config.lang == '--') {
config.lang = '(auto)';
}
let editor;
setupToolbar();
setupEditor();
setupOutputArea();
updateOutputArea();
setupCustomThemeEditor();
loadFont();
installServiceWorker();
function setupEditor() {
let updateCode_ = code => {
localStorage.highlighterCode = config.code = code;
updateOutputArea();
};
if (navigator.userAgent.match(/iP(hone|od|ad)|Android/)) {
// Ace editor is pretty busted on mobile, just use a <textarea>
let $textArea = $('<textarea>')
.attr('autocapitalize', 'off')
.attr('spellcheck', 'false')
.val(config.code)
.on('input', () => updateCode_($textArea.val()))
.appendTo($editor);
return;
}
editor = ace.edit($editor.get(0));
editor.$blockScrolling = Infinity;
editor.setValue(config.code, -1);
editor.setTheme('ace/theme/chrome');
editor.getSession().setMode('ace/mode/text');
editor.setOptions({
fontFamily: 'Roboto Mono',
fontSize: '11pt',
});
editor.on('change', () => updateCode_(editor.getValue()));
editor.getSelection().on('changeCursor', () => updateOutputArea());
editor.getSelection().on('changeSelection', () => updateOutputArea());
updateEditorParams();
}
function updateEditorParams() {
if (!editor) {
return;
}
editor.setOptions({
fontFamily: config.font,
fontSize: '11pt',
});
editor.getSession().setTabSize(config.tabSize);
}
function setupOutputArea() {
// select all on click
$output.click(() => {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents($output.find('pre').get(0));
selection.removeAllRanges();
selection.addRange(range);
});
// re-layout on window resize
$(window).on('resize', () => updateOutputArea());
document.fonts.ready.then(() => updateOutputArea());
}
function setupToolbar() {
$('#theme')
.val(config.theme)
.on('input', ev => {
localStorage.highlighterTheme = config.theme = $(ev.target).val();
updateOutputArea();
});
$('#lang')
.val(config.lang)
.on('input', ev => {
localStorage.highlighterLang = config.lang = $(ev.target).val();
updateOutputArea();
});
let $dl = $('#lang-datalist');
let langs = Object.keys(Prism.languages)
.filter(s => typeof Prism.languages[s] == 'object');
for (let lang of langs) {
$dl.append($('<option>').attr('value', lang));
}
$('#tab-size')
.val(config.tabSize)
.on('input', ev => {
localStorage.highlighterTabSize = $(ev.target).val();
config.tabSize = Number(localStorage.highlighterTabSize);
updateEditorParams();
updateOutputArea();
});
$('#font')
.val(config.font)
.on('input', ev => {
localStorage.highlighterFont = config.font = $(ev.target).val();
loadFont();
});
$('#selection-treatment')
.val(config.selectionTreatment)
.on('input', ev => {
localStorage.highlighterSelectionTreatment = config.selectionTreatment = $(ev.target).val();
updateOutputArea();
});
let $typeSize = $('#type-size');
let setTypeSize_ = size => {
if ($typeSize.val() != String(size)) {
$typeSize.val(size);
}
config.typeSize = size;
localStorage.highlighterTypeSize = String(config.typeSize);
updateOutputArea();
};
$typeSize
.val(config.typeSize)
.on('input', () => {
let val = parseInt($typeSize.val(), 10);
if (!isNaN(val) && val > 4) {
setTypeSize_(val);
}
})
.on('keydown', ev => {
if (!ev.shiftKey) {
if (ev.keyCode == 38 || ev.keyCode == 40) {
setTypeSize_(parseInt($typeSize.val(), 10) + (ev.keyCode == 38 ? 1 : -1));
ev.preventDefault();
}
}
})
.on('blur', ev => setTypeSize_(config.typeSize));
}
function loadFont() {
WebFont.load({
google: {
families: [`${config.font}:400,700`]
},
active: () => {
updateEditorParams();
updateOutputArea();
}
});
}
function updateOutputArea() {
let $messages = $('.edit-area .messages');
$messages.empty();
$output.empty();
// set theme
if (config.theme == 'custom') {
$('.custom-theme-area').css('display', 'flex');
setTheme(config.customTheme, config.typeSize);
} else {
$('.custom-theme-area').css('display', 'none');
setTheme(DEFAULT_THEMES[config.theme], config.typeSize);
}
// build pre element
let $pre = $('<pre>')
.addClass('prettyprint')
.css({
'font-family': config.font,
'font-size': `${config.typeSize}px`,
'background': 'transparent',
})
.appendTo($output);
let lang = config.lang;
if (lang == '(auto)') {
lang = /\s*</.test(config.code) ? 'markup' : 'js';
}
if (!Prism.languages[lang]) {
$('#lang').addClass('is-invalid');
return;
}
$('#lang').removeClass('is-invalid');
let html = Prism.highlight(
cleanupCode(config.code).code,
Prism.languages[lang], lang);
$pre.html(html);
highlightSelection();
// add line numbers
if (false) {
addLineNumbers();
}
// find width by measuring the longest line
let preWidth = Math.max(1, measureNaturalPreWidth($pre));
let preHeight = Math.max(1, $pre.outerHeight());
// center and scale the pre in the output area
let scale = Math.min(1, Math.min(
$output.width() / preWidth,
$output.height() / preHeight));
$pre.css({
width: preWidth,
transform: `translate(-50%, -50%) scale(${scale})`
});
// show messages
let messages = [];
if ((config.code.match(/\n/g) || []).length >= WARN_LINES) {
messages.push({
type: 'warning',
message:
`More than ${WARN_LINES} lines of code will be hard to read in a
slide presentation.`
});
}
let lines = config.code.split('\n') || [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].length > WARN_LINE_LENGTH) {
messages.push({
type: 'warning',
message:
`Line ${(i + 1)} has more than ${WARN_LINE_LENGTH} characters!`
});
break;
}
}
messages.forEach(({type, message}) =>
$('<div>')
.addClass(`message message-${type}`)
.text(message)
.appendTo($messages));
}
const htmlEscape = s => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
function highlightSelection() {
if (!editor) {
return;
}
$output.removeClass('has-highlights');
$output.removeAttr('data-seltreat');
if (config.selectionTreatment == '--') {
return;
}
$output.attr('data-seltreat', config.selectionTreatment);
let rawCode = config.code;
let {code, commonIndent, leadingEmptyLines} = cleanupCode(rawCode);
let preRoot = $output.find('pre').get(0);
let rangeToCharPos = ({row, column}) => code.split(/\r?\n/)
.slice(0, row - leadingEmptyLines)
.reduce((a, r) => a + r.length + 1, 0)
+ Math.max(0,
((rawCode.split(/\n/)[row] || '').substring(0, column).match(/\t/g) || []).length
* (config.tabSize - 1)
+ column - commonIndent);
let hasHighlights = false;
for (let range of editor.getSelection().getAllRanges()) {
let targetStartPos = rangeToCharPos(range.start);
let targetEndPos = rangeToCharPos(range.end);
if (targetEndPos == targetStartPos) {
continue;
}
hasHighlights = true;
let childStartPos = 0;
let traverse_ = (parent, emptyClass = '') => {
for (let child of Array.from(parent.childNodes)) {
if (child.childNodes.length >= 2 ||
(child.childNodes.length >= 1
&& child.childNodes[0].nodeType != 3 /* TEXT */)) {
// this is a complex element, traverse it instead of treating it
// as a leaf nodeS
traverse_(child, child.className);
continue;
}
let childContent = child.textContent;
let childEndPos = childStartPos + childContent.length;
if (targetStartPos < childEndPos && targetEndPos >= childStartPos) {
// some overlap
let startInChild = Math.max(0, targetStartPos - childStartPos);
let endInChild = Math.min(childContent.length, childContent.length - (childEndPos - targetEndPos));
let makeSub = (tag, start, end) => {
if (start == end) {
return null;
}
let f = document.createElement(tag);
if (child.className) {
f.className = child.className;
} else if (emptyClass) {
f.className = emptyClass;
}
f.innerHTML = htmlEscape(childContent.substring(start, end));
return f;
};
child.replaceWith.apply(child, [
makeSub('span', 0, startInChild),
makeSub('mark', startInChild, endInChild),
makeSub('span', endInChild, childContent.length),
].filter(s => !!s));
}
childStartPos = childEndPos;
}
};
traverse_(preRoot);
}
$output.toggleClass('has-highlights', hasHighlights);
}
function addLineNumbers() {
let $pre = $output.find('pre');
let htmlLines = $pre.html().split(/\n/);
$pre.html(htmlLines
.map((s, ind) => `<span style="color:grey">` +
String(ind + 1).padStart(Math.ceil((htmlLines.length + 1) / 10), ' ') +
`</span> ${s}`)
.join('\n'));
}
function cleanupCode(code) {
let lines = code.split('\n');
// Remove leading and trailing empty lines
let leadingEmptyLines = 0;
for (let line of lines) {
if (line.match(/^\s*$/)) {
++leadingEmptyLines;
} else {
break;
}
}
let trailingEmptyLines = 0;
for (let line of [...lines].reverse()) {
if (line.match(/^\s*$/)) {
++trailingEmptyLines;
} else {
break;
}
}
if (leadingEmptyLines == lines.length) {
trailingEmptyLines = 0;
}
lines = lines.slice(leadingEmptyLines, lines.length - trailingEmptyLines);
// Tabs to 4 spaces
lines = lines.map(line => line.replace(/\t/g, ' '.repeat(config.tabSize)));
// Remove trailing whitespace
lines = lines.map(line => line.replace(/ +$/g, ''));
// Remove common indent
let commonIndent = -1;
for (let line of lines) {
if (!$.trim(line)) {
continue;
}
let indent = line.match(/^\s*/)[0].length;
if (indent < commonIndent || commonIndent == -1) {
commonIndent = indent;
}
}
if (commonIndent > 0) {
lines = lines.map(line => line.substring(commonIndent));
}
code = lines.join('\n');
return {code, commonIndent, leadingEmptyLines, trailingEmptyLines};
}
function measureNaturalPreWidth(pre) {
// compute the natural width of a monospace <pre> by computing
// the length of its longest line
let $pre = $(pre);
let longestLine = $pre.text()
.split('\n')
.reduce((longest, line) => (longest.length > line.length) ? longest : line, '');
let $preClone = $pre
.clone()
.css({
position: 'fixed',
left: -10000,
top: 0,
display: 'inline-block',
width: 'auto',
height: 'auto',
})
.text(longestLine)
.appendTo(document.body);
let naturalWidth = $preClone.width();
$preClone.remove();
return naturalWidth;
}
function setupCustomThemeEditor() {
let sanitize_ = s => s.replace(/^\s*|\s*$/g, '').toUpperCase();
let rebuildCustomThemeProperties = () => {
let $customThemeEditor = $('.custom-theme-editor').empty();
for (let prop of THEME_PROPERTIES) {
let $prop = $('<div>')
.addClass('custom-theme-prop')
.appendTo($customThemeEditor);
let $label = $('<label>')
.appendTo($prop);
let hexColor = String(config.customTheme[prop.id] || '#000000').toUpperCase();
let $textInput, $colorInput;
$colorInput = $('<input>')
.attr('type', 'color')
.val(hexColor)
.on('input', () => {
config.customTheme[prop.id] = sanitize_($colorInput.val());
$textInput.val(config.customTheme[prop.id]);
localStorage.customTheme = JSON.stringify(config.customTheme);
updateOutputArea();
})
.appendTo($label);
$textInput = $('<input>')
.attr('type', 'text')
.val(hexColor)
.on('input', () => {
config.customTheme[prop.id] = sanitize_($textInput.val());
$colorInput.val(config.customTheme[prop.id]);
localStorage.customTheme = JSON.stringify(config.customTheme);
updateOutputArea();
})
.appendTo($label);
$label.append(`<span>${prop.name}</span>`); // text
}
}
rebuildCustomThemeProperties();
$('.custom-theme-import-export').click(() => {
let currentJSON = JSON.stringify(config.customTheme);
let newJSON = window.prompt(
'Copy the below JSON or paste new JSON for your custom theme.', currentJSON);
if (newJSON && newJSON != currentJSON) {
try {
config.customTheme = Object.assign({}, DEFAULT_THEMES['light'], JSON.parse(newJSON) || {});
localStorage.customTheme = JSON.stringify(config.customTheme);
updateOutputArea();
rebuildCustomThemeProperties();
} catch (e) {
alert('Error parsing the JSON: ' + e);
}
}
});
}
function installServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js').then(registration => {
console.log('SW registered: ', registration);
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}
}