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
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
In the absence of any formal way to specify interfaces in JavaScript,
here's a skeleton implementation of a playground transport.
function Transport() {
// Set up any transport state (eg, make a websocket connection).
return {
Run: function(body, output, options) {
// Compile and run the program 'body' with 'options'.
// Call the 'output' callback to display program output.
return {
Kill: function() {
// Kill the running program.
}
};
}
};
}
// The output callback is called multiple times, and each time it is
// passed an object of this form.
var write = {
Kind: 'string', // 'start', 'stdout', 'stderr', 'end'
Body: 'string' // content of write or end status message
}
// The first call must be of Kind 'start' with no body.
// Subsequent calls may be of Kind 'stdout' or 'stderr'
// and must have a non-null Body string.
// The final call should be of Kind 'end' with an optional
// Body string, signifying a failure ("killed", for example).
// The output callback must be of this form.
// See PlaygroundOutput (below) for an implementation.
function outputCallback(write) {
}
*/
// HTTPTransport is the default transport.
// enableVet enables running vet if a program was compiled and ran successfully.
// If vet returned any errors, display them before the output of a program.
function HTTPTransport(enableVet) {
'use strict';
function playback(output, data) {
// Backwards compatibility: default values do not affect the output.
var events = data.Events || [];
var errors = data.Errors || '';
var status = data.Status || 0;
var isTest = data.IsTest || false;
var testsFailed = data.TestsFailed || 0;
var timeout;
output({ Kind: 'start' });
function next() {
if (!events || events.length === 0) {
if (isTest) {
if (testsFailed > 0) {
output({
Kind: 'system',
Body:
'\n' +
testsFailed +
' test' +
(testsFailed > 1 ? 's' : '') +
' failed.',
});
} else {
output({ Kind: 'system', Body: '\nAll tests passed.' });
}
} else {
if (status > 0) {
output({ Kind: 'end', Body: 'status ' + status + '.' });
} else {
if (errors !== '') {
// errors are displayed only in the case of timeout.
output({ Kind: 'end', Body: errors + '.' });
} else {
output({ Kind: 'end' });
}
}
}
return;
}
var e = events.shift();
if (e.Delay === 0) {
output({ Kind: e.Kind, Body: e.Message });
next();
return;
}
timeout = setTimeout(function() {
output({ Kind: e.Kind, Body: e.Message });
next();
}, e.Delay / 1000000);
}
next();
return {
Stop: function() {
clearTimeout(timeout);
},
};
}
function error(output, msg) {
output({ Kind: 'start' });
output({ Kind: 'stderr', Body: msg });
output({ Kind: 'end' });
}
function buildFailed(output, msg) {
output({ Kind: 'start' });
output({ Kind: 'stderr', Body: msg });
output({ Kind: 'system', Body: '\nGo build failed.' });
}
var seq = 0;
return {
Run: function(body, output, options) {
seq++;
var cur = seq;
var playing;
$.ajax('/compile', {
type: 'POST',
data: { version: 2, body: body, withVet: enableVet },
dataType: 'json',
success: function(data) {
if (seq != cur) return;
if (!data) return;
if (playing != null) playing.Stop();
if (data.Errors) {
if (data.Errors === 'process took too long') {
// Playback the output that was captured before the timeout.
playing = playback(output, data);
} else {
buildFailed(output, data.Errors);
}
return;
}
if (!data.Events) {
data.Events = [];
}
if (data.VetErrors) {
// Inject errors from the vet as the first events in the output.
data.Events.unshift({
Message: 'Go vet exited.\n\n',
Kind: 'system',
Delay: 0,
});
data.Events.unshift({
Message: data.VetErrors,
Kind: 'stderr',
Delay: 0,
});
}
if (!enableVet || data.VetOK || data.VetErrors) {
playing = playback(output, data);
return;
}
// In case the server support doesn't support
// compile+vet in same request signaled by the
// 'withVet' parameter above, also try the old way.
// TODO: remove this when it falls out of use.
// It is 2019-05-13 now.
$.ajax('/vet', {
data: { body: body },
type: 'POST',
dataType: 'json',
success: function(dataVet) {
if (dataVet.Errors) {
// inject errors from the vet as the first events in the output
data.Events.unshift({
Message: 'Go vet exited.\n\n',
Kind: 'system',
Delay: 0,
});
data.Events.unshift({
Message: dataVet.Errors,
Kind: 'stderr',
Delay: 0,
});
}
playing = playback(output, data);
},
error: function() {
playing = playback(output, data);
},
});
},
error: function() {
error(output, 'Error communicating with remote server.');
},
});
return {
Kill: function() {
if (playing != null) playing.Stop();
output({ Kind: 'end', Body: 'killed' });
},
};
},
};
}
function SocketTransport() {
'use strict';
var id = 0;
var outputs = {};
var started = {};
var websocket;
if (window.location.protocol == 'http:') {
websocket = new WebSocket('ws://' + window.location.host + '/socket');
} else if (window.location.protocol == 'https:') {
websocket = new WebSocket('wss://' + window.location.host + '/socket');
}
websocket.onclose = function() {
console.log('websocket connection closed');
};
websocket.onmessage = function(e) {
var m = JSON.parse(e.data);
var output = outputs[m.Id];
if (output === null) return;
if (!started[m.Id]) {
output({ Kind: 'start' });
started[m.Id] = true;
}
output({ Kind: m.Kind, Body: m.Body });
};
function send(m) {
websocket.send(JSON.stringify(m));
}
return {
Run: function(body, output, options) {
var thisID = id + '';
id++;
outputs[thisID] = output;
send({ Id: thisID, Kind: 'run', Body: body, Options: options });
return {
Kill: function() {
send({ Id: thisID, Kind: 'kill' });
},
};
},
};
}
function PlaygroundOutput(el) {
'use strict';
return function(write) {
if (write.Kind == 'start') {
el.innerHTML = '';
return;
}
var cl = 'system';
if (write.Kind == 'stdout' || write.Kind == 'stderr') cl = write.Kind;
var m = write.Body;
if (write.Kind == 'end') {
m = '\nProgram exited' + (m ? ': ' + m : '.');
}
if (m.indexOf('IMAGE:') === 0) {
// TODO(adg): buffer all writes before creating image
var url = 'data:image/png;base64,' + m.substr(6);
var img = document.createElement('img');
img.src = url;
el.appendChild(img);
return;
}
// ^L clears the screen.
var s = m.split('\x0c');
if (s.length > 1) {
el.innerHTML = '';
m = s.pop();
}
m = m.replace(/&/g, '&');
m = m.replace(/</g, '<');
m = m.replace(/>/g, '>');
var needScroll = el.scrollTop + el.offsetHeight == el.scrollHeight;
var span = document.createElement('span');
span.className = cl;
span.innerHTML = m;
el.appendChild(span);
if (needScroll) el.scrollTop = el.scrollHeight - el.offsetHeight;
};
}
(function() {
function lineHighlight(error) {
var regex = /prog.go:([0-9]+)/g;
var r = regex.exec(error);
while (r) {
$('.lines div')
.eq(r[1] - 1)
.addClass('lineerror');
r = regex.exec(error);
}
}
function highlightOutput(wrappedOutput) {
return function(write) {
if (write.Body) lineHighlight(write.Body);
wrappedOutput(write);
};
}
function lineClear() {
$('.lineerror').removeClass('lineerror');
}
// opts is an object with these keys
// codeEl - code editor element
// outputEl - program output element
// runEl - run button element
// fmtEl - fmt button element (optional)
// fmtImportEl - fmt "imports" checkbox element (optional)
// shareEl - share button element (optional)
// shareURLEl - share URL text input element (optional)
// shareRedirect - base URL to redirect to on share (optional)
// toysEl - toys select element (optional)
// enableHistory - enable using HTML5 history API (optional)
// transport - playground transport to use (default is HTTPTransport)
// enableShortcuts - whether to enable shortcuts (Ctrl+S/Cmd+S to save) (default is false)
// enableVet - enable running vet and displaying its errors
function playground(opts) {
var code = $(opts.codeEl);
var transport = opts['transport'] || new HTTPTransport(opts['enableVet']);
var running;
// autoindent helpers.
function insertTabs(n) {
// find the selection start and end
var start = code[0].selectionStart;
var end = code[0].selectionEnd;
// split the textarea content into two, and insert n tabs
var v = code[0].value;
var u = v.substr(0, start);
for (var i = 0; i < n; i++) {
u += '\t';
}
u += v.substr(end);
// set revised content
code[0].value = u;
// reset caret position after inserted tabs
code[0].selectionStart = start + n;
code[0].selectionEnd = start + n;
}
function autoindent(el) {
var curpos = el.selectionStart;
var tabs = 0;
while (curpos > 0) {
curpos--;
if (el.value[curpos] == '\t') {
tabs++;
} else if (tabs > 0 || el.value[curpos] == '\n') {
break;
}
}
setTimeout(function() {
insertTabs(tabs);
}, 1);
}
// NOTE(cbro): e is a jQuery event, not a DOM event.
function handleSaveShortcut(e) {
if (e.isDefaultPrevented()) return false;
if (!e.metaKey && !e.ctrlKey) return false;
if (e.key != 'S' && e.key != 's') return false;
e.preventDefault();
// Share and save
share(function(url) {
window.location.href = url + '.go?download=true';
});
return true;
}
function keyHandler(e) {
if (opts.enableShortcuts && handleSaveShortcut(e)) return;
if (e.keyCode == 9 && !e.ctrlKey) {
// tab (but not ctrl-tab)
insertTabs(1);
e.preventDefault();
return false;
}
if (e.keyCode == 13) {
// enter
if (e.shiftKey) {
// +shift
run();
e.preventDefault();
return false;
}
if (e.ctrlKey) {
// +control
fmt();
e.preventDefault();
} else {
autoindent(e.target);
}
}
return true;
}
code.unbind('keydown').bind('keydown', keyHandler);
var outdiv = $(opts.outputEl).empty();
var output = $('<pre/>').appendTo(outdiv);
function body() {
return $(opts.codeEl).val();
}
function setBody(text) {
$(opts.codeEl).val(text);
}
function origin(href) {
return ('' + href)
.split('/')
.slice(0, 3)
.join('/');
}
var pushedEmpty = window.location.pathname == '/';
function inputChanged() {
if (pushedEmpty) {
return;
}
pushedEmpty = true;
$(opts.shareURLEl).hide();
window.history.pushState(null, '', '/');
}
function popState(e) {
if (e === null) {
return;
}
if (e && e.state && e.state.code) {
setBody(e.state.code);
}
}
var rewriteHistory = false;
if (
window.history &&
window.history.pushState &&
window.addEventListener &&
opts.enableHistory
) {
rewriteHistory = true;
code[0].addEventListener('input', inputChanged);
window.addEventListener('popstate', popState);
}
function setError(error) {
if (running) running.Kill();
lineClear();
lineHighlight(error);
output
.empty()
.addClass('error')
.text(error);
}
function loading() {
lineClear();
if (running) running.Kill();
output.removeClass('error').text('Waiting for remote server...');
}
function run() {
loading();
running = transport.Run(
body(),
highlightOutput(PlaygroundOutput(output[0]))
);
}
function fmt() {
loading();
var data = { body: body() };
if ($(opts.fmtImportEl).is(':checked')) {
data['imports'] = 'true';
}
$.ajax('/fmt', {
data: data,
type: 'POST',
dataType: 'json',
success: function(data) {
if (data.Error) {
setError(data.Error);
} else {
setBody(data.Body);
setError('');
}
},
});
}
var shareURL; // jQuery element to show the shared URL.
var sharing = false; // true if there is a pending request.
var shareCallbacks = [];
function share(opt_callback) {
if (opt_callback) shareCallbacks.push(opt_callback);
if (sharing) return;
sharing = true;
var sharingData = body();
$.ajax('/share', {
processData: false,
data: sharingData,
type: 'POST',
contentType: 'text/plain; charset=utf-8',
complete: function(xhr) {
sharing = false;
if (xhr.status != 200) {
alert('Server error; try again.');
return;
}
if (opts.shareRedirect) {
window.location = opts.shareRedirect + xhr.responseText;
}
var path = '/p/' + xhr.responseText;
var url = origin(window.location) + path;
for (var i = 0; i < shareCallbacks.length; i++) {
shareCallbacks[i](url);
}
shareCallbacks = [];
if (shareURL) {
shareURL
.show()
.val(url)
.focus()
.select();
if (rewriteHistory) {
var historyData = { code: sharingData };
window.history.pushState(historyData, '', path);
pushedEmpty = false;
}
}
},
});
}
$(opts.runEl).click(run);
$(opts.fmtEl).click(fmt);
if (
opts.shareEl !== null &&
(opts.shareURLEl !== null || opts.shareRedirect !== null)
) {
if (opts.shareURLEl) {
shareURL = $(opts.shareURLEl).hide();
}
$(opts.shareEl).click(function() {
share();
});
}
if (opts.toysEl !== null) {
$(opts.toysEl).bind('change', function() {
var toy = $(this).val();
$.ajax('/doc/play/' + toy, {
processData: false,
type: 'GET',
complete: function(xhr) {
if (xhr.status != 200) {
alert('Server error; try again.');
return;
}
setBody(xhr.responseText);
},
});
});
}
}
window.playground = playground;
})();
|