Poprawienie skryptu editor.js zgodnie z sugestiami jslist.
[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).empty();
96         
97         this.callHook('unload');
98         this.hooks = null; // flush the hooks
99         return false;
100     }
101 };
102
103 Panel.prototype.refresh = function(event, data) {
104     var self = this;
105     var reload = function() {
106         $.log('hard reload for panel ', self.current_url);
107         self.load(self.current_url);
108         return true;
109     };
110
111     if( this.callHook('refresh', reload) ) {
112         $('.change-notification', this.wrap).fadeOut();
113     }
114 }; 
115
116 Panel.prototype.otherPanelChanged = function(other) {
117     $.log('Panel ', this, ' is aware that ', other, ' changed.');
118     if(!this.callHook('dirty')) {
119         $('.change-notification', this.wrap).fadeIn();
120     }
121 };      
122
123 Panel.prototype.markChanged = function () {
124     this.wrap.addClass('changed');
125 };
126
127 Panel.prototype.changed = function () {
128     return this.wrap.hasClass('changed');
129 };
130
131 Panel.prototype.unmarkChanged = function () {
132     this.wrap.removeClass('changed');
133 };
134
135 Panel.prototype.saveInfo = function() {
136     var saveInfo = {};
137     this.callHook('saveInfo', null, saveInfo);
138     return saveInfo;
139 };
140
141 Panel.prototype.connectToolbar = function()
142 {
143     var self = this;
144     self.hotkeys = [];
145     
146     // check if there is a one
147     var toolbar = $("div.toolbar", this.contentDiv);
148     // $.log('Connecting toolbar', toolbar);
149     if(toolbar.length === 0) return;
150
151     // move the extra
152     var extra_buttons = $('span.panel-toolbar-extra', toolbar);
153     var placeholder = $('div.panel-toolbar span.panel-toolbar-extra', this.wrap);
154     placeholder.replaceWith(extra_buttons);
155     placeholder.hide();
156
157     var action_buttons = $('button', extra_buttons);
158
159     // connect group-switch buttons
160     var group_buttons = $('*.toolbar-tabs-container button', toolbar);
161
162     // $.log('Found groups:', group_buttons);
163
164     group_buttons.each(function() {
165         var group = $(this);
166         var group_name = group.attr('ui:group');
167         // $.log('Connecting group: ' + group_name);
168
169         group.click(function() {
170             // change the active group
171             var active = $("*.toolbar-tabs-container button.active", toolbar);
172             if (active != group) {
173                 active.removeClass('active');                
174                 group.addClass('active');
175                 $(".toolbar-button-groups-container p", toolbar).each(function() {
176                     if ( $(this).attr('ui:group') != group_name) {
177                         $(this).hide();
178                     } else {
179                         $(this).show();
180                     }
181                 });
182                 self.callHook('toolbarResized');
183             }
184         });        
185     });
186
187     // connect action buttons
188     var allbuttons = $.makeArray(action_buttons);
189     $.merge(allbuttons,
190         $.makeArray($('*.toolbar-button-groups-container button', toolbar)) );
191         
192     $(allbuttons).each(function() {
193         var button = $(this);
194         var hk = button.attr('ui:hotkey');
195         if(hk) hk = new Hotkey( parseInt(hk) );
196
197         try {
198             var params = $.evalJSON(button.attr('ui:action-params'));
199         } catch(object) {
200             $.log('JSON exception in ', button, ': ', object);
201             button.attr('disabled', 'disabled');
202             return;
203         }
204
205         var callback = function() {
206             editor.callScriptlet(button.attr('ui:action'), self, params);
207         };
208
209         // connect button
210         button.click(callback);
211        
212         // connect hotkey
213         if(hk) {
214             self.hotkeys[hk.code] = callback;
215         // $.log('hotkey', hk);
216         }
217         
218         // tooltip
219         if (button.attr('ui:tooltip') )
220         {
221             var tooltip = button.attr('ui:tooltip');
222             if(hk) tooltip += ' ['+hk+']';
223
224             button.wTooltip({
225                 delay: 1000,
226                 style: {
227                     border: "1px solid #7F7D67",
228                     opacity: 0.9,
229                     background: "#FBFBC6",
230                     padding: "1px",
231                     fontSize: "12px"
232                 },
233                 content: tooltip
234             });
235         }
236     });
237 };
238
239 Panel.prototype.hotkeyPressed = function(event)
240 {
241     var code = event.keyCode;
242     if(event.altKey) code = code | 0x100;
243     if(event.ctrlKey) code = code | 0x200;
244     if(event.shiftKey) code = code | 0x400;
245
246     var callback = this.hotkeys[code];
247     if(callback) callback();
248 };
249
250 Panel.prototype.isHotkey = function(event) {
251     var code = event.keyCode;
252     if(event.altKey) code = code | 0x100;
253     if(event.ctrlKey) code = code | 0x200;
254     if(event.shiftKey) code = code | 0x400;
255
256     if(this.hotkeys[code] !== null) {
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     $.log(this.options);
302     
303     this.loadPanelOptions();
304 };
305
306 Editor.prototype.loadPanelOptions = function() {
307     var self = this;
308     var totalWidth = 0;
309     
310     $('.panel-wrap', self.rootDiv).each(function(index) {
311         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
312         if ($(this).hasClass('last-panel')) {
313             $(this).css({
314                 left: totalWidth,
315                 right: 0
316             });
317         } else {
318             $(this).css({
319                 left: totalWidth,
320                 width: panelWidth
321             });
322             totalWidth += panelWidth;               
323         }
324         $.log('panel:', this, $(this).css('left'));
325         $('.panel-toolbar option', this).each(function() {
326             if ($(this).attr('p:panel-name') == self.options.panels[index].name) {
327                 $(this).parent('select').val($(this).attr('value'));
328             }
329         });
330     });   
331 };
332
333 Editor.prototype.savePanelOptions = function() {
334     var self = this;
335     var panels = [];
336     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
337         panels.push({
338             name: $('.panel-toolbar option:selected', this).attr('p:panel-name'),
339             ratio: $(this).width() / self.rootDiv.width()
340         });
341     });
342     self.options.panels = panels;
343     self.options.lastUpdate = new Date().getTime() / 1000;
344     $.log($.toJSON(self.options));
345     $.cookie('options', $.toJSON(self.options), {
346         expires: 7,
347         path: '/'
348     });
349 };
350
351 Editor.prototype.saveToBranch = function(msg) 
352 {
353     var changed_panel = $('.panel-wrap.changed');
354     var self = this;
355     $.log('Saving to local branch - panel:', changed_panel);
356
357     if(!msg) msg = "Zapis z edytora platformy.";
358
359     if( changed_panel.length === 0) {
360         $.log('Nothing to save.');
361         return true; /* no changes */
362     }
363
364     if( changed_panel.length > 1) {
365         alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
366         return false;
367     }
368
369     var saveInfo = changed_panel.data('ctrl').saveInfo();
370     var postData = '';
371     
372     if (saveInfo.postData instanceof Object) {
373         postData = $.param(saveInfo.postData);
374     } else {
375         postData = saveInfo.postData;
376     }
377     
378     postData += '&' + $.param({
379         'commit_message': msg
380     });
381
382     self.showPopup('save-waiting', '', -1);
383
384     $.ajax({
385         url: saveInfo.url,
386         dataType: 'json',
387         success: function(data, textStatus) {
388             if (data.result != 'ok') {
389                 self.showPopup('save-error', (data.errors && data.errors[0]) || 'Nieznany błąd X_X.');
390             }
391             else {
392                 self.refreshPanels();
393
394
395                 if(self.autosaveTimer) {
396                     clearTimeout(self.autosaveTimer);
397                 }
398                 if (data.warnings === null) {
399                     self.showPopup('save-successful');
400                 } else {
401                     self.showPopup('save-warn', data.warnings[0]);
402                 }
403             }
404             
405             self.advancePopupQueue();
406         },
407         error: function(rq, tstat, err) {
408             self.showPopup('save-error', '- bład wewnętrzny serwera.');
409             self.advancePopupQueue();
410         },
411         type: 'POST',
412         data: postData
413     });
414
415     return true;
416 };
417
418 Editor.prototype.autoSave = function() 
419 {
420     this.autosaveTimer = null;
421     // first check if there is anything to save
422     $.log('Autosave');
423     this.saveToBranch("Automatyczny zapis z edytora platformy.");
424 };
425
426 Editor.prototype.onContentChanged = function(event, data) {
427     var self = this;
428
429     $('#toolbar-button-save').removeAttr('disabled');
430     $('#toolbar-button-commit').attr('disabled', 'disabled');
431     $('#toolbar-button-update').attr('disabled', 'disabled');
432     
433     if(this.autosaveTimer) return;
434     this.autosaveTimer = setTimeout( function() {
435         self.autoSave();
436     }, 300000 );
437 };
438
439 Editor.prototype.updateUserBranch = function() {
440     if($('.panel-wrap.changed').length !== 0) {
441         alert("There are unsaved changes - can't update.");
442     }
443
444     var self = this;
445     $.ajax({
446         url: $('#toolbar-button-update').attr('ui:ajax-action'),
447         dataType: 'json',
448         success: function(data, textStatus) {
449             switch(data.result) {
450                 case 'done':
451                     self.showPopup('generic-yes', 'Plik uaktualniony.');
452                     self.refreshPanels();
453                     break;
454                 case 'nothing-to-do':
455                     self.showPopup('generic-info', 'Brak zmian do uaktualnienia.');
456                     break;
457                 default:
458                     self.showPopup('generic-error', data.errors && data.errors[0]);
459             }
460         },
461         error: function(rq, tstat, err) {
462             self.showPopup('generic-error', 'Błąd serwera: ' + err);
463         },
464         type: 'POST',
465         data: {}
466     });
467 };
468
469 Editor.prototype.sendMergeRequest = function (message) {
470     if( $('.panel-wrap.changed').length !== 0) {
471         alert("There are unsaved changes - can't commit.");
472     }
473
474     var self =  this;
475     $.log('URL !: ', $('#commit-dialog form').attr('action'));
476     
477     $.ajax({        
478         url: $('#commit-dialog form').attr('action'),
479         dataType: 'json',
480         success: function(data, textStatus) {
481             switch(data.result) {
482                 case 'done':
483                     self.showPopup('generic-yes', 'Łączenie zmian powiodło się.');
484
485                     if(data.localmodified) {
486                         self.refreshPanels();
487                     }
488                         
489                     break;
490                 case 'nothing-to-do':
491                     self.showPopup('generic-info', 'Brak zmian do połaczenia.');
492                     break;
493                 default:
494                     self.showPopup('generic-error', data.errors && data.errors[0]);
495             }
496         },
497         error: function(rq, tstat, err) {
498             self.showPopup('generic-error', 'Błąd serwera: ' + err);
499         },
500         type: 'POST',
501         data: {
502             'message': message
503         }
504     }); 
505 };
506
507 Editor.prototype.postSplitRequest = function(s, f)
508 {
509     $.ajax({
510         url: $('#split-dialog form').attr('action'),
511         dataType: 'html',
512         success: s,
513         error: f,
514         type: 'POST',
515         data: $('#split-dialog form').serialize()
516     });
517 };
518
519
520 Editor.prototype.allPanels = function() {
521     return $('#' + this.rootDiv.attr('id') +' > *.panel-wrap', this.rootDiv.parent());
522 };
523
524 Editor.prototype.registerScriptlet = function(scriptlet_id, scriptlet_func)
525 {
526     // I briefly assume, that it's verified not to break the world on SS
527     if (!this[scriptlet_id]) {
528         this[scriptlet_id] = scriptlet_func;
529     }
530 };
531
532 Editor.prototype.callScriptlet = function(scriptlet_id, panel, params) {
533     var func = this[scriptlet_id];
534     if(!func) {
535         throw 'No scriptlet named "' + scriptlet_id + '" found.';
536     }
537     return func(this, panel, params);
538 };
539
540 $(function() {
541     $.fbind = function (self, func) {
542         return function() { 
543             return func.apply(self, arguments);
544         };
545     };
546     
547     editor = new Editor();
548
549     // do the layout
550     editor.loadConfig();
551     editor.setupUI();
552 });