simplify
[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     attachments = require('views/attachments/attachments');
17
18
19
20
21 var exerciseFix = function(newNodes) {
22     var list, exercise, max, addedItem, answerValues;
23     if(newNodes.created.is('item')) {
24         list = newNodes.created.parent();
25         exercise = list.parent();
26         if(exercise && exercise.is('exercise')) {
27             if(exercise.is('exercise.order')) {
28                 answerValues = exercise.object.getItems()
29                             .map(function(item) {
30                                 if(!addedItem && item.node.sameNode(newNodes.created)) {
31                                     addedItem = item;
32                                 }
33                                 return item.getAnswer();
34                             });
35                 max = Math.max.apply(Math.max, answerValues);
36                 addedItem.setAnswer(max + 1);
37             }
38         }
39     }
40 };
41
42 plugin.documentExtension.textNode.transformations = {
43     breakContent: {
44         impl: function(args) {
45             var node = this,
46                 isSpan = node.parent().getTagName() === 'span',
47                 parentDescribingNodes = [],
48                 newNodes, emptyText;
49             newNodes = node.split({offset: args.offset});
50             newNodes.second.contents()
51                 .filter(function(child) {
52                     return child.object.describesParent;
53                 })
54                 .forEach(function(child) {
55                     //child.detach();
56                     parentDescribingNodes.push(child);
57                     child.detach();
58                 });
59             [newNodes.first, newNodes.second].some(function(newNode) {
60                 if(!(newNode.contents().length)) {
61                     emptyText = newNode.append({text: ''});
62                     return true; // break
63                 }
64             });
65
66             /* <hack>
67             /*
68                 This makes sure that adding a new item to the list in some of the edumed exercises
69                 sets an answer attribute that makes sense (and not just copies it which would create
70                 a duplicate value).
71
72                 This won't be neccessary when/if we introduce canvas element own key event handlers.
73
74                 Alternatively, WLXML elements could implement their own item split methods that we
75                 would delegate to.
76             */
77                 exerciseFix(newNodes);
78             /* </hack> */
79
80             parentDescribingNodes.forEach(function(node) {
81                 newNodes.first.append(node);
82             });
83
84             var parent, newNode;
85
86             var copyNode = function(n) {
87                 var attrs = {};
88                 n.getAttrs().forEach(function(attr) {
89                     attrs[attr.name] = attr.value;
90                 });
91
92                 return node.document.createDocumentNode({
93                     tagName: n.getTagName(),
94                     attrs: attrs
95                 });
96             };
97
98             var move = function(node, to) {
99                 var copy;
100                 if(!node.containsNode(newNodes.second)) {
101                     to.append(node);
102                     return false;
103                 } else {
104                     if(!node.sameNode(newNodes.second)) {
105                         copy = to.append(copyNode(node));
106                         node.contents().some(function(n) {
107                             return move(n, copy);
108                         });
109                     }
110                     return true;
111                 }
112             };
113
114             if(isSpan) {
115                 newNodes.first.parents().some(function(p) {
116                     if(p.getTagName() !== 'span') {
117                         parent = p;
118                         return true;
119                     }
120                 });
121                 newNode = parent.before({tagName: parent.getTagName(), attrs: {'class': parent.getClass()}});
122                 parent.contents().some(function(n) {
123                     return move(n, newNode);
124                 });
125                 if(newNodes.second.contents()[0].getText().length === 0) {
126                     var textNode = newNodes.second.contents()[0];
127                     newNodes.second.detach();
128                     newNodes.second = parent;
129                     emptyText = newNodes.second.append(textNode);
130                 }
131             }
132
133             var newNodeText = newNodes.second.contents()[0].getText();
134             if(newNodes.second.is({tagName: 'header'}) && newNodeText === '') {
135                 newNodes.second = newNodes.second.setTag('div');
136                 newNodes.second.setClass('p');
137             }
138
139             return _.extend(newNodes, {emptyText: emptyText});
140         }
141     },
142     mergeContentUp: function() {
143         /* globals Node */
144         var myPrev = this,
145             base = this,
146             ret;
147
148         if(myPrev.nodeType === Node.TEXT_NODE) {
149             if(myPrev.getIndex() > 0) {
150                 return;
151             }
152             myPrev = base = myPrev.parent();
153         }
154
155         myPrev = myPrev && myPrev.prev();
156
157         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
158             var ptr = this,
159                 next;
160             while(ptr) {
161                 next = ptr.next();
162                 if(!ret) {
163                     ret = myPrev.append(ptr);
164                 } else {
165                     myPrev.append(ptr);
166                 }
167                 
168                 ptr = next;
169             }
170             if(base !== this) {
171                 base.detach();
172             }
173             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
174         }
175     }
176 };
177
178 plugin.documentExtension.documentNode.transformations = {
179     moveUp: function() {
180         var toMerge = this,
181             prev = toMerge.prev();
182
183         var merge = function(from, to) {
184             var toret;
185             from.contents().forEach(function(node, idx) {
186                 var len, ret;
187                 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
188                     len = node.getText().length;
189                 }
190                 ret = to.append(node);
191                 
192                 if(idx === 0 && ret.nodeType === Node.TEXT_NODE) {
193                     toret = {
194                         node: ret,
195                         offset: ret.getText().length - len
196                     };
197                 } else if(!toret) {
198                     toret = {
199                         node: ret.getFirstTextNode(),
200                         offset: 0
201                     };
202                 }
203             });
204             from.detach();
205             return toret;
206         };
207
208         var strategies = [
209             {
210                 applies: function() {
211                     return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
212                 },
213                 run: function() {
214                     var textNode = prev.getLastTextNode(),
215                         txt, prevText, prevTextLen;
216                     if(textNode) {
217                         txt = textNode.getText();
218                         if(txt.length > 1) {
219                             textNode.setText(txt.substr(0, txt.length-1));
220                             return {node: toMerge, offset: 0};
221                         } else {
222                             if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
223                                 prevTextLen = prevText.getText().length;
224                             }
225                             prev.detach();
226                             return {
227                                 node: prevText ? prevText : toMerge,
228                                 offset : prevText ? prevTextLen : 0
229                             };
230                         }
231                     }
232                 }
233             },
234             {
235                 applies: function() {
236                     return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
237                 },
238                 run: function() {
239                     if(prev && (prev.is('p') || prev.is({tagName: 'header'}))) {
240                         return merge(toMerge, prev);
241                     }
242                     if(prev && 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
546 var createLinkFromSelection = function(callback, params) {
547     var doc = params.fragment.document,
548         dialog = Dialog.create({
549             title: gettext('Create link'),
550             executeButtonText: gettext('Apply'),
551             cancelButtonText: gettext('Cancel'),
552             fields: [
553                 {label: gettext('Link'), name: 'href', type: 'input',
554                 prePasteHandler: function(text) {
555                                     return params.fragment.document.getLinkForUrl(text);
556                                 }.bind(this),
557                 description: '<a href="#-" class="attachment-library">' + gettext('attachment library') + '</a>'
558                 }
559             ]
560         }),
561         action = this;
562     
563     dialog.on('execute', function(event) {
564         doc.transaction(function() {
565             var span =  action.params.fragment.startNode.parent().wrapText({
566                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
567                 offsetStart: params.fragment.startOffset,
568                 offsetEnd: params.fragment.endOffset,
569                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
570             }),
571                 doc = params.fragment.document;
572             event.success();
573             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
574         }, {
575             metadata: {
576                 description: action.getState().description,
577                 fragment: params.fragment
578             },
579             success: callback
580         });
581     });
582     dialog.show();
583     $(".attachment-library", dialog.$el).on('click', function() {
584         attachments.select(function(v) {$("input", dialog.$el).val(v);});
585     });
586 };
587
588 var editLink = function(callback, params) {
589     var doc = params.fragment.document,
590         link = params.fragment.node.getParent('link'),
591         dialog = Dialog.create({
592             title: gettext('Edit link'),
593             executeButtonText: gettext('Apply'),
594             cancelButtonText: gettext('Cancel'),
595             fields: [
596                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
597             ]
598         }),
599         action = this;
600     
601     dialog.on('execute', function(event) {
602         doc.transaction(function() {
603             link.setAttr('href', event.formData.href);
604             event.success();
605             return params.fragment;
606         }, {
607             metadata: {
608                 description: action.getState().description,
609                 fragment: params.fragment
610             },
611             success: callback
612         });
613     });
614     dialog.show();
615 };
616
617 var linkAction = {
618     name: 'link',
619     params: {
620         fragment: {type: 'context', name: 'fragment'}
621     },
622     stateDefaults: {
623         label: gettext('link')
624     },
625     getState: function(params) {
626         if(!params.fragment || !params.fragment.isValid()) {
627             return {allowed: false};
628         }
629
630         if(params.fragment instanceof params.fragment.TextRangeFragment) {
631             if(!params.fragment.hasSiblingBoundaries() || params.fragment.startNode.parent().is('link')) {
632                 return {allowed: false};
633             }
634             return {
635                 allowed: true,
636                 description: gettext('Create link from selection'),
637                 execute: createLinkFromSelection
638             };
639         }
640
641         if(params.fragment instanceof params.fragment.CaretFragment) {
642             if(params.fragment.node.isInside('link')) {
643                 return {
644                     allowed: true,
645                     toggled: true,
646                     description: gettext('Edit link'),
647                     execute: editLink
648                 };
649             }
650         }
651         return {allowed: false};
652     }
653 };
654
655
656 var metadataParams = {};
657
658 plugin.actions = [
659     undoRedoAction('undo'),
660     undoRedoAction('redo'),
661     commentAction,
662     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
663     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
664     linkAction,
665     metadataEditor.action(metadataParams)
666 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
667
668
669 plugin.config = function(config) {
670     // templates.actions[0].config(config.templates);
671     templates.actions[0].params.template.options = config.templates;
672     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
673         if(configRow1.key < configRow2.key) {
674             return -1;
675         }
676         if(configRow1.key > configRow2.key) {
677             return 1;
678         }
679         return 0;
680     });
681 };
682
683 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);
684
685 return plugin;
686
687 });