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