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