This commit is contained in:
2019-06-30 21:18:31 +08:00
commit db843337ce
31 changed files with 4888 additions and 0 deletions

147
js/common.js Normal file
View File

@ -0,0 +1,147 @@
require.config({paths: {'vs': 'https://lib.baomitu.com/monaco-editor/0.15.6/min/vs'}});
// Before loading vs/editor/editor.main, define a global MonacoEnvironment that overwrites
// the default worker url location (used when creating WebWorkers). The problem here is that
// HTML5 does not allow cross-domain web workers, so we need to proxy the instantiation of
// a web worker through a same-domain script
window.MonacoEnvironment = {
getWorkerUrl: function (workerId, label) {
return '/js/monaco-editor-worker-loader-proxy.js';
}
};
window.isAdmin = false;
function getNowDate() {
var date = new Date();
var sign1 = "-";
var sign2 = ":";
var year = date.getFullYear() // 年
var month = date.getMonth() + 1; // 月
var day = date.getDate(); // 日
var hour = date.getHours(); // 时
var minutes = date.getMinutes(); // 分
var seconds = date.getSeconds() //秒
var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
var week = weekArr[date.getDay()];
// 给一位数数据前面加 “0”
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (day >= 0 && day <= 9) {
day = "0" + day;
}
if (hour >= 0 && hour <= 9) {
hour = "0" + hour;
}
if (minutes >= 0 && minutes <= 9) {
minutes = "0" + minutes;
}
if (seconds >= 0 && seconds <= 9) {
seconds = "0" + seconds;
}
return year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds + " " + week;
}
function GetQueryString(name) {
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return '';
}
$(function () {
var id = window.localStorage.id;
if (!id) {
window.location.href = '/login.html'
}
var setRealName = function (id, realname) {
$.ajax({
type: "POST",
url: "/api.php?action=setRealName",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
id: id,
realname: realname
},
success: function (r) {
if (r.status === 1) {
console.log('保存真实姓名成功!')
} else {
alert('很抱歉,保存真实姓名失败,请稍后刷新重试。')
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!')
}
})
};
function loadImage(url, callback) {
var img = new Image(); //创建一个Image对象实现图片的预下载
img.crossOrigin = "Anonymous";
img.src = url;
img.onload = function () { //图片下载完毕时异步调用callback函数
callback.call(img);//将回调函数的this替换为Image对象
};
}
var getUserInfo = function (id) {
$.ajax({
type: "POST",
url: "/api.php?action=getUserInfo",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
id: id
},
success: function (r) {
if (r.status === 1) {
if (!r.result.userinfo) {
window.location.href = "login.html"
}
if (!r.result.userinfo.realname) {
var name = prompt("请输入你的真实姓名,方便大家进行沟通", "");
if (name != null && name !== "") {
r.result.userinfo.realname = name;
setRealName(id, name)
}
}
window.isAdmin = r.result.userinfo.admin === '1';
window.credit = r.result.userinfo.credit;
if ($('.myCredit')) $('.myCredit').text('经验:' + window.credit);
loadImage(r.result.userinfo.headimgurl.replace('http://', 'https://'), function () {
$('#avator').append(this)
});
$('#realname').text(r.result.userinfo.realname);
$('#nickname').text('(' + r.result.userinfo.nickname + ')');
if (window.isAdmin) {
$('.admin').css('display', 'block')
}
} else {
alert('很抱歉,获取用户信息失败,请稍后刷新重试。')
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!')
}
})
};
$('#logout').click(function () {
window.localStorage.removeItem('id');
window.location.href = "/login.html"
});
getUserInfo(id);
});

187
js/index.js Normal file
View File

