Plugowalne akcje w toolbarach.
[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.connectToolbar();
51                         self.callHook('load');
52                 },
53         error: function(request, textStatus, errorThrown) {
54             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
55             $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.");
56         }
57     });
58 }
59
60 Panel.prototype.unload = function(event, data) {
61         $.log('got unload signal', this, ' target: ', data);
62
63         if( data == this ) {
64                 $.log('unloading', this);
65         $(this.contentDiv).html('');
66                 this.callHook('unload');
67                 this.hooks = null; // flush the hooks
68                 return false;
69     };
70 }
71
72 Panel.prototype.refresh = function(event, data) {
73     var self = this;
74     reload = function() {
75         $.log('hard reload for panel ', self.current_url);
76         self.load(self.current_url);
77         return true;
78     }
79
80     if( this.callHook('refresh', reload) )
81         $('.change-notification', this.wrap).fadeOut();
82
83
84 Panel.prototype.otherPanelChanged = function(other) {
85         $.log('panel ', other, ' changed.');
86         if(!this.callHook('dirty'))
87         $('.change-notification', this.wrap).fadeIn();
88 }       
89
90 Panel.prototype.markChanged = function () {
91         this.wrap.addClass('changed');
92 }
93
94 Panel.prototype.changed = function () {
95         return this.wrap.hasClass('changed');
96 }
97
98 Panel.prototype.unmarkChanged = function () {
99         this.wrap.removeClass('changed');
100 }
101
102 Panel.prototype.saveInfo = function() {
103         var saveInfo = {};
104         this.callHook('saveInfo', null, saveInfo);
105         return saveInfo;
106 }
107
108 Panel.prototype.connectToolbar = function() {
109     // check if there is a one
110     var toolbar = $("div.toolbar", this.contentDiv);
111     $.log('Connecting toolbar', toolbar);
112     if(toolbar.length == 0) return;
113
114     // connect group-switch buttons
115     var group_buttons = $('*.toolbar-tabs-container button', toolbar);
116
117     $.log('Found groups:', group_buttons);
118
119     group_buttons.each(function() {
120         var group = $(this);
121         var group_name = group.attr('ui:group');
122         $.log('Connecting group: ' + group_name);
123
124         group.click(function() {
125             // change the active group
126             var active = $("*.toolbar-tabs-container button.active");
127             if (active != group) {
128                 active.removeClass('active');                
129                 group.addClass('active');
130                 $(".toolbar-button-groups-container p").each(function() {
131                     if ( $(this).attr('ui:group') != group_name) 
132                         $(this).hide();
133                     else
134                         $(this).show();
135                 });
136             }
137         });        
138     });
139
140     // connect action buttons
141     var action_buttons = $('*.toolbar-button-groups-container button');
142     action_buttons.each(function() {
143         var button = $(this);
144         var action = button.attr('ui:action').split(':');
145         var action_name = action[0];
146         var action_data = action[1];
147         
148         button.click(function() {
149             $.log('emiting action ', action_name, ' with data: ', action_data);
150             $(document).trigger('ui:action:' + action_name, action_data);
151         });
152     });
153 }
154
155 function Editor() {
156         this.rootDiv = $('#panels');
157     this.popupQueue = [];
158     this.autosaveTimer = null;
159 }
160
161 Editor.prototype.setupUI = function() {
162         // set up the UI visually and attach callbacks
163         var self = this;
164    
165         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
166     // self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
167     
168         $('#panels > *.panel-wrap').each(function() {
169                 var panelWrap = $(this);
170                 $.log('wrap: ', panelWrap);
171                 var panel = new Panel(panelWrap);
172                 panelWrap.data('ctrl', panel); // attach controllers to wraps
173         panel.load($('.panel-toolbar select', panelWrap).val());
174         
175         $('.panel-toolbar select', panelWrap).change(function() {
176             var url = $(this).val();
177             panelWrap.data('ctrl').load(url);
178             self.savePanelOptions();
179         });
180
181         $('.panel-toolbar button.refresh-button', panelWrap).click(
182             function() { panel.refresh(); } );            
183     });
184
185         $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) });
186     
187     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
188     $('#toolbar-button-commit').click( function (event, data) { self.sendPullRequest(); } );
189     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
190 }
191
192 Editor.prototype.loadConfig = function() {
193     // Load options from cookie
194     var defaultOptions = {
195         panels: [
196             {name: 'htmleditor', ratio: 0.5},
197             {name: 'gallery', ratio: 0.5}
198         ],
199         lastUpdate: 0,
200     }
201     
202     try {
203         var cookie = $.cookie('options');
204         this.options = $.secureEvalJSON(cookie);
205         if (!this.options) {
206             this.options = defaultOptions;
207         }
208     } catch (e) {    
209         this.options = defaultOptions;
210     }
211     $.log(this.options);
212     
213     this.loadPanelOptions();
214 }
215
216 Editor.prototype.loadPanelOptions = function() {
217     var self = this;
218     var totalWidth = 0;
219     
220     $('.panel-wrap', self.rootDiv).each(function(index) {
221         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
222         if ($(this).hasClass('last-panel')) {
223             $(this).css({
224                 left: totalWidth,
225                 right: 0,
226             });
227         } else {
228             $(this).css({
229                 left: totalWidth,
230                 width: panelWidth,
231             });
232             totalWidth += panelWidth;               
233         }
234         $.log('panel:', this, $(this).css('left'));
235         $('.panel-toolbar select', this).val(
236             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
237         )
238     });   
239 }
240
241 Editor.prototype.savePanelOptions = function() {
242     var self = this;
243     var panels = [];
244     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
245         panels.push({
246             name: $('.panel-toolbar option:selected', this).attr('name'),
247             ratio: $(this).width() / self.rootDiv.width()
248         })
249     });
250     self.options.panels = panels;
251     self.options.lastUpdate = (new Date()).getTime() / 1000;
252     $.log($.toJSON(self.options));
253     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
254 }
255
256 Editor.prototype.saveToBranch = function(msg) 
257 {
258         var changed_panel = $('.panel-wrap.changed');
259         var self = this;
260         $.log('Saving to local branch - panel:', changed_panel);
261
262         if(!msg) msg = "Zapis z edytora platformy.";
263
264         if( changed_panel.length == 0) {
265                 $.log('Nothing to save.');
266                 return true; /* no changes */
267         }
268
269         if( changed_panel.length > 1) {
270                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
271                 return false;
272         }
273
274         saveInfo = changed_panel.data('ctrl').saveInfo();
275     var postData = ''
276     
277     if(saveInfo.postData instanceof Object)
278         postData = $.param(saveInfo.postData);
279     else
280         postData = saveInfo.postData;
281
282     postData += '&' + $.param({'commit_message': msg})
283
284         $.ajax({
285                 url: saveInfo.url,
286                 dataType: 'json',
287                 success: function(data, textStatus) {
288                         if (data.result != 'ok')
289                                 self.showPopup('save-error', data.errors[0]);
290                         else {
291                                 self.refreshPanels(changed_panel);
292                 $('#toolbar-button-save').attr('disabled', 'disabled');
293                 $('#toolbar-button-commit').removeAttr('disabled');
294                 if(self.autosaveTimer)
295                     clearTimeout(self.autosaveTimer);
296
297                 self.showPopup('save-successful');
298             }
299                 },
300                 error: function(rq, tstat, err) {
301             self.showPopup('save-error');
302                 },
303                 type: 'POST',
304                 data: postData
305         });
306
307     return true;
308 };
309
310 Editor.prototype.autoSave = function() 
311 {
312     this.autosaveTimer = null;
313     // first check if there is anything to save
314     $.log('Autosave');
315     this.saveToBranch("Automatyczny zapis z edytora platformy.");
316 }
317
318 Editor.prototype.onContentChanged = function(event, data) {
319         var self = this;
320
321         $('#toolbar-button-save').removeAttr('disabled');
322         $('#toolbar-button-commit').attr('disabled', 'disabled');
323     
324         if(this.autosaveTimer) return;    
325         this.autosaveTimer = setTimeout( function() { self.autoSave(); }, 300000 );
326 };
327
328 Editor.prototype.refreshPanels = function(goodPanel) {
329         var self = this;
330         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
331
332         panels.each(function() {
333                 var panel = $(this).data('ctrl');
334                 $.log('Refreshing: ', this, panel);
335                 if ( panel.changed() )
336                         panel.unmarkChanged();
337                 else 
338                         panel.refresh();
339         });
340 };              
341
342
343 Editor.prototype.sendPullRequest = function () {
344     if( $('.panel-wrap.changed').length != 0)        
345         alert("There are unsaved changes - can't make a pull request.");
346
347     this.showPopup('not-implemented');
348 /*
349         $.ajax({
350                 url: '/pull-request',
351                 dataType: 'json',
352                 success: function(data, textStatus) {
353             $.log('data: ' + data);
354                 },
355                 error: function(rq, tstat, err) {
356                         $.log('commit error', rq, tstat, err);
357                 },
358                 type: 'POST',
359                 data: {}
360         }); */
361 }
362
363 Editor.prototype.showPopup = function(name, text) 
364 {
365     var self = this;
366     self.popupQueue.push( [name, text] )
367
368     if( self.popupQueue.length > 1) 
369         return;
370
371     var box = $('#message-box > #' + name);
372     $('*.data', box).html(text);
373     box.fadeIn();
374  
375     self._nextPopup = function() {
376         var elem = self.popupQueue.pop()
377         if(elem) {
378             var box = $('#message-box > #' + elem[0]);
379
380             box.fadeOut(300, function() {
381                 $('*.data', box).html();
382     
383                 if( self.popupQueue.length > 0) {
384                     box = $('#message-box > #' + self.popupQueue[0][0]);
385                     $('*.data', box).html(self.popupQueue[0][1]);
386                     box.fadeIn();
387                     setTimeout(self._nextPopup, 5000);
388                 }
389             });
390         }
391     }
392
393     setTimeout(self._nextPopup, 5000);
394 }
395
396
397 $(function() {
398         editor = new Editor();
399
400         // do the layout
401         editor.loadConfig();
402         editor.setupUI();
403 });