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