@ -0,0 +1,187 @@
$(function () {
var language = {
"sProcessing": "处理中...",
"sLengthMenu": "显示 _MENU_ 项结果",
"sZeroRecords": "没有匹配结果",
"sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
"sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
"sInfoFiltered": "(由 _MAX_ 项结果过滤)",
"sInfoPostFix": "",
"sSearch": "搜索:",
"sUrl": "",
"sEmptyTable": "表中数据为空",
"sLoadingRecords": "载入中...",
"sInfoThousands": ",",
"oPaginate": {
"sFirst": "首页",
"sPrevious": "上页",
"sNext": "下页",
"sLast": "末页"
},
"oAria": {
"sSortAscending": ": 以升序排列此列",
"sSortDescending": ": 以降序排列此列"
}
};
var tableInit = function (r) {
$('#stage-table').DataTable({
language: language,
data: r.result.stage,
columns: [
{title: ""},
{title: "ID"},
{title: "No"},
{title: "题名"},
{title: "编程语言"},
{title: "解答"},
{title: "通过率"},
{title: "难度"},
{title: "管理"}
],
"order": [[2, "asc"]],
columnDefs: [
{
"targets": 0,
"orderable": false,
"className": "table-is-pass",
"render": function (data, type, row) {
if (data === '1') {
return '<svg viewBox="0 0 1397 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="27" height="20"><path d="M1396.363636 121.018182c0 0-223.418182 74.472727-484.072727 372.363636-242.036364 269.963636-297.890909 381.672727-390.981818 530.618182C512 1014.690909 372.363636 744.727273 0 549.236364l195.490909-186.181818c0 0 176.872727 121.018182 297.890909 344.436364 0 0 307.2-474.763636 902.981818-707.490909L1396.363636 121.018182 1396.363636 121.018182zM1396.363636 121.018182" fill="#1afa29"></path></svg>';
}
return '';
}
},
{
"targets": 1,
"data": null,
"visible": false,
"orderable": false
},
{
"targets": 3,
"className": "table-pname",
"render": function (data, type, row) {
return '<a href="/page/run.php?id=' + row[1] + '" target="_blank">' + data + '</a>';
}
},
{
"targets": -1,
"data": null,
"visible": window.isAdmin,
"render": function (data, type, row) {
return '<a href="/page/edit.php?id=' + row[1] + '" target="_blank" class="pure-button" style="font-size: 70%;">编辑</a>';
}
}]
});
$('#challenge-table').DataTable({
language: language,
data: r.result.challenge,
columns: [
{title: ""},
{title: "ID"},
{title: "No"},
{title: "题名"},
{title: "编程语言"},
{title: "解答"},
{title: "通过率"},
{title: "难度"},
{title: "管理"}
],
"order": [[2, "asc"]],
columnDefs: [
{
"targets": 0,
"orderable": false,
"render": function (data, type, row) {
return data;
}
},
{
"targets": 1,
"data": null,
"visible": false,
"orderable": false
},
{
"targets": 3,
"className": "table-pname",
"render": function (data, type, row) {
return '<a href="/page/run.php?id=' + row[1] + '" target="_blank">' + data + '</a>';
}
},
{
"targets": -1,
"data": null,
"visible": window.isAdmin,
"render": function (data, type, row) {
return '<a href="/page/edit.php?id=' + row[1] + '" target="_blank" class="pure-button" style="font-size: 70%;">编辑</a>';
}
}]
});
$('.tabs').tabslet({
controls: {
prev: '.prevTab',
next: '.nextTab'
}
});
$('#loading').hide();
};
var checkAdmin = function (r) {
if (window.isAdmin !== null) {
tableInit(r);
} else {
setTimeout(function () {
checkAdmin(r)
}, 50);
}
};
$.ajax({
type: "GET",
url: "/api.php?action=getProblemsetList&user_id=" + window.localStorage.id,
dataType: "json",
cache: !1,
timeout: 6e4,
success: function (r) {
if (r.status === 1) {
checkAdmin(r)
} else {
alert('很抱歉,获取数据失败,请稍后刷新重试。');
$('#loading').hide();
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!');
$('#loading').hide();
}
});
$('#myRecordButton').click(function() {
$.ajax({
type: "GET",
url: "/api.php?action=getMyRecordCount&user_id=" + window.localStorage.id,
dataType: "json",
cache: !1,
timeout: 6e4,
success: function (r) {
if (r.status === 1) {
if (r.result.all === r.result.pass) {
alert('恭喜您!已完成全部 ' + r.result.all + ' 道闯关题!');
} else {
alert('闯关题共有 ' + r.result.all + ' 道,您已经完成 ' + r.result.pass + '道。');
}
} else {
alert('很抱歉,获取数据失败,请稍后刷新重试。');
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!');
}
});
});
});

351
js/jquery.splitter.js Normal file
View File

@ -0,0 +1,351 @@
/*!
* JQuery Spliter Plugin version 0.27.1
* Copyright (C) 2010-2018 Jakub T. Jankiewicz <https://jcubic.pl/me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function($, undefined) {
var count = 0;
var splitter_id = null;
var splitters = [];
var current_splitter = null;
$.fn.split = function(options) {
var data = this.data('splitter');
if (data) {
return data;
}
var panel_1;
var panel_2;
var settings = $.extend({
limit: 100,
orientation: 'horizontal',
position: '50%',
invisible: false,
onDragStart: $.noop,
onDragEnd: $.noop,
onDrag: $.noop,
percent: false
}, options || {});
this.settings = settings;
var cls;
var children = this.children();
if (settings.orientation == 'vertical') {
panel_1 = children.first().addClass('left_panel');
panel_2 = panel_1.next().addClass('right_panel');
cls = 'vsplitter';
} else if (settings.orientation == 'horizontal') {
panel_1 = children.first().addClass('top_panel');
panel_2 = panel_1.next().addClass('bottom_panel');
cls = 'hsplitter';
}
if (settings.invisible) {
cls += ' splitter-invisible';
}
var width = this.width();
var height = this.height();
var id = count++;
this.addClass('splitter_panel');
var splitter = $('<div/>').addClass(cls).bind('mouseenter touchstart', function() {
splitter_id = id;
}).bind('mouseleave touchend', function() {
splitter_id = null;
}).insertAfter(panel_1);
var position;
function get_position(position) {
if (typeof position === 'number') {
return position;
} else if (typeof position === 'string') {
var match = position.match(/^([0-9\.]+)(px|%)$/);
if (match) {
if (match[2] == 'px') {
return +match[1];
} else {
if (settings.orientation == 'vertical') {
return (width * +match[1]) / 100;
} else if (settings.orientation == 'horizontal') {
return (height * +match[1]) / 100;
}
}
} else {
//throw position + ' is invalid value';
}
} else {
//throw 'position have invalid type';
}
}
function set_limit(limit) {
if(!isNaN(parseFloat(limit)) && isFinite(limit)){
return {
leftUpper: limit,
rightBottom: limit
};
}
return limit;
}
var self = $.extend(this, {
refresh: function() {
var new_width = this.width();
var new_height = this.height();
if (width != new_width || height != new_height) {
width = this.width();
height = this.height();
self.position(position);
}
},
option: function(name, value) {
if (name === 'position') {
return self.position(value);
} else if (typeof value === 'undefined') {
return settings[name];
} else {
settings[name] = value;
}
return self;
},
position: (function() {
if (settings.orientation == 'vertical') {
return function(n, silent) {
if (n === undefined) {
return position;
} else {
position = get_position(n);
var sw = splitter.width();
var sw2 = sw/2, pw;
var width = self.width();
if (settings.invisible) {
pw = panel_1.width(position).outerWidth();
panel_2.width(width - pw - 27); // 特殊处理
splitter.css('left', pw - sw2);
} else {
if (settings.percent) {
var w1 = (position - sw2) / width * 100;
pw = panel_1.css('width', w1 + '%').outerWidth();
panel_2.css('width', (width-pw-sw) / width * 100 + '%');
splitter.css('left', (pw / width * 100) + '%');
} else {
pw = panel_1.css('width', position - sw2).outerWidth();
panel_2.width(width - pw - sw - 20); // 特殊处理
splitter.css('left', pw);
}
}
panel_1.find('.splitter_panel').eq(0).height(self.height());
panel_2.find('.splitter_panel').eq(0).height(self.height());
}
if (!silent) {
self.trigger('splitter.resize');
self.find('.splitter_panel').trigger('splitter.resize');
}
return self;
};
} else if (settings.orientation == 'horizontal') {
return function(n, silent) {
if (n === undefined) {
return position;
} else {
position = get_position(n);
var sw = splitter.height();
var sw2 = sw / 2, pw;
var height = self.height();
if (settings.invisible) {
pw = panel_1.height(position).outerHeight();
panel_2.height(height - pw);
splitter.css('top', pw - sw2);
} else if (settings.percent) {
var h1 = (position - sw2) / height * 100;
pw = panel_1.css('height', h1 + '%').outerHeight();
panel_2.css('height', ((height - pw - sw) / height * 100) + '%');
splitter.css('top', (pw / height * 100) + '%');
} else {
pw = panel_1.height(position - sw2).outerHeight();
panel_2.height(height - pw - sw);
splitter.css('top', pw);
}
}
if (!silent) {
self.trigger('splitter.resize');
self.find('.splitter_panel').trigger('splitter.resize');
}
return self;
};
} else {
return $.noop;
}
})(),
orientation: settings.orientation,
limit: set_limit(settings.limit),
isActive: function() {
return splitter_id === id;
},
destroy: function() {
self.removeClass('splitter_panel');
splitter.unbind('mouseenter');
splitter.unbind('mouseleave');
splitter.unbind('touchstart');
splitter.unbind('touchmove');
splitter.unbind('touchend');
splitter.unbind('touchleave');
splitter.unbind('touchcancel');
if (settings.orientation == 'vertical') {
panel_1.removeClass('left_panel');
panel_2.removeClass('right_panel');
} else if (settings.orientation == 'horizontal') {
panel_1.removeClass('top_panel');
panel_2.removeClass('bottom_panel');
}
self.unbind('splitter.resize');
self.trigger('splitter.resize');
self.find('.splitter_panel').trigger('splitter.resize');
splitters[id] = null;
count--;
splitter.remove();
self.removeData('splitter');
var not_null = false;
for (var i=splitters.length; i--;) {
if (splitters[i] !== null) {
not_null = true;
break;
}
}
//remove document events when no splitters
if (!not_null) {
$(document.documentElement).unbind('.splitter');
$(window).unbind('resize.splitter');
splitters = [];
count = 0;
}
}
});
self.bind('splitter.resize', function(e) {
var pos = self.position();
if (self.orientation == 'vertical' &&
pos > self.width()) {
pos = self.width() - self.limit.rightBottom-1;
} else if (self.orientation == 'horizontal' &&
pos > self.height()) {
pos = self.height() - self.limit.rightBottom-1;
}
if (pos < self.limit.leftUpper) {
pos = self.limit.leftUpper + 1;
}
e.stopPropagation();
self.position(pos, true);
});
//inital position of splitter
var pos;
if (settings.orientation == 'vertical') {
if (pos > width-settings.limit.rightBottom) {
pos = width-settings.limit.rightBottom;
} else {
pos = get_position(settings.position);
}
} else if (settings.orientation == 'horizontal') {
//position = height/2;
if (pos > height-settings.limit.rightBottom) {
pos = height-settings.limit.rightBottom;
} else {
pos = get_position(settings.position);
}
}
if (pos < settings.limit.leftUpper) {
pos = settings.limit.leftUpper;
}
self.position(pos, true);
var parent = this.closest('.splitter_panel');
if (parent.length) {
this.height(parent.height());
}
// bind events to document if no splitters
if (splitters.filter(Boolean).length === 0) {
$(window).bind('resize.splitter', function() {
$.each(splitters, function(i, splitter) {
if (splitter) {
splitter.refresh();
}
});
});
$(document.documentElement).on('mousedown.splitter touchstart.splitter', function(e) {
if (splitter_id !== null) {
e.preventDefault();
current_splitter = splitters[splitter_id];
setTimeout(function() {
$('<div class="splitterMask"></div>').
css('cursor', current_splitter.children().eq(1).css('cursor')).
insertAfter(current_splitter);
});
current_splitter.settings.onDragStart(e);
}
}).bind('mouseup.splitter touchend.splitter touchleave.splitter touchcancel.splitter', function(e) {
if (current_splitter) {
setTimeout(function() {
$('.splitterMask').remove();
});
current_splitter.settings.onDragEnd(e);
current_splitter = null;
}
}).bind('mousemove.splitter touchmove.splitter', function(e) {
if (current_splitter !== null) {
var leftUpperLimit = current_splitter.limit.leftUpper;
var rightBottomLimit = current_splitter.limit.rightBottom;
var offset = current_splitter.offset();
if (current_splitter.orientation == 'vertical') {
var pageX = e.pageX;
if(e.originalEvent && e.originalEvent.changedTouches){
pageX = e.originalEvent.changedTouches[0].pageX;
}
var x = pageX - offset.left;
if (x <= current_splitter.limit.leftUpper) {
x = current_splitter.limit.leftUpper + 1;
} else if (x >= current_splitter.width() - rightBottomLimit) {
x = current_splitter.width() - rightBottomLimit - 1;
}
if (x > current_splitter.limit.leftUpper &&
x < current_splitter.width()-rightBottomLimit) {
current_splitter.position(x, true);
current_splitter.trigger('splitter.resize');
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
} else if (current_splitter.orientation == 'horizontal') {
var pageY = e.pageY;
if(e.originalEvent && e.originalEvent.changedTouches){
pageY = e.originalEvent.changedTouches[0].pageY;
}
var y = pageY-offset.top;
if (y <= current_splitter.limit.leftUpper) {
y = current_splitter.limit.leftUpper + 1;
} else if (y >= current_splitter.height() - rightBottomLimit) {
y = current_splitter.height() - rightBottomLimit - 1;
}
if (y > current_splitter.limit.leftUpper &&
y < current_splitter.height()-rightBottomLimit) {
current_splitter.position(y, true);
current_splitter.trigger('splitter.resize');
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
}
current_splitter.settings.onDrag(e);
}
});//*/
}
splitters[id] = self;
self.data('splitter', self);
return self;
};
})(jQuery);

