8ac4f631215f2c8125ad5f096d684d24ce7a4035
[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     edumed = require('plugins/core/edumed/edumed'),
16     add_attachments = require('views/attachments/add_attachments');
17
18
19 var exerciseFix = function(newNodes) {
20     var list, exercise, max, addedItem, answerValues;
21     if(newNodes.created.is('item')) {
22         list = newNodes.created.parent();
23         exercise = list.parent();
24         if(exercise && exercise.is('exercise')) {
25             if(exercise.is('exercise.order')) {
26                 answerValues = exercise.object.getItems()
27                             .map(function(item) {
28                                 if(!addedItem && item.node.sameNode(newNodes.created)) {
29                                     addedItem = item;
30                                 }
31                                 return item.getAnswer();
32                             });
33                 max = Math.max.apply(Math.max, answerValues);
34                 addedItem.setAnswer(max + 1);
35             }
36         }
37     }
38 };
39
40 plugin.documentExtension.textNode.transformations = {
41     breakContent: {
42         impl: function(args) {
43             var node = this,
44                 isSpan = node.parent().getTagName() === 'span',
45                 parentDescribingNodes = [],
46                 newNodes, emptyText;
47             newNodes = node.split({offset: args.offset});
48             newNodes.second.contents()
49                 .filter(function(child) {
50                     return child.object.describesParent;
51                 })
52                 .forEach(function(child) {
53                     //child.detach();
54                     parentDescribingNodes.push(child);
55                     child.detach();
56                 });
57             [newNodes.first, newNodes.second].some(function(newNode) {
58                 if(!(newNode.contents().length)) {
59                     emptyText = newNode.append({text: ''});
60                     return true; // break
61                 }
62             });
63
64             /* <hack>
65             /*
66                 This makes sure that adding a new item to the list in some of the edumed exercises
67                 sets an answer attribute that makes sense (and not just copies it which would create
68                 a duplicate value).
69
70                 This won't be neccessary when/if we introduce canvas element own key event handlers.
71
72                 Alternatively, WLXML elements could implement their own item split methods that we
73                 would delegate to.
74             */
75                 exerciseFix(newNodes);
76             /* </hack> */
77
78             parentDescribingNodes.forEach(function(node) {
79                 newNodes.first.append(node);
80             });
81
82             var parent, newNode;
83
84             var copyNode = function(n) {
85                 var attrs = {};
86                 n.getAttrs().forEach(function(attr) {
87                     attrs[attr.name] = attr.value;
88                 });
89
90                 return node.document.createDocumentNode({
91                     tagName: n.getTagName(),
92                     attrs: attrs
93                 });
94             };
95
96             var move = function(node, to) {
97                 var copy;
98                 if(!node.containsNode(newNodes.second)) {
99                     to.append(node);
100                     return false;
101                 } else {
102                     if(!node.sameNode(newNodes.second)) {
103                         copy = to.append(copyNode(node));
104                         node.contents().some(function(n) {
105                             return move(n, copy);
106                         });
107                     }
108                     return true;
109                 }
110             };
111
112             if(isSpan) {
113                 newNodes.first.parents().some(function(p) {
114                     if(p.getTagName() !== 'span') {
115                         parent = p;
116                         return true;
117                     }
118                 });
119                 newNode = parent.before({tagName: parent.getTagName(), attrs: {'class': parent.getClass()}});
120                 parent.contents().some(function(n) {
121                     return move(n, newNode);
122                 });
123             }
124
125             return _.extend(newNodes, {emptyText: emptyText});
126         }
127     },
128     mergeContentUp: function() {
129         /* globals Node */
130         var myPrev = this,
131             base = this,
132             ret;
133
134         if(myPrev.nodeType === Node.TEXT_NODE) {
135             if(myPrev.getIndex() > 0) {
136                 return;
137             }
138             myPrev = base = myPrev.parent();
139         }
140
141         myPrev = myPrev && myPrev.prev();
142
143         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
144             var ptr = this,
145                 next;
146             while(ptr) {
147                 next = ptr.next();
148                 if(!ret) {
149                     ret = myPrev.append(ptr);
150                 } else {
151                     myPrev.append(ptr);
152                 }
153                 
154                 ptr = next;
155             }
156             if(base !== this) {
157                 base.detach();
158             }
159             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
160         }
161     }
162 };
163
164 plugin.documentExtension.documentNode.transformations = {
165     moveUp: function() {
166         var toMerge = this,
167             prev = toMerge.prev();
168
169         var merge = function(from, to) {
170             var toret;
171             from.contents().forEach(function(node, idx) {
172                 var len, ret;
173                 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
174                     len = node.getText().length;
175                 }
176                 ret = to.append(node);
177                 
178                 if(idx === 0 && ret.nodeType === Node.TEXT_NODE) {
179                     toret = {
180                         node: ret,
181                         offset: ret.getText().length - len
182                     };
183                 } else if(!toret) {
184                     toret = {
185                         node: ret.getFirstTextNode(),
186                         offset: 0
187                     };
188                 }
189             });
190             from.detach();
191             return toret;
192         };
193
194         var strategies = [
195             {
196                 applies: function() {
197                     return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
198                 },
199                 run: function() {
200                     var textNode = prev.getLastTextNode(),
201                         txt, prevText, prevTextLen;
202                     if(textNode) {
203                         txt = textNode.getText();
204                         if(txt.length > 1) {
205                             textNode.setText(txt.substr(0, txt.length-1));
206                             return {node: toMerge, offset: 0};
207                         } else {
208                             if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
209                                 prevTextLen = prevText.getText().length;
210                             }
211                             prev.detach();
212                             return {
213                                 node: prevText ? prevText : toMerge,
214                                 offset : prevText ? prevTextLen : 0
215                             };
216                         }
217                     }
218                 }
219             },
220             {
221                 applies: function() {
222                     return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
223                 },
224                 run: function() {
225                     if(prev && (prev.is('p') || prev.is({tagName: 'header'}))) {
226                         return merge(toMerge, prev);
227                     }
228                     if(prev && prev.is('list')) {
229                         var items = prev.contents().filter(function(n) { return n.is('item');});
230                         return merge(toMerge, items[items.length-1]);
231                     }
232                 }
233             },
234             {
235                 applies: function() {
236                     return toMerge.is({tagName: 'span'});
237                 },
238                 run: function() {
239                     /* globals Node */
240                     var toret = {node: toMerge.contents()[0] , offset: 0},
241                         txt, txtNode, parent;
242                     if(!prev) {
243                         toMerge.parents().some(function(p) {
244                             if(p.is({tagName: 'span'})) {
245                                 parent = prev = p;
246                             } else {
247                                 if(!parent) {
248                                     parent = p;
249                                 }
250                                 prev = prev && prev.prev();
251                                 return true;
252                             }
253                         });
254                     }
255                     if(!prev) {
256                         return parent.moveUp();
257                     }
258                     else if(prev.nodeType === Node.TEXT_NODE && (txt = prev.getText())) {
259                         prev.setText(txt.substr(0, txt.length-1));
260                         return toret;
261                     } else if(prev.is({tagName: 'span'})) {
262                         if((txtNode = prev.getLastTextNode())) {
263                             txt = txtNode.getText();
264                             if(txt.length > 1) {
265                                 txtNode.setText(txt.substr(0, txt.length-1));
266                             } else {
267                                 if(txtNode.parent().contents().length === 1) {
268                                     txtNode.parent().detach();
269                                 } else {
270                                     txtNode.detach();
271                                 }
272
273                             }
274                             return toret;
275                         }
276                     }
277
278                 }
279             },
280             {
281                 applies: function() {
282                     return toMerge.is({tagName: 'header'});
283                 },
284                 run: function() {
285                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
286                         return merge(toMerge, prev);
287                     }
288                 }
289             },
290             {
291                 applies: function() {
292                     return toMerge.is('item');
293                 },
294                 run: function() {
295                     var list;
296                     if(prev && prev.is('item')) {
297                         return merge(toMerge, prev);
298                     } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
299                         list.before(toMerge);
300                         toMerge.setClass('p');
301                         if(!list.contents().length) {
302                             list.detach();
303                         }
304                         return {node: toMerge.contents()[0], offset:0};
305                     }
306                 }
307             }
308         ];
309
310         var toret;
311         strategies.some(function(strategy) {
312             if(strategy.applies()) {
313                 toret = strategy.run();
314                 return true;
315             }
316         });
317         return toret;
318     },
319     insertNewNode: function () {
320         var node = this;
321         var newElement = this.document.createDocumentNode({tagName: 'div', attrs: {class: 'p'}});
322         node.after(newElement);
323         newElement.append({text: ''});
324         return newElement;
325     }
326 };
327
328 var undoRedoAction = function(dir) {
329     return {
330         name: dir,
331         params: {
332             document: {type: 'context', name: 'document'},
333         },
334         stateDefaults: {
335             label: dir === 'undo' ? '<-' : '->',
336             icon: 'share-alt',
337             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
338             execute: function(callback, params) {
339                 var metadata = _.last(params.document[dir+'Stack']).metadata,
340                     fragment = metadata && metadata.fragment;
341                 params.document[dir]();
342                 if(fragment) {
343                     if(!fragment.isValid()) {
344                         fragment.restoreFromPaths();
345                     }
346                     if(fragment.isValid()) {
347                         callback(fragment);
348                     }
349                 }
350                 callback();
351             },
352         },
353         getState: function(params) {
354             var allowed = params.document && !!(params.document[dir+'Stack'].length),
355                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
356                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
357             if(allowed) {
358                 var metadata = _.last(params.document[dir+'Stack']).metadata;
359                 if(metadata) {
360                     desc += ': ' + (metadata.description || gettext('unknown operation'));
361                 }
362             }
363             return {
364                 allowed: allowed,
365                 description: allowed ? desc : descEmpty
366             };
367         }
368     };
369 };
370
371 var pad = function(number) {
372     if(number < 10) {
373         number = '0' + number;
374     }
375     return number;
376 };
377
378 var commentAction = {
379     name: 'comment',
380     params: {
381         fragment: {type: 'context', name: 'fragment'}
382     },
383     stateDefaults: {
384         icon: 'comment',
385         execute: function(callback, params, editor) {
386             /* globals Node */
387             var node = params.fragment.node,
388                 action = this;
389             if(node.nodeType === Node.TEXT_NODE) {
390                 node = node.parent();
391             }
392             node.document.transaction(function() {
393                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
394                 comment.append({text:''});
395                 var user = editor.getUser(), creator;
396                 if(user) {
397                     creator = user.name;
398                     if(user.email) {
399                         creator += ' (' + user.email + ')';
400                     }
401                 } else {
402                     creator = 'anonymous';
403                 }
404
405                 var currentDate = new Date(),
406                     dt = pad(currentDate.getDate()) + '-' +
407                                 pad((currentDate.getMonth() + 1))  + '-' +
408                                 pad(currentDate.getFullYear()) + ' ' +
409                                 pad(currentDate.getHours()) + ':' +
410                                 pad(currentDate.getMinutes()) + ':' +
411                                 pad(currentDate.getSeconds());
412
413                 var metadata = comment.getMetadata();
414                 metadata.add({key: 'creator', value: creator});
415                 metadata.add({key: 'date', value: dt});
416             }, {
417                 metadata: {
418                     description: action.getState().description
419                 },
420                 success: callback
421             });
422         },
423     },
424     getState: function(params) {
425         var state = {
426             allowed: params.fragment && params.fragment.isValid() &&
427                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
428         };
429         if(state.allowed) {
430             state.description = gettext('Insert comment');
431         }
432         return state;
433     }
434 };
435
436
437 var createWrapTextAction = function(createParams) {
438     return {
439         name: createParams.name,
440         params: {
441             fragment: {type: 'context', name: 'fragment'},
442         },
443         getState: function(params) {
444             var state = {
445                     label: this.config.label
446                 },
447                 parent;
448             
449             if(!params.fragment || !params.fragment.isValid()) {
450                 return _.extend(state, {allowed: false});
451             }
452
453             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
454                 return _.extend(state, {
455                     allowed: true,
456                     toggled: true,
457                     description: createParams.unwrapDescription,
458                     execute: function(callback, params) {
459                         var node = params.fragment.node,
460                             doc = node.document,
461                             toRemove = node.getParent(createParams.klass),
462                             prefLen = 0;
463
464                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
465                             prefLen = toRemove.prev().getText().length;
466                         }
467
468                         doc.transaction(function() {
469                             var ret = toRemove.unwrapContent(),
470                                 newFragment = params.fragment;
471                             if(!newFragment.isValid()) {
472                                 newFragment =  doc.createFragment(doc.CaretFragment, {
473                                     node: ret.element1,
474                                     offset: prefLen + params.fragment.offset
475                                 });
476                             }
477                             return newFragment;
478                         }, {
479                             metadata: {
480                                 description: createParams.unwrapDescription,
481                                 fragment: params.fragment
482                             },
483                             success: callback
484                         });
485                     }
486                 });
487             }
488
489             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
490                 parent = params.fragment.startNode.parent();
491                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
492                     return _.extend(state, {allowed: false});
493                 }
494
495                 return _.extend(state, {
496                     allowed: true,
497                     description: createParams.wrapDescription,
498                     execute: function(callback, params) {
499                         params.fragment.document.transaction(function() {
500                             var parent = params.fragment.startNode.parent(),
501                                 doc = params.fragment.document,
502                                 wrapper, lastTextNode;
503                             
504                             wrapper = parent.wrapText({
505                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
506                                 offsetStart: params.fragment.startOffset,
507                                 offsetEnd: params.fragment.endOffset,
508                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
509                             });
510                                 
511                             lastTextNode = wrapper.getLastTextNode();
512                             if(lastTextNode) {
513                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
514                             }
515                         }, {
516                             metadata: {
517                                 description: createParams.wrapDescription,
518                                 fragment: params.fragment
519                             },
520                             success: callback
521                         });
522                     }
523                 });
524             }
525             return _.extend(state, {allowed: false});
526         }
527     };
528 };
529
530
531 var createLinkFromSelection = function(callback, params) {
532     var fragment = params.fragment,
533         doc = fragment.document,
534         text = fragment.startNode.nativeNode.data.substring(fragment.startOffset, fragment.endOffset),
535         url;
536     if (text.indexOf('//') >= 0 && text.indexOf(' ') < 0) {
537         url = text;
538     } else if (text.substr(0, 4) === 'www.' && text.indexOF(' ') < 0) {
539         url = 'http://' + text;
540     }
541     var dialog = Dialog.create({
542             title: gettext('Create link'),
543             executeButtonText: gettext('Apply'),
544             cancelButtonText: gettext('Cancel'),
545             fields: [
546                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: url || '',
547                 prePasteHandler: function(text) {
548                                     return params.fragment.document.getLinkForUrl(text);
549                                 }.bind(this)
550                 }
551             ]
552         }),
553         action = this;
554     
555     dialog.on('execute', function(event) {
556         doc.transaction(function() {
557             var span =  action.params.fragment.startNode.parent().wrapText({
558                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
559                 offsetStart: params.fragment.startOffset,
560                 offsetEnd: params.fragment.endOffset,
561                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
562             }),
563                 doc = params.fragment.document;
564             event.success();
565             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
566         }, {
567             metadata: {
568                 description: action.getState().description,
569                 fragment: params.fragment
570             },
571             success: callback
572         });
573     });
574     dialog.show();
575     add_attachments(dialog);
576 };
577
578 var editLink = function(callback, params) {
579     var doc = params.fragment.document,
580         link = params.fragment.node.getParent('link'),
581         dialog = Dialog.create({
582             title: gettext('Edit link'),
583             executeButtonText: gettext('Apply'),
584             cancelButtonText: gettext('Cancel'),
585             fields: [
586                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
587             ]
588         }),
589         action = this;
590     
591     dialog.on('execute', function(event) {
592         doc.transaction(function() {
593             link.setAttr('href', event.formData.href);
594             event.success();
595             return params.fragment;
596         }, {
597             metadata: {
598                 description: action.getState().description,
599                 fragment: params.fragment
600             },
601             success: callback
602         });
603     });
604     dialog.show();
605 };
606
607 var linkAction = {
608     name: 'link',
609     params: {
610         fragment: {type: 'context', name: 'fragment'}
611     },
612     stateDefaults: {
613         label: gettext('link')
614     },
615     getState: function(params) {
616         if(!params.fragment || !params.fragment.isValid()) {
617             return {allowed: false};
618         }
619
620         if(params.fragment instanceof params.fragment.TextRangeFragment) {
621             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
622                 return {allowed: false};
623             }
624             return {
625                 allowed: true,
626                 description: gettext('Create link from selection'),
627                 execute: createLinkFromSelection
628             };
629         }
630
631         if(params.fragment instanceof params.fragment.CaretFragment) {
632             if(params.fragment.node.isInside('link')) {
633                 return {
634                     allowed: true,
635                     toggled: true,
636                     description: gettext('Edit link'),
637                     execute: editLink
638                 };
639             }
640         }
641         return {allowed: false};
642     }
643 };
644
645 var metadataParams = {};
646
647 plugin.actions = [
648     undoRedoAction('undo'),
649     undoRedoAction('redo'),
650     commentAction,
651     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
652     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
653     linkAction,
654     metadataEditor.action(metadataParams)
655 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
656
657
658 plugin.config = function(config) {
659     // templates.actions[0].config(config.templates);
660     templates.actions[0].params.template.options = config.templates;
661     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
662         if(configRow1.key < configRow2.key) {
663             return -1;
664         }
665         if(configRow1.key > configRow2.key) {
666             return 1;
667         }
668         return 0;
669     });
670 };
671
672 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);
673
674 return plugin;
675
676 });