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