View File

@ -0,0 +1,4 @@
self.MonacoEnvironment = {
baseUrl: 'https://lib.baomitu.com/monaco-editor/0.15.6/min/'
};
importScripts('https://lib.baomitu.com/monaco-editor/0.15.6/min/vs/base/worker/workerMain.js');

329
js/page/edit.js Normal file
View File

@ -0,0 +1,329 @@
$(function () {
var jsCode = `'use strict';
var phpEngine = uniter.createEngine('PHP');
phpEngine.expose({
pass: function () {
pass();
return '测试通过';
},
}, 'r');
phpEngine.getStdout().on('data', function (data) {
print(data);
});
phpEngine.getStderr().on('data', function (data) {
print(data);
});
phpEngine.execute(phpCode).fail(function (error) {
// print(error.toString());
});
`;
var testCode = `<?php
$pass = 1;
$m =
if ($m != ) {
$pass = 0;
echo "测试用例:<br>";
echo "输出结果:" . $m . "<br>";
}
if ($pass) {
echo $r->pass();
} else {
echo "<br>测试不通过";
}`;
require(["vs/editor/editor.main"], function () {
window.editor = monaco.editor.create(document.getElementById('phpContainer'), {
value: [
'<?php',
'\tfunction sum($a, $b) {',
'\t\treturn $a + $b;',
'\t}',
'',
'// --------- 测试区域',
''
].join('\n'),
language: 'php'
});
window.jsEditor = monaco.editor.create(document.getElementById('jsContainer'), {
value: jsCode,
language: 'javascript'
});
window.testEditor = monaco.editor.create(document.getElementById('testContainer'), {
value: testCode,
language: 'php'
});
function execMain() {
var javascriptCode = window.jsEditor.getValue(),
phpCode = window.editor.getValue(),
resultIframe = document.getElementById('result'),
resultDocument = resultIframe.contentWindow.document,
resultBody;
function clear() {
resultBody.innerHTML = '';
}
function print(html) {
resultBody.insertAdjacentHTML('beforeEnd', html);
}
function pass() {
console.log('pass')
}
function printText(text) {
resultBody.appendChild(document.createTextNode(text));
}
// Ensure the document has a body for IE9
resultDocument.write('<body></body>');
resultDocument.close();
resultBody = resultDocument.body;
clear();
try {
/*jshint evil: true */
new Function('phpCode, print, resultBody, pass', javascriptCode)(phpCode, print, resultBody, pass);
} catch (error) {
printText('<JavaScript error> ' + error.toString());
}
}
function runUnit() {
var javascriptCode = window.jsEditor.getValue(),
phpCode = window.editor.getValue(),
testCode = window.testEditor.getValue(),
resultIframe = document.getElementById('result'),
resultDocument = resultIframe.contentWindow.document,
resultBody;
if (phpCode.indexOf('// --------- 测试区域') !== -1) {
phpCode = phpCode.substring(0, phpCode.lastIndexOf('// --------- 测试区域')) + testCode.replace('<?php', '');
} else {
phpCode = phpCode + testCode.replace('<?php', '');
}
function clear() {
resultBody.innerHTML = '';
}
function print(html) {
resultBody.insertAdjacentHTML('beforeEnd', html);
}
function pass() {
console.log('测试通过')
}
function printText(text) {
resultBody.appendChild(document.createTextNode(text));
}
// Ensure the document has a body for IE9
resultDocument.write('<body></body>');
resultDocument.close();
resultBody = resultDocument.body;
clear();
try {
/*jshint evil: true */
new Function('phpCode, print, resultBody, pass', javascriptCode)(phpCode, print, resultBody, pass);
} catch (error) {
printText('<JavaScript error> ' + error.toString());
}
}
$('#runMain').click(function () {
execMain()
});
$('#runUnit').click(function () {
runUnit()
});
var contentHeight = window.document.body.clientHeight - 50;
$('#phpContainer').css('height', contentHeight - 70);
$('#jsContainer').css('height', contentHeight - 70);
$('#testContainer').css('height', contentHeight - 70);
$('#article').css('height', contentHeight + 30);
window.editor.layout();
window.jsEditor.layout();
window.testEditor.layout();
window.onresize = function () {
window.editor.layout();
window.jsEditor.layout();
window.testEditor.layout();
};
var describe = new SimpleMDE({ element: $("#describe")[0] });
var answer = new SimpleMDE({ element: $("#answer")[0] });
var testCase = new SimpleMDE({ element: $("#testCase")[0] });
var expectedResult = new SimpleMDE({ element: $("#expectedResult")[0] });
$('#submitForm').click(function () {
// 李永升你应该适配一下大于1时直接加百分号小于1时乘以100再加百分号
var passPercent = $('#passPercent').val();
if (passPercent > 1) {
passPercent = passPercent / 100
}
$('#passPercent').val(passPercent);
var postData = $('#edit-form').serializeArray();
var javascriptCode = window.jsEditor.getValue(),
phpUnitCode = window.testEditor.getValue(),
phpCode = window.editor.getValue();
postData.push({
name: 'javascriptCode',
value: javascriptCode
});
postData.push({
name: 'phpUnitCode',
value: phpUnitCode
});
postData.push({
name: 'phpCode',
value: phpCode
});
postData.push({
name: 'describe',
value: describe.value()
});
postData.push({
name: 'answer',
value: answer.value()
});
postData.push({
name: 'testCase',
value: testCase.value()
});
postData.push({
name: 'expectedResult',
value: expectedResult.value()
});
if (GetQueryString('id')) {
$.ajax({
type: "POST",
url: "/api.php?action=editProblemset&id=" + GetQueryString('id'),
dataType: "json",
cache: !1,
timeout: 6e4,
data: postData,
success: function (r) {
if (r.status === 1) {
window.location.href = '/index.php'
} else {
alert('很抱歉,保存失败,请稍后刷新重试。')
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!')
}
})
} else {
$.ajax({
type: "POST",
url: "/api.php?action=addProblemset",
dataType: "json",
cache: !1,
timeout: 6e4,
data: postData,
success: function (r) {
if (r.status === 1) {
window.location.href = '/index.php'
} else {
alert('很抱歉,新增题目失败,请稍后刷新重试。')
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!')
}
})
}
});
if (GetQueryString('id')) {
$.ajax({
type: "GET",
url: "/api.php?action=getProblemset&id=" + GetQueryString('id'),
dataType: "json",
cache: !1,
timeout: 6e4,
success: function (r) {
if (r.status === 1) {
$('#type').val(r.result.type);
$('#name').val(r.result.name);
$('#isAnswer').val(r.result.isAnswer);
$('#language').val(r.result.language);
$('#difficulty').val(r.result.difficulty);
$('#isCredit').val(r.result.isCredit);
$('#passPercent').val(r.result.passPercent);
$('#tag').val(r.result.tag);
$('#credit').val(r.result.credit);
$('#mark').val(r.result.mark);
describe.value(r.result.describe);
answer.value(r.result.answer);
testCase.value(r.result.testCase);
expectedResult.value(r.result.expectedResult);
window.editor.setValue(r.result.phpCode);
window.testEditor.setValue(r.result.phpUnitCode);
window.jsEditor.setValue(r.result.javascriptCode);
$('.tabs').tabslet({
controls: {
prev: '.prevTab',
next: '.nextTab'
}
});
} else {
alert('很抱歉,获取数据失败,请稍后刷新重试。')
}
$('#loading').hide();
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!');
$('#loading').hide();
}
})
} else {
$('#loading').hide();
$('.tabs').tabslet({
controls: {
prev: '.prevTab',
next: '.nextTab'
}
});
}
});
});

304
js/page/run.js Normal file
View File

@ -0,0 +1,304 @@
$(function () {
var converter = new showdown.Converter();
var phpUnitCode = "";
var javascriptCode = "";
var theType = "";
var no = "";
var isLoading = false;
require(["vs/editor/editor.main"], function () {
window.editor = monaco.editor.create(document.getElementById('container'), {
value: [
'<?php',
'\techo "Hello world!";'
].join('\n'),
language: 'php'
});
function run (phpCode, oldCode) {
var resultIframe = document.getElementById('result');
var resultDocument = resultIframe.contentWindow.document;
var resultBody = null;
var clear = function () {
resultBody.innerHTML = '';
};
var print = function (html) {
// outExeTime();
resultBody.insertAdjacentHTML('beforeEnd', html);
};
var pass = function () {
console.log('测试通过');
$.ajax({
type: "POST",
url: "/api.php?action=addRecord",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
user_id: window.localStorage.id,
problemset_id: GetQueryString('id'),
type: theType,
code: oldCode,
is_pass: '1'
},
success: function (r) {
if (r.status === 1) {
console.log('测试通过的结果保存成功');
if (confirm("测试通过,进入下一题?")) {
$.ajax({
type: "GET",
url: "/api.php?action=getNextNo&no=" + no + "&type=" + theType,
dataType: "json",
cache: !1,
timeout: 6e4,
success: function (r) {
if (r.status === 1) {
if (r.id > 0) {
window.location.href = '/page/run.php?id=' + r.id;
} else if (r.id == 0){
alert('恭喜你!已经做完最后一题!');
window.location.href = '/index.php';
} else {
window.location.href = '/index.php';
}
} else {
alert('很抱歉,获取下一题数据失败,请重试。')
}
},
error: function () {
alert('很抱歉,出错了,请重试!');
}
})
}
} else {
alert('很抱歉,保存数据失败,请重试。')
}
},
error: function () {
alert('很抱歉,出错了,请重试!');
}
})
}
var printText = function (text) {
resultBody.appendChild(document.createTextNode(text));
};
// Ensure the document has a body for IE9
resultDocument.write('<body></body>');
resultDocument.close();
resultBody = resultDocument.body;
clear();
try {
/*jshint evil: true */
new Function('phpCode, print, resultBody, pass', javascriptCode)(phpCode, print, resultBody, pass);
} catch (error) {
printText('<JavaScript error> ' + error.toString());
}
}
function exec(test) {
// var start = (new Date()).getTime()
var phpCode = window.editor.getValue();
var oldCode = phpCode;
if (!test) {
if (isLoading) return;
isLoading = true;
if (phpCode.indexOf('// --------- 测试区域') !== -1) {
phpCode = phpCode.substring(0, phpCode.lastIndexOf('// --------- 测试区域')) + phpUnitCode.replace('<?php', '');
} else {
phpCode = phpCode + phpUnitCode.replace('<?php', '');
}
// 每次提交都记录数据, 需要成功返回后再执行,确保数据一致性
$.ajax({
type: "POST",
url: "/api.php?action=addRecord",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
user_id: window.localStorage.id,
problemset_id: GetQueryString('id'),
type: theType,
code: oldCode,
is_pass: '0'
},
success: function () {
run(phpCode, oldCode);
isLoading = false;
},
error: function () {
alert('很抱歉,出错了,请重试!');
isLoading = false;
}
})
} else {
run(phpCode, oldCode)
}
}
$('#testRun').click(function () {
$('.tabs').trigger('show', '#resultView');
exec(true);
});
$('#run').click(function () {
$('.tabs').trigger('show', '#resultView');
exec(false);
});
var contentHeight = window.document.body.clientHeight - 50;
$('#container').css('height', contentHeight - 70);
var splitter = $('#content').height(contentHeight).split({
orientation: 'vertical',
limit: 10,
position: '40%', // if there is no percentage it interpret it as pixels
onDrag: function (event) {
console.log(splitter.position());
window.editor.layout();
}
});
if (!localStorage.auto) {
localStorage.auto = '1';
}
window.auto = localStorage.auto;
window.editor.onDidChangeModelContent(function () {
if (window.auto === '1') {
exec(true)
}
});
window.editor.layout();
if (window.auto === '1') {
$("#auto").prop("checked", 'true');
exec(true);
} else {
$("#auto").prop("checked", 'false')
}
$("#auto").click(function () {
if ($(this).prop("checked")) {
window.auto = '1';
localStorage.auto = '1'
} else {
window.auto = '2';
localStorage.auto = '2'
}
});
if (GetQueryString('id')) {
$.ajax({
type: "GET",
url: "/api.php?action=getProblemset&id=" + GetQueryString('id'),
dataType: "json",
cache: !1,
timeout: 6e4,
success: function (r) {
if (r.status === 1) {
var typeStr = '挑战赛';
if (r.result.type === '1') {
typeStr = '闯关模式'
}
var difficultyStr = '困难';
if (r.result.difficulty === '1') {
difficultyStr = '简单'
} else if (r.result.difficulty === '2') {
difficultyStr = '中等'
}
$(document).attr('title', r.result.name + ' - ' + typeStr);
$('#describeView .cont').html('<h3 style="font-weight: 600">' + r.result.name + '(' + difficultyStr + ')' + ' - ' + typeStr + '</h3>' + converter.makeHtml(r.result.describe));
$('#answerView .cont').html(converter.makeHtml(r.result.answer));
if (r.result.isAnswer !== '1') {
$('#answerViewButton').hide();
}
window.editor.setValue(r.result.phpCode);
phpUnitCode = r.result.phpUnitCode;
javascriptCode = r.result.javascriptCode;
var testCase = r.result.testCase;
var expectedResult = r.result.expectedResult;
$('.testCaseContent').html(converter.makeHtml(testCase));
$('.expectedResultContent').html(converter.makeHtml(expectedResult));
$('#rightPane pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
theType = r.result.type;
no = r.result.no;
$.ajax({
type: "POST",
url: "/api.php?action=getRecord",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
user_id: window.localStorage.id,
problemset_id: GetQueryString('id'),
},
success: function (r) {
if (r.status === 1) {
window.editor.setValue(r.code);
}
$('.tabs').tabslet({
controls: {
prev: '.prevTab',
next: '.nextTab'
}
});
$('#loading').hide();
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!');
$('#loading').hide();
}
});
} else {
alert('很抱歉,获取数据失败,请稍后刷新重试。')
}
$('#loading').hide();
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!');
$('#loading').hide();
}
})
} else {
$('#loading').hide();
$('.tabs').tabslet({
controls: {
prev: '.prevTab',
next: '.nextTab'
}
});
}
});
});

