tutorial button
[fnpeditor.git] / src / editor / modules / data / data.js
1 define([
2     'libs/jquery',
3     'views/dialog/dialog',
4     'wlxml/wlxml',
5     'wlxml/extensions/list/list',
6     'fnpjs/logging/logging',
7     'fnpjs/datetime',
8     './document'
9 ], function($, Dialog, wlxml, listExtension, logging, datetime, Document) {
10
11 'use strict';
12 /* global gettext, alert, window */
13
14 var logger = logging.getLogger('editor.modules.data');
15
16
17 return function(sandbox) {
18
19     var data = sandbox.getBootstrappedData(),
20         documentDirty = false,
21         draftDirty = false,
22         wlxmlDocument;
23
24
25     var loadDocument = function(text, isDraft, draftTimestamp) {
26         logger.debug('loading document');
27         var xmlValid = true;
28         try {
29             wlxmlDocument = wlxml.WLXMLDocumentFromXML(text, {editorConfig: sandbox.getConfig()}, Document.Document);
30         } catch(e) {
31             logger.exception(e);
32             alert(gettext('The content of this document seems to be invalid - only XML source editing will be possible. :(')); // TODO
33             wlxmlDocument = wlxml.WLXMLDocumentFromXML(text, {}, Document.DumbDocument);
34             xmlValid = false;
35         }
36
37         Object.keys(data)
38             .filter(function(key) {
39                 return key !== 'history' && key !== 'document';
40             })
41             .forEach(function(key) {
42                 wlxmlDocument.setProperty(key, data[key]);
43             });
44
45         wlxmlDocument.registerExtension(listExtension);
46         sandbox.getPlugins().forEach(function(plugin) {
47             if(plugin.documentExtension) {
48                 wlxmlDocument.registerExtension(plugin.documentExtension);
49             }
50         });
51         
52         var modificationFlag = true;
53         var handleChange = function() {
54             documentDirty = true;
55             draftDirty = true;
56             modificationFlag = true;
57         };
58         wlxmlDocument.on('change', handleChange);
59         wlxmlDocument.on('contentSet', handleChange);
60
61         if(window.localStorage) {
62             window.setInterval(function() {
63                 var timestamp = datetime.currentStrfmt(),
64                     key = getLocalStorageKey();
65                 if(modificationFlag) {
66                     modificationFlag = false;
67                     return;
68                 }
69                 if(wlxmlDocument && documentDirty && draftDirty) {
70                     logger.debug('Saving draft to local storage.');
71                     sandbox.publish('savingStarted', 'local');
72                     window.localStorage.setItem(key.content, wlxmlDocument.toXML());
73                     window.localStorage.setItem(key.contentTimestamp, timestamp);
74                     sandbox.publish('savingEnded', 'success', 'local', {timestamp: timestamp});
75                     draftDirty = false;
76                 }
77             }, sandbox.getConfig().autoSaveInterval || 2500);
78         }
79         sandbox.publish('ready', isDraft, draftTimestamp, xmlValid);
80     };
81     
82     function readCookie(name) {
83         /* global escape, unescape, document */
84         var nameEQ = escape(name) + '=';
85         var ca = document.cookie.split(';');
86         for (var i = 0; i < ca.length; i++) {
87             var c = ca[i];
88             while (c.charAt(0) === ' ') {
89                 c = c.substring(1, c.length);
90             }
91             if (c.indexOf(nameEQ) === 0) {
92                 return unescape(c.substring(nameEQ.length, c.length));
93             }
94         }
95         return null;
96     }
97     
98     $.ajaxSetup({
99         crossDomain: false,
100         beforeSend: function(xhr, settings) {
101             if (!(/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type))) {
102                 xhr.setRequestHeader('X-CSRFToken', readCookie('csrftoken'));
103             }
104         }
105     });
106     
107     var reloadHistory = function() {
108         $.ajax({
109             method: 'get',
110             url: sandbox.getConfig().documentHistoryUrl(data.document_id),
111             success: function(history) {
112                 data.history = history;
113                 sandbox.publish('historyItemAdded', history.slice(-1)[0]);
114             },
115         });
116     };
117
118     var getLocalStorageKey = function(forVersion) {
119         var base = 'draft-id:' + data.document_id + '-ver:' + (forVersion || wlxmlDocument.properties.version);
120         return {
121             content: base,
122             contentTimestamp: base + '-content-timestamp'
123         };
124     };
125
126    
127     return {
128         start: function() {
129             var text;
130             $('#tuton').remove();
131             if(window.localStorage) {
132                 text = window.localStorage.getItem(getLocalStorageKey(data.version).content);
133
134                 var timestamp = window.localStorage.getItem(getLocalStorageKey(data.version).contentTimestamp),
135                     usingDraft;
136                 if(text) {
137                     logger.debug('Local draft exists');
138                     var dialog = Dialog.create({
139                         title: gettext('Local draft of a document exists'),
140                         text: gettext('Unsaved local draft of this version of the document exists in your browser. Do you want to load it instead?'),
141                         executeButtonText: gettext('Yes, restore local draft'),
142                         cancelButtonText: gettext('No, use version loaded from the server')
143                     });
144                     dialog.on('cancel', function() {
145                         logger.debug('Bootstrapped version chosen');
146                         usingDraft = false;
147                         text = sandbox.getBootstrappedData().document;
148                         
149                     });
150                     dialog.on('execute', function(event) {
151                         logger.debug('Local draft chosen');
152                         usingDraft = true;
153                         event.success();
154                     });
155                     dialog.show();
156                     dialog.on('close', function() {
157                         loadDocument(text, usingDraft, timestamp);
158                     });
159                 } else {
160                     loadDocument(sandbox.getBootstrappedData().document, false);
161                 }
162             } else {
163                 loadDocument(sandbox.getBootstrappedData().document, false);
164             }
165         },
166         getDocument: function() {
167             return wlxmlDocument;
168         },
169         saveDocument: function() {
170             var documentSaveForm = $.extend({
171                         fields: [],
172                         content_field_name: 'text',
173                         version_field_name: 'version'
174                     },
175                     sandbox.getConfig().documentSaveForm
176                 ),
177                 dialog = Dialog.create({
178                     fields: documentSaveForm.fields,
179                     title: gettext('Save Document'),
180                     executeButtonText: gettext('Save'),
181                     cancelButtonText: gettext('Cancel')
182                 });
183             /* Set stage field initial value to current document stage. */
184             for (var i in documentSaveForm.fields) {
185                 if (documentSaveForm.fields[i].name == 'textsave-stage') {
186                     documentSaveForm.fields[i].initialValue = data.stage;
187                 }
188             }
189             
190             dialog.on('execute', function(event) {
191                 sandbox.publish('savingStarted', 'remote');
192
193                 var formData = event.formData;
194                 formData[documentSaveForm.content_field_name] = wlxmlDocument.toXML();
195                 formData[documentSaveForm.version_field_name] = wlxmlDocument.properties.version;
196                 if(sandbox.getConfig().jsonifySentData) {
197                     formData = JSON.stringify(formData);
198                 }
199
200                 dialog.toggleButtons(false);
201                 $.ajax({
202                     method: 'post',
203                     url: sandbox.getConfig().documentSaveUrl(data.document_id),
204                     data: formData,
205                     success: function(ajax_data) {
206                         event.success();
207                         sandbox.publish('savingEnded', 'success', 'remote', ajax_data);
208
209                         Object.keys(ajax_data)
210                             .filter(function(key) {
211                                 return key !== 'text';
212                             })
213                             .forEach(function(key) {
214                                 wlxmlDocument.setProperty(key, ajax_data[key]);
215                                 // ugly, but whatever
216                                 data[key] = ajax_data[key];
217                             });
218
219                         reloadHistory();
220                     },
221                     error: function(data) {
222                         event.error();
223                         sandbox.publish('savingEnded', 'error', 'remote');
224                         var dialog = Dialog.create({
225                             title: gettext('Error'),
226                             text: JSON.parse(data.responseText).text.join('\n'),
227                             executeButtonText: gettext('Close')
228                         });
229                         dialog.show();
230                         dialog.on('execute', function(e) {
231                             e.success();
232                         });
233                     }
234                 });
235             });
236             dialog.on('cancel', function() {
237             });
238             dialog.show();
239             
240
241         },
242         getHistory: function() {
243             return data.history;
244         },
245         fetchDiff: function(ver1, ver2) {
246             $.ajax({
247                 method: 'get',
248                 url: sandbox.getConfig().documentDiffUrl(data.document_id),
249                 data: {from: ver1, to: ver2},
250                 success: function(data) {
251                     sandbox.publish('diffFetched', {table: data, ver1: ver1, ver2: ver2});
252                 },
253             });
254         },
255         restoreVersion: function(version) {
256             var documentRestoreForm = $.extend({
257                         fields: [],
258                         version_field_name: 'version'
259                     },
260                     sandbox.getConfig().documentRestoreForm
261                 ),
262                 dialog = Dialog.create({
263                     fields: documentRestoreForm.fields,
264                     title: gettext('Restore Version'),
265                     executeButtonText: gettext('Restore'),
266                     cancelButtonText: gettext('Cancel')
267                 });
268
269             dialog.on('execute', function(event) {
270                 var formData = event.formData;
271                 formData[documentRestoreForm.version_field_name] = version;
272                 sandbox.publish('restoringStarted', {version: version});
273                 if(sandbox.getConfig().jsonifySentData) {
274                     formData = JSON.stringify(formData);
275                 }
276                 $.ajax({
277                     method: 'post',
278                     dataType: 'json',
279                     url: sandbox.getConfig().documentRestoreUrl(data.document_id),
280                     data: formData,
281                     success: function(ajax_data) {
282                         Object.keys(ajax_data)
283                             .filter(function(key) {
284                                 return key !== 'document';
285                             })
286                             .forEach(function(key) {
287                                 wlxmlDocument.setProperty(key, ajax_data[key]);
288                                 // ugly, but whatever
289                                 data[key] = ajax_data[key];
290                             });
291                         reloadHistory();
292                         wlxmlDocument.loadXML(ajax_data.document);
293                         documentDirty = false;
294                         sandbox.publish('documentReverted', ajax_data.version);
295                         event.success();
296                     },
297                 });
298             });
299             dialog.show();
300         },
301         publishVersion: function(revision) {
302             var documentPublishForm = $.extend({
303                         fields: [],
304                         revision_field_name: 'revision'
305                     },
306                     sandbox.getConfig().documentPublishForm
307                 ),
308                 dialog = Dialog.create({
309                     fields: documentPublishForm.fields,
310                     title: gettext('Publish'),
311                     executeButtonText: gettext('Publish'),
312                     cancelButtonText: gettext('Cancel')
313                 });
314
315             dialog.on('execute', function(event) {
316                 var formData = event.formData;
317                 formData[documentPublishForm.revision_field_name] = revision;
318                 sandbox.publish('publishingStarted', {version: revision});
319                 if(sandbox.getConfig().jsonifySentData) {
320                     formData = JSON.stringify(formData);
321                 }
322                 $.ajax({
323                     method: 'post',
324                     //dataType: 'json',
325                     dataType: 'text',
326                     url: sandbox.getConfig().documentPublishUrl,
327                     data: formData,
328                     success: function(data) {
329                         reloadHistory();
330                         sandbox.publish('documentPublished');
331                         event.success();
332                     },
333                 });
334             });
335             dialog.show();
336         },
337         dropDraft: function() {
338             logger.debug('Dropping a draft...');
339             wlxmlDocument.loadXML(sandbox.getBootstrappedData().document);
340             draftDirty = false;
341             logger.debug('Draft dropped');
342             sandbox.publish('draftDropped');
343         }
344     };
345 };
346
347 });