fix for isbn import
[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, base_id) {
69         var id = (''+klass)+'_' + base_id;
70         var $tab = $('<li class="nav-item" id="'+id+'" data-ui-related="'+base_id+'" data-ui-jsclass="'+klass+'" ><a href="#" class="nav-link">'
71                      + title + ' <span class="badge badge-danger tabclose">x</span></a></li>');
72         var $view = $('<div class="editor '+klass+'" id="'+base_id+'"> </div>');
73
74         this.perspectives[id] = new $.wiki[klass]({
75             doc: doc,
76             id: id,
77             base_id: base_id,
78         });
79
80         $('#tabs').append($tab);
81         $view.hide().appendTo('#editor');
82         return {
83             tab: $tab[0],
84             view: $view[0],
85         };
86     };
87
88     $.wiki.initTab = function(options) {
89         var klass = $(options.tab).attr('data-ui-jsclass');
90
91         let perspective = new $.wiki[klass]({
92             doc: options.doc,
93             id: $(options.tab).attr('id'),
94         });
95         $.wiki.perspectives[perspective.perspective_id] = perspective;
96         return perspective;
97     };
98
99     $.wiki.perspectiveForTab = function(tab) { // element or id
100         return this.perspectives[ $(tab).attr('id')];
101     }
102
103     $.wiki.exitTab = function(tab){
104         var self = this;
105         var $tab = $(tab);
106         if (!('.active', $tab).length) return;
107         $('.active', $tab).removeClass('active');
108         self.perspectives[$tab.attr('id')].onExit();
109         $('#' + $tab.attr('data-ui-related')).hide();
110     }
111
112     $.wiki.switchToTab = function(tab){
113         var self = this;
114         var $tab = $(tab);
115
116         // Create dynamic tabs (for diffs).
117         if ($tab.length != 1) {
118             let parts = tab.split('_');
119             if (parts.length > 1) {
120                 // TODO: register perspectives for it.
121                 if (parts[0] == '#DiffPerspective') {
122                     $tab = $($.wiki.DiffPerspective.openId(parts[1]));
123                 }
124             }
125         }
126
127         if($tab.length != 1)
128             $tab = $(DEFAULT_PERSPECTIVE);
129
130         var $old_a = $tab.closest('.tabs').find('.active');
131
132         $old_a.each(function(){
133             var tab = $(this).parent()
134             $(this).removeClass('active');
135             self.perspectives[tab.attr('id')].onExit();
136             $('#' + tab.attr('data-ui-related')).hide();
137         });
138
139         /* show new */
140         $('a', tab).addClass('active');
141         $('#' + $tab.attr('data-ui-related')).show();
142
143         console.log($tab);
144         console.log($.wiki.perspectives);
145
146         $.wiki.perspectives[$tab.attr('id')].onEnter();
147     };
148
149     /*
150      * Basic perspective.
151      */
152     $.wiki.Perspective = class Perspective {
153         constructor(options) {
154             this.doc = options.doc;
155             this.perspective_id = options.id || ''
156         };
157
158         config() {
159             return $.wiki.state.perspectives[this.perspective_id];
160         }
161
162         toString() {
163             return this.perspective_id;
164         }
165
166         dirty() {
167             return true;
168         }
169
170         onEnter() {
171             // called when perspective in initialized
172             if (!this.noupdate_hash_onenter) {
173                 document.location.hash = '#' + this.perspective_id;
174             }
175         }
176
177         onExit () {
178             // called when user switches to another perspective
179             if (!this.noupdate_hash_onenter) {
180                 document.location.hash = '';
181             }
182         }
183
184         destroy() {
185             // pass
186         }
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     class GenericDialog {
228         constructor(element) {
229             if(!element) return;
230
231             var self = this;
232
233             self.$elem = $(element);
234
235             if(!self.$elem.attr('data-ui-initialized')) {
236                 console.log("Initializing dialog", this);
237                 self.initialize();
238                 self.$elem.attr('data-ui-initialized', true);
239             }
240
241             self.show();
242         }
243
244         /*
245          * Steps to follow when the dialog in first loaded on page.
246          */
247         initialize(){
248             var self = this;
249
250             /* bind buttons */
251             $('button[data-ui-action]', self.$elem).click(function(event) {
252                 event.preventDefault();
253
254                 var action = $(this).attr('data-ui-action');
255                 console.log("Button pressed, action: ", action);
256
257                 try {
258                     self[action + "Action"].call(self);
259                 } catch(e) {
260                     console.log("Action failed:", e);
261                     // always hide on cancel
262                     if(action == 'cancel')
263                         self.hide();
264                 }
265             });
266         }
267
268         /*
269          * Prepare dialog for user. Clear any unnessary data.
270          */
271         show() {
272             $.blockUI({
273                 message: this.$elem,
274                 css: {
275                     'top': '25%',
276                     'left': '25%',
277                     'width': '50%',
278                     'max-height': '75%',
279                     'overflow-y': 'scroll'
280                 }
281             });
282         }
283
284         hide() {
285             $.unblockUI();
286         }
287
288         cancelAction() {
289             this.hide();
290         }
291
292         doneAction() {
293             this.hide();
294         }
295
296         clearForm() {
297             $("*[data-ui-error-for]", this.$elem).text('');
298         }
299
300         reportErrors(errors) {
301             var global = $("*[data-ui-error-for='__all__']", this.$elem);
302             var unassigned = [];
303
304             $("*[data-ui-error-for]", this.$elem).text('');
305             for (var field_name in errors)
306             {
307                 var span = $("*[data-ui-error-for='"+field_name+"']", this.$elem);
308
309                 if(!span.length) {
310                     unassigned.push(field_name);
311                     continue;
312                 }
313
314                 span.text(errors[field_name].join(' '));
315             }
316
317             if(unassigned.length > 0)
318                 global.text( global.text() + 'W formularzu wystąpiły błędy');
319         }
320     }
321
322     $.wiki.cls.GenericDialog = GenericDialog;
323
324     $.wiki.showDialog = function(selector, options) {
325         var elem = $(selector);
326
327         if(elem.length != 1) {
328             console.log("Failed to show dialog:", selector, elem);
329             return false;
330         }
331
332         try {
333             var klass = elem.attr('data-ui-jsclass');
334             return new $.wiki.cls[klass](elem, options);
335         } catch(e) {
336             console.log("Failed to show dialog", selector, klass, e);
337             return false;
338         }
339     };
340
341     window.addEventListener("message", (event) => {
342         event.source.close()
343
344         $.ajax("/editor/editor-user-area/", {
345             success: function(d) {
346                 $("#user-area")[0].innerHTML = d;
347             }
348         });
349     }, false);
350
351     $("#login").click(function (e) {
352         e.preventDefault();
353         let h = 600;
354         let w = 500;
355         let x = window.screenX + (window.innerWidth - w) / 2;
356         let y = window.screenY + (window.innerHeight - h) / 2;
357         window.open(
358             "/accounts/login/?next=/editor/back",
359             "login-window",
360             "width=" + w + " height=" + h + " top=" + y + " left=" + x
361         );
362     });
363
364 })(jQuery);