JavascriptEditor.js 16.9 KB
Newer Older
NoSubject's avatar
NoSubject 已提交
1 2 3
o2.widget = o2.widget || {};
o2.require("o2.widget.codemirror", null, false);
o2.require("o2.widget.ace", null, false);
NoSubject's avatar
NoSubject 已提交
4
o2.require("o2.widget.monaco", null, false);
NoSubject's avatar
NoSubject 已提交
5 6 7 8
o2.require("o2.xDesktop.UserData", null, false);
o2.widget.JavascriptEditor = new Class({
	Implements: [Options, Events],
	options: {
NoSubject's avatar
NoSubject 已提交
9 10
        //"type": "ace",
        "type": "monaco",
NoSubject's avatar
NoSubject 已提交
11 12 13 14 15 16 17 18 19 20
		"title": "JavascriptEditor",
		"style": "default",
		"option": {
			value: "",
			mode: "javascript",
			"lineNumbers": true
		}
	},
	initialize: function(node, options){
		this.setOptions(options);
NoSubject's avatar
NoSubject 已提交
21
		this.unbindEvents = [];
NoSubject's avatar
NoSubject 已提交
22 23 24
		this.editorClass = o2.widget[this.options.type];
		this.node = $(node);
	},
NoSubject's avatar
NoSubject 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    getDefaultEditorData: function(){
	    switch (this.options.type) {
            case "ace":
                return {
                    "javascriptEditor": {
                        "theme": "tomorrow",
                        "fontSize" : "12px"
                    }
                };
            case "monaco":
                return {
                    "javascriptEditor": {
                        "monaco_theme": "vs",
                        "fontSize" : "12px"
                    }
                };
        }
    },
NoSubject's avatar
NoSubject 已提交
43 44 45 46 47 48
    getEditorTheme: function(callback){
        if (!o2.editorData){
            o2.UD.getData("editor", function(json){
                if (json.data){
                    o2.editorData = JSON.decode(json.data);
                }else{
NoSubject's avatar
NoSubject 已提交
49
                    o2.editorData = this.getDefaultEditorData();
NoSubject's avatar
NoSubject 已提交
50 51
                }
                if (callback) callback();
NoSubject's avatar
NoSubject 已提交
52
            }.bind(this));
NoSubject's avatar
NoSubject 已提交
53 54 55 56 57 58 59 60 61
        }else{
            if (callback) callback();
        }
    },
    load: function(callback){
        this.getEditorTheme(function(json){
            if (this.options.type.toLowerCase()=="ace"){
                this.loadAce(callback);
            }
NoSubject's avatar
NoSubject 已提交
62 63 64
            if (this.options.type.toLowerCase()=="monaco"){
                this.loadMonaco(callback);
            }
NoSubject's avatar
NoSubject 已提交
65 66 67
            if (this.options.type.toLowerCase()=="codeMirror"){
                this.loadCodeMirror(callback);
            }
NoSubject's avatar
NoSubject 已提交
68 69 70 71 72

            while (this.unbindEvents.length){
                var ev = this.unbindEvents.shift();
                this.addEditorEvent(ev.name, ev.fun);
            }
NoSubject's avatar
NoSubject 已提交
73 74
        }.bind(this));
    },
NoSubject's avatar
NoSubject 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    loadMonaco: function(callback){
        if (o2.editorData.javascriptEditor){
            this.theme = o2.editorData.javascriptEditor.monaco_theme;
            this.fontSize = o2.editorData.javascriptEditor.fontSize;
        }else{
            o2.editorData.javascriptEditor = {
                "monaco_theme": "vs",
                "fontSize" : "12px"
            };
        }
        if (!this.theme) this.theme = "vs";
        if( !this.fontSize )this.fontSize = "12px";

        this.editorClass.load(function(){
            this.editor = monaco.editor.create(this.node, {
                value: this.options.option.value,
                language: "javascript",
                theme: this.theme,
                fontSize: this.fontSize,
                lineNumbersMinChars: 3,
                mouseWheelZoom: true,
                automaticLayout: true
            });
            this.focus();

NoSubject's avatar
NoSubject 已提交
101 102 103 104 105
            o2.require("o2.xScript.Macro", function(){
                var json = null;
                o2.getJSON("/o2_core/o2/widget/$JavascriptEditor/environment.json", function(data){ json = data; }, false);
                this.Macro = new o2.Macro.FormContext(json);

NoSubject's avatar
NoSubject 已提交
106 107 108 109 110 111 112 113 114 115
                //registerReferenceProvider
                //monaco.languages.registerReferenceProvider('javascript', {
                monaco.languages.registerCompletionItemProvider('javascript', {
                    provideCompletionItems: function(model, position, context, token) {
                        debugger;
                        var textUntilPosition = model.getValueInRange({startLineNumber: position.lineNumber, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column});
                        var textPrefix = textUntilPosition.substr(0, textUntilPosition.lastIndexOf("."));
                        code = "try {return "+textPrefix+";}catch(e){return null;}";
                        var o = this.Macro.exec(code);

NoSubject's avatar
NoSubject 已提交
116 117 118 119 120 121 122
                        var word = model.getWordUntilPosition(position);
                        var range = {
                            startLineNumber: position.lineNumber,
                            endLineNumber: position.lineNumber,
                            startColumn: word.startColumn,
                            endColumn: word.endColumn
                        };
NoSubject's avatar
NoSubject 已提交
123

NoSubject's avatar
NoSubject 已提交
124 125 126 127 128 129 130 131 132 133 134
                        if (o){
                            var arr = [];
                            Object.keys(o).each(function(key){
                                var type = typeOf(o[key]);
                                if (type==="function") {
                                    var count = o[key].length;
                                    var v = key+"(";
                                    for (var i=1; i<=count; i++) v+= (i==count) ? "par"+i :  "par"+i+", ";
                                    v+=");";
                                    arr.push({
                                        label: key,
NoSubject's avatar
NoSubject 已提交
135
                                        kind: monaco.languages.CompletionItemKind.Function,
NoSubject's avatar
NoSubject 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
                                        //documentation: "Fast, unopinionated, minimalist web framework",
                                        insertText: v,
                                        range: range
                                    });
                                }else{
                                    arr.push({
                                        label: key,
                                        kind: monaco.languages.CompletionItemKind.Interface,
                                        //documentation: "Fast, unopinionated, minimalist web framework",
                                        insertText: key,
                                        range: range
                                    });
                                }
                            });
                        }

                        return {suggestions: arr}

                    }.bind(this),
                    resolveCompletionItem: this.provideCompletionItems
NoSubject's avatar
NoSubject 已提交
156
                });
NoSubject's avatar
NoSubject 已提交
157 158 159 160 161


            }.bind(this));


NoSubject's avatar
NoSubject 已提交
162 163 164 165
            this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function(e){
                this.fireEvent("save");
            }.bind(this));

NoSubject's avatar
NoSubject 已提交
166 167 168 169 170 171 172 173 174 175 176
            this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_I, function(e){
                this.format();
            }.bind(this));
            this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_F, function(e){
                this.format();
            }.bind(this));

            if( this.fontSize ){
                this.editor.updateOptions( {"fontSize": this.fontSize} );
            }

NoSubject's avatar
NoSubject 已提交
177 178 179 180 181 182
            this.fireEvent("postLoad");
            if (callback) callback();

        }.bind(this));
    },

