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