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