NoSubject's avatar
NoSubject 已提交
183
    loadAce: function(callback){
NoSubject's avatar
NoSubject 已提交
184 185 186 187 188 189 190 191 192 193 194 195
        if (o2.editorData.javascriptEditor){
            this.theme = o2.editorData.javascriptEditor.theme;
            this.fontSize = o2.editorData.javascriptEditor.fontSize;
        }else{
            o2.editorData.javascriptEditor = {
                "theme": "tomorrow",
                "fontSize" : "12px"
            };
        }
        if (!this.theme) this.theme = "tomorrow";
        if( !this.fontSize )this.fontSize = "12px";

NoSubject's avatar
NoSubject 已提交
196 197 198 199 200 201 202 203
        this.editorClass.load(function(){
            var exports = ace.require("ace/ext/language_tools");
            this.editor = ace.edit(this.node);
            this.editor.session.setMode("ace/mode/"+this.options.option.mode);
            this.editor.setTheme("ace/theme/"+this.theme);
            this.editor.setOptions({
                enableBasicAutocompletion: true,
                enableSnippets: true,
R
roo00 已提交
204 205
                enableLiveAutocompletion: true,
                lineNumbers: this.options.option.lineNumbers
NoSubject's avatar
NoSubject 已提交
206 207 208 209 210 211 212 213 214 215
            });
            if (this.options.option.value) this.editor.setValue(this.options.option.value);

            this.focus();

            //this.editor.focus();
            //this.editor.navigateFileStart();
            //添加自动完成列表
            o2.require("o2.xScript.Macro", function(){
                var json = null;
NoSubject's avatar
NoSubject 已提交
216
                o2.getJSON("/o2_core/o2/widget/$JavascriptEditor/environment.json", function(data){ json = data; }, false);
NoSubject's avatar
NoSubject 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
                this.Macro = new o2.Macro.FormContext(json);
                exports.addCompleter({
                    identifierRegexps: [
                        /[a-zA-Z_0-9\$\-\u00A2-\uFFFF\.]/
                    ],
                    getCompletions: function(editor, session, pos, prefix, callback){
                        var x = prefix.substr(0, prefix.lastIndexOf("."));
                        code = "try {return "+x+";}catch(e){return null;}";
                        var o = this.Macro.exec(code);

                        if (o){
                            var arr1 = [];
                            var arr2 = [];
                            Object.keys(o).each(function(key){
                                var type = typeOf(o[key]);
                                if (type==="function") {
                                    var count = o[key].length;
                                    var v = x+"."+key+"(";
                                    for (var i=1; i<=count; i++) v+= (i==count) ? "par"+i :  "par"+i+", ";
                                    v+=");";
                                    arr1.push({
                                        caption: key,
                                        value: v,
                                        score: 3,
                                        meta: "function O2"
                                    });
                                }else{
                                    arr2.push({
                                        caption: key,
                                        value: x+"."+key,
                                        score: 3,
                                        meta: (type!="null") ? typeOf(o[key])+" O2" : "O2"
                                    });
                                }
                            });
                            callback(null, arr1.concat(arr2));
                        }
                    }.bind(this)
                });
            }.bind(this));

            this.editor.commands.addCommand({
                name: 'save',
                bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
                exec: function(editor) {
                    this.fireEvent("save");
                }.bind(this),
NoSubject's avatar
NoSubject 已提交
264
                readOnly: false
NoSubject's avatar
NoSubject 已提交
265 266 267 268 269 270
            });

            this.editor.commands.addCommand({
                name: 'format',
                bindKey: {win: 'Ctrl-Alt-i|Ctrl-Alt-f',  mac: 'Command-i|Command-f'},
                exec: function(editor, e, e1) {
NoSubject's avatar
NoSubject 已提交
271
                    this.format();
NoSubject's avatar
NoSubject 已提交
272
                }.bind(this),
NoSubject's avatar
NoSubject 已提交
273
                readOnly: false
NoSubject's avatar
NoSubject 已提交
274
            });
NoSubject's avatar
NoSubject 已提交
275 276 277 278 279 280 281 282 283 284 285

            this.editor.commands.addCommand({
                name: "showKeyboardShortcuts",
                bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
                exec: function(editor) {
                    ace.config.loadModule("ace/ext/keybinding_menu", function(module) {
                        module.init(editor);
                        editor.showKeyboardShortcuts()
                    })
                }.bind(this)
            });
NoSubject's avatar
NoSubject 已提交
286 287 288 289 290

            this.node.addEvent("keydown", function(e){
                e.stopPropagation();
            });

NoSubject's avatar
NoSubject 已提交
291 292 293 294
            if( this.fontSize ){
                this.editor.setFontSize( this.fontSize );
            }

NoSubject's avatar
NoSubject 已提交
295 296 297 298 299
            this.fireEvent("postLoad");
            if (callback) callback();
        }.bind(this));
    },

