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