8b8851a823fc01a335697e06a80c52e7f873bc54
[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     stubDocument = '<section><div>' + gettext('This is an empty document.') + '</div></section>';
16
17
18 return function(sandbox) {
19
20     var document_id = sandbox.getBootstrappedData().document_id;
21     var history = sandbox.getBootstrappedData().history;
22     var documentDirty = false;
23     var draftDirty = false;
24
25     var documentProperties = {};
26     var data = sandbox.getBootstrappedData();
27     Object.keys(data)
28         .filter(function(key) {
29             return key !== 'history' && key !== 'document';
30         })
31         .forEach(function(key) {
32             documentProperties[key] = data[key];
33         });
34
35     var wlxmlDocument, text;
36
37     var loadDocument = function(text, isDraft, draftTimestamp) {
38         logger.debug('loading document');
39         try {
40             wlxmlDocument = wlxml.WLXMLDocumentFromXML(text, {editorConfig: sandbox.getConfig()}, Document);
41         } catch(e) {
42             logger.exception(e);
43             alert(gettext('This document contains errors and can\'t be loaded. :(')); // TODO
44             wlxmlDocument = wlxml.WLXMLDocumentFromXML(stubDocument, {}, Document);
45         }
46
47         wlxmlDocument.registerExtension(listExtension);
48         sandbox.getPlugins().forEach(function(plugin) {
49             if(plugin.documentExtension) {
50                 wlxmlDocument.registerExtension(plugin.documentExtension);
51             }
52         });
53         
54         var modificationFlag = true;
55         var handleChange = function() {
56             documentDirty = true;
57             draftDirty = true;
58             modificationFlag = true;
59         };
60         wlxmlDocument.on('change', handleChange);
61         wlxmlDocument.on('contentSet', handleChange);
62
63         if(window.localStorage) {
64             window.setInterval(function() {
65                 if(modificationFlag) {
66                     modificationFlag = false;
67                     return;
68                 }
69                 if(wlxmlDocument && documentDirty && draftDirty) {
70                     var timestamp = datetime.currentStrfmt();
71                     logger.debug('Saving draft to local storage.');
72                     sandbox.publish('savingStarted', 'local');
73                     window.localStorage.setItem(getLocalStorageKey().content, wlxmlDocument.toXML());
74                     window.localStorage.setItem(getLocalStorageKey().contentTimestamp, timestamp);
75                     sandbox.publish('savingEnded', 'success', 'local', {timestamp: timestamp});
76                     draftDirty = false;
77                 }
78             }, sandbox.getConfig().autoSaveInterval || 2500);
79         }
80         sandbox.publish('ready', isDraft, draftTimestamp);
81     };
82     
83     function readCookie(name) {
84         /* global escape, unescape, document */
85         var nameEQ = escape(name) + '=';
86         var ca = document.cookie.split(';');
87         for (var i = 0; i < ca.length; i++) {
88             var c = ca[i];
89             while (c.charAt(0) === ' ') {
90                 c = c.substring(1, c.length);
91             }
92             if (c.indexOf(nameEQ) === 0) {
93                 return unescape(c.substring(nameEQ.length, c.length));
94             }
95         }
96         return null;
97     }
98     
99     $.ajaxSetup({
100         crossDomain: false,
101         beforeSend: function(xhr, settings) {
102             if (!(/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type))) {
103                 xhr.setRequestHeader('X-CSRFToken', readCookie('csrftoken'));
104             }
105         }
106     });
107     
108     var reloadHistory = function() {
109         $.ajax({
110             method: 'get',
111             url: sandbox.getConfig().documentHistoryUrl(document_id),
112             success: function(data) {
113                 history = data;
114                 sandbox.publish('historyItemAdded', data.slice(-1)[0]);
115             },
116         });
117     };
118
119     var getLocalStorageKey = function() {
120         var base = 'draft-id:' + document_id + '-ver:' + documentProperties.version;
121         return {
122             content: base,
123             contentTimestamp: base + '-content-timestamp'
124         };
125     };
126
127    
128     return {
129         start: function() {
130             if(window.localStorage) {
131                 text = window.localStorage.getItem(getLocalStorageKey().content);
132
133                 var timestamp = window.localStorage.getItem(getLocalStorageKey().contentTimestamp),
134                     usingDraft;
135                 if(text) {
136                     logger.debug('Local draft exists');
137                     var dialog = Dialog.create({
138                         title: gettext('Local draft of a document exists'),
139                         text: gettext('Unsaved local draft of this version of the document exists in your browser. Do you want to load it instead?'),
140                         executeButtonText: gettext('Yes, restore local draft'),
141                         cancelButtonText: gettext('No, use version loaded from the server')
142                     });
143                     dialog.on('cancel', function() {
144                         logger.debug('Bootstrapped version chosen');
145                         usingDraft = false;
146                         text = sandbox.getBootstrappedData().document;
147                         
148                     });
149                     dialog.on('execute', function(event) {
150                         logger.debug('Local draft chosen');
151                         usingDraft = true;
152                         event.success();
153                     });
154                     dialog.show();
155                     dialog.on('close', function() {
156                         loadDocument(text, usingDraft, timestamp);
157                     });
158                 } else {
159                     loadDocument(sandbox.getBootstrappedData().document, false);
160                 }
161             } else {
162                 loadDocument(sandbox.getBootstrappedData().document, false);
163             }
164         },
165         getDocument: function() {
166             return wlxmlDocument;
167         },
168         saveDocument: function() {
169             var documentSaveForm = $.extend({
170                         fields: [],
171                         content_field_name: 'text',
172                         version_field_name: 'version'
173                     },
174                     sandbox.getConfig().documentSaveForm
175                 ),
176                 dialog = Dialog.create({
177                     fields: documentSaveForm.fields,
178                     title: gettext('Save Document'),
179                     executeButtonText: gettext('Save'),
180                     cancelButtonText: gettext('Cancel')
181                 });
182             
183             dialog.on('execute', function(event) {
184                 sandbox.publish('savingStarted', 'remote');
185
186                 var formData = event.formData;
187                 formData[documentSaveForm.content_field_name] = wlxmlDocument.toXML();
188                 formData[documentSaveForm.version_field_name] = documentProperties.version;
189                 if(sandbox.getConfig().jsonifySentData) {
190                     formData = JSON.stringify(formData);
191                 }
192
193                 dialog.toggleButtons(false);
194                 $.ajax({
195                     method: 'post',
196                     url: sandbox.getConfig().documentSaveUrl(document_id),
197                     data: formData,
198                     success: function(data) {
199                         event.success();
200                         sandbox.publish('savingEnded', 'success', 'remote', data);
201
202                         Object.keys(data)
203                             .filter(function(key) {
204                                 return key !== 'text';
205                             })
206                             .forEach(function(key) {
207                                 documentProperties[key] = data[key];
208                             });
209
210                         reloadHistory();
211                     },
212                     error: function() {event.error(); sandbox.publish('savingEnded', 'error', 'remote');}
213                 });
214             });
215             dialog.on('cancel', function() {
216             });
217             dialog.show();
218             
219
220         },
221         getHistory: function() {
222             return history;
223         },
224         fetchDiff: function(ver1, ver2) {
225             $.ajax({
226                 method: 'get',
227                 url: sandbox.getConfig().documentDiffUrl(document_id),
228                 data: {from: ver1, to: ver2},
229                 success: function(data) {
230                     sandbox.publish('diffFetched', {table: data, ver1: ver1, ver2: ver2});
231                 },
232             });
233         },
234         restoreVersion: function(version) {
235             var documentRestoreForm = $.extend({
236                         fields: [],
237                         version_field_name: 'version'
238                     },
239                     sandbox.getConfig().documentRestoreForm
240                 ),
241                 dialog = Dialog.create({
242                     fields: documentRestoreForm.fields,
243                     title: gettext('Restore Version'),
244                     executeButtonText: gettext('Restore'),
245                     cancelButtonText: gettext('Cancel')
246                 });
247
248             dialog.on('execute', function(event) {
249                 var formData = event.formData;
250                 formData[documentRestoreForm.version_field_name] = version;
251                 sandbox.publish('restoringStarted', {version: version});
252                 if(sandbox.getConfig().jsonifySentData) {
253                     formData = JSON.stringify(formData);
254                 }
255                 $.ajax({
256                     method: 'post',
257                     dataType: 'json',
258                     url: sandbox.getConfig().documentRestoreUrl(document_id),
259                     data: formData,
260                     success: function(data) {
261                         Object.keys(data)
262                             .filter(function(key) {
263                                 return key !== 'document';
264                             })
265                             .forEach(function(key) {
266                                 documentProperties = data[key];
267                             });
268                         reloadHistory();
269                         wlxmlDocument.loadXML(data.document);
270                         documentDirty = false;
271                         sandbox.publish('documentReverted', data.version);
272                         event.success();
273                     },
274                 });
275             });
276             dialog.show();
277         },
278         dropDraft: function() {
279             logger.debug('Dropping a draft...');
280             wlxmlDocument.loadXML(sandbox.getBootstrappedData().document);
281             draftDirty = false;
282             logger.debug('Draft dropped');
283             sandbox.publish('draftDropped');
284         },
285         getDocumentId: function() {
286             return document_id;
287         },
288         getDocumentProperties: function() {
289             return documentProperties;
290         }
291     };
292 };
293
294 });