NoSubject's avatar
NoSubject 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    setValue: function(v){
        if (this.editor) this.editor.setValue(v);
    },
    getValue: function(){
        return (this.editor) ? this.editor.getValue() : "";
    },
    resize: function(y){
        if (this.editor){
            switch (this.options.type.toLowerCase()) {
                case "ace": this.editor.resize(); break;
                case "monaco": this.editor.layout(); break;
            }
        }
    },
    addEditorEvent: function(name, fun){
        if (this.editor){
            switch (this.options.type.toLowerCase()) {
                case "ace": this.editor.on(name, fun); break;
                case "monaco":
                    var ev = name;
                    switch (ev) {
                        case "change": ev = "onDidChangeModelContent"; break;
                    }
                    if (this.editor[ev]) this.editor[ev](fun);
                    break;
            }
        }else{
            this.unbindEvents.push({"name": name, "fun": fun});
        }
    },
    validatedAce: function(){
        var session = this.editor.getSession();
        var annotations = session.getAnnotations();
        for (var i=0; i<annotations.length; i++){
            if (annotations[i].type=="error") return false;
        }
        return true;
    },
    validatedMonaco: function(){
        var mod = this.editor.getModel();
        var ms = monaco.editor.getModelMarkers({"resource": mod.uri});
        for (var i=0; i<ms.length; i++){
            if (ms[i].severity==8) return false;
        }
        return true;
    },

    validated: function(){
        if (this.editor){
           switch (this.options.type.toLowerCase()) {
               case "ace": return this.validatedAce();
               case "monaco": return this.validatedMonaco();
           }
            return true;
        }
        return true
    },

    formatAce: function(){
        var mode = this.options.option.mode.toString().toLowerCase();
        if (mode==="javascript"){
            o2.load("JSBeautifier", function(){
                this.editor.setValue(js_beautify(editor.getValue()));
            }.bind(this));
        }else if (mode==="html"){
            o2.load("JSBeautifier_html", function(){
                this.editor.setValue(html_beautify(editor.getValue()));
            }.bind(this));
        }else if (mode==="css"){
            o2.load("JSBeautifier_css", function(){
                this.editor.setValue(css_beautify(editor.getValue()));
            }.bind(this));
        }else{
            o2.load("JSBeautifier", function(){
                this.editor.setValue(js_beautify(editor.getValue()));
            }.bind(this));
        }
    },
    formatMonaco: function(){
        this.editor.getAction("editor.action.formatDocument").run();
    },
    format: function(){
        if (this.editor){
            switch (this.options.type.toLowerCase()) {
                case "ace": this.formatAce();
                case "monaco": this.formatMonaco();
            }
        }
    },

    focus: function(){
        if (this.editor){
            switch (this.options.type.toLowerCase()) {
                case "ace": this.editor.focus(); this.goto(); break;
                case "monaco": this.editor.focus();
            }
        }
    },
    goto: function(){
        var p = this.editor.getCursorPosition();
        if (p.row==0){
            p.row = this.editor.renderer.getScrollBottomRow();
        }
        this.editor.gotoLine(p.row+1, p.column+1, true);
    },

