wide/static/js/playground.js

515 lines
18 KiB
JavaScript
Raw Normal View History

2015-02-13 04:59:51 +03:00
/*
2019-05-17 06:28:50 +03:00
* Copyright (c) 2014-present, b3log.org
2015-02-13 04:59:51 +03:00
*
* 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
*
2018-03-12 07:28:33 +03:00
* https://www.apache.org/licenses/LICENSE-2.0
2015-02-13 04:59:51 +03:00
*
* 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.
*/
2015-12-08 18:48:16 +03:00
/*
* @file playground.js
*
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @author <a href="http://88250.b3log.org">Liang Ding</a>
2019-06-23 09:14:37 +03:00
* @version 1.0.0.3, Jun 23, 2019
2015-12-08 18:48:16 +03:00
*/
2015-02-13 04:59:51 +03:00
var playground = {
autocompleteMutex: false,
2015-02-13 04:59:51 +03:00
editor: undefined,
pid: undefined,
2015-02-14 15:38:33 +03:00
_resize: function () {
2016-10-29 18:30:09 +03:00
playground.editor.setSize("auto", ($("#editorDiv").parent().height() * 0.7) + "px");
2015-02-14 15:38:33 +03:00
},
_initShare: function () {
2015-02-15 08:53:02 +03:00
$("#dialogShare").dialog({
"modal": true,
"title": config.label.share,
2015-02-20 04:42:05 +03:00
"hideFooter": true
2015-02-15 06:09:17 +03:00
});
},
_initWideShare: function () {
2015-02-14 15:38:33 +03:00
$(".share-panel .font-ico").click(function () {
var key = $(this).attr('class').split('-')[2];
var url = "https://wide.b3log.org", pic = 'https://wide.b3log.org/static/images/wide-logo.png';
var urls = {};
urls.email = "mailto:?subject=" + $('title').text()
+ "&body=" + $('meta[name=description]').attr('content') + ' ' + url;
var twitterShare = encodeURIComponent($('meta[name=description]').attr('content') + " " + url + " #golang");
urls.twitter = "https://twitter.com/intent/tweet?status=" + twitterShare;
urls.facebook = "https://www.facebook.com/sharer/sharer.php?u=" + url;
urls.googleplus = "https://plus.google.com/share?url=" + url;
var title = encodeURIComponent($('title').text() + '. \n' + $('meta[name=description]').attr('content')
+ " #golang#");
urls.weibo = "http://v.t.sina.com.cn/share/share.php?title=" + title + "&url=" + url + "&pic=" + pic;
2018-10-05 16:04:40 +03:00
urls.qqz = "https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=" + url + "&sharesource=qzone&title=" + title+ "&pics=" + pic;
2015-02-14 15:38:33 +03:00
2018-10-05 16:04:40 +03:00
window.open(urls[key], "_blank", "top=100,left=200,width=648,height=618");
2015-02-15 05:08:51 +03:00
2015-02-14 15:38:33 +03:00
$(".menu .share-panel").hide();
});
},
2015-02-13 04:59:51 +03:00
init: function () {
2015-02-15 09:24:49 +03:00
CodeMirror.registerHelper("hint", "go", function (editor) {
var word = /[\w$]+/;
var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
var start = cur.ch, end = start;
while (end < curLine.length && word.test(curLine.charAt(end))) {
++end;
}
while (start && word.test(curLine.charAt(start - 1))) {
--start;
}
var request = newWideRequest();
request.code = editor.getValue();
request.cursorLine = cur.line;
request.cursorCh = cur.ch;
var autocompleteHints = [];
if (playground.autocompleteMutex && editor.state.completionActive) {
return;
}
playground.autocompleteMutex = true;
2015-02-15 09:24:49 +03:00
$.ajax({
async: false, // 同步执行
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/autocomplete',
2015-02-15 09:24:49 +03:00
data: JSON.stringify(request),
dataType: "json",
success: function (data) {
var autocompleteArray = data[1];
if (autocompleteArray) {
for (var i = 0; i < autocompleteArray.length; i++) {
var displayText = '',
text = autocompleteArray[i].name;
switch (autocompleteArray[i].class) {
case "type":
displayText = '<span class="fn-clear"><span class="ico-type ico"></span>'// + autocompleteArray[i].class
+ '<b>' + autocompleteArray[i].name + '</b> '
+ autocompleteArray[i].type + '</span>';
break;
case "const":
displayText = '<span class="fn-clear"><span class="ico-const ico"></span>'// + autocompleteArray[i].class
+ '<b>' + autocompleteArray[i].name + '</b> '
+ autocompleteArray[i].type + '</span>';
break;
case "var":
displayText = '<span class="fn-clear"><span class="ico-var ico"></span>'// + autocompleteArray[i].class
+ '<b>' + autocompleteArray[i].name + '</b> '
+ autocompleteArray[i].type + '</span>';
break;
case "package":
displayText = '<span class="fn-clear"><span class="ico-package ico"></span>'// + autocompleteArray[i].class
+ '<b>' + autocompleteArray[i].name + '</b> '
+ autocompleteArray[i].type + '</span>';
break;
case "func":
displayText = '<span><span class="ico-func ico"></span>'// + autocompleteArray[i].class
+ '<b>' + autocompleteArray[i].name + '</b>'
+ autocompleteArray[i].type.substring(4) + '</span>';
text += '()';
break;
default:
console.warn("Can't handle autocomplete [" + autocompleteArray[i].class + "]");
break;
}
autocompleteHints[i] = {
displayText: displayText,
text: text
};
}
}
}
});
setTimeout(function () {
playground.autocompleteMutex = false;
}, 20);
2015-02-15 09:24:49 +03:00
return {list: autocompleteHints, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
});
CodeMirror.commands.autocompleteAnyWord = function (cm) {
cm.showHint({hint: CodeMirror.hint.auto});
};
CodeMirror.commands.autocompleteAfterDot = function (cm) {
var mode = cm.getMode();
if (mode && "go" !== mode.name) {
return CodeMirror.Pass;
}
var token = cm.getTokenAt(cm.getCursor());
if ("comment" === token.type || "string" === token.type) {
return CodeMirror.Pass;
}
setTimeout(function () {
if (!cm.state.completionActive) {
cm.showHint({hint: CodeMirror.hint.go, completeSingle: false});
}
}, 50);
return CodeMirror.Pass;
};
2015-02-14 15:38:33 +03:00
playground.editor = CodeMirror.fromTextArea($("#editor")[0], {
2015-02-13 04:59:51 +03:00
lineNumbers: true,
autoCloseBrackets: true,
matchBrackets: true,
highlightSelectionMatches: {showToken: /\w/},
2015-02-13 19:00:38 +03:00
rulers: [{color: "#ccc", column: 80, lineStyle: "dashed"}],
2015-02-13 04:59:51 +03:00
styleActiveLine: true,
theme: "wide",
tabSize: 4,
indentUnit: 4,
2015-09-17 16:43:49 +03:00
indentWithTabs: true,
2015-02-13 04:59:51 +03:00
foldGutter: true,
2015-02-15 05:08:51 +03:00
cursorHeight: 1,
2015-02-15 09:24:49 +03:00
viewportMargin: 500,
extraKeys: {
"Ctrl-\\": "autocompleteAnyWord",
".": "autocompleteAfterDot"
}
2015-02-14 15:38:33 +03:00
});
2015-03-25 11:00:59 +03:00
playground.editor.setOption("gutters", ["CodeMirror-lint-markers", "CodeMirror-foldgutter"]);
2015-02-15 05:08:51 +03:00
2015-02-14 15:38:33 +03:00
$(window).resize(function () {
playground._resize();
2015-02-13 04:59:51 +03:00
});
2015-02-14 12:49:21 +03:00
2016-10-29 18:30:09 +03:00
playground.editor.setSize("auto", ($("#editorDiv").parent().height() * 0.7) + "px");
2015-02-14 12:49:21 +03:00
var hovered = false;
$(".menu .ico-share").hover(function () {
$(".menu .share-panel").show();
hovered = true;
}, function () {
if (!hovered) {
$(".menu .share-panel").hide();
}
hovered = false;
setTimeout(function () {
if (!hovered) {
$(".menu .share-panel").hide();
}
2019-05-17 06:25:44 +03:00
}, 500);
2015-02-14 12:49:21 +03:00
});
$(".menu .share-panel").hover(function () {
$(".menu .share-panel").show();
hovered = true;
}, function () {
$(".menu .share-panel").hide();
hovered = false;
});
2015-02-13 07:57:12 +03:00
playground.editor.on('changes', function (cm) {
$("#url").html("");
2015-08-15 06:41:37 +03:00
});
2015-08-15 06:41:37 +03:00
playground.editor.on('keydown', function (cm, evt) {
if (evt.altKey || evt.ctrlKey || evt.shiftKey) {
return;
}
var k = evt.which;
if (k < 48) {
return;
}
// hit [0-9]
2015-08-15 06:41:37 +03:00
if (k > 57 && k < 65) {
return;
}
// hit [a-z]
if (k > 90) {
return;
}
if (config.autocomplete) {
if (0.5 <= Math.random()) {
CodeMirror.commands.autocompleteAfterDot(cm);
}
}
2015-02-13 07:57:12 +03:00
});
2015-02-13 04:59:51 +03:00
this._initWS();
2015-02-14 15:38:33 +03:00
this._resize();
2015-02-15 06:09:17 +03:00
this._initWideShare();
2015-02-14 15:38:33 +03:00
this._initShare();
menu._initAbout();
2016-10-29 18:30:09 +03:00
this._initGoNews();
2015-02-13 04:59:51 +03:00
},
_initWS: function () {
// Used for session retention, server will release all resources of the session if this channel closed
var sessionWS = new ReconnectingWebSocket(config.channel + '/session/ws?sid=' + config.wideSessionId);
sessionWS.onopen = function () {
2019-06-23 09:14:37 +03:00
// console.log('[session onopen] connected');
2015-02-13 04:59:51 +03:00
};
sessionWS.onmessage = function (e) {
2019-06-23 09:14:37 +03:00
// console.log('[session onmessage]' + e.data);
2015-02-13 04:59:51 +03:00
};
sessionWS.onclose = function (e) {
2019-06-23 09:14:37 +03:00
// console.log('[session onclose] disconnected (' + e.code + ')');
2015-02-13 04:59:51 +03:00
};
sessionWS.onerror = function (e) {
2019-06-23 09:14:37 +03:00
// console.log('[session onerror] ' + JSON.parse(e));
2015-02-13 04:59:51 +03:00
};
var playgroundWS = new ReconnectingWebSocket(config.channel + '/playground/ws?sid=' + config.wideSessionId);
playgroundWS.onopen = function () {
2019-06-23 09:14:37 +03:00
// console.log('[playground onopen] connected');
2015-02-13 04:59:51 +03:00
};
playgroundWS.onmessage = function (e) {
var data = JSON.parse(e.data);
2015-02-14 12:49:21 +03:00
2015-02-13 05:50:14 +03:00
if ("init-playground" === data.cmd) {
return;
}
2015-02-13 04:59:51 +03:00
playground.pid = data.pid;
2019-05-23 10:51:56 +03:00
var output = $("#output").html();
if ("" === output) {
output = "<pre>" + data.output + "</pre>";
} else {
output = output.replace(/<\/pre>$/g, data.output + '</pre>');
}
2019-05-18 20:53:31 +03:00
output = output.replace(/\r/g, '');
output = output.replace(/\n/g, '<br/>');
2019-05-23 10:51:56 +03:00
if (-1 !== output.indexOf("<br/>")) {
output = Autolinker.link(output);
}
$("#output").html(output);
2015-02-13 04:59:51 +03:00
};
playgroundWS.onclose = function (e) {
2019-06-23 09:14:37 +03:00
// console.log('[playground onclose] disconnected (' + e.code + ')');
2015-02-13 04:59:51 +03:00
};
playgroundWS.onerror = function (e) {
2019-06-23 09:14:37 +03:00
console.log('[playground onerror] ', e);
2015-02-13 04:59:51 +03:00
};
},
2016-10-29 18:30:09 +03:00
_initGoNews: function () {
$.ajax({
url: "https://hacpai.com/apis/articles?tags=wide,golang&p=1&size=20",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
success: function (data, textStatus) {
var articles = data.articles;
if (0 === articles.length) {
return;
}
var length = articles.length;
2017-04-23 19:10:16 +03:00
var listHTML = "<ul><li class='title'>" + config.label.community +
"<a href='https://hacpai.com/article/1437497122181' target='_blank' class='fn-right'>边看边练</li>";
2016-10-29 18:30:09 +03:00
for (var i = 0; i < length; i++) {
var article = articles[i];
listHTML += "<li>"
+ "<a target='_blank' href='"
+ article.articlePermalink + "'>"
+ article.articleTitle + "</a>"
+"</span></li>";
}
$("#goNews").html(listHTML + "</ul>");
}
});
},
2015-02-15 08:53:02 +03:00
share: function () {
if (!playground.editor) {
return;
}
var code = playground.editor.getValue();
var request = newWideRequest();
request.code = code;
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/save',
2015-02-15 08:53:02 +03:00
data: JSON.stringify(request),
dataType: "json",
2015-11-24 12:39:35 +03:00
success: function (result) {
var data = result.data;
2015-02-15 08:53:02 +03:00
playground.editor.setValue(data.code);
2019-05-24 16:52:17 +03:00
if (0 != result.code) {
2015-02-15 08:53:02 +03:00
return;
}
var url = window.location.protocol + "//" + window.location.host + '/playground/' + data.fileName;
2015-02-16 12:10:21 +03:00
var request = newWideRequest();
request.url = url;
2019-05-17 08:18:33 +03:00
var html = '<div class="fn-clear"><label>' + config.label.url
+ config.label.colon + '</label><a href="'
+ url + '" target="_blank">' + url + "</a><br/>";
html += '<label>' + config.label.embeded + config.label.colon
+ '</label><br/><textarea rows="5" style="width:100%" readonly><iframe style="border:1px solid" src="'
+ url + '" width="99%" height="600"></iframe></textarea>';
html += '</div>';
$("#dialogShare").html(html);
$("#dialogShare").dialog("open");
2015-02-15 08:53:02 +03:00
}
});
},
2015-02-13 04:59:51 +03:00
stop: function () {
2015-02-15 05:08:51 +03:00
if (!playground.editor) {
return;
}
var cursor = playground.editor.getCursor();
playground.editor.focus();
playground.editor.setCursor(cursor);
if (!playground.pid) {
2015-02-13 04:59:51 +03:00
return;
}
var request = newWideRequest();
request.pid = playground.pid;
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/stop',
2015-02-13 04:59:51 +03:00
data: JSON.stringify(request),
dataType: "json"
});
},
run: function () {
if (!playground.editor) {
return;
}
2015-02-15 05:08:51 +03:00
var cursor = playground.editor.getCursor();
playground.editor.focus();
2015-02-13 04:59:51 +03:00
var code = playground.editor.getValue();
// Step 1. save & format code
var request = newWideRequest();
request.code = code;
2019-05-18 20:53:31 +03:00
$("#output").html("");
2015-02-13 04:59:51 +03:00
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/save',
2015-02-13 04:59:51 +03:00
data: JSON.stringify(request),
dataType: "json",
2015-11-24 12:39:35 +03:00
success: function (result) {
var data = result.data;
2015-02-13 04:59:51 +03:00
playground.editor.setValue(data.code);
2015-02-15 05:08:51 +03:00
playground.editor.setCursor(cursor);
2015-02-13 04:59:51 +03:00
2019-05-24 16:52:17 +03:00
if (0 != result.code) {
2015-02-13 04:59:51 +03:00
return;
}
// Step 2. compile code
var request = newWideRequest();
2015-02-13 05:50:14 +03:00
request.fileName = data.fileName;
2015-02-13 04:59:51 +03:00
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/build',
2015-02-13 04:59:51 +03:00
data: JSON.stringify(request),
dataType: "json",
2015-11-24 12:39:35 +03:00
success: function (result) {
var data = result.data;
2015-02-13 04:59:51 +03:00
2019-05-18 20:53:31 +03:00
$("#output").html(data.output);
2015-02-13 04:59:51 +03:00
2019-05-24 16:52:17 +03:00
if (0 != result.code) {
2015-02-13 04:59:51 +03:00
return;
}
// Step 3. run the executable binary and handle its output
var request = newWideRequest();
request.executable = data.executable;
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/run',
2015-02-13 04:59:51 +03:00
data: JSON.stringify(request),
dataType: "json",
2015-11-24 12:39:35 +03:00
success: function (result) {
2015-02-13 04:59:51 +03:00
// console.log(data);
}
});
}
});
}
});
2015-02-14 12:49:21 +03:00
},
format: function () {
if (!playground.editor) {
return;
}
2015-02-15 05:08:51 +03:00
var cursor = playground.editor.getCursor();
playground.editor.focus();
2015-02-14 12:49:21 +03:00
var code = playground.editor.getValue();
var request = newWideRequest();
request.code = code;
$.ajax({
type: 'POST',
2019-05-17 04:27:22 +03:00
url: '/playground/save',
2015-02-14 12:49:21 +03:00
data: JSON.stringify(request),
dataType: "json",
2015-11-24 12:39:35 +03:00
success: function (result) {
playground.editor.setValue(result.data.code);
2015-02-15 05:08:51 +03:00
playground.editor.setCursor(cursor);
2015-02-14 12:49:21 +03:00
}
});
2015-02-13 04:59:51 +03:00
}
};
$(document).ready(function () {
playground.init();
});