425b161fdf37bb41474cf20212dc3af0827ba999
[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: {}, elementNode: {}}},
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                 isSpan = node.parent().getTagName() === 'span',
23                 parentDescribingNodes = [],
24                 newNodes, emptyText;
25             newNodes = node.split({offset: args.offset});
26             newNodes.second.contents()
27                 .filter(function(child) {
28                     return child.object.describesParent;
29                 })
30                 .forEach(function(child) {
31                     //child.detach();
32                     parentDescribingNodes.push(child);
33                     child.detach();
34                 });
35             [newNodes.first, newNodes.second].some(function(newNode) {
36                 if(!(newNode.contents().length)) {
37                     emptyText = newNode.append({text: ''});
38                     return true; // break
39                 }
40             });
41             parentDescribingNodes.forEach(function(node) {
42                 newNodes.first.append(node);
43             });
44
45             var parent, newNode;
46
47             var copyNode = function(n) {
48                 var attrs = {};
49                 n.getAttrs().forEach(function(attr) {
50                     attrs[attr.name] = attr.value;
51                 });
52
53                 return node.document.createDocumentNode({
54                     tagName: n.getTagName(),
55                     attrs: attrs
56                 });
57             };
58
59             var move = function(node, to) {
60                 var copy;
61                 if(!node.containsNode(newNodes.second)) {
62                     to.append(node);
63                     return false;
64                 } else {
65                     if(!node.sameNode(newNodes.second)) {
66                         copy = to.append(copyNode(node));
67                         node.contents().some(function(n) {
68                             return move(n, copy);
69                         });
70                     }
71                     return true;
72                 }
73             };
74
75             if(isSpan) {
76                 newNodes.first.parents().some(function(p) {
77                     if(p.getTagName() !== 'span') {
78                         parent = p;
79                         return true;
80                     }
81                 });
82                 newNode = parent.before({tagName: parent.getTagName(), attrs: {'class': parent.getClass()}});
83                 parent.contents().some(function(n) {
84                     return move(n, newNode);
85                 });
86             }
87
88             return _.extend(newNodes, {emptyText: emptyText});
89         }
90     },
91     mergeContentUp: function() {
92         /* globals Node */
93         var myPrev = this,
94             base = this,
95             ret;
96
97         if(myPrev.nodeType === Node.TEXT_NODE) {
98             if(myPrev.getIndex() > 0) {
99                 return;
100             }
101             myPrev = base = myPrev.parent();
102         }
103
104         myPrev = myPrev && myPrev.prev();
105
106         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
107             var ptr = this,
108                 next;
109             while(ptr) {
110                 next = ptr.next();
111                 if(!ret) {
112                     ret = myPrev.append(ptr);
113                 } else {
114                     myPrev.append(ptr);
115                 }
116                 
117                 ptr = next;
118             }
119             if(base !== this) {
120                 base.detach();
121             }
122             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
123         }
124     }
125 };
126
127 plugin.documentExtension.elementNode.transformations = {
128     moveUp: function() {
129         var toMerge = this,
130             prev = toMerge.prev();
131
132         var merge = function(from, to) {
133             var toret;
134             from.contents().forEach(function(node, idx) {
135                 var len, ret;
136                 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
137                     len = node.getText().length;
138                 }
139                 ret = to.append(node);
140                 
141                 if(idx === 0) {
142                     toret = {
143                         node: ret,
144                         offset: ret.getText().length - len
145                     };
146                 }
147             });
148             from.detach();
149             return toret;
150         };
151
152         var strategies = [
153             {
154                 applies: function() {
155                     return toMerge.is('p');
156                 },
157                 run: function() {
158                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
159                         return merge(toMerge, prev);
160                     }
161                     if(prev && prev.is('list')) {
162                         var items = prev.contents().filter(function(n) { return n.is('item');});
163                         return merge(toMerge, items[items.length-1]);
164                     }
165                 }
166             },
167             {
168                 applies: function() {
169                     return toMerge.is({tagName: 'header'});
170                 },
171                 run: function() {
172                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
173                         return merge(toMerge, prev);
174                     }
175                 }
176             },
177             {
178                 applies: function() {
179                     return toMerge.is('item');
180                 },
181                 run: function() {
182                     var list;
183                     if(prev && prev.is('item')) {
184                         return merge(toMerge, prev);
185                     } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
186                         list.before(toMerge);
187                         toMerge.setClass('p');
188                         if(!list.contents().length) {
189                             list.detach();
190                         }
191                         return {node: toMerge.contents()[0], offset:0};
192                     }
193                 }
194             }
195         ];
196
197         var toret;
198         strategies.some(function(strategy) {
199             if(strategy.applies()) {
200                 toret = strategy.run();
201                 return true;
202             }
203         });
204         return toret;
205     }
206 };
207
208 var undoRedoAction = function(dir) {
209     return {
210         name: dir,
211         params: {
212             document: {type: 'context', name: 'document'},
213         },
214         stateDefaults: {
215             label: dir === 'undo' ? '<-' : '->',
216             icon: 'share-alt',
217             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
218             execute: function(callback, params) {
219                 var metadata = _.last(params.document[dir+'Stack']).metadata,
220                     fragment = metadata && metadata.fragment;
221                 params.document[dir]();
222                 if(fragment) {
223                     if(!fragment.isValid()) {
224                         fragment.restoreFromPaths();
225                     }
226                     if(fragment.isValid()) {
227                         callback(fragment);
228                     }
229                 }
230                 callback();
231             },
232         },
233         getState: function(params) {
234             var allowed = params.document && !!(params.document[dir+'Stack'].length),
235                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
236                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
237             if(allowed) {
238                 var metadata = _.last(params.document[dir+'Stack']).metadata;
239                 if(metadata) {
240                     desc += ': ' + (metadata.description || gettext('unknown operation'));
241                 }
242             }
243             return {
244                 allowed: allowed,
245                 description: allowed ? desc : descEmpty
246             };
247         }
248     };
249 };
250
251 var pad = function(number) {
252     if(number < 10) {
253         number = '0' + number;
254     }
255     return number;
256 };
257
258 var commentAction = {
259     name: 'comment',
260     params: {
261         fragment: {type: 'context', name: 'fragment'}
262     },
263     stateDefaults: {
264         icon: 'comment',
265         execute: function(callback, params, editor) {
266             /* globals Node */
267             var node = params.fragment.node,
268                 action = this;
269             if(node.nodeType === Node.TEXT_NODE) {
270                 node = node.parent();
271             }
272             node.document.transaction(function() {
273                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
274                 comment.append({text:''});
275                 var user = editor.getUser(), creator;
276                 if(user) {
277                     creator = user.name;
278                     if(user.email) {
279                         creator += ' (' + user.email + ')';
280                     }
281                 } else {
282                     creator = 'anonymous';
283                 }
284
285                 var currentDate = new Date(),
286                     dt = pad(currentDate.getDate()) + '-' +
287                                 pad((currentDate.getMonth() + 1))  + '-' +
288                                 pad(currentDate.getFullYear()) + ' ' +
289                                 pad(currentDate.getHours()) + ':' +
290                                 pad(currentDate.getMinutes()) + ':' +
291                                 pad(currentDate.getSeconds());
292
293                 var metadata = comment.getMetadata();
294                 metadata.add({key: 'creator', value: creator});
295                 metadata.add({key: 'date', value: dt});
296             }, {
297                 metadata: {
298                     description: action.getState().description
299                 },
300                 success: callback
301             });
302         },
303     },
304     getState: function(params) {
305         var state = {
306             allowed: params.fragment && params.fragment.isValid() &&
307                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
308         };
309         if(state.allowed) {
310             state.description = gettext('Insert comment');
311         }
312         return state;
313     }
314 };
315
316
317 var createWrapTextAction = function(createParams) {
318     return {
319         name: createParams.name,
320         params: {
321             fragment: {type: 'context', name: 'fragment'},
322         },
323         getState: function(params) {
324             var state = {
325                     label: this.config.label
326                 },
327                 parent;
328             
329             if(!params.fragment || !params.fragment.isValid()) {
330                 return _.extend(state, {allowed: false});
331             }
332
333             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
334                 return _.extend(state, {
335                     allowed: true,
336                     toggled: true,
337                     description: createParams.unwrapDescription,
338                     execute: function(callback, params) {
339                         var node = params.fragment.node,
340                             doc = node.document,
341                             toRemove = node.getParent(createParams.klass),
342                             prefLen = 0;
343
344                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
345                             prefLen = toRemove.prev().getText().length;
346                         }
347
348                         doc.transaction(function() {
349                             var ret = toRemove.unwrapContent(),
350                                 newFragment = params.fragment;
351                             if(!newFragment.isValid()) {
352                                 newFragment =  doc.createFragment(doc.CaretFragment, {
353                                     node: ret.element1,
354                                     offset: prefLen + params.fragment.offset
355                                 });
356                             }
357                             return newFragment;
358                         }, {
359                             metadata: {
360                                 description: createParams.unwrapDescription,
361                                 fragment: params.fragment
362                             },
363                             success: callback
364                         });
365                     }
366                 });
367             }
368
369             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
370                 parent = params.fragment.startNode.parent();
371                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
372                     return _.extend(state, {allowed: false});
373                 }
374
375                 return _.extend(state, {
376                     allowed: true,
377                     description: createParams.wrapDescription,
378                     execute: function(callback, params) {
379                         params.fragment.document.transaction(function() {
380                             var parent = params.fragment.startNode.parent(),
381                                 doc = params.fragment.document,
382                                 wrapper, lastTextNode;
383                             
384                             wrapper = parent.wrapText({
385                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
386                                 offsetStart: params.fragment.startOffset,
387                                 offsetEnd: params.fragment.endOffset,
388                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
389                             });
390                                 
391                             lastTextNode = wrapper.getLastTextNode();
392                             if(lastTextNode) {
393                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
394                             }
395                         }, {
396                             metadata: {
397                                 description: createParams.wrapDescription,
398                                 fragment: params.fragment
399                             },
400                             success: callback
401                         });
402                     }
403                 });
404             }
405             return _.extend(state, {allowed: false});
406         }
407     };
408 };
409
410
411 var createLinkFromSelection = function(callback, params) {
412     var doc = params.fragment.document,
413         dialog = Dialog.create({
414             title: gettext('Create link'),
415             executeButtonText: gettext('Apply'),
416             cancelButtonText: gettext('Cancel'),
417             fields: [
418                 {label: gettext('Link'), name: 'href', type: 'input',
419                 prePasteHandler: function(text) {
420                                     return params.fragment.document.getLinkForUrl(text);
421                                 }.bind(this)
422                 }
423             ]
424         }),
425         action = this;
426     
427     dialog.on('execute', function(event) {
428         doc.transaction(function() {
429             var span =  action.params.fragment.startNode.parent().wrapText({
430                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
431                 offsetStart: params.fragment.startOffset,
432                 offsetEnd: params.fragment.endOffset,
433                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
434             }),
435                 doc = params.fragment.document;
436             event.success();
437             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
438         }, {
439             metadata: {
440                 description: action.getState().description,
441                 fragment: params.fragment
442             },
443             success: callback
444         });
445     });
446     dialog.show();
447 };
448
449 var editLink = function(callback, params) {
450     var doc = params.fragment.document,
451         link = params.fragment.node.getParent('link'),
452         dialog = Dialog.create({
453             title: gettext('Edit link'),
454             executeButtonText: gettext('Apply'),
455             cancelButtonText: gettext('Cancel'),
456             fields: [
457                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
458             ]
459         }),
460         action = this;
461     
462     dialog.on('execute', function(event) {
463         doc.transaction(function() {
464             link.setAttr('href', event.formData.href);
465             event.success();
466             return params.fragment;
467         }, {
468             metadata: {
469                 description: action.getState().description,
470                 fragment: params.fragment
471             },
472             success: callback
473         });
474     });
475     dialog.show();
476 };
477
478 var linkAction = {
479     name: 'link',
480     params: {
481         fragment: {type: 'context', name: 'fragment'}
482     },
483     stateDefaults: {
484         label: gettext('link')
485     },
486     getState: function(params) {
487         if(!params.fragment || !params.fragment.isValid()) {
488             return {allowed: false};
489         }
490
491         if(params.fragment instanceof params.fragment.TextRangeFragment) {
492             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
493                 return {allowed: false};
494             }
495             return {
496                 allowed: true,
497                 description: gettext('Create link from selection'),
498                 execute: createLinkFromSelection
499             };
500         }
501
502         if(params.fragment instanceof params.fragment.CaretFragment) {
503             if(params.fragment.node.isInside('link')) {
504                 return {
505                     allowed: true,
506                     toggled: true,
507                     description: gettext('Edit link'),
508                     execute: editLink
509                 };
510             }
511         }
512         return {allowed: false};
513     }
514 };
515
516 var metadataParams = {};
517
518 plugin.actions = [
519     undoRedoAction('undo'),
520     undoRedoAction('redo'),
521     commentAction,
522     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
523     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
524     linkAction,
525     metadataEditor.action(metadataParams)
526 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
527
528
529
530 plugin.config = function(config) {
531     // templates.actions[0].config(config.templates);
532     templates.actions[0].params.template.options = config.templates;
533     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
534         if(configRow1.key < configRow2.key) {
535             return -1;
536         }
537         if(configRow1.key > configRow2.key) {
538             return 1;
539         }
540         return 0;
541     });
542 };
543
544 plugin.canvasElements = canvasElements;
545
546 return plugin;
547
548 });