update
[redakcja.git] / src / redakcja / static / js / wiki / base.js
1 (function($)
2 {
3         var noop = function() { };
4
5         $.wiki = {
6                 perspectives: {},
7                 cls: {},
8                 state: {
9                         "version": 1,
10                         "perspectives": {
11                                 "ScanGalleryPerspective": {
12                                         "show": true,
13                                         "page": undefined
14                                 },
15                                 "CodeMirrorPerspective": {}
16                                 /*
17                                 "VisualPerspective": {},
18                                 "HistoryPerspective": {},
19                                 "SummaryPerspective": {}
20                                 */
21                         }
22                 }
23         };
24
25         $.wiki.loadConfig = function() {
26                 if(!window.localStorage)
27                         return;
28
29                 try {
30                         var value = window.localStorage.getItem(CurrentDocument.id) || "{}";
31                         var config = JSON.parse(value);
32
33                         if (config.version == $.wiki.state.version) {
34                                 $.wiki.state.perspectives = $.extend($.wiki.state.perspectives, config.perspectives);
35                         }
36                 } catch(e) {
37                         console.log("Failed to load config, using default.");
38                 }
39
40                 console.log("Loaded:", $.wiki.state, $.wiki.state.version);
41         };
42
43         $(window).bind('unload', function() {
44                 if(window.localStorage)
45                         window.localStorage.setItem(CurrentDocument.id, JSON.stringify($.wiki.state));
46         })
47
48
49         $.wiki.activePerspective = function() {
50             return this.perspectives[$("#tabs li a.active").parent().attr('id')];
51         };
52
53         $.wiki.exitContext = function() {
54                 var ap = this.activePerspective();
55                 if(ap) ap.onExit();
56                 return ap;
57         };
58
59         $.wiki.enterContext = function(ap) {
60                 if(ap) ap.onEnter();
61         };
62
63         $.wiki.isDirty = function() {
64                 var ap = this.activePerspective();
65                 return (!!CurrentDocument && CurrentDocument.has_local_changes) || ap.dirty();
66         };
67
68         $.wiki.newTab = function(doc, title, klass) {
69                 var base_id = 'id' + Math.floor(Math.random()* 5000000000);
70                 var id = (''+klass)+'_' + base_id;
71                 var $tab = $('<li class="nav-item" id="'+id+'" data-ui-related="'+base_id+'" data-ui-jsclass="'+klass+'" ><a href="#" class="nav-link">'
72                                 + title + ' <span class="badge badge-danger tabclose">x</span></a></li>');
73                 var $view = $('<div class="editor '+klass+'" id="'+base_id+'"> </div>');
74
75                 this.perspectives[id] = new $.wiki[klass]({
76                         doc: doc,
77                         id: id,
78                         base_id: base_id,
79                 });
80
81                 $('#tabs').append($tab);
82                 $view.hide().appendTo('#editor');
83                 return {
84                         tab: $tab[0],
85                         view: $view[0],
86                 };
87         };
88
89         $.wiki.initTab = function(options) {
90                 var klass = $(options.tab).attr('data-ui-jsclass');
91
92                 return new $.wiki[klass]({
93                         doc: options.doc,
94                         id: $(options.tab).attr('id'),
95                         callback: function() {
96                                 $.wiki.perspectives[this.perspective_id] = this;
97                                 if(options.callback)
98                                         options.callback.call(this);
99                         }
100                 });
101         };
102
103         $.wiki.perspectiveForTab = function(tab) { // element or id
104                 return this.perspectives[ $(tab).attr('id')];
105         }
106
107     $.wiki.switchToTab = function(tab){
108         var self = this;
109         var $tab = $(tab);
110
111         if($tab.length != 1)
112             $tab = $(DEFAULT_PERSPECTIVE);
113
114         var $old_a = $tab.closest('.tabs').find('.active');
115
116         $old_a.each(function(){
117             var tab = $(this).parent()
118             $(this).removeClass('active');
119             self.perspectives[tab.attr('id')].onExit();
120             $('#' + tab.attr('data-ui-related')).hide();
121         });
122
123         /* show new */
124         $('a', tab).addClass('active');
125         $('#' + $tab.attr('data-ui-related')).show();
126
127         console.log($tab);
128         console.log($.wiki.perspectives);
129
130         $.wiki.perspectives[$tab.attr('id')].onEnter();
131     };
132
133         /*
134          * Basic perspective.
135          */
136         $.wiki.Perspective = function(options) {
137                 if(!options) return;
138
139                 this.doc = options.doc;
140                 if (options.id) {
141                         this.perspective_id = options.id;
142                 }
143                 else {
144                         this.perspective_id = '';
145                 }
146
147                 if(options.callback)
148                         options.callback.call(this);
149         };
150
151         $.wiki.Perspective.prototype.config = function() {
152                 return $.wiki.state.perspectives[this.perspective_id];
153         }
154
155         $.wiki.Perspective.prototype.toString = function() {
156                 return this.perspective_id;
157         };
158
159         $.wiki.Perspective.prototype.dirty = function() {
160                 return true;
161         };
162
163         $.wiki.Perspective.prototype.onEnter = function () {
164                 // called when perspective in initialized
165                 if (!this.noupdate_hash_onenter) {
166                         document.location.hash = '#' + this.perspective_id;
167                 }
168         };
169
170         $.wiki.Perspective.prototype.onExit = function () {
171                 // called when user switches to another perspective
172                 if (!this.noupdate_hash_onenter) {
173                         document.location.hash = '';
174                 }
175         };
176
177         $.wiki.Perspective.prototype.destroy = function() {
178                 // pass
179         };
180
181         $.wiki.Perspective.prototype.freezeState = function () {
182                 // free UI state (don't store data here)
183         };
184
185         $.wiki.Perspective.prototype.unfreezeState = function (frozenState) {
186                 // restore UI state
187         };
188
189         /*
190          * Stub rendering (used in generating history)
191          */
192         $.wiki.renderStub = function(params)
193         {
194                 params = $.extend({ 'filters': {} }, params);
195                 var $elem = params.stub.clone();
196                 $elem.removeClass('row-stub');
197                 params.container.append($elem);
198
199                 $('*[data-stub-value]', $elem).each(function() {
200                         var $this = $(this);
201                         var field = $this.attr('data-stub-value');
202
203                         var value = params.data[field];
204
205                         if(params.filters[field])
206                                 value = params.filters[field](value);
207
208                         if(value === null || value === undefined) return;
209
210                         if(!$this.attr('data-stub-target')) {
211                                 $this.text(value);
212                         }
213                         else {
214                                 $this.attr($this.attr('data-stub-target'), value);
215                                 $this.removeAttr('data-stub-target');
216                                 $this.removeAttr('data-stub-value');
217                         }
218                 });
219
220                 $elem.show();
221                 return $elem;
222         };
223
224         /*
225          * Dialogs
226          */
227         function GenericDialog(element) {
228                 if(!element) return;
229
230                 var self = this;
231
232                 self.$elem = $(element);
233
234                 if(!self.$elem.attr('data-ui-initialized')) {
235                         console.log("Initializing dialog", this);
236                         self.initialize();
237                         self.$elem.attr('data-ui-initialized', true);
238                 }
239
240                 self.show();
241         };
242
243         GenericDialog.prototype = {
244
245                 /*
246                 * Steps to follow when the dialog in first loaded on page.
247                 */
248                 initialize: function(){
249                         var self = this;
250
251                         /* bind buttons */
252                         $('button[data-ui-action]', self.$elem).click(function(event) {
253                                 event.preventDefault();
254
255                                 var action = $(this).attr('data-ui-action');
256                                 console.log("Button pressed, action: ", action);
257
258                                 try {
259                                         self[action + "Action"].call(self);
260                                 } catch(e) {
261                                         console.log("Action failed:", e);
262                                         // always hide on cancel
263                                         if(action == 'cancel')
264                                                 self.hide();
265                                 }
266                         });
267                 },
268
269                 /*
270                  * Prepare dialog for user. Clear any unnessary data.
271                 */
272                 show: function() {
273                         $.blockUI({
274                                 message: this.$elem,
275                                 css: {
276                                     'top': '25%',
277                                     'left': '25%',
278                                     'width': '50%',
279                                     'max-height': '75%',
280                                     'overflow-y': 'scroll'
281                                 }
282                         });
283                 },
284
285                 hide: function(){
286                         $.unblockUI();
287                 },
288
289                 cancelAction: function() {
290                         this.hide();
291                 },
292
293                 doneAction: function() {
294                         this.hide();
295                 },
296
297                 clearForm: function() {
298                         $("*[data-ui-error-for]", this.$elem).text('');
299                 },
300
301                 reportErrors: function(errors) {
302                         var global = $("*[data-ui-error-for='__all__']", this.$elem);
303                         var unassigned = [];
304
305             $("*[data-ui-error-for]", this.$elem).text('');
306                         for (var field_name in errors)
307                         {
308                                 var span = $("*[data-ui-error-for='"+field_name+"']", this.$elem);
309
310                                 if(!span.length) {
311                                         unassigned.push(field_name);
312                                         continue;
313                                 }
314
315                                 span.text(errors[field_name].join(' '));
316                         }
317
318                         if(unassigned.length > 0)
319                                 global.text( global.text() + 'W formularzu wystąpiły błędy');
320                 }
321         };
322
323         $.wiki.cls.GenericDialog = GenericDialog;
324
325         $.wiki.showDialog = function(selector, options) {
326                 var elem = $(selector);
327
328                 if(elem.length != 1) {
329                         console.log("Failed to show dialog:", selector, elem);
330                         return false;
331                 }
332
333                 try {
334                     var klass = elem.attr('data-ui-jsclass');
335                         return new $.wiki.cls[klass](elem, options);
336                 } catch(e) {
337                         console.log("Failed to show dialog", selector, klass, e);
338                         return false;
339                 }
340         };
341
342
343     window.addEventListener("message", (event) => {
344         event.source.close()
345
346         $.ajax("/editor/editor-user-area/", {
347             success: function(d) {
348                 $("#user-area")[0].innerHTML = d;
349             }
350         });
351     }, false);
352     
353     $("#login").click(function (e) {
354         e.preventDefault();
355         let h = 600;
356         let w = 500;
357         let x = window.screenX + (window.innerWidth - w) / 2;
358         let y = window.screenY + (window.innerHeight - h) / 2;
359         window.open(
360             "/accounts/login/?next=/editor/back",
361             "login-window",
362             "width=" + w + " height=" + h + " top=" + y + " left=" + x
363         );
364     });
365     
366 })(jQuery);