NoSubject's avatar
NoSubject 已提交
406

NoSubject's avatar
NoSubject 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
	loadCodeMirror: function(callback){
		if (this.fireEvent("queryLoad")){
			this.editorClass.load(function(){
				this.editorClass.loadJavascript(function(editor){
					this.options.option.mode = "javascript";
					this.editor = CodeMirror(this.node, this.options.option);

					this.editor.setSize("100%", "100%");
					this.fireEvent("postLoad");

                    if (callback) callback();
				}.bind(this));
			}.bind(this));
		}
	},
    showLineNumbers: function(){
        if (this.options.type.toLowerCase()=="codeMirror") this.editor.setOption("lineNumbers", true);
    },
    max: function(){
        if (this.options.type.toLowerCase()=="codeMirror") this.editor.setSize("100%", "100%");
    },

    getCursorPixelPosition: function(){
        var session = this.editor.getSession();
        var pos = this.editor.getCursorPosition();
        var line = session.getLine(pos.row);
        var prefix = this.retrievePrecedingIdentifier(line, pos.column);

        var base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
        base.$insertRight = true;

        var renderer = this.editor.renderer;
        var pos = renderer.$cursorLayer.getPixelPosition(base, true);

        var rect = this.editor.container.getBoundingClientRect();
        pos.top += rect.top - renderer.layerConfig.offset;
        pos.left += rect.left - this.editor.renderer.scrollLeft;
        pos.left += renderer.gutterWidth;

        return pos;
    },
    retrievePrecedingIdentifier: function(text, pos, regex) {
        regex = regex || /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;
        var buf = [];
        for (var i = pos-1; i >= 0; i--) {
            if (regex.test(text[i]))
                buf.push(text[i]);
            else
                break;
        }
        return buf.reverse().join("");
    }


});