editor: cleanup - removing unnecessary wlxml class handling code in canvas generic...
[fnpeditor.git] / src / editor / plugins / core / core.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals gettext */
5
6 var _ = require('libs/underscore'),
7     templates = require('plugins/core/templates'),
8     footnote = require('plugins/core/footnote'),
9     switchTo = require('plugins/core/switch'),
10     lists = require('plugins/core/lists'),
11     plugin = {name: 'core', actions: [], canvas: {}, documentExtension: {textNode: {}}},
12     Dialog = require('views/dialog/dialog'),
13     canvasElements = require('plugins/core/canvasElements'),
14     metadataEditor = require('plugins/core/metadataEditor/metadataEditor');
15
16
17
18 plugin.documentExtension.textNode.transformations = {
19     breakContent: {
20         impl: function(args) {
21             var node = this,
22                 parentDescribingNodes = [],
23                 newNodes, emptyText;
24             newNodes = node.split({offset: args.offset});
25             newNodes.second.contents()
26                 .filter(function(child) {
27                     return child.object.describesParent;
28                 })
29                 .forEach(function(child) {
30                     //child.detach();
31                     parentDescribingNodes.push(child);
32                     child.detach();
33                 });
34             [newNodes.first, newNodes.second].some(function(newNode) {
35                 if(!(newNode.contents().length)) {
36                     emptyText = newNode.append({text: ''});
37                     return true; // break
38                 }
39             });
40             parentDescribingNodes.forEach(function(node) {
41                 newNodes.first.append(node);
42             });
43             return _.extend(newNodes, {emptyText: emptyText});
44         },
45         getChangeRoot: function() {
46             return this.context.parent().parent();
47         }
48     },
49     mergeContentUp: function() {
50         /* globals Node */
51         var myPrev = this,
52             base = this,
53             ret;
54
55         if(myPrev.nodeType === Node.TEXT_NODE) {
56             if(myPrev.getIndex() > 0) {
57                 return;
58             }
59             myPrev = base = myPrev.parent();
60         }
61
62         myPrev = myPrev && myPrev.prev();
63
64         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
65             var ptr = this,
66                 next;
67             while(ptr) {
68                 next = ptr.next();
69                 if(!ret) {
70                     ret = myPrev.append(ptr);
71                 } else {
72                     myPrev.append(ptr);
73                 }
74                 
75                 ptr = next;
76             }
77             if(base !== this) {
78                 base.detach();
79             }
80             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
81         }
82     }
83 };
84
85 var undoRedoAction = function(dir) {
86     return {
87         name: dir,
88         params: {
89             document: {type: 'context', name: 'document'},
90         },
91         stateDefaults: {
92             label: dir === 'undo' ? '<-' : '->',
93             icon: 'share-alt',
94             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
95             execute: function(callback, params) {
96                 var metadata = _.last(params.document[dir+'Stack']).metadata,
97                     fragment = metadata && metadata.fragment;
98                 params.document[dir]();
99                 if(fragment) {
100                     if(!fragment.isValid()) {
101                         fragment.restoreFromPaths();
102                     }
103                     if(fragment.isValid()) {
104                         callback(fragment);
105                     }
106                 }
107                 callback();
108             },
109         },
110         getState: function(params) {
111             var allowed = params.document && !!(params.document[dir+'Stack'].length),
112                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
113                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
114             if(allowed) {
115                 var metadata = _.last(params.document[dir+'Stack']).metadata;
116                 if(metadata) {
117                     desc += ': ' + (metadata.description || gettext('unknown operation'));
118                 }
119             }
120             return {
121                 allowed: allowed,
122                 description: allowed ? desc : descEmpty
123             };
124         }
125     };
126 };
127
128 var pad = function(number) {
129     if(number < 10) {
130         number = '0' + number;
131     }
132     return number;
133 };
134
135 var commentAction = {
136     name: 'comment',
137     params: {
138         fragment: {type: 'context', name: 'fragment'}
139     },
140     stateDefaults: {
141         icon: 'comment',
142         execute: function(callback, params, editor) {
143             /* globals Node */
144             var node = params.fragment.node,
145                 action = this;
146             if(node.nodeType === Node.TEXT_NODE) {
147                 node = node.parent();
148             }
149             node.document.transaction(function() {
150                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
151                 comment.append({text:''});
152                 var user = editor.getUser(), creator;
153                 if(user) {
154                     creator = user.name;
155                     if(user.email) {
156                         creator += ' (' + user.email + ')';
157                     }
158                 } else {
159                     creator = 'anonymous';
160                 }
161
162                 var currentDate = new Date(),
163                     dt = pad(currentDate.getDate()) + '-' +
164                                 pad((currentDate.getMonth() + 1))  + '-' +
165                                 pad(currentDate.getFullYear()) + ' ' +
166                                 pad(currentDate.getHours()) + ':' +
167                                 pad(currentDate.getMinutes()) + ':' +
168                                 pad(currentDate.getSeconds());
169
170                 var metadata = comment.getMetadata();
171                 metadata.add({key: 'creator', value: creator});
172                 metadata.add({key: 'date', value: dt});
173             }, {
174                 metadata: {
175                     description: action.getState().description
176                 },
177                 success: callback
178             });
179         },
180     },
181     getState: function(params) {
182         var state = {
183             allowed: params.fragment && params.fragment.isValid() &&
184                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
185         };
186         if(state.allowed) {
187             state.description = gettext('Insert comment');
188         }
189         return state;
190     }
191 };
192
193
194 var createWrapTextAction = function(createParams) {
195     return {
196         name: createParams.name,
197         params: {
198             fragment: {type: 'context', name: 'fragment'},
199         },
200         getState: function(params) {
201             var state = {
202                     label: this.config.label
203                 },
204                 parent;
205             
206             if(!params.fragment || !params.fragment.isValid()) {
207                 return _.extend(state, {allowed: false});
208             }
209
210             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
211                 return _.extend(state, {
212                     allowed: true,
213                     toggled: true,
214                     description: createParams.unwrapDescription,
215                     execute: function(callback, params) {
216                         var node = params.fragment.node,
217                             doc = node.document,
218                             toRemove = node.getParent(createParams.klass),
219                             prefLen = 0;
220
221                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
222                             prefLen = toRemove.prev().getText().length;
223                         }
224
225                         doc.transaction(function() {
226                             var ret = toRemove.unwrapContent(),
227                                 newFragment = params.fragment;
228                             if(!newFragment.isValid()) {
229                                 newFragment =  doc.createFragment(doc.CaretFragment, {
230                                     node: ret.element1,
231                                     offset: prefLen + params.fragment.offset
232                                 });
233                             }
234                             return newFragment;
235                         }, {
236                             metadata: {
237                                 description: createParams.unwrapDescription,
238                                 fragment: params.fragment
239                             },
240                             success: callback
241                         });
242                     }
243                 });
244             }
245
246             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
247                 parent = params.fragment.startNode.parent();
248                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
249                     return _.extend(state, {allowed: false});
250                 }
251
252                 return _.extend(state, {
253                     allowed: true,
254                     description: createParams.wrapDescription,
255                     execute: function(callback, params) {
256                         params.fragment.document.transaction(function() {
257                             var parent = params.fragment.startNode.parent(),
258                                 doc = params.fragment.document,
259                                 wrapper, lastTextNode;
260                             
261                             wrapper = parent.wrapText({
262                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
263                                 offsetStart: params.fragment.startOffset,
264                                 offsetEnd: params.fragment.endOffset,
265                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
266                             });
267                                 
268                             lastTextNode = wrapper.getLastTextNode();
269                             if(lastTextNode) {
270                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
271                             }
272                         }, {
273                             metadata: {
274                                 description: createParams.wrapDescription,
275                                 fragment: params.fragment
276                             },
277                             success: callback
278                         });
279                     }
280                 });
281             }
282             return _.extend(state, {allowed: false});
283         }
284     };
285 };
286
287
288 var createLinkFromSelection = function(callback, params) {
289     var doc = params.fragment.document,
290         dialog = Dialog.create({
291             title: gettext('Create link'),
292             executeButtonText: gettext('Apply'),
293             cancelButtonText: gettext('Cancel'),
294             fields: [
295                 {label: gettext('Link'), name: 'href', type: 'input',
296                 prePasteHandler: function(text) {
297                                     return params.fragment.document.getLinkForUrl(text);
298                                 }.bind(this)
299                 }
300             ]
301         }),
302         action = this;
303     
304     dialog.on('execute', function(event) {
305         doc.transaction(function() {
306             var span =  action.params.fragment.startNode.parent().wrapText({
307                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
308                 offsetStart: params.fragment.startOffset,
309                 offsetEnd: params.fragment.endOffset,
310                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
311             }),
312                 doc = params.fragment.document;
313             event.success();
314             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
315         }, {
316             metadata: {
317                 description: action.getState().description,
318                 fragment: params.fragment
319             },
320             success: callback
321         });
322     });
323     dialog.show();
324 };
325
326 var editLink = function(callback, params) {
327     var doc = params.fragment.document,
328         link = params.fragment.node.getParent('link'),
329         dialog = Dialog.create({
330             title: gettext('Edit link'),
331             executeButtonText: gettext('Apply'),
332             cancelButtonText: gettext('Cancel'),
333             fields: [
334                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
335             ]
336         }),
337         action = this;
338     
339     dialog.on('execute', function(event) {
340         doc.transaction(function() {
341             link.setAttr('href', event.formData.href);
342             event.success();
343             return params.fragment;
344         }, {
345             metadata: {
346                 description: action.getState().description,
347                 fragment: params.fragment
348             },
349             success: callback
350         });
351     });
352     dialog.show();
353 };
354
355 var linkAction = {
356     name: 'link',
357     params: {
358         fragment: {type: 'context', name: 'fragment'}
359     },
360     stateDefaults: {
361         label: gettext('link')
362     },
363     getState: function(params) {
364         if(!params.fragment || !params.fragment.isValid()) {
365             return {allowed: false};
366         }
367
368         if(params.fragment instanceof params.fragment.TextRangeFragment) {
369             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
370                 return {allowed: false};
371             }
372             return {
373                 allowed: true,
374                 description: gettext('Create link from selection'),
375                 execute: createLinkFromSelection
376             };
377         }
378
379         if(params.fragment instanceof params.fragment.CaretFragment) {
380             if(params.fragment.node.isInside('link')) {
381                 return {
382                     allowed: true,
383                     toggled: true,
384                     description: gettext('Edit link'),
385                     execute: editLink
386                 };
387             }
388         }
389         return {allowed: false};
390     }
391 };
392
393 var metadataParams = {};
394
395 plugin.actions = [
396     undoRedoAction('undo'),
397     undoRedoAction('redo'),
398     commentAction,
399     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
400     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
401     linkAction,
402     metadataEditor.action(metadataParams)
403 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
404
405
406
407 plugin.config = function(config) {
408     // templates.actions[0].config(config.templates);
409     templates.actions[0].params.template.options = config.templates;
410     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
411         if(configRow1.key < configRow2.key) {
412             return -1;
413         }
414         if(configRow1.key > configRow2.key) {
415             return 1;
416         }
417         return 0;
418     });
419 };
420
421 plugin.canvasElements = canvasElements;
422
423 return plugin;
424
425 });