2e4682c431c26b6a5507796ecc28b15135901545
[redakcja.git] / redakcja / static / js / wiki_img / wikiapi.js
1 (function($) {
2         $.wikiapi = {};
3         var noop = function() {
4         };
5         var noops = {
6                 success: noop,
7                 failure: noop
8         };
9         /*
10          * Return absolute reverse path of given named view. (at least he have it
11          * hard-coded in one place)
12          *
13          * TODO: think of a way, not to hard-code it here ;)
14          *
15          */
16         function reverse() {
17                 var vname = arguments[0];
18                 var base_path = "/images";
19
20                 if (vname == "ajax_document_text") {
21                         var path = "/" + arguments[1] + "/text";
22
23                     if (arguments[2] !== undefined)
24                                 path += "/" + arguments[2];
25
26                         return base_path + path;
27                 }
28
29                 /*if (vname == "ajax_document_history") {
30
31                         return base_path + "/" + arguments[1] + "/history";
32                 }
33 */
34                 if (vname == "ajax_document_gallery") {
35
36                         return base_path + "/" + arguments[1] + "/gallery";
37                 }
38 /*
39                 if (vname == "ajax_document_diff")
40                         return base_path + "/" + arguments[1] + "/diff";
41
42         if (vname == "ajax_document_rev")
43             return base_path + "/" + arguments[1] + "/rev";
44
45                 if (vname == "ajax_document_addtag")
46                         return base_path + "/" + arguments[1] + "/tags";
47
48                 if (vname == "ajax_publish")
49                         return base_path + "/" + arguments[1] + "/publish";*/
50
51                 console.log("Couldn't reverse match:", vname);
52                 return "/404.html";
53         };
54
55         /*
56          * Document Abstraction
57          */
58         function WikiDocument(element_id) {
59                 var meta = $('#' + element_id);
60                 this.id = meta.attr('data-document-name');
61
62                 this.revision = $("*[data-key='revision']", meta).text();
63                 this.readonly = !!$("*[data-key='readonly']", meta).text();
64
65                 this.galleryLink = $("*[data-key='gallery']", meta).text();
66                 this.galleryImages = [];
67                 this.text = null;
68                 this.has_local_changes = false;
69                 this._lock = -1;
70                 this._context_lock = -1;
71                 this._lock_count = 0;
72         };
73
74         WikiDocument.prototype.triggerDocumentChanged = function() {
75                 $(document).trigger('wlapi_document_changed', this);
76         };
77         /*
78          * Fetch text of this document.
79          */
80         WikiDocument.prototype.fetch = function(params) {
81                 params = $.extend({}, noops, params);
82                 var self = this;
83                 $.ajax({
84                         method: "GET",
85                         url: reverse("ajax_document_text", self.id),
86                         data: {"revision": self.revision},
87                         dataType: 'json',
88                         success: function(data) {
89                                 var changed = false;
90
91                                 if (self.text === null || self.revision !== data.revision) {
92                                         self.text = data.text;
93                                         if (self.text === '') {
94                                             self.text = '<obraz></obraz>';
95                                         }
96                                         self.revision = data.revision;
97                                         changed = true;
98                                         self.triggerDocumentChanged();
99                                 };
100
101                                 self.has_local_changes = false;
102                                 params['success'](self, changed);
103                         },
104                         error: function() {
105                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
106                         }
107                 });
108         };
109
110         /*
111          * Set document's text
112          */
113         WikiDocument.prototype.setText = function(text) {
114                 this.text = text;
115                 this.has_local_changes = true;
116         };
117
118         /*
119          * Save text back to the server
120          */
121         WikiDocument.prototype.save = function(params) {
122                 params = $.extend({}, noops, params);
123                 var self = this;
124
125                 if (!self.has_local_changes) {
126                         console.log("Abort: no changes.");
127                         return params['success'](self, false, "Nie ma zmian do zapisania.");
128                 };
129
130                 // Serialize form to dictionary
131                 var data = {};
132                 $.each(params['form'].serializeArray(), function() {
133                         data[this.name] = this.value;
134                 });
135
136                 data['textsave-text'] = self.text;
137
138                 $.ajax({
139                         url: reverse("ajax_document_text", self.id),
140                         type: "POST",
141                         dataType: "json",
142                         data: data,
143                         success: function(data) {
144                                 var changed = false;
145
146                 $('#header').removeClass('saving');
147
148                                 if (data.text) {
149                                         self.text = data.text;
150                                         self.revision = data.revision;
151                                         changed = true;
152                                         self.triggerDocumentChanged();
153                                 };
154
155                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
156                         },
157                         error: function(xhr) {
158                 if ($('#header').hasClass('saving')) {
159                     $('#header').removeClass('saving');
160                     $.blockUI({
161                         message: "<p>Nie udało się zapisać zmian. <br/><button onclick='$.unblockUI()'>OK</button></p>"
162                     })
163                 }
164                 else {
165                     try {
166                         params['failure'](self, $.parseJSON(xhr.responseText));
167                     }
168                     catch (e) {
169                         params['failure'](self, {
170                             "__message": "<p>Nie udało się zapisać - błąd serwera.</p>"
171                         });
172                     };
173                 }
174
175                         }
176                 });
177
178         $('#save-hide').click(function(){
179             $('#header').addClass('saving');
180             $.unblockUI();
181             $.wiki.blocking.unblock();
182         });
183         }; /* end of save() */
184
185         WikiDocument.prototype.publish = function(params) {
186                 params = $.extend({}, noops, params);
187                 var self = this;
188                 $.ajax({
189                         url: reverse("ajax_publish", self.id),
190                         type: "POST",
191                         dataType: "json",
192                         success: function(data) {
193                                 params.success(self, data);
194                         },
195                         error: function(xhr) {
196                                 if (xhr.status == 403 || xhr.status == 401) {
197                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
198                                 }
199                                 else {
200                                         try {
201                                                 params.failure(self, xhr.responseText);
202                                         }
203                                         catch (e) {
204                                                 params.failure(self, "Nie udało się - błąd serwera.");
205                                         };
206                                 };
207
208                         }
209                 });
210         };
211         WikiDocument.prototype.setTag = function(params) {
212                 params = $.extend({}, noops, params);
213                 var self = this;
214                 var data = {
215                         "addtag-id": self.id,
216                 };
217
218                 /* unpack form */
219                 $.each(params.form.serializeArray(), function() {
220                         data[this.name] = this.value;
221                 });
222
223                 $.ajax({
224                         url: reverse("ajax_document_addtag", self.id),
225                         type: "POST",
226                         dataType: "json",
227                         data: data,
228                         success: function(data) {
229                                 params.success(self, data.message);
230                         },
231                         error: function(xhr) {
232                                 if (xhr.status == 403 || xhr.status == 401) {
233                                         params.failure(self, {
234                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
235                                         });
236                                 }
237                                 else {
238                                         try {
239                                                 params.failure(self, $.parseJSON(xhr.responseText));
240                                         }
241                                         catch (e) {
242                                                 params.failure(self, {
243                                                         "__all__": ["Nie udało się - błąd serwera."]
244                                                 });
245                                         };
246                                 };
247                         }
248                 });
249         };
250
251     WikiDocument.prototype.getImageItems = function(tag) {
252         var self = this;
253
254         var parser = new DOMParser();
255         var doc = parser.parseFromString(self.text, 'text/xml');
256         var error = $('parsererror', doc);
257
258         if (error.length != 0) {
259             return null;
260         }
261
262         var a = [];
263         $(tag, doc).each(function(i, e) {
264             var $e = $(e);
265             a.push([
266                 $e.text(),
267                 $e.attr('x1'),
268                 $e.attr('y1'),
269                 $e.attr('x2'),
270                 $e.attr('y2')
271             ]);
272         });
273
274         return a;
275     }
276
277     WikiDocument.prototype.setImageItems = function(tag, items) {
278         var self = this;
279
280         var parser = new DOMParser();
281         var doc = parser.parseFromString(self.text, 'text/xml');
282         var serializer = new XMLSerializer();
283         var error = $('parsererror', doc);
284
285         if (error.length != 0) {
286             return null;
287         }
288
289         $(tag, doc).remove();
290         $root = $(doc.firstChild);
291         $.each(items, function(i, e) {
292             var el = $(doc.createElement(tag));
293             el.text(e[0]);
294             if (e[1] !== null) {
295                 el.attr('x1', e[1]);
296                 el.attr('y1', e[2]);
297                 el.attr('x2', e[3]);
298                 el.attr('y2', e[4]);
299             }
300             $root.append(el);
301         });
302         self.setText(serializer.serializeToString(doc));
303     }
304
305
306         $.wikiapi.WikiDocument = WikiDocument;
307 })(jQuery);