* End of javascript refactoring: both editors, history and gallery work as expected.
[redakcja.git] / platforma / static / js / wiki / wikiapi.js
1 (function($) {
2         
3         $.wikiapi = {};
4         
5         var noop = function() {};
6         var noops = {'success': noop, 'failure': noop};
7         
8         /*
9          * Return absolute reverse path of given named view.
10          * (at least he have it hard-coded in one place)
11          * 
12          * TODO: think of a way, not to hard-code it here ;) 
13          * 
14          */
15         function reverse() {
16                 var vname = arguments[0];
17                         
18                 if(vname == "ajax_document_text") {
19                         var path = "/" + arguments[1] + "/text";
20                         if (arguments[2] !== undefined) 
21                                 path += "/" + arguments[2];
22                         return path;
23                 }
24                         
25                 if (vname == "ajax_document_history") {
26                         return "/" + arguments[1] + "/history";
27                 }
28                 
29                 if (vname == "ajax_document_gallery") {
30                         return "/gallery/" + arguments[1];
31                 }                                               
32                                         
33                 if(vname == "ajax_document_diff")
34                         return "/" + arguments[1] + "/diff"; 
35                         
36                 console.log("Couldn't reverse match:", vname);
37                 return "/404.html";             
38         };
39         
40         /*
41          * Document Abstraction  
42          */
43         function WikiDocument(element_id) {
44                 var meta = $('#'+element_id);
45                 
46                 this.id = meta.attr('data-document-name');              
47                 this.revision = $("*[data-key='revision']", meta).text();
48                 this.galleryLink = $("*[data-key='gallery']", meta).text();
49                 this.galleryImages = [];
50                 this.text = null;
51                 
52                 this.has_local_changes = false;
53                 this._lock = -1;
54                 this._context_lock = -1;
55                 this._lock_count = 0; 
56         }
57         
58 //      WikiDocument.prototype.lock = function() {
59 //              if(this._lock < 0) {
60 //                      this._lock = Math.random();
61 //                      this._context_lock = this._lock;
62 //                      this._lock_count = 1;
63 //                      return this._lock;
64 //              }
65 //              
66 //              // reentrant locks 
67 //              if(this._context_lock === this._lock) {
68 //                      this._lock_count += 1;
69 //                      return this._lock;
70 //              }
71 //              
72 //              throw "Document operation in progress. Try again later."
73 //      };
74 //              
75 //      WikiDocument.prototype.unlock = function(lockNumber) {
76 //              if(this.locked === lockNumber) {
77 //                      this._lock_count -= 1;
78 //                      
79 //                      if(this._lock_count === 0) {
80 //                              this._lock = -1;
81 //                              this._context_lock = -1;
82 //                      };                      
83 //                      return;
84 //              }
85 //              throw "Trying to unlock with wrong lockNumber";
86 //      };
87 //      
88 //      /*
89 //       * About to leave context of current lock.
90 //       */
91 //      WikiDocument.prototype.leaveContext = function() {
92 //              var old = this._context_lock;
93 //              this._context_lock = -1;
94 //              return old;
95 //      };
96
97         WikiDocument.prototype.triggerDocumentChanged = function() {
98                 $(document).trigger('wlapi_document_changed', this);            
99         };
100         
101         /*
102          * Fetch text of this document.
103          */
104         WikiDocument.prototype.fetch = function(params) {               
105                 params = $.extend({}, noops, params);
106                 var self = this;
107                 
108                 $.ajax({
109                         method: "GET",
110                         url: reverse("ajax_document_text", self.id),
111                         dataType: 'json', 
112                         success: function(data) 
113                         {
114                                 var changed = false;
115                                 
116                                 if (self.text === null || self.revision !== data.revision) {
117                                         self.text = data.text;
118                                         self.revision = data.revision;
119                                         self.gallery = data.gallery;                                    
120                                         changed = true;
121                                         self.triggerDocumentChanged();          
122                                 }
123                                 
124                                 self.has_local_changes = false;                         
125                                 params['success'](self, changed);
126                         },
127                         error: function() {             
128                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
129                         }
130                 });                                             
131         };
132         
133         /*
134          * Fetch history of this document.
135          * 
136          * from - First revision to fetch (default = 0)
137          * upto - Last revision to fetch (default = tip)
138          * 
139          */
140         WikiDocument.prototype.fetchHistory = function(params) {                
141                 /* this doesn't modify anything, so no locks */         
142                 params = $.extend({}, noops, params);           
143                 var self = this;
144                 
145                 $.ajax({                        
146                         method: "GET",
147                         url: reverse("ajax_document_history", self.id),
148                         dataType: 'json',
149                         data: {"from": params['from'], "upto": params['upto']},
150                         success: function(data) {
151                                 params['success'](self, data);
152                         },
153                         error: function() {
154                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
155                         }
156                 });                                             
157         };
158         
159         WikiDocument.prototype.fetchDiff = function(params) {           
160                 /* this doesn't modify anything, so no locks */
161                 var self = this;
162                                 
163                 params = $.extend({
164                         'from': self.revision, 
165                         'to': self.revision
166                 }, noops, params);
167                                         
168                 $.ajax({                        
169                         method: "GET",
170                         url: reverse("ajax_document_diff", self.id),
171                         dataType: 'html',
172                         data: {"from": params['from'], "to": params['to']},
173                         success: function(data) {
174                                 params['success'](self, data);
175                         },
176                         error: function() {
177                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
178                         }
179                 });                                             
180         };
181         
182         /* 
183          * Fetch gallery
184          */
185         WikiDocument.prototype.refreshGallery = function(params) {
186                 params = $.extend({}, noops, params);           
187                 var self = this;
188                 
189                 $.ajax({                        
190                         method: "GET",
191                         url: reverse("ajax_document_gallery", self.galleryLink),
192                         dataType: 'json',
193                         // data: {},
194                         success: function(data) {
195                                 self.galleryImages = data;
196                                 params['success'](self, data);                          
197                         },
198                         error: function() {
199                                 self.galleryImages = [];        
200                                 params['failure'](self, "<p>Nie udało się wczytać gallerii pod nazwą: '"
201                                         + self.galleryLink + "'.</p>");
202                                                         
203                         }
204                 });                             
205         };      
206         
207         /*
208          * Set document's text
209          */
210         WikiDocument.prototype.setText = function(text) {               
211                 this.text = text;
212                 this.has_local_changes = true;                                  
213         };
214         
215         /*
216          * Set document's gallery link
217          */
218         WikiDocument.prototype.setGalleryLink = function(gallery) {                             
219                 this.galleryLink = gallery;
220                 this.has_local_changes = true;                  
221         };
222         
223         /*
224          * Save text back to the server
225          */
226         WikiDocument.prototype.save = function(params){
227                 params = $.extend({}, noops, params);
228                 var self = this;
229                                 
230                 if (!self.has_local_changes) {
231                         console.log("Abort: no changes.");
232                         return params['success'](self, false, "Nie ma zmian do zapisania.");
233                 };              
234                 
235                 // Serialize form to dictionary
236                 var data = {};          
237                 $.each(params['form'].serializeArray(), function() {
238                         data[this.name] = this.value;                   
239                 });
240                 
241                 var metaComment = '<!--';
242                 metaComment += '\n\tgallery:' + self.galleryLink;
243                 metaComment += '\n-->\n'
244                 
245                 data.text = metaComment + self.text;
246                 data.comment = data.comment; 
247                 
248                 $.ajax({
249                         url: reverse("ajax_document_text", self.id),
250                         type: "POST",
251                         dataType: "json",
252                         data: data,
253                         success: function(data){
254                                 var changed = false;
255                                 if (data.text) {
256                                         self.text = data.text;
257                                         self.revision = data.revision;
258                                         self.gallery = data.gallery;
259                                         changed = true;
260                                         self.triggerDocumentChanged();
261                                 }
262                                 params['success'](self, changed, 
263                                         ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna") );
264                         },
265                         error: function(xhr) {
266                                 try {                                    
267                                         params['failure'](self, $.parseJSON(xhr.responseText));
268                                 } 
269                                 catch(e) {
270                                         params['failure'](self, {"__message": "<p>Nie udało się zapisać - błąd serwera.</p>"});                            
271                                 };
272                         }
273                 });             
274         }; /* end of save() */
275         
276         WikiDocument.prototype.setTag = function(params) {
277                 
278         };
279         
280         
281         $.wikiapi.WikiDocument = WikiDocument;
282         
283 })(jQuery);