585f3ce227425fa9addb472986cf18d0f11e955e
[redakcja.git] / project / static / js / editor.js
1 function Panel(panelWrap) {
2         var self = this;
3         self.wrap = panelWrap;
4         self.contentDiv = $('.panel-content', panelWrap);
5         self.instanceId = Math.ceil(Math.random() * 1000000000);
6         $.log('new panel - wrap: ', self.wrap);
7         
8         $(document).bind('panel:unload.' + self.instanceId, 
9                         function(event, data) { self.unload(event, data); });   
10
11         $(document).bind('panel:contentChanged', function(event, data) {
12                 $.log(self, ' got changed event from: ', data);
13                 if(self != data) 
14                         self.otherPanelChanged(event.target);
15                 else 
16                         self.markChanged();
17
18                 return false;           
19         });
20 }
21
22 Panel.prototype.callHook = function() {
23     args = $.makeArray(arguments)
24     var hookName = args.splice(0,1)[0]
25     var noHookAction = args.splice(0,1)[0]
26     var result = false;
27
28         $.log('calling hook: ', hookName, 'with args: ', args);
29         if(this.hooks && this.hooks[hookName])
30                 result = this.hooks[hookName].apply(this, args);
31         else if (noHookAction instanceof Function) 
32         result = noHookAction(args);
33     return result;
34 }
35
36 Panel.prototype.load = function (url) {
37     $.log('preparing xhr load: ', this.wrap);
38     $(document).trigger('panel:unload', this);
39         var self = this;
40         self.current_url = url;
41
42     $.ajax({
43         url: url,
44         dataType: 'html',
45                 success: function(data, tstat) {
46                         panel_hooks = null;
47                         $(self.contentDiv).html(data);
48                         self.hooks = panel_hooks;                       
49                         panel_hooks = null;
50                         self.callHook('load');
51                 },
52         error: function(request, textStatus, errorThrown) {
53             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
54             $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.");
55         }
56     });
57 }
58
59 Panel.prototype.unload = function(event, data) {
60         $.log('got unload signal', this, ' target: ', data);
61
62         if( data == this ) {
63                 $.log('unloading', this);
64         $(this.contentDiv).html('');
65                 this.callHook('unload');
66                 this.hooks = null; // flush the hooks
67                 return false;
68     };
69 }
70
71 Panel.prototype.refresh = function(event, data) {
72     var self = this;
73     reload = function() {
74         $.log('hard reload for panel ', self.current_url);
75         self.load(self.current_url);
76         return true;
77     }
78
79     if( this.callHook('refresh', reload) )
80         $('.change-notification', this.wrap).fadeOut();
81
82
83 Panel.prototype.otherPanelChanged = function(other) {
84         $.log('panel ', other, ' changed.');
85         if(!this.callHook('dirty'))
86         $('.change-notification', this.wrap).fadeIn();
87 }       
88
89 Panel.prototype.markChanged = function () {
90         this.wrap.addClass('changed');
91 }
92
93 Panel.prototype.changed = function () {
94         return this.wrap.hasClass('changed');
95 }
96
97 Panel.prototype.unmarkChanged = function () {
98         this.wrap.removeClass('changed');
99 }
100
101 Panel.prototype.saveInfo = function() {
102         var saveInfo = {};
103         this.callHook('saveInfo', null, saveInfo);
104         return saveInfo;
105 }
106
107
108 function Editor() {
109         this.rootDiv = $('#panels');
110     this.popupQueue = [];
111     this.autosaveTimer = null;
112 }
113
114 Editor.prototype.setupUI = function() {
115         // set up the UI visually and attach callbacks
116         var self = this;
117    
118         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
119     // self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
120     
121         $('#panels > *.panel-wrap').each(function() {
122                 var panelWrap = $(this);
123                 $.log('wrap: ', panelWrap);
124                 var panel = new Panel(panelWrap);
125                 panelWrap.data('ctrl', panel); // attach controllers to wraps
126         panel.load($('.panel-toolbar select', panelWrap).val());
127         
128         $('.panel-toolbar select', panelWrap).change(function() {
129             var url = $(this).val();
130             panelWrap.data('ctrl').load(url);
131             self.savePanelOptions();
132         });
133
134         $('.panel-toolbar button.refresh-button', panelWrap).click(
135             function() { panel.refresh(); } );            
136     });
137
138         $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) });
139     
140     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
141     $('#toolbar-button-commit').click( function (event, data) { self.sendPullRequest(); } );
142     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
143 }
144
145 Editor.prototype.loadConfig = function() {
146     // Load options from cookie
147     var defaultOptions = {
148         panels: [
149             {name: 'htmleditor', ratio: 0.5},
150             {name: 'gallery', ratio: 0.5}
151         ],
152         lastUpdate: 0,
153     }
154     
155     try {
156         var cookie = $.cookie('options');
157         this.options = $.secureEvalJSON(cookie);
158         if (!this.options) {
159             this.options = defaultOptions;
160         }
161     } catch (e) {    
162         this.options = defaultOptions;
163     }
164     $.log(this.options);
165     
166     this.loadPanelOptions();
167 }
168
169 Editor.prototype.loadPanelOptions = function() {
170     var self = this;
171     var totalWidth = 0;
172     
173     $('.panel-wrap', self.rootDiv).each(function(index) {
174         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
175         if ($(this).hasClass('last-panel')) {
176             $(this).css({
177                 left: totalWidth,
178                 right: 0,
179             });
180         } else {
181             $(this).css({
182                 left: totalWidth,
183                 width: panelWidth,
184             });
185             totalWidth += panelWidth;               
186         }
187         $.log('panel:', this, $(this).css('left'));
188         $('.panel-toolbar select', this).val(
189             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
190         )
191     });   
192 }
193
194 Editor.prototype.savePanelOptions = function() {
195     var self = this;
196     var panels = [];
197     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
198         panels.push({
199             name: $('.panel-toolbar option:selected', this).attr('name'),
200             ratio: $(this).width() / self.rootDiv.width()
201         })
202     });
203     self.options.panels = panels;
204     self.options.lastUpdate = (new Date()).getTime() / 1000;
205     $.log($.toJSON(self.options));
206     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
207 }
208
209 Editor.prototype.saveToBranch = function(msg) 
210 {
211         var changed_panel = $('.panel-wrap.changed');
212         var self = this;
213         $.log('Saving to local branch - panel:', changed_panel);
214
215         if(!msg) msg = "Zapis z edytora platformy.";
216
217         if( changed_panel.length == 0) {
218                 $.log('Nothing to save.');
219                 return true; /* no changes */
220         }
221
222         if( changed_panel.length > 1) {
223                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
224                 return false;
225         }
226
227         saveInfo = changed_panel.data('ctrl').saveInfo();
228     var postData = ''
229     
230     if(saveInfo.postData instanceof Object)
231         postData = $.param(saveInfo.postData);
232     else
233         postData = saveInfo.postData;
234
235     postData += '&' + $.param({'commit_message': msg})
236
237         $.ajax({
238                 url: saveInfo.url,
239                 dataType: 'json',
240                 success: function(data, textStatus) {
241                         if (data.result != 'ok')
242                                 self.showPopup('save-error', data.errors[0]);
243                         else {
244                                 self.refreshPanels(changed_panel);
245                 $('#toolbar-button-save').attr('disabled', 'disabled');
246                 $('#toolbar-button-commit').removeAttr('disabled');
247                 if(self.autosaveTimer)
248                     clearTimeout(self.autosaveTimer);
249
250                 self.showPopup('save-successful');
251             }
252                 },
253                 error: function(rq, tstat, err) {
254             self.showPopup('save-error');
255                 },
256                 type: 'POST',
257                 data: postData
258         });
259
260     return true;
261 };
262
263 Editor.prototype.autoSave = function() 
264 {
265     this.autosaveTimer = null;
266     // first check if there is anything to save
267     $.log('Autosave');
268     this.saveToBranch("Automatyczny zapis z edytora platformy.");
269 }
270
271 Editor.prototype.onContentChanged = function(event, data) {
272         var self = this;
273
274         $('#toolbar-button-save').removeAttr('disabled');
275         $('#toolbar-button-commit').attr('disabled', 'disabled');
276     
277         if(this.autosaveTimer) return;    
278         this.autosaveTimer = setTimeout( function() { self.autoSave(); }, 300000 );
279 };
280
281 Editor.prototype.refreshPanels = function(goodPanel) {
282         var self = this;
283         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
284
285         panels.each(function() {
286                 var panel = $(this).data('ctrl');
287                 $.log('Refreshing: ', this, panel);
288                 if ( panel.changed() )
289                         panel.unmarkChanged();
290                 else 
291                         panel.refresh();
292         });
293 };              
294
295
296 Editor.prototype.sendPullRequest = function () {
297     if( $('.panel-wrap.changed').length != 0)        
298         alert("There are unsaved changes - can't make a pull request.");
299
300     this.showPopup('not-implemented');
301 /*
302         $.ajax({
303                 url: '/pull-request',
304                 dataType: 'json',
305                 success: function(data, textStatus) {
306             $.log('data: ' + data);
307                 },
308                 error: function(rq, tstat, err) {
309                         $.log('commit error', rq, tstat, err);
310                 },
311                 type: 'POST',
312                 data: {}
313         }); */
314 }
315
316 Editor.prototype.showPopup = function(name, text) 
317 {
318     var self = this;
319     self.popupQueue.push( [name, text] )
320
321     if( self.popupQueue.length > 1) 
322         return;
323
324     var box = $('#message-box > #' + name);
325     $('*.data', box).html(text);
326     box.fadeIn();
327  
328     self._nextPopup = function() {
329         var elem = self.popupQueue.pop()
330         if(elem) {
331             var box = $('#message-box > #' + elem[0]);
332
333             box.fadeOut(300, function() {
334                 $('*.data', box).html();
335     
336                 if( self.popupQueue.length > 0) {
337                     box = $('#message-box > #' + self.popupQueue[0][0]);
338                     $('*.data', box).html(self.popupQueue[0][1]);
339                     box.fadeIn();
340                     setTimeout(self._nextPopup, 5000);
341                 }
342             });
343         }
344     }
345
346     setTimeout(self._nextPopup, 5000);
347 }
348
349
350 $(function() {
351         editor = new Editor();
352
353         // do the layout
354         editor.loadConfig();
355         editor.setupUI();
356 });