4c58129a8fe2727401ebdf5c1b379951048bca3f
[fnpeditor.git] / src / editor / plugins / core / core.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals gettext */
5
6 var _ = require('libs/underscore'),
7     templates = require('plugins/core/templates'),
8     footnote = require('plugins/core/footnote'),
9     switchTo = require('plugins/core/switch'),
10     lists = require('plugins/core/lists'),
11     plugin = {name: 'core', actions: [], canvas: {}, documentExtension: {textNode: {}, documentNode: {}}},
12     Dialog = require('views/dialog/dialog'),
13     canvasElements = require('plugins/core/canvasElements'),
14     metadataEditor = require('plugins/core/metadataEditor/metadataEditor'),
15     edumed = require('plugins/core/edumed/edumed'),
16     add_attachments = require('views/attachments/add_attachments');
17
18
19 var exerciseFix = function(newNodes) {
20     var list, exercise, max, addedItem, answerValues;
21     if(newNodes.created.is('item')) {
22         list = newNodes.created.parent();
23         exercise = list.parent();
24         if(exercise && exercise.is('exercise')) {
25             if(exercise.is('exercise.order')) {
26                 answerValues = exercise.object.getItems()
27                             .map(function(item) {
28                                 if(!addedItem && item.node.sameNode(newNodes.created)) {
29                                     addedItem = item;
30                                 }
31                                 return item.getAnswer();
32                             });
33                 max = Math.max.apply(Math.max, answerValues);
34                 addedItem.setAnswer(max + 1);
35             }
36         }
37     }
38 };
39
40 plugin.documentExtension.textNode.transformations = {
41     breakContent: {
42         impl: function(args) {
43             var node = this,
44                 isSpan = node.parent().getTagName() === 'span',
45                 parentDescribingNodes = [],
46                 newNodes, emptyText;
47             newNodes = node.split({offset: args.offset});
48             newNodes.second.contents()
49                 .filter(function(child) {
50                     return child.object.describesParent;
51                 })
52                 .forEach(function(child) {
53                     //child.detach();
54                     parentDescribingNodes.push(child);
55                     child.detach();
56                 });
57             [newNodes.first, newNodes.second].some(function(newNode) {
58                 if(!(newNode.contents().length)) {
59                     emptyText = newNode.append({text: ''});
60                     return true; // break
61                 }
62             });
63
64             /* <hack>
65             /*
66                 This makes sure that adding a new item to the list in some of the edumed exercises
67                 sets an answer attribute that makes sense (and not just copies it which would create
68                 a duplicate value).
69
70                 This won't be neccessary when/if we introduce canvas element own key event handlers.
71
72                 Alternatively, WLXML elements could implement their own item split methods that we
73                 would delegate to.
74             */
75                 exerciseFix(newNodes);
76             /* </hack> */
77
78             parentDescribingNodes.forEach(function(node) {
79                 newNodes.first.append(node);
80             });
81
82             var parent, newNode;
83
84             var copyNode = function(n) {
85                 var attrs = {};
86                 n.getAttrs().forEach(function(attr) {
87                     attrs[attr.name] = attr.value;
88                 });
89
90                 return node.document.createDocumentNode({
91                     tagName: n.getTagName(),
92                     attrs: attrs
93                 });
94             };
95
96             var move = function(node, to) {
97                 var copy;
98                 if(!node.containsNode(newNodes.second)) {
99                     to.append(node);
100                     return false;
101                 } else {
102                     if(!node.sameNode(newNodes.second)) {
103                         copy = to.append(copyNode(node));
104                         node.contents().some(function(n) {
105                             return move(n, copy);
106                         });
107                     }
108                     return true;
109                 }
110             };
111
112             if(isSpan) {
113                 newNodes.first.parents().some(function(p) {
114                     if(p.getTagName() !== 'span') {
115                         parent = p;
116                         return true;
117                     }
118                 });
119                 newNode = parent.before({tagName: parent.getTagName(), attrs: {'class': parent.getClass()}});
120                 parent.contents().some(function(n) {
121                     return move(n, newNode);
122                 });
123                 if(newNodes.second.contents()[0].getText().length === 0) {
124                     var textNode = newNodes.second.contents()[0];
125                     newNodes.second.detach();
126                     newNodes.second = parent;
127                     emptyText = newNodes.second.append(textNode);
128                 }
129             }
130
131             var newNodeText = newNodes.second.contents()[0].getText();
132             if(newNodes.second.is({tagName: 'header'}) && newNodeText === '') {
133                 newNodes.second = newNodes.second.setTag('div');
134                 newNodes.second.setClass('p');
135             }
136
137             return _.extend(newNodes, {emptyText: emptyText});
138         }
139     },
140     mergeContentUp: function() {
141         /* globals Node */
142         var myPrev = this,
143             base = this,
144             ret;
145
146         if(myPrev.nodeType === Node.TEXT_NODE) {
147             if(myPrev.getIndex() > 0) {
148                 return;
149             }
150             myPrev = base = myPrev.parent();
151         }
152
153         myPrev = myPrev && myPrev.prev();
154
155         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
156             var ptr = this,
157                 next;
158             while(ptr) {
159                 next = ptr.next();
160                 if(!ret) {
161                     ret = myPrev.append(ptr);
162                 } else {
163                     myPrev.append(ptr);
164                 }
165                 
166                 ptr = next;
167             }
168             if(base !== this) {
169                 base.detach();
170             }
171             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
172         }
173     }
174 };
175
176 plugin.documentExtension.documentNode.transformations = {
177     moveUp: function() {
178         var toMerge = this,
179             prev = toMerge.prev();
180
181         var merge = function(from, to) {
182             var toret;
183             from.contents().forEach(function(node, idx) {
184                 var len, ret;
185                 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
186                     len = node.getText().length;
187                 }
188                 ret = to.append(node);
189                 
190                 if(idx === 0 && ret.nodeType === Node.TEXT_NODE) {
191                     toret = {
192                         node: ret,
193                         offset: ret.getText().length - len
194                     };
195                 } else if(!toret) {
196                     toret = {
197                         node: ret.getFirstTextNode(),
198                         offset: 0
199                     };
200                 }
201             });
202             from.detach();
203             return toret;
204         };
205
206         var strategies = [
207             {
208                 applies: function() {
209                     return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
210                 },
211                 run: function() {
212                     var textNode = prev.getLastTextNode(),
213                         txt, prevText, prevTextLen;
214                     if(textNode) {
215                         txt = textNode.getText();
216                         if(txt.length > 1) {
217                             textNode.setText(txt.substr(0, txt.length-1));
218                             return {node: toMerge, offset: 0};
219                         } else {
220                             if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
221                                 prevTextLen = prevText.getText().length;
222                             }
223                             prev.detach();
224                             return {
225                                 node: prevText ? prevText : toMerge,
226                                 offset : prevText ? prevTextLen : 0
227                             };
228                         }
229                     }
230                 }
231             },
232             {
233                 applies: function() {
234                     return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
235                 },
236                 run: function() {
237                     if(prev && (prev.is('p') || prev.is({tagName: 'header'}))) {
238                         return merge(toMerge, prev);
239                     }
240                     if(prev && prev.is('list')) {
241                         var items = prev.contents().filter(function(n) { return n.is('item');});
242                         return merge(toMerge, items[items.length-1]);
243                     }
244                 }
245             },
246             {
247                 applies: function() {
248                     return toMerge.is({tagName: 'span'});
249                 },
250                 run: function() {
251                     /* globals Node */
252                     var toret = {node: toMerge.contents()[0] , offset: 0},
253                         txt, txtNode, parent;
254                     if(!prev) {
255                         toMerge.parents().some(function(p) {
256                             if(p.is({tagName: 'span'})) {
257                                 parent = prev = p;
258                             } else {
259                                 if(!parent) {
260                                     parent = p;
261                                 }
262                                 prev = prev && prev.prev();
263                                 return true;
264                             }
265                         });
266                     }
267                     if(!prev) {
268                         return parent.moveUp();
269                     }
270                     else if(prev.nodeType === Node.TEXT_NODE && (txt = prev.getText())) {
271                         prev.setText(txt.substr(0, txt.length-1));
272                         return toret;
273                     } else if(prev.is({tagName: 'span'})) {
274                         if((txtNode = prev.getLastTextNode())) {
275                             txt = txtNode.getText();
276                             if(txt.length > 1) {
277                                 txtNode.setText(txt.substr(0, txt.length-1));
278                             } else {
279                                 if(txtNode.parent().contents().length === 1) {
280                                     txtNode.parent().detach();
281                                 } else {
282                                     txtNode.detach();
283                                 }
284
285                             }
286                             return toret;
287                         }
288                     }
289
290                 }
291             },
292             {
293                 applies: function() {
294                     return toMerge.is({tagName: 'header'});
295                 },
296                 run: function() {
297                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
298                         return merge(toMerge, prev);
299                     }
300                 }
301             },
302             {
303                 applies: function() {
304                     return toMerge.is('item');
305                 },
306                 run: function() {
307                     var list;
308                     if(prev && prev.is('item')) {
309                         return merge(toMerge, prev);
310                     } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
311                         list.before(toMerge);
312                         toMerge.setClass('p');
313                         if(!list.contents().length) {
314                             list.detach();
315                         }
316                         return {node: toMerge.contents()[0], offset:0};
317                     }
318                 }
319             }
320         ];
321
322         var toret;
323         strategies.some(function(strategy) {
324             if(strategy.applies()) {
325                 toret = strategy.run();
326                 return true;
327             }
328         });
329         return toret;
330     },
331     insertNewNode: function () {
332         var node = this;
333         var newElement = this.document.createDocumentNode({tagName: 'div', attrs: {class: 'p'}});
334         node.after(newElement);
335         newElement.append({text: ''});
336         return newElement;
337     }
338 };
339
340 var undoRedoAction = function(dir) {
341     return {
342         name: dir,
343         params: {
344             document: {type: 'context', name: 'document'},
345         },
346         stateDefaults: {
347             label: dir === 'undo' ? '<-' : '->',
348             icon: 'share-alt',
349             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
350             execute: function(callback, params) {
351                 var metadata = _.last(params.document[dir+'Stack']).metadata,
352                     fragment = metadata && metadata.fragment;
353                 params.document[dir]();
354                 if(fragment) {
355                     if(!fragment.isValid()) {
356                         fragment.restoreFromPaths();
357                     }
358                     if(fragment.isValid()) {
359                         callback(fragment);
360                     }
361                 }
362                 callback();
363             },
364         },
365         getState: function(params) {
366             var allowed = params.document && !!(params.document[dir+'Stack'].length),
367                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
368                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
369             if(allowed) {
370                 var metadata = _.last(params.document[dir+'Stack']).metadata;
371                 if(metadata) {
372                     desc += ': ' + (metadata.description || gettext('unknown operation'));
373                 }
374             }
375             return {
376                 allowed: allowed,
377                 description: allowed ? desc : descEmpty
378             };
379         }
380     };
381 };
382
383 var pad = function(number) {
384     if(number < 10) {
385         number = '0' + number;
386     }
387     return number;
388 };
389
390 var commentAction = {
391     name: 'comment',
392     params: {
393         fragment: {type: 'context', name: 'fragment'}
394     },
395     stateDefaults: {
396         icon: 'comment',
397         execute: function(callback, params, editor) {
398             /* globals Node */
399             var node = params.fragment.node,
400                 action = this;
401             if(node.nodeType === Node.TEXT_NODE) {
402                 node = node.parent();
403             }
404             node.document.transaction(function() {
405                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
406                 comment.append({text:''});
407                 var user = editor.getUser(), creator;
408                 if(user) {
409                     creator = user.name;
410                     if(user.email) {
411                         creator += ' (' + user.email + ')';
412                     }
413                 } else {
414                     creator = 'anonymous';
415                 }
416
417                 var currentDate = new Date(),
418                     dt = pad(currentDate.getDate()) + '-' +
419                                 pad((currentDate.getMonth() + 1))  + '-' +
420                                 pad(currentDate.getFullYear()) + ' ' +
421                                 pad(currentDate.getHours()) + ':' +
422                                 pad(currentDate.getMinutes()) + ':' +
423                                 pad(currentDate.getSeconds());
424
425                 var metadata = comment.getMetadata();
426                 metadata.add({key: 'creator', value: creator});
427                 metadata.add({key: 'date', value: dt});
428             }, {
429                 metadata: {
430                     description: action.getState().description
431                 },
432                 success: callback
433             });
434         },
435     },
436     getState: function(params) {
437         var state = {
438             allowed: params.fragment && params.fragment.isValid() &&
439                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
440         };
441         if(state.allowed) {
442             state.description = gettext('Insert comment');
443         }
444         return state;
445     }
446 };
447
448
449 var createWrapTextAction = function(createParams) {
450     return {
451         name: createParams.name,
452         params: {
453             fragment: {type: 'context', name: 'fragment'},
454         },
455         getState: function(params) {
456             var state = {
457                     label: this.config.label
458                 },
459                 parent;
460             
461             if(!params.fragment || !params.fragment.isValid()) {
462                 return _.extend(state, {allowed: false});
463             }
464
465             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
466                 return _.extend(state, {
467                     allowed: true,
468                     toggled: true,
469                     description: createParams.unwrapDescription,
470                     execute: function(callback, params) {
471                         var node = params.fragment.node,
472                             doc = node.document,
473                             toRemove = node.getParent(createParams.klass),
474                             prefLen = 0;
475
476                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
477                             prefLen = toRemove.prev().getText().length;
478                         }
479
480                         doc.transaction(function() {
481                             var ret = toRemove.unwrapContent(),
482                                 newFragment = params.fragment;
483                             if(!newFragment.isValid()) {
484                                 newFragment =  doc.createFragment(doc.CaretFragment, {
485                                     node: ret.element1,
486                                     offset: prefLen + params.fragment.offset
487                                 });
488                             }
489                             return newFragment;
490                         }, {
491                             metadata: {
492                                 description: createParams.unwrapDescription,
493                                 fragment: params.fragment
494                             },
495                             success: callback
496                         });
497                     }
498                 });
499             }
500
501             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundaries()) {
502                 parent = params.fragment.startNode.parent();
503                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
504                     return _.extend(state, {allowed: false});
505                 }
506
507                 return _.extend(state, {
508                     allowed: true,
509                     description: createParams.wrapDescription,
510                     execute: function(callback, params) {
511                         params.fragment.document.transaction(function() {
512                             var parent = params.fragment.startNode.parent(),
513                                 doc = params.fragment.document,
514                                 wrapper, lastTextNode;
515                             
516                             wrapper = parent.wrapText({
517                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
518                                 offsetStart: params.fragment.startOffset,
519                                 offsetEnd: params.fragment.endOffset,
520                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
521                             });
522                                 
523                             lastTextNode = wrapper.getLastTextNode();
524                             if(lastTextNode) {
525                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
526                             }
527                         }, {
528                             metadata: {
529                                 description: createParams.wrapDescription,
530                                 fragment: params.fragment
531                             },
532                             success: callback
533                         });
534                     }
535                 });
536             }
537             return _.extend(state, {allowed: false});
538         }
539     };
540 };
541
542
543 var createLinkFromSelection = function(callback, params) {
544     var fragment = params.fragment,
545         doc = fragment.document,
546         text = fragment.startNode.nativeNode.data.substring(fragment.startOffset, fragment.endOffset),
547         url;
548     if (text.indexOf('//') >= 0 && text.indexOf(' ') < 0) {
549         url = text;
550     } else if (text.substr(0, 4) === 'www.' && text.indexOF(' ') < 0) {
551         url = 'http://' + text;
552     }
553     var dialog = Dialog.create({
554             title: gettext('Create link'),
555             executeButtonText: gettext('Apply'),
556             cancelButtonText: gettext('Cancel'),
557             fields: [
558                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: url || '',
559                 prePasteHandler: function(text) {
560                                     return params.fragment.document.getLinkForUrl(text);
561                                 }.bind(this)
562                 }
563             ]
564         }),
565         action = this;
566     
567     dialog.on('execute', function(event) {
568         doc.transaction(function() {
569             var span =  action.params.fragment.startNode.parent().wrapText({
570                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
571                 offsetStart: params.fragment.startOffset,
572                 offsetEnd: params.fragment.endOffset,
573                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
574             }),
575                 doc = params.fragment.document;
576             event.success();
577             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
578         }, {
579             metadata: {
580                 description: action.getState().description,
581                 fragment: params.fragment
582             },
583             success: callback
584         });
585     });
586     dialog.show();
587     add_attachments(dialog);
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 var metadataParams = {};
658
659 plugin.actions = [
660     undoRedoAction('undo'),
661     undoRedoAction('redo'),
662     commentAction,
663     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
664     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
665     linkAction,
666     metadataEditor.action(metadataParams)
667 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
668
669
670 plugin.config = function(config) {
671     // templates.actions[0].config(config.templates);
672     templates.actions[0].params.template.options = config.templates;
673     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
674         if(configRow1.key < configRow2.key) {
675             return -1;
676         }
677         if(configRow1.key > configRow2.key) {
678             return 1;
679         }
680         return 0;
681     });
682 };
683
684 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);
685
686 return plugin;
687
688 });