* Plugin jQuery.modal
[redakcja.git] / project / static / js / editor.js
1 function Hotkey(code) {
2     this.code = code
3     this.has_alt = ((code & 0x01 << 8) != 0)
4     this.has_ctrl = ((code & 0x01 << 9) != 0)
5     this.has_shift = ((code & 0x01 << 10) != 0)
6     this.character = String.fromCharCode(code & 0xff)
7 }
8
9 Hotkey.prototype.toString = function() {
10     mods = []
11     if(this.has_alt) mods.push('Alt')
12     if(this.has_ctrl) mods.push('Ctrl')
13     if(this.has_shift) mods.push('Shift')
14     mods.push('"'+this.character+'"')
15     return mods.join('+')
16 }
17
18 function Panel(panelWrap) {
19     var self = this;
20     self.hotkeys = [];
21     self.wrap = panelWrap;
22     self.contentDiv = $('.panel-content', panelWrap);
23     self.instanceId = Math.ceil(Math.random() * 1000000000);
24     // $.log('new panel - wrap: ', self.wrap);
25         
26     $(document).bind('panel:unload.' + self.instanceId,
27         function(event, data) {
28             self.unload(event, data);
29         });
30
31     $(document).bind('panel:contentChanged', function(event, data) {
32         $.log(self, ' got changed event from: ', data);
33         if(self != data)
34             self.otherPanelChanged(event.target);
35         else
36             self.markChanged();
37
38         return false;
39     });
40 }
41
42 Panel.prototype.callHook = function() {
43     var args = $.makeArray(arguments)
44     var hookName = args.splice(0,1)[0]
45     var noHookAction = args.splice(0,1)[0]
46     var result = false;
47
48     // $.log('calling hook: ', hookName, 'with args: ', args);
49     if(this.hooks && this.hooks[hookName])
50         result = this.hooks[hookName].apply(this, args);
51     else if (noHookAction instanceof Function)
52         result = noHookAction(args);
53     return result;
54 }
55
56 Panel.prototype.load = function (url) {
57     // $.log('preparing xhr load: ', this.wrap);
58     $(document).trigger('panel:unload', this);
59     var self = this;
60     self.current_url = url;
61
62     $.ajax({
63         url: url,
64         dataType: 'html',
65         success: function(data, tstat) {
66             panel_hooks = null;
67             $(self.contentDiv).html(data);
68             self.hooks = panel_hooks;
69             panel_hooks = null;
70             self.connectToolbar();
71             self.callHook('load');
72             self.callHook('toolbarResized');
73         },
74         error: function(request, textStatus, errorThrown) {
75             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
76             $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.");
77         }
78     });
79 }
80
81 Panel.prototype.unload = function(event, data) {
82     // $.log('got unload signal', this, ' target: ', data);
83     if( data == this ) {        
84         $(this.contentDiv).html('');
85
86         // disconnect the toolbar
87         $('div.panel-toolbar span.panel-toolbar-extra', this.wrap).empty();
88         
89         this.callHook('unload');
90         this.hooks = null; // flush the hooks
91         return false;
92     };
93 }
94
95 Panel.prototype.refresh = function(event, data) {
96     var self = this;
97     reload = function() {
98         $.log('hard reload for panel ', self.current_url);
99         self.load(self.current_url);
100         return true;
101     }
102
103     if( this.callHook('refresh', reload) )
104         $('.change-notification', this.wrap).fadeOut();
105
106
107 Panel.prototype.otherPanelChanged = function(other) {
108     $.log('Panel ', this, ' is aware that ', other, ' changed.');
109     if(!this.callHook('dirty'))
110         $('.change-notification', this.wrap).fadeIn();
111 }       
112
113 Panel.prototype.markChanged = function () {
114     this.wrap.addClass('changed');
115 }
116
117 Panel.prototype.changed = function () {
118     return this.wrap.hasClass('changed');
119 }
120
121 Panel.prototype.unmarkChanged = function () {
122     this.wrap.removeClass('changed');
123 }
124
125 Panel.prototype.saveInfo = function() {
126     var saveInfo = {};
127     this.callHook('saveInfo', null, saveInfo);
128     return saveInfo;
129 }
130
131 Panel.prototype.connectToolbar = function()
132 {
133     var self = this;
134     self.hotkeys = [];
135     
136     // check if there is a one
137     var toolbar = $("div.toolbar", this.contentDiv);
138     // $.log('Connecting toolbar', toolbar);
139     if(toolbar.length == 0) return;
140
141     // move the extra
142     var extra_buttons = $('span.panel-toolbar-extra', toolbar);
143     var placeholder = $('div.panel-toolbar span.panel-toolbar-extra', this.wrap);
144     placeholder.replaceWith(extra_buttons);
145
146     var action_buttons = $('button', extra_buttons);
147
148     // connect group-switch buttons
149     var group_buttons = $('*.toolbar-tabs-container button', toolbar);
150
151     // $.log('Found groups:', group_buttons);
152
153     group_buttons.each(function() {
154         var group = $(this);
155         var group_name = group.attr('ui:group');
156         // $.log('Connecting group: ' + group_name);
157
158         group.click(function() {
159             // change the active group
160             var active = $("*.toolbar-tabs-container button.active", toolbar);
161             if (active != group) {
162                 active.removeClass('active');                
163                 group.addClass('active');
164                 $(".toolbar-button-groups-container p", toolbar).each(function() {
165                     if ( $(this).attr('ui:group') != group_name) 
166                         $(this).hide();
167                     else
168                         $(this).show();
169                 });
170                 self.callHook('toolbarResized');
171             }
172         });        
173     });
174
175     // connect action buttons
176     var allbuttons = $.makeArray(action_buttons)
177     $.merge(allbuttons,
178         $.makeArray($('*.toolbar-button-groups-container button', toolbar)) );
179         
180     $(allbuttons).each(function() {
181         var button = $(this);
182         var hk = button.attr('ui:hotkey');
183         if(hk) hk = new Hotkey( parseInt(hk) );
184
185         try {
186             var params = $.evalJSON(button.attr('ui:action-params'));
187         } catch(object) {
188             $.log('JSON exception in ', button, ': ', object);
189             button.attr('disabled', 'disabled');
190             return;
191         }
192
193         var callback = function() {
194             editor.callScriptlet(button.attr('ui:action'), self, params);
195         };
196
197         // connect button
198         button.click(callback);
199        
200         // connect hotkey
201         if(hk) {
202             self.hotkeys[hk.code] = callback;
203         // $.log('hotkey', hk);
204         }
205         
206         // tooltip
207         if (button.attr('ui:tooltip') )
208         {
209             var tooltip = button.attr('ui:tooltip');
210             if(hk) tooltip += ' ['+hk+']';
211
212             button.wTooltip({
213                 delay: 1000,
214                 style: {
215                     border: "1px solid #7F7D67",
216                     opacity: 0.9,
217                     background: "#FBFBC6",
218                     padding: "1px",
219                     fontSize: "12px"
220                 },
221                 content: tooltip
222             });
223         }
224     });
225 }
226
227 Panel.prototype.hotkeyPressed = function(event)
228 {
229     code = event.keyCode;
230     if(event.altKey) code = code | 0x100;
231     if(event.ctrlKey) code = code | 0x200;
232     if(event.shiftKey) code = code | 0x400;
233
234     var callback = this.hotkeys[code];
235     if(callback) callback();
236 }
237
238 Panel.prototype.isHotkey = function(event) {
239     code = event.keyCode;
240     if(event.altKey) code = code | 0x100;
241     if(event.ctrlKey) code = code | 0x200;
242     if(event.shiftKey) code = code | 0x400;
243
244     if(this.hotkeys[code] != null)
245         return true;
246         
247     return false;
248 }
249
250 //
251 Panel.prototype.fireEvent = function(name) {
252     $(document).trigger('panel:'+name, this);
253 }
254
255 function Editor()
256 {
257     this.rootDiv = $('#panels');
258     this.popupQueue = [];
259     this.autosaveTimer = null;
260     this.scriplets = {};
261 }
262
263 Editor.prototype.loadConfig = function() {
264     // Load options from cookie
265     var defaultOptions = {
266         panels: [
267         {
268             name: 'htmleditor',
269             ratio: 0.5
270         },
271
272         {
273             name: 'gallery',
274             ratio: 0.5
275         }
276         ],
277         lastUpdate: 0
278     }
279     
280     try {
281         var cookie = $.cookie('options');
282         this.options = $.secureEvalJSON(cookie);
283         if (!this.options) {
284             this.options = defaultOptions;
285         }
286     } catch (e) {    
287         this.options = defaultOptions;
288     }
289     $.log(this.options);
290     
291     this.loadPanelOptions();
292 }
293
294 Editor.prototype.loadPanelOptions = function() {
295     var self = this;
296     var totalWidth = 0;
297     
298     $('.panel-wrap', self.rootDiv).each(function(index) {
299         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
300         if ($(this).hasClass('last-panel')) {
301             $(this).css({
302                 left: totalWidth,
303                 right: 0
304             });
305         } else {
306             $(this).css({
307                 left: totalWidth,
308                 width: panelWidth
309             });
310             totalWidth += panelWidth;               
311         }
312         $.log('panel:', this, $(this).css('left'));
313         $('.panel-toolbar select', this).val(
314             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
315             )
316     });   
317 }
318
319 Editor.prototype.savePanelOptions = function() {
320     var self = this;
321     var panels = [];
322     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
323         panels.push({
324             name: $('.panel-toolbar option:selected', this).attr('name'),
325             ratio: $(this).width() / self.rootDiv.width()
326         })
327     });
328     self.options.panels = panels;
329     self.options.lastUpdate = (new Date()).getTime() / 1000;
330     $.log($.toJSON(self.options));
331     $.cookie('options', $.toJSON(self.options), {
332         expires: 7,
333         path: '/'
334     });
335 }
336
337 Editor.prototype.saveToBranch = function(msg) 
338 {
339     var changed_panel = $('.panel-wrap.changed');
340     var self = this;
341     $.log('Saving to local branch - panel:', changed_panel);
342
343     if(!msg) msg = "Zapis z edytora platformy.";
344
345     if( changed_panel.length == 0) {
346         $.log('Nothing to save.');
347         return true; /* no changes */
348     }
349
350     if( changed_panel.length > 1) {
351         alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
352         return false;
353     }
354
355     saveInfo = changed_panel.data('ctrl').saveInfo();
356     var postData = ''
357     
358     if(saveInfo.postData instanceof Object)
359         postData = $.param(saveInfo.postData);
360     else
361         postData = saveInfo.postData;
362
363     postData += '&' + $.param({
364         'commit_message': msg
365     })
366
367     self.showPopup('save-waiting', '', -1);
368
369     $.ajax({
370         url: saveInfo.url,
371         dataType: 'json',
372         success: function(data, textStatus) {
373             if (data.result != 'ok') {
374                 self.showPopup('save-error', (data.errors && data.errors[0]) || 'Nieznany błąd X_X.');
375             }
376             else {
377                 self.refreshPanels();
378                 $('#toolbar-button-save').attr('disabled', 'disabled');
379                 $('#toolbar-button-commit').removeAttr('disabled');
380                 $('#toolbar-button-update').removeAttr('disabled');
381                 if(self.autosaveTimer)
382                     clearTimeout(self.autosaveTimer);
383
384                 if (data.warnings == null)
385                     self.showPopup('save-successful');
386                 else
387                     self.showPopup('save-warn', data.warnings[0]);
388             }
389             
390             self.advancePopupQueue();
391         },
392         error: function(rq, tstat, err) {
393             self.showPopup('save-error', '- bład wewnętrzny serwera.');
394             self.advancePopupQueue();
395         },
396         type: 'POST',
397         data: postData
398     });
399
400     return true;
401 };
402
403 Editor.prototype.autoSave = function() 
404 {
405     this.autosaveTimer = null;
406     // first check if there is anything to save
407     $.log('Autosave');
408     this.saveToBranch("Automatyczny zapis z edytora platformy.");
409 }
410
411 Editor.prototype.onContentChanged = function(event, data) {
412     var self = this;
413
414     $('#toolbar-button-save').removeAttr('disabled');
415     $('#toolbar-button-commit').attr('disabled', 'disabled');
416     $('#toolbar-button-update').attr('disabled', 'disabled');
417     
418     if(this.autosaveTimer) return;
419     this.autosaveTimer = setTimeout( function() {
420         self.autoSave();
421     }, 300000 );
422 };
423
424 Editor.prototype.updateUserBranch = function() {
425     if( $('.panel-wrap.changed').length != 0)
426         alert("There are unsaved changes - can't update.");
427
428     var self = this;
429     $.ajax({
430         url: $('#toolbar-button-update').attr('ui:ajax-action'),
431         dataType: 'json',
432         success: function(data, textStatus) {
433             switch(data.result) {
434                 case 'done':
435                     self.showPopup('generic-yes', 'Plik uaktualniony.');
436                     self.refreshPanels()
437                     break;
438                 case 'nothing-to-do':
439                     self.showPopup('generic-info', 'Brak zmian do uaktualnienia.');
440                     break;
441                 default:
442                     self.showPopup('generic-error', data.errors && data.errors[0]);
443             }
444         },
445         error: function(rq, tstat, err) {
446             self.showPopup('generic-error', 'Błąd serwera: ' + err);
447         },
448         type: 'POST',
449         data: {}
450     });
451 }
452
453 Editor.prototype.sendMergeRequest = function (message) {
454     if( $('.panel-wrap.changed').length != 0)        
455         alert("There are unsaved changes - can't commit.");
456
457     var self =  this;
458     $.log('URL !: ', $('#commit-dialog form').attr('action'));
459     
460     $.ajax({        
461         url: $('#commit-dialog form').attr('action'),
462         dataType: 'json',
463         success: function(data, textStatus) {
464             switch(data.result) {
465                 case 'done':
466                     self.showPopup('generic-yes', 'Łączenie zmian powiodło się.');
467
468                     if(data.localmodified)
469                         self.refreshPanels()
470                         
471                     break;
472                 case 'nothing-to-do':
473                     self.showPopup('generic-info', 'Brak zmian do połaczenia.');
474                     break;
475                 default:
476                     self.showPopup('generic-error', data.errors && data.errors[0]);
477             }
478         },
479         error: function(rq, tstat, err) {
480             self.showPopup('generic-error', 'Błąd serwera: ' + err);
481         },
482         type: 'POST',
483         data: {
484             'message': message
485         }
486     }); 
487 }
488
489 Editor.prototype.postSplitRequest = function(s, f)
490 {
491     $.ajax({
492         url: $('#split-dialog form').attr('action'),
493         dataType: 'html',
494         success: s,
495         error: f,
496         type: 'POST',
497         data: $('#split-dialog form').serialize()
498     });
499 };
500
501
502 Editor.prototype.allPanels = function() {
503     return $('#' + this.rootDiv.attr('id') +' > *.panel-wrap', this.rootDiv.parent());
504 }
505
506 Editor.prototype.registerScriptlet = function(scriptlet_id, scriptlet_func)
507 {
508     // I briefly assume, that it's verified not to break the world on SS
509     if (!this[scriptlet_id])
510         this[scriptlet_id] = scriptlet_func;
511 }
512
513 Editor.prototype.callScriptlet = function(scriptlet_id, panel, params) {
514     var func = this[scriptlet_id]
515     if(!func)
516         throw 'No scriptlet named "' + scriptlet_id + '" found.';
517
518     return func(this, panel, params);
519 }
520   
521 $(function() {
522     $.fbind = function (self, func) {
523         return function() { 
524             return func.apply(self, arguments);
525         };
526     };
527     
528     editor = new Editor();
529
530     // do the layout
531     editor.loadConfig();
532     editor.setupUI();
533 });