46d3941934f2078e18c6797efe941409216139ce
[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 option', this).each(function() {
314             if ($(this).attr('p:panel-name') == self.options.panels[index].name) {
315                 $(this).parent('select').val($(this).attr('value'));
316             }
317         });
318     });   
319 }
320
321 Editor.prototype.savePanelOptions = function() {
322     var self = this;
323     var panels = [];
324     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
325         panels.push({
326             name: $('.panel-toolbar option:selected', this).attr('p:panel-name'),
327             ratio: $(this).width() / self.rootDiv.width()
328         })
329     });
330     self.options.panels = panels;
331     self.options.lastUpdate = (new Date()).getTime() / 1000;
332     $.log($.toJSON(self.options));
333     $.cookie('options', $.toJSON(self.options), {
334         expires: 7,
335         path: '/'
336     });
337 }
338
339 Editor.prototype.saveToBranch = function(msg) 
340 {
341     var changed_panel = $('.panel-wrap.changed');
342     var self = this;
343     $.log('Saving to local branch - panel:', changed_panel);
344
345     if(!msg) msg = "Zapis z edytora platformy.";
346
347     if( changed_panel.length == 0) {
348         $.log('Nothing to save.');
349         return true; /* no changes */
350     }
351
352     if( changed_panel.length > 1) {
353         alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
354         return false;
355     }
356
357     saveInfo = changed_panel.data('ctrl').saveInfo();
358     var postData = ''
359     
360     if(saveInfo.postData instanceof Object)
361         postData = $.param(saveInfo.postData);
362     else
363         postData = saveInfo.postData;
364
365     postData += '&' + $.param({
366         'commit_message': msg
367     })
368
369     self.showPopup('save-waiting', '', -1);
370
371     $.ajax({
372         url: saveInfo.url,
373         dataType: 'json',
374         success: function(data, textStatus) {
375             if (data.result != 'ok') {
376                 self.showPopup('save-error', (data.errors && data.errors[0]) || 'Nieznany błąd X_X.');
377             }
378             else {
379                 self.refreshPanels();
380                 $('#toolbar-button-save').attr('disabled', 'disabled');
381                 $('#toolbar-button-commit').removeAttr('disabled');
382                 $('#toolbar-button-update').removeAttr('disabled');
383                 if(self.autosaveTimer)
384                     clearTimeout(self.autosaveTimer);
385
386                 if (data.warnings == null)
387                     self.showPopup('save-successful');
388                 else
389                     self.showPopup('save-warn', data.warnings[0]);
390             }
391             
392             self.advancePopupQueue();
393         },
394         error: function(rq, tstat, err) {
395             self.showPopup('save-error', '- bład wewnętrzny serwera.');
396             self.advancePopupQueue();
397         },
398         type: 'POST',
399         data: postData
400     });
401
402     return true;
403 };
404
405 Editor.prototype.autoSave = function() 
406 {
407     this.autosaveTimer = null;
408     // first check if there is anything to save
409     $.log('Autosave');
410     this.saveToBranch("Automatyczny zapis z edytora platformy.");
411 }
412
413 Editor.prototype.onContentChanged = function(event, data) {
414     var self = this;
415
416     $('#toolbar-button-save').removeAttr('disabled');
417     $('#toolbar-button-commit').attr('disabled', 'disabled');
418     $('#toolbar-button-update').attr('disabled', 'disabled');
419     
420     if(this.autosaveTimer) return;
421     this.autosaveTimer = setTimeout( function() {
422         self.autoSave();
423     }, 300000 );
424 };
425
426 Editor.prototype.updateUserBranch = function() {
427     if( $('.panel-wrap.changed').length != 0)
428         alert("There are unsaved changes - can't update.");
429
430     var self = this;
431     $.ajax({
432         url: $('#toolbar-button-update').attr('ui:ajax-action'),
433         dataType: 'json',
434         success: function(data, textStatus) {
435             switch(data.result) {
436                 case 'done':
437                     self.showPopup('generic-yes', 'Plik uaktualniony.');
438                     self.refreshPanels()
439                     break;
440                 case 'nothing-to-do':
441                     self.showPopup('generic-info', 'Brak zmian do uaktualnienia.');
442                     break;
443                 default:
444                     self.showPopup('generic-error', data.errors && data.errors[0]);
445             }
446         },
447         error: function(rq, tstat, err) {
448             self.showPopup('generic-error', 'Błąd serwera: ' + err);
449         },
450         type: 'POST',
451         data: {}
452     });
453 }
454
455 Editor.prototype.sendMergeRequest = function (message) {
456     if( $('.panel-wrap.changed').length != 0)        
457         alert("There are unsaved changes - can't commit.");
458
459     var self =  this;
460     $.log('URL !: ', $('#commit-dialog form').attr('action'));
461     
462     $.ajax({        
463         url: $('#commit-dialog form').attr('action'),
464         dataType: 'json',
465         success: function(data, textStatus) {
466             switch(data.result) {
467                 case 'done':
468                     self.showPopup('generic-yes', 'Łączenie zmian powiodło się.');
469
470                     if(data.localmodified)
471                         self.refreshPanels()
472                         
473                     break;
474                 case 'nothing-to-do':
475                     self.showPopup('generic-info', 'Brak zmian do połaczenia.');
476                     break;
477                 default:
478                     self.showPopup('generic-error', data.errors && data.errors[0]);
479             }
480         },
481         error: function(rq, tstat, err) {
482             self.showPopup('generic-error', 'Błąd serwera: ' + err);
483         },
484         type: 'POST',
485         data: {
486             'message': message
487         }
488     }); 
489 }
490
491 Editor.prototype.postSplitRequest = function(s, f)
492 {
493     $.ajax({
494         url: $('#split-dialog form').attr('action'),
495         dataType: 'html',
496         success: s,
497         error: f,
498         type: 'POST',
499         data: $('#split-dialog form').serialize()
500     });
501 };
502
503
504 Editor.prototype.allPanels = function() {
505     return $('#' + this.rootDiv.attr('id') +' > *.panel-wrap', this.rootDiv.parent());
506 }
507
508 Editor.prototype.registerScriptlet = function(scriptlet_id, scriptlet_func)
509 {
510     // I briefly assume, that it's verified not to break the world on SS
511     if (!this[scriptlet_id])
512         this[scriptlet_id] = scriptlet_func;
513 }
514
515 Editor.prototype.callScriptlet = function(scriptlet_id, panel, params) {
516     var func = this[scriptlet_id]
517     if(!func)
518         throw 'No scriptlet named "' + scriptlet_id + '" found.';
519
520     return func(this, panel, params);
521 }
522   
523 $(function() {
524     $.fbind = function (self, func) {
525         return function() { 
526             return func.apply(self, arguments);
527         };
528     };
529     
530     editor = new Editor();
531
532     // do the layout
533     editor.loadConfig();
534     editor.setupUI();
535 });