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