Client user script editor
[KiwiIRC.git] / client / assets / dev / applet_scripteditor.js
1 (function () {
2 var view = Backbone.View.extend({
3 events: {
4 'click .btn_save': 'onSave'
5 },
6
7 initialize: function (options) {
8 var that = this;
9 this.$el = $($('#tmpl_script_editor').html());
10
11 this.model.on('applet_loaded', function () {
12 that.$el.parent().css('height', '100%');
13 $script('http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js', function (){ that.createAce(); });
14 });
15 },
16
17
18 createAce: function () {
19 var editor_id = 'editor_' + Math.floor(Math.random()*10000000).toString();
20 this.editor_id = editor_id;
21
22 this.$el.find('.editor').attr('id', editor_id);
23
24 this.editor = ace.edit(editor_id);
25 this.editor.setTheme("ace/theme/monokai");
26 this.editor.getSession().setMode("ace/mode/javascript");
27
28 var script_content = _kiwi.global.settings.get('user_script') || '';
29 this.editor.setValue(script_content);
30 },
31
32
33 onSave: function (event) {
34 var script_content, user_fn;
35
36 // Build the user script up with some pre-defined components
37 script_content = 'var network = kiwi.components.Network();\n';
38 script_content += 'var input = kiwi.components.ControlInput();\n';
39 script_content += this.editor.getValue() + '\n';
40
41 // Add a dispose method to the user script for cleaning up
42 script_content += 'this._dispose = function(){ network.off(); if(this.dispose) this.dispose(); }';
43
44 // Try to compile the user script
45 try {
46 user_fn = new Function(script_content);
47
48 // Dispose any existing user script
49 if (_kiwi.user_script && _kiwi.user_script._dispose)
50 _kiwi.user_script._dispose();
51
52 // Create and run the new user script
53 _kiwi.user_script = new user_fn();
54
55 } catch (err) {
56 this.setStatus('Script error. ' + err.toString());
57 return;
58 }
59
60 // If we're this far, no errors occured. Save the user script
61 _kiwi.global.settings.set('user_script', this.editor.getValue());
62 _kiwi.global.settings.save();
63
64 this.setStatus('Your script has been saved and is now active :)');
65 },
66
67
68 setStatus: function (status_text) {
69 var $status = this.$el.find('.toolbar .status');
70
71 status_text = status_text || '';
72 $status.slideUp('fast', function() {
73 $status.text(status_text);
74 $status.slideDown();
75 });
76 }
77 });
78
79
80
81 var applet = Backbone.Model.extend({
82 initialize: function () {
83 var that = this;
84
85 this.set('title', 'Script Editor');
86 this.view = new view({model: this})
87
88 }
89 });
90
91
92 _kiwi.model.Applet.register('kiwi_script_editor', applet);
93 //_kiwi.model.Applet.loadOnce('kiwi_script_editor');
94 })();