diff --git a/.babelrc b/.babelrc index 5839401..6c7b08b 100644 --- a/.babelrc +++ b/.babelrc @@ -1,5 +1,7 @@ { - "presets": ["env", "react"], - "plugins": ["transform-class-properties" + "presets": [["@babel/preset-env", {"targets": "defaults" }], "@babel/preset-react"], + "plugins": [ + "@babel/plugin-syntax-dynamic-import", + "@babel/plugin-proposal-class-properties" ] } \ No newline at end of file diff --git a/dist/main.css b/dist/main.css deleted file mode 100644 index dba0692..0000000 --- a/dist/main.css +++ /dev/null @@ -1,187 +0,0 @@ -@charset "utf-8"; - -/* 设置滚动条的样式 */ -::-webkit-scrollbar { - width: 6px; -} -/* 外层轨道 */ -::-webkit-scrollbar-track { - -webkit-box-shadow: inset006pxrgba(255,0,0,0.3); - - background: rgba(255, 255, 255, 0.1); -} -/* 滚动条滑块 */ -::-webkit-scrollbar-thumb { - border-radius: 4px; - background: rgba(0,0,0,0.2); - -webkit-box-shadow: inset006pxrgba(0,0,0,0.5); -} -::-webkit-scrollbar-thumb:window-inactive { - background: rgba(0,0,0,0.2); -} - -.json-schema-react-editor { - font-size: 14px; -} - -.json-schema-react-editor .array-item-type { - text-align: left -} - - - -.json-schema-react-editor .add-btn { - margin: 8px; -} - -.json-schema-react-editor .pretty-editor{ - border: 1px solid #d9d9d9; - border-radius: 4px; - height: 800px; -} - -.json-schema-react-editor .import-json-button{ - margin: 5px; -} - -.json-schema-react-editor .certain-category-search .ant-select-selection--single { - height: 32px; -} - -.json-schema-react-editor .certain-category-search .ant-select-search__field__wrap { - display: unset; -} -.json-schema-react-editor .option-formStyle{ - /* padding-left: 25px; */ - padding-Top: 8px -} - -.json-schema-react-editor .required-icon { - font-size: 1em; - color: red; - font-weight: bold; - padding-left: 5px -} - -.json-schema-react-editor .object-style { - /* border-left: 2px dotted gray; */ - /* padding-left: 8px; */ - padding-top: 6px; - /* margin-left: 20px; */ - margin-top: 8px; -} - - - -.json-schema-react-editor .col-item-type{ - text-align: center -} - -.json-schema-react-editor .down-style { - cursor: pointer; -} - - -.json-schema-react-editor .col-item-desc{ - text-align: center -} - -.json-schema-react-editor .col-item-mock{ - text-align: center; - padding-right: 6px; -} - -.json-schema-react-editor .col-item-setting{ - padding-left: 6px; - cursor: pointer; -} - -.json-schema-react-editor .plus { - color: #2395f1 -} - -.json-schema-react-editor .close { - color: #ff561b -} - -.json-schema-react-editor .array-type { - margin-top: 8px; -} - -.json-schema-react-editor .delete-item { - padding-right: 8px; -} - -.json-schema-react-editor .object-style .name-item .ant-input-group-addon { - background-color: unset; - border: unset; -} - -.json-schema-react-editor .object-style .name-item .ant-input-group > .ant-input:first-child, .ant-input-group-addon:first-child { - border-bottom-right-radius: 4px; - border-top-right-radius: 4px; -} - -.json-schema-react-editor .icon-object { - color: #0d1b3ea6; - font-weight: 400; - font-size: 10px; -} - -.json-schema-react-editor .down-style-col{ - width: 10px; -} - - - -.json-schema-react-editor .wrapper{ - padding-left: 8px; -} - -/* .schema-content { - margin-left: 20px; -} */ - -.json-schema-react-editor .adv-set { - padding-right: 8px; - color: #00a854; -} - -.json-schema-react-editor .type-select-style { - width: 90% -} - -.json-schema-react-editor-import-modal .ant-tabs-nav .ant-tabs-tab{ - height: auto -} - -.json-schema-react-editor-adv-modal .other-row { - margin-bottom: 16px; -} - -.json-schema-react-editor-adv-modal .other-label { - text-align: right; - padding-right: 8px; -} - -.json-schema-react-editor-adv-modal .default-setting { - font-size: 16px; - font-weight: 400; - margin-bottom: 16px; - border-left: 3px solid #2395f1; - padding-left: 8px; -} - -.json-schema-react-editor-adv-modal .ant-modal-body{ - min-height: 400px; -} - -.json-schema-react-editor-adv-modal .ant-modal-body .ace_editor { - min-height: 350px; -} - -.json-schema-react-editor-adv-modal-select .format-items-title { - color: #999; - position: absolute; - right: 16px; -} diff --git a/dist/main.js b/dist/main.js deleted file mode 100644 index d9ea5a8..0000000 --- a/dist/main.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("prop-types"),require("underscore"),require("antd"),require("react-redux"),require("react-dom"),require("brace"),require("moox")):"function"==typeof define&&define.amd?define(["react","prop-types","underscore","antd","react-redux","react-dom","brace","moox"],t):"object"==typeof exports?exports.schema=t(require("react"),require("prop-types"),require("underscore"),require("antd"),require("react-redux"),require("react-dom"),require("brace"),require("moox")):e.schema=t(e.React,e[void 0],e._,e[void 0],e[void 0],e.ReactDom,e.ace,e[void 0])}(window,function(e,t,n,r,o,a,i,l){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/dist/",n(n.s=10)}([function(t,n){t.exports=e},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.JSONPATH_JOIN_CHAR=".",t.lang="en_US",t.format=[{name:"date-time"},{name:"date"},{name:"email"},{name:"hostname"},{name:"ipv4"},{name:"ipv6"},{name:"uri"}];n(3);function o(e,t){if("object"===e.type){var n=function(e){var t=[];return Object.keys(e).map(function(e){t.push(e)}),t}(e.properties);t?e.required=[].concat(n):delete e.required,function(e,t){for(var n in e)"array"!==e[n].type&&"object"!==e[n].type||o(e[n],t)}(e.properties,t)}else{if("array"!==e.type)return e;o(e.items,t)}}t.SCHEMA_TYPE=["string","number","array","object","boolean","integer"],t.defaultSchema={string:{type:"string"},number:{type:"number"},array:{type:"array",items:{type:"string"}},object:{type:"object",properties:{}},boolean:{type:"boolean"},integer:{type:"integer"}},t.debounce=function(e,t){var n=void 0;return function(){clearTimeout(n),n=setTimeout(e,t)}},t.getData=function(e,t){for(var n=e,r=0;r0&&void 0!==arguments[0]?arguments[0]:{};e.lang&&(l.default.lang=e.lang);var t=(0,s.default)({schema:c.default});e.format?t.__jsonSchemaFormat=e.format:t.__jsonSchemaFormat=l.default.format,e.mock&&(t.__jsonSchemaMock=e.mock);var n=t.getStore(),d=function(e){return o.default.createElement(a.Provider,{store:n,className:"wrapper"},o.default.createElement(i.default,r({Model:t},e)))};return d.propTypes={data:u.default.string,onChange:u.default.func,showEditor:u.default.bool},d}},function(e,t){e.exports=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;nc)break;var u=this.getFoldWidgetRange(e,"all",t);if(u){if(u.start.row<=a)break;if(u.isMultiLine())t=u.end.row;else if(r==c)break}l=t}}return new o(a,i,l,e.getLine(l).length)},this.getCommentRegionBlock=function(e,t,n){for(var r=t.search(/\s*$/),a=e.getLength(),i=n,l=/^\s*(?:\/\*|\/\/|--)#?(end)?region\b/,s=1;++ni)return new o(i,r,n,t.length)}}.call(i.prototype)}),ace.define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"],function(e,t,r){"use strict";var o=e("../lib/oop"),a=e("./text").Mode,i=e("./json_highlight_rules").JsonHighlightRules,l=e("./matching_brace_outdent").MatchingBraceOutdent,s=e("./behaviour/cstyle").CstyleBehaviour,c=e("./folding/cstyle").FoldMode,u=e("../worker/worker_client").WorkerClient,d=function(){this.HighlightRules=i,this.$outdent=new l,this.$behaviour=new s,this.foldingRules=new c};o.inherits(d,a),function(){this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t);"start"==e&&(t.match(/^.*[\{\(\[]\s*$/)&&(r+=n));return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.createWorker=function(e){var t=new u(["ace"],n(16),"JsonWorker");return t.attachToDocument(e.getDocument()),t.on("annotate",function(t){e.setAnnotations(t.data)}),t.on("terminate",function(){e.clearAnnotations()}),t},this.$id="ace/mode/json"}.call(d.prototype),t.Mode=d})},function(e,t){e.exports.id="ace/mode/json_worker",e.exports.src='"no use strict";(function(window){function resolveModuleId(id,paths){for(var testPath=id,tail="";testPath;){var alias=paths[testPath];if("string"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,"/")+(tail||alias.main||alias.name);if(alias===!1)return"";var i=testPath.lastIndexOf("/");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:"error",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf("!")){var chunks=moduleName.split("!");return window.normalizeModule(parentId,chunks[0])+"!"+window.normalizeModule(parentId,chunks[1])}if("."==moduleName.charAt(0)){var base=parentId.split("/").slice(0,-1).join("/");for(moduleName=(base?base+"/":"")+moduleName;-1!==moduleName.indexOf(".")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,"").replace(/\\/\\.\\//,"/").replace(/[^\\/]+\\/\\.\\.\\//,"")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error("worker.js acequire() accepts only (parentId, id) as arguments");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log("unable to load "+id);var path=resolveModuleId(id,window.acequire.tlns);return".js"!=path.slice(-3)&&(path+=".js"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,"string"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),"function"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=["require","exports","module"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case"require":return req;case"exports":return module.exports;case"module":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire("ace/lib/event_emitter").EventEmitter,oop=window.acequire("ace/lib/oop"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:"call",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:"event",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error("Unknown command:"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire("ace/lib/es5-shim"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}})(this),ace.define("ace/lib/oop",["require","exports","module"],function(acequire,exports){"use strict";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define("ace/range",["require","exports","module"],function(acequire,exports){"use strict";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){"object"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){"object"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define("ace/apply_delta",["require","exports","module"],function(acequire,exports){"use strict";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||"";switch(delta.action){case"insert":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case"remove":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define("ace/lib/event_emitter",["require","exports","module"],function(acequire,exports){"use strict";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){"object"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?"unshift":"push"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(acequire,exports){"use strict";var oop=acequire("./lib/oop"),EventEmitter=acequire("./lib/event_emitter").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal("change",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"],function(acequire,exports){"use strict";var oop=acequire("./lib/oop"),applyDelta=acequire("./apply_delta").applyDelta,EventEmitter=acequire("./lib/event_emitter").EventEmitter,Range=acequire("./range").Range,Anchor=acequire("./anchor").Anchor,Document=function(textOrLines){this.$lines=[""],0===textOrLines.length?this.$lines=[""]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0==="aaa".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,"\\n").split("\\n")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:"\\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\\r\\n";case"unix":return"\\n";default:return this.$autoNewLine||"\\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal("changeNewLineMode"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return"\\r\\n"==text||"\\r"==text||"\\n"==text},this.getLine=function(row){return this.$lines[row]||""},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||"").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead."),this.insertMergedLines(position,["",""])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:"insert",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([""]),column=0):(lines=[""].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:"insert",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:"remove",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:"remove",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:"remove",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:"remove",lines:["",""]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert="insert"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal("change",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(""),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:"insert"==delta.action?"remove":"insert",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define("ace/lib/lang",["require","exports","module"],function(acequire,exports){"use strict";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split("").reverse().join("")},exports.stringRepeat=function(string,count){for(var result="";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,"")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,"")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&"object"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if("object"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if("[object Object]"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,"\\\\$1")},exports.escapeHTML=function(str){return str.replace(/&/g,"&").replace(/"/g,""").replace(/\'/g,"'").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:"insert",start:data[i],lines:data[i+1]};else var d={action:"remove",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define("ace/mode/json/json_parse",["require","exports","module"],function(){"use strict";var at,ch,text,value,escapee={\'"\':\'"\',"\\\\":"\\\\","/":"/",b:"\\b",f:"\\f",n:"\\n",r:"\\r",t:"\t"},error=function(m){throw{name:"SyntaxError",message:m,at:at,text:text}},next=function(c){return c&&c!==ch&&error("Expected \'"+c+"\' instead of \'"+ch+"\'"),ch=text.charAt(at),at+=1,ch},number=function(){var number,string="";for("-"===ch&&(string="-",next("-"));ch>="0"&&"9">=ch;)string+=ch,next();if("."===ch)for(string+=".";next()&&ch>="0"&&"9">=ch;)string+=ch;if("e"===ch||"E"===ch)for(string+=ch,next(),("-"===ch||"+"===ch)&&(string+=ch,next());ch>="0"&&"9">=ch;)string+=ch,next();return number=+string,isNaN(number)?(error("Bad number"),void 0):number},string=function(){var hex,i,uffff,string="";if(\'"\'===ch)for(;next();){if(\'"\'===ch)return next(),string;if("\\\\"===ch)if(next(),"u"===ch){for(uffff=0,i=0;4>i&&(hex=parseInt(next(),16),isFinite(hex));i+=1)uffff=16*uffff+hex;string+=String.fromCharCode(uffff)}else{if("string"!=typeof escapee[ch])break;string+=escapee[ch]}else string+=ch}error("Bad string")},white=function(){for(;ch&&" ">=ch;)next()},word=function(){switch(ch){case"t":return next("t"),next("r"),next("u"),next("e"),!0;case"f":return next("f"),next("a"),next("l"),next("s"),next("e"),!1;case"n":return next("n"),next("u"),next("l"),next("l"),null}error("Unexpected \'"+ch+"\'")},array=function(){var array=[];if("["===ch){if(next("["),white(),"]"===ch)return next("]"),array;for(;ch;){if(array.push(value()),white(),"]"===ch)return next("]"),array;next(","),white()}}error("Bad array")},object=function(){var key,object={};if("{"===ch){if(next("{"),white(),"}"===ch)return next("}"),object;for(;ch;){if(key=string(),white(),next(":"),Object.hasOwnProperty.call(object,key)&&error(\'Duplicate key "\'+key+\'"\'),object[key]=value(),white(),"}"===ch)return next("}"),object;next(","),white()}}error("Bad object")};return value=function(){switch(white(),ch){case"{":return object();case"[":return array();case\'"\':return string();case"-":return number();default:return ch>="0"&&"9">=ch?number():word()}},function(source,reviver){var result;return text=source,at=0,ch=" ",result=value(),white(),ch&&error("Syntax error"),"function"==typeof reviver?function walk(holder,key){var k,v,value=holder[key];if(value&&"object"==typeof value)for(k in value)Object.hasOwnProperty.call(value,k)&&(v=walk(value,k),void 0!==v?value[k]=v:delete value[k]);return reviver.call(holder,key,value)}({"":result},""):result}}),ace.define("ace/mode/json_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/json/json_parse"],function(acequire,exports){"use strict";var oop=acequire("../lib/oop"),Mirror=acequire("../worker/mirror").Mirror,parse=acequire("./json/json_parse"),JsonWorker=exports.JsonWorker=function(sender){Mirror.call(this,sender),this.setTimeout(200)};oop.inherits(JsonWorker,Mirror),function(){this.onUpdate=function(){var value=this.doc.getValue(),errors=[];try{value&&parse(value)}catch(e){var pos=this.doc.indexToPosition(e.at-1);errors.push({row:pos.row,column:pos.column,text:e.message,type:"error"})}this.sender.emit("annotate",errors)}}.call(JsonWorker.prototype)}),ace.define("ace/lib/es5-shim",["require","exports","module"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,"sentinel",{}),"sentinel"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError("Function.prototype.bind called on incompatible "+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,"__defineGetter__"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,"XXX"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0\n}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return"[object Array]"==_toString(obj)});var boxedString=Object("a"),splitString="a"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,thisp=arguments[1],i=-1,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,result=[],thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");if(!length&&1==arguments.length)throw new TypeError("reduce of empty array with no initial value");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError("reduce of empty array with no initial value")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");if(!length&&1==arguments.length)throw new TypeError("reduceRight of empty array with no initial value");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError("reduceRight of empty array with no initial value")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&"[object String]"==_toString(this)?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&"[object String]"==_toString(this)?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(object,property){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if("object"!=typeof prototype)throw new TypeError("typeof prototype["+typeof prototype+"] != \'object\'");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom="undefined"==typeof document||doesDefinePropertyWork(document.createElement("div"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR="Property description must be an object: ",ERR_NON_OBJECT_TARGET="Object.defineProperty called on non-object: ",ERR_ACCESSORS_NOT_SUPPORTED="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(object,property,descriptor){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if("object"!=typeof descriptor&&"function"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,"value"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,"get")&&defineGetter(object,property,descriptor.get),owns(descriptor,"set")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return"function"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name="";owns(object,name);)name+="?";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError("Object.keys called on a non-object");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws="\t\\n\v\\f\\r   ᠎              \\u2028\\u2029\ufeff";if(!String.prototype.trim||ws.trim()){ws="["+ws+"]";var trimBeginRegexp=RegExp("^"+ws+ws+"*"),trimEndRegexp=RegExp(ws+ws+"*$");String.prototype.trim=function(){return(this+"").replace(trimBeginRegexp,"").replace(trimEndRegexp,"")}}var toObject=function(o){if(null==o)throw new TypeError("can\'t convert "+o+" to object");return Object(o)}});'},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=function(){function e(e,t){for(var n=0;n=0}},this.format.map(function(e){return a.default.createElement(g,{value:e.name,key:e.name},e.name," ",a.default.createElement("span",{className:"format-items-title"},e.title))})))))}}]),t}();v.contextTypes={changeCustomValue:s.default.func,Model:s.default.object};var w=function(e){function t(e){f(this,t);var n=p(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onChangeCheckBox=function(e,t){n.setState({checked:e}),e||(delete t.enum,n.setState({enum:""}),n.context.changeCustomValue(t))},n.changeEnumOtherValue=function(e,t){n.setState({enum:e});var r=e.split("\n");0===r.length||1==r.length&&!r[0]?(delete t.enum,n.context.changeCustomValue(t)):(t.enum=r.map(function(e){return+e}),n.context.changeCustomValue(t))},n.onEnterEnumOtherValue=function(e,t){var r=e.split("\n").map(function(e){return+e});t.enum=r,n.context.changeCustomValue(t)},n.changeEnumDescOtherValue=function(e,t){t.enumDesc=e,n.context.changeCustomValue(t)},n.state={checked:!l.default.isUndefined(e.data.enum),enum:l.default.isUndefined(e.data.enum)?"":e.data.enum.join("\n")},n}return m(t,o.PureComponent),r(t,[{key:"componentWillReceiveProps",value:function(e){var t=l.default.isUndefined(this.props.data.enum)?"":this.props.data.enum.join("\n"),n=l.default.isUndefined(e.data.enum)?"":e.data.enum.join("\n");t!==n&&this.setState({enum:n})}},{key:"render",value:function(){var e=this,t=this.props.data;return a.default.createElement("div",null,a.default.createElement("div",{className:"default-setting"},(0,u.default)("base_setting")),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:4,className:"other-label"},(0,u.default)("default"),":"),a.default.createElement(i.Col,{span:20},a.default.createElement(i.Input,{value:t.default,placeholder:(0,u.default)("default"),onChange:function(n){return y(n.target.value,"default",t,e.context.changeCustomValue)}}))),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:13,className:"other-label"},a.default.createElement("span",null,"exclusiveMinimum ",a.default.createElement(i.Tooltip,{title:(0,u.default)("exclusiveMinimum")},a.default.createElement(i.Icon,{type:"question-circle-o",style:{width:"10px"}})),"  :")),a.default.createElement(i.Col,{span:11},a.default.createElement(i.Switch,{checked:t.exclusiveMinimum,placeholder:"exclusiveMinimum",onChange:function(n){return y(n,"exclusiveMinimum",t,e.context.changeCustomValue)}})))),a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:13,className:"other-label"},a.default.createElement("span",null,"exclusiveMaximum ",a.default.createElement(i.Tooltip,{title:(0,u.default)("exclusiveMaximum")},a.default.createElement(i.Icon,{type:"question-circle-o",style:{width:"10px"}})),"  :")),a.default.createElement(i.Col,{span:11},a.default.createElement(i.Switch,{checked:t.exclusiveMaximum,placeholder:"exclusiveMaximum",onChange:function(n){return y(n,"exclusiveMaximum",t,e.context.changeCustomValue)}}))))),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:8,className:"other-label"},(0,u.default)("minimum"),":"),a.default.createElement(i.Col,{span:16},a.default.createElement(i.InputNumber,{value:t.minimum,placeholder:(0,u.default)("minimum"),onChange:function(n){return y(n,"minimum",t,e.context.changeCustomValue)}})))),a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:8,className:"other-label"},(0,u.default)("maximum"),":"),a.default.createElement(i.Col,{span:16},a.default.createElement(i.InputNumber,{value:t.maximum,placeholder:(0,u.default)("maximum"),onChange:function(n){return y(n,"maximum",t,e.context.changeCustomValue)}}))))),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:4,className:"other-label"},a.default.createElement("span",null,(0,u.default)("enum"),a.default.createElement(i.Checkbox,{checked:this.state.checked,onChange:function(n){return e.onChangeCheckBox(n.target.checked,t)}})," ",":")),a.default.createElement(i.Col,{span:20},a.default.createElement(h,{value:this.state.enum,disabled:!this.state.checked,placeholder:(0,u.default)("enum_msg"),autosize:{minRows:2,maxRows:6},onChange:function(n){e.changeEnumOtherValue(n.target.value,t)}}))),this.state.checked&&a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:4,className:"other-label"},a.default.createElement("span",null,(0,u.default)("enum_desc")," :")),a.default.createElement(i.Col,{span:20},a.default.createElement(h,{value:t.enumDesc,disabled:!this.state.checked,placeholder:(0,u.default)("enum_desc_msg"),autosize:{minRows:2,maxRows:6},onChange:function(n){e.changeEnumDescOtherValue(n.target.value,t)}}))))}}]),t}();w.contextTypes={changeCustomValue:s.default.func};var b=function(e,t){var n=e.data,r=l.default.isUndefined(n.default)?"":n.default?"true":"false";return a.default.createElement("div",null,a.default.createElement("div",{className:"default-setting"},(0,u.default)("base_setting")),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:4,className:"other-label"},(0,u.default)("default"),":"),a.default.createElement(i.Col,{span:20},a.default.createElement(i.Select,{value:r,onChange:function(e){return y("true"===e,"default",n,t.changeCustomValue)},style:{width:200}},a.default.createElement(g,{value:"true"},"true"),a.default.createElement(g,{value:"false"},"false")))))};b.contextTypes={changeCustomValue:s.default.func};var E=function(e,t){var n=e.data;return a.default.createElement("div",null,a.default.createElement("div",{className:"default-setting"},(0,u.default)("base_setting")),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:6,className:"other-label"},a.default.createElement("span",null,"uniqueItems ",a.default.createElement(i.Tooltip,{title:(0,u.default)("unique_items")},a.default.createElement(i.Icon,{type:"question-circle-o",style:{width:"10px"}})),"  :")),a.default.createElement(i.Col,{span:18},a.default.createElement(i.Switch,{checked:n.uniqueItems,placeholder:"uniqueItems",onChange:function(e){return y(e,"uniqueItems",n,t.changeCustomValue)}}))),a.default.createElement(i.Row,{className:"other-row",type:"flex",align:"middle"},a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:12,className:"other-label"},(0,u.default)("min_items"),":"),a.default.createElement(i.Col,{span:12},a.default.createElement(i.InputNumber,{value:n.minItems,placeholder:"minItems",onChange:function(e){return y(e,"minItems",n,t.changeCustomValue)}})))),a.default.createElement(i.Col,{span:12},a.default.createElement(i.Row,{type:"flex",align:"middle"},a.default.createElement(i.Col,{span:12,className:"other-label"},(0,u.default)("max_items"),":"),a.default.createElement(i.Col,{span:12},a.default.createElement(i.InputNumber,{value:n.maxItems,placeholder:"maxItems",onChange:function(e){return y(e,"maxItems",n,t.changeCustomValue)}}))))))};E.contextTypes={changeCustomValue:s.default.func};var x=function(e,t){var n=e.data,r=function(e){return{string:a.default.createElement(v,{data:e}),number:a.default.createElement(w,{data:e}),boolean:a.default.createElement(b,{data:e}),integer:a.default.createElement(w,{data:e}),array:a.default.createElement(E,{data:e})}[e.type]}(JSON.parse(n));return a.default.createElement("div",null,a.default.createElement("div",null,r),a.default.createElement("div",{className:"default-setting"},(0,u.default)("all_setting")),a.default.createElement(c.default,{data:n,mode:"json",onChange:function(e){return function(e,t){e.text&&t(e.jsonData)}(e,t.changeCustomValue)}}))};x.contextTypes={changeCustomValue:s.default.func},t.default=x},function(e,t,n){var r=n(21);function o(e){return"date"===r.string(e).toLowerCase()?"date-time":null}function a(e){var t=r.string(e).toLowerCase();return"date"===t?"string":"regexp"===t?"string":"function"===t?"string":t}function i(e,t,n){var r,o,a;e=Object.keys(e),t=Object.keys(t),n=n||[];for(var i=0,l=t.length;i=0?(s.splice(c,1),a.push("required"),0===s.length?o.default.deleteData(e.data,a):o.default.setData(e.data,a,s)):t.required&&-1===c&&(s.push(t.name),a.push("required"),o.default.setData(e.data,a,s))},requireAllAction:function(e,t,n){var r=o.default.cloneObject(t.value);o.default.handleSchemaRequired(r,t.required),e.data=r},deleteItemAction:function(e,t,n){var r=t.key,a=r[r.length-1],i=n.data,l=o.default.getParentKeys(r),s=o.default.getData(i,l),c={};for(var u in s)u!==a&&(c[u]=s[u]);o.default.setData(e.data,l,c)},addFieldAction:function(e,t,n){var r=t.prefix,a=n.data,i=t.name,l=o.default.getData(a,r),c={},u=o.default.getParentKeys(r),d=o.default.getData(a,u),f=[].concat(d.required||[]);if(i){for(var p in l)if(c[p]=l[p],p===i){var m="field_"+s++;c[m]=o.default.defaultSchema.string,f.push(m)}}else{c=Object.assign({},l);var h="field_"+s++;c[h]=o.default.defaultSchema.string,f.push(h)}o.default.setData(e.data,r,c),u.push("required"),o.default.setData(e.data,u,f)},addChildFieldAction:function(e,t,n){var r=t.key,a=n.data,i=o.default.getData(a,r),l={};l=Object.assign({},i);var c="field_"+s++;l[c]=o.default.defaultSchema.string,o.default.setData(e.data,r,l);var u=o.default.getParentKeys(r),d=o.default.getData(a,u),f=[].concat(d.required||[]);f.push(c),u.push("required"),o.default.setData(e.data,u,f)},setOpenValueAction:function(e,t,n){var r=t.key.join(o.default.JSONPATH_JOIN_CHAR),a=void 0;a=l.isUndefined(t.value)?!o.default.getData(n.open,[r]):t.value,o.default.setData(e.open,[r],a)}}},function(e,t){},,,,,function(e,t){}])}); \ No newline at end of file diff --git a/package.json b/package.json index 83b7706..3b2b616 100644 --- a/package.json +++ b/package.json @@ -5,37 +5,43 @@ "main": "package/index.js", "license": "MIC", "scripts": { - "start": "ykit s -p 8082", - "demo": "NODE_ENV=production ykit pack -m", - "build": "NODE_ENV=production webpack" + "start": "webpack serve -c webpack/webpack.dev.js", + "watch": "webpack -c webpack/webpack.dev.js --watch", + "build": "NODE_ENV=production webpack -c webpack/webpack.prod.js" }, "dependencies": { "antd": "^3.1.6", + "brace": "^0.11.1", "generate-schema": "^2.6.0", - "moox": "^1.0.2", - "react-redux": "^5.0.6", - "underscore": "^1.8.3", - "brace": "^0.10.0" + "lodash": "^4.17.20", + "react-redux": "^5.1.2", + "redux": "^4.0.5" }, "devDependencies": { + "@babel/cli": "^7.12.13", + "@babel/core": "^7.12.13", + "@babel/plugin-proposal-class-properties": "^7.12.13", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/preset-env": "^7.12.13", + "@babel/preset-react": "^7.12.13", "autoprefixer": "^7.2.1", - "babel-cli": "^6.26.0", - "babel-core": "^6.26.0", - "babel-loader": "^7.1.4", - "babel-plugin-import": "^1.7.0", - "babel-plugin-transform-class-properties": "^6.24.1", - "babel-preset-env": "^1.6.1", - "babel-preset-react": "^6.24.1", - "babel-preset-react-app": "^3.1.0", - "cross-env": "^5.1.1", - "css-loader": "^0.28.11", - "extract-text-webpack-plugin": "^4.0.0-beta.0", - "less": "^2.7.2", - "less-loader": "^4.1.0", + "babel-loader": "^8.2.2", + "babel-plugin-import": "^1.13.3", + "babel-plugin-lodash": "^3.3.4", + "css-loader": "^5.0.1", + "file-loader": "^6.2.0", + "html-webpack-plugin": "^5.0.0", + "less": "^4.1.1", + "less-loader": "^8.0.0", + "lodash-webpack-plugin": "^0.11.6", + "mini-css-extract-plugin": "^1.3.5", + "postcss": "^8.2.5", + "postcss-loader": "^5.0.0", "react-addons-perf": "^15.4.2", "style-loader": "^0.20.3", - "webpack": "^4.5.0", - "webpack-cli": "^2.0.14", - "ykit-config-antd": "^1.2.0" + "webpack": "^5.21.2", + "webpack-bundle-analyzer": "^4.4.0", + "webpack-cli": "^4.5.0", + "webpack-dev-server": "^3.11.2" } } diff --git a/package/App.js b/package/App.js index 1e40af9..bb30a73 100644 --- a/package/App.js +++ b/package/App.js @@ -21,7 +21,7 @@ const TabPane = Tabs.TabPane; import './index.css'; import AceEditor from './components/AceEditor/AceEditor.js'; -import _ from 'underscore'; +import _ from 'lodash'; import { connect } from 'react-redux'; import SchemaJson from './components/SchemaComponents/SchemaJson.js'; import PropTypes from 'prop-types'; @@ -32,7 +32,9 @@ const utils = require('./utils'); import CustomItem from './components/SchemaComponents/SchemaOther.js'; import LocalProvider from './components/LocalProvider/index.js'; import MockSelect from './components/MockSelect/index.js'; - +import { + changeEditorSchema, changeType, addChildField, changeValue, requireAll +} from './redux/actions'; class jsonSchema extends React.Component { @@ -52,7 +54,6 @@ class jsonSchema extends React.Component { editorModalName: '', // 弹窗名称desctiption | mock mock: '' }; - this.Model = this.props.Model.schema; this.jsonSchemaData = null; this.jsonData = null; } @@ -70,12 +71,12 @@ class jsonSchema extends React.Component { } let jsonData = GenerateSchema(this.jsonData); - this.Model.changeEditorSchemaAction({ value: jsonData }); + this.props.changeEditorSchema({ value: jsonData }); } else { if (!this.jsonSchemaData) { return message.error('json 数据格式有误'); } - this.Model.changeEditorSchemaAction({ value: this.jsonSchemaData }); + this.props.changeEditorSchema({ value: this.jsonSchemaData }); } this.setState({ visible: false }); }; @@ -90,7 +91,7 @@ class jsonSchema extends React.Component { if (oldData !== newData) return this.props.onChange(newData); } if (this.props.data && this.props.data !== nextProps.data) { - this.Model.changeEditorSchemaAction({ value: JSON.parse(nextProps.data) }); + this.props.changeEditorSchema({ value: JSON.parse(nextProps.data) }); } } @@ -103,13 +104,13 @@ class jsonSchema extends React.Component { "properties":{} }`; } - this.Model.changeEditorSchemaAction({ value: JSON.parse(data) }); + this.props.changeEditorSchema({ value: JSON.parse(data) }); } getChildContext() { return { getOpenValue: keys => { - return utils.getData(this.props.open, keys); + return _.get(this.props.open, keys.join(utils.JSONPATH_JOIN_CHAR)); }, changeCustomValue: this.changeCustomValue, Model: this.props.Model, @@ -129,14 +130,14 @@ class jsonSchema extends React.Component { return this.alterMsg(); } handleSchema(e.jsonData); - this.Model.changeEditorSchemaAction({ + this.props.changeEditorSchema({ value: e.jsonData }); }; // 修改数据类型 changeType = (key, value) => { - this.Model.changeTypeAction({ key: [key], value }); + this.props.changeType({ key: [key], value }); }; handleImportJson = e => { @@ -154,7 +155,7 @@ class jsonSchema extends React.Component { }; // 增加子节点 addChildField = key => { - this.Model.addChildFieldAction({ key: [key] }); + this.props.addChildField({ key: [key] }); this.setState({ show: true }); }; @@ -167,7 +168,7 @@ class jsonSchema extends React.Component { if (key[0] === 'mock') { value = value ? { mock: value } : ''; } - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); }; // 备注/mock弹窗 点击ok 时 @@ -179,7 +180,7 @@ class jsonSchema extends React.Component { if (name === 'mock') { value = value ? { mock: value } : ''; } - this.Model.changeValueAction({ key: this.state.descriptionKey, value }); + this.props.changeValue({ key: this.state.descriptionKey, value }); }; handleEditCancel = () => { @@ -219,11 +220,11 @@ class jsonSchema extends React.Component { // 高级设置 handleAdvOk = () => { if (this.state.itemKey.length === 0) { - this.Model.changeEditorSchemaAction({ + this.props.changeEditorSchema({ value: this.state.curItemCustomValue }); } else { - this.Model.changeValueAction({ + this.props.changeValue({ key: this.state.itemKey, value: this.state.curItemCustomValue }); @@ -254,7 +255,7 @@ class jsonSchema extends React.Component { changeCheckBox = e => { this.setState({ checked: e }); - this.Model.requireAllAction({ required: e, value: this.props.schema }); + this.props.requireAll({ required: e, value: this.props.schema }); }; render() { @@ -471,13 +472,10 @@ class jsonSchema extends React.Component { ) : null} - {this.state.show && ( - - )} + />)} @@ -497,10 +495,15 @@ jsonSchema.propTypes = { onChange: PropTypes.func, showEditor: PropTypes.bool, isMock: PropTypes.bool, - Model: PropTypes.object }; -export default connect(state => ({ - schema: state.schema.data, - open: state.schema.open -}))(jsonSchema); +const mapStateToProps = ({ schema, open }) => { + return {schema, open}; +}; + +export default connect( + mapStateToProps, + { + changeEditorSchema, changeType, addChildField, changeValue, requireAll + } +)(jsonSchema); diff --git a/package/components/AceEditor/AceEditor.js b/package/components/AceEditor/AceEditor.js index 4fbe42d..f2b3907 100644 --- a/package/components/AceEditor/AceEditor.js +++ b/package/components/AceEditor/AceEditor.js @@ -1,7 +1,7 @@ -import React from 'react'; +import React, {PureComponent} from 'react'; import mockEditor from './mockEditor'; import PropTypes from 'prop-types'; -import _ from 'underscore'; +import _ from 'lodash'; const ModeMap = { javascript: 'ace/mode/javascript', @@ -25,7 +25,7 @@ function getMode(mode) { return ModeMap[mode] || ModeMap.text; } -class AceEditor extends React.PureComponent { +class AceEditor extends PureComponent { constructor(props) { super(props); } diff --git a/package/components/AceEditor/mockEditor.js b/package/components/AceEditor/mockEditor.js index 686e97c..2309fab 100755 --- a/package/components/AceEditor/mockEditor.js +++ b/package/components/AceEditor/mockEditor.js @@ -1,5 +1,6 @@ -var ace = require('brace'); -require('brace/mode/json'); +// import ace from 'ace-builds/src-min-noconflict/ace'; +import ace from 'brace'; +import 'brace/mode/json'; function run(options) { @@ -78,4 +79,4 @@ function run(options) { return mockEditor; } -module.exports = run; +export default run; diff --git a/package/components/LocalProvider/index.js b/package/components/LocalProvider/index.js index 84d40ab..aec6fd6 100644 --- a/package/components/LocalProvider/index.js +++ b/package/components/LocalProvider/index.js @@ -1,5 +1,4 @@ -import utils from '../../utils' -import React from 'react'; +import { lang } from '../../utils' const langs = { en_US: { @@ -75,14 +74,5 @@ const langs = { } export default (message) => { - return langs[utils.lang][message] -} - - - - -// exports.LocalProvider = (props)=>{ -// console.log(langs[utils.lang][props.message]) -// return {langs[utils.lang][props.message]} -// // return langs[utils.lang][props.message] -// } + return langs[lang][message] +} \ No newline at end of file diff --git a/package/components/SchemaComponents/SchemaJson.js b/package/components/SchemaComponents/SchemaJson.js index e48e80f..9d69415 100644 --- a/package/components/SchemaComponents/SchemaJson.js +++ b/package/components/SchemaComponents/SchemaJson.js @@ -4,50 +4,45 @@ import { Menu, Row, Col, - Form, Select, Checkbox, - Button, Icon, Input, - Modal, message, Tooltip } from 'antd'; import FieldInput from './FieldInput' -const FormItem = Form.Item; +import { + changeEditorSchema, changeType, addChildField, changeValue, requireAll, + setOpenValue, changeName, deleteItem, enableRequire, addField +} from '../../redux/actions'; + const Option = Select.Option; -const { TextArea } = Input; import './schemaJson.css'; -import _ from 'underscore'; +import _ from 'lodash'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { JSONPATH_JOIN_CHAR, SCHEMA_TYPE } from '../../utils.js'; -const InputGroup = Input.Group; import LocaleProvider from '../LocalProvider/index.js'; -import utils from '../../utils'; import MockSelect from '../MockSelect/index.js'; const mapping = (name, data, showEdit, showAdv) => { switch (data.type) { case 'array': return ; - break; case 'object': let nameArray = [].concat(name, 'properties'); return ; - break; default: return null; } }; -class SchemaArray extends PureComponent { +class SchemaArrayComponent extends PureComponent { constructor(props, context) { super(props); this._tagPaddingLeftStyle = {}; - this.Model = context.Model.schema; } componentWillMount() { @@ -65,8 +60,8 @@ class SchemaArray extends PureComponent { // 修改数据类型 handleChangeType = value => { let prefix = this.getPrefix(); - let key = [].concat(prefix, 'type'); - this.Model.changeTypeAction({ key, value }); + let keys = [].concat(prefix, 'type'); + this.props.changeType({ keys, value }); }; // 修改备注信息 @@ -74,7 +69,7 @@ class SchemaArray extends PureComponent { let prefix = this.getPrefix(); let key = [].concat(prefix, `description`); let value = e.target.value; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); }; // 修改mock信息 @@ -82,29 +77,29 @@ class SchemaArray extends PureComponent { let prefix = this.getPrefix(); let key = [].concat(prefix, `mock`); let value = e ? { mock: e } : ''; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); }; handleChangeTitle = e =>{ let prefix = this.getPrefix(); let key = [].concat(prefix, `title`); let value = e.target.value; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); } // 增加子节点 handleAddChildField = () => { let prefix = this.getPrefix(); let keyArr = [].concat(prefix, 'properties'); - this.Model.addChildFieldAction({ key: keyArr }); - this.Model.setOpenValueAction({ key: keyArr, value: true }); + this.props.addChildField({ key: keyArr }); + this.props.setOpenValue({ key: keyArr, value: true }); }; handleClickIcon = () => { let prefix = this.getPrefix(); // 数据存储在 properties.name.properties下 let keyArr = [].concat(prefix, 'properties'); - this.Model.setOpenValueAction({ key: keyArr }); + this.props.setOpenValue({ key: keyArr }); }; handleShowEdit = (name, type) => { @@ -116,13 +111,17 @@ class SchemaArray extends PureComponent { this.props.showAdv(this.getPrefix(), this.props.data.items); }; + getOpenValue = jsonPath => { + return _.get(this.props.open, jsonPath); + }; + render() { const { data, prefix, showEdit, showAdv } = this.props; const items = data.items; let prefixArray = [].concat(prefix, 'items'); let prefixArrayStr = [].concat(prefixArray, 'properties').join(JSONPATH_JOIN_CHAR); - let showIcon = this.context.getOpenValue([prefixArrayStr]); + let showIcon = this.getOpenValue([prefixArrayStr]); return ( !_.isUndefined(data.items) && (
@@ -214,18 +213,16 @@ class SchemaArray extends PureComponent { } } -SchemaArray.contextTypes = { - getOpenValue: PropTypes.func, - Model: PropTypes.object, - isMock: PropTypes.bool -}; +const SchemaArray = connect(({ open }) => { return { open }}, { + changeEditorSchema, changeType, addChildField, changeValue, requireAll, + setOpenValue, changeName, deleteItem, enableRequire, addField +})(SchemaArrayComponent); -class SchemaItem extends PureComponent { +class SchemaItemComponent extends PureComponent { constructor(props, context) { super(props); this._tagPaddingLeftStyle = {}; // this.num = 0 - this.Model = context.Model.schema; } componentWillMount() { @@ -249,7 +246,7 @@ class SchemaItem extends PureComponent { return message.error(`The field "${value}" already exists.`); } - this.Model.changeNameAction({ value, prefix, name }); + this.props.changeName({ keys: prefix, name, value }); }; // 修改备注信息 @@ -257,7 +254,7 @@ class SchemaItem extends PureComponent { let prefix = this.getPrefix(); let key = [].concat(prefix, 'description'); let value = e.target.value; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); }; // 修改mock 信息 @@ -265,29 +262,28 @@ class SchemaItem extends PureComponent { let prefix = this.getPrefix(); let key = [].concat(prefix, `mock`); let value = e ? { mock: e } : ''; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); }; handleChangeTitle = e => { let prefix = this.getPrefix(); let key = [].concat(prefix, `title`); let value = e.target.value; - this.Model.changeValueAction({ key, value }); + this.props.changeValue({ key, value }); } // 修改数据类型 handleChangeType = e => { let prefix = this.getPrefix(); - let key = [].concat(prefix, 'type'); - this.Model.changeTypeAction({ key, value: e }); + let keys = [].concat(prefix, 'type'); + this.props.changeType({ keys, value: e }); }; - // 删除节点 handleDeleteItem = () => { const { prefix, name } = this.props; let nameArray = this.getPrefix(); - this.Model.deleteItemAction({ key: nameArray }); - this.Model.enableRequireAction({ prefix, name, required: false }); + this.props.deleteItem({ keys: nameArray }); + this.props.enableRequire({ keys: prefix, name, required: false }); }; /* 展示备注编辑弹窗 @@ -300,7 +296,6 @@ class SchemaItem extends PureComponent { showEdit(this.getPrefix(), editorName, data.properties[name][editorName], type); }; - // 展示高级设置弹窗 handleShowAdv = () => { const { data, name, showAdv } = this.props; showAdv(this.getPrefix(), data.properties[name]); @@ -309,7 +304,7 @@ class SchemaItem extends PureComponent { // 增加子节点 handleAddField = () => { const { prefix, name } = this.props; - this.Model.addFieldAction({ prefix, name }); + this.props.addField({ keys: prefix, name }); }; // 控制三角形按钮 @@ -317,26 +312,22 @@ class SchemaItem extends PureComponent { let prefix = this.getPrefix(); // 数据存储在 properties.xxx.properties 下 let keyArr = [].concat(prefix, 'properties'); - this.Model.setOpenValueAction({ key: keyArr }); + this.props.setOpenValue({ key: keyArr }); }; // 修改是否必须 handleEnableRequire = e => { const { prefix, name } = this.props; let required = e.target.checked; - // this.enableRequire(this.props.prefix, this.props.name, e.target.checked); - this.Model.enableRequireAction({ prefix, name, required }); + this.props.enableRequire({ keys: prefix, name, required }); }; render() { - let { name, data, prefix, showEdit, showAdv } = this.props; + let { name, data, prefix, open, showEdit, showAdv } = this.props; let value = data.properties[name]; let prefixArray = [].concat(prefix, name); - - let prefixStr = prefix.join(JSONPATH_JOIN_CHAR); - let prefixArrayStr = [].concat(prefixArray, 'properties').join(JSONPATH_JOIN_CHAR); - let show = this.context.getOpenValue([prefixStr]); - let showIcon = this.context.getOpenValue([prefixArrayStr]); + let show = _.get(open, prefix); + let showIcon = _.get(open, [].concat(prefix, name, 'properties')); return show ? (
@@ -396,15 +387,6 @@ class SchemaItem extends PureComponent { {this.context.isMock && ( - {/* this.handleShowEdit('mock', value.type)} /> - } - placeholder={LocaleProvider('mock')} - value={value.mock ? value.mock.mock : ''} - onChange={this.handleChangeMock} - disabled={value.type === 'object' || value.type === 'array'} - /> */} this.handleShowEdit('mock', value.type)} @@ -458,62 +440,55 @@ class SchemaItem extends PureComponent { } } -SchemaItem.contextTypes = { - getOpenValue: PropTypes.func, - Model: PropTypes.object, +SchemaItemComponent.contextTypes = { isMock: PropTypes.bool }; -class SchemaObjectComponent extends Component { - shouldComponentUpdate(nextProps) { - if ( - _.isEqual(nextProps.data, this.props.data) && - _.isEqual(nextProps.prefix, this.props.prefix) && - _.isEqual(nextProps.open, this.props.open) - ) { - return false; - } - return true; - } +const SchemaItem = connect(({ open }) => { return { open }}, { + changeEditorSchema, changeType, addChildField, changeValue, requireAll, + setOpenValue, changeName, deleteItem, enableRequire, addField +})(SchemaItemComponent); +class SchemaObjectComponent extends Component { render() { const { data, prefix, showEdit, showAdv } = this.props; return (
- {Object.keys(data.properties).map((name, index) => ( - - ))} + {Object.keys(data.properties).map((name, index) => { + return ( + + ); + })}
); } } -const SchemaObject = connect(state => ({ - open: state.schema.open -}))(SchemaObjectComponent); +const SchemaObject = connect( + ({ schema }) => {return { schema }} +)(SchemaObjectComponent); -const DropPlus = (props, context) => { - const { prefix, name, add } = props; - const Model = context.Model.schema; +const DropPlusComponent = (props, context) => { + const { prefix, name, addField, setOpenValue, addChildField} = props; const menu = ( - Model.addFieldAction({ prefix, name })}> + addField({ keys: prefix, name })}> {LocaleProvider('sibling_node')} { - Model.setOpenValueAction({ key: [].concat(prefix, name, 'properties'), value: true }); - Model.addChildFieldAction({ key: [].concat(prefix, name, 'properties') }); + setOpenValue({ key: [].concat(prefix, name, 'properties'), value: true }); + addChildField({ key: [].concat(prefix, name, 'properties') }); }} > {LocaleProvider('child_node')} @@ -531,13 +506,15 @@ const DropPlus = (props, context) => { ); }; -DropPlus.contextTypes = { - Model: PropTypes.object -}; +const DropPlus = connect(null, { addField, addChildField, setOpenValue })(DropPlusComponent); -const SchemaJson = props => { - const item = mapping([], props.data, props.showEdit, props.showAdv); +const SchemaJsonComponent = ({ schema, showEdit, showAdv }) => { + const item = mapping([], schema, showEdit, showAdv); return
{item}
; }; +const SchemaJson = connect(({ schema, open }) => { + return {schema, open}; +})(SchemaJsonComponent); + export default SchemaJson; diff --git a/package/components/SchemaComponents/SchemaOther.js b/package/components/SchemaComponents/SchemaOther.js index 04a61cc..f00d06a 100644 --- a/package/components/SchemaComponents/SchemaOther.js +++ b/package/components/SchemaComponents/SchemaOther.js @@ -1,27 +1,19 @@ import React, { PureComponent } from 'react'; import { - Dropdown, - Menu, Input, InputNumber, Row, Col, - Form, Select, Checkbox, - Button, Icon, - Modal, - message, Tooltip, Switch } from 'antd'; const { TextArea } = Input; import './schemaJson.css'; -import _ from 'underscore'; -import { connect } from 'react-redux'; import PropTypes from 'prop-types'; -import { JSONPATH_JOIN_CHAR, SCHEMA_TYPE } from '../../utils.js'; +import { STRING_FORMATS } from '../../utils.js'; const Option = Select.Option; import AceEditor from '../AceEditor/AceEditor.js'; import LocalProvider from '../LocalProvider/index.js'; @@ -37,7 +29,7 @@ class SchemaString extends PureComponent { this.state = { checked: _.isUndefined(props.data.enum) ? false : true }; - this.format = context.Model.__jsonSchemaFormat; + this.format = STRING_FORMATS; } componentWillReceiveProps(nextprops) { diff --git a/package/index.js b/package/index.js deleted file mode 100644 index db3a00a..0000000 --- a/package/index.js +++ /dev/null @@ -1,44 +0,0 @@ -import React from 'react' -import { render } from 'react-dom' -import { Provider } from 'react-redux' -import App from './App.js' -import utils from './utils' -import moox from 'moox' -import schema from './models/schema' -import PropTypes from 'prop-types' - -module.exports = (config = {})=>{ - if(config.lang) utils.lang = config.lang; - - const Model = moox({ - schema - }) - if(config.format){ - Model.__jsonSchemaFormat = config.format - } else { - Model.__jsonSchemaFormat = utils.format - } - - if(config.mock) { - Model.__jsonSchemaMock = config.mock - } - - - - const store = Model.getStore(); - - const Component = (props)=>{ - return - - - } - - Component.propTypes = { - data: PropTypes.string, - onChange: PropTypes.func, - showEditor: PropTypes.bool - } - return Component; - -} - diff --git a/package/models/schema.js b/package/models/schema.js deleted file mode 100644 index 11dfafb..0000000 --- a/package/models/schema.js +++ /dev/null @@ -1,205 +0,0 @@ -const _ = require('underscore'); -import utils from '../utils'; -let fieldNum = 1; -import handleSchema from '../schema.js'; - -export default { - state: { - message: null, - data: { - title: '', - type: 'object', - properties: {}, - required: [] - }, - open: { - properties: true - } - }, - - changeEditorSchemaAction: function(state, action) { - handleSchema(action.value); - state.data = action.value; - }, - - changeNameAction: function(state, action, oldState) { - const keys = action.prefix; - const name = action.name; - const value = action.value; - let oldData = oldState.data; - let parentKeys = utils.getParentKeys(keys); - let parentData = utils.getData(oldData, parentKeys); - let requiredData = [].concat(parentData.required || []); - let propertiesData = utils.getData(oldData, keys); - let newPropertiesData = {}; - - let curData = propertiesData[name]; - let openKeys = [].concat(keys, value, 'properties').join(utils.JSONPATH_JOIN_CHAR); - let oldOpenKeys = [].concat(keys, name, 'properties').join(utils.JSONPATH_JOIN_CHAR); - if (curData.properties) { - delete state.open[oldOpenKeys]; - state.open[openKeys] = true; - } - - if (propertiesData[value] && typeof propertiesData[value] === 'object') { - return; - } - - requiredData = requiredData.map(item => { - if (item === name) return value; - return item; - }); - - parentKeys.push('required'); - utils.setData(state.data, parentKeys, requiredData); - - for (let i in propertiesData) { - if (i === name) { - newPropertiesData[value] = propertiesData[i]; - } else newPropertiesData[i] = propertiesData[i]; - } - - utils.setData(state.data, keys, newPropertiesData); - }, - - changeValueAction: function(state, action) { - const keys = action.key; - if (action.value) { - utils.setData(state.data, keys, action.value); - } else { - utils.deleteData(state.data, keys); - } - }, - - changeTypeAction: function(state, action, oldState) { - const keys = action.key; - const value = action.value; - - let parentKeys = utils.getParentKeys(keys); - let oldData = oldState.data; - let parentData = utils.getData(oldData, parentKeys); - if (parentData.type === value) { - return; - } - // let newParentData = utils.defaultSchema[value]; - let newParentDataItem = utils.defaultSchema[value]; - - // 将备注过滤出来 - let parentDataItem = parentData.description ? { description: parentData.description } : {}; - let newParentData = Object.assign({}, newParentDataItem, parentDataItem); - - let newKeys = [].concat('data', parentKeys); - utils.setData(state, newKeys, newParentData); - }, - - enableRequireAction: function(state, action, oldState) { - const keys = action.prefix; - let parentKeys = utils.getParentKeys(keys); - let oldData = oldState.data; - let parentData = utils.getData(oldData, parentKeys); - let requiredData = [].concat(parentData.required || []); - let index = requiredData.indexOf(action.name); - - if (!action.required && index >= 0) { - requiredData.splice(index, 1); - parentKeys.push('required'); - if (requiredData.length === 0) { - utils.deleteData(state.data, parentKeys); - } else { - utils.setData(state.data, parentKeys, requiredData); - } - } else if (action.required && index === -1) { - requiredData.push(action.name); - parentKeys.push('required'); - utils.setData(state.data, parentKeys, requiredData); - } - }, - - requireAllAction: function(state, action, oldState) { - // let oldData = oldState.data; - let data = utils.cloneObject(action.value); - utils.handleSchemaRequired(data, action.required); - - state.data = data; - }, - - deleteItemAction: function(state, action, oldState) { - const keys = action.key; - - let name = keys[keys.length - 1]; - let oldData = oldState.data; - let parentKeys = utils.getParentKeys(keys); - let parentData = utils.getData(oldData, parentKeys); - let newParentData = {}; - for (let i in parentData) { - if (i !== name) { - newParentData[i] = parentData[i]; - } - } - - utils.setData(state.data, parentKeys, newParentData); - }, - - addFieldAction: function(state, action, oldState) { - const keys = action.prefix; - let oldData = oldState.data; - let name = action.name; - let propertiesData = utils.getData(oldData, keys); - let newPropertiesData = {}; - - let parentKeys = utils.getParentKeys(keys); - let parentData = utils.getData(oldData, parentKeys); - let requiredData = [].concat(parentData.required || []); - - if (!name) { - newPropertiesData = Object.assign({}, propertiesData); - let ranName = 'field_' + fieldNum++; - newPropertiesData[ranName] = utils.defaultSchema.string; - requiredData.push(ranName); - } else { - for (let i in propertiesData) { - newPropertiesData[i] = propertiesData[i]; - if (i === name) { - let ranName = 'field_' + fieldNum++; - newPropertiesData[ranName] = utils.defaultSchema.string; - requiredData.push(ranName); - } - } - } - utils.setData(state.data, keys, newPropertiesData); - // add required - parentKeys.push('required'); - utils.setData(state.data, parentKeys, requiredData); - }, - addChildFieldAction: function(state, action, oldState) { - const keys = action.key; - let oldData = oldState.data; - let propertiesData = utils.getData(oldData, keys); - let newPropertiesData = {}; - - newPropertiesData = Object.assign({}, propertiesData); - let ranName = 'field_' + fieldNum++; - newPropertiesData[ranName] = utils.defaultSchema.string; - utils.setData(state.data, keys, newPropertiesData); - - // add required - let parentKeys = utils.getParentKeys(keys); - let parentData = utils.getData(oldData, parentKeys); - let requiredData = [].concat(parentData.required || []); - requiredData.push(ranName); - parentKeys.push('required'); - utils.setData(state.data, parentKeys, requiredData); - }, - - setOpenValueAction: function(state, action, oldState) { - const keys = action.key.join(utils.JSONPATH_JOIN_CHAR); - - let status; - if (_.isUndefined(action.value)) { - status = utils.getData(oldState.open, [keys]) ? false : true; - } else { - status = action.value; - } - utils.setData(state.open, [keys], status); - } -}; diff --git a/package/redux/actionTypes.js b/package/redux/actionTypes.js new file mode 100644 index 0000000..52ab9a3 --- /dev/null +++ b/package/redux/actionTypes.js @@ -0,0 +1,10 @@ +export const CHANGE_EDITOR_SCHEMA = "CHANGE_EDITOR_SCHEMA"; +export const CHANGE_NAME = "CHANGE_NAME"; +export const CHANGE_VALUE = "CHANGE_VALUE"; +export const CHANGE_TYPE = "CHANGE_TYPE"; +export const ENABLE_REQUIRE = "ENABLE_REQUIRE"; +export const REQUIRE_ALL = "REQUIRE_ALL"; +export const DELETE_ITEM = "DELETE_ITEM"; +export const ADD_FIELD = "ADD_FIELD"; +export const ADD_CHILD_FIELD = "ADD_CHILD_FIELD"; +export const SET_OPEN_VALUE = "SET_OPEN_VALUE"; \ No newline at end of file diff --git a/package/redux/actions.js b/package/redux/actions.js new file mode 100644 index 0000000..218d09d --- /dev/null +++ b/package/redux/actions.js @@ -0,0 +1,56 @@ +import * as types from './actionTypes'; + +let fieldNum = 1; + +export const changeEditorSchema = ({ value }) => ({ + type: types.CHANGE_EDITOR_SCHEMA, + payload: { value } +}); + +export const changeName = ({ keys, name, value }) => ({ + type: types.CHANGE_NAME, + payload: { keys, name, value } +}) + +export const changeValue = ({key, value}) => ({ + type: types.CHANGE_VALUE, + payload: {keys: key, value} +}) + +export const changeType = ({ keys, value }) => ({ + type: types.CHANGE_TYPE, + payload: { keys, value } +}) + +export const enableRequire = ({ keys, name, required }) => ({ + type: types.ENABLE_REQUIRE, + payload: { keys, name, required } +}) + +export const requireAll = payload => ({ + type: types.REQUIRE_ALL, + payload +}) + +export const deleteItem = ({ keys }) => ({ + type: types.DELETE_ITEM, + payload: { keys } +}) + +export const addField = ({ keys, name }) => ({ + type: types.ADD_FIELD, + payload: { keys, name, fieldNum: fieldNum++ } +}) + +export const addChildField = ({ key }) => ({ + type: types.ADD_CHILD_FIELD, + payload: { + keys: key, //@TODO change key to keys + fieldNum: fieldNum++ + } +}) + +export const setOpenValue = ({ key, value }) => ({ + type: types.SET_OPEN_VALUE, + payload: {key, value} +}) diff --git a/package/redux/reducers/index.js b/package/redux/reducers/index.js new file mode 100644 index 0000000..90212f0 --- /dev/null +++ b/package/redux/reducers/index.js @@ -0,0 +1,5 @@ +import { combineReducers } from "redux"; +import schema from './schema'; +import open from './open'; + +export default combineReducers({ schema, open }); diff --git a/package/redux/reducers/open.js b/package/redux/reducers/open.js new file mode 100644 index 0000000..69e90bc --- /dev/null +++ b/package/redux/reducers/open.js @@ -0,0 +1,20 @@ +import * as types from '../actionTypes'; +import _ from 'lodash'; + +const initialState = { + properties: true +}; + +const open = (state = initialState, action) => { + switch (action.type) { + case types.SET_OPEN_VALUE: + const {key, value} = action.payload; + let clonedState = _.cloneDeep(state); + let status = _.isUndefined(value) ? !_.get(state, key) : !!value; + return _.set(clonedState, key, status); + default: + return state; + } +}; + +export default open; \ No newline at end of file diff --git a/package/redux/reducers/schema.js b/package/redux/reducers/schema.js new file mode 100644 index 0000000..7f6ba01 --- /dev/null +++ b/package/redux/reducers/schema.js @@ -0,0 +1,187 @@ +import * as types from '../actionTypes'; +import handleSchema from '../../schema'; +import { defaultSchema } from '../../utils'; +import _ from 'lodash'; + +const initialSchema = { + title: '', + type: 'object', + properties: {}, + required: [] +} + +const getParentKey = (keys) => (keys.length === 1) ? [] : _.dropRight(keys, 1); + +const addRequiredFields = (state, keys, fieldName) => { + let parentKeys = getParentKey(keys); // parent + let parentData = parentKeys.length ? _.get(state, parentKeys) : state; + let requiredData = [].concat(parentData.required || []); + requiredData.push(fieldName); + parentKeys.push('required'); + return _.set(state, parentKeys, _.uniq(requiredData)); +} + +const removeRequireField = (state, keys, fieldName) => { + let parentKeys = getParentKey(keys); // parent + let parentData = parentKeys.length ? _.get(state, parentKeys) : state; + let requiredData = [].concat(parentData.required || []); + let filteredRequire = requiredData.filter(i => i !== fieldName); + parentKeys.push('required'); + return _.set(state, parentKeys, _.uniq(filteredRequire)); +}; + +const addChildField = (state, keys, fieldName) => { + let currentField = _.get(state, keys); + if(_.isUndefined(currentField)) { + return state; + } + return _.update(state, keys, (n => _.assign(n, { + [fieldName]: defaultSchema.string + }))); +} + +const _handleEditorSchemaChange = (state, { value }) => { + handleSchema(value); + return {...state, ...value}; +} + +const _handleAddChildField = (state, {keys, fieldNum}) => { + const fieldName = `field_${fieldNum}`; + let originalState = _.clone(state); + state = addChildField(state, keys, fieldName); + return addRequiredFields(originalState, keys, fieldName); +} + +const _handleDelete = (state, { keys }) => { + const clonedState = _.clone(state); + _.unset(clonedState, keys); + return clonedState; +} + +const _handleAddField = (state, { keys, name, fieldNum }) => { + const clonedState = _.cloneDeep(state); + let propertiesData = _.get(state, keys); + let newPropertiesData = {}; + let parentKeys = getParentKey(keys); + let parentData = parentKeys.length ? _.get(state, parentKeys): state; + let requiredData = [].concat(parentData.required || []); + + let fieldName = `field_${fieldNum}`; + + if(!!name) { + for (let i in propertiesData) { + newPropertiesData[i] = propertiesData[i]; + if (i === name) { + newPropertiesData[fieldName] = defaultSchema.string; + requiredData.push(fieldName); + } + } + } else { + newPropertiesData = _.assign(propertiesData, { + [fieldName]: defaultSchema.string + }); + requiredData.push(fieldName); + } + + let newState = _.update(clonedState, keys, (n => _.assign(n, newPropertiesData))); + return addRequiredFields(newState, keys, fieldName); +}; + +const _handleChangeType = (state, {keys, value}) => { + let parentKeys = getParentKey(keys); + let parentData = parentKeys.length ? _.get(state, parentKeys) : state; + let clonedState = _.cloneDeep(state); + + if (parentData.type === value) { + return clonedState; + } + + let description = parentData.description ? { description: parentData.description } : {}; + let newParentDataItem = {...defaultSchema[value], ...description}; + return _.set(clonedState, parentKeys, newParentDataItem); +}; + +const _handleEnableRequire = (state, { keys, name, required }) => { + let parentKeys = getParentKey(keys); + let clonedState = _.cloneDeep(state); + let parentData = parentKeys.length ? _.get(state, parentKeys) : state; + let requiredArray = [].concat(parentData.required || []); + var requiredFieldIndex = requiredArray.indexOf(name); + let foundRequired = requiredFieldIndex >= 0; + + if (!required && foundRequired) { + // Remove from required arr + requiredArray.splice(requiredFieldIndex, 1); + } else if (required && !foundRequired) { + // Add to required arr + requiredArray.push(name); + } + parentKeys.push('required'); + return _.set(clonedState, parentKeys, requiredArray); +} + +const getSchemaItem = (state, keys) => { + return keys.length ? _.get(state, keys) : state; +} + +const getRequiredFields = (schema) => { + return [].concat(schema.required || []); +} + +const _handleChangeName = (state, { keys, name, value }) => { + let clonedState = _.cloneDeep(state); + let parentKeys = getParentKey(keys); + let parentData = getSchemaItem(state, parentKeys); + let requiredArray = getRequiredFields(parentData); + + const items = _.get(clonedState, keys); + const keyExists = Object.keys(items).indexOf(value) >= 0 && items[value] === 'object'; + + if (keyExists || !_.has(items, name)) { + return state; + } + + items[value] = items[name]; + delete items[name]; + + requiredArray = requiredArray.map(item => { + if (item === name) return value; + return item; + }); + + let newState = addRequiredFields(clonedState, keys, value); + return removeRequireField(newState, keys, name); +}; + +const _handleChangeValue = (state, {keys, value}) => { + if (value) { + return _.set(state, keys, value); + } else { + return _handleDelete(state, keys); + } +}; + +const schema = (state = initialSchema, action) => { + switch (action.type) { + case types.CHANGE_EDITOR_SCHEMA: + return _handleEditorSchemaChange(state, action.payload); + case types.ADD_CHILD_FIELD: + return _handleAddChildField(state, action.payload); + case types.DELETE_ITEM: + return _handleDelete(state, action.payload); + case types.ADD_FIELD: + return _handleAddField(state, action.payload); + case types.CHANGE_TYPE: + return _handleChangeType(state, action.payload); + case types.ENABLE_REQUIRE: + return _handleEnableRequire(state, action.payload); + case types.CHANGE_NAME: + return _handleChangeName(state, action.payload); + case types.CHANGE_VALUE: + return _handleChangeValue(state, action.payload); + default: + return state; + } +}; + +export default schema; \ No newline at end of file diff --git a/package/redux/store.js b/package/redux/store.js new file mode 100644 index 0000000..f02d47a --- /dev/null +++ b/package/redux/store.js @@ -0,0 +1,4 @@ +import { createStore } from "redux"; +import rootReducer from "./reducers"; + +export default createStore(rootReducer); diff --git a/package/utils.js b/package/utils.js index 0129834..c9a04c8 100644 --- a/package/utils.js +++ b/package/utils.js @@ -1,7 +1,9 @@ -const JSONPATH_JOIN_CHAR = '.'; -exports.JSONPATH_JOIN_CHAR = JSONPATH_JOIN_CHAR; -exports.lang = 'en_US'; -exports.format = [ +import _ from 'lodash'; + +export const JSONPATH_JOIN_CHAR = '.'; +export const lang = 'en_US'; + +export const STRING_FORMATS = [ { name: 'date-time' }, { name: 'date' }, { name: 'email' }, @@ -10,9 +12,10 @@ exports.format = [ { name: 'ipv6' }, { name: 'uri' } ]; -const _ = require('underscore'); -exports.SCHEMA_TYPE = ['string', 'number', 'array', 'object', 'boolean', 'integer']; -exports.defaultSchema = { + +export const SCHEMA_TYPE = ['string', 'number', 'array', 'object', 'boolean', 'integer']; + +export const defaultSchema = { string: { type: 'string' }, @@ -37,11 +40,7 @@ exports.defaultSchema = { } }; -// 防抖函数,减少高频触发的函数执行的频率 -// 请在 constructor 里使用: - -// this.func = debounce(this.func, 400); -exports.debounce = (func, wait) => { +export const debounce = (func, wait) => { let timeout; return function() { clearTimeout(timeout); @@ -49,25 +48,20 @@ exports.debounce = (func, wait) => { }; }; -function getData(state, keys) { - let curState = state; - for (let i = 0; i < keys.length; i++) { - curState = curState[keys[i]]; - } - return curState; +export const getData = (state, keys) => { + let objPath = keys.join(JSONPATH_JOIN_CHAR); + return _.get(state, objPath); } -exports.getData = getData; - -exports.setData = function(state, keys, value) { - let curState = state; - for (let i = 0; i < keys.length - 1; i++) { - curState = curState[keys[i]]; +export const setData = (state, keys, value) => { + let objPath = keys.join(JSONPATH_JOIN_CHAR); + if(_.has(state, objPath)) { + return _.set(state, objPath, value); } - curState[keys[keys.length - 1]] = value; + return state; }; -exports.deleteData = function(state, keys) { +export const deleteData = function(state, keys) { let curState = state; for (let i = 0; i < keys.length - 1; i++) { curState = curState[keys[i]]; @@ -76,14 +70,14 @@ exports.deleteData = function(state, keys) { delete curState[keys[keys.length - 1]]; }; -exports.getParentKeys = function(keys) { +export const getParentKeys = function(keys) { if (keys.length === 1) return []; let arr = [].concat(keys); arr.splice(keys.length - 1, 1); return arr; }; -exports.clearSomeFields = function(keys, data) { +export const clearSomeFields = function(keys, data) { const newData = Object.assign({}, data); keys.forEach(key => { delete newData[key]; @@ -100,8 +94,7 @@ function getFieldstitle(data) { return requiredtitle; } -function handleSchemaRequired(schema, checked) { - // console.log(schema) +export const handleSchemaRequired = (schema, checked) => { if (schema.type === 'object') { let requiredtitle = getFieldstitle(schema.properties); @@ -127,9 +120,7 @@ function handleObject(properties, checked) { } } -exports.handleSchemaRequired = handleSchemaRequired; - -function cloneObject(obj) { +export const cloneObject = (obj) => { if (typeof obj === 'object') { if (Array.isArray(obj)) { var newArr = []; @@ -148,5 +139,3 @@ function cloneObject(obj) { return obj; } } - -exports.cloneObject = cloneObject; diff --git a/postcss.config.js b/postcss.config.js new file mode 100644 index 0000000..b90a2cf --- /dev/null +++ b/postcss.config.js @@ -0,0 +1,5 @@ +module.exports = { + plugins: [ + require('autoprefixer') + ] +} \ No newline at end of file diff --git a/src/index.js b/src/index.js index aa82b65..9dd67eb 100644 --- a/src/index.js +++ b/src/index.js @@ -1,70 +1,22 @@ import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; -import { combineReducers, createStore, applyMiddleware } from 'redux'; +import store from "../package/redux/store"; import 'antd/dist/antd.css'; - -if (process.env.NODE_ENV !== 'production') { - window.Perf = require('react-addons-perf'); -} -//import '../dist/main.css' -const jeditor = require('../package/index.js'); -const mock = [ - { name: '字符串', mock: '@string' }, - { name: '自然数', mock: '@natural' }, - { name: '浮点数', mock: '@float' }, - { name: '字符', mock: '@character' }, - { name: '布尔', mock: '@boolean' }, - { name: 'url', mock: '@url' }, - { name: '域名', mock: '@domain' }, - { name: 'ip地址', mock: '@ip' }, - { name: 'id', mock: '@id' }, - { name: 'guid', mock: '@guid' }, - { name: '当前时间', mock: '@now' }, - { name: '时间戳', mock: '@timestamp' } -]; - -const JEditor1 = jeditor({mock: mock}); +import JEditor from '../package/App'; render(
- -

JSON-Schema-Editor

-
-

- A json-schema editor of high efficient and easy-to-use, base on React.{' '} - - Github - -

-
-

- 该工具已被用于开源接口管理平台:{' '} - - YApi - -

- -
-

Example:

-
- - { - console.log('changeValue', e); - }} - /> - - {/* { - // console.log("changeValue", e); - }} - /> */} + + { + console.log('changeValue', e); + }} + /> +
, document.getElementById('root') ); diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index 2668c3e..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,42 +0,0 @@ -var ExtractTextPlugin = require("extract-text-webpack-plugin"); -module.exports = { - entry: './package/index.js', - mode: "production", - output: { - publicPath: "/dist/", - libraryTarget: "umd", - library: ['schema'], - filename: '[name].js' - }, - module: { - rules: [ - { - test: /\.js$/, - exclude: /node_modules/, - use: { - loader: "babel-loader" - } - }, - { - test: /\.css$/, - use: ExtractTextPlugin.extract({ - fallback: "style-loader", - use: "css-loader" - }) - }, - { test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"] } - ] - }, - plugins: [new ExtractTextPlugin("main.css")], - externals: [ - { react: { commonjs: "react", commonjs2: "react",amd: 'react', root: ['React'] } }, - { "react-redux": { commonjs: "react-redux", commonjs2: "react-redux",amd:"react-redux" } }, - { underscore: { commonjs: "underscore", commonjs2: "underscore",amd:'underscore', root: ['_'] } }, - { brace: { commonjs: "brace", commonjs2: "brace", amd: 'brace', root: ['ace'] } }, - { moox: { commonjs: "moox", commonjs2: "moox", amd: 'moox' } }, - { "react-dom": { commonjs: "react-dom", commonjs2: "react-dom", amd: 'react-dom', root: ['ReactDom'] } }, - { redux: { commonjs: "redux", commonjs2: "redux", amd: 'redux'} }, - { "prop-types": { commonjs: "prop-types", commonjs2: "prop-types",amd: 'prop-types' } }, - { antd: { commonjs: "antd", commonjs2: "antd", amd: 'antd' } } - ] -}; diff --git a/webpack/webpack.common.js b/webpack/webpack.common.js new file mode 100644 index 0000000..122e529 --- /dev/null +++ b/webpack/webpack.common.js @@ -0,0 +1,45 @@ +const webpack = require('webpack') +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); + +module.exports = { + entry: './src/index.js', + output: { + filename: '[name].[hash:8].js', + sourceMapFilename: '[name].[hash:8].map', + libraryTarget: 'umd', + chunkFilename: '[id].[hash:8].js' + }, + resolve: { + extensions: ['.js', '.jsx', '.json'] + }, + module: { + rules: [ + { + test: /\.js$/, + exclude: /node_modules/, + use: { + loader: "babel-loader" + } + }, + { + test: /\.css$/, + use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'] + }, + { test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"] } + ] + }, + plugins: [ + new MiniCssExtractPlugin(), + new webpack.SourceMapDevToolPlugin({ + filename: '[file].map[query]' + }), + new HtmlWebpackPlugin({template: 'dist/index.html', inject: 'body'}), + ], + optimization: { + minimize: true, + splitChunks: { + chunks: 'all', + }, + } +}; diff --git a/webpack/webpack.dev.js b/webpack/webpack.dev.js new file mode 100644 index 0000000..8daae6f --- /dev/null +++ b/webpack/webpack.dev.js @@ -0,0 +1,17 @@ +const common = require('./webpack.common'); +const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; +const path = require('path'); + +module.exports = Object.assign({}, common, { + mode: 'development', + devtool: 'inline-source-map', + devServer: { + contentBase: path.join(__dirname, 'dist'), + compress: false, + port: 8080, + }, + plugins: [ + ...common.plugins, + new BundleAnalyzerPlugin() + ] +}) diff --git a/webpack/webpack.prod.js b/webpack/webpack.prod.js new file mode 100644 index 0000000..46f91dd --- /dev/null +++ b/webpack/webpack.prod.js @@ -0,0 +1,6 @@ +const common = require('./webpack.common'); + +module.exports = Object.assign({}, common, { + mode: 'production', + devtool: 'source-map' +});