4b36ae9ec5918a794155d42f079905c3745103d9
[redakcja.git] / redakcja / static / js / wiki / 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 = "/documents";
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_addtag")
43                         return base_path + "/" + arguments[1] + "/tags";
44
45                 if (vname == "ajax_publish")
46                         return base_path + "/" + arguments[1] + "/publish";
47
48                 console.log("Couldn't reverse match:", vname);
49                 return "/404.html";
50         };
51
52         /*
53          * Document Abstraction
54          */
55         function WikiDocument(element_id) {
56                 var meta = $('#' + element_id);
57                 this.id = meta.attr('data-document-name');
58
59                 this.revision = $("*[data-key='revision']", meta).text();
60                 this.readonly = !!$("*[data-key='readonly']", meta).text();
61
62                 this.galleryLink = $("*[data-key='gallery']", meta).text();
63                 this.galleryImages = [];
64                 this.text = null;
65                 this.has_local_changes = false;
66                 this._lock = -1;
67                 this._context_lock = -1;
68                 this._lock_count = 0;
69         };
70
71         WikiDocument.prototype.triggerDocumentChanged = function() {
72                 $(document).trigger('wlapi_document_changed', this);
73         };
74         /*
75          * Fetch text of this document.
76          */
77         WikiDocument.prototype.fetch = function(params) {
78                 params = $.extend({}, noops, params);
79                 var self = this;
80                 $.ajax({
81                         method: "GET",
82                         url: reverse("ajax_document_text", self.id),
83                         data: {"revision": self.revision},
84                         dataType: 'json',
85                         success: function(data) {
86                                 var changed = false;
87
88                                 if (self.text === null || self.revision !== data.revision) {
89                                         self.text = data.text;
90                                         self.revision = data.revision;
91                                         self.gallery = data.gallery;
92                                         changed = true;
93                                         self.triggerDocumentChanged();
94                                 };
95
96                                 self.has_local_changes = false;
97                                 params['success'](self, changed);
98                         },
99                         error: function() {
100                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
101                         }
102                 });
103         };
104         /*
105          * Fetch history of this document.
106          *
107          * from - First revision to fetch (default = 0) upto - Last revision to
108          * fetch (default = tip)
109          *
110          */
111         WikiDocument.prototype.fetchHistory = function(params) {
112                 /* this doesn't modify anything, so no locks */
113                 params = $.extend({}, noops, params);
114                 var self = this;
115                 $.ajax({
116                         method: "GET",
117                         url: reverse("ajax_document_history", self.id),
118                         dataType: 'json',
119                         data: {
120                                 "from": params['from'],
121                                 "upto": params['upto']
122                         },
123                         success: function(data) {
124                                 params['success'](self, data);
125                         },
126                         error: function() {
127                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
128                         }
129                 });
130         };
131         WikiDocument.prototype.fetchDiff = function(params) {
132                 /* this doesn't modify anything, so no locks */
133                 var self = this;
134                 params = $.extend({
135                         'from': self.revision,
136                         'to': self.revision
137                 }, noops, params);
138                 $.ajax({
139                         method: "GET",
140                         url: reverse("ajax_document_diff", self.id),
141                         dataType: 'html',
142                         data: {
143                                 "from": params['from'],
144                                 "to": params['to']
145                         },
146                         success: function(data) {
147                                 params['success'](self, data);
148                         },
149                         error: function() {
150                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
151                         }
152                 });
153         };
154
155         /*
156          * Fetch gallery
157          */
158         WikiDocument.prototype.refreshGallery = function(params) {
159                 params = $.extend({}, noops, params);
160                 var self = this;
161                 $.ajax({
162                         method: "GET",
163                         url: reverse("ajax_document_gallery", self.galleryLink),
164                         dataType: 'json',
165                         // data: {},
166                         success: function(data) {
167                                 self.galleryImages = data;
168                                 params['success'](self, data);
169                         },
170                         error: function() {
171                                 self.galleryImages = [];
172                                 params['failure'](self, "<p>Nie udało się wczytać galerii pod nazwą: '" + self.galleryLink + "'.</p>");
173                         }
174                 });
175         };
176
177         /*
178          * Set document's text
179          */
180         WikiDocument.prototype.setText = function(text) {
181                 this.text = text;
182                 this.has_local_changes = true;
183         };
184
185         /*
186          * Set document's gallery link
187          */
188         WikiDocument.prototype.setGalleryLink = function(gallery) {
189                 this.galleryLink = gallery;
190                 this.has_local_changes = true;
191         };
192
193         /*
194          * Save text back to the server
195          */
196         WikiDocument.prototype.save = function(params) {
197                 params = $.extend({}, noops, params);
198                 var self = this;
199
200                 if (!self.has_local_changes) {
201                         console.log("Abort: no changes.");
202                         return params['success'](self, false, "Nie ma zmian do zapisania.");
203                 };
204
205                 // Serialize form to dictionary
206                 var data = {};
207                 $.each(params['form'].serializeArray(), function() {
208                         data[this.name] = this.value;
209                 });
210
211                 var metaComment = '<!--';
212                 metaComment += '\n\tgallery:' + self.galleryLink;
213                 metaComment += '\n-->\n'
214
215                 data['textsave-text'] = metaComment + self.text;
216
217                 $.ajax({
218                         url: reverse("ajax_document_text", self.id),
219                         type: "POST",
220                         dataType: "json",
221                         data: data,
222                         success: function(data) {
223                                 var changed = false;
224
225                 $('#header').removeClass('saving');
226
227                                 if (data.text) {
228                                         self.text = data.text;
229                                         self.revision = data.revision;
230                                         self.gallery = data.gallery;
231                                         changed = true;
232                                         self.triggerDocumentChanged();
233                                 };
234
235                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
236                         },
237                         error: function(xhr) {
238                 if ($('#header').hasClass('saving')) {
239                     $('#header').removeClass('saving');
240                     $.blockUI({
241                         message: "<p>Nie udało się zapisać zmian. <br/><button onclick='$.unblockUI()'>OK</button></p>"
242                     })
243                 }
244                 else {
245                     try {
246                         params['failure'](self, $.parseJSON(xhr.responseText));
247                     }
248                     catch (e) {
249                         params['failure'](self, {
250                             "__message": "<p>Nie udało się zapisać - błąd serwera.</p>"
251                         });
252                     };
253                 }
254
255                         }
256                 });
257
258         $('#save-hide').click(function(){
259             $('#header').addClass('saving');
260             $.unblockUI();
261             $.wiki.blocking.unblock();
262         });
263         }; /* end of save() */
264
265         WikiDocument.prototype.publish = function(params) {
266                 params = $.extend({}, noops, params);
267                 var self = this;
268                 $.ajax({
269                         url: reverse("ajax_publish", self.id),
270                         type: "POST",
271                         dataType: "json",
272                         success: function(data) {
273                                 params.success(self, data);
274                         },
275                         error: function(xhr) {
276                                 if (xhr.status == 403 || xhr.status == 401) {
277                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
278                                 }
279                                 else {
280                                         try {
281                                                 params.failure(self, xhr.responseText);
282                                         }
283                                         catch (e) {
284                                                 params.failure(self, "Nie udało się - błąd serwera.");
285                                         };
286                                 };
287
288                         }
289                 });
290         };
291         WikiDocument.prototype.setTag = function(params) {
292                 params = $.extend({}, noops, params);
293                 var self = this;
294                 var data = {
295                         "addtag-id": self.id,
296                 };
297
298                 /* unpack form */
299                 $.each(params.form.serializeArray(), function() {
300                         data[this.name] = this.value;
301                 });
302
303                 $.ajax({
304                         url: reverse("ajax_document_addtag", self.id),
305                         type: "POST",
306                         dataType: "json",
307                         data: data,
308                         success: function(data) {
309                                 params.success(self, data.message);
310                         },
311                         error: function(xhr) {
312                                 if (xhr.status == 403 || xhr.status == 401) {
313                                         params.failure(self, {
314                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
315                                         });
316                                 }
317                                 else {
318                                         try {
319                                                 params.failure(self, $.parseJSON(xhr.responseText));
320                                         }
321                                         catch (e) {
322                                                 params.failure(self, {
323                                                         "__all__": ["Nie udało się - błąd serwera."]
324                                                 });
325                                         };
326                                 };
327                         }
328                 });
329         };
330
331         $.wikiapi.WikiDocument = WikiDocument;
332 })(jQuery);