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