153
js/page/test.js Normal file
View File

@ -0,0 +1,153 @@
$(function () {
var saveTestCode = function (code) {
$.ajax({
type: "POST",
url: "/api.php?action=saveTestCode",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
user_id: window.localStorage.id,
code: code
}
})
};
require(["vs/editor/editor.main"], function () {
$.ajax({
type: "POST",
url: "/api.php?action=getTestCode",
dataType: "json",
cache: !1,
timeout: 6e4,
data: {
user_id: window.localStorage.id,
},
success: function (r) {
if (r.status === 1) {
window.editor = monaco.editor.create(document.getElementById('container'), {
value: r.code,
language: 'php'
});
function exec() {
// var start = (new Date()).getTime()
var javascriptCode = `'use strict';
var phpEngine = uniter.createEngine('PHP');
phpEngine.getStdout().on('data', function (data) {
print(data);
});
phpEngine.getStderr().on('data', function (data) {
print(data);
});
phpEngine.execute(phpCode).fail(function (error) {
// print(error.toString());
});
`,
phpCode = window.editor.getValue(),
resultIframe = document.getElementById('result'),
resultDocument = resultIframe.contentWindow.document,
resultBody;
saveTestCode(phpCode);
function clear() {
resultBody.innerHTML = '';
}
function print(html) {
// outExeTime();
resultBody.insertAdjacentHTML('beforeEnd', html);
}
function printText(text) {
resultBody.appendChild(document.createTextNode(text));
}
// function outExeTime () {
// // var execTimeString = getNowDate() + '执行结果(' + ((new Date()).getTime() - start) + 'ms)';
// // var headerHtml = '<span style="color: #888;font-weight: 300;font-size: 10px;">' + execTimeString + ':</span><br>'
// // $('#out').html(headerHtml)
// }
// Ensure the document has a body for IE9
resultDocument.write('<body></body>');
resultDocument.close();
resultBody = resultDocument.body;
clear();
try {
/*jshint evil: true */
new Function('phpCode, print, resultBody', javascriptCode)(phpCode, print, resultBody);
} catch (error) {
printText('<JavaScript error> ' + error.toString());
}
}
$('#run').click(function () {
exec()
});
var contentHeight = window.document.body.clientHeight - 50;
$('#container').css('height', contentHeight - 70);
var splitter = $('#content').height(contentHeight).split({
orientation: 'vertical',
limit: 10,
position: '40%', // if there is no percentage it interpret it as pixels
onDrag: function (event) {
console.log(splitter.position());
window.editor.layout();
}
});
if (!localStorage.auto) {
localStorage.auto = '1';
}
window.auto = localStorage.auto;
window.editor.onDidChangeModelContent(function () {
if (window.auto === '1') {
exec()
}
});
window.editor.layout();
if (window.auto === '1') {
$("#auto").prop("checked", 'true')
exec()
} else {
$("#auto").prop("checked", 'false')
}
$("#auto").click(function () {
if ($(this).prop("checked")) {
window.auto = '1';
localStorage.auto = '1'
} else {
window.auto = '2';
localStorage.auto = '2'
}
});
$('#loading').hide();
} else {
alert('很抱歉,获取已保存的代码失败,请稍后刷新重试。')
}
},
error: function () {
alert('很抱歉,出错了,请稍后刷新重试!')
}
});
});
});

3
js/page/user.js Normal file
View File

@ -0,0 +1,3 @@
$(function () {
$('#loading').hide();
});

3
js/page/userinfo.js Normal file
View File

@ -0,0 +1,3 @@
$(function () {
$('#loading').hide();
});

15
js/uniter.js Normal file

File diff suppressed because one or more lines are too long