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