Dodanie login_required. Automatyczne tworzenie branchy, przy pierwszym użyciu.
[redakcja.git] / project / static / js / editor.js
1 function Panel(panelWrap) {
2         var self = this;
3         self.wrap = panelWrap;
4         self.contentDiv = $('.panel-content', panelWrap);
5         self.instanceId = Math.ceil(Math.random() * 1000000000);
6         $.log('new panel - wrap: ', self.wrap);
7         
8         $(document).bind('panel:unload.' + self.instanceId, 
9                         function(event, data) { self.unload(event, data); });   
10
11         $(document).bind('panel:contentChanged', function(event, data) {
12                 $.log(self, ' got changed event from: ', data);
13                 if(self != data) 
14                         self.otherPanelChanged(event.target);
15                 else 
16                         self.markChanged();
17
18                 return false;           
19         });
20 }
21
22 Panel.prototype.callHook = function() {
23     args = $.makeArray(arguments)
24     var hookName = args.splice(0,1)[0]
25     var noHookAction = args.splice(0,1)[0]
26     var result = false;
27
28         $.log('calling hook: ', hookName, 'with args: ', args);
29         if(this.hooks && this.hooks[hookName])
30                 result = this.hooks[hookName].apply(this, args);
31         else if (noHookAction instanceof Function) 
32         result = noHookAction(args);
33     return result;
34 }
35
36 Panel.prototype.load = function (url) {
37     $.log('preparing xhr load: ', this.wrap);
38     $(document).trigger('panel:unload', this);
39         var self = this;
40         self.current_url = url;
41
42     $.ajax({
43         url: url,
44         dataType: 'html',
45                 success: function(data, tstat) {
46                         panel_hooks = null;
47                         $(self.contentDiv).html(data);
48                         self.hooks = panel_hooks;                       
49                         panel_hooks = null;
50                         self.callHook('load');
51                 },
52         error: function(request, textStatus, errorThrown) {
53             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
54         }
55     });
56 }
57
58 Panel.prototype.unload = function(event, data) {
59         $.log('got unload signal', this, ' target: ', data);
60
61         if( data == this ) {
62                 $.log('unloading', this);
63         $(this.contentDiv).html('');
64                 this.callHook('unload');
65                 this.hooks = null; // flush the hooks
66                 return false;
67     };
68 }
69
70 Panel.prototype.refresh = function(event, data) {
71     var self = this;
72     reload = function() {
73         $.log('hard reload for panel ', self.current_url);
74         self.load(self.current_url);
75         return true;
76     }
77
78     if( this.callHook('refresh', reload) )
79         $('.change-notification', this.wrap).fadeOut();
80
81
82 Panel.prototype.otherPanelChanged = function(other) {
83         $.log('panel ', other, ' changed.');
84         if(!this.callHook('dirty'))
85         $('.change-notification', this.wrap).fadeIn();
86 }       
87
88 Panel.prototype.markChanged = function () {
89         if(!this.wrap.hasClass('changed') ) // TODO: is this needed ?
90                 this.wrap.addClass('changed');
91 }
92
93 Panel.prototype.changed = function () {
94         return this.wrap.hasClass('changed');
95 }
96
97 Panel.prototype.unmarkChanged = function () {
98         this.wrap.removeClass('changed');
99 }
100
101 Panel.prototype.saveInfo = function() {
102         var saveInfo = {};
103         this.callHook('saveInfo', null, saveInfo);
104         return saveInfo;
105 }
106
107
108 function Editor() {
109         this.rootDiv = $('#panels');
110 }
111
112 Editor.prototype.setupUI = function() {
113         // set up the UI visually and attach callbacks
114         var self = this;
115    
116         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
117     self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
118     
119         $('#panels > *.panel-wrap').each(function() {
120                 var panelWrap = $(this);
121                 $.log('wrap: ', panelWrap);
122                 panel = new Panel(panelWrap);
123                 panelWrap.data('ctrl', panel); // attach controllers to wraps
124         panel.load($('.panel-toolbar select', panelWrap).val());
125         
126         $('.panel-toolbar select', panelWrap).change(function() {
127             var url = $(this).val();
128             panelWrap.data('ctrl').load(url);
129             self.savePanelOptions();
130         });
131     });
132
133         $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) });
134     
135     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
136     $('#toolbar-button-commit').click( function (event, data) { self.sendPullRequest(); } );
137     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
138 }
139
140 Editor.prototype.loadConfig = function() {
141     // Load options from cookie
142     var defaultOptions = {
143         panels: [
144             {name: 'htmleditor', ratio: 0.5},
145             {name: 'gallery', ratio: 0.5}
146         ]
147     }
148     
149     try {
150         var cookie = $.cookie('options');
151         this.options = $.secureEvalJSON(cookie);
152         if (!this.options) {
153             this.options = defaultOptions;
154         }
155     } catch (e) {    
156         this.options = defaultOptions;
157     }
158     $.log(this.options);
159     
160     this.loadPanelOptions();
161 }
162
163 Editor.prototype.loadPanelOptions = function() {
164     var self = this;
165     var totalWidth = 0;
166     
167     $('.panel-wrap', self.rootDiv).each(function(index) {
168         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
169         if ($(this).hasClass('last-panel')) {
170             $(this).css({
171                 left: totalWidth,
172                 right: 0,
173             });
174         } else {
175             $(this).css({
176                 left: totalWidth,
177                 width: panelWidth,
178             });
179             totalWidth += panelWidth;               
180         }
181         $.log('panel:', this, $(this).css('left'));
182         $('.panel-toolbar select', this).val(
183             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
184         )
185     });   
186 }
187
188 Editor.prototype.savePanelOptions = function() {
189     var self = this;
190     var panels = [];
191     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
192         panels.push({
193             name: $('.panel-toolbar option:selected', this).attr('name'),
194             ratio: $(this).width() / self.rootDiv.width()
195         })
196     });
197     self.options.panels = panels;
198     $.log($.toJSON(self.options));
199     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
200 }
201
202 Editor.prototype.saveToBranch = function() {
203         var changed_panel = $('.panel-wrap.changed');
204         var self = this;
205         $.log('Saving to local branch - panel:', changed_panel);
206
207         if( changed_panel.length == 0) {
208                 $.log('Nothing to save.');
209                 return; /* no changes */
210         }
211
212         if( changed_panel.length > 1) {
213                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
214                 return;
215         }
216
217         saveInfo = changed_panel.data('ctrl').saveInfo();
218
219         $.ajax({
220                 url: saveInfo.url,
221                 dataType: 'json',
222                 success: function(data, textStatus) {
223                         if (data.result != 'ok')
224                                 $.log('save errors: ', data.errors)
225                         else {
226                                 self.refreshPanels(changed_panel);
227                 $('#toolbar-button-save').attr('disabled', 'disabled');
228                 $('#toolbar-button-commit').removeAttr('disabled');
229             }
230                 },
231                 error: function(rq, tstat, err) {
232                         $.log('save error', rq, tstat, err);
233                 },
234                 type: 'POST',
235                 data: saveInfo.postData
236         });
237 };
238
239 Editor.prototype.onContentChanged = function(event, data) {
240         $('#toolbar-button-save').removeAttr('disabled');
241         $('#toolbar-button-commit').attr('disabled', 'disabled');
242 };
243
244 Editor.prototype.refreshPanels = function(goodPanel) {
245         var self = this;
246         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
247
248         panels.each(function() {
249                 var panel = $(this).data('ctrl');
250                 $.log('Refreshing: ', this, panel);
251                 if ( panel.changed() )
252                         panel.unmarkChanged();
253                 else 
254                         panel.refresh();
255         });
256 };              
257
258
259 Editor.prototype.sendPullRequest = function () {
260     if( $('.panel-wrap.changed').length != 0)
261         alert("There are unsaved changes - can't make a pull request.");
262
263         $.ajax({
264                 url: '/pull-request',
265                 dataType: 'json',
266                 success: function(data, textStatus) {
267             $.log('data: ' + data);
268                 },
269                 error: function(rq, tstat, err) {
270                         $.log('commit error', rq, tstat, err);
271                 },
272                 type: 'POST',
273                 data: {}
274         });
275 }
276
277 $(function() {
278         editor = new Editor();
279
280         // do the layout
281         editor.loadConfig();
282         editor.setupUI();
283 });