1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567 |
- var MagicEditor = {
- init : function(){
- this.config = {};
- var skin = this.getValue('skin');
- if(skin){
- $('body').addClass('skin-' + skin);
- }
- this.addedGroups = {};
- this.apiId = null;
- this.apiList = [];
- this.debugSessionId = null;
- this.defaultRequestValue = '{\r\n\t"request" : {\r\n\t\t"message" : "Hello MagicAPI!"\r\n\t},\r\n\t"path" : {\r\n\t\t"id" : "123456"\r\n\t},\r\n\t"body" : {\r\n\t\t"id" : "123456"\r\n\t},\r\n\t"header" : {\r\n\t\t"token" : "tokenValue"\r\n\t},\r\n\t"cookie" : {\r\n\t\t"cookieName" : "cookieValue"\r\n\t},\r\n\t"session" : {\r\n\t\t"userId" : "123"\r\n\t}\r\n}';
- this.initMTA();
- this.loadAPI();
- this.initShortKey();
- this.initSkin();
- this.initLeftToobarContainer();
- this.initBottomContainer();
- this.initSelect();
- this.initContextMenu();
- this.initScriptEditor();
- this.resetEditor();
- this.checkUpdate();
- this.backupInterval();
- var _this = this;
- $.getJSON('config.json',function(data){
- _this.config = data;
- })
- },
- initSkin : function(){
- var skinSelector = $('.skin-selector');
- $('.button-skin').on('click',function(){
- skinSelector.toggle();
- return false;
- });
- var $body = $('body');
- $body.on('click',function(){
- skinSelector.hide();
- })
- var _this = this;
- skinSelector.on('click','li',function(){
- skinSelector.hide();
- $(this).siblings().each(function(){
- $body.removeClass('skin-' + $(this).text())
- })
- _this.setSkin($(this).text());
- })
- },
- resetEditor : function(){
- $('input[name=group]').val('未分组');
- $('input[name=method]').val('GET');
- $('input[name=name]').val('');
- $('input[name=path]').val('');
- $('input[name=prefix]').val('');
- this.outputJson = null;
- this.apiId = null;
- this.scriptEditor&&this.scriptEditor.setValue('return message;');
- this.requestEditor && this.requestEditor.setValue(this.defaultRequestValue);
- this.resultEditor&&this.resultEditor.setValue('');
- this.optionsEditor && this.optionsEditor.setValue('{\r\n}');
- },
- addBreakPoint : function(line){
- var model = this.scriptEditor.getModel();
- model.deltaDecorations([],[{
- range : new monaco.Range(line, 1, line, 1),
- options: {
- isWholeLine: true,
- linesDecorationsClassName: 'breakpoints',
- className : 'breakpoint-line',
- }
- }])
- },
- removeBreakPoint : function(line){
- var model = this.scriptEditor.getModel();
- var decorations = [];
- if (line !== undefined) {
- decorations = model.getLineDecorations(line);
- } else {
- decorations = model.getAllDecorations();
- }
- var ids = [];
- for (var i=0,len =decorations.length;i<len;i++) {
- if (decorations[i].options.linesDecorationsClassName === 'breakpoints') {
- ids.push(decorations[i].id)
- }
- }
- model.deltaDecorations(ids, [])
- },
- hasBreakPoint : function(line){
- var decorations = this.scriptEditor.getLineDecorations(line);
- for (var i=0,len =decorations.length;i<len;i++) {
- if (decorations[i].options.linesDecorationsClassName === 'breakpoints') {
- return true;
- }
- }
- },
- renderApiList : function(){
- var empty = true;
- var root = [];
- var groups = {};
- var apiList = this.apiList;
- if(apiList&&apiList.length > 0){
- var $groupUL = $('input[name=group]').next();
- for(var i=0,len = apiList.length;i<len;i++){
- var info = apiList[i];
- info.groupName = info.groupName || '未分组';
- if(!groups[info.groupName]){
- groups[info.groupName] = {
- id : info.groupName,
- children : [],
- spread : true,
- groupPrefix : info.groupPrefix,
- title : info.groupName
- }
- if($groupUL.find('[data-name='+$.escapeSelector(info.groupName)+']').length == 0){
- $groupUL.append($('<li data-name="'+info.groupName+'" data-prefix="'+(info.groupPrefix || '')+'"/>').append(info.groupName))
- }
- }
- if(info.show!==false){
- groups[info.groupName].children.push({
- id : info.id,
- groupName : info.groupName,
- groupPrefix : info.groupPrefix,
- name : info.name,
- title : '<label style="padding-right: 4px;color:#000">' + info.name + "</label>" + info.path,
- path : info.path
- });
- }
- }
- }
- for(var key in this.addedGroups){
- if(!groups[key]){
- groups[key] = this.addedGroups[key];
- }
- }
- var $dom = $('.api-list-container').html('');
- for(var key in groups){
- var group = groups[key];
- var $item = $('<div/>').addClass('group-item')
- .addClass('opened')
- .append($('<div/>').addClass('group-header')
- .append('<i class="iconfont icon-arrow-bottom"></i><i class="iconfont icon-list"></i>')
- .append($('<label/>').append(key))
- .append(group.groupPrefix ? '<span>('+group.groupPrefix+')</span>': '')
- );
- if(group.children){
- var $ul = $('<ul/>').addClass('group-list');
- for(var i =0,len = group.children.length;i<len;i++){
- var info = group.children[i];
- $ul.append($('<li/>').attr('data-id',info.id).append('<i class="iconfont icon-script"></i>')
- .append('<label>'+info.name+'</label>')
- .append('<span>('+info.path+')</span>'));
- }
- $item.append($ul);
- }
- $dom.append($item);
- }
- },
- loadAPI : function(id,isCopy){
- var _this = this;
- if(id){
- this.ajax({
- url : 'get',
- data : {
- id : id
- },
- success : function(info){
- _this.resetEditor();
- $('.button-delete').removeClass('disabled');
- if(isCopy === true){
- $('input[name=name]').val();
- $('input[name=path]').val();
- MagicEditor.setStatusBar('复制接口:' + info.name + '(' + info.path + ')')
- }else{
- _this.apiId = id;
- $('input[name=name]').val(info.name);
- $('input[name=path]').val(info.path);
- MagicEditor.setStatusBar('编辑接口:' + info.name + '(' + info.path + ')')
- }
- $('input[name=method]').val(info.method);
- $('input[name=group]').val(info.groupName || '未分组');
- $('input[name=prefix]').val(info.groupPrefix || '');
- $('.button-run,.button-delete').removeClass('disabled');
- _this.scriptEditor && _this.scriptEditor.setValue(info.script);
- _this.requestEditor && _this.requestEditor.setValue(info.parameter || _this.defaultRequestValue);
- _this.optionsEditor && _this.optionsEditor.setValue(info.option || '{\r\n}');
- }
- })
- }else{
- this.ajax({
- url : 'list',
- success : function(list){
- _this.apiList = list;
- _this.renderApiList();
- }
- })
- }
- },
- createNew : function($header){
- MagicEditor.createDialog({
- title : '新建接口',
- content : '新建接口会清空当前编辑器,是否继续?',
- buttons : [{
- name : '继续',
- click : function(){
- $('.group-item .group-list li.selected').removeClass('selected');
- MagicEditor.resetEditor();
- $('.button-delete').addClass('disabled');
- if($header){
- $('input[name=group]').val($header.find('label').text());
- var prefix = $header.find('span').text();
- if(prefix){
- $('input[name=prefix]').val(prefix.substring(1,prefix.length - 1));
- }
- }
- MagicEditor.report('create_api');
- MagicEditor.setStatusBar('创建接口');
- }
- },{
- name : '取消'
- }]
- })
- },
- setStatusBar : function(value){
- $('.footer-container').html(value);
- },
- initMTA : function(){
- window._mtac = {};
- var element = document.createElement("script");
- element.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
- element.setAttribute("name", "MTAH5");
- element.setAttribute("sid", "500724136");
- element.setAttribute("cid", "500724141");
- var s = document.getElementsByTagName("script")[0];
- s.parentNode.insertBefore(element, s);
- var _this = this;
- element.onload = element.onreadystatechange = function(){
- if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete') {
- _this.report('v0_3_4');
- }
- }
- },
- // 修改分组
- updateGroup : function($header){
- var _this = MagicEditor;
- var oldGroupName = $header.find('label').text();
- var oldPrefix = $header.find('span').text();
- oldPrefix = oldPrefix ? oldPrefix.substring(1,oldPrefix.length - 1) : '';
- _this.createDialog({
- title : '修改分组:' + oldGroupName,
- content : '<label>分组名称:</label><input type="text" name="name" value="'+oldGroupName+'" autocomplete="off"/><div style="height:2px;"></div><label>分组前缀:</label><input type="text" value="'+oldPrefix+'" name="prefix" autocomplete="off"/>',
- replace : false,
- buttons : [{
- name : '修改',
- click : function($dom){
- var groupName = $dom.find('input[name=name]').val();
- var groupPrefix = $dom.find('input[name=prefix]').val();
- if(!groupName){
- $dom.find('input[name=path]').focus();
- return false;
- }
- var exists = false;
- $('.group-header').each(function(){
- if(this !== $header[0]){
- var name = $(this).find('label').text();
- if(name == groupName){
- exists = true;
- return false;
- }
- }
- });
- if(groupName.indexOf("'")!= -1 || groupName.indexOf('"') != -1){
- _this.alert('创建分组','分组名不能包含特殊字符 \' "');
- return false;
- }
- if(groupPrefix.indexOf("'")!= -1 || groupPrefix.indexOf('"') != -1){
- _this.alert('创建分组','分组前缀不能包含特殊字符 \' "');
- return false;
- }
- if(exists){
- _this.alert('创建分组','分组已存在!');
- return false;
- }
- _this.report('group_update');
- _this.ajax({
- url : 'group/update',
- data : {
- oldGroupName : oldGroupName,
- groupName : groupName,
- prefix : groupPrefix
- },
- success : function(){
- if(_this.addedGroups[oldGroupName]){
- delete _this.addedGroups[oldGroupName]
- }
- _this.addedGroups[groupName] = {
- groupName : groupName,
- groupPrefix : groupPrefix
- }
- var apiList = _this.apiList;
- if(apiList&&apiList.length > 0){
- for(var i=0,len = apiList.length;i<len;i++){
- if(apiList[i].groupName == oldGroupName){
- apiList[i].groupName = groupName;
- apiList[i].groupPrefix = groupPrefix || '';
- }
- }
- }
- var $group = $('input[name=group]');
- $group.next().find('li[data-name='+$.escapeSelector(oldGroupName)+']').attr('data-prefix',(groupPrefix || '')).attr('data-name',groupName).html(groupName);
- if($group.val() == oldGroupName){
- $group.val(groupName);
- $('input[name=prefix]').val(groupPrefix);
- }
- $header.find('label').html(groupName).next().html(groupPrefix ? '('+groupPrefix+')' : '');
- _this.renderApiList();
- }
- })
- }
- },{
- name : '取消'
- }]
- })
- },
- // 创建分组
- createGroup : function(){
- var _this = MagicEditor;
- _this.setStatusBar('创建分组..');
- MagicEditor.createDialog({
- title : '创建分组',
- content : '<label>分组名称:</label><input type="text" name="name" autocomplete="off"/><div style="height:2px;"></div><label>分组前缀:</label><input type="text" name="prefix" autocomplete="off"/>',
- replace : false,
- buttons : [{
- name : '创建',
- click : function($dom){
- var groupName = $dom.find('input[name=name]').val();
- var groupPrefix = $dom.find('input[name=prefix]').val();
- if(!groupName){
- $dom.find('input[name=path]').focus();
- return false;
- }
- if(groupName.indexOf("'")!= -1 || groupName.indexOf('"') != -1){
- _this.alert('创建分组','分组名不能包含特殊字符 \' "');
- return false;
- }
- if(groupPrefix.indexOf("'")!= -1 || groupPrefix.indexOf('"') != -1){
- _this.alert('创建分组','分组前缀不能包含特殊字符 \' "');
- return false;
- }
- var exists = false;
- $('.group-header').each(function(){
- var name = $(this).find('label').text();
- if(name == groupName){
- exists = true;
- return false;
- }
- });
- if(exists){
- _this.setStatusBar('分组「'+groupName + '」');
- _this.alert('创建分组','分组已存在!');
- return false;
- }
- _this.addedGroups[groupName] = {
- groupName : groupName,
- groupPrefix : groupPrefix
- }
- _this.report('group_create');
- _this.setStatusBar('分组「'+groupName + '」创建成功');
- $('input[name=group]').next().append($('<li data-name="'+groupName+'" data-prefix="'+(groupPrefix || '')+'"/>').append(groupName));
- _this.renderApiList();
- }
- },{
- name : '取消'
- }]
- })
- },
- // 删除分组
- deleteGroup : function($header){
- var _this = MagicEditor;
- var groupName = $header.find('label').text();
- _this.setStatusBar('准备删除分组「'+groupName + '」');
- _this.createDialog({
- title : '删除接口分组',
- content : '是否要删除接口分组「'+groupName + '」',
- buttons : [{
- name : '删除',
- click : function(){
- _this.report('group_delete');
- var ids = [];
- $header.next().find('li').each(function(){
- ids.push($(this).data('id'));
- });
- _this.setStatusBar('准备删除接口分组「'+groupName + '」');
- delete _this.addedGroups[groupName];
- _this.ajax({
- url : 'group/delete',
- data : {
- apiIds : ids.join(','),
- groupName : groupName
- },
- success : function(){
- _this.setStatusBar('接口分组「'+groupName + '」已删除');
- _this.loadAPI(); //重新加载
- }
- })
- }
- },{
- name : '取消'
- }]
- })
- },
- report : function(eventId){
- try{
- MtaH5.clickStat(eventId);
- }catch(ignored){}
- },
- deleteApi : function($li){
- var text = $li.text();
- MagicEditor.createDialog({
- title : '删除接口',
- content : '是否要删除接口「'+text + '」',
- buttons : [{
- name : '删除',
- click : function(){
- MagicEditor.setStatusBar('准备删除接口');
- MagicEditor.report('script_delete')
- var apiId = $li.data('id');
- MagicEditor.ajax({
- url : 'delete',
- data : {
- id : apiId
- },
- success : function(){
- if(MagicEditor.apiId == apiId){
- MagicEditor.apiId = null;
- }
- MagicEditor.setStatusBar('接口「'+text + '」已删除');
- MagicEditor.loadAPI(); //重新加载
- }
- })
- }
- },{
- name : '取消'
- }]
- })
- },
- ajax : function(options){
- $.ajax({
- url : options.url,
- async : options.async,
- type : 'post',
- dataType : 'json',
- contentType : options.contentType,
- data : options.data,
- success : function(json,data,xhr){
- if(json.code == 1){
- options&&options.success(json.data,json,xhr);
- }else{
- var val = options.exception&&options.exception(json.code,json.message,json);
- if(val !== false){
- MagicEditor.alert('Error',json.message);
- }
- }
- },
- error : function(){
- MagicEditor.setStatusBar('ajax请求失败');
- MagicEditor.alert('网络错误','ajax请求失败');
- options.error&&options.error();
- }
- })
- },
- copyApi : function($li){
- var id = $li&&$li.data('id');
- id&&MagicEditor.confirm('复制接口','复制接口会清空当前编辑器,是否继续?',function(){
- MagicEditor.loadAPI(id,true);
- })
- },
- copyApiPath : function($li){
- var _this = MagicEditor;
- var path = $li&&$li.find('span').text();
- if(_this.config.web&&path){
- path = path.substring(1,path.length - 1);
- var prefix = $li.parent().prev().find('span').text() || '';
- if(prefix){
- prefix = prefix.substring(1,prefix.length - 1).replace(/(^\/+)|(\/+$)/g,'');
- }
- path = prefix + '/' + path.replace(/(^\/+)/g,'');
- if(_this.config&&_this.config.prefix){
- path = _this.config.prefix.replace(/(^\/+)|(\/+$)/g,'') + '/'+ path;
- }
- var host = location.href.substring(0,location.href.indexOf(_this.config.web)).replace(/(\/+$)/g,'');
- if(_this.config.prefix){
- host = host + '/' + _this.config.prefix.replace(/(^\/+)|(\/+$)/g,'');
- }
- path = host + '/' + path;
- try {
- var copyText = document.createElement('textarea');
- copyText.style = 'position:absolute;left:-99999999px';
- document.body.appendChild(copyText);
- copyText.innerHTML = path;
- copyText.readOnly = false;
- copyText.select();
- copyText.setSelectionRange(0, copyText.value.length);
- document.execCommand("copy");
- _this.alert('复制接口路径','复制成功');
- } catch (e) {
- _this.alert('复制接口路径失败,请手动赋值',path);
- }
- }
- },
- resetDebugContent : function(){
- $('.bottom-item-body table tbody').html('<tr><td colspan="3" align="center">no message.</td></tr>');
- },
- doContinue : function(step){
- if($('.button-continue').hasClass('disabled')){
- return;
- }
- if(this.debugSessionId){
- MagicEditor.resetDebugContent();
- $('.button-continue,.button-step-over').addClass('disabled');
- var _this = this;
- this.ajax({
- url : 'continue',
- data : {
- id : this.debugSessionId,
- breakpoints : _this.getBreakPoints().join(','),
- step : step ? '1' : '0'
- },
- success : function(data,json,xhr){
- _this.convertResult(json.code,json.message,json,xhr);
- },
- exception : function(code,message,json){
- return _this.convertResult(code,message,json);
- },
- error : function(){
- $('.button-run').removeClass('disabled');
- }
- })
- }
- },
- paddingZero : function(val){
- if(val < 10){
- return '0' + val;
- }
- return val.toString();
- },
- getTimeStr : function(date){
- var month = date.getMonth() + 1;
- var day = date.getDate();
- var hour = date.getHours();
- var minute = date.getMinutes();
- var seconds = date.getSeconds();
- return date.getFullYear() + '-' + this.paddingZero(month) + '-' + this.paddingZero(day) + ' ' + this.paddingZero(hour) + ':' + this.paddingZero(minute) + ':'+this.paddingZero(seconds);
- },
- appendLog : function(level,message,throwable){
- var $div = $('<div class="output-log-line level-'+level+'"/>')
- $div.append($('<div class="timestamp"/>').append(this.getTimeStr(new Date())));
- $div.append($('<div class="level"/>').append(level.toUpperCase()));
- var messages = message.replace(/ /g,' ').replace(/\t/g,' ').split('\n');
- $div.append($('<div class="message"/>').append(messages[0]));
- if(messages.length > 1){
- for(var i=1;i<messages.length;i++){
- $div.append($('<div class="message-line level-'+level+'" />').append(messages[i]));
- }
- }
- if(throwable){
- messages = throwable.replace(/ /g,' ').replace(/\t/g,' ').split('\n');
- for(var i=0;i<messages.length;i++){
- $div.append($('<div class="message-line level-'+level+'" />').append(messages[i]));
- }
- }
- if(!this.$output){
- this.$output = $('.bottom-container .bottom-item-body.output');
- }
- this.$output.append($div);
- this.$output.scrollTop(this.$output[0].scrollHeight);
- },
- createConsole : function(callback){
- var source = new EventSource('console');
- var _this = this;
- source.onerror = function(){
- source.close();
- }
- source.addEventListener('create',function(e){
- _this.navigateTo(4);
- callback&&callback(e.data);
- })
- source.addEventListener('close',function(e){
- source.close();
- })
- source.addEventListener('log',function(e){
- var data = JSON.parse(e.data);
- _this.appendLog(data.level,data.message,data.throwable);
- })
- },
- getBreakPoints : function(){
- var decorations = MagicEditor.scriptEditor.getModel().getAllDecorations();
- var breakpoints = [];
- for (var i=0,len =decorations.length;i<len;i++) {
- if (decorations[i].options.linesDecorationsClassName === 'breakpoints') {
- breakpoints.push(decorations[i].range.startLineNumber);
- }
- }
- return breakpoints;
- },
- doTest : function(){
- var _this = this;
- if($('.button-run').hasClass('disabled')){
- return;
- }
- var request = _this.requestEditor.getValue();
- try{
- request = JSON.parse(request);
- if(typeof request != 'object'){
- _this.setStatusBar('请求参数有误!');
- _this.alert('运行测试','请求参数有误!');
- return;
- }
- }catch(e){
- _this.setStatusBar('请求参数有误!');
- _this.alert('运行测试','请求参数有误!');
- return;
- }
- var options = _this.optionsEditor.getValue();
- try{
- options = JSON.parse(options);
- if(typeof options != 'object'){
- _this.setStatusBar('接口选项有误!');
- _this.alert('运行测试','接口选项有误!');
- return;
- }
- }catch(e){
- _this.setStatusBar('接口选项有误!');
- _this.alert('运行测试','接口选项有误!');
- return;
- }
- _this.setStatusBar('开始测试...');
- _this.createConsole(function(sessionId){
- _this.report('run');
- request.script = _this.scriptEditor.getValue();
- var breakpoints = _this.getBreakPoints();
- request.breakpoints = breakpoints;
- request.sessionId = sessionId;
- request.options = options;
- _this.resetDebugContent();
- $('.button-run').addClass('disabled');
- $('.button-continue,.button-step-over').addClass('disabled');
- _this.ajax({
- url : 'test',
- data : JSON.stringify(request),
- contentType : 'application/json;charset=utf-8',
- success : function(data,json,xhr){
- _this.convertResult(json.code,json.message,json,xhr);
- },
- exception : function(code,message,json){
- return _this.convertResult(code,message,json);
- },
- error : function(){
- $('.button-run').removeClass('disabled');
- }
- })
- });
- },
- doSave : function(){
- if($('.button-save').hasClass('disabled')){
- return;
- }
- $('.button-save').addClass('disabled');
- var name = $('input[name=name]').val();
- var path = $('input[name=path]').val();
- var method = $('input[name=method]').val();
- var groupName = $('input[name=group]').val();
- var groupPrefix = $('input[name=prefix]').val();
- this.setStatusBar('准备保存接口:' + name + "(" + path + ")");
- var _this = this;
- this.ajax({
- url : 'save',
- data : {
- script : this.scriptEditor.getValue(),
- path : path,
- method : method,
- id : this.apiId,
- groupName : groupName,
- groupPrefix : groupPrefix,
- parameter: this.requestEditor.getValue(),
- option: this.optionsEditor.getValue(),
- name : name,
- output : this.outputJson
- },
- async : false,
- exception : function(){
- $('.button-save').removeClass('disabled');
- },
- error : function(){
- $('.button-save').removeClass('disabled');
- },
- success : function(id){
- $('.button-save,.button-delete').removeClass('disabled');
- if(_this.apiId){
- _this.report('script_save');
- for(var i=0,len = _this.apiList.length;i<len;i++){
- if(_this.apiList[i].id == _this.apiId){
- _this.apiList[i].name = name;
- _this.apiList[i].path = path;
- _this.apiList[i].method = method;
- _this.apiList[i].groupName = groupName;
- break;
- }
- }
- }else{
- _this.report('script_add');
- _this.apiId = id;
- _this.apiList.unshift({
- id : id,
- name : name,
- path : path,
- method : method,
- groupName : groupName || '未分组',
- })
- }
- _this.setStatusBar('保存成功!');
- _this.loadAPI();
- }
- })
- },
- convertResult : function(code,message,json,xhr){
- this.debugSessionId = null;
- this.resetDebugContent();
- this.debugDecorations&&this.scriptEditor&&this.scriptEditor.deltaDecorations(this.debugDecorations,[]);
- this.debugDecorations = null;
- var _this = this;
- var ret = undefined;
- if(code === -1000){
- MagicEditor.setStatusBar('脚本执行出错..');
- MagicEditor.report('script_error');
- $(".button-run").removeClass('disabled');
- $('.button-continue,.button-step-over').addClass('disabled');
- this.navigateTo(2);
- if (json.body) {
- var line = json.body;
- var range = new monaco.Range(line[0], line[2], line[1], line[3] + 1);
- var decorations = this.scriptEditor&&this.scriptEditor.deltaDecorations([],[{
- range: range,
- options : {
- hoverMessage : {
- value : message
- },
- inlineClassName : 'squiggly-error',
- }
- }])
- this.scriptEditor.revealRangeInCenter(range);
- this.scriptEditor.focus();
- setTimeout(function(){
- _this.scriptEditor&&_this.scriptEditor.deltaDecorations(decorations,[])
- },10000)
- }
- ret = false;
- }else if(code === 1000){ // debug断点
- $(".button-run").addClass('disabled');
- $('.button-continue,.button-step-over').removeClass('disabled');
- this.navigateTo(3);
- this.debugIn(message, json.body);
- return false;
- }
- MagicEditor.setStatusBar('脚本执行完毕');
- $(".button-run").removeClass('disabled');
- $('.button-continue,.button-step-over').addClass('disabled');
- this.navigateTo(2)
- var outputJson;
- var contentType = xhr&&xhr.getResponseHeader('ma-content-type');
- if(contentType == 'application/octet-stream'){ //文件下载
- var disposition = xhr.getResponseHeader('ma-content-disposition');
- var filename = 'output';
- if(disposition){
- filename = decodeURIComponent(disposition.substring(disposition.indexOf('filename=') + 9));
- }
- outputJson = this.formatJson({
- filename : filename
- });
- var a = document.createElement("a");
- a.download = filename;
- var bstr = atob(json.data);
- var n = bstr.length;
- var u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- a.href = window.URL.createObjectURL(new Blob([u8arr]));
- a.click();
- MagicEditor.report('output_blob');
- }else if(contentType && contentType.indexOf('image') == 0){ //image开头
- outputJson = this.formatJson(json.data);
- this.createDialog({
- title : '图片结果',
- content : '<p align="center"><img src="data:'+contentType+';base64,'+json.data+'"></p>',
- replace : false,
- buttons : [{name : 'OK'}]
- })
- MagicEditor.report('output_image');
- }else{
- outputJson = this.formatJson(json.data);
- }
- this.outputJson = outputJson;
- this.resultEditor.setValue(outputJson);
- return ret;
- },
- debugIn : function(id,data){
- MagicEditor.setStatusBar('进入断点...');
- MagicEditor.report('debug_in');
- this.debugSessionId = id;
- if(data.variables.length > 0){
- var $tbody = $('.bottom-item-body table tbody').html('');
- for(var i =0,len = data.variables.length;i<len;i++){
- var item = data.variables[i];
- var $tr = $('<tr/>');
- $tr.append($('<td/>').html(item.name))
- $tr.append($('<td/>').html(item.value))
- $tr.append($('<td/>').html(item.type))
- $tbody.append($tr);
- }
- }else{
- this.resetDebugContent();
- }
- this.debugDecorations = [this.scriptEditor&&this.scriptEditor.deltaDecorations([],[{
- range : new monaco.Range(data.range[0],1,data.range[0],1),
- options: {
- isWholeLine: true,
- inlineClassName : 'debug-line',
- className : 'debug-line',
- }
- }])];
- },
- backupInterval : function(){
- var _this = this;
- var info = _this.getValue('api_info');
- if(info){
- info = JSON.parse(info);
- _this.apiId = info.id;
- $('input[name=name]').val(info.name || '');
- $('input[name=path]').val(info.path || '');
- $('input[name=method]').val(info.method || '');
- $('input[name=group]').val(info.groupName || '');
- $('input[name=prefix]').val(info.groupPrefix || '');
- _this.scriptEditor&&_this.scriptEditor.setValue(info.script || 'return message;');
- _this.requestEditor&&_this.requestEditor.setValue(info.parameters || _this.defaultRequestValue);
- _this.options&&_this.options.setValue(info.options || '{\r\n}');
- _this.output&&_this.output.setValue(info.options || '');
- }
- setInterval(function(){
- _this.setValue('api_info',{
- id : _this.apiId,
- name : $('input[name=name]').val(),
- path : $('input[name=path]').val(),
- method : $('input[name=method]').val(),
- groupName : $('input[name=group]').val(),
- groupPrefix : $('input[name=prefix]').val(),
- script : _this.scriptEditor&&_this.scriptEditor.getValue(),
- parameters : _this.requestEditor&&_this.requestEditor.getValue(),
- options : _this.optionsEditor&&_this.optionsEditor.getValue(),
- output: _this.outputEditor&&_this.outputEditor.getValue()
- })
- },5000)
- },
- // 初始化快捷键
- initShortKey : function(){
- var _this = this;
- $('body').on('keydown',function(e){
- if(e.keyCode == 119){ //F8
- _this.doContinue();
- e.preventDefault();
- }else if(e.keyCode == 117){ //F6
- _this.doContinue(true);
- e.preventDefault();
- }else if(e.keyCode == 81 && (e.metaKey || e.ctrlKey)){ //Ctrl + Q
- _this.doTest();
- e.preventDefault();
- }else if(e.keyCode == 83 && (e.metaKey || e.ctrlKey)){ //Ctrl + S
- _this.doSave();
- e.preventDefault();
- }else if(e.keyCode == 78 && e.altKey){ //Alt + N
- _this.createNew();
- e.preventDefault();
- }else if(e.keyCode == 71 && e.altKey){ //Alt + G
- _this.createGroup();
- e.preventDefault();
- }else if(e.keyCode == 27 || e.keyCode == 13){ //Enter or Esc
- $('.dialog-wrapper').remove();
- }
- })
- },
- //检测更新
- checkUpdate : function(){
- var _this = this;
- var ignoreVersion = this.getValue('ignore-version');
- $.ajax({
- url : 'https://img.shields.io/maven-central/v/org.ssssssss/magic-api.json',
- dataType : 'json',
- success : function(data){
- if(data.value != 'v0.3.4'){
- if(ignoreVersion != data.value){
- _this.createDialog({
- title : '更新提示',
- content : '检测到已有新版本'+data.value+',是否更新?',
- buttons : [{
- name : '更新日志',
- click : function(){
- _this.setValue('ignore-version',data.value)
- window.open('http://www.ssssssss.org/changelog.html')
- }
- },{
- name : '残忍拒绝',
- click : function(){
- _this.setValue('ignore-version',data.value)
- }
- }]
- })
- }
- MagicEditor.setStatusBar('版本检测完毕,最新版本为:' + data.value+',建议更新!!');
- }else{
- MagicEditor.setStatusBar('版本检测完毕,当前已是最新版');
- }
- },
- error : function(){
- MagicEditor.setStatusBar('版本检测失败');
- }
- })
- },
- alert : function(title,content){
- this.createDialog({
- title : title,
- content : content,
- buttons : [{name : 'OK'}]
- });
- },
- confirm : function(title,content,callback){
- this.createDialog({
- title : title,
- content : content,
- buttons : [{name : '确定',click : function(){callback&&callback();}},{name : '取消'}]
- });
- },
- doShowHistory : function(){
- if(!this.apiId){
- this.alert('历史记录','请选择接口后在查看历史记录');
- return;
- }
- var _this = this;
- var apiId = this.apiId;
- var name = $('input[name=name]').val();
- var scriptModel = monaco.editor.createModel(this.scriptEditor.getValue(),'magicscript');
- _this.report('history_view');
- this.ajax({
- url : 'backups',
- data : {
- id : apiId
- },
- success : function(timestamps){
- if(timestamps.length == 0){
- _this.alert('历史记录','暂无历史记录信息');
- return;
- }
- var $ul = $('<ul class="not-select"/>')
- for(var i=0,len = timestamps.length;i<len;i++){
- var timestamp = timestamps[i];
- var timeStr = _this.getTimeStr(new Date(timestamp));
- $ul.append($('<li/>').attr('data-timestamp',timestamp).attr('data-id',apiId).append(timeStr))
- }
- var html = $ul[0].outerHTML;
- html+= '<div class="version"><span class="version-time"></span><span class="current">当前版本</span></div>'
- html += '<div class="diff-editor"></div>';
- _this.setStatusBar('查看历史记录:' + (name || ''));
- _this.createDialog({
- title : '历史记录:' + (name || ''),
- content : html,
- replace : false,
- className : 'history-list',
- buttons : [{
- name : '恢复',
- click : function(){
- _this.scriptEditor.setValue(scriptModel.getValue());
- _this.report('history_revert');
- _this.setStatusBar('恢复历史记录:' + (name || ''));
- }
- },{
- name : '取消'
- }],
- close : function(){
- _this.diffEditor = null;
- },
- onCreate : function($dom){
- _this.diffEditor = monaco.editor.createDiffEditor($dom.find('.diff-editor')[0], {
- enableSplitViewResizing: false,
- minimap : {
- enabled : false
- },
- folding : false,
- lineDecorationsWidth : 20,
- fixedOverflowWidgets :false
- });
- _this.diffEditor.setModel({
- original : scriptModel,
- modified : scriptModel
- });
- var $version = $dom.find('.version-time');
- $dom.on('click','ul li[data-timestamp]',function(){
- $(this).addClass('selected').siblings().removeClass('selected');
- var timestamp = $(this).data('timestamp');
- $version.html($(this).text());
- _this.ajax({
- url : 'backup/get',
- data : {
- id : apiId,
- timestamp : timestamp
- },
- success : function(info){
- _this.diffEditor.setModel({
- original : monaco.editor.createModel(info.script,'magicscript'),
- modified : scriptModel
- });
- }
- })
- })
- }
- })
- }
- })
- },
- //初始化右键菜单
- initContextMenu : function(){
- var _this = this;
- $('.api-list-container').on('contextmenu','.group-header',function(e){
- _this.createContextMenu([{
- name : '新建接口',
- shortKey : 'Alt+N',
- click : _this.createNew
- },{
- name : '刷新接口',
- shortKey : '',
- click : function (){_this.loadAPI()}
- },{
- name : '删除组',
- shortKey : '',
- click : _this.deleteGroup
- },{
- name : '新建分组',
- shortKey : 'Alt+G',
- click : _this.createGroup
- },{
- name : '修改分组',
- shortKey : '',
- click : _this.updateGroup
- }],e.pageX,e.pageY,$(this));
- return false;
- }).on('contextmenu','.group-list li',function(e){
- var $li = $(this);
- _this.createContextMenu([{
- name : '复制接口',
- shortKey : '',
- click : _this.copyApi,
- },{
- name : '复制路径',
- shortKey : '',
- click : _this.copyApiPath
- },{
- name : '刷新接口',
- shortKey : '',
- click : function (){_this.loadAPI()}
- },{
- name : '移动',
- shortKey : 'Ctrl+M',
- click : function(){
- _this.alert('移动接口','功能暂未实现!');
- }
- },{
- name : '删除接口',
- shortKey : '',
- click : _this.deleteApi
- },{
- name : '新建分组',
- shortKey : 'Alt+G',
- click : _this.createGroup
- }],e.pageX,e.pageY,$li)
- return false;
- }).on('contextmenu',function(e){
- _this.createContextMenu([{
- name : '新建分组',
- shortKey : 'Alt+G',
- click : _this.createGroup
- }],e.pageX,e.pageY,$(this));
- return false;
- })
- },
- initSelect : function(){
- var _this = this;
- $('body').on('click','.select',function(){
- $('.select ul').hide();
- $(this).find('ul').show();
- return false;
- }).on('click','.select ul li',function(){
- var $this = $(this);
- var prefix = $this.data('prefix');
- if(prefix !== undefined){
- $('input[name=prefix]').val(prefix || '');
- }
- $this.parent().hide().parent().find('input').val($this.text());
- $this.addClass('selected').siblings().removeClass('selected');
- return false;
- }).on('click',function(){
- $('.select ul').hide();
- }).on('click','.api-list-container ul li',function(){
- $('.api-list-container ul li.selected').removeClass('selected');
- _this.loadAPI($(this).addClass('selected').data('id'))
- }).on('click','.button-run',function(){
- _this.doTest();
- }).on('click','.button-history',function(){
- _this.doShowHistory();
- }).on('click','.button-delete',function(){
- if($(this).hasClass('disabled')){
- return;
- }
- if(_this.apiId){
- var $li = $('.group-list li[data-id='+_this.apiId+']');
- if($li.length > 0){
- _this.deleteApi($li);
- }
- }
- }).on('click','.button-save',function(){
- _this.doSave();
- }).on('click','.button-continue',function(){
- _this.doContinue();
- }).on('click','.button-step-over',function(){
- _this.doContinue(true);
- }).on('click','.button-gitee',function(){
- MagicEditor.report('button-gitee');
- window.open('https://gitee.com/ssssssss-team/magic-api');
- }).on('click','.button-github',function(){
- MagicEditor.report('button-github');
- window.open('https://github.com/ssssssss-team/magic-api')
- }).on('click','.button-qq',function(){
- window.open('https://shang.qq.com/wpa/qunwpa?idkey=10faa4cf9743e0aa379a72f2ad12a9e576c81462742143c8f3391b52e8c3ed8d')
- }).on('click','.button-help',function(){
- MagicEditor.report('button-help');
- window.open('https://ssssssss.org')
- });
- },
- getValue : function(key){
- return localStorage&&localStorage.getItem(key) || '';
- },
- setValue : function(key,value){
- if(Array.isArray(value) || typeof value == 'object'){
- value = JSON.stringify(value);
- }
- localStorage&&localStorage.setItem(key,value) || '';
- },
- removeValue : function(key){
- localStorage&&localStorage.removeItem(key);
- },
- bindEditorShortKey : function(editor){
- // Alt + / 代码提示
- editor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.US_SLASH,function(){
- editor.trigger(null, 'editor.action.triggerSuggest', {})
- },'!findWidgetVisible && !inreferenceSearchEditor && !editorHasSelection');
- // Ctrl + Shift + U 转大写
- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_U,function(){
- editor.trigger(null, 'editor.action.transformToUppercase', {})
- });
- // Ctrl + Shift + X 转小写
- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_X,function(){
- editor.trigger(null, 'editor.action.transformToLowercase', {})
- });
- // Ctrl + Alt + L 代码格式化
- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_L,function(){
- editor.trigger(null, 'editor.action.formatDocument', {})
- },'editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly');
- // Ctrl + Alt + L 选中代码格式化
- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_L,function(){
- editor.trigger(null, 'editor.action.formatSelection', {})
- },'editorHasDocumentFormattingProvider && editorHasSelection && editorTextFocus && !editorReadonly');
- },
- // 初始化脚本编辑器
- initScriptEditor : function(){
- this.ajax({
- url: 'classes',
- async : false,
- success: function (data) {
- data = data || {};
- Parser.scriptClass = data.classes || {};
- Parser.extensions = data.extensions || {};
- }
- })
- $.get('classes.txt',function(txt){
- Parser.importClass = txt.split('\r\n');
- })
- monaco.editor.defineTheme('default', {
- base: 'vs',
- inherit: true,
- rules: [
- { background: '#ffffff' },
- { token: 'keywords', foreground: '000080',fontStyle : 'bold'},
- { token: 'number', foreground: '0000FF' },
- { token: 'keyword', foreground: '000080',fontStyle : 'bold'},
- { token: 'string.sql', foreground: '000000'},
- { token: 'predefined.sql', foreground: '000000'},
- { token: 'operator.sql', foreground: '000080',fontStyle : 'bold'},
- { token: 'key', foreground: '660E7A' },
- { token: 'string.key.json', foreground: '660E7A' },
- { token: 'string.value.json', foreground: '008000' },
- { token: 'keyword.json', foreground: '0000FF' },
- { token: 'string', foreground: '008000',fontStyle : 'bold' },
- { token: 'string.invalid', foreground: '008000' ,background : 'FFCCCC'},
- { token: 'string.escape.invalid', foreground: '008000' ,background : 'FFCCCC'},
- { token: 'string.escape', foreground: '000080',fontStyle : 'bold'},
- { token: 'comment', foreground: '808080'},
- { token: 'comment.doc', foreground: '808080'},
- { token: 'string.escape', foreground: '000080'}
- ],
- colors: {
- 'editor.foreground': '#000000',
- 'editor.background': '#ffffff',
- // 'editor.lineHighlightBorder' : '#00000000',
- 'editorLineNumber.foreground': '#999999', //行号的颜色
- 'editorGutter.background' : '#f0f0f0', //行号背景色
- 'editor.lineHighlightBackground' : '#FFFAE3', //光标所在行的颜色
- 'dropdown.background' : '#F2F2F2', //右键菜单
- 'dropdown.foreground' : '#000000', //右键菜单文字颜色
- 'list.activeSelectionBackground': '#1A7DC4', //右键菜单悬浮背景色
- 'list.activeSelectionForeground' : '#ffffff', //右键菜单悬浮文字颜色
- }
- });
- monaco.editor.defineTheme('dark', {
- base: 'vs-dark',
- inherit: true,
- rules: [
- { foreground: 'A9B7C6' },
- { token: 'keywords', foreground: 'CC7832',fontStyle : 'bold'},
- { token: 'keyword', foreground: 'CC7832',fontStyle : 'bold'},
- { token: 'number', foreground: '6897BB' },
- { token: 'string', foreground: '6A8759',fontStyle : 'bold' },
- { token: 'string.sql', foreground: 'A9B7C6'},
- { token: 'predefined.sql', foreground: 'A9B7C6'},
- { token: 'key', foreground: '9876AA' },
- { token: 'string.key.json', foreground: '9876AA' },
- { token: 'string.value.json', foreground: '6A8759' },
- { token: 'keyword.json', foreground: '6897BB' },
- { token: 'operator.sql', foreground: 'CC7832',fontStyle : 'bold'},
- { token: 'string.invalid', foreground: '008000' ,background : 'FFCCCC'},
- { token: 'string.escape.invalid', foreground: '008000' ,background : 'FFCCCC'},
- { token: 'string.escape', foreground: '000080',fontStyle : 'bold'},
- { token: 'comment', foreground: '808080'},
- { token: 'comment.doc', foreground: '629755'},
- { token: 'string.escape', foreground: 'CC7832'}
- ],
- colors: {
- 'editor.background': '#2B2B2B',
- // 'editor.lineHighlightBorder' : '#00000000',
- 'editorLineNumber.foreground': '#999999', //行号的颜色
- 'editorGutter.background' : '#313335', //行号背景色
- 'editor.lineHighlightBackground' : '#323232', //光标所在行的颜色
- 'dropdown.background' : '#3C3F41', //右键菜单
- 'dropdown.foreground' : '#BBBBBB', //右键菜单文字颜色
- 'list.activeSelectionBackground': '#4B6EAF', //右键菜单悬浮背景色
- 'list.activeSelectionForeground' : '#FFFFFF', //右键菜单悬浮文字颜色
- }
- });
- var theme = this.getValue('skin') || 'default';
- this.report('theme_' + theme);
- this.scriptEditor = monaco.editor.create($('.editor-container')[0], {
- minimap : {
- enabled : false
- },
- language: 'magicscript',
- folding : false,
- lineDecorationsWidth : 35,
- theme : theme,
- })
- this.requestEditor = monaco.editor.create($('.request-editor')[0], {
- value: "{}",
- minimap : {
- enabled : false
- },
- language: 'json',
- folding : false,
- fixedOverflowWidgets :true,
- theme : theme
- })
- this.optionsEditor = monaco.editor.create($('.options-editor')[0], {
- value: "{}",
- minimap : {
- enabled : false
- },
- language: 'json',
- folding : false,
- fixedOverflowWidgets :true,
- theme : theme
- })
- this.resultEditor = monaco.editor.create($('.result-editor')[0], {
- value: "{}",
- minimap : {
- enabled : false
- },
- language: 'json',
- folding : false,
- readOnly : true,
- fixedOverflowWidgets : true,
- theme : theme
- })
- var _this = this;
- this.scriptEditor.onMouseDown(function(e){
- if (e.target.detail && e.target.detail.offsetX && e.target.detail.offsetX >= 0 && e.target.detail.offsetX <= 60) {
- var line = e.target.position.lineNumber;
- if (_this.scriptEditor.getModel().getLineContent(line).trim() === '') {
- return
- }
- if(_this.hasBreakPoint(line)){
- _this.removeBreakPoint(line);
- }else{
- _this.addBreakPoint(line);
- }
- }
- });
- this.bindEditorShortKey(this.scriptEditor);
- this.bindEditorShortKey(this.requestEditor);
- this.bindEditorShortKey(this.optionsEditor);
- },
- navigateTo : function(index){
- var $parent = $('.bottom-container');
- var $dom = $parent.find('.bottom-content-container').show();
- $parent.find('.bottom-tab li').eq(index).addClass('selected').siblings().removeClass('selected');
- $dom.find('.bottom-content-item').eq(index).show().siblings('.bottom-content-item').hide();
- this.layout();
- },
- createDialog : function(options){
- options = options || {};
- var $dialog = $('<div/>').addClass('dialog');
- if(options.className){
- $dialog.addClass(options.className);
- }
- var $header = $('<div/>').addClass('dialog-header').addClass('not-select').append(options.title || '');
- var $close = $('<span/>').append('<i class="iconfont icon-close"></i>');
- $header.append($close);
- $close.on('click',function(){
- options.close&&options.close();
- $wrapper.remove();
- })
- $dialog.append($header);
- var content = options.content || '';
- if(options.replace !== false){
- content = content.replace(/\n/g,'<br>').replace(/ /g,' ').replace(/\t/g,' ');
- }
- $dialog.append('<div class="dialog-content">' + content + '</div>');
- var buttons = options.buttons || [];
- var $buttons = $('<div/>').addClass('dialog-buttons').addClass('not-select');
- if(buttons.length > 1){
- $buttons.addClass('button-align-right');
- }
- for(var i=0,len = buttons.length;i<len;i++){
- var button = buttons[i];
- $buttons.append($('<button/>').html(button.name || '').addClass(button.className || '').addClass(i == 0 ? 'active' : ''));
- }
- $dialog.append($buttons);
- var $wrapper = $('<div/>').addClass('dialog-wrapper').append($dialog);
- $buttons.on('click','button',function(){
- var index = $(this).index();
- if(buttons[index].click&&buttons[index].click($dialog) === false){
- return;
- }
- options.close&&options.close();
- $wrapper.remove();
- })
- $('body').append($wrapper);
- options.onCreate&&options.onCreate($wrapper);
- },
- createContextMenu : function(menus,left,top,$dom){
- $('.context-menu').remove();
- var $ul = $('<ul/>').addClass('context-menu').addClass('not-select');
- for(var i=0,len = menus.length;i<len;i++){
- var menu = menus[i];
- $ul.append($('<li/>').append('<label>'+menu.name+'</label>').append('<span>'+(menu.shortKey || '')+'<span>'));
- }
- $ul.on('click','li',function(){
- var menu = menus[$(this).index()]
- menu&&menu.click&&menu.click($dom);
- });
- $ul.css({
- left : left + 'px',
- top : top + 'px'
- })
- $('body').append($ul).on('click',function(){
- $ul.remove();
- });
- },
- // 初始化左侧工具条
- initLeftToobarContainer : function(){
- var $apiContainr = $('.api-list-container');
- var value = this.getValue('left-toolbar-width');
- if(value && !isNaN(Number(value))){
- $apiContainr.width(value);
- }
- if('false' == this.getValue('left-toolbar-show')){
- $('.left-toolbar-container li').removeClass('selected');
- $apiContainr.hide();
- }
- var _this = this;
- $('.left-toolbar-container').on('click','li',function(){
- var $this = $(this);
- if($this.hasClass('selected')){ //当前是选中状态
- $this.removeClass('selected');
- _this.setValue('left-toolbar-show',false);
- $apiContainr.hide();
- }else{
- $this.addClass('selected');
- _this.setValue('left-toolbar-show',true);
- $apiContainr.show();
- }
- _this.layout();
- })
- var $middleContainer = $('.middle-container');
- // 调整宽度
- var resizer = $middleContainer.find('.resizer-x')[0];
- resizer.onmousedown = function(){
- var box = $apiContainr[0].getClientRects()[0];
- document.onmousemove = function(e){
- var move = e.clientX - 22;
- if(move > 150 && move < 700){
- _this.layout();
- _this.setValue('left-toolbar-width',move);
- $apiContainr.width(move);
- }
- }
- document.onmouseup = function(evt){
- document.onmousemove = null;
- document.onmouseup = null;
- resizer.releaseCapture && resizer.releaseCapture();
- }
- resizer.setCapture && resizer.setCapture();
- }
- $('body').on('click','.group-header',function(){
- var $parent = $(this).parent();
- if($parent.hasClass('opened')){
- $parent.removeClass('opened');
- $(this).find('.icon-arrow-bottom').removeClass('icon-arrow-bottom').addClass('icon-arrow-right');
- }else{
- $parent.addClass('opened');
- $(this).find('.icon-arrow-right').removeClass('icon-arrow-right').addClass('icon-arrow-bottom');
- }
- })
- },
- formatJson : function (val, defaultVal) {
- return (val ? JSON.stringify(val, null, 4) : defaultVal) || '';
- },
- // 初始化底部
- initBottomContainer : function(){
- var $contentContainer = $('.bottom-container .bottom-content-container');
- var value = this.getValue('bottom-container-height');
- if(value && !isNaN(Number(value))){
- $contentContainer.height(value);
- }
- if('false' == this.getValue('bottom-tab-show')){
- $contentContainer.hide(); //隐藏全部
- $('.bottom-container .bottom-tab li').removeClass('selected');
- }else{
- var index = Number(this.getValue('bottom-tab-index'));
- if(!isNaN(index)){
- this.navigateTo(index);
- }
- }
- var _this = this;
- $('.bottom-container').on('click','.bottom-tab li',function(){
- var $this = $(this);
- if($this.hasClass('selected')){ //当前是选中状态
- $contentContainer.hide(); //隐藏全部
- $this.removeClass('selected')
- _this.setValue('bottom-tab-show',true);
- }else{
- $this.addClass('selected').siblings().removeClass('selected'); //选中选择项,取消其他选择项
- var index = $(this).index();
- _this.setValue('bottom-tab-index',index);
- _this.setValue('bottom-tab-show',true);
- $contentContainer.show().find('.bottom-content-item').hide().eq(index).show();
- }
- _this.layout();
- }).on('click','.button-minimize',function(){
- _this.setValue('bottom-tab-show',false);
- $contentContainer.hide(); //隐藏全部
- $('.bottom-tab li').removeClass('selected');
- _this.layout();
- });
- // 调整底部高度
- var resizer = $contentContainer.find('.resizer-y')[0];
- resizer.onmousedown = function(){
- var box = $contentContainer[0].getClientRects()[0];
- document.onmousemove = function(e){
- if(e.clientY > 150){
- var move = box.height - (e.clientY - box.y);
- if(move > 30){
- _this.setValue('bottom-container-height',move);
- _this.layout();
- $contentContainer.height(move);
- }
- }
- }
- document.onmouseup = function(evt){
- document.onmousemove = null;
- document.onmouseup = null;
- resizer.releaseCapture && resizer.releaseCapture();
- }
- resizer.setCapture && resizer.setCapture();
- }
- $('.bottom-container').on('click','.bottom-content-item:eq(0) .button-clear',function(){
- _this.requestEditor&&_this.requestEditor.setValue('{}');
- }).on('click','.bottom-content-item:eq(0) .button-format',function(){
- try{
- _this.requestEditor.setValue(_this.formatJson(JSON.parse(_this.requestEditor.getValue()),'{\r\n}'));
- }catch(e){}
- }).on('click','.bottom-content-item:eq(1) .button-clear',function(){
- _this.optionsEditor&&_this.optionsEditor.setValue('{}');
- }).on('click','.bottom-content-item:eq(1) .button-format',function(){
- try{
- _this.optionsEditor.setValue(_this.formatJson(JSON.parse(_this.optionsEditor.getValue()),'{\r\n}'));
- }catch(e){}
- }).on('click','.bottom-content-item:eq(2) .button-clear',function(){
- _this.resultEditor&&_this.resultEditor.setValue('{}');
- }).on('click','.bottom-content-item:eq(2) .button-format',function(){
- try{
- _this.resultEditor.setValue(_this.formatJson(JSON.parse(_this.resultEditor.getValue()),'{\r\n}'));
- }catch(e){}
- }).on('click','.bottom-content-item:eq(4) .button-clear',function(){
- $('.bottom-container .bottom-item-body.output').html('')
- })
- },
- setSkin : function(skin){
- $('body').addClass('skin-' + skin);
- this.setValue('skin',skin);
- monaco.editor.setTheme(skin);
- MagicEditor.report('theme_' + skin);
- MagicEditor.setStatusBar('切换皮肤至:' + skin);
- //this.scriptEditor&&this.scriptEditor.setTheme(skin);
- },
- layout : function(){
- this.scriptEditor&&this.scriptEditor.layout();
- this.optionsEditor&&this.optionsEditor.layout();
- this.requestEditor&&this.requestEditor.layout();
- this.resultEditor&&this.resultEditor.layout();
- this.diffEditor&&this.diffEditor.layout();
- }
- }
- $(function(){
- require(['vs/editor/editor.main'],function(){
- MagicEditor.init();
- $('.loading-wrapper').remove();
- })
- $(window).resize(function(){
- MagicEditor.layout();
- });
- });
|