Wyświetlanie informacji o błędach w XML i DC. Closes #9.
[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     }
153     
154     try {
155         var cookie = $.cookie('options');
156         this.options = $.secureEvalJSON(cookie);
157         if (!this.options) {
158             this.options = defaultOptions;
159         }
160     } catch (e) {    
161         this.options = defaultOptions;
162     }
163     $.log(this.options);
164     
165     this.loadPanelOptions();
166 }
167
168 Editor.prototype.loadPanelOptions = function() {
169     var self = this;
170     var totalWidth = 0;
171     
172     $('.panel-wrap', self.rootDiv).each(function(index) {
173         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
174         if ($(this).hasClass('last-panel')) {
175             $(this).css({
176                 left: totalWidth,
177                 right: 0,
178             });
179         } else {
180             $(this).css({
181                 left: totalWidth,
182                 width: panelWidth,
183             });
184             totalWidth += panelWidth;               
185         }
186         $.log('panel:', this, $(this).css('left'));
187         $('.panel-toolbar select', this).val(
188             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
189         )
190     });   
191 }
192
193 Editor.prototype.savePanelOptions = function() {
194     var self = this;
195     var panels = [];
196     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
197         panels.push({
198             name: $('.panel-toolbar option:selected', this).attr('name'),
199             ratio: $(this).width() / self.rootDiv.width()
200         })
201     });
202     self.options.panels = panels;
203     $.log($.toJSON(self.options));
204     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
205 }
206
207 Editor.prototype.saveToBranch = function(msg) 
208 {
209         var changed_panel = $('.panel-wrap.changed');
210         var self = this;
211         $.log('Saving to local branch - panel:', changed_panel);
212
213         if(!msg) msg = "Zapis z edytora platformy.";
214
215         if( changed_panel.length == 0) {
216                 $.log('Nothing to save.');
217                 return true; /* no changes */
218         }
219
220         if( changed_panel.length > 1) {
221                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
222                 return false;
223         }
224
225         saveInfo = changed_panel.data('ctrl').saveInfo();
226     var postData = ''
227     
228     if(saveInfo.postData instanceof Object)
229         postData = $.param(saveInfo.postData);
230     else
231         postData = saveInfo.postData;
232
233     postData += '&' + $.param({'commit_message': msg})
234
235         $.ajax({
236                 url: saveInfo.url,
237                 dataType: 'json',
238                 success: function(data, textStatus) {
239                         if (data.result != 'ok')
240                                 self.showPopup('save-error', data.errors[0]);
241                         else {
242                                 self.refreshPanels(changed_panel);
243                 $('#toolbar-button-save').attr('disabled', 'disabled');
244                 $('#toolbar-button-commit').removeAttr('disabled');
245                 if(self.autosaveTimer)
246                     clearTimeout(self.autosaveTimer);
247
248                 self.showPopup('save-successful');
249             }
250                 },
251                 error: function(rq, tstat, err) {
252             self.showPopup('save-error');
253                 },
254                 type: 'POST',
255                 data: postData
256         });
257
258     return true;
259 };
260
261 Editor.prototype.autoSave = function() 
262 {
263     this.autosaveTimer = null;
264     // first check if there is anything to save
265     $.log('Autosave');
266     this.saveToBranch("Automatyczny zapis z edytora platformy.");
267 }
268
269 Editor.prototype.onContentChanged = function(event, data) {
270         var self = this;
271
272         $('#toolbar-button-save').removeAttr('disabled');
273         $('#toolbar-button-commit').attr('disabled', 'disabled');
274     
275         if(this.autosaveTimer) return;    
276         this.autosaveTimer = setTimeout( function() { self.autoSave(); }, 300000 );
277 };
278
279 Editor.prototype.refreshPanels = function(goodPanel) {
280         var self = this;
281         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
282
283         panels.each(function() {
284                 var panel = $(this).data('ctrl');
285                 $.log('Refreshing: ', this, panel);
286                 if ( panel.changed() )
287                         panel.unmarkChanged();
288                 else 
289                         panel.refresh();
290         });
291 };              
292
293
294 Editor.prototype.sendPullRequest = function () {
295     if( $('.panel-wrap.changed').length != 0)        
296         alert("There are unsaved changes - can't make a pull request.");
297
298     this.showPopup('not-implemented');
299 /*
300         $.ajax({
301                 url: '/pull-request',
302                 dataType: 'json',
303                 success: function(data, textStatus) {
304             $.log('data: ' + data);
305                 },
306                 error: function(rq, tstat, err) {
307                         $.log('commit error', rq, tstat, err);
308                 },
309                 type: 'POST',
310                 data: {}
311         }); */
312 }
313
314 Editor.prototype.showPopup = function(name, text) 
315 {
316     var self = this;
317     self.popupQueue.push( [name, text] )
318
319     if( self.popupQueue.length > 1) 
320         return;
321
322     var box = $('#message-box > #' + name);
323     $('*.data', box).html(text);
324     box.fadeIn();
325  
326     self._nextPopup = function() {
327         var elem = self.popupQueue.pop()
328         if(elem) {
329             var box = $('#message-box > #' + elem[0]);
330
331             box.fadeOut(300, function() {
332                 $('*.data', box).html();
333     
334                 if( self.popupQueue.length > 0) {
335                     box = $('#message-box > #' + self.popupQueue[0][0]);
336                     $('*.data', box).html(self.popupQueue[0][1]);
337                     box.fadeIn();
338                     setTimeout(self._nextPopup, 5000);
339                 }
340             });
341         }
342     }
343
344     setTimeout(self._nextPopup, 5000);
345 }
346
347
348 $(function() {
349         editor = new Editor();
350
351         // do the layout
352         editor.loadConfig();
353         editor.setupUI();
354 });