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