Files
freeCodeCamp/client/sandbox.js

92 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-08-27 11:40:06 -07:00
/* global jailed */
var printCallback;
2015-08-27 11:40:06 -07:00
// sends the input to the plugin for evaluation
2015-08-27 11:40:06 -07:00
function submit(code, callback) {
printCallback = callback;
// postpone the evaluation until the plugin is initialized
plugin.whenConnected(function() {
if (requests === 0) {
startLoading();
}
requests++;
plugin.remote.run(code);
});
}
// puts the message on the terminal
var print = function(cls, msg) {
2015-08-27 11:40:06 -07:00
printCallback(cls, msg);
};
// will restart the plugin if it does not respond
var disconnectTimeout = null;
var startLoading = function() {
2015-08-27 11:40:06 -07:00
disconnectTimeout = setTimeout(disconnect, 3000);
};
var endLoading = function() {
2015-08-27 11:40:06 -07:00
clearTimeout(disconnectTimeout);
};
var disconnect = function() {
2015-08-27 11:40:06 -07:00
plugin.disconnect();
};
// interface provided to the plugin
var api = {
2015-08-27 11:40:06 -07:00
output: function(data) {
endLoading();
// print('input', data.input);
if (data.error) {
print('Error', data);
reset();
} else {
print(null, data);
reset();
}
2015-08-27 11:40:06 -07:00
}
};
// obtaining absolute path of this script
var scripts = document.getElementsByTagName('script');
2015-08-27 11:40:06 -07:00
var path = scripts[scripts.length - 1].src
.split('?')[0]
.split('/')
.slice(0, -1)
.join('/') + '/';
var requests;
// (re)initializes the plugin
var reset = function() {
2015-08-27 11:40:06 -07:00
requests = 0;
plugin = new jailed.Plugin(path + 'plugin.js', api);
plugin.whenDisconnected( function() {
// give some time to handle the last responce
setTimeout( function() {
endLoading();
console.log('resetting on fatal plugin error');
2015-08-27 11:40:06 -07:00
if (challengeType === 0) {
codeOutput.setValue(
'Sorry, your code is either too slow, has a fatal error, ' +
'or contains an infinite loop.'
);
}
reset();
}, 10);
});
};
// initialize everything
var plugin = null;
reset();