-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
repl.js
771 lines (658 loc) · 21 KB
/
repl.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
(function(babel, $, _, ace, LZString, window) {
'use strict';
var UPDATE_DELAY = 500;
var presets = [
'env',
'es2015',
'es2015-loose',
'es2016',
'es2017',
'react',
'stage-0',
'stage-1',
'stage-2',
'stage-3'
];
var targets = [
// {name: "Chrome", min: 4, default: 58},
// {name: "Opera", min: 10, default: 44},
// {name: "Edge", min: 12, default: 15},
// {name: "Firefox", min: 2, default: 53},
// {name: "Safari", min: 3, default: 10},
// {name: "IE", min: 6, default: 11},
// {name: "iOS", min: 3, default: 10},
{name: "Electron", min: 0.3, default: 1.5, step: 0.1},
{name: "Node", label: "Node.js", min: '0.10', default: 7.4, step: 0.1}
];
/* Register standalone version of env preset. */
Babel.registerPreset('env', babelPresetEnv.default);
/* Throw meaningful errors for getters of commonjs. */
var enableCommonJSError = true;
["module", "exports", "require"].forEach(function(commonVar){
Object.defineProperty(window, commonVar, {
configurable: true,
get: function () {
if (enableCommonJSError) {
throw new Error(commonVar + " is not supported in the browser, you need a commonjs environment such as node.js/io.js, browserify/webpack etc");
}
}
});
});
/*
* Utils for working with the browser's URI (e.g. the query params)
*/
function UriUtils () {}
UriUtils.encode = function (value) {
return window.encodeURIComponent(value);
};
UriUtils.decode = function (value) {
try {
return window.decodeURIComponent('' + value);
} catch (err) {
return value;
}
};
UriUtils.parseQuery = function () {
var query = window.location.hash.replace(/^\#\?/, '');
if (!query) {
return null;
}
return query.split('&').map(function(param) {
var splitPoint = param.indexOf('=');
return {
key : param.substring(0, splitPoint),
value : param.substring(splitPoint + 1)
};
}).reduce(function(params, param){
if (param.key && param.value) {
if (param.key.slice(-3) === '_lz') {
params[param.key.slice(0, -3)] = UriUtils.decompress(param.value);
} else {
params[param.key] = UriUtils.decode(param.value);
}
}
return params;
}, {});
};
UriUtils.compress = function(string) {
return LZString.compressToBase64(string)
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
};
UriUtils.decompress = function(string) {
var safe = string
.replace(/\-/g, '+') // Convert '-' to '+'
.replace(/\_/g, '/'); // Convert '_' to '/'
return LZString.decompressFromBase64(safe);
};
// `code` can get very long. A basic, fast LZW compression to base64
// saves significant bytes, especially considering the explosion in size
// when url-encoding common code characters (like ' ' to '%20')
var compressable = ['code'];
UriUtils.updateQuery = function (object) {
var query = Object.keys(object)
.filter(function(key) {
// Prevents compressed keys from entering twice
return key.slice(-3) !== '_lz';
})
.map(function(key){
if (compressable.indexOf(key) !== -1) {
key += '_lz';
return key + '=' + UriUtils.compress(object.code);
}
return key + '=' + UriUtils.encode(object[key]);
}).join('&');
window.location.hash = '?' + query;
};
/*
* Long term storage for persistence of state/etc
*/
function StorageService () {
try {
this.store = window.localStorage;
} catch (e) {
console.warn('Could not access localStorage. Disabling state persistence.');
this.store = null;
}
}
StorageService.prototype.get = function (key) {
try {
return JSON.parse(this.store.getItem(key));
} catch(e) {}
};
StorageService.prototype.set = function (key, value) {
try {
this.store.setItem(key, JSON.stringify(value));
} catch(e) {}
};
/*
* Decorating the ACE editor
*/
function Editor(selector) {
this.$el = $(selector);
this.editor = ace.edit(this.$el[0]);
this.session = this.editor.getSession();
this.document = this.session.getDocument();
this.editor.setTheme('ace/theme/tomorrow');
this.editor.setShowPrintMargin(false);
this.editor.commands.removeCommands(['gotoline', 'find']);
this.$el.css({
fontFamily: '"Operator Mono", "Fira Code", "Ubuntu Mono", "Droid Sans Mono", "Liberation Mono", "Source Code Pro", Menlo, Monaco, Consolas, "Courier New", monospace',
lineHeight: 'inherit'
});
this.session.setMode('ace/mode/javascript');
this.session.setUseSoftTabs(true);
this.session.setTabSize(2);
this.session.setUseWorker(false);
this.editor.setOption('scrollPastEnd', 0.33);
}
/*
* Options exposed for the REPL that will influence Babel's transpiling
*/
function $checkboxValue($element) {
return {
get: function () {
return $element.is(":checked");
},
set: function (value) {
var setting = value !== 'false' && value !== false;
$element.prop('checked', setting);
},
enumerable: true,
configurable: false
};
}
function $inputValue($element) {
return {
get: function () {
return $element.val().trim();
},
set: function (value) {
var setting = value !== 'undefined' && value !== 'false' && value;
$element.val(setting);
},
enumerable: true,
configurable: false
};
}
/**
* By default, Bootstrap closes dropdown menus whenever an item in them is
* clicked. This function overrides that behaviour for the presets dropdown,
* and ensures the checkbox is selected correctly.
*/
function handlePresetClick($input, evt) {
evt.preventDefault();
evt.stopPropagation();
// Needs to run in a timeout to properly handle clicks directly on the
// checkbox.
setTimeout(function() {
$input.checked = !$input.checked;
onPresetChange();
}, 0);
}
function handleTargetClick($input, evt) {
evt.preventDefault();
evt.stopPropagation();
// Needs to run in a timeout to properly handle clicks directly on the
// checkbox.
setTimeout(function() {
$input.checked = !$input.checked;
onTargetChange();
}, 0);
}
function prevent(evt) {
evt.preventDefault();
evt.stopPropagation();
}
function envItemToString(item) {
return item.name + ' ' + JSON.stringify(item.targets);
}
function onEnvBuild(node, opts, envResult) {
var buffer = '';
buffer += 'Using targets:\n'
buffer += JSON.stringify(envResult.targets, null, 2);
buffer += '\n\n';
buffer += 'Using plugins:\n'
buffer += envResult.transformationsWithTargets
.map(envItemToString)
.join('\n');
if (opts.useBuiltIns) {
buffer += '\n\n';
buffer += 'Using polyfills:\n';
buffer += envResult.polyfillsWithTargets
.map(envItemToString)
.join('\n');
}
buffer += '\n\n';
node.text(buffer);
}
function getEnvOptions(options) {
var origTargets = options.targets,
browsers = options.browsers,
builtIns = !options.evaluate && options.builtIns;
var arrayOfTargets = origTargets.split(',').filter(Boolean);
var targets = arrayOfTargets.reduce(function(objectOfTargets, target){
target = target.split('-');
var name = target[0].toLowerCase();
var version = parseFloat(target[1]);
objectOfTargets[name] = version;
return objectOfTargets;
}, {});
if (browsers) {
targets.browsers = browsers;
}
return {
useBuiltIns: builtIns,
targets: targets
};
};
/**
* Options for selecting presets to use.
*/
function getPresetOptions() {
// Create the checkboxes for all available presets
var $presetContainer = document.getElementById('babel-repl-preset-dropdown');
var $presets = [];
presets.forEach(function(presetName) {
var $input = document.createElement('input');
$input.type = 'checkbox';
$input.name = 'preset';
$input.value = presetName;
$input.id = 'option-' + presetName;
// This should really be a <label>, but it *needs* to be an <a> to get the
// right styling. Thanks Bootstrap.
var $label = document.createElement('a');
$label.href = '#';
$label.className = 'small';
$label.tabIndex = -1;
$label.addEventListener(
'click',
handlePresetClick.bind(null, $input),
false
);
$label.appendChild($input);
$label.appendChild(document.createTextNode(' ' + presetName));
var $li = document.createElement('li');
$li.appendChild($label);
$presetContainer.appendChild($li);
$presets.push($input);
});
return {
get: function() {
return $presets
.filter(function($preset) { return $preset.checked; })
.map(function($preset) { return $preset.value; })
.join(',');
},
set: function(value) {
value = value.split(',');
$presets.forEach(function($preset) {
$preset.checked = value.indexOf($preset.value) > -1;
});
},
enumerable: true,
configurable: true,
};
}
function getTargetOptions() {
// Create version + checkbox for all available targets
var $targetsListCointainer = document.querySelector('#babel-repl-targets-dropdown .dropdown-menu-list');
var $targets = [];
targets.forEach(function(target) {
var targetName = target.name,
targetLabel = target.label || targetName,
defaultVersion = target.default,
minVersion = target.min,
step = target.step || 1;
var $checkbox = document.createElement('input');
$checkbox.type = 'checkbox';
$checkbox.name = 'target';
$checkbox.value = targetName;
$checkbox.id = 'option-' + targetName;
var $input = document.createElement('input');
$input.type = 'number';
$input.min = minVersion;
$input.value = defaultVersion;
$input.step = step;
$input.name = 'version';
$input.id = 'option-target-' + targetName.toLowerCase();
var $label = document.createElement('a');
$label.href = '#';
$label.className = 'small';
$label.tabIndex = -1;
var $span = document.createElement('span');
$span.innerHTML = targetLabel;
$label.appendChild($span);
$label.addEventListener(
'click',
handleTargetClick.bind(null, $checkbox),
false
);
$input.addEventListener(
'click',
prevent,
false
);
$input.addEventListener(
'change',
_.debounce(onTargetChange, 500),
false
);
$label.appendChild($checkbox);
$label.appendChild($input);
var $li = document.createElement('li');
$li.appendChild($label);
$targetsListCointainer.appendChild($li);
$targets.push({$checkbox: $checkbox, $input: $input});
});
return {
get: function() {
return $targets
.filter(function(target) { return target.$checkbox.checked && target.$input.value; })
.map(function(target) { return target.$checkbox.value + '-' + target.$input.value; })
.join(',');
},
set: function(valueStr) {
var values = valueStr.split(',');
values.forEach(function(value){
value = value.split('-');
$targets.forEach(function(target) {
var name = value[0],
version = value[1];
target.$checkbox.checked = name && name.indexOf(target.$checkbox.value) > -1;
target.$input.value = version && name.indexOf(target.$checkbox.value) > -1 ? version : target.$input.value;
});
})
},
enumerable: true,
configurable: true,
};
}
var isBabiliLoading = false;
/**
* Checks if Babili has been loaded. If not, kicks off a load (if it hasn't
* already started) and returns false. Returns true if Babili is ready to use.
*/
function hasBabiliLoaded() {
if (window.Babili) {
return true;
}
if (isBabiliLoading) {
return false;
}
// Babili-standalone is exported as a UMD script, and thus hits the CommonJS
// error ("is not supported in the browser..."), temporarily disable it
// while loading.
enableCommonJSError = false;
var script = document.createElement('script');
script.async = true;
script.src = 'https://unpkg.com/babili-standalone@0/babili.min.js';
script.onload = function() {
enableCommonJSError = true;
onSourceChange();
};
document.head.appendChild(script);
isBabiliLoading = true;
return false;
}
/*
* Babel options for transpilation as used by the REPL
*/
function Options () {
var $evaluate = $('#option-evaluate');
var $lineWrap = $('#option-lineWrap');
var $babili = $('#option-babili');
var $browsers = $('#option-browsers');
var $builtIns = $('#option-builtIns');
var $debug = $('#option-debug');
var options = {};
Object.defineProperties(options, {
babili: $checkboxValue($babili),
evaluate: $checkboxValue($evaluate),
lineWrap: $checkboxValue($lineWrap),
presets: getPresetOptions(),
targets: getTargetOptions(),
browsers: $inputValue($browsers),
builtIns: $checkboxValue($builtIns),
debug: $checkboxValue($debug)
});
// Merge in defaults
var defaults = {
babili: false,
evaluate: true,
lineWrap: false,
presets: 'es2015,stage-2,react',
browsers: ''
};
_.assign(options, defaults);
return options;
}
/*
* Babel Web REPL
*/
function REPL () {
this.storage = new StorageService();
var state = this.storage.get('replState') || {};
_.assign(state, UriUtils.parseQuery());
this.options = _.assign(new Options(), state);
this.input = new Editor('.babel-repl-input .ace_editor').editor;
this.input.setValue(UriUtils.decode(state.code || ''));
this.output = new Editor('.babel-repl-output .ace_editor').editor;
this.output.setReadOnly(true);
this.output.setHighlightActiveLine(false);
this.output.setHighlightGutterLine(false);
this.$errorReporter = $('.babel-repl-errors');
this.$consoleDebug = $('.babel-repl-console-debug');
this.$consoleReporter = $('.babel-repl-console-output');
this.$toolBar = $('.babel-repl-toolbar');
this.$textareaWrapper = $('.dropdown-menu-container');
this.$envBar = $('#option-browsers');
document.getElementById('babel-repl-version').innerHTML = babel.version;
}
REPL.prototype.clearOutput = function () {
this.$errorReporter.text('');
this.$consoleDebug.text('');
this.$consoleReporter.text('');
};
REPL.prototype.setOutput = function (output) {
this.output.setValue(output, -1);
};
REPL.prototype.printError = function (message) {
this.$errorReporter.text(message);
};
REPL.prototype.getSource = function () {
return this.input.getValue();
};
REPL.prototype.compile = function () {
var options = this.options;
this.output.session.setUseWrapMode(options.lineWrap);
var transformed;
var code = this.getSource();
this.clearOutput();
if (options.babili && !hasBabiliLoaded()) {
this.setOutput('// Babili is loading, please wait...');
return;
}
var presets = options.presets.split(',');
if (options.babili) {
presets.push('babili');
}
if (presets.includes('env')) {
var $consoleDebug = this.$consoleDebug;
presets = presets.map(function (preset) {
if (preset === 'env') {
var envOptions = getEnvOptions(options);
if (options.debug) {
envOptions.onPresetBuild = onEnvBuild.bind(
null,
$consoleDebug,
envOptions
);
}
return ["env", envOptions];
}
return preset;
})
}
try {
transformed = babel.transform(code, {
presets: presets.filter(Boolean),
filename: 'repl',
babelrc: false,
});
} catch (err) {
this.printError(err.message);
throw err;
}
this.setOutput(transformed.code);
if (options.evaluate) {
this.evaluate(transformed.code);
}
};
var capturingConsole;
REPL.prototype.evaluate = function(code) {
capturingConsole = Object.create(console);
var $consoleReporter = this.$consoleReporter;
var buffer = [];
var error;
var done = false;
function flush() {
$consoleReporter.text(buffer.join('\n'));
}
function write(data) {
buffer.push(data);
if (done) flush();
}
function capture() {
if (this !== capturingConsole) { return; }
var logs = _.map(arguments, function(log) {
return window.prettyFormat(log);
});
write(logs.join(' '));
}
capturingConsole.clear = function() {
buffer = [];
flush();
console.clear();
};
['error', 'log', 'info', 'debug'].forEach(function(key) {
capturingConsole[key] = function() {
Function.prototype.apply.call(console[key], console, arguments);
capture.apply(this, arguments);
};
});
try {
new Function('console', code)(capturingConsole);
} catch (err) {
error = err;
buffer.push(err.message);
}
done = true;
flush();
};
REPL.prototype.persistState = function (state) {
UriUtils.updateQuery(state);
this.storage.set('replState', state);
};
/*
* Initialize the REPL
*/
var repl = new REPL();
function onPresetChange() {
// Update the list of presets that are displayed on the dropdown list anchor
var $envTargets = $('.babel-repl-targets-container');
var $envBuiltIns = $('#option-builtIns-wrapper');
var $envDebug = $('#option-debug-wrapper');
var presetList = repl.options.presets.replace(/,/g, ', ');
// Hide targets anchor unless env preset is selected.
var envIncluded = repl.options.presets.includes('env');
$envTargets.toggleClass('hidden', !envIncluded);
$envBuiltIns.toggleClass('hidden', !envIncluded);
$envDebug.toggleClass('hidden', !envIncluded);
document.getElementById('babel-repl-selected-presets').innerHTML = presetList;
onSourceChange();
}
function onTargetChange() {
// Update the list of targets that are displayed on the dropdown list anchor
var browsersList = repl.options.browsers;
var targetList = repl.options.targets.replace(/,/g, ', ');
var targetsEl = document.getElementById('babel-repl-selected-targets');
if (browsersList.length && targetList.length) {
browsersList += ', ';
}
targetsEl.innerHTML = browsersList + targetList;
onSourceChange();
}
function onToolbarChange() {
var $envBuiltIns = $('#option-builtIns-wrapper');
var $envBuiltInsInput = $envBuiltIns.find('input[type=checkbox]');
var evaluate = repl.options.evaluate;
var title = evaluate ? 'Disabled in evaluate mode' : '';
$envBuiltIns.attr('title', title);
if (evaluate) {
$envBuiltInsInput.prop('checked', false);
}
$envBuiltInsInput.attr('disabled', evaluate);
onSourceChange();
}
function onSourceChange() {
var error;
try {
repl.compile();
} catch(err) {
error = err;
}
var code = repl.getSource();
var state = _.assign(repl.options, {
code: code
});
repl.persistState(state);
if (error) throw error;
}
repl.input.on('change', _.debounce(onSourceChange, UPDATE_DELAY));
repl.$envBar.on('keyup', _.debounce(onTargetChange, UPDATE_DELAY));
repl.$toolBar.on('change', onToolbarChange);
repl.$textareaWrapper.on('click', function(e){e.stopPropagation();})
/*
* Make REPL editors resizable by width
* Returns a function to disable feature
*/
function initResizable(resizeSelector) {
var $container = $('.babel-repl');
var $leftPanel = $('.babel-repl-left-panel');
var $rightPanel = $('.babel-repl-right-panel');
var activeClass = 'babel-repl-resize-active';
var offsetX;
function onResize(e) {
var curPos = e.pageX - offsetX;
var leftWidth = curPos / $container.width() * 100;
var rightWidth = 100 - leftWidth;
if (leftWidth < 10 || leftWidth > 90) {
return;
}
$leftPanel.outerWidth(leftWidth + '%');
$rightPanel.outerWidth(rightWidth + '%');
}
function onResizeStart(e) {
e.preventDefault();
offsetX = e.offsetX;
$(document).on('mousemove', onResize);
$(document).on('mouseup', onResizeStop);
$container.addClass(activeClass);
}
function onResizeStop(e) {
$(document).off('mousemove', onResize);
$(document).off('mouseup', onResizeStop);
$container.removeClass(activeClass);
}
$(resizeSelector).on('mousedown', onResizeStart);
return function() {
$(resizeSelector).off('mousedown', onResizeStart);
};
}
initResizable('.babel-repl-resize');
onPresetChange();
onTargetChange();
onToolbarChange();
}(Babel, $, _, ace, LZString, window));