editor: canvas arrow key navigation improvements
[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: {}, documentNode: {}}},
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.documentNode.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 && ret.nodeType === Node.TEXT_NODE) {
142                     toret = {
143                         node: ret,
144                         offset: ret.getText().length - len
145                     };
146                 } else if(!toret) {
147                     toret = {
148                         node: ret.getFirstTextNode(),
149                         offset: 0
150                     };
151                 }
152             });
153             from.detach();
154             return toret;
155         };
156
157         var strategies = [
158             {
159                 applies: function() {
160                     return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
161                 },
162                 run: function() {
163                     var textNode = prev.getLastTextNode(),
164                         txt, prevText, prevTextLen;
165                     if(textNode) {
166                         txt = textNode.getText();
167                         if(txt.length > 1) {
168                             textNode.setText(txt.substr(0, txt.length-1));
169                             return {node: toMerge, offset: 0};
170                         } else {
171                             if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
172                                 prevTextLen = prevText.getText().length;
173                             }
174                             prev.detach();
175                             return {
176                                 node: prevText ? prevText : toMerge,
177                                 offset : prevText ? prevTextLen : 0
178                             };
179                         }
180                     }
181                 }
182             },
183             {
184                 applies: function() {
185                     return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
186                 },
187                 run: function() {
188                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
189                         return merge(toMerge, prev);
190                     }
191                     if(prev && prev.is('list')) {
192                         var items = prev.contents().filter(function(n) { return n.is('item');});
193                         return merge(toMerge, items[items.length-1]);
194                     }
195                 }
196             },
197             {
198                 applies: function() {
199                     return toMerge.is({tagName: 'span'});
200                 },
201                 run: function() {
202                     /* globals Node */
203                     var toret = {node: toMerge.contents()[0] , offset: 0},
204                         txt, txtNode, parent;
205                     if(!prev) {
206                         toMerge.parents().some(function(p) {
207                             if(p.is({tagName: 'span'})) {
208                                 parent = prev = p;
209                             } else {
210                                 if(!parent) {
211                                     parent = p;
212                                 }
213                                 prev = prev && prev.prev();
214                                 return true;
215                             }
216                         });
217                     }
218                     if(!prev) {
219                         return parent.moveUp();
220                     }
221                     else if(prev.nodeType === Node.TEXT_NODE && (txt = prev.getText())) {
222                         prev.setText(txt.substr(0, txt.length-1));
223                         return toret;
224                     } else if(prev.is({tagName: 'span'})) {
225                         if((txtNode = prev.getLastTextNode())) {
226                             txt = txtNode.getText();
227                             txtNode.setText(txt.substr(0, txt.length-1));
228                             return toret;
229                         }
230                     }
231
232                 }
233             },
234             {
235                 applies: function() {
236                     return toMerge.is({tagName: 'header'});
237                 },
238                 run: function() {
239                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
240                         return merge(toMerge, prev);
241                     }
242                 }
243             },
244             {
245                 applies: function() {
246                     return toMerge.is('item');
247                 },
248                 run: function() {
249                     var list;
250                     if(prev && prev.is('item')) {
251                         return merge(toMerge, prev);
252                     } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
253                         list.before(toMerge);
254                         toMerge.setClass('p');
255                         if(!list.contents().length) {
256                             list.detach();
257                         }
258                         return {node: toMerge.contents()[0], offset:0};
259                     }
260                 }
261             }
262         ];
263
264         var toret;
265         strategies.some(function(strategy) {
266             if(strategy.applies()) {
267                 toret = strategy.run();
268                 return true;
269             }
270         });
271         return toret;
272     }
273 };
274
275 var undoRedoAction = function(dir) {
276     return {
277         name: dir,
278         params: {
279             document: {type: 'context', name: 'document'},
280         },
281         stateDefaults: {
282             label: dir === 'undo' ? '<-' : '->',
283             icon: 'share-alt',
284             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
285             execute: function(callback, params) {
286                 var metadata = _.last(params.document[dir+'Stack']).metadata,
287                     fragment = metadata && metadata.fragment;
288                 params.document[dir]();
289                 if(fragment) {
290                     if(!fragment.isValid()) {
291                         fragment.restoreFromPaths();
292                     }
293                     if(fragment.isValid()) {
294                         callback(fragment);
295                     }
296                 }
297                 callback();
298             },
299         },
300         getState: function(params) {
301             var allowed = params.document && !!(params.document[dir+'Stack'].length),
302                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
303                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
304             if(allowed) {
305                 var metadata = _.last(params.document[dir+'Stack']).metadata;
306                 if(metadata) {
307                     desc += ': ' + (metadata.description || gettext('unknown operation'));
308                 }
309             }
310             return {
311                 allowed: allowed,
312                 description: allowed ? desc : descEmpty
313             };
314         }
315     };
316 };
317
318 var pad = function(number) {
319     if(number < 10) {
320         number = '0' + number;
321     }
322     return number;
323 };
324
325 var commentAction = {
326     name: 'comment',
327     params: {
328         fragment: {type: 'context', name: 'fragment'}
329     },
330     stateDefaults: {
331         icon: 'comment',
332         execute: function(callback, params, editor) {
333             /* globals Node */
334             var node = params.fragment.node,
335                 action = this;
336             if(node.nodeType === Node.TEXT_NODE) {
337                 node = node.parent();
338             }
339             node.document.transaction(function() {
340                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
341                 comment.append({text:''});
342                 var user = editor.getUser(), creator;
343                 if(user) {
344                     creator = user.name;
345                     if(user.email) {
346                         creator += ' (' + user.email + ')';
347                     }
348                 } else {
349                     creator = 'anonymous';
350                 }
351
352                 var currentDate = new Date(),
353                     dt = pad(currentDate.getDate()) + '-' +
354                                 pad((currentDate.getMonth() + 1))  + '-' +
355                                 pad(currentDate.getFullYear()) + ' ' +
356                                 pad(currentDate.getHours()) + ':' +
357                                 pad(currentDate.getMinutes()) + ':' +
358                                 pad(currentDate.getSeconds());
359
360                 var metadata = comment.getMetadata();
361                 metadata.add({key: 'creator', value: creator});
362                 metadata.add({key: 'date', value: dt});
363             }, {
364                 metadata: {
365                     description: action.getState().description
366                 },
367                 success: callback
368             });
369         },
370     },
371     getState: function(params) {
372         var state = {
373             allowed: params.fragment && params.fragment.isValid() &&
374                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
375         };
376         if(state.allowed) {
377             state.description = gettext('Insert comment');
378         }
379         return state;
380     }
381 };
382
383
384 var createWrapTextAction = function(createParams) {
385     return {
386         name: createParams.name,
387         params: {
388             fragment: {type: 'context', name: 'fragment'},
389         },
390         getState: function(params) {
391             var state = {
392                     label: this.config.label
393                 },
394                 parent;
395             
396             if(!params.fragment || !params.fragment.isValid()) {
397                 return _.extend(state, {allowed: false});
398             }
399
400             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
401                 return _.extend(state, {
402                     allowed: true,
403                     toggled: true,
404                     description: createParams.unwrapDescription,
405                     execute: function(callback, params) {
406                         var node = params.fragment.node,
407                             doc = node.document,
408                             toRemove = node.getParent(createParams.klass),
409                             prefLen = 0;
410
411                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
412                             prefLen = toRemove.prev().getText().length;
413                         }
414
415                         doc.transaction(function() {
416                             var ret = toRemove.unwrapContent(),
417                                 newFragment = params.fragment;
418                             if(!newFragment.isValid()) {
419                                 newFragment =  doc.createFragment(doc.CaretFragment, {
420                                     node: ret.element1,
421                                     offset: prefLen + params.fragment.offset
422                                 });
423                             }
424                             return newFragment;
425                         }, {
426                             metadata: {
427                                 description: createParams.unwrapDescription,
428                                 fragment: params.fragment
429                             },
430                             success: callback
431                         });
432                     }
433                 });
434             }
435
436             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
437                 parent = params.fragment.startNode.parent();
438                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
439                     return _.extend(state, {allowed: false});
440                 }
441
442                 return _.extend(state, {
443                     allowed: true,
444                     description: createParams.wrapDescription,
445                     execute: function(callback, params) {
446                         params.fragment.document.transaction(function() {
447                             var parent = params.fragment.startNode.parent(),
448                                 doc = params.fragment.document,
449                                 wrapper, lastTextNode;
450                             
451                             wrapper = parent.wrapText({
452                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
453                                 offsetStart: params.fragment.startOffset,
454                                 offsetEnd: params.fragment.endOffset,
455                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
456                             });
457                                 
458                             lastTextNode = wrapper.getLastTextNode();
459                             if(lastTextNode) {
460                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
461                             }
462                         }, {
463                             metadata: {
464                                 description: createParams.wrapDescription,
465                                 fragment: params.fragment
466                             },
467                             success: callback
468                         });
469                     }
470                 });
471             }
472             return _.extend(state, {allowed: false});
473         }
474     };
475 };
476
477
478 var createLinkFromSelection = function(callback, params) {
479     var doc = params.fragment.document,
480         dialog = Dialog.create({
481             title: gettext('Create link'),
482             executeButtonText: gettext('Apply'),
483             cancelButtonText: gettext('Cancel'),
484             fields: [
485                 {label: gettext('Link'), name: 'href', type: 'input',
486                 prePasteHandler: function(text) {
487                                     return params.fragment.document.getLinkForUrl(text);
488                                 }.bind(this)
489                 }
490             ]
491         }),
492         action = this;
493     
494     dialog.on('execute', function(event) {
495         doc.transaction(function() {
496             var span =  action.params.fragment.startNode.parent().wrapText({
497                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
498                 offsetStart: params.fragment.startOffset,
499                 offsetEnd: params.fragment.endOffset,
500                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
501             }),
502                 doc = params.fragment.document;
503             event.success();
504             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
505         }, {
506             metadata: {
507                 description: action.getState().description,
508                 fragment: params.fragment
509             },
510             success: callback
511         });
512     });
513     dialog.show();
514 };
515
516 var editLink = function(callback, params) {
517     var doc = params.fragment.document,
518         link = params.fragment.node.getParent('link'),
519         dialog = Dialog.create({
520             title: gettext('Edit link'),
521             executeButtonText: gettext('Apply'),
522             cancelButtonText: gettext('Cancel'),
523             fields: [
524                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
525             ]
526         }),
527         action = this;
528     
529     dialog.on('execute', function(event) {
530         doc.transaction(function() {
531             link.setAttr('href', event.formData.href);
532             event.success();
533             return params.fragment;
534         }, {
535             metadata: {
536                 description: action.getState().description,
537                 fragment: params.fragment
538             },
539             success: callback
540         });
541     });
542     dialog.show();
543 };
544
545 var linkAction = {
546     name: 'link',
547     params: {
548         fragment: {type: 'context', name: 'fragment'}
549     },
550     stateDefaults: {
551         label: gettext('link')
552     },
553     getState: function(params) {
554         if(!params.fragment || !params.fragment.isValid()) {
555             return {allowed: false};
556         }
557
558         if(params.fragment instanceof params.fragment.TextRangeFragment) {
559             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
560                 return {allowed: false};
561             }
562             return {
563                 allowed: true,
564                 description: gettext('Create link from selection'),
565                 execute: createLinkFromSelection
566             };
567         }
568
569         if(params.fragment instanceof params.fragment.CaretFragment) {
570             if(params.fragment.node.isInside('link')) {
571                 return {
572                     allowed: true,
573                     toggled: true,
574                     description: gettext('Edit link'),
575                     execute: editLink
576                 };
577             }
578         }
579         return {allowed: false};
580     }
581 };
582
583 var metadataParams = {};
584
585 plugin.actions = [
586     undoRedoAction('undo'),
587     undoRedoAction('redo'),
588     commentAction,
589     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
590     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
591     linkAction,
592     metadataEditor.action(metadataParams)
593 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
594
595
596
597 plugin.config = function(config) {
598     // templates.actions[0].config(config.templates);
599     templates.actions[0].params.template.options = config.templates;
600     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
601         if(configRow1.key < configRow2.key) {
602             return -1;
603         }
604         if(configRow1.key > configRow2.key) {
605             return 1;
606         }
607         return 0;
608     });
609 };
610
611 plugin.canvasElements = canvasElements;
612
613 return plugin;